diff --git a/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COBilling.js b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COBilling.js new file mode 100644 index 000000000..7cf14bea6 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COBilling.js @@ -0,0 +1,849 @@ +'use strict'; + +/** + * Controller for the billing logic. It is used by both the single shipping and the multishipping + * functionality and is responsible for payment method selection and entering a billing address. + * + * @module controllers/COBilling + */ + +/* API Includes */ +var GiftCertificate = require('dw/order/GiftCertificate'); +var GiftCertificateMgr = require('dw/order/GiftCertificateMgr'); +var GiftCertificateStatusCodes = require('dw/order/GiftCertificateStatusCodes'); +var PaymentInstrument = require('dw/order/PaymentInstrument'); +var PaymentMgr = require('dw/order/PaymentMgr'); +var ProductListMgr = require('dw/customer/ProductListMgr'); +var Resource = require('dw/web/Resource'); +var Status = require('dw/system/Status'); +var StringUtils = require('dw/util/StringUtils'); +var Transaction = require('dw/system/Transaction'); +var URLUtils = require('dw/web/URLUtils'); +var Countries = require('app_storefront_core/cartridge/scripts/util/Countries'); + +/* Script Modules */ +var app = require('~/cartridge/scripts/app'); +var guard = require('~/cartridge/scripts/guard'); +// ### Custom Adyen cartridge start ### +var AdyenController = require("int_adyen_controllers/cartridge/controllers/Adyen"); +var AdyenHelper = require("int_adyen_overlay/cartridge/scripts/util/adyenHelper"); +var AdyenConfigs = require("int_adyen_overlay/cartridge/scripts/util/adyenConfigs"); +var constants = require("*/cartridge/adyenConstants/constants"); +// ### Custom Adyen cartridge end ### +var BasketMgr = require('dw/order/BasketMgr'); +var OrderMgr = require('dw/order/OrderMgr'); + +/** + * Initializes the address form. If the customer chose "use as billing + * address" option on the single shipping page the form is prepopulated with the shipping + * address, otherwise it prepopulates with the billing address that was already set. + * If neither address is available, it prepopulates with the default address of the authenticated customer. + */ +function initAddressForm(cart) { + if (app.getForm('singleshipping').object.shippingAddress.useAsBillingAddress.value === true) { + app.getForm('billing').object.billingAddress.addressFields.firstName.value = app.getForm('singleshipping').object.shippingAddress.addressFields.firstName.value; + app.getForm('billing').object.billingAddress.addressFields.lastName.value = app.getForm('singleshipping').object.shippingAddress.addressFields.lastName.value; + app.getForm('billing').object.billingAddress.addressFields.address1.value = app.getForm('singleshipping').object.shippingAddress.addressFields.address1.value; + app.getForm('billing').object.billingAddress.addressFields.address2.value = app.getForm('singleshipping').object.shippingAddress.addressFields.address2.value; + app.getForm('billing').object.billingAddress.addressFields.city.value = app.getForm('singleshipping').object.shippingAddress.addressFields.city.value; + app.getForm('billing').object.billingAddress.addressFields.postal.value = app.getForm('singleshipping').object.shippingAddress.addressFields.postal.value; + app.getForm('billing').object.billingAddress.addressFields.phone.value = app.getForm('singleshipping').object.shippingAddress.addressFields.phone.value; + app.getForm('billing').object.billingAddress.addressFields.states.state.value = app.getForm('singleshipping').object.shippingAddress.addressFields.states.state.value; + app.getForm('billing').object.billingAddress.addressFields.country.value = app.getForm('singleshipping').object.shippingAddress.addressFields.country.value; + app.getForm('billing').object.billingAddress.addressFields.phone.value = app.getForm('singleshipping').object.shippingAddress.addressFields.phone.value; + } else if (cart.getBillingAddress() !== null) { + app.getForm('billing.billingAddress.addressFields').copyFrom(cart.getBillingAddress()); + app.getForm('billing.billingAddress.addressFields.states').copyFrom(cart.getBillingAddress()); + } else if (customer.authenticated && customer.profile.addressBook.preferredAddress !== null) { + app.getForm('billing.billingAddress.addressFields').copyFrom(customer.profile.addressBook.preferredAddress); + app.getForm('billing.billingAddress.addressFields.states').copyFrom(customer.profile.addressBook.preferredAddress); + } +} + +/** + * Initializes the email address form field. If there is already a customer + * email set at the basket, that email address is used. If the + * current customer is authenticated the email address of the customer's profile + * is used. + */ +function initEmailAddress(cart) { + if (cart.getCustomerEmail() !== null) { + app.getForm('billing').object.billingAddress.email.emailAddress.value = cart.getCustomerEmail(); + } else if (customer.authenticated && customer.profile.email !== null) { + app.getForm('billing').object.billingAddress.email.emailAddress.value = customer.profile.email; + } +} + +/** + * Updates data for the billing page and renders it. + * If payment method is set to gift certificate, gets the gift certificate code from the form. + * Updates the page metadata. Gets a view and adds any passed parameters to it. Sets the Basket and ContinueURL properties. + * Renders the checkout/billing/billing template. + * @param {module:models/CartModel~CartModel} cart - A CartModel wrapping the current Basket. + * @param {object} params - (optional) if passed, added to view properties so they can be accessed in the template. + */ +// ### Custom Adyen cartridge start ### +function returnToForm(cart, params) { + var pageMeta = require('~/cartridge/scripts/meta'); + + // if the payment method is set to gift certificate get the gift certificate code from the form + if (!empty(cart.getPaymentInstrument()) && cart.getPaymentInstrument().getPaymentMethod() === PaymentInstrument.METHOD_GIFT_CERTIFICATE) { + app.getForm('billing').copyFrom({ + giftCertCode: cart.getPaymentInstrument().getGiftCertificateCode() + }); + } + pageMeta.update({ + pageTitle: Resource.msg('billing.meta.pagetitle', 'checkout', 'SiteGenesis Checkout') + }); + if (params) { + app.getView(require('~/cartridge/scripts/object').extend(params, { + Basket: cart.object, + AdyenHelper: AdyenHelper, + ContinueURL: URLUtils.https('COBilling-Billing') + })).render('checkout/billing/billing'); + } else { + app.getView({ + Basket: cart.object, + AdyenHelper: AdyenHelper, + ContinueURL: URLUtils.https('COBilling-Billing') + }).render('checkout/billing/billing'); + } +} +// ### Custom Adyen cartridge end ### + +/** + * Updates cart calculation and page information and renders the billing page. + * @transactional + * @param {module:models/CartModel~CartModel} cart - A CartModel wrapping the current Basket. + * @param {object} params - (optional) if passed, added to view properties so they can be accessed in the template. + */ +function start(cart, params) { + app.getController('COShipping').PrepareShipments(); + Transaction.wrap(function () { + cart.calculate(); + }); + var pageMeta = require('~/cartridge/scripts/meta'); + pageMeta.update({ + pageTitle: Resource.msg('billing.meta.pagetitle', 'checkout', 'SiteGenesis Checkout') + }); + returnToForm(cart, params); +} + +/** + * Initializes the credit card list by determining the saved customer payment methods for the current locale. + * @param {module:models/CartModel~CartModel} cart - A CartModel wrapping the current Basket. + * @return {object} JSON object with members ApplicablePaymentMethods and ApplicableCreditCards. + */ +function initCreditCardList(cart) { + var paymentAmount = cart.getNonGiftCertificateAmount(); + var countryCode; + var applicablePaymentMethods; + var applicablePaymentCards; + var applicableCreditCards; + countryCode = Countries.getCurrent({ + CurrentRequest: { + locale: request.locale + } + }).countryCode; + applicablePaymentMethods = PaymentMgr.getApplicablePaymentMethods(customer, countryCode, paymentAmount.value); + applicablePaymentCards = PaymentMgr.getPaymentMethod(PaymentInstrument.METHOD_CREDIT_CARD).getApplicablePaymentCards(customer, countryCode, paymentAmount.value); + app.getForm('billing').object.paymentMethods.creditCard.type.setOptions(applicablePaymentCards.iterator()); + applicableCreditCards = null; + if (customer.authenticated) { + var profile = app.getModel('Profile').get(); + if (profile) { + applicableCreditCards = profile.validateWalletPaymentInstruments(countryCode, paymentAmount.getValue()).ValidPaymentInstruments; + } + } + return { + ApplicablePaymentMethods: applicablePaymentMethods, + ApplicableCreditCards: applicableCreditCards + }; +} + +/** + * Starting point for billing. After a successful shipping setup, both COShipping + * and COShippingMultiple call this function. + */ +// ### Custom Adyen cartridge start ### +function publicStart() { + var cart = app.getModel('Cart').get(); + if (cart) { + // Initializes all forms of the billing page including: - address form - email address - coupon form + initAddressForm(cart); + initEmailAddress(cart); + + // Get the Saved Cards from Adyen to get latest saved cards + if (customer.authenticated) { + require('int_adyen_overlay/cartridge/scripts/updateSavedCards').updateSavedCards({ + CurrentCustomer: customer + }); + } + var creditCardList = initCreditCardList(cart); + var applicablePaymentMethods = creditCardList.ApplicablePaymentMethods; + var billingForm = app.getForm('billing').object; + var paymentMethods = billingForm.paymentMethods; + if (paymentMethods.valid) { + paymentMethods.selectedPaymentMethodID.setOptions(applicablePaymentMethods.iterator()); + } else { + paymentMethods.clearFormElement(); + } + app.getForm('billing.couponCode').clear(); + app.getForm('billing.giftCertCode').clear(); + var AdyenSessionsResponse = AdyenController.Sessions(customer); + + // var AdyenPosTerminals = AdyenController.GetTerminals(); + //TODO fix terminals + start(cart, { + ApplicableCreditCards: creditCardList.ApplicableCreditCards, + AdyenSessionsResponse: AdyenSessionsResponse + }); + } else { + app.getController('Cart').Show(); + } +} +// ### Custom Adyen cartridge end ### + +/** + * Adjusts gift certificate redemptions after applying coupon(s), because this changes the order total. + * Removes and then adds currently added gift certificates to reflect order total changes. + */ +function adjustGiftCertificates() { + var i, j, cart, gcIdList, gcID, gc; + cart = app.getModel('Cart').get(); + if (cart) { + gcIdList = cart.getGiftCertIdList(); + Transaction.wrap(function () { + for (i = 0; i < gcIdList.length; i += 1) { + cart.removeGiftCertificatePaymentInstrument(gcIdList[i]); + } + gcID = null; + for (j = 0; j < gcIdList.length; j += 1) { + gcID = gcIdList[j]; + gc = GiftCertificateMgr.getGiftCertificateByCode(gcID); + if (gc && + // make sure exists + gc.isEnabled() && + // make sure it is enabled + gc.getStatus() !== GiftCertificate.STATUS_PENDING && + // make sure it is available for use + gc.getStatus() !== GiftCertificate.STATUS_REDEEMED && + // make sure it has not been fully redeemed + gc.balance.currencyCode === cart.getCurrencyCode()) { + // make sure the GC is in the right currency + cart.createGiftCertificatePaymentInstrument(gc); + } + } + }); + } +} + +/** + * Used to adjust gift certificate totals, update page metadata, and render the billing page. + * This function is called whenever a billing form action is handled. + * @see {@link module:controllers/COBilling~returnToForm|returnToForm} + * @see {@link module:controllers/COBilling~adjustGiftCertificates|adjustGiftCertificates} + * @see {@link module:controllers/COBilling~billing|billing} + */ +function handleCoupon() { + var CouponError; + // @FIXME what is that used for? + if (empty(CouponError)) { + /* + * Adjust gift certificate redemptions as after applying coupon(s), + * order total is changed. AdjustGiftCertificate pipeline removes and + * then adds currently added gift certificates to reflect order total + * changes. + */ + adjustGiftCertificates(); + } + returnToForm(app.getModel('Cart').get()); +} + +/** + * Redeems a gift certificate. If the gift certificate was not successfully + * redeemed, the form field is invalidated with the appropriate error message. + * If the gift certificate was redeemed, the form gets cleared. This function + * is called by an Ajax request and generates a JSON response. + * @param {String} giftCertCode - Gift certificate code entered into the giftCertCode field in the billing form. + * @returns {object} JSON object containing the status of the gift certificate. + */ +function redeemGiftCertificate(giftCertCode) { + var cart, gc, newGCPaymentInstrument, gcPaymentInstrument, status, result; + cart = app.getModel('Cart').get(); + if (cart) { + // fetch the gift certificate + gc = GiftCertificateMgr.getGiftCertificateByCode(giftCertCode); + if (!gc) { + // make sure exists + result = new Status(Status.ERROR, GiftCertificateStatusCodes.GIFTCERTIFICATE_NOT_FOUND); + } else if (!gc.isEnabled()) { + // make sure it is enabled + result = new Status(Status.ERROR, GiftCertificateStatusCodes.GIFTCERTIFICATE_DISABLED); + } else if (gc.getStatus() === GiftCertificate.STATUS_PENDING) { + // make sure it is available for use + result = new Status(Status.ERROR, GiftCertificateStatusCodes.GIFTCERTIFICATE_PENDING); + } else if (gc.getStatus() === GiftCertificate.STATUS_REDEEMED) { + // make sure it has not been fully redeemed + result = new Status(Status.ERROR, GiftCertificateStatusCodes.GIFTCERTIFICATE_INSUFFICIENT_BALANCE); + } else if (gc.balance.currencyCode !== cart.getCurrencyCode()) { + // make sure the GC is in the right currency + result = new Status(Status.ERROR, GiftCertificateStatusCodes.GIFTCERTIFICATE_CURRENCY_MISMATCH); + } else { + newGCPaymentInstrument = Transaction.wrap(function () { + gcPaymentInstrument = cart.createGiftCertificatePaymentInstrument(gc); + cart.calculate(); + return gcPaymentInstrument; + }); + status = new Status(Status.OK); + status.addDetail('NewGCPaymentInstrument', newGCPaymentInstrument); + result = status; + } + } else { + result = new Status(Status.ERROR, 'BASKET_NOT_FOUND'); + } + return result; +} + +/** + * Updates credit card information from the httpParameterMap and determines if there is a currently selected credit card. + * If a credit card is selected, it adds the the credit card number to the billing form. Otherwise, the {@link module:controllers/COBilling~publicStart|publicStart} method is called. + * In either case, it will initialize the credit card list in the billing form and call the {@link module:controllers/COBilling~start|start} function. + */ +function updateCreditCardSelection() { + var cart, applicableCreditCards, UUID, selectedCreditCard, instrumentsIter, creditCardInstrument; + cart = app.getModel('Cart').get(); + applicableCreditCards = initCreditCardList(cart).ApplicableCreditCards; + UUID = request.httpParameterMap.creditCardUUID.value || request.httpParameterMap.dwfrm_billing_paymentMethods_creditCardList.stringValue; + selectedCreditCard = null; + if (UUID && applicableCreditCards && !applicableCreditCards.empty) { + // find credit card in payment instruments + instrumentsIter = applicableCreditCards.iterator(); + while (instrumentsIter.hasNext()) { + creditCardInstrument = instrumentsIter.next(); + if (UUID.equals(creditCardInstrument.UUID)) { + selectedCreditCard = creditCardInstrument; + } + } + if (selectedCreditCard) { + app.getForm('billing').object.paymentMethods.creditCard.number.value = selectedCreditCard.creditCardNumber; + } else { + publicStart(); + } + } else { + publicStart(); + } + app.getForm('billing.paymentMethods.creditCard').copyFrom(selectedCreditCard); + initCreditCardList(cart); + start(cart); +} + +/** + * Clears the form element for the currently selected payment method and removes the other payment methods. + * + * @return {Boolean} Returns true if payment is successfully reset. Returns false if the currently selected payment + * method is bml and the ssn cannot be validated. + */ +function resetPaymentForms() { + var cart = app.getModel('Cart').get(); + var status = Transaction.wrap(function () { + if (app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value.equals('PayPal')) { + app.getForm('billing').object.paymentMethods.creditCard.clearFormElement(); + app.getForm('billing').object.paymentMethods.bml.clearFormElement(); + cart.removePaymentInstruments(cart.getPaymentInstruments(PaymentInstrument.METHOD_CREDIT_CARD)); + cart.removePaymentInstruments(cart.getPaymentInstruments(PaymentInstrument.METHOD_BML)); + } else if (app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value.equals(PaymentInstrument.METHOD_CREDIT_CARD)) { + app.getForm('billing').object.paymentMethods.bml.clearFormElement(); + cart.removePaymentInstruments(cart.getPaymentInstruments(PaymentInstrument.METHOD_BML)); + cart.removePaymentInstruments(cart.getPaymentInstruments('PayPal')); + } else if (app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value.equals(PaymentInstrument.METHOD_BML)) { + app.getForm('billing').object.paymentMethods.creditCard.clearFormElement(); + if (!app.getForm('billing').object.paymentMethods.bml.ssn.valid) { + return false; + } + cart.removePaymentInstruments(cart.getPaymentInstruments(PaymentInstrument.METHOD_CREDIT_CARD)); + cart.removePaymentInstruments(cart.getPaymentInstruments('PayPal')); + } + return true; + }); + return status; +} + +/** + * Validates the billing form. + * @returns {boolean} Returns true if the billing address is valid or no payment is needed. Returns false if the billing form is invalid. + */ +function validateBilling() { + if (!app.getForm('billing').object.billingAddress.valid) { + return false; + } + if (!empty(request.httpParameterMap.noPaymentNeeded.value)) { + return true; + } + if (!empty(app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value) && app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value.equals(PaymentInstrument.METHOD_CREDIT_CARD)) { + if (!app.getForm('billing').object.valid) { + return false; + } + } + return true; +} + +/** + * Handles the selection of the payment method and performs payment method-specific + * validation and verification on the entered form fields. If the + * order total is 0 (if the user has product promotions) then we do not + * need a valid payment method. + */ +function handlePaymentSelection(cart) { + var result; + if (empty(app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value)) { + if (cart.getTotalGrossPrice() > 0) { + result = { + error: true + }; + } else { + result = { + ok: true + }; + } + } + + // skip the payment handling if the whole payment was made using gift cert + if (app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value.equals(PaymentInstrument.METHOD_GIFT_CERTIFICATE)) { + result = { + ok: true + }; + } + if (empty(PaymentMgr.getPaymentMethod(app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value).paymentProcessor)) { + result = { + error: true, + MissingPaymentProcessor: true + }; + } + if (!result) { + result = app.getModel('PaymentProcessor').handle(cart.object, app.getForm('billing').object.paymentMethods.selectedPaymentMethodID.value); + } + return result; +} + +/** + * Gets or creates a billing address and copies it to the billingaddress form. Also sets the customer email address + * to the value in the billingAddress form. + * @transaction + * @param {module:models/CartModel~CartModel} cart - A CartModel wrapping the current Basket. + * @returns {boolean} true + */ +function handleBillingAddress(cart) { + var billingAddress = cart.getBillingAddress(); + Transaction.wrap(function () { + if (!billingAddress) { + billingAddress = cart.createBillingAddress(); + } + app.getForm('billing.billingAddress.addressFields').copyTo(billingAddress); + app.getForm('billing.billingAddress.addressFields.states').copyTo(billingAddress); + cart.setCustomerEmail(app.getForm('billing').object.billingAddress.email.emailAddress.value); + }); + return true; +} + +/** + * Checks if there is currently a cart and if one exists, gets the customer address from the httpParameterMap and saves it to the customer address book. + * Initializes the list of credit cards and calls the {@link module:controllers/COBilling~start|start} function. + * If a cart does not already exist, calls the {@link module:controllers/Cart~Show|Cart controller Show function}. + */ +function updateAddressDetails() { + var cart, address, billingAddress; + cart = app.getModel('Cart').get(); + if (cart) { + address = customer.getAddressBook().getAddress(empty(request.httpParameterMap.addressID.value) ? request.httpParameterMap.dwfrm_billing_addressList.value : request.httpParameterMap.addressID.value); + app.getForm('billing.billingAddress.addressFields').copyFrom(address); + app.getForm('billing.billingAddress.addressFields.states').copyFrom(address); + billingAddress = cart.getBillingAddress(); + app.getForm('billing.billingAddress.addressFields').copyTo(billingAddress); + initCreditCardList(cart); + start(cart); + } else { + //@FIXME redirect + app.getController('Cart').Show(); + } +} + +/** + * Form handler for the billing form. Handles the following actions: + * - __applyCoupon__ - gets the coupon to add from the httpParameterMap couponCode property and calls {@link module:controllers/COBilling~handleCoupon|handleCoupon} + * - __creditCardSelect__ - calls the {@link module:controllers/COBilling~updateCreditCardSelection|updateCreditCardSelection} function. + * - __paymentSelect__ - calls the {@link module:controllers/COBilling~publicStart|publicStart} function. + * - __redeemGiftCert__ - redeems the gift certificate entered into the billing form and returns to the cart. + * - __save__ - validates payment and address information and handles any errors. If the billing form is valid, + * saves the billing address to the customer profile, sets a flag to indicate the billing step is successful, and calls + * the {@link module:controllers/COSummary~start|COSummary controller Start function}. + * - __selectAddress__ - calls the {@link module:controllers/COBilling~updateAddressDetails|updateAddressDetails} function. + */ +// ### Custom Adyen cartridge start ### +function billing(data) { + // restore cart and redirect to billing stage if successful + if (session.privacy.currentOrderNumber && session.privacy.currentOrderToken) { + var order = OrderMgr.getOrder(session.privacy.currentOrderNumber, session.privacy.currentOrderToken); + + // Clear cache so the order restore will only be attmpted once per order + session.privacy.currentOrderNumber = null; + session.privacy.currentOrderToken = null; + Transaction.wrap(function () { + OrderMgr.failOrder(order, true); + }); + publicStart(); + return; + } + if (!validateBilling()) { + var responseUtils = require('~/cartridge/scripts/util/Response'); + responseUtils.renderJSON({ + fieldErrors: true + }); + } + var paymentInformation = app.getForm('adyPaydata'); + if (paymentInformation.get("paymentFromComponentStateData").value()) { + AdyenController.ShowConfirmationPaymentFromComponent(); + return; + } + app.getForm('billing').handleAction({ + applyCoupon: function () { + var couponCode = request.httpParameterMap.couponCode.stringValue || request.httpParameterMap.dwfrm_billing_couponCode.stringValue; + + // TODO what happened to this start node? + app.getController('Cart').AddCoupon(couponCode); + handleCoupon(); + return; + }, + creditCardSelect: function () { + updateCreditCardSelection(); + return; + }, + paymentSelect: function () { + // ToDo - pass parameter ? + publicStart(); + return; + }, + redeemGiftCert: function () { + var status = redeemGiftCertificate(app.getForm('billing').object.giftCertCode.htmlValue); + if (!status.isError()) { + returnToForm(app.getModel('Cart').get(), { + NewGCPaymentInstrument: status.getDetail('NewGCPaymentInstrument') + }); + } else { + returnToForm(app.getModel('Cart').get()); + } + return; + }, + save: function () { + Transaction.wrap(function () { + var cart = app.getModel('Cart').get(); + if (!resetPaymentForms() || !validateBilling() || !handleBillingAddress(cart) || + // Performs validation steps, based upon the entered billing address + // and address options. + handlePaymentSelection(cart).error) { + // Performs payment method specific checks, such as credit card verification. + returnToForm(cart); + } else { + if (customer.authenticated && app.getForm('billing').object.billingAddress.addToAddressBook.value) { + app.getModel('Profile').get(customer.profile).addAddressToAddressBook(cart.getBillingAddress()); + } + // Mark step as fulfilled + app.getForm('billing').object.fulfilled.value = true; + if (!paymentInformation.get("paymentFromComponentStateData").value()) { + // A successful billing page will jump to the next checkout step. + app.getController('COSummary').Start(); + } + return; + } + }); + }, + selectAddress: function () { + updateAddressDetails(); + return; + } + }); +} +// ### Custom Adyen cartridge end ### + +/** +* Gets the gift certificate code from the httpParameterMap and redeems it. For an ajax call, renders an empty JSON object. +* Otherwise, renders a JSON object with information about the gift certificate code and the success and status of the redemption. +*/ +function redeemGiftCertificateJson() { + var giftCertCode, giftCertStatus; + giftCertCode = request.httpParameterMap.giftCertCode.stringValue; + giftCertStatus = redeemGiftCertificate(giftCertCode); + let responseUtils = require('~/cartridge/scripts/util/Response'); + if (request.httpParameterMap.format.stringValue !== 'ajax') { + // @FIXME we could also build an ajax guard? + responseUtils.renderJSON({}); + } else { + responseUtils.renderJSON({ + status: giftCertStatus.code, + success: !giftCertStatus.error, + message: Resource.msgf('billing.' + giftCertStatus.code, 'checkout', null, giftCertCode), + code: giftCertCode + }); + } +} + +/** + * Removes gift certificate from the basket payment instruments and + * generates a JSON response with a status. This function is called by an Ajax + * request. + */ +function removeGiftCertificate() { + if (!empty(request.httpParameterMap.giftCertificateID.stringValue)) { + var cart = app.getModel('Cart').get(); + Transaction.wrap(function () { + cart.removeGiftCertificatePaymentInstrument(request.httpParameterMap.giftCertificateID.stringValue); + cart.calculate(); + }); + } + publicStart(); +} + +/** + * Updates the order totals and recalculates the basket after a coupon code is applied. + * Renders the checkout/minisummary template, which includes the mini cart order totals and shipment summary. + */ +function updateSummary() { + var cart = app.getModel('Cart').get(); + Transaction.wrap(function () { + cart.calculate(); + }); + app.getView({ + checkoutstep: 4, + Basket: cart.object + }).render('checkout/minisummary'); +} + +/** + * Renders a form dialog to edit an address. The dialog is supposed to be opened + * by an Ajax request and ends in templates, which trigger a certain JavaScript + * event. The calling page of this dialog is responsible for handling these + * events. + */ +function editAddress() { + app.getForm('billing').objectaddress.clearFormElement(); + var address = customer.getAddressBook().getAddress(request.httpParameterMap.addressID.stringValue); + if (address) { + app.getForm('billinaddress').copyFrom(address); + app.getForm('billingaggdress.states').copyFrom(address); + } + app.getView({ + ContinueURL: URLUtils.https('COBilling-EditBillingAddress') + }).render('checkout/billing/billingaddressdetails'); +} + +/** + * Form handler for the returnToForm form. + * - __apply __ - attempts to save billing address information to the platform. If there is an error, renders the + * components/dialog/dialogapply template. If it is successful, sets the ContinueURL to {@link module:controllers/COBilling~EditBillingAddress|EditBillingAddress} and renders the + * checkout/billing/billingaddressdetails template. + * - __remove __ - Checks if the customer owns any product lists. If they do not, removes the address from the customer address book + * and renders the components/dialog/dialogdelete template. + * If they do own product lists, sets the ContinueURL to {@link module:controllers/COBilling~EditBillingAddress|EditBillingAddress} and renders the checkout/billing/billingaddressdetails template. + */ +function editBillingAddress() { + app.getForm('returnToForm').handleAction({ + apply: function () { + if (!app.getForm('billingaddress').copyTo(app.getForm('billingaddress').object)) { + app.getView({ + ContinueURL: URLUtils.https('COBilling-EditBillingAddress') + }).render('checkout/billing/billingaddressdetails'); + } else { + app.getView().render('components/dialog/dialogapply'); + } + }, + remove: function () { + if (ProductListMgr.getProductLists(app.getForm('billing').objectaddress.object).isEmpty()) { + customer.getAddressBook().removeAddress(app.getForm('billing').objectaddress.object); + app.getView().render('components/dialog/dialogdelete'); + } else { + app.getView({ + ContinueURL: URLUtils.https('COBilling-EditBillingAddress') + }).render('checkout/billing/billingaddressdetails'); + } + } + }); +} + +/** + * Returns information of a gift certificate including its balance as JSON + * response. Required to check the remaining balance. + */ +function getGiftCertificateBalance() { + var giftCertificate = GiftCertificateMgr.getGiftCertificateByCode(request.httpParameterMap.giftCertificateID.value); + var responseUtils = require('~/cartridge/scripts/util/Response'); + if (giftCertificate && giftCertificate.isEnabled()) { + responseUtils.renderJSON({ + giftCertificate: { + ID: giftCertificate.getGiftCertificateCode(), + balance: StringUtils.formatMoney(giftCertificate.getBalance()) + } + }); + } else { + responseUtils.renderJSON({ + error: Resource.msg('billing.giftcertinvalid', 'checkout', null) + }); + } +} + +/** + * Selects a customer credit card and returns the details of the credit card as + * JSON response. Required to fill credit card form with details of selected + * credit card. + */ +function selectCreditCard() { + var cart, applicableCreditCards, selectedCreditCard, instrumentsIter, creditCardInstrument; + cart = app.getModel('Cart').get(); + applicableCreditCards = initCreditCardList(cart).ApplicableCreditCards; + selectedCreditCard = null; + + // ensure mandatory parameter 'CreditCardUUID' and 'CustomerPaymentInstruments' + // in pipeline dictionary and collection is not empty + if (request.httpParameterMap.creditCardUUID.value && applicableCreditCards && !applicableCreditCards.empty) { + // find credit card in payment instruments + instrumentsIter = applicableCreditCards.iterator(); + while (instrumentsIter.hasNext()) { + creditCardInstrument = instrumentsIter.next(); + if (request.httpParameterMap.creditCardUUID.value.equals(creditCardInstrument.UUID)) { + selectedCreditCard = creditCardInstrument; + } + } + if (selectedCreditCard) { + app.getForm('billing').object.paymentMethods.creditCard.number.value = selectedCreditCard.getCreditCardNumber(); + } + } + app.getView({ + SelectedCreditCard: selectedCreditCard + }).render('checkout/billing/creditcardjson'); +} + +/** + * Revalidates existing payment instruments in later checkout steps. + * + * @param {module:models/CartModel~CartModel} cart - A CartModel wrapping the current Basket. + * @return {Boolean} true if existing payment instruments are valid, false if not. + */ +// ### Custom Adyen cartridge start ### +function validatePayment(cart) { + var paymentAmount, countryCode, invalidPaymentInstruments, result; + if (cart.getPaymentInstrument() && [constants.METHOD_ADYEN_POS, constants.METHOD_ADYEN_COMPONENT].indexOf(cart.getPaymentInstrument().getPaymentMethod()) !== -1) { + result = true; + return result; + } + if (app.getForm('billing').object.fulfilled.value) { + paymentAmount = cart.getNonGiftCertificateAmount(); + countryCode = Countries.getCurrent({ + CurrentRequest: { + locale: request.locale + } + }).countryCode; + invalidPaymentInstruments = cart.validatePaymentInstruments(customer, countryCode, paymentAmount.value).InvalidPaymentInstruments; + if (!invalidPaymentInstruments && cart.calculatePaymentTransactionTotal()) { + result = true; + } else { + app.getForm('billing').object.fulfilled.value = false; + result = false; + } + } else { + result = false; + } + return result; +} +// ### Custom Adyen cartridge end ### + +/** + * Attempts to save the used credit card in the customer payment instruments. + * The logic replaces an old saved credit card with the same masked credit card + * number of the same card type with the new credit card. This ensures creating + * only unique cards as well as replacing expired cards. + * @transactional + * @return {Boolean} true if credit card is successfully saved. + */ +// ### Custom Adyen cartridge start ### +function saveCreditCard() { + if (AdyenConfigs.getAdyenRecurringPaymentsEnabled()) { + //saved credit cards are handling in COPlaceOrder and Login for Adyen - saved cards are synced with Adyen ListRecurringDetails API call + return true; + } else { + var i, creditCards, newCreditCard; + if (customer.authenticated && app.getForm('billing').object.paymentMethods.creditCard.saveCard.value) { + creditCards = customer.getProfile().getWallet().getPaymentInstruments(PaymentInstrument.METHOD_CREDIT_CARD); + Transaction.wrap(function () { + newCreditCard = customer.getProfile().getWallet().createPaymentInstrument(PaymentInstrument.METHOD_CREDIT_CARD); + + // copy the credit card details to the payment instrument + newCreditCard.setCreditCardHolder(app.getForm('billing').object.paymentMethods.creditCard.owner.value); + newCreditCard.setCreditCardNumber(app.getForm('billing').object.paymentMethods.creditCard.number.value); + newCreditCard.setCreditCardExpirationMonth(app.getForm('billing').object.paymentMethods.creditCard.expiration.month.value); + newCreditCard.setCreditCardExpirationYear(app.getForm('billing').object.paymentMethods.creditCard.expiration.year.value); + newCreditCard.setCreditCardType(app.getForm('billing').object.paymentMethods.creditCard.type.value); + for (i = 0; i < creditCards.length; i++) { + var creditcard = creditCards[i]; + if (creditcard.maskedCreditCardNumber === newCreditCard.maskedCreditCardNumber && creditcard.creditCardType === newCreditCard.creditCardType) { + customer.getProfile().getWallet().removePaymentInstrument(creditcard); + } + } + }); + } + return true; + } +} +// ### Custom Adyen cartridge end ### + +/* +* Module exports +*/ + +/* +* Web exposed methods +*/ +/** Starting point for billing. + * @see module:controllers/COBilling~publicStart */ +exports.Start = guard.ensure(['https'], publicStart); + +/** Redeems gift certificates. + * @see module:controllers/COBilling~redeemGiftCertificateJson */ +exports.RedeemGiftCertificateJson = guard.ensure(['https', 'get'], redeemGiftCertificateJson); +/** Removes gift certificate from the basket payment instruments. + * @see module:controllers/COBilling~removeGiftCertificate */ +exports.RemoveGiftCertificate = guard.ensure(['https', 'get'], removeGiftCertificate); +/** Updates the order totals and recalculates the basket after a coupon code is applied. + * @see module:controllers/COBilling~updateSummary */ +exports.UpdateSummary = guard.ensure(['https', 'get'], updateSummary); +/** Gets the customer address and saves it to the customer address book. + * @see module:controllers/COBilling~updateAddressDetails */ +exports.UpdateAddressDetails = guard.ensure(['https', 'get'], updateAddressDetails); +/** Renders a form dialog to edit an address. + * @see module:controllers/COBilling~editAddress */ +exports.EditAddress = guard.ensure(['https', 'get', 'csrf'], editAddress); +/** Returns information of a gift certificate including its balance as JSON response. + * @see module:controllers/COBilling~getGiftCertificateBalance */ +exports.GetGiftCertificateBalance = guard.ensure(['https', 'get'], getGiftCertificateBalance); +/** Selects a customer credit card and returns the details of the credit card as JSON response. + * @see module:controllers/COBilling~selectCreditCard */ +exports.SelectCreditCard = guard.ensure(['https', 'get'], selectCreditCard); +/** Adds the currently selected credit card to the billing form and initializes the credit card selection list. + * @see module:controllers/COBilling~updateCreditCardSelection */ +exports.UpdateCreditCardSelection = guard.ensure(['https', 'get'], updateCreditCardSelection); +/** Form handler for the billing form. + * @see module:controllers/COBilling~billing */ +exports.Billing = guard.ensure(['https', 'csrf'], billing); +/** Form handler for the returnToForm form. + * @see module:controllers/COBilling~editBillingAddress */ +exports.EditBillingAddress = guard.ensure(['https', 'post'], editBillingAddress); +/* + * Local methods + */ +/** Saves the credit card used in the billing form in the customer payment instruments. + * @see module:controllers/COBilling~saveCreditCard */ +exports.SaveCreditCard = saveCreditCard; +/** Revalidates existing payment instruments in later checkout steps. + * @see module:controllers/COBilling~validatePayment */ +exports.ValidatePayment = validatePayment; +/** Handles the selection of the payment method and performs payment method specific validation and verification upon the entered form fields. + * @see module:controllers/COBilling~handlePaymentSelection */ +exports.HandlePaymentSelection = handlePaymentSelection; \ No newline at end of file diff --git a/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COPlaceOrder.js b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COPlaceOrder.js new file mode 100644 index 000000000..2be72cdfb --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COPlaceOrder.js @@ -0,0 +1,261 @@ +'use strict'; + +/** + * Controller that creates an order from the current basket. It's a pure processing controller and does + * no page rendering. The controller is used by checkout and is called upon the triggered place order action. + * It contains the actual logic to authorize the payment and create the order. The controller communicates the result + * of the order creation process and uses a status object PlaceOrderError to set proper error states. + * The calling controller is must handle the results of the order creation and evaluate any errors returned by it. + * + * @module controllers/COPlaceOrder + */ + +/* API Includes */ +var OrderMgr = require('dw/order/OrderMgr'); +var PaymentMgr = require('dw/order/PaymentMgr'); +var Status = require('dw/system/Status'); +var Transaction = require('dw/system/Transaction'); + +/* Script Modules */ +var app = require('~/cartridge/scripts/app'); +var guard = require('~/cartridge/scripts/guard'); +var Cart = app.getModel('Cart'); +var Order = app.getModel('Order'); +var PaymentProcessor = app.getModel('PaymentProcessor'); + +/** + * Responsible for payment handling. This function uses PaymentProcessorModel methods to + * handle payment processing specific to each payment instrument. It returns an + * error if any of the authorizations failed or a payment + * instrument is of an unknown payment method. If a payment method has no + * payment processor assigned, the payment is accepted as authorized. + * + * @transactional + * @param {dw.order.Order} order - the order to handle payments for. + * @return {Object} JSON object containing information about missing payments, errors, or an empty object if the function is successful. + */ +// ### Custom Adyen cartridge start ### +function handlePayments(order) { + if (order.getTotalNetPrice().value !== 0.00) { + var paymentInstruments = order.getPaymentInstruments(); + if (paymentInstruments.length === 0) { + return { + missingPaymentInfo: true + }; + } + /** + * Sets the transaction ID for the payment instrument. + */ + var handlePaymentTransaction = function () { + paymentInstrument.getPaymentTransaction().setTransactionID(order.getOrderNo()); + }; + for (var i = 0; i < paymentInstruments.length; i++) { + var paymentInstrument = paymentInstruments[i]; + if (PaymentMgr.getPaymentMethod(paymentInstrument.getPaymentMethod()).getPaymentProcessor() === null) { + Transaction.wrap(handlePaymentTransaction); + } else { + var authorizationResult = PaymentProcessor.authorize(order, paymentInstrument); + if (authorizationResult.not_supported || authorizationResult.error) { + return { + error: true + }; + } + if (authorizationResult.isAdyen) { + return authorizationResult; + } + } + } + } + return {}; +} +// ### Custom Adyen cartridge end ### + +/** + * The entry point for order creation. This function is not exported, as this controller must only + * be called by another controller. + * + * @transactional + * @return {Object} JSON object that is empty, contains error information, or PlaceOrderError status information. + */ +// ### Custom Adyen cartridge start ### +function start() { + var cart = Cart.get(); + if (!cart) { + app.getController('Cart').Show(); + return {}; + } + var COShipping = app.getController('COShipping'); + + // Clean shipments. + COShipping.PrepareShipments(cart); + + // Make sure there is a valid shipping address, accounting for gift certificates that do not have one. + if (cart.getProductLineItems().size() > 0 && cart.getDefaultShipment().getShippingAddress() === null) { + COShipping.Start(); + return {}; + } + + // Make sure the billing step is fulfilled, otherwise restart checkout. + if (!session.forms.billing.fulfilled.value) { + app.getController('COCustomer').Start(); + return {}; + } + Transaction.wrap(function () { + cart.calculate(); + }); + var COBilling = app.getController('COBilling'); + Transaction.wrap(function () { + if (!COBilling.ValidatePayment(cart)) { + COBilling.Start(); + return {}; + } + }); + + // Recalculate the payments. If there is only gift certificates, make sure it covers the order total, if not + // back to billing page. + Transaction.wrap(function () { + if (!cart.calculatePaymentTransactionTotal()) { + COBilling.Start(); + return {}; + } + }); + + // Handle used addresses and credit cards. + var saveCCResult = COBilling.SaveCreditCard(); + if (!saveCCResult) { + return { + error: true, + PlaceOrderError: new Status(Status.ERROR, 'confirm.error.technical') + }; + } + + // Creates a new order. This will internally ReserveInventoryForOrder and will create a new Order with status + // 'Created'. + var order = cart.createOrder(); + if (!order) { + // TODO - need to pass BasketStatus to Cart-Show ? + app.getController('Cart').Show(); + return {}; + } + var handlePaymentsResult = handlePayments(order); + var constants = require('*/cartridge/adyenConstants/constants'); + var URLUtils = require('dw/web/URLUtils'); + + // Cache current order number in order to potentially restore cart. + session.privacy.currentOrderNumber = order.orderNo; + session.privacy.currentOrderToken = order.orderToken; + var submitOrder = handlePaymentsResult.isAdyen === false || + //adyen is not the payment processor for this payment + handlePaymentsResult.isAdyen && !handlePaymentsResult.action || + // isAdyen and no action + handlePaymentsResult.action && handlePaymentsResult.action.type === constants.ACTIONTYPES.VOUCHER || + // action type is voucher + !handlePaymentsResult.action && !handlePaymentsResult.isFinal; // no action and payment is not final (SEPA) + if (handlePaymentsResult.error) { + return Transaction.wrap(function () { + OrderMgr.failOrder(order); + return { + continueUrl: URLUtils.url('Adyen-ShowConfirmation', 'error', 'true', 'errorStatus', 'confirm.error.technical').toString() + }; + }); + } else if (handlePaymentsResult.missingPaymentInfo) { + return Transaction.wrap(function () { + OrderMgr.failOrder(order); + return { + continueUrl: URLUtils.url('Adyen-ShowConfirmation', 'error', 'true', 'errorStatus', 'confirm.error.technical').toString() + }; + }); + } else { + if (submitOrder) { + var orderPlacementStatus = Order.submit(order); + if (!orderPlacementStatus.error) { + clearForms(); + } + if (handlePaymentsResult.isAdyen) { + return { + continueUrl: URLUtils.url('Adyen-ShowConfirmation', 'authorized', 'true', 'merchantReference', order.orderNo, 'orderToken', order.orderToken).toString() + }; + } + return orderPlacementStatus; + } + } + return handlePaymentsResult; +} +// ### Custom Adyen cartridge end ### + +function clearForms() { + // Clears all forms used in the checkout process. + session.forms.singleshipping.clearFormElement(); + session.forms.multishipping.clearFormElement(); + session.forms.billing.clearFormElement(); + + // clear cached order number + session.privacy.currentOrderNumber = null; + session.privacy.currentOrderToken = null; +} + +/** + * Asynchronous Callbacks for OCAPI. These functions result in a JSON response. + * Sets the payment instrument information in the form from values in the httpParameterMap. + * Checks that the payment instrument selected is valid and authorizes the payment. Renders error + * message information if the payment is not authorized. + */ +function submitPaymentJSON() { + var order = Order.get(request.httpParameterMap.order_id.stringValue); + if (!order.object || request.httpParameterMap.order_token.stringValue !== order.getOrderToken()) { + app.getView().render('checkout/components/faults'); + return; + } + session.forms.billing.paymentMethods.clearFormElement(); + var requestObject = JSON.parse(request.httpParameterMap.requestBodyAsString); + var form = session.forms.billing.paymentMethods; + for (var requestObjectItem in requestObject) { + var asyncPaymentMethodResponse = requestObject[requestObjectItem]; + var terms = requestObjectItem.split('_'); + if (terms[0] === 'creditCard') { + var value = terms[1] === 'month' || terms[1] === 'year' ? Number(asyncPaymentMethodResponse) : asyncPaymentMethodResponse; + form.creditCard[terms[1]].setValue(value); + } else if (terms[0] === 'selectedPaymentMethodID') { + form.selectedPaymentMethodID.setValue(asyncPaymentMethodResponse); + } + } + if (app.getController('COBilling').HandlePaymentSelection('cart').error || handlePayments().error) { + app.getView().render('checkout/components/faults'); + return; + } + app.getView().render('checkout/components/payment_methods_success'); +} + +/* + * Asynchronous Callbacks for SiteGenesis. + * Identifies if an order exists, submits the order, and shows a confirmation message. + */ +function submit() { + var order = Order.get(request.httpParameterMap.order_id.stringValue); + var orderPlacementStatus; + if (order.object && request.httpParameterMap.order_token.stringValue === order.getOrderToken()) { + orderPlacementStatus = Order.submit(order.object); + if (!orderPlacementStatus.error) { + clearForms(); + return app.getController('COSummary').ShowConfirmation(order.object); + } + } + app.getController('COSummary').Start(); +} + +/* + * Module exports + */ + +/* + * Web exposed methods + */ +/** @see module:controllers/COPlaceOrder~submitPaymentJSON */ +exports.SubmitPaymentJSON = guard.ensure(['https'], submitPaymentJSON); +/** @see module:controllers/COPlaceOrder~submitPaymentJSON */ +exports.Submit = guard.ensure(['https'], submit); + +/* + * Local methods + */ +exports.Start = start; \ No newline at end of file diff --git a/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COSummary.js b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COSummary.js new file mode 100644 index 000000000..ed2d8a095 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/COSummary.js @@ -0,0 +1,130 @@ +'use strict'; + +/** + * This controller implements the last step of the checkout. A successful handling + * of billing address and payment method selection leads to this controller. It + * provides the customer with a last overview of the basket prior to confirm the + * final order creation. + * + * @module controllers/COSummary + */ + +/* API Includes */ +var Resource = require('dw/web/Resource'); +var Transaction = require('dw/system/Transaction'); +var URLUtils = require('dw/web/URLUtils'); +/* Script Modules */ +var app = require('~/cartridge/scripts/app'); +var guard = require('~/cartridge/scripts/guard'); +var Cart = app.getModel('Cart'); +// ### Custom Adyen cartridge start ### +var AdyenController = require("int_adyen_controllers/cartridge/controllers/Adyen"); +// ### Custom Adyen cartridge end ### + +/** + * Renders the summary page prior to order creation. + * @param {Object} context context object used for the view + */ +function start(context) { + var cart = Cart.get(); + + // Checks whether all payment methods are still applicable. Recalculates all existing non-gift certificate payment + // instrument totals according to redeemed gift certificates or additional discounts granted through coupon + // redemptions on this page. + var COBilling = app.getController('COBilling'); + if (!COBilling.ValidatePayment(cart)) { + COBilling.Start(); + return; + } else { + Transaction.wrap(function () { + cart.calculate(); + }); + Transaction.wrap(function () { + if (!cart.calculatePaymentTransactionTotal()) { + COBilling.Start(); + } + }); + var pageMeta = require('~/cartridge/scripts/meta'); + var viewContext = require('app_storefront_core/cartridge/scripts/common/extend').immutable(context, { + Basket: cart.object + }); + pageMeta.update({ + pageTitle: Resource.msg('summary.meta.pagetitle', 'checkout', 'SiteGenesis Checkout') + }); + app.getView(viewContext).render('checkout/summary/summary'); + } +} + +/** + * This function is called when the "Place Order" action is triggered by the + * customer. + */ +// ### Custom Adyen cartridge start ### +function submit() { + // Calls the COPlaceOrder controller that does the place order action and any payment authorization. + // If the order creation failed, it returns a JSON object with an error key and a boolean value. + var placeOrderResult = app.getController('COPlaceOrder').Start(); + if (Object.keys(placeOrderResult).length === 0 || placeOrderResult.error) { + start({ + PlaceOrderError: placeOrderResult.PlaceOrderError + }); + } else { + if (placeOrderResult.isAdyen || placeOrderResult.continueUrl) { + const responseUtils = require('*/cartridge/scripts/util/Response'); + responseUtils.renderJSON(placeOrderResult); + } else { + showConfirmation(placeOrderResult.Order); + } + } +} +// ### Custom Adyen cartridge end ## + +/** + * Renders the order confirmation page after successful order + * creation. If a nonregistered customer has checked out, the confirmation page + * provides a "Create Account" form. This function handles the + * account creation. + */ +// ### Custom Adyen cartridge start ### +function showConfirmation(order) { + var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); + var adyenGivingConfig = AdyenHelper.getAdyenGivingConfig(order); + if (!customer.authenticated) { + // Initializes the account creation form for guest checkouts by populating the first and last name with the + // used billing address. + var customerForm = app.getForm('profile.customer'); + customerForm.setValue('firstname', order.billingAddress.firstName); + customerForm.setValue('lastname', order.billingAddress.lastName); + customerForm.setValue('email', order.customerEmail); + customerForm.setValue('orderNo', order.orderNo); + } + app.getForm('profile.login.passwordconfirm').clear(); + app.getForm('profile.login.password').clear(); + var pageMeta = require('~/cartridge/scripts/meta'); + pageMeta.update({ + pageTitle: Resource.msg('confirmation.meta.pagetitle', 'checkout', 'SiteGenesis Checkout Confirmation') + }); + app.getView({ + Order: order, + AdyenGivingConfig: adyenGivingConfig, + ContinueURL: URLUtils.https('Account-RegistrationForm') // needed by registration form after anonymous checkouts + }).render('checkout/confirmation/confirmation'); +} +// ### Custom Adyen cartridge end ### + +/* + * Module exports + */ + +/* + * Web exposed methods + */ +/** @see module:controllers/COSummary~Start */ +exports.Start = guard.ensure(['https'], start); +/** @see module:controllers/COSummary~Submit */ +exports.Submit = guard.ensure(['https', 'post', 'csrf'], submit); + +/* + * Local method + */ +exports.ShowConfirmation = showConfirmation; \ No newline at end of file diff --git a/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/PaymentInstruments.js b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/PaymentInstruments.js new file mode 100644 index 000000000..6d0bc7560 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/cartridge/controllers/PaymentInstruments.js @@ -0,0 +1,307 @@ +'use strict'; + +/** + * Controller that displays credit card and other payment information and + * lets the user change it. + * + * @module controllers/PaymentInstruments + */ + +/* API includes */ +var PaymentInstrument = require('dw/order/PaymentInstrument'); +var PaymentMgr = require('dw/order/PaymentMgr'); +var PaymentStatusCodes = require('dw/order/PaymentStatusCodes'); +var Status = require('dw/system/Status'); +var Transaction = require('dw/system/Transaction'); +var URLUtils = require('dw/web/URLUtils'); + +/* Script Modules */ +var app = require('~/cartridge/scripts/app'); +var guard = require('~/cartridge/scripts/guard'); +var constants = require("*/cartridge/adyenConstants/constants"); +// ### Custom Adyen cartridge start ### +var AdyenHelper = require('int_adyen_overlay/cartridge/scripts/util/adyenHelper'); +var AdyenConfigs = require('int_adyen_overlay/cartridge/scripts/util/adyenConfigs'); +var adyenSessions = require('int_adyen_overlay/cartridge/scripts/adyenSessions'); +var adyenSaveCreditCard = require("*/cartridge/scripts/adyenSaveCreditCard"); +var AdyenLogs = require("int_adyen_overlay/cartridge/scripts/adyenCustomLogs"); +// ### Custom Adyen cartridge end ### + +/** + * Displays a list of customer payment instruments. + * + * Gets customer payment instrument information. Clears the paymentinstruments form and adds the customer + * payment information to it. Updates the page metadata. + * Renders a list of the saved credit card payment instruments of the current + * customer (account/payment/paymentinstrumentlist template). + */ +// ### Custom Adyen cartridge start ### +function list() { + // Get the Saved Cards from Adyen to get latest saved cards + require('int_adyen_overlay/cartridge/scripts/updateSavedCards').updateSavedCards({ + CurrentCustomer: customer + }); + var paymentInstruments = getAdyenPaymentInstruments(); + var pageMeta = require('~/cartridge/scripts/meta'); + var paymentForm = app.getForm('paymentinstruments'); + paymentForm.clear(); + paymentForm.get('creditcards.storedcards').copyFrom(paymentInstruments); + pageMeta.update(dw.content.ContentMgr.getContent('myaccount-paymentsettings')); + app.getView({ + PaymentInstruments: paymentInstruments + }).render('account/payment/paymentinstrumentlist'); +} +// ### Custom Adyen cartridge end ## + +// ### Custom Adyen cartridge start ## +function getSessionData() { + var sessionsResponse = adyenSessions.createSession(null, customer, ''); + return { + id: sessionsResponse.id, + sessionData: sessionsResponse.sessionData + }; +} +// ### Custom Adyen cartridge end ## + +/** + * Adds a new credit card payment instrument to the saved payment instruments of the current customer. + * Sets the ContinueURL to PaymentInstruments-PaymentForm and renders the payment instrument details page + * (account/payment/paymentinstrumentdetails template). + * __Note:__this function is called by the {@link module:controllers/PaymentInstruments~handlePaymentForm|handlePaymentForm} function. + * @param {boolean} clearForm true or missing clears the form before displaying the page, false skips it + */ +function add(clearForm) { + var paymentForm = app.getForm('paymentinstruments'); + if (clearForm !== false) { + paymentForm.clear(); + } + paymentForm.get('creditcards.newcreditcard.type').setOptions(dw.order.PaymentMgr.getPaymentMethod(dw.order.PaymentInstrument.METHOD_CREDIT_CARD).activePaymentCards.iterator()); + app.getView({ + ContinueURL: URLUtils.https('PaymentInstruments-PaymentForm'), + SessionData: JSON.stringify(getSessionData()) + }).render('account/payment/paymentinstrumentdetails'); +} + +/** + * Form handler for the paymentinstruments form. Handles the following actions: + * - __create__ - calls the {@link module:controllers/PaymentInstruments~create|create} function to create a payment instrument + * and redirects to {@link module:controllers/PaymentInstruments~list|list}. If the + * creation fails, calls the {@link module:controllers/PaymentInstruments~add|add} function with a clearform value of false. + * - __error__ - calls the {@link module:controllers/PaymentInstruments~add|add} function with a clearform value of false. + */ +function handlePaymentForm() { + var paymentForm = app.getForm('paymentinstruments'); + paymentForm.handleAction({ + create: function () { + if (!create()) { + response.redirect(URLUtils.https('PaymentInstruments-List', 'error', 'AuthorisationFailed')); + return; + } else { + response.redirect(URLUtils.https('PaymentInstruments-List')); + } + }, + error: function () { + add(false); + } + }); +} +/** + * Saves a customer credit card payment instrument. + * @param {Object} params + * @param {dw.customer.CustomerPaymentInstrument} params.PaymentInstrument - credit card object. + * @param {dw.web.FormGroup} params.CreditCardFormFields - new credit card form. + */ +function save(params) { + var saveCustomerCreditCard = require('app_storefront_core/cartridge/scripts/checkout/SaveCustomerCreditCard'); + var result = saveCustomerCreditCard.save(params); + if (result === PIPELET_ERROR) { + throw new Error('Problem saving credit card'); + } +} + +/** + * Creates a new payment instrument. Verifies the credit card and checks if it is a duplicate of + * a card already in the current customer's payment instruments. In a transaction, the function + * attempts to save the credit card to the customer's payment instruments. If a duplicate card was + * detected, the original card is removed after the new card is created. If the card cannot be created + * successfully, the transaction is rolled back. Whether successful or not, the paymentinstruments + * form is cleared. + * + * @transaction + * @return {boolean} true if the credit card can be verified, false otherwise + */ +// ### Custom Adyen cartridge start ### +function create() { + if (getAdyenPaymentInstruments()) { + return adyenSaveCreditCard.create(); + } + var paymentForm = app.getForm('paymentinstruments'); + var newCreditCardForm = paymentForm.get('creditcards.newcreditcard'); + var ccNumber = newCreditCardForm.get('number').value(); + var wallet = customer.getProfile().getWallet(); + var paymentInstruments = wallet.getPaymentInstruments(dw.order.PaymentInstrument.METHOD_CREDIT_CARD); + if (AdyenConfigs.getAdyenRecurringPaymentsEnabled()) { + var createRecurringPaymentAccountResult = AdyenHelper.createRecurringPaymentAccount({ + Customer: customer + }); + if (createRecurringPaymentAccountResult.error) { + return false; + } + pspReference = 'PspReference' in createRecurringPaymentAccountResult && !empty(createRecurringPaymentAccountResult.PspReference) ? createRecurringPaymentAccountResult.PspReference : ''; + tokenID = 'TokenID' in createRecurringPaymentAccountResult && !empty(createRecurringPaymentAccountResult.TokenID) ? createRecurringPaymentAccountResult.TokenID : ''; + try { + Transaction.wrap(function () { + /* var newCreditCard = customer.getProfile().getWallet().createPaymentInstrument(PaymentInstrument.METHOD_CREDIT_CARD); + * // copy the credit card details to the payment instrument + * newCreditCard.setCreditCardHolder( + newCreditCard.setCreditCardNumber( + newCreditCard.setCreditCardType( + newCreditCard.setCreditCardToken(tokenID); + newCreditCard.custom.AdyenPspReference = pspReference; */ + require('int_adyen_overlay/cartridge/scripts/updateSavedCards').updateSavedCards({ + CurrentCustomer: customer, + PaymentsMap: createRecurringPaymentAccountResult.PaymentsMap + }); + }); + } catch (e) { + AdyenLogs.error_log(`${e}: ${e.stack}`); + return false; + } + return true; + } + var isDuplicateCard = false; + var oldCard; + for (var i = 0; i < paymentInstruments.length; i++) { + var card = paymentInstruments[i]; + if (card.creditCardNumber === ccNumber) { + isDuplicateCard = true; + oldCard = card; + break; + } + } + Transaction.begin(); + var paymentInstrument = wallet.createPaymentInstrument(dw.order.PaymentInstrument.METHOD_CREDIT_CARD); + try { + save({ + PaymentInstrument: paymentInstrument, + CreditCardFormFields: newCreditCardForm.object + }); + } catch (err) { + Transaction.rollback(); + return false; + } + if (isDuplicateCard) { + wallet.removePaymentInstrument(oldCard); + } + Transaction.commit(); + paymentForm.clear(); + return true; +} +// ### Custom Adyen cartridge end ### + +/** + * Form handler for the paymentinstruments form. Handles the following actions: + * - __remove__ - uses the form and action supplied by the FormModel to remove a customer payment instrument + * in a transaction. + * - __error__ - does nothing. + * + * In either case, redirects to the {@link module:controllers/PaymentInstruments~list|List} function. + * @transaction + * @TODO Should be moved into handlePaymentForm + * @FIXME Inner method should be lowercase.error action should do something + */ +// ### Custom Adyen cartridge start ### +function Delete() { + var paymentForm = app.getForm('paymentinstruments'); + paymentForm.handleAction({ + remove: function (formGroup, action) { + Transaction.wrap(function () { + var wallet = customer.getProfile().getWallet(); + var paymentInstrument = action.object; + if (!empty(paymentInstrument)) { + if (AdyenConfigs.getAdyenRecurringPaymentsEnabled() && !empty(paymentInstrument.getCreditCardToken())) { + var result = require('int_adyen_overlay/cartridge/scripts/adyenDeleteRecurringPayment').deleteRecurringPayment({ + Customer: customer, + RecurringDetailReference: paymentInstrument.getCreditCardToken() + }); + if (result == PIPELET_NEXT) { + wallet.removePaymentInstrument(paymentInstrument); + } + } else { + wallet.removePaymentInstrument(paymentInstrument); + } + } + }); + }, + error: function () { + // @TODO When could this happen + } + }); + response.redirect(URLUtils.https('PaymentInstruments-List')); +} +// ### Custom Adyen cartridge end ### + +/* + * Private helpers + */ +// ### Custom Adyen cartridge start ### +function getAdyenPaymentInstruments() { + var wallet = customer.getProfile().getWallet(); + return wallet.getPaymentInstruments(constants.METHOD_ADYEN_COMPONENT); +} +// ### Custom Adyen cartridge start ### + +/** + * Verifies if the entered credit card details are valid. + * + * @returns {boolean} true in case of success, otherwise false. + */ +// ### Custom Adyen cartridge start ### +function verifyCreditCard() { + var newCreditCardForm = app.getForm('paymentinstruments.creditcards.newcreditcard'); + if (getAdyenPaymentInstruments()) { + return true; + } + var expirationMonth = newCreditCardForm.get('expiration.month').value(); + var expirationYear = newCreditCardForm.get('expiration.year').value(); + var cardNumber = newCreditCardForm.get('number').value(); + var paymentCard = PaymentMgr.getPaymentCard(newCreditCardForm.get('type').value()); + var verifyPaymentCardResult = paymentCard.verify(expirationMonth, expirationYear, cardNumber); + if (verifyPaymentCardResult.error === true) { + if (!newCreditCardForm.isValid()) { + return false; + } + if (verifyPaymentCardResult.code === Status.OK) { + return true; + } + + // Invalidate the payment card form elements. + for (var i = 0; i < verifyPaymentCardResult.items.length; i++) { + if (verifyPaymentCardResult.items[i].code === PaymentStatusCodes.CREDITCARD_INVALID_CARD_NUMBER) { + newCreditCardForm.get('number').invalidate(); + } else if (verifyPaymentCardResult.items[i].code === PaymentStatusCodes.CREDITCARD_INVALID_EXPIRATION_DATE) { + newCreditCardForm.get('expiration.month').invalidate(); + newCreditCardForm.get('expiration.year').invalidate(); + } + } + return false; + } + return true; +} +// ### Custom Adyen cartridge end ### + +/* + * Web exposed methods + */ +/** Renders a list of the saved credit card payment instruments of the current customer. + * @see module:controllers/PaymentInstruments~list */ +exports.List = guard.ensure(['https', 'get', 'loggedIn'], list); +/** Adds a new credit card payment instrument to the saved payment instruments of the current customer. + * @see module:controllers/PaymentInstruments~add */ +exports.Add = guard.ensure(['https', 'get', 'loggedIn'], add); +/** Handles the submitted form for creating payment instruments. + * @see module:controllers/PaymentInstruments~handlePaymentForm */ +exports.PaymentForm = guard.ensure(['https', 'post', 'loggedIn', 'csrf'], handlePaymentForm); +/** Deletes a saved credit card payment instrument. + * @see module:controllers/PaymentInstruments~Delete */ +exports.Delete = guard.ensure(['https', 'loggedIn'], Delete); \ No newline at end of file diff --git a/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/package.json b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/package.json new file mode 100644 index 000000000..a9de38453 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_controllers_changes/package.json @@ -0,0 +1,3 @@ +{ + "hooks": "./cartridge/scripts/hooks.json" +} diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/forms/default/billing.xml b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/forms/default/billing.xml new file mode 100644 index 000000000..88f5bfe1d --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/forms/default/billing.xml @@ -0,0 +1,77 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/forms/default/creditcard.xml b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/forms/default/creditcard.xml new file mode 100644 index 000000000..69198b20a --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/forms/default/creditcard.xml @@ -0,0 +1,74 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/scripts/util/Resource.ds b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/scripts/util/Resource.ds new file mode 100644 index 000000000..b360d2ce6 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/scripts/util/Resource.ds @@ -0,0 +1,253 @@ +/** + * Resource helper + * + */ +var Currency = require('dw/util/Currency'); +var Site = require('dw/system/Site'); +var ContentMgr = require('dw/content/ContentMgr'); +var ProductAvailabilityModel = require('dw/catalog/ProductAvailabilityModel'); + +/* Script Modules */ +var AdyenHelper = require ("int_adyen_overlay/cartridge/scripts/util/adyenHelper"); + +function ResourceHelper() {} +/** + * Get the client-side constants + * @param pageContext + * @returns {Object} An objects key key-value pairs holding the constants + */ +ResourceHelper.getConstants = function(pageContext) { + return { + AVAIL_STATUS_IN_STOCK : ProductAvailabilityModel.AVAILABILITY_STATUS_IN_STOCK, + AVAIL_STATUS_PREORDER : ProductAvailabilityModel.AVAILABILITY_STATUS_PREORDER, + AVAIL_STATUS_BACKORDER : ProductAvailabilityModel.AVAILABILITY_STATUS_BACKORDER, + AVAIL_STATUS_NOT_AVAILABLE : ProductAvailabilityModel.AVAILABILITY_STATUS_NOT_AVAILABLE + }; +} +/** + * Get the client-side resources of a given page + * @param pageContext + * @returns {Object} An objects key key-value pairs holding the resources + */ +ResourceHelper.getResources = function(pageContext) { + var Resource = require('dw/web/Resource'); + + // application resources + var resources = { + // Common + I_AGREE : Resource.msg('global.i_agree', 'locale', null), + TRACKING_CONSENT : Resource.msg('global.tracking_consent', 'locale', null), + TRACKING_NO_CONSENT : Resource.msg('global.tracking_no_consent', 'locale', null), + CLOSE : Resource.msg('global.close', 'locale', null), + NO_THANKS : Resource.msg('global.nothanks', 'locale', null), + OK : Resource.msg('global.ok', 'locale', null), + ARE_YOU_HUMAN : Resource.msg('global.captcha.areyouhuman', 'locale', null), + + // Checkout + SHIP_QualifiesFor : Resource.msg('shipment.qualifiesfor', 'checkout', null), + CC_LOAD_ERROR : Resource.msg('billing.creditcardloaderror', 'checkout', null), + COULD_NOT_SAVE_ADDRESS : Resource.msg('multishippingaddresses.couldnotsaveaddress', 'checkout', null), + + // Registry resources + REG_ADDR_ERROR : Resource.msg('global.couldntloadaddress', 'locale', null), + + // bonus products messages + BONUS_PRODUCT : Resource.msg('product.bonusproduct', 'product', null), + BONUS_PRODUCTS : Resource.msg('product.bonusproducts', 'product', null), + SELECT_BONUS_PRODUCTS : Resource.msg('product.selectbonusproducts', 'product', null), + SELECT_BONUS_PRODUCT : Resource.msg('product.selectbonusproduct', 'product', null), + BONUS_PRODUCT_MAX : Resource.msg('product.bonusproductsmax', 'product', null), + BONUS_PRODUCT_TOOMANY : Resource.msg('product.bonusproductstoomany', 'product', null), + SIMPLE_SEARCH : Resource.msg('simplesearch.searchtext', 'search', null), + SUBSCRIBE_EMAIL_DEFAULT : Resource.msg('subscribe.email.default', 'forms', 'Email Address'), + + CURRENCY_SYMBOL : Currency.getCurrency(Site.current.getDefaultCurrency()).symbol, + MISSINGVAL : Resource.msg('global.missingval', 'locale', null), + SERVER_ERROR : Resource.msg('global.servererror', 'locale', null), + MISSING_LIB : Resource.msg('global.missinglib', 'locale', null), + BAD_RESPONSE : Resource.msg('global.badresponse', 'locale', null), + INVALID_PHONE : Resource.msg('global.invalidphone', 'locale', null), + REMOVE : Resource.msg('global.remove', 'locale', null), + QTY : Resource.msg('global.qty', 'locale', null), + EMPTY_IMG_ALT : Resource.msg('global.remove', 'locale', null), + COMPARE_BUTTON_LABEL : Resource.msg('productcomparewidget.compareitemsbutton', 'search', null), + COMPARE_CONFIRMATION : Resource.msg('productcomparewidget.maxproducts', 'search', null), + COMPARE_REMOVE_FAIL : Resource.msg('productcomparewidget.removefail', 'search', null), + COMPARE_ADD_FAIL : Resource.msg('productcomparewidget.addfail', 'search', null), + ADD_TO_CART_FAIL : Resource.msg('cart.unableToAdd', 'checkout', null), + REGISTRY_SEARCH_ADVANCED_CLOSE : Resource.msg('account.giftregistry.closeadvanced', 'account', null), + GIFT_CERT_INVALID : Resource.msg('billing.giftcertinvalid', 'checkout', null), + GIFT_CERT_BALANCE : Resource.msg('billing.giftcertbalance', 'checkout', null), + GIFT_CERT_AMOUNT_INVALID : Resource.msg('giftcert.amountvalueerror', 'forms', null), + GIFT_CERT_MISSING : Resource.msg('billing.giftcertidmissing', 'checkout', null), + INVALID_OWNER : Resource.msg('billing.ownerparseerror', 'checkout', null), + COUPON_CODE_MISSING : Resource.msg('cart.COUPON_CODE_MISSING', 'checkout', null), + COOKIES_DISABLED : Resource.msg('global.browsertoolscheck.cookies', 'locale', null), + BML_AGREE_TO_TERMS : Resource.msg('bml.termserror', 'forms', null), + CHAR_LIMIT_MSG : Resource.msg('character.limit', 'forms', null), + CONFIRM_DELETE : Resource.msg('confirm.delete', 'forms', null), + TITLE_GIFTREGISTRY : Resource.msg('title.giftregistry', 'forms', null), + TITLE_ADDRESS : Resource.msg('title.address', 'forms', null), + TITLE_CREDITCARD : Resource.msg('title.creditcard', 'forms', null), + SERVER_CONNECTION_ERROR : Resource.msg('global.serverconnection', 'locale', 'Server connection failed!'), + IN_STOCK_DATE : Resource.msg('global.inStockDate', 'locale', null), + ITEM_STATUS_NOTAVAILABLE : Resource.msg('global.allnotavailable', 'locale', null), + INIFINITESCROLL : Resource.msg('paginginformation.infinite-scroll', 'search', null), + STORE_NEAR_YOU : Resource.msg('storelist.lightbox.whatsavailable', 'storepickup', 'What\'s available at a store near you'), + SELECT_STORE : Resource.msg('storelist.lightbox.selectstore', 'storepickup', null), + SELECTED_STORE : Resource.msg('storelist.lightbox.selectedstore', 'storepickup', null), + PREFERRED_STORE : Resource.msg('storelist.lightbox.preferredstore', 'storepickup', null), + SET_PREFERRED_STORE : Resource.msg('storelist.lightbox.setpreferredstore', 'storepickup', null), + ENTER_ZIP : Resource.msg('storelist.lightbox.enterzip', 'storepickup', null), + INVALID_ZIP : Resource.msg('storelist.lightbox.invalidpostalcode', 'storepickup', null), + SEARCH : Resource.msg('global.search', 'locale', null), + CHANGE_LOCATION : Resource.msg('storelist.lightbox.changelocation', 'storepickup', null), + CONTINUE_WITH_STORE : Resource.msg('storelist.lightbox.continuewithstore', 'storepickup', null), + CONTINUE : Resource.msg('global.continue', 'locale', null), + SEE_MORE : Resource.msg('storelist.lightbox.seemore', 'storepickup', null), + SEE_LESS : Resource.msg('storelist.lightbox.seeless', 'storepickup', null), + QUICK_VIEW : Resource.msg('product.quickview', 'product', null), + QUICK_VIEW_POPUP : Resource.msg('product.quickview.popup', 'product', null), + TLS_WARNING : Resource.msg('global.browsertoolscheck.tls', 'locale', null), + CSRF_TOKEN_MISMATCH : Resource.msg('global.csrf.failed.error', 'locale', null), + + // Validation messages + VALIDATE_REQUIRED : Resource.msg('validate.required', 'forms', null), + VALIDATE_REMOTE : Resource.msg('validate.remote', 'forms', null), + VALIDATE_EMAIL : Resource.msg('validate.email', 'forms', null), + VALIDATE_URL : Resource.msg('validate.url', 'forms', null), + VALIDATE_DATE : Resource.msg('validate.date', 'forms', null), + VALIDATE_DATEISO : Resource.msg('validate.dateISO', 'forms', null), + VALIDATE_NUMBER : Resource.msg('validate.number', 'forms', null), + VALIDATE_DIGITS : Resource.msg('validate.digits', 'forms', null), + VALIDATE_CREDITCARD : Resource.msg('validate.creditcard', 'forms', null), + VALIDATE_EQUALTO : Resource.msg('validate.equalTo', 'forms', null), + VALIDATE_MAXLENGTH : Resource.msg('validate.maxlength', 'forms', null), + VALIDATE_MINLENGTH : Resource.msg('validate.minlength', 'forms', null), + VALIDATE_RANGELENGTH : Resource.msg('validate.rangelength', 'forms', null), + VALIDATE_RANGE : Resource.msg('validate.range', 'forms', null), + VALIDATE_MAX : Resource.msg('validate.max', 'forms', null), + VALIDATE_MIN : Resource.msg('validate.min', 'forms', null), + ADYEN_CC_VALIDATE : Resource.msg('adyen.creditcard', 'adyen', null) + + }; + + // additional resources + resources[ProductAvailabilityModel.AVAILABILITY_STATUS_IN_STOCK] = Resource.msg('global.instock', 'locale', null); + resources["QTY_" + ProductAvailabilityModel.AVAILABILITY_STATUS_IN_STOCK] = Resource.msg('global.quantityinstock', 'locale', null); + resources[ProductAvailabilityModel.AVAILABILITY_STATUS_PREORDER] = Resource.msg('global.allpreorder', 'locale', null); + resources["QTY_" + ProductAvailabilityModel.AVAILABILITY_STATUS_PREORDER] = Resource.msg('global.quantitypreorder', 'locale', null); + resources["REMAIN_" + ProductAvailabilityModel.AVAILABILITY_STATUS_PREORDER] = Resource.msg('global.remainingpreorder', 'locale', null); + resources[ProductAvailabilityModel.AVAILABILITY_STATUS_BACKORDER] = Resource.msg('global.allbackorder', 'locale', null); + resources["QTY_" + ProductAvailabilityModel.AVAILABILITY_STATUS_BACKORDER] = Resource.msg('global.quantitybackorder', 'locale', null); + resources["REMAIN_" + ProductAvailabilityModel.AVAILABILITY_STATUS_BACKORDER] = Resource.msg('global.remainingbackorder', 'locale', null); + resources[ProductAvailabilityModel.AVAILABILITY_STATUS_NOT_AVAILABLE] = Resource.msg('global.allnotavailable', 'locale', null); + resources["REMAIN_" + ProductAvailabilityModel.AVAILABILITY_STATUS_NOT_AVAILABLE] = Resource.msg('global.remainingnotavailable', 'locale', null); + + return resources; +} + +/** + * Get the client-side URLs of a given page + * @returns {Object} An objects key key-value pairs holding the URLs + */ +ResourceHelper.getUrls = function(pageContext) { + var URLUtils = require('dw/web/URLUtils'); + var Resource = require('dw/web/Resource'); + + // application urls + var urls = { + appResources : URLUtils.url('Resources-Load').toString(), + pageInclude : URLUtils.url('Page-Include').toString(), + continueUrl : request.isHttpSecure() ? URLUtils.httpsContinue().toString() : URLUtils.httpContinue().toString(), + staticPath : URLUtils.staticURL("/").toString(), + addGiftCert : URLUtils.url('GiftCert-Purchase').toString(), + minicartGC : URLUtils.url('GiftCert-ShowMiniCart').toString(), + addProduct : URLUtils.url('Cart-AddProduct').toString(), + minicart : URLUtils.url('Cart-MiniAddProduct').toString(), + cartShow : URLUtils.url('Cart-Show').toString(), + giftRegAdd : URLUtils.https('Address-GetAddressDetails', 'addressID', '').toString(), + paymentsList : URLUtils.https('PaymentInstruments-List').toString(), + addressesList : URLUtils.https('Address-List').toString(), + wishlistAddress : URLUtils.https('Wishlist-SetShippingAddress').toString(), + deleteAddress : URLUtils.url('Address-Delete').toString(), + getProductUrl : URLUtils.url('Product-Show').toString(), + getBonusProducts : URLUtils.url('Product-GetBonusProducts').toString(), + addBonusProduct : URLUtils.url('Cart-AddBonusProduct').toString(), + getSetItem : URLUtils.url('Product-GetSetItem').toString(), + productDetail : URLUtils.url('Product-Detail').toString(), + getAvailability : URLUtils.url('Product-GetAvailability').toString(), + removeImg : URLUtils.staticURL('/images/icon_remove.gif').toString(), + searchsuggest : URLUtils.url('Search-GetSuggestions').toString(), + productNav : URLUtils.url('Product-Productnav').toString(), + summaryRefreshURL : URLUtils.url('COBilling-UpdateSummary').toString(), + billingSelectCC : URLUtils.https('COBilling-SelectCreditCard').toString(), + updateAddressDetails : URLUtils.https('COShipping-UpdateAddressDetails').toString(), + updateAddressDetailsBilling : URLUtils.https('COBilling-UpdateAddressDetails').toString(), + shippingMethodsJSON : URLUtils.https('COShipping-GetApplicableShippingMethodsJSON').toString(), + shippingMethodsList : URLUtils.https('COShipping-UpdateShippingMethodList').toString(), + selectShippingMethodsList : URLUtils.https('COShipping-SelectShippingMethod').toString(), + resetPaymentForms : URLUtils.url('COBilling-ResetPaymentForms').toString(), + compareShow : URLUtils.url('Compare-Show').toString(), + compareAdd : URLUtils.url('Compare-AddProduct').toString(), + compareRemove : URLUtils.url('Compare-RemoveProduct').toString(), + compareEmptyImage : URLUtils.staticURL('/images/comparewidgetempty.png').toString(), + giftCardCheckBalance : URLUtils.https('COBilling-GetGiftCertificateBalance').toString(), + redeemGiftCert : URLUtils.https('COBilling-RedeemGiftCertificateJson').toString(), + addCoupon : URLUtils.https('Cart-AddCouponJson').toString(), + storesInventory : URLUtils.url('StoreInventory-Inventory').toString(), + setPreferredStore : URLUtils.url('StoreInventory-SetPreferredStore').toString(), + getPreferredStore : URLUtils.url('StoreInventory-GetPreferredStore').toString(), + setStorePickup : URLUtils.url('StoreInventory-SetStore').toString(), + setZipCode : URLUtils.url('StoreInventory-SetZipCode').toString(), + getZipCode : URLUtils.url('StoreInventory-GetZipCode').toString(), + billing : URLUtils.url('COBilling-Start').toString(), + setSessionCurrency : URLUtils.url('Currency-SetSessionCurrency').toString(), + addEditAddress : URLUtils.url('COShippingMultiple-AddEditAddressJSON').toString(), + cookieHint : URLUtils.url('Page-Show', 'cid', 'cookie_hint').toString(), + consentTracking : URLUtils.url('Page-Show', 'cid', 'consent_tracking_hint').toString(), + consentTrackingSetSession : URLUtils.url('Account-ConsentTracking').toString(), + rateLimiterReset : URLUtils.url('RateLimiter-HideCaptcha').toString(), + csrffailed : URLUtils.url('CSRF-Failed').toString() + }; + return urls; +} +/** + * Get the client-side preferences of a given page + * @returns {Object} An objects key key-value pairs holding the preferences + */ +ResourceHelper.getPreferences = function(pageContext) { + var cookieHintAsset = ContentMgr.getContent('cookie_hint'); + var consentTrackingHintAsset = ContentMgr.getContent('consent_tracking_hint'); + return { + LISTING_INFINITE_SCROLL: (Site.getCurrent().getCustomPreferenceValue('enableInfiniteScroll') ? true : false), + LISTING_REFINE_SORT: true, + STORE_PICKUP: Site.getCurrent().getCustomPreferenceValue('enableStorePickUp'), + COOKIE_HINT: (cookieHintAsset && cookieHintAsset.online) || false, + CONSENT_TRACKING_HINT: (consentTrackingHintAsset && consentTrackingHintAsset.online) || false, + CHECK_TLS: Site.getCurrent().getCustomPreferenceValue('checkTLS'), + ADYEN_SF_ENABLED : dw.order.PaymentMgr.getPaymentMethod('AdyenComponent').isActive() + || (dw.order.PaymentMgr.getPaymentMethod('CREDIT_CARD') && ['Adyen_Component', 'ADYEN_CREDIT'].indexOf(dw.order.PaymentMgr.getPaymentMethod('CREDIT_CARD').getPaymentProcessor().getID()) > -1) + }; +} +/** + * Get the client-side preferences of a given page + * @returns {Object} An objects key key-value pairs holding the preferences + */ +ResourceHelper.getSessionAttributes = function(pageContext) { + return { + SHOW_CAPTCHA: session.privacy.showCaptcha + }; +} +/** + * Get the client-side user settings + * @returns {Object} An objects key key-value pairs holding the settings + */ +ResourceHelper.getUserSettings = function(pageContext) { + var ProductAvailabilityModel = require('dw/catalog/ProductAvailabilityModel'); + var AdyenHelper = require ("int_adyen_overlay/cartridge/scripts/util/adyenHelper"); + return { + zip: session.custom.zipcode == "null" ? null : session.custom.zipcode, + storeId: session.custom.storeId == "null" ? null : session.custom.storeId + }; +} diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/static/default/js/app.js b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/static/default/js/app.js new file mode 100644 index 000000000..f4f220cf1 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/static/default/js/app.js @@ -0,0 +1,11072 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a;}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r);},p,p.exports,r,e,n,t);}return n[i].exports;}for(var u="function"==typeof require&&require,i=0;i{if(paypalTerminatedEarly){paymentFromComponent({cancelTransaction:true,merchantReference:document.querySelector('#merchantReference').value});paypalTerminatedEarly=false;return actions.resolve();}paypalTerminatedEarly=true;$('#dwfrm_billing').trigger('submit');if(formErrorsExist){paypalTerminatedEarly=false;return actions.reject();}},onSubmit:(state,component)=>{assignPaymentMethodValue();paymentFromComponent(state.data,component);document.querySelector('#adyenStateData').value=JSON.stringify(state.data);},onCancel:(data,component)=>{paypalTerminatedEarly=false;paymentFromComponent({cancelTransaction:true,merchantReference:document.querySelector('#merchantReference').value},component);},onError:(/* error, component */)=>{paypalTerminatedEarly=false;$('#dwfrm_billing').trigger('submit');},onAdditionalDetails:(state/* , component */)=>{paypalTerminatedEarly=false;document.querySelector('#paymentFromComponentStateData').value=JSON.stringify(state.data);$('#dwfrm_billing').trigger('submit');}},mbway:{showPayButton:true,onSubmit:(state,component)=>{$('#dwfrm_billing').trigger('submit');assignPaymentMethodValue();if(formErrorsExist){return false;}document.getElementById('component_mbway').querySelector('button').disabled=true;paymentFromComponent(state.data,component);document.querySelector('#adyenStateData').value=JSON.stringify(state.data);},onError:(/* error, component */)=>{$('#dwfrm_billing').trigger('submit');},onAdditionalDetails:(state/* , component */)=>{document.querySelector('#paymentFromComponentStateData').value=JSON.stringify(state.data);$('#dwfrm_billing').trigger('submit');}},swish:getQRCodeConfig(),bcmc_mobile:getQRCodeConfig(),wechatpayQR:getQRCodeConfig(),pix:getQRCodeConfig(),amazonpay:getAmazonpayConfig()};if(window.googleMerchantID!=='null'&&window.Configuration.environment==='live'){checkoutConfiguration.paymentMethodsConfiguration.paywithgoogle.configuration.merchantIdentifier=window.googleMerchantID;checkoutConfiguration.paymentMethodsConfiguration.googlepay.configuration.merchantIdentifier=window.googleMerchantID;}if(window.cardholderNameBool!=='null'){checkoutConfiguration.paymentMethodsConfiguration.card.hasHolderName=true;checkoutConfiguration.paymentMethodsConfiguration.card.holderNameRequired=true;}checkoutConfiguration.session={id:window.sessionsResponse.id,sessionData:window.sessionsResponse.sessionData};checkout=await AdyenCheckout(checkoutConfiguration);paymentMethodsResponse=checkout.paymentMethodsResponse;document.querySelector('#paymentMethodsList').innerHTML='';renderGenericComponent();}}function zeroAuth(data,checkout){$.ajax({url:window.zeroAuthURL,type:'POST',contentType:'application/; charset=utf-8',data:JSON.stringify(data),async:false,success:function(data){if(data.zeroAuthResult.action){document.querySelector('#buttonsContainer').style.display='none';checkout.createFromAction(data.zeroAuthResult.action).mount('#newCard');}if(data.zeroAuthResult.resultCode==='Authorised'){window.location.href=window.paymentInstrumentsList;}else if(data.zeroAuthResult.resultCode==='Refused'){window.location.href=window.paymentInstrumentsListError;}}});}function paymentsDetails(state){$.ajax({type:'post',url:window.paymentsDetails,data:JSON.stringify({data:state.data}),contentType:'application/; charset=utf-8',async:false,success(data){if(data.response.isSuccessful){window.location.href=window.paymentInstrumentsList;}else if(!data.response.isFinal&&typeof data.response.action==='object'){checkout.createFromAction(data.action).mount('#action-container');}else{window.location.href=window.paymentInstrumentsListError;}}});}/** + * @function + * @description Initializes Adyen Checkout My Account events + */async function initializeAccountEvents(){checkoutConfiguration=window.Configuration;checkoutConfiguration.onAdditionalDetails=function(state){paymentsDetails(state);};checkoutConfiguration.session=window.sessionData;checkout=await AdyenCheckout(checkoutConfiguration);var newCard=document.getElementById('newCard');var adyenStateData;var isValid=false;var node=checkout.create('card',{hasHolderName:true,holderNameRequired:true,onChange:function(state){adyenStateData=state.data;isValid=state.isValid;}}).mount(newCard);$('#applyBtn').on('click',function(e){e.preventDefault();if(!isValid){node.showValidation();return false;}document.querySelector('#adyenStateData').value=JSON.stringify(adyenStateData);zeroAuth(adyenStateData,checkout);});}function assignPaymentMethodValue(){var adyenPaymentMethod=document.querySelector('#adyenPaymentMethodName');adyenPaymentMethod.value=document.querySelector(`#lb_${selectedMethod}`).innerHTML;}/** + * To avoid re-rendering components twice, unmounts existing components from payment methods list + */function unmountComponents(){var promises=Object.entries(componentsObj).map(function([key,val]){delete componentsObj[key];return resolveUnmount(key,val);});return Promise.all(promises);}function resolveUnmount(key,val){try{return Promise.resolve(val.node.unmount(`component_${key}`));}catch(e){// try/catch block for val.unmount +return Promise.resolve(false);}}function displaySelectedMethod(type){selectedMethod=type;resetPaymentMethod();if(['paypal','paywithgoogle','googlepay','mbway','amazonpay',...qrCodeMethods].indexOf(type)>-1){document.querySelector('#billing-submit').disabled=true;}else{document.querySelector('#billing-submit').disabled=false;}document.querySelector(`#component_${type}`).setAttribute('style','display:block');}function resetPaymentMethod(){$('.additionalFields').hide();}function showValidation(){if(componentsObj[selectedMethod]&&!componentsObj[selectedMethod].isValid){componentsObj[selectedMethod].node.showValidation();return false;}return true;}/** + * Assigns stateData value to the hidden stateData input field + * so it's sent to the backend for processing + */function validateComponents(){var stateData;if(componentsObj[selectedMethod]&&componentsObj[selectedMethod].stateData){stateData=componentsObj[selectedMethod].stateData;}else{var type=document.querySelector(`#component_${selectedMethod} .type`)?document.querySelector(`#component_${selectedMethod} .type`).value:selectedMethod;stateData={paymentMethod:{type:type}};var brandElm=document.querySelector(`#component_${selectedMethod} .brand`);if(brandElm&&brandElm.value){stateData.paymentMethod.brand=brandElm.value;}}document.querySelector('#adyenStateData').value=JSON.stringify(stateData);}/** + * Contains fallback components for payment methods that don't have an Adyen web component yet + */function getFallback(paymentMethod){var fallback={giftcard:` + + `};return fallback[paymentMethod.type];}/** + * Renders all payment methods (including card component) retrieved from Adyen session + */async function renderGenericComponent(){if(Object.keys(componentsObj).length){await unmountComponents();}checkoutConfiguration.paymentMethodsResponse=paymentMethodsResponse.paymentMethods;if(sessionsResponse.amount){checkoutConfiguration.amount=sessionsResponse.amount;checkoutConfiguration.paymentMethodsConfiguration.paypal.amount=sessionsResponse.amount;checkoutConfiguration.paymentMethodsConfiguration.amazonpay.amount=sessionsResponse.amount;setInstallments(sessionsResponse.amount);}if(sessionsResponse.countryCode){checkoutConfiguration.countryCode=sessionsResponse.countryCode;}var amazonpay=paymentMethodsResponse.paymentMethods.find(paymentMethod=>paymentMethod.type==='amazonpay');if(amazonpay){checkoutConfiguration.paymentMethodsConfiguration.amazonpay.configuration=amazonpay.configuration;}if(paymentMethodsResponse.storedPaymentMethods){for(var i=0;i{renderPaymentMethod(pm,false,sessionsResponse.imagePath);});var firstPaymentMethod=document.querySelector('input[type=radio][name=brandCode]');firstPaymentMethod.checked=true;displaySelectedMethod(firstPaymentMethod.value);}function getPaymentMethodID(isStored,paymentMethod){if(isStored){return`storedCard${paymentMethod.id}`;}if(paymentMethod.brand){// gift cards all share the same type. Brand is used to differentiate between them +return`${paymentMethod.type}_${paymentMethod.brand}`;}return paymentMethod.type;}function renderPaymentMethod(paymentMethod,storedPaymentMethodBool,path){var paymentMethodsUI=document.querySelector('#paymentMethodsList');var li=document.createElement('li');var paymentMethodID=getPaymentMethodID(storedPaymentMethodBool,paymentMethod);var isSchemeNotStored=paymentMethod.type==='scheme'&&!storedPaymentMethodBool;var paymentMethodImage=storedPaymentMethodBool?`${path}${paymentMethod.brand}.png`:`${path}${paymentMethod.type}.png`;var cardImage=`${path}card.png`;var imagePath=isSchemeNotStored?cardImage:paymentMethodImage;var label=storedPaymentMethodBool?`${paymentMethod.name} ${MASKED_CC_PREFIX}${paymentMethod.lastFour}`:`${paymentMethod.name}`;var liContents=` + + + + `;var container=document.createElement('div');li.innerHTML=liContents;li.classList.add('paymentMethod');var node=renderCheckoutComponent(storedPaymentMethodBool,checkout,paymentMethod,container,paymentMethodID);container.classList.add('additionalFields');container.setAttribute('id',`component_${paymentMethodID}`);container.setAttribute('style','display:none');li.append(container);paymentMethodsUI.append(li);if(paymentMethod.type!=='paywithgoogle'){node&&node.mount(container);}else{node.isAvailable().then(()=>{node.mount(container);}).catch(()=>{});// eslint-disable-line no-empty +}var input=document.querySelector(`#rb_${paymentMethodID}`);input.onchange=async function(event){if(document.querySelector('.adyen-checkout__qr-loader')&&qrCodeMethods.indexOf(selectedMethod)>-1||paypalTerminatedEarly){paypalTerminatedEarly=false;paymentFromComponent({cancelTransaction:true,merchantReference:document.querySelector('#merchantReference').value});}displaySelectedMethod(event.target.value);};if(paymentMethodID==='giropay'){container.innerHTML='';}if(componentsObj[paymentMethodID]&&!container.childNodes[0]&&['bcmc','scheme'].indexOf(paymentMethodID)===-1){componentsObj[paymentMethodID].isValid=true;}}function renderCheckoutComponent(storedPaymentMethodBool,checkout,paymentMethod,container,paymentMethodID){if(storedPaymentMethodBool){return createCheckoutComponent(checkout,paymentMethod,container,paymentMethodID);}var fallback=getFallback(paymentMethod);if(fallback){var template=document.createElement('template');template.innerHTML=fallback;container.append(template.content);return;}return createCheckoutComponent(checkout,paymentMethod,container,paymentMethodID);}function getPersonalDetails(){const shippingAddress=sessionsResponse.shippingAddress;return{firstName:shippingAddress.firstName,lastName:shippingAddress.lastName,telephoneNumber:shippingAddress.phone};}function createCheckoutComponent(checkout,paymentMethod,container,paymentMethodID){try{var nodeData=Object.assign(paymentMethod,{data:Object.assign(getPersonalDetails(),{personalDetails:getPersonalDetails()}),visibility:{personalDetails:'editable',billingAddress:'hidden',deliveryAddress:'hidden'}});var node=checkout.create(paymentMethod.type,nodeData);if(!componentsObj[paymentMethodID]){componentsObj[paymentMethodID]={};}componentsObj[paymentMethodID].node=node;return node;}catch(e){}// eslint-disable-line no-empty +return false;}/** + * Makes an ajax call to the controller function PaymentFromComponent. + * Used by certain payment methods like paypal + */function paymentFromComponent(data,component){$.ajax({url:window.paymentFromComponentURL,type:'post',data:JSON.stringify(data),contentType:'application/; charset=utf-8',success:function(data){if(data.result&&data.result.orderNo&&data.result.orderToken){document.querySelector('#orderToken').value=data.result.orderToken;document.querySelector('#merchantReference').value=data.result.orderNo;}if(data.result&&data.result.fullResponse&&data.result.fullResponse.action){component.handleAction(data.result.fullResponse.action);}else{document.querySelector('#paymentFromComponentStateData').value=JSON.stringify('null');$('#dwfrm_billing').trigger('submit');}}}).fail(function/* xhr, textStatus */(){});}$('#dwfrm_billing').submit(function(e){if(['paypal','mbway','amazonpay',...qrCodeMethods].indexOf(selectedMethod)>-1&&!document.querySelector('#paymentFromComponentStateData').value){e.preventDefault();var form=$(this);var url=form.attr('action');$.ajax({type:'POST',url:url,data:form.serialize(),async:false,success:function(data){formErrorsExist=data.fieldErrors;}});}});function getQRCodeConfig(){return{showPayButton:true,onSubmit:(state,component)=>{$('#dwfrm_billing').trigger('submit');if(formErrorsExist){return;}assignPaymentMethodValue();document.querySelector('#adyenStateData').value=JSON.stringify(state.data);paymentFromComponent(state.data,component);},onAdditionalDetails:(state/* , component */)=>{document.querySelector('#paymentFromComponentStateData').value=JSON.stringify(state.data);$('#dwfrm_billing').trigger('submit');}};}function getCardConfig(){return{enableStoreDetails:showStoreDetails,onBrand:function(brandObject){$('#cardType').val(brandObject.brand);},onFieldValid:function(data){if(data.endDigits){maskedCardNumber=MASKED_CC_PREFIX+data.endDigits;$('#cardNumber').val(maskedCardNumber);}},onChange:function(state){isValid=state.isValid;var methodToUpdate=state.data.paymentMethod.storedPaymentMethodId?`storedCard${state.data.paymentMethod.storedPaymentMethodId}`:selectedMethod;$('#browserInfo').val(JSON.stringify(state.data.browserInfo));componentsObj[methodToUpdate].isValid=isValid;componentsObj[methodToUpdate].stateData=state.data;}};}function getGooglePayConfig(){return{environment:window.Configuration.environment,onSubmit:()=>{assignPaymentMethodValue();document.querySelector('#billing-submit').disabled=false;document.querySelector('#billing-submit').click();},configuration:{gatewayMerchantId:window.merchantAccount},showPayButton:true,buttonColor:'white'};}function getAmazonpayConfig(){return{showPayButton:true,productType:'PayAndShip',checkoutMode:'ProcessOrder',locale:window.Configuration.locale,returnUrl:window.returnURL,addressDetails:{name:sessionsResponse.shippingAddress.firstName+' '+sessionsResponse.shippingAddress.lastName,addressLine1:sessionsResponse.shippingAddress.address1,city:sessionsResponse.shippingAddress.city,stateOrRegion:sessionsResponse.shippingAddress.city,postalCode:sessionsResponse.shippingAddress.postalCode,countryCode:sessionsResponse.shippingAddress.country,phoneNumber:sessionsResponse.shippingAddress.phone},onClick:(resolve,reject)=>{$('#dwfrm_billing').trigger('submit');if(formErrorsExist){reject();}else{assignPaymentMethodValue();resolve();}},onError:()=>{}};}function getInstallmentValues(maxValue){const values=[];for(let i=1;i<=maxValue;i+=1){values.push(i);}return values;}function setInstallments(amount){try{if(installmentLocales.indexOf(window.Configuration.locale)<0){return;}const[minAmount,numOfInstallments]=window.installments?window.installments.replace(/\[|]/g,'').split(','):[null,null];if(minAmount<=amount.value){checkoutConfiguration.paymentMethodsConfiguration.card.installmentOptions={card:{}};// eslint-disable-next-line max-len +checkoutConfiguration.paymentMethodsConfiguration.card.installmentOptions.card.values=getInstallmentValues(numOfInstallments);checkoutConfiguration.paymentMethodsConfiguration.card.showInstallmentAmounts=true;}}catch(e){}// eslint-disable-line no-empty +}/** + * @function + * @description Initializes Adyen CSE billing events + */exports.initBilling=function(){initializeBillingEvents();};exports.initAccount=function(){initializeAccountEvents();};exports.renderGenericComponent=function(){renderGenericComponent();};},{"./adyen-giving":2,"./amazon":4,"./summary":50}],2:[function(require,module,exports){let donation;function handleOnDonate(state,component){if(!state.isValid){return;}const selectedAmount=state.data.amount;const donationData={amountValue:selectedAmount.value,amountCurrency:selectedAmount.currency,orderNo:window.orderNo,pspReference:window.pspReference};$.ajax({url:window.donateURL,type:'post',data:JSON.stringify(donationData),contentType:'application/; charset=utf-8',success(){component.setStatus('success');}});}function handleOnCancel(){const adyenGiving=document.getElementById('adyenGiving');adyenGiving.style.transition='all 3s ease-in-out';adyenGiving.style.display='none';donation.unmount();}if(document.querySelector('.adyen-payment-details')&&window.adyenGivingAvailable){const adyenGivingNode=document.getElementById('donate-container');let amounts;try{amounts=JSON.parse(window.donationAmounts);}catch(e){amounts=[];}const donationConfig={amounts,backgroundUrl:window.adyenGivingBackgroundUrl,description:window.charityDescription,logoUrl:window.adyenGivingLogoUrl,name:window.charityName,url:window.charityWebsite,showCancelButton:true,onDonate:handleOnDonate,onCancel:handleOnCancel};AdyenCheckout(window.Configuration).then(checkout=>{checkout.create('donation',donationConfig).mount(adyenGivingNode);});}},{}],3:[function(require,module,exports){'use strict';var progress=require('./progress'),util=require('./util');var currentRequests=[];/** + * @function + * @description Ajax request to get json response + * @param {Boolean} async Asynchronous or not + * @param {String} url URI for the request + * @param {Object} data Name/Value pair data request + * @param {Function} callback Callback function to be called + */var getJson=function(options){options.url=util.toAbsoluteUrl(options.url);// return if no url exists or url matches a current request +if(!options.url||currentRequests[options.url]){return;}currentRequests[options.url]=true;// make the server call +$.ajax({dataType:'json',url:options.url,async:typeof options.async==='undefined'||options.async===null?true:options.async,data:options.data||{}})// success +.done(function(response){if(options.callback){options.callback(response);}})// failed +.fail(function(xhr,textStatus){if(textStatus==='parsererror'){window.alert(Resources.BAD_RESPONSE);}if(options.callback){options.callback(null);}})// executed on success or fail +.always(function(){// remove current request from hash +if(currentRequests[options.url]){delete currentRequests[options.url];}});};/** + * @function + * @description ajax request to load html response in a given container + * @param {String} url URI for the request + * @param {Object} data Name/Value pair data request + * @param {Function} callback Callback function to be called + * @param {Object} target Selector or element that will receive content + */var load=function(options){options.url=util.toAbsoluteUrl(options.url);// return if no url exists or url matches a current request +if(!options.url||currentRequests[options.url]){return;}currentRequests[options.url]=true;// make the server call +$.ajax({dataType:'html',url:util.appendParamToURL(options.url,'format','ajax'),data:options.data,xhrFields:{withCredentials:true}}).done(function(response){// success +if(options.target){$(options.target).empty().html(response);}if(options.callback){options.callback(response);}}).fail(function(xhr,textStatus){// failed +if(textStatus==='parsererror'){window.alert(Resources.BAD_RESPONSE);}options.callback(null,textStatus);}).always(function(){progress.hide();// remove current request from hash +if(currentRequests[options.url]){delete currentRequests[options.url];}});};exports.getJson=getJson;exports.load=load;},{"./progress":42,"./util":53}],4:[function(require,module,exports){if(window.amazonCheckoutSessionId){window.sessionsResponse=null;const amazonPayNode=document.getElementById('amazonContainerSG');function handleAuthorised(response){document.querySelector('#result').value=JSON.stringify({pspReference:response.fullResponse.pspReference,resultCode:response.fullResponse.resultCode,paymentMethod:response.fullResponse.paymentMethod?response.fullResponse.paymentMethod:response.fullResponse.additionalData.paymentMethod});document.querySelector('#paymentFromComponentStateData').value=JSON.stringify(response);document.querySelector('#showConfirmationForm').submit();}function handleError(){document.querySelector('#result').value=JSON.stringify({error:true});document.querySelector('#paymentFromComponentStateData').value=JSON.stringify({error:true});document.querySelector('#showConfirmationForm').submit();}function handleAmazonResponse(response,component){if(response.fullResponse&&response.fullResponse.action){component.handleAction(response.fullResponse.action);}else if(response.resultCode===window.resultCodeAuthorised){handleAuthorised(response);}else{// first try the amazon decline flow +component.handleDeclineFlow();// if this does not trigger a redirect, try the regular handleError flow +handleError();}}function paymentFromComponent(data,component){$.ajax({url:window.paymentFromComponentURL,type:'post',contentType:'application/; charset=utf-8',data:JSON.stringify(data),success(response){if(response.result&&response.result.orderNo&&response.result.orderToken){document.querySelector('#orderToken').value=response.result.orderToken;document.querySelector('#merchantReference').value=response.result.orderNo;}handleAmazonResponse(response.result,component);}});}const amazonConfig={showOrderButton:false,returnUrl:window.returnURL,configuration:{merchantId:window.amazonMerchantID,storeId:window.amazonStoreID,publicKeyId:window.amazonPublicKeyID},amazonCheckoutSessionId:window.amazonCheckoutSessionId,onSubmit:(state,component)=>{document.querySelector('#adyenStateData').value=JSON.stringify(state.data);paymentFromComponent(state.data,component);},onAdditionalDetails:state=>{state.data.paymentMethod='amazonpay';$.ajax({type:'post',url:window.paymentsDetailsURL,data:JSON.stringify({data:state.data,orderToken:document.querySelector('#orderToken').value}),contentType:'application/; charset=utf-8',success(data){if(data.response.isSuccessful){handleAuthorised(data.response);}else if(!data.response.isFinal&&typeof data.response.action==='object'){checkout.createFromAction(data.action).mount('#amazonContainerSG');}else{handleError();}}});}};async function mountAmazonPayComponent(){const checkout=await AdyenCheckout(window.Configuration);const amazonPayComponent=checkout.create('amazonpay',amazonConfig).mount(amazonPayNode);amazonPayComponent.submit();}mountAmazonPayComponent();}},{}],5:[function(require,module,exports){/** + * (c) 2009-2014 Demandware Inc. + * Subject to standard usage terms and conditions + * For all details and documentation: + * https://bitbucket.com/demandware/sitegenesis + */'use strict';var countries=require('./countries'),dialog=require('./dialog'),minicart=require('./minicart'),page=require('./page'),rating=require('./rating'),searchplaceholder=require('./searchplaceholder'),searchsuggest=require('./searchsuggest'),tooltip=require('./tooltip'),util=require('./util'),validator=require('./validator'),tls=require('./tls'),consentTracking=require('./consentTracking');// if jQuery has not been loaded, load from google cdn +if(!window.jQuery){var s=document.createElement('script');s.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');s.setAttribute('type','text/javascript');document.getElementsByTagName('head')[0].appendChild(s);}require('./jquery-ext')();require('./cookieprivacy')();consentTracking.init();require('./captcha')();function initializeEvents(){var controlKeys=['8','13','46','45','36','35','38','37','40','39'];$('body').on('keydown','textarea[data-character-limit]',function(e){var text=$.trim($(this).val()),charsLimit=$(this).data('character-limit'),charsUsed=text.length;if(charsUsed>=charsLimit&&controlKeys.indexOf(e.which.toString())<0){e.preventDefault();}}).on('change keyup mouseup','textarea[data-character-limit]',function(){var text=$.trim($(this).val()),charsLimit=$(this).data('character-limit'),charsUsed=text.length,charsRemain=charsLimit-charsUsed;if(charsRemain<0){$(this).val(text.slice(0,charsRemain));charsRemain=0;}$(this).next('div.char-count').find('.char-remain-count').html(charsRemain);});/** + * initialize search suggestions, pending the value of the site preference(enhancedSearchSuggestions) + * this will either init the legacy(false) or the beta versions(true) of the the search suggest feature. + * */var $searchContainer=$('#navigation .header-search');searchsuggest.init($searchContainer,Resources.SIMPLE_SEARCH);// add show/hide navigation elements +$('.secondary-navigation .toggle').click(function(){$(this).toggleClass('expanded').next('ul').toggle();});// add generic toggle functionality +$('.toggle').next('.toggle-content').hide();$('.toggle').click(function(){$(this).toggleClass('expanded').next('.toggle-content').toggle();});// subscribe email box +var $subscribeEmail=$('.subscribe-email');if($subscribeEmail.length>0){$subscribeEmail.focus(function(){var val=$(this.val());if(val.length>0&&val!==Resources.SUBSCRIBE_EMAIL_DEFAULT){return;// do not animate when contains non-default value +}$(this).animate({color:'#999999'},500,'linear',function(){$(this).val('').css('color','#333333');});}).blur(function(){var val=$.trim($(this.val()));if(val.length>0){return;// do not animate when contains value +}$(this).val(Resources.SUBSCRIBE_EMAIL_DEFAULT).css('color','#999999').animate({color:'#333333'},500,'linear');});}$('.privacy-policy').on('click',function(e){e.preventDefault();dialog.open({url:$(e.target).attr('href'),options:{height:600}});});$('.consent-tracking-policy').on('click',function(e){e.preventDefault();consentTracking.show();});// main menu toggle +$('.menu-toggle').on('click',function(){$('#wrapper').toggleClass('menu-active');});$('.menu-category li .menu-item-toggle').on('click',function(e){e.preventDefault();var $parentLi=$(e.target).closest('li');$parentLi.siblings('li').removeClass('active').find('.menu-item-toggle').removeClass('fa-chevron-up active').addClass('fa-chevron-right');$parentLi.toggleClass('active');$(e.target).toggleClass('fa-chevron-right fa-chevron-up active');});$('.user-account').on('click',function(e){e.preventDefault();$(this).parent('.user-info').toggleClass('active');});}/** + * @private + * @function + * @description Adds class ('js') to html for css targeting and loads js specific styles. + */function initializeDom(){// add class to html for css targeting +$('html').addClass('js');if(SitePreferences.LISTING_INFINITE_SCROLL){$('html').addClass('infinite-scroll');}// load js specific styles +util.limitCharacters();}var pages={account:require('./pages/account'),cart:require('./pages/cart'),checkout:require('./pages/checkout'),compare:require('./pages/compare'),product:require('./pages/product'),registry:require('./pages/registry'),search:require('./pages/search'),storefront:require('./pages/storefront'),wishlist:require('./pages/wishlist'),storelocator:require('./pages/storelocator')};var app={init:function(){if(document.cookie.length===0){$('
').addClass('browser-compatibility-alert').append($('

').addClass('browser-error').html(Resources.COOKIES_DISABLED)).appendTo('#browser-check');}initializeDom();initializeEvents();// init specific global components +countries.init();tooltip.init();minicart.init();validator.init();rating.init();searchplaceholder.init();// execute page specific initializations +$.extend(page,window.pageContext);var ns=page.ns;if(ns&&pages[ns]&&pages[ns].init){pages[ns].init();}// Check TLS status if indicated by site preference +if(SitePreferences.CHECK_TLS===true){tls.getUserAgent();}}};// general extension functions +(function(){String.format=function(){var s=arguments[0];var i,len=arguments.length-1;for(i=0;i\n';attributes+=''+attr.displayName+': ';attributes+=''+attr.displayValue+'\n';attributes+='';}attributes+='

  • \n';attributes+='Qty: ';attributes+=''+data.qty+'';return['
  • ','','
    '+data.name+'
    ','
      ',attributes,'
        ','
      • '].join('\n');};// hide swatches that are not selected or not part of a Product Variation Group +var hideSwatches=function(){$('.bonus-product-item:not([data-producttype="master"]) .swatches li').not('.selected').not('.variation-group-value').hide();// prevent unselecting the selected variant +$('.bonus-product-item .swatches .selected').on('click',function(){return false;});};/** + * @private + * @function + * @description Updates the summary page with the selected bonus product + */function updateSummary(){var $bonusProductList=$('#bonus-product-list');if(!selectedList.length){$bonusProductList.find('li.selected-bonus-item').remove();}else{var ulList=$bonusProductList.find('ul.selected-bonus-items').first();var i,len;for(i=0,len=selectedList.length;i=maxItems){$bonusProductList.find('.select-bonus-item').attr('disabled','disabled');}var cartItems=$bonusProductList.find('.selected-bonus-item');cartItems.each(function(){var ci=$(this);var product={uuid:ci.data('uuid'),pid:ci.data('pid'),qty:ci.find('.item-qty').text(),name:ci.find('.item-name').html(),attributes:{}};var attributes=ci.find('ul.item-attributes li');attributes.each(function(){var li=$(this);product.attributes[li.data('attributeId')]={displayName:li.children('.display-name').html(),displayValue:li.children('.display-value').html()};});selectedList.push(product);});$bonusProductList.on('click','.bonus-product-item a[href].swatchanchor',function(e){e.preventDefault();var url=this.href,$this=$(this);url=util.appendParamsToUrl(url,{'source':'bonus','format':'ajax'});$.ajax({url:url,success:function(response){$this.closest('.bonus-product-item').empty().html(response);hideSwatches();}});}).on('change','.input-text',function(){$bonusProductList.find('.select-bonus-item').removeAttr('disabled');$(this).closest('.bonus-product-form').find('.quantity-error').text('');}).on('click','.select-bonus-item',function(e){e.preventDefault();if(selectedList.length>=maxItems){$bonusProductList.find('.select-bonus-item').attr('disabled','disabled');$bonusProductList.find('.bonus-items-available').text('0');return;}var form=$(this).closest('.bonus-product-form'),detail=$(this).closest('.product-detail'),uuid=form.find('input[name="productUUID"]').val(),qtyVal=form.find('input[name="Quantity"]').val(),qty=isNaN(qtyVal)?1:+qtyVal;if(qty>maxItems){$bonusProductList.find('.select-bonus-item').attr('disabled','disabled');form.find('.quantity-error').text(Resources.BONUS_PRODUCT_TOOMANY);return;}var product={uuid:uuid,pid:form.find('input[name="pid"]').val(),qty:qty,name:detail.find('.product-name').text(),attributes:detail.find('.product-variations').data('attributes'),options:[]};var optionSelects=form.find('.product-option');optionSelects.each(function(){product.options.push({name:this.name,value:$(this).val(),display:$(this).children(':selected').first().html()});});selectedList.push(product);updateSummary();}).on('click','.remove-link',function(e){e.preventDefault();var container=$(this).closest('.selected-bonus-item');if(!container.data('uuid')){return;}var uuid=container.data('uuid');var i,len=selectedList.length;for(i=0;imaxItems){bonusProducts.bonusproducts[0].product.qty=maxItems;}// make the server call +$.ajax({type:'POST',dataType:'json',cache:false,contentType:'application/json',url:url,data:JSON.stringify(bonusProducts)}).done(function(){// success +page.refresh();}).fail(function(xhr,textStatus){// failed +if(textStatus==='parsererror'){window.alert(Resources.BAD_RESPONSE);}else{window.alert(Resources.SERVER_CONNECTION_ERROR);}}).always(function(){$bonusProduct.dialog('close');});}).on('click','#more-bonus-products',function(e){e.preventDefault();var uuid=$('#bonus-product-list').data().lineItemDetail.uuid;//get the next page of choice of bonus products +var lineItemDetail=JSON.parse($('#bonus-product-list').attr('data-line-item-detail'));lineItemDetail.pageStart=lineItemDetail.pageStart+lineItemDetail.pageSize;$('#bonus-product-list').attr('data-line-item-detail',JSON.stringify(lineItemDetail));var url=util.appendParamsToUrl(Urls.getBonusProducts,{bonusDiscountLineItemUUID:uuid,format:'ajax',lazyLoad:'true',pageStart:lineItemDetail.pageStart,pageSize:$('#bonus-product-list').data().lineItemDetail.pageSize,bonusProductsTotal:$('#bonus-product-list').data().lineItemDetail.bpTotal});$.ajax({type:'GET',cache:false,contentType:'application/json',url:url}).done(function(data){//add the new page to DOM and remove 'More' link if it is the last page of results +$('#more-bonus-products').before(data);if(lineItemDetail.pageStart+lineItemDetail.pageSize>=$('#bonus-product-list').data().lineItemDetail.bpTotal){$('#more-bonus-products').remove();}}).fail(function(xhr,textStatus){if(textStatus==='parsererror'){window.alert(Resources.BAD_RESPONSE);}else{window.alert(Resources.SERVER_CONNECTION_ERROR);}});});}var bonusProductsView={/** + * @function + * @description Open the list of bonus products selection dialog + */show:function(url){var $bonusProduct=$('#bonus-product-dialog');// create the dialog +dialog.open({target:$bonusProduct,url:url,options:{width:795,title:Resources.BONUS_PRODUCTS},callback:function(){initializeGrid();hideSwatches();}});},/** + * @function + * @description Open bonus product promo prompt dialog + */loadBonusOption:function(){var self=this,bonusDiscountContainer=document.querySelector('.bonus-discount-container');if(!bonusDiscountContainer){return;}// get the html from minicart, then trash it +var bonusDiscountContainerHtml=bonusDiscountContainer.outerHTML;bonusDiscountContainer.parentNode.removeChild(bonusDiscountContainer);dialog.open({html:bonusDiscountContainerHtml,options:{width:400,title:Resources.BONUS_PRODUCT,buttons:[{text:Resources.SELECT_BONUS_PRODUCTS,click:function(){var uuid=$('.bonus-product-promo').data('lineitemid'),url=util.appendParamsToUrl(Urls.getBonusProducts,{bonusDiscountLineItemUUID:uuid,source:'bonus',format:'ajax',lazyLoad:'false',pageStart:0,pageSize:10,bonusProductsTotal:-1});$(this).dialog('close');self.show(url);}},{text:Resources.NO_THANKS,click:function(){$(this).dialog('close');}}]},callback:function(){// show hide promo details +$('.show-promo-details').on('click',function(){$('.promo-details').toggleClass('visible');});}});}};module.exports=bonusProductsView;},{"./dialog":12,"./page":18,"./util":53}],7:[function(require,module,exports){'use strict';var dialog=require('./dialog');var util=require('./util');var SessionAttributes=window.SessionAttributes;/** + * @function captcha Used to display/control the scrim containing the simulated captcha code + **/module.exports=function(){/** + * if the session.privacy.ratelimited element is present then show the notification + * NOTE: You will probably want to replace this with a call to an actual CAPTCHA system to replace the simple one here + */if(SessionAttributes.SHOW_CAPTCHA){dialog.open({html:'

        '+Resources.ARE_YOU_HUMAN+'

        ',options:{closeOnEscape:false,dialogClass:'no-close',buttons:[{text:Resources.OK,click:function(){var url=util.appendParamsToUrl(Urls.rateLimiterReset,{format:'ajax'});$.ajax({url:url});$(this).dialog('close');}}]}});}};},{"./dialog":12,"./util":53}],8:[function(require,module,exports){'use strict';var page=require('./page'),util=require('./util'),TPromise=require('promise');var _currentCategory='',MAX_ACTIVE=6;/** + * @private + * @function + * @description Verifies the number of elements in the compare container and updates it with sequential classes for ui targeting + */function refreshContainer(){var $compareContainer=$('.compare-items');var $compareItems=$compareContainer.find('.compare-item');var numActive=$compareItems.filter('.active').length;if(numActive<2){$('#compare-items-button').attr('disabled','disabled');}else{$('#compare-items-button').removeAttr('disabled');}$compareContainer.toggle(numActive>0);}/** + * @private + * @function + * @description Adds an item to the compare container and refreshes it + */function addToList(data){// get the first compare-item not currently active +var $item=$('.compare-items .compare-item').not('.active').first(),$productTile=$('#'+data.uuid);if($item.length===0){if($productTile.length>0){$productTile.find('.compare-check')[0].checked=false;}window.alert(Resources.COMPARE_ADD_FAIL);return;}// if already added somehow, return +if($('[data-uuid="'+data.uuid+'"]').length>0){return;}// set as active item +$item.addClass('active').attr('data-uuid',data.uuid).attr('data-itemid',data.itemid).data('uuid',data.uuid).data('itemid',data.itemid).append($(data.img).clone().addClass('compare-item-image'));}/** + * @private + * @function + * description Removes an item from the compare container and refreshes it + */function removeFromList($item){if($item.length===0){return;}// remove class, data and id from item +$item.removeClass('active').removeAttr('data-uuid').removeAttr('data-itemid').data('uuid','').data('itemid','')// remove the image +.find('.compare-item-image').remove();}function addProductAjax(args){var promise=new TPromise(function(resolve,reject){$.ajax({url:Urls.compareAdd,data:{pid:args.itemid,category:_currentCategory},dataType:'json'}).done(function(response){if(!response||!response.success){reject(new Error(Resources.COMPARE_ADD_FAIL));}else{resolve(response);}}).fail(function(jqxhr,status,err){reject(new Error(err));});});return promise;}function removeProductAjax(args){var promise=new TPromise(function(resolve,reject){$.ajax({url:Urls.compareRemove,data:{pid:args.itemid,category:_currentCategory},dataType:'json'}).done(function(response){if(!response||!response.success){reject(new Error(Resources.COMPARE_REMOVE_FAIL));}else{resolve(response);}}).fail(function(jqxhr,status,err){reject(new Error(err));});});return promise;}function shiftImages(){return new TPromise(function(resolve){var $items=$('.compare-items .compare-item');$items.each(function(i,item){var $item=$(item);// last item +if(i===$items.length-1){return removeFromList($item);}var $next=$items.eq(i+1);if($next.hasClass('active')){// remove its own image +$next.find('.compare-item-image').detach().appendTo($item);$item.addClass('active').attr('data-uuid',$next.data('uuid')).attr('data-itemid',$next.data('itemid')).data('uuid',$next.data('uuid')).data('itemid',$next.data('itemid'));}});resolve();});}/** + * @function + * @description Adds product to the compare table + */function addProduct(args){var promise;var $items=$('.compare-items .compare-item');var $cb=$(args.cb);var numActive=$items.filter('.active').length;if(numActive===MAX_ACTIVE){if(!window.confirm(Resources.COMPARE_CONFIRMATION)){$cb[0].checked=false;return;}// remove product using id +var $firstItem=$items.first();promise=removeItem($firstItem).then(function(){return shiftImages();});}else{promise=TPromise.resolve(0);}return promise.then(function(){return addProductAjax(args).then(function(){addToList(args);if($cb&&$cb.length>0){$cb[0].checked=true;}refreshContainer();});}).then(null,function(){if($cb&&$cb.length>0){$cb[0].checked=false;}});}/** + * @function + * @description Removes product from the compare table + * @param {object} args - the arguments object should have the following properties: itemid, uuid and cb (checkbox) + */function removeProduct(args){var $cb=args.cb?$(args.cb):null;return removeProductAjax(args).then(function(){var $item=$('[data-uuid="'+args.uuid+'"]');removeFromList($item);if($cb&&$cb.length>0){$cb[0].checked=false;}refreshContainer();},function(){if($cb&&$cb.length>0){$cb[0].checked=true;}});}function removeItem($item){var uuid=$item.data('uuid'),$productTile=$('#'+uuid);return removeProduct({itemid:$item.data('itemid'),uuid:uuid,cb:$productTile.length===0?null:$productTile.find('.compare-check')});}/** + * @private + * @function + * @description Initializes the DOM-Object of the compare container + */function initializeDom(){var $compareContainer=$('.compare-items');_currentCategory=$compareContainer.data('category')||'';var $active=$compareContainer.find('.compare-item').filter('.active');$active.each(function(){var $productTile=$('#'+$(this).data('uuid'));if($productTile.length===0){return;}$productTile.find('.compare-check')[0].checked=true;});// set container state +refreshContainer();}/** + * @private + * @function + * @description Initializes the events on the compare container + */function initializeEvents(){// add event to buttons to remove products +$('.compare-item').on('click','.compare-item-remove',function(){removeItem($(this).closest('.compare-item'));});// Button to go to compare page +$('#compare-items-button').on('click',function(){page.redirect(util.appendParamToURL(Urls.compareShow,'category',_currentCategory));});// Button to clear all compared items +// rely on refreshContainer to take care of hiding the container +$('#clear-compared-items').on('click',function(){$('.compare-items .active').each(function(){removeItem($(this));});});}exports.init=function(){initializeDom();initializeEvents();};exports.addProduct=addProduct;exports.removeProduct=removeProduct;},{"./page":18,"./util":53,"promise":70}],9:[function(require,module,exports){'use strict';var dialog=require('./dialog');var util=require('./util');/** + * @function getConsent Used to display/control of the modal containing the consent management message + **/function getConsent(){dialog.open({url:Urls.consentTracking,options:{closeOnEscape:false,dialogClass:'no-close',buttons:[{text:Resources.TRACKING_CONSENT,click:function(){$(this).dialog('close');$.ajax({type:'GET',url:util.appendParamToURL(Urls.consentTrackingSetSession,'consentTracking',true),success:function(){showPrivacyDialog();},error:function(){showPrivacyDialog();}});}},{text:Resources.TRACKING_NO_CONSENT,click:function(){$(this).dialog('close');$.ajax({type:'GET',url:util.appendParamToURL(Urls.consentTrackingSetSession,'consentTracking',false),success:function(){showPrivacyDialog();},error:function(){showPrivacyDialog();}});}}]}});}function enablePrivacyCookies(){if(document.cookie.indexOf('dw=1')<0){document.cookie='dw=1; path=/';}if(document.cookie.indexOf('dw_cookies_accepted')<0){document.cookie='dw_cookies_accepted=1; path=/';}}function showPrivacyDialog(){if(SitePreferences.COOKIE_HINT===true&&document.cookie.indexOf('dw_cookies_accepted')<0){// check for privacy policy page +if($('.privacy-policy').length===0){dialog.open({url:Urls.cookieHint,options:{closeOnEscape:false,dialogClass:'no-close',buttons:[{text:Resources.I_AGREE,click:function(){$(this).dialog('close');enablePrivacyCookies();}}]}});}}else{// Otherwise, we don't need to show the asset, just enable the cookies +enablePrivacyCookies();}}var consentTracking={init:function(){if(consent==null&&SitePreferences.CONSENT_TRACKING_HINT){// eslint-disable-line no-undef +getConsent();}if(consent!=null&&SitePreferences.CONSENT_TRACKING_HINT){// eslint-disable-line no-undef +showPrivacyDialog();}},show:function(){getConsent();}};module.exports=consentTracking;},{"./dialog":12,"./util":53}],10:[function(require,module,exports){'use strict';var dialog=require('./dialog');/** + * @function cookieprivacy Used to display/control the scrim containing the cookie privacy code + **/module.exports=function(){/** + * If we have not accepted cookies AND we're not on the Privacy Policy page, then show the notification + * NOTE: You will probably want to adjust the Privacy Page test to match your site's specific privacy / cookie page + */if(!SitePreferences.CONSENT_TRACKING_HINT&&SitePreferences.COOKIE_HINT===true&&document.cookie.indexOf('dw_cookies_accepted')<0){// check for privacy policy page +if($('.privacy-policy').length===0){dialog.open({url:Urls.cookieHint,options:{closeOnEscape:false,dialogClass:'no-close',buttons:[{text:Resources.I_AGREE,click:function(){$(this).dialog('close');enableCookies();}}]}});}}else{// Otherwise, we don't need to show the asset, just enable the cookies +enableCookies();}function enableCookies(){if(document.cookie.indexOf('dw=1')<0){document.cookie='dw=1; path=/';}if(document.cookie.indexOf('dw_cookies_accepted')<0){document.cookie='dw_cookies_accepted=1; path=/';}}};},{"./dialog":12}],11:[function(require,module,exports){'use strict';exports.init=function init(){$('.country-selector .current-country').on('click',function(){$('.country-selector .selector').toggleClass('active');$(this).toggleClass('selector-active');});// set currency first before reload +$('.country-selector .selector .locale').on('click',function(e){e.preventDefault();var url=this.href;var currency=this.getAttribute('data-currency');$.ajax({dataType:'json',url:Urls.setSessionCurrency,data:{format:'ajax',currencyMnemonic:currency}}).done(function(response){if(!response.success){throw new Error('Unable to set currency');}window.location.href=url;});});};},{}],12:[function(require,module,exports){'use strict';var ajax=require('./ajax'),util=require('./util'),_=require('lodash'),imagesLoaded=require('imagesloaded');var dialog={/** + * @function + * @description Appends a dialog to a given container (target) + * @param {Object} params params.target can be an id selector or an jquery object + */create:function(params){var $target,id;if(_.isString(params.target)){if(params.target.charAt(0)==='#'){$target=$(params.target);}else{$target=$('#'+params.target);}}else if(params.target instanceof jQuery){$target=params.target;}else{$target=$('#dialog-container');}// if no element found, create one +if($target.length===0){if($target.selector&&$target.selector.charAt(0)==='#'){id=$target.selector.substr(1);$target=$('
        ').attr('id',id).addClass('dialog-content').appendTo('body');}}// create the dialog +this.$container=$target;this.$container.dialog(_.merge({},this.settings,params.options||{}));},/** + * @function + * @description Opens a dialog using the given url (params.url) or html (params.html) + * @param {Object} params + * @param {Object} params.url should contain the url + * @param {String} params.html contains the html of the dialog content + */open:function(params){// close any open dialog +this.close();this.create(params);this.replace(params);},/** + * @description populate the dialog with html content, then open it + **/openWithContent:function(params){var content,position,callback;if(!this.$container){return;}content=params.content||params.html;if(!content){return;}this.$container.empty().html(content);if(!this.$container.dialog('isOpen')){this.$container.dialog('open');}if(params.options){position=params.options.position;}if(!position){position=this.settings.position;}imagesLoaded(this.$container).on('done',function(){this.$container.dialog('option','position',position);}.bind(this));callback=typeof params.callback==='function'?params.callback:function(){};callback();},/** + * @description Replace the content of current dialog + * @param {object} params + * @param {string} params.url - If the url property is provided, an ajax call is performed to get the content to replace + * @param {string} params.html - If no url property is provided, use html provided to replace + */replace:function(params){if(!this.$container){return;}if(params.url){params.url=util.appendParamToURL(params.url,'format','ajax');ajax.load({url:params.url,data:params.data,callback:function(response){params.content=response;this.openWithContent(params);}.bind(this)});}else if(params.html){this.openWithContent(params);}},/** + * @function + * @description Closes the dialog + */close:function(){if(!this.$container){return;}this.$container.dialog('close');},exists:function(){return this.$container&&this.$container.length>0;},isActive:function(){return this.exists()&&this.$container.children.length>0;},settings:{autoOpen:false,height:'auto',modal:true,overlay:{opacity:0.5,background:'black'},resizable:false,title:'',width:'800',close:function(){$(this).dialog('close');},position:{my:'center',at:'center',of:window,collision:'flipfit'}}};module.exports=dialog;},{"./ajax":3,"./util":53,"imagesloaded":67,"lodash":68}],13:[function(require,module,exports){'use strict';var ajax=require('./ajax'),util=require('./util');/** + * @function + * @description Load details to a given gift certificate + * @param {String} id The ID of the gift certificate + * @param {Function} callback A function to called + */exports.checkBalance=function(id,callback){// load gift certificate details +var url=util.appendParamToURL(Urls.giftCardCheckBalance,'giftCertificateID',id);ajax.getJson({url:url,callback:callback});};},{"./ajax":3,"./util":53}],14:[function(require,module,exports){'use strict';var ajax=require('./ajax'),minicart=require('./minicart'),util=require('./util');var setAddToCartHandler=function(e){e.preventDefault();var form=$(this).closest('form');var options={url:util.ajaxUrl(form.attr('action')),method:'POST',cache:false,data:form.serialize()};$.ajax(options).done(function(response){if(response.success){ajax.load({url:Urls.minicartGC,data:{lineItemId:response.result.lineItemId},callback:function(response){minicart.show(response);form.find('input,textarea').val('');}});}else{form.find('span.error').hide();for(var id in response.errors.FormErrors){var $errorEl=$('#'+id).addClass('error').removeClass('valid').next('.error');if(!$errorEl||$errorEl.length===0){$errorEl=$('');$('#'+id).after($errorEl);}$errorEl.text(response.errors.FormErrors[id].replace(/\\'/g,'\'')).show();}}}).fail(function(xhr,textStatus){// failed +if(textStatus==='parsererror'){window.alert(Resources.BAD_RESPONSE);}else{window.alert(Resources.SERVER_CONNECTION_ERROR);}});};exports.init=function(){$('#AddToBasketButton').on('click',setAddToCartHandler);};},{"./ajax":3,"./minicart":17,"./util":53}],15:[function(require,module,exports){'use strict';// jQuery extensions +module.exports=function(){// params +// toggleClass - required +// triggerSelector - optional. the selector for the element that triggers the event handler. defaults to the child elements of the list. +// eventName - optional. defaults to 'click' +$.fn.toggledList=function(options){if(!options.toggleClass){return this;}var list=this;return list.on(options.eventName||'click',options.triggerSelector||list.children(),function(e){e.preventDefault();var classTarget=options.triggerSelector?$(this).parent():$(this);classTarget.toggleClass(options.toggleClass);// execute callback if exists +if(options.callback){options.callback();}});};$.fn.syncHeight=function(){var arr=$.makeArray(this);arr.sort(function(a,b){return $(a).height()-$(b).height();});return this.height($(arr[arr.length-1]).height());};};},{}],16:[function(require,module,exports){'use strict';var dialog=require('./dialog'),page=require('./page'),validator=require('./validator');var login={/** + * @private + * @function + * @description init events for the loginPage + */init:function(){//o-auth binding for which icon is clicked +$('.oAuthIcon').bind('click',function(){$('#OAuthProvider').val(this.id);});//toggle the value of the rememberme checkbox +$('#dwfrm_login_rememberme').bind('change',function(){if($('#dwfrm_login_rememberme').attr('checked')){$('#rememberme').val('true');}else{$('#rememberme').val('false');}});$('#password-reset').on('click',function(e){e.preventDefault();dialog.open({url:$(e.target).attr('href'),options:{open:function(){validator.init();var $requestPasswordForm=$('[name$="_requestpassword"]');var $submit=$requestPasswordForm.find('[name$="_requestpassword_send"]');$($submit).on('click',function(e){if(!$requestPasswordForm.valid()){return;}e.preventDefault();var data=$requestPasswordForm.serialize();// add form action to data +data+='&'+$submit.attr('name')+'=';// make sure the server knows this is an ajax request +if(data.indexOf('ajax')===-1){data+='&format=ajax';}$.ajax({type:'POST',url:$requestPasswordForm.attr('action'),data:data,success:function(response){if(typeof response==='object'&&!response.success&&response.error===Resources.CSRF_TOKEN_MISMATCH){page.redirect(Urls.csrffailed);}else if(typeof response==='string'){dialog.$container.html(response);}},failure:function(){dialog.$container.html('

        '+Resources.SERVER_ERROR+'

        ');}});});}}});});}};module.exports=login;},{"./dialog":12,"./page":18,"./validator":54}],17:[function(require,module,exports){'use strict';var util=require('./util'),bonusProductsView=require('./bonus-products-view');var timer={id:null,clear:function(){if(this.id){window.clearTimeout(this.id);delete this.id;}},start:function(duration,callback){this.id=setTimeout(callback,duration);}};var minicart={init:function(){this.$el=$('#mini-cart');this.$content=this.$el.find('.mini-cart-content');$('.mini-cart-product').eq(0).find('.mini-cart-toggle').addClass('fa-caret-down');$('.mini-cart-product').not(':first').addClass('collapsed').find('.mini-cart-toggle').addClass('fa-caret-right');$('.mini-cart-toggle').on('click',function(){$(this).toggleClass('fa-caret-down fa-caret-right');$(this).closest('.mini-cart-product').toggleClass('collapsed');});// events +this.$el.find('.mini-cart-total').on('mouseenter',function(){if(this.$content.not(':visible')){this.slide();}}.bind(this));this.$content.on('mouseenter',function(){timer.clear();}).on('mouseleave',function(){timer.clear();timer.start(30,this.close.bind(this));}.bind(this));},/** + * @function + * @description Shows the given content in the mini cart + * @param {String} A HTML string with the content which will be shown + */show:function(html){this.$el.html(html);util.scrollBrowser(0);this.init();this.slide();bonusProductsView.loadBonusOption();},/** + * @function + * @description Slides down and show the contents of the mini cart + */slide:function(){timer.clear();// show the item +this.$content.slideDown('slow');// after a time out automatically close it +timer.start(6000,this.close.bind(this));},/** + * @function + * @description Closes the mini cart with given delay + * @param {Number} delay The delay in milliseconds + */close:function(delay){timer.clear();this.$content.slideUp(delay);}};module.exports=minicart;},{"./bonus-products-view":6,"./util":53}],18:[function(require,module,exports){'use strict';var util=require('./util');var page={title:'',type:'',params:util.getQueryStringParams(window.location.search.substr(1)),redirect:function(newURL){setTimeout(function(){window.location.href=newURL;},0);},refresh:function(){setTimeout(function(){window.location.assign(window.location.href);},500);}};module.exports=page;},{"./util":53}],19:[function(require,module,exports){'use strict';var giftcert=require('../giftcert'),tooltip=require('../tooltip'),util=require('../util'),dialog=require('../dialog'),page=require('../page'),login=require('../login'),validator=require('../validator'),adyenCheckout=require('../adyen-checkout');/** + * @function + * @description Initializes the events on the address form (apply, cancel, delete) + * @param {Element} form The form which will be initialized + */function initializeAddressForm(){var $form=$('#edit-address-form');$form.find('input[name="format"]').remove();tooltip.init();//$("").attr({type:"hidden", name:"format", value:"ajax"}).appendTo(form); +$form.on('click','.apply-button',function(e){e.preventDefault();if(!$form.valid()){return false;}var url=util.appendParamToURL($form.attr('action'),'format','ajax');var applyName=$form.find('.apply-button').attr('name');var options={url:url,data:$form.serialize()+'&'+applyName+'=x',type:'POST'};$.ajax(options).done(function(data){if(typeof data!=='string'){if(data.success){dialog.close();page.refresh();}else if(data.error){page.redirect(Urls.csrffailed);}else{window.alert(data.message);return false;}}else{$('#dialog-container').html(data);account.init();tooltip.init();}});}).on('click','.cancel-button, .close-button',function(e){e.preventDefault();dialog.close();}).on('click','.delete-button',function(e){e.preventDefault();if(window.confirm(String.format(Resources.CONFIRM_DELETE,Resources.TITLE_ADDRESS))){var url=util.appendParamsToUrl(Urls.deleteAddress,{AddressID:$form.find('#addressid').val(),format:'ajax'});$.ajax({url:url,method:'POST',dataType:'json'}).done(function(data){if(data.status.toLowerCase()==='ok'){dialog.close();page.refresh();}else if(data.message.length>0){window.alert(data.message);return false;}else{dialog.close();page.refresh();}});}});validator.init();}/** + * @private + * @function + * @description Toggles the list of Orders + */function toggleFullOrder(){$('.order-items').find('li.hidden:first').prev('li').append('View All').children('.toggle').click(function(){$(this).parent().siblings('li.hidden').show();$(this).remove();});}/** + * @private + * @function + * @description Binds the events on the address form (edit, create, delete) + */function initAddressEvents(){var addresses=$('#addresses');if(addresses.length===0){return;}addresses.on('click','.address-edit, .address-create',function(e){e.preventDefault();dialog.open({url:this.href,options:{open:initializeAddressForm}});}).on('click','.delete',function(e){e.preventDefault();if(window.confirm(String.format(Resources.CONFIRM_DELETE,Resources.TITLE_ADDRESS))){$.ajax({url:util.appendParamToURL($(this).attr('href'),'format','ajax'),dataType:'json'}).done(function(data){if(data.status.toLowerCase()==='ok'){page.redirect(Urls.addressesList);}else if(data.message.length>0){window.alert(data.message);}else{page.refresh();}});}});}/** + * @private + * @function + * @description Binds the events of the payment methods list (delete card) + */function initPaymentEvents(){$('.add-card').on('click',function(e){e.preventDefault();dialog.open({url:$(e.target).attr('href'),options:{open:initializePaymentForm}});});var paymentList=$('.payment-list');if(paymentList.length===0){return;}util.setDeleteConfirmation(paymentList,String.format(Resources.CONFIRM_DELETE,Resources.TITLE_CREDITCARD));$('form[name="payment-remove"]').on('submit',function(e){e.preventDefault();// override form submission in order to prevent refresh issues +var button=$(this).find('.delete');$('').attr({type:'hidden',name:button.attr('name'),value:button.attr('value')||'delete card'}).appendTo($(this));var data=$(this).serialize();$.ajax({type:'POST',url:$(this).attr('action'),data:data}).done(function(){page.redirect(Urls.paymentsList);});});}function initializePaymentForm(){$('#CreditCardForm').on('click','.cancel-button',function(e){e.preventDefault();dialog.close();});if(SitePreferences.ADYEN_SF_ENABLED){adyenCheckout.initAccount();}}/** + * @private + * @function + * @description Binds the events of the order, address and payment pages + */function initializeEvents(){toggleFullOrder();initAddressEvents();initPaymentEvents();login.init();}var account={init:function(){initializeEvents();giftcert.init();},initCartLogin:function(){login.init();}};module.exports=account;},{"../adyen-checkout":1,"../dialog":12,"../giftcert":14,"../login":16,"../page":18,"../tooltip":52,"../util":53,"../validator":54}],20:[function(require,module,exports){'use strict';var account=require('./account'),bonusProductsView=require('../bonus-products-view'),quickview=require('../quickview'),cartStoreInventory=require('../storeinventory/cart');/** + * @private + * @function + * @description Binds events to the cart page (edit item's details, bonus item's actions, coupon code entry) + */function initializeEvents(){$('#cart-table').on('click','.item-edit-details a',function(e){e.preventDefault();quickview.show({url:e.target.href,source:'cart'});}).on('click','.bonus-item-actions a, .item-details .bonusproducts a',function(e){e.preventDefault();bonusProductsView.show(this.href);});// override enter key for coupon code entry +$('form input[name$="_couponCode"]').on('keydown',function(e){if(e.which===13&&$(this).val().length===0){return false;}});//to prevent multiple submissions of the form when removing a product from the cart +var removeItemEvent=false;$('button[name$="deleteProduct"]').on('click',function(e){if(removeItemEvent){e.preventDefault();}else{removeItemEvent=true;}});}exports.init=function(){initializeEvents();if(SitePreferences.STORE_PICKUP){cartStoreInventory.init();}account.initCartLogin();};},{"../bonus-products-view":6,"../quickview":43,"../storeinventory/cart":47,"./account":19}],21:[function(require,module,exports){'use strict';var util=require('../../util');var shipping=require('./shipping');/** + * @function + * @description Selects the first address from the list of addresses + */exports.init=function(){var $form=$('.address');// select address from list +$('select[name$="_addressList"]',$form).on('change',function(){var selected=$(this).children(':selected').first();var selectedAddress=$(selected).data('address');if(!selectedAddress){return;}util.fillAddressFields(selectedAddress,$form);shipping.updateShippingMethodList();// re-validate the form +$form.validate().form();});};},{"../../util":53,"./shipping":26}],22:[function(require,module,exports){/*eslint-disable */'use strict';var ajax=require('../../ajax'),formPrepare=require('./formPrepare'),giftcard=require('../../giftcard'),util=require('../../util'),adyenCheckout=require('../../adyen-checkout');/** + * @function + * @description Fills the Credit Card form with the passed data-parameter and clears the former cvn input + * @param {Object} data The Credit Card data (holder, type, masked number, expiration month/year) + */function setCCFields(data){var $creditCard=$('[data-method="CREDIT_CARD"]');$creditCard.find('input[name$="creditCard_owner"]').val(data.holder).trigger('change');$creditCard.find('select[name$="_type"]').val(data.type).trigger('change');$creditCard.find('input[name*="_creditCard_number"]').val(data.maskedNumber).trigger('change');$creditCard.find('[name$="_month"]').val(data.expirationMonth).trigger('change');$creditCard.find('[name$="_year"]').val(data.expirationYear).trigger('change');$creditCard.find('input[name$="_cvn"]').val('').trigger('change');$creditCard.find('[name$="creditCard_selectedCardID"]').val(data.selectedCardID).trigger('change');}/** + * @function + * @description Updates the credit card form with the attributes of a given card + * @param {String} cardID the credit card ID of a given card + */function populateCreditCardForm(cardID){// load card details +var url=util.appendParamToURL(Urls.billingSelectCC,'creditCardUUID',cardID);ajax.getJson({url:url,callback:function(data){if(!data){window.alert(Resources.CC_LOAD_ERROR);return false;}setCCFields(data);}});}$('input[name="brandCode"]').on('change',function(e){$("#dwfrm_adyPaydata_issuer").val("");$('.checkoutComponent').hide();$('#component_'+$(this).val()).show();});/** + * @function + * @description Changes the payment method form depending on the passed paymentMethodID + * @param {String} paymentMethodID the ID of the payment method, to which the payment method form should be changed to + */function updatePaymentMethod(paymentMethodID){var $paymentMethods=$('.payment-method');$paymentMethods.removeClass('payment-method-expanded');var $selectedPaymentMethod=$paymentMethods.filter('[data-method="'+paymentMethodID+'"]');if($selectedPaymentMethod.length===0){$selectedPaymentMethod=$('[data-method="Custom"]');}$selectedPaymentMethod.addClass('payment-method-expanded');// ensure checkbox of payment method is checked +$('input[name$="_selectedPaymentMethodID"]').removeAttr('checked');$('input[value='+paymentMethodID+']').prop('checked','checked');formPrepare.validateForm();}/** + * @function + * @description Changes the payment type or issuerId of the selected payment method + * @param {String, Boolean} value of payment type or issuerId and a test value to see which one it is, to which the payment type or issuerId should be changed to + */function updatePaymentType(selectedPayType,issuerType){if(issuerType){$('#dwfrm_adyPaydata_issuer').val(selectedPayType);}else{$('input[name="brandCode"]').removeAttr('checked');$('input[value='+selectedPayType+']').prop('checked','checked');}// if the payment type has hidden fields reveal it +$('#component_'+selectedPayType).show();formPrepare.validateForm();}/** + * @function + * @description Adyen - Initializes the visibility of HPP fields + */function initializeHPPFields(){if($('[name="brandCode"]:checked').hasClass('openInvoice')){$('.additionalfield').hide().find('input').val('');$('.additionalfield.'+$('.checkout-billing').find('select.country').val()).show();}else{$('.additionalfield').hide().find('input').val('');}}/** + * @function + * @description loads billing address, Gift Certificates, Coupon and Payment methods + */exports.init=function(){var $checkoutForm=$('.checkout-billing');var $addGiftCert=$('#add-giftcert');var $giftCertCode=$('input[name$="_giftCertCode"]');var $addCoupon=$('#add-coupon');var $couponCode=$('input[name$="_couponCode"]');var $selectPaymentMethod=$('.payment-method-options');var selectedPaymentMethod=$selectPaymentMethod.find(':checked').val();var $payType=$('[name="brandCode"]');var $issuer=$('.issuer');var selectedPayType=$payType.find(':checked').val();formPrepare.init({formSelector:'form[id$="billing"]',continueSelector:'[name$="billing_save"]'});// default payment method to 'CREDIT_CARD' +updatePaymentMethod(selectedPaymentMethod?selectedPaymentMethod:'CREDIT_CARD');$selectPaymentMethod.on('click','input[type="radio"]',function(){updatePaymentMethod($(this).val());if($(this).val()=='Adyen'&&$payType.length>0){//set payment type of Adyen to the first one +updatePaymentType(selectedPayType?selectedPayType:$payType[0].value,false);}else{$payType.removeAttr('checked');}});$issuer.on('change',function(){updatePaymentType($(this).val(),true);});$payType.on('change',function(){$('#selectedIssuer').val("");$issuer.hide();$('.checkoutComponent').hide();$('#component_'+$(this).val()).show();if($(this).siblings(".issuer").length>0){$('#selectedIssuer').val($(this).siblings(".issuer").val());$(this).siblings('.issuer').show();}});// select credit card from list +$('#creditCardList').on('change',function(){var cardUUID=$(this).val();if(!cardUUID){return;}populateCreditCardForm(cardUUID);// remove server side error +$('.required.error').removeClass('error');$('.error-message').remove();});$('#check-giftcert').on('click',function(e){e.preventDefault();var $balance=$('.balance');if($giftCertCode.length===0||$giftCertCode.val().length===0){var error=$balance.find('span.error');if(error.length===0){error=$('').addClass('error').appendTo($balance);}error.html(Resources.GIFT_CERT_MISSING);return;}giftcard.checkBalance($giftCertCode.val(),function(data){if(!data||!data.giftCertificate){$balance.html(Resources.GIFT_CERT_INVALID).removeClass('success').addClass('error');return;}$balance.html(Resources.GIFT_CERT_BALANCE+' '+data.giftCertificate.balance).removeClass('error').addClass('success');});});$addGiftCert.on('click',function(e){e.preventDefault();var code=$giftCertCode.val(),$error=$checkoutForm.find('.giftcert-error');if(code.length===0){$error.html(Resources.GIFT_CERT_MISSING);return;}var url=util.appendParamsToUrl(Urls.redeemGiftCert,{giftCertCode:code,format:'ajax'});$.getJSON(url,function(data){var fail=false;var msg='';if(!data){msg=Resources.BAD_RESPONSE;fail=true;}else if(!data.success){msg=data.message.split('<').join('<').split('>').join('>');fail=true;}if(fail){$error.html(msg);return;}else{window.location.assign(Urls.billing);}});});$addCoupon.on('click',function(e){e.preventDefault();var $error=$checkoutForm.find('.coupon-error'),code=$couponCode.val();if(code.length===0){$error.html(Resources.COUPON_CODE_MISSING);return;}var url=util.appendParamsToUrl(Urls.addCoupon,{couponCode:code,format:'ajax'});$.getJSON(url,function(data){var fail=false;var msg='';if(!data){msg=Resources.BAD_RESPONSE;fail=true;}else if(!data.success){msg=data.message.split('<').join('<').split('>').join('>');fail=true;}if(fail){$error.html(msg);return;}//basket check for displaying the payment section, if the adjusted total of the basket is 0 after applying the coupon +//this will force a page refresh to display the coupon message based on a parameter message +if(data.success&&data.baskettotal===0){window.location.assign(Urls.billing);}});});// trigger events on enter +$couponCode.on('keydown',function(e){if(e.which===13){e.preventDefault();$addCoupon.click();}});$giftCertCode.on('keydown',function(e){if(e.which===13){e.preventDefault();$addGiftCert.click();}});if(SitePreferences.ADYEN_SF_ENABLED){adyenCheckout.initBilling();}};},{"../../adyen-checkout":1,"../../ajax":3,"../../giftcard":13,"../../util":53,"./formPrepare":23}],23:[function(require,module,exports){'use strict';var _=require('lodash');var $form,$continue,$requiredInputs,validator;var hasEmptyRequired=function(){// filter out only the visible fields +var requiredValues=$requiredInputs.filter(':visible').map(function(){return $(this).val();});return _(requiredValues).includes('');};var validateForm=function(){// only validate form when all required fields are filled to avoid +// throwing errors on empty form +if(!validator){return;}if(!hasEmptyRequired()){if(validator.form()){$continue.removeAttr('disabled');}}else{$continue.attr('disabled','disabled');}};var validateEl=function(){if($(this).val()===''){$continue.attr('disabled','disabled');}else{// enable continue button on last required field that is valid +// only validate single field +if(validator.element(this)&&!hasEmptyRequired()){$continue.removeAttr('disabled');}else{$continue.attr('disabled','disabled');}}};var init=function(opts){if(!opts.formSelector||!opts.continueSelector){throw new Error('Missing form and continue action selectors.');}$form=$(opts.formSelector);$continue=$(opts.continueSelector);validator=$form.validate();$requiredInputs=$('.required',$form).find(':input');validateForm();// start listening +$requiredInputs.on('change',validateEl);$requiredInputs.filter('input').on('keyup',_.debounce(validateEl,200));};exports.init=init;exports.validateForm=validateForm;exports.validateEl=validateEl;},{"lodash":68}],24:[function(require,module,exports){'use strict';var address=require('./address'),billing=require('./billing'),multiship=require('./multiship'),shipping=require('./shipping');/** + * @function Initializes the page events depending on the checkout stage (shipping/billing) + */exports.init=function(){address.init();if($('.checkout-shipping').length>0){shipping.init();}else if($('.checkout-multi-shipping').length>0){multiship.init();}else{billing.init();}//if on the order review page and there are products that are not available diable the submit order button +if($('.order-summary-footer').length>0){if($('.notavailable').length>0){$('.order-summary-footer .submit-order .button-fancy-large').attr('disabled','disabled');}}};},{"./address":21,"./billing":22,"./multiship":25,"./shipping":26}],25:[function(require,module,exports){'use strict';var address=require('./address'),formPrepare=require('./formPrepare'),dialog=require('../../dialog'),util=require('../../util'),validator=require('../../validator');/** + * @function + * @description Initializes gift message box for multiship shipping, the message box starts off as hidden and this will display it if the radio button is checked to yes, also added event handler to listen for when a radio button is pressed to display the message box + */function initMultiGiftMessageBox(){$.each($('.item-list'),function(){var $this=$(this);var $giftMessage=$this.find('.gift-message-text');//handle initial load +$giftMessage.toggleClass('hidden',$('input[name$="_isGift"]:checked',this).val()!=='true');//set event listeners +$this.on('change',function(){$giftMessage.toggleClass('hidden',$('input[name$="_isGift"]:checked',this).val()!=='true');});});}/** + * @function + * @description capture add edit adddress form events + */function addEditAddress(target){var $addressForm=$('form[name$="multishipping_editAddress"]'),$addressDropdown=$addressForm.find('select[name$=_addressList]'),$addressList=$addressForm.find('.address-list'),add=true,originalUUID,resetOptionValue=false,selectedAddressUUID=$(target).parent().siblings('.select-address').val();$addressDropdown.on('change',function(e){e.preventDefault();var selectedAddress=$addressList.find('select').val();if(selectedAddress!=='newAddress'){selectedAddress=$.grep($addressList.data('addresses'),function(add){return add.UUID===selectedAddress;})[0];add=false;resetOptionValue=false;// proceed to fill the form with the selected address +util.fillAddressFields(selectedAddress,$addressForm);}else if(selectedAddress==='newAddress'){add=true;resetOptionValue=true;$addressForm.find('.input-text, .input-select').val('');}else{//reset the form if the value of the option is not a UUID +$addressForm.find('.input-text, .input-select').val('');}});$addressForm.on('click','.cancel',function(e){e.preventDefault();dialog.close();});$addressForm.on('submit',function(e){e.preventDefault();if(!$addressForm.valid()){return false;}$.getJSON(Urls.addEditAddress,$addressForm.serialize(),function(response){if(!response.success){$('#multiaddresserror').html(Resources.COULD_NOT_SAVE_ADDRESS);return;}$('#multiaddresserror').toggleClass('hidden',response.success);var address=response.address,$shippingAddress=$(target).closest('.shippingaddress'),$select=$shippingAddress.find('.select-address'),$selected=$select.find('option:selected'),newOption='';dialog.close();if(address.UUID!==originalUUID){resetOptionValue=true;}if(add){$('.shippingaddress select').removeClass('no-option').append(newOption);$('.no-address').hide();}else{$('.shippingaddress select').find('option[value="'+address.UUID+'"]').html(newOption);}// if there's no previously selected option, select it +if($selected.length===0||$selected.val()===''||resetOptionValue){$select.find('option[value="'+address.UUID+'"]').prop('selected','selected').trigger('change');}});});//preserve the uuid of the option for the hop up form +if(selectedAddressUUID){//update the form with selected address +$addressList.find('option').each(function(){//check the values of the options +if($(this).attr('value')===selectedAddressUUID){$(this).prop('selected','selected');$addressDropdown.trigger('change');}});originalUUID=selectedAddressUUID;}validator.init();}/** + * @function + * @description shows gift message box in multiship, and if the page is the multi shipping address page it will call initmultishipshipaddress() to initialize the form + */exports.init=function(){initMultiGiftMessageBox();if($('.cart-row .shippingaddress .select-address').length>0){formPrepare.init({continueSelector:'[name$="addressSelection_save"]',formSelector:'[id$="multishipping_addressSelection"]'});}$('.edit-address').on('click','span',function(e){dialog.open({url:this.attributes.href.value,options:{open:function(){address.init();addEditAddress(e.target);}}});});};},{"../../dialog":12,"../../util":53,"../../validator":54,"./address":21,"./formPrepare":23}],26:[function(require,module,exports){'use strict';var ajax=require('../../ajax'),formPrepare=require('./formPrepare'),progress=require('../../progress'),tooltip=require('../../tooltip'),util=require('../../util');var shippingMethods;/** + * @function + * @description Initializes gift message box, if shipment is gift + */function giftMessageBox(){// show gift message box, if shipment is gift +$('.gift-message-text').toggleClass('hidden',$('input[name$="_shippingAddress_isGift"]:checked').val()!=='true');}/** + * @function + * @description updates the order summary based on a possibly recalculated basket after a shipping promotion has been applied + */function updateSummary(){var $summary=$('#secondary.summary');// indicate progress +progress.show($summary);// load the updated summary area +$summary.load(Urls.summaryRefreshURL,function(){// hide edit shipping method link +$summary.fadeIn('fast');$summary.find('.checkout-mini-cart .minishipment .header a').hide();$summary.find('.order-totals-table .order-shipping .label a').hide();});}/** + * @function + * @description Helper method which constructs a URL for an AJAX request using the + * entered address information as URL request parameters. + */function getShippingMethodURL(url,extraParams){var $form=$('.address');var params={address1:$form.find('input[name$="_address1"]').val(),address2:$form.find('input[name$="_address2"]').val(),countryCode:$form.find('select[id$="_country"]').val(),stateCode:$form.find('select[id$="_state"]').val(),postalCode:$form.find('input[name$="_postal"]').val(),city:$form.find('input[name$="_city"]').val()};return util.appendParamsToUrl(url,$.extend(params,extraParams));}/** + * @function + * @description selects a shipping method for the default shipment and updates the summary section on the right hand side + * @param + */function selectShippingMethod(shippingMethodID){// nothing entered +if(!shippingMethodID){return;}// attempt to set shipping method +var url=getShippingMethodURL(Urls.selectShippingMethodsList,{shippingMethodID:shippingMethodID});ajax.getJson({url:url,callback:function(data){updateSummary();if(!data||!data.shippingMethodID){window.alert('Couldn\'t select shipping method.');return false;}// display promotion in UI and update the summary section, +// if some promotions were applied +$('.shippingpromotions').empty();// TODO the for loop below isn't doing anything? +// if (data.shippingPriceAdjustments && data.shippingPriceAdjustments.length > 0) { +// var len = data.shippingPriceAdjustments.length; +// for (var i=0; i < len; i++) { +// var spa = data.shippingPriceAdjustments[i]; +// } +// } +}});}/** + * @function + * @description Make an AJAX request to the server to retrieve the list of applicable shipping methods + * based on the merchandise in the cart and the currently entered shipping address + * (the address may be only partially entered). If the list of applicable shipping methods + * has changed because new address information has been entered, then issue another AJAX + * request which updates the currently selected shipping method (if needed) and also updates + * the UI. + */function updateShippingMethodList(){var $shippingMethodList=$('#shipping-method-list');if(!$shippingMethodList||$shippingMethodList.length===0){return;}var url=getShippingMethodURL(Urls.shippingMethodsJSON);ajax.getJson({url:url,callback:function(data){if(!data){window.alert('Couldn\'t get list of applicable shipping methods.');return false;}if(shippingMethods&&shippingMethods.toString()===data.toString()){// No need to update the UI. The list has not changed. +return true;}// We need to update the UI. The list has changed. +// Cache the array of returned shipping methods. +shippingMethods=data;// indicate progress +progress.show($shippingMethodList);// load the shipping method form +var smlUrl=getShippingMethodURL(Urls.shippingMethodsList);$shippingMethodList.load(smlUrl,function(){$shippingMethodList.fadeIn('fast');// rebind the radio buttons onclick function to a handler. +$shippingMethodList.find('[name$="_shippingMethodID"]').click(function(){selectShippingMethod($(this).val());});// update the summary +updateSummary();progress.hide();tooltip.init();//if nothing is selected in the shipping methods select the first one +if($shippingMethodList.find('.input-radio:checked').length===0){$shippingMethodList.find('.input-radio:first').prop('checked','checked');}});}});}exports.init=function(){formPrepare.init({continueSelector:'[name$="shippingAddress_save"]',formSelector:'[id$="singleshipping_shippingAddress"]'});$('input[name$="_shippingAddress_isGift"]').on('click',giftMessageBox);$('.address').on('change','input[name$="_addressFields_address1"], input[name$="_addressFields_address2"], select[name$="_addressFields_states_state"], input[name$="_addressFields_city"], input[name$="_addressFields_zip"]',updateShippingMethodList);giftMessageBox();updateShippingMethodList();};exports.updateShippingMethodList=updateShippingMethodList;},{"../../ajax":3,"../../progress":42,"../../tooltip":52,"../../util":53,"./formPrepare":23}],27:[function(require,module,exports){'use strict';var addProductToCart=require('./product/addToCart'),ajax=require('../ajax'),page=require('../page'),productTile=require('../product-tile'),quickview=require('../quickview');/** + * @private + * @function + * @description Binds the click events to the remove-link and quick-view button + */function initializeEvents(){$('#compare-table').on('click','.remove-link',function(e){e.preventDefault();ajax.getJson({url:this.href,callback:function(){page.refresh();}});}).on('click','.open-quick-view',function(e){e.preventDefault();var url=$(this).closest('.product').find('.thumb-link').attr('href');quickview.show({url:url,source:'quickview'});});$('#compare-category-list').on('change',function(){$(this).closest('form').submit();});}exports.init=function(){productTile.init();initializeEvents();addProductToCart();};},{"../ajax":3,"../page":18,"../product-tile":41,"../quickview":43,"./product/addToCart":28}],28:[function(require,module,exports){'use strict';var dialog=require('../../dialog'),minicart=require('../../minicart'),page=require('../../page'),util=require('../../util'),Promise=require('promise'),_=require('lodash');/** + * @description Make the AJAX request to add an item to cart + * @param {Element} form The form element that contains the item quantity and ID data + * @returns {Promise} + */var addItemToCart=function(form){var $form=$(form),$qty=$form.find('input[name="Quantity"]');if($qty.length===0||isNaN($qty.val())||parseInt($qty.val(),10)===0){$qty.val('1');}return Promise.resolve($.ajax({type:'POST',url:util.ajaxUrl(Urls.addProduct),data:$form.serialize()})).then(function(response){// handle error in the response +if(response.error){throw new Error(response.error);}else{return response;}});};/** + * @description Handler to handle the add to cart event + */var addToCart=function(e){e.preventDefault();var $form=$(this).closest('form');addItemToCart($form).then(function(response){var $uuid=$form.find('input[name="uuid"]');if($uuid.length>0&&$uuid.val().length>0){page.refresh();}else{// do not close quickview if adding individual item that is part of product set +// @TODO should notify the user some other way that the add action has completed successfully +if(!$(this).hasClass('sub-product-item')){dialog.close();}minicart.show(response);}}.bind(this));};/** + * @description Handler to handle the add all items to cart event + */var addAllToCart=function(e){e.preventDefault();var $productForms=$('#product-set-list').find('form').toArray();Promise.all(_.map($productForms,addItemToCart)).then(function(responses){dialog.close();// show the final response only, which would include all the other items +minicart.show(responses[responses.length-1]);});};/** + * @function + * @description Binds the click event to a given target for the add-to-cart handling + */module.exports=function(){$('.add-to-cart[disabled]').attr('title',$('.availability-msg').text());$('.product-detail').on('click','.add-to-cart',addToCart);$('#add-all-to-cart').on('click',addAllToCart);};},{"../../dialog":12,"../../minicart":17,"../../page":18,"../../util":53,"lodash":68,"promise":70}],29:[function(require,module,exports){'use strict';var ajax=require('../../ajax'),util=require('../../util');var updateContainer=function(data){var $availabilityMsg=$('#pdpMain .availability .availability-msg');var message;// this should be lexically scoped, when `let` is supported (ES6) +if(!data){$availabilityMsg.html(Resources.ITEM_STATUS_NOTAVAILABLE);return;}$availabilityMsg.empty();// Look through levels ... if msg is not empty, then create span el +if(data.levels.IN_STOCK>0){if(data.levels.PREORDER===0&&data.levels.BACKORDER===0&&data.levels.NOT_AVAILABLE===0){// Just in stock +message=Resources.IN_STOCK;}else{// In stock with conditions ... +message=data.inStockMsg;}$availabilityMsg.append('

        '+message+'

        ');}if(data.levels.PREORDER>0){if(data.levels.IN_STOCK===0&&data.levels.BACKORDER===0&&data.levels.NOT_AVAILABLE===0){message=Resources.PREORDER;}else{message=data.preOrderMsg;}$availabilityMsg.append('

        '+message+'

        ');}if(data.levels.BACKORDER>0){if(data.levels.IN_STOCK===0&&data.levels.PREORDER===0&&data.levels.NOT_AVAILABLE===0){message=Resources.BACKORDER;}else{message=data.backOrderMsg;}$availabilityMsg.append('

        '+message+'

        ');}if(data.inStockDate!==''){$availabilityMsg.append('

        '+String.format(Resources.IN_STOCK_DATE,data.inStockDate)+'

        ');}if(data.levels.NOT_AVAILABLE>0){if(data.levels.PREORDER===0&&data.levels.BACKORDER===0&&data.levels.IN_STOCK===0){message=Resources.NOT_AVAILABLE;}else{message=Resources.REMAIN_NOT_AVAILABLE;}$availabilityMsg.append('

        '+message+'

        ');}};var getAvailability=function(){ajax.getJson({url:util.appendParamsToUrl(Urls.getAvailability,{pid:$('#pid').val(),Quantity:$(this).val()}),callback:updateContainer});};module.exports=function(){$('#pdpMain').on('change','.pdpForm input[name="Quantity"]',getAvailability);};},{"../../ajax":3,"../../util":53}],30:[function(require,module,exports){'use strict';var dialog=require('../../dialog');var util=require('../../util');var qs=require('qs');var url=require('url');var _=require('lodash');var zoomMediaQuery=matchMedia('(min-width: 960px)');/** + * @description Enables the zoom viewer on the product detail page + * @param zmq {Media Query List} + */function loadZoom(zmq){var $imgZoom=$('#pdpMain .main-image'),hiresUrl;if(!zmq){zmq=zoomMediaQuery;}if($imgZoom.length===0||dialog.isActive()||util.isMobile()||!zoomMediaQuery.matches){// remove zoom +$imgZoom.trigger('zoom.destroy');return;}hiresUrl=$imgZoom.attr('href');if(hiresUrl&&hiresUrl!=='null'&&hiresUrl.indexOf('noimagelarge')===-1&&zoomMediaQuery.matches){$imgZoom.zoom({url:hiresUrl});}}zoomMediaQuery.addListener(loadZoom);/** + * @description Sets the main image attributes and the href for the surrounding tag + * @param {Object} atts Object with url, alt, title and hires properties + */function setMainImage(atts){$('#pdpMain .primary-image').attr({src:atts.url,alt:atts.alt,title:atts.title});updatePinButton(atts.url);if(!dialog.isActive()&&!util.isMobile()){$('#pdpMain .main-image').attr('href',atts.hires);}loadZoom();}function updatePinButton(imageUrl){var pinButton=document.querySelector('.share-icon[data-share=pinterest]');if(!pinButton){return;}var newUrl=imageUrl;if(!imageUrl){newUrl=document.querySelector('#pdpMain .primary-image').getAttribute('src');}var href=url.parse(pinButton.href);var query=qs.parse(href.query);query.media=url.resolve(window.location.href,newUrl);query.url=window.location.href;var newHref=url.format(_.extend({},href,{query:query,// query is only used if search is absent +search:qs.stringify(query)}));pinButton.href=newHref;}/** + * @description Replaces the images in the image container, for eg. when a different color was clicked. + */function replaceImages(){var $newImages=$('#update-images'),$imageContainer=$('#pdpMain .product-image-container');if($newImages.length===0){return;}$imageContainer.html($newImages.html());$newImages.remove();loadZoom();}/* @module image + * @description this module handles the primary image viewer on PDP + **/ /** + * @description by default, this function sets up zoom and event handler for thumbnail click + **/module.exports=function(){if(dialog.isActive()||util.isMobile()){$('#pdpMain .main-image').removeAttr('href');}updatePinButton();loadZoom();// handle product thumbnail click event +$('#pdpMain').on('click','.productthumbnail',function(){// switch indicator +$(this).closest('.product-thumbnails').find('.thumb.selected').removeClass('selected');$(this).closest('.thumb').addClass('selected');setMainImage($(this).data('lgimg'));});};module.exports.loadZoom=loadZoom;module.exports.setMainImage=setMainImage;module.exports.replaceImages=replaceImages;},{"../../dialog":12,"../../util":53,"lodash":68,"qs":80,"url":88}],31:[function(require,module,exports){'use strict';var dialog=require('../../dialog'),productStoreInventory=require('../../storeinventory/product'),tooltip=require('../../tooltip'),util=require('../../util'),addToCart=require('./addToCart'),availability=require('./availability'),image=require('./image'),productNav=require('./productNav'),productSet=require('./productSet'),recommendations=require('./recommendations'),variant=require('./variant');/** + * @description Initialize product detail page with reviews, recommendation and product navigation. + */function initializeDom(){productNav();recommendations();tooltip.init();}/** + * @description Initialize event handlers on product detail page + */function initializeEvents(){var $pdpMain=$('#pdpMain');addToCart();availability();variant();image();productSet();if(SitePreferences.STORE_PICKUP){productStoreInventory.init();}// Add to Wishlist and Add to Gift Registry links behaviors +$pdpMain.on('click','[data-action="wishlist"], [data-action="gift-registry"]',function(){var data=util.getQueryStringParams($('.pdpForm').serialize());if(data.cartAction){delete data.cartAction;}var url=util.appendParamsToUrl(this.href,data);this.setAttribute('href',url);});// product options +$pdpMain.on('change','.product-options select',function(){var salesPrice=$pdpMain.find('.product-add-to-cart .price-sales');var selectedItem=$(this).children().filter(':selected').first();salesPrice.text(selectedItem.data('combined'));});// prevent default behavior of thumbnail link and add this Button +$pdpMain.on('click','.thumbnail-link, .unselectable a',function(e){e.preventDefault();});$('.size-chart-link a').on('click',function(e){e.preventDefault();dialog.open({url:$(e.target).attr('href')});});}var product={initializeEvents:initializeEvents,init:function(){initializeDom();initializeEvents();}};module.exports=product;},{"../../dialog":12,"../../storeinventory/product":49,"../../tooltip":52,"../../util":53,"./addToCart":28,"./availability":29,"./image":30,"./productNav":32,"./productSet":33,"./recommendations":34,"./variant":35}],32:[function(require,module,exports){'use strict';var ajax=require('../../ajax'),util=require('../../util');/** + * @description loads product's navigation + **/module.exports=function(){var $pidInput=$('.pdpForm input[name="pid"]').last(),$navContainer=$('#product-nav-container');// if no hash exists, or no pid exists, or nav container does not exist, return +if(window.location.hash.length<=1||$pidInput.length===0||$navContainer.length===0){return;}var pid=$pidInput.val(),hash=window.location.hash.substr(1),url=util.appendParamToURL(Urls.productNav+'?'+hash,'pid',pid);ajax.load({url:url,target:$navContainer});};},{"../../ajax":3,"../../util":53}],33:[function(require,module,exports){'use strict';var ajax=require('../../ajax'),tooltip=require('../../tooltip'),util=require('../../util');module.exports=function(){var $addToCart=$('#add-to-cart'),$addAllToCart=$('#add-all-to-cart'),$productSetList=$('#product-set-list');var updateAddToCartButtons=function(){if($productSetList.find('.add-to-cart[disabled]').length>0){$addAllToCart.attr('disabled','disabled');// product set does not have an add-to-cart button, but product bundle does +$addToCart.attr('disabled','disabled');}else{$addAllToCart.removeAttr('disabled');$addToCart.removeAttr('disabled');}};if($productSetList.length>0){updateAddToCartButtons();}// click on swatch for product set +$productSetList.on('click','.product-set-item .swatchanchor',function(e){e.preventDefault();if($(this).parents('li').hasClass('unselectable')){return;}var url=Urls.getSetItem+this.search;var $container=$(this).closest('.product-set-item');var qty=$container.find('form input[name="Quantity"]').first().val();ajax.load({url:util.appendParamToURL(url,'Quantity',isNaN(qty)?'1':qty),target:$container,callback:function(){updateAddToCartButtons();tooltip.init();}});});};},{"../../ajax":3,"../../tooltip":52,"../../util":53}],34:[function(require,module,exports){'use strict';/** + * @description Creates product recommendation carousel using jQuery jcarousel plugin + **/module.exports=function(){var $carousel=$('#carousel-recommendations');if(!$carousel||$carousel.length===0||$carousel.children().length===0){return;}$carousel.jcarousel();$('#carousel-recommendations .jcarousel-prev').on('jcarouselcontrol:active',function(){$(this).removeClass('inactive');}).on('jcarouselcontrol:inactive',function(){$(this).addClass('inactive');}).jcarouselControl({target:'-=1'});$('#carousel-recommendations .jcarousel-next').on('jcarouselcontrol:active',function(){$(this).removeClass('inactive');}).on('jcarouselcontrol:inactive',function(){$(this).addClass('inactive');}).jcarouselControl({target:'+=1'});};},{}],35:[function(require,module,exports){'use strict';var ajax=require('../../ajax'),image=require('./image'),progress=require('../../progress'),productStoreInventory=require('../../storeinventory/product'),tooltip=require('../../tooltip'),util=require('../../util');/** + * @description update product content with new variant from href, load new content to #product-content panel + * @param {String} href - url of the new product variant + **/var updateContent=function(href){var $pdpForm=$('.pdpForm');var qty=$pdpForm.find('input[name="Quantity"]').first().val();var params={Quantity:isNaN(qty)?'1':qty,format:'ajax',productlistid:$pdpForm.find('input[name="productlistid"]').first().val()};progress.show($('#pdpMain'));ajax.load({url:util.appendParamsToUrl(href,params),target:$('#product-content'),callback:function(){if(SitePreferences.STORE_PICKUP){productStoreInventory.init();}image.replaceImages();tooltip.init();}});};module.exports=function(){var $pdpMain=$('#pdpMain');// hover on swatch - should update main image with swatch image +$pdpMain.on('mouseenter mouseleave','.swatchanchor',function(){var largeImg=$(this).data('lgimg'),$imgZoom=$pdpMain.find('.main-image'),$mainImage=$pdpMain.find('.primary-image');if(!largeImg){return;}// store the old data from main image for mouseleave handler +$(this).data('lgimg',{hires:$imgZoom.attr('href'),url:$mainImage.attr('src'),alt:$mainImage.attr('alt'),title:$mainImage.attr('title')});// set the main image +image.setMainImage(largeImg);});// click on swatch - should replace product content with new variant +$pdpMain.on('click','.product-detail .swatchanchor',function(e){e.preventDefault();if($(this).parents('li').hasClass('unselectable')){return;}updateContent(this.href);});// change drop down variation attribute - should replace product content with new variant +$pdpMain.on('change','.variation-select',function(){if($(this).val().length===0){return;}updateContent($(this).val());});};},{"../../ajax":3,"../../progress":42,"../../storeinventory/product":49,"../../tooltip":52,"../../util":53,"./image":30}],36:[function(require,module,exports){'use strict';var addProductToCart=require('./product/addToCart'),ajax=require('../ajax'),login=require('../login'),quickview=require('../quickview'),util=require('../util');/** + * @function + * @description Loads address details to a given address and fills the address form + * @param {String} addressID The ID of the address to which data will be loaded + */function populateForm(addressID,$form){// load address details +var url=Urls.giftRegAdd+addressID;ajax.getJson({url:url,callback:function(data){if(!data||!data.address){window.alert(Resources.REG_ADDR_ERROR);return false;}// fill the form +$form.find('[name$="_addressid"]').val(data.address.ID);$form.find('[name$="_firstname"]').val(data.address.firstName);$form.find('[name$="_lastname"]').val(data.address.lastName);$form.find('[name$="_address1"]').val(data.address.address1);$form.find('[name$="_address2"]').val(data.address.address2);$form.find('[name$="_city"]').val(data.address.city);$form.find('[name$="_country"]').val(data.address.countryCode).trigger('change');$form.find('[name$="_postal"]').val(data.address.postalCode);$form.find('[name$="_state"]').val(data.address.stateCode);$form.find('[name$="_phone"]').val(data.address.phone);// $form.parent('form').validate().form(); +}});}/** + * @private + * @function + * @description Initializes events for the gift registration + */function initializeEvents(){var $eventAddressForm=$('form[name$="_giftregistry"]'),$beforeAddress=$eventAddressForm.find('fieldset[name="address-before"]'),$afterAddress=$eventAddressForm.find('fieldset[name="address-after"]');$('.usepreevent').on('click',function(){// filter out storefront toolkit +$(':input',$beforeAddress).not('[id^="ext"]').not('select[name$="_addressBeforeList"]').each(function(){var fieldName=$(this).attr('name'),$afterField=$afterAddress.find('[name="'+fieldName.replace('Before','After')+'"]');$afterField.val($(this).val()).trigger('change');});});$eventAddressForm.on('change','select[name$="_addressBeforeList"]',function(){var addressID=$(this).val();if(addressID.length===0){return;}populateForm(addressID,$beforeAddress);}).on('change','select[name$="_addressAfterList"]',function(){var addressID=$(this).val();if(addressID.length===0){return;}populateForm(addressID,$afterAddress);});$('.item-list').on('click','.item-edit-details a',function(e){e.preventDefault();var productListID=$('input[name=productListID]').val();quickview.show({url:e.target.href,source:'giftregistry',productlistid:productListID});});}exports.init=function(){initializeEvents();addProductToCart();login.init();util.setDeleteConfirmation('.item-list',String.format(Resources.CONFIRM_DELETE,Resources.TITLE_GIFTREGISTRY));};},{"../ajax":3,"../login":16,"../quickview":43,"../util":53,"./product/addToCart":28}],37:[function(require,module,exports){'use strict';var compareWidget=require('../compare-widget'),productTile=require('../product-tile'),progress=require('../progress'),util=require('../util');function infiniteScroll(){// getting the hidden div, which is the placeholder for the next page +var loadingPlaceHolder=$('.infinite-scroll-placeholder[data-loading-state="unloaded"]');// get url hidden in DOM +var gridUrl=loadingPlaceHolder.attr('data-grid-url');if(loadingPlaceHolder.length===1&&util.elementInViewport(loadingPlaceHolder.get(0),250)){// switch state to 'loading' +// - switches state, so the above selector is only matching once +// - shows loading indicator +loadingPlaceHolder.attr('data-loading-state','loading');loadingPlaceHolder.addClass('infinite-scroll-loading');// named wrapper function, which can either be called, if cache is hit, or ajax repsonse is received +var fillEndlessScrollChunk=function(html){loadingPlaceHolder.removeClass('infinite-scroll-loading');loadingPlaceHolder.attr('data-loading-state','loaded');$('div.search-result-content').append(html);};// old condition for caching was `'sessionStorage' in window && sessionStorage["scroll-cache_" + gridUrl]` +// it was removed to temporarily address RAP-2649 +$.ajax({type:'GET',dataType:'html',url:gridUrl,success:function(response){// put response into cache +try{sessionStorage['scroll-cache_'+gridUrl]=response;}catch(e){// nothing to catch in case of out of memory of session storage +// it will fall back to load via ajax +}// update UI +fillEndlessScrollChunk(response);productTile.init();}});}}/** + * @private + * @function + * @description replaces breadcrumbs, lefthand nav and product listing with ajax and puts a loading indicator over the product listing + */function updateProductListing(url){if(!url||url===window.location.href){return;}progress.show($('.search-result-content'));$('#main').load(util.appendParamToURL(url,'format','ajax'),function(){compareWidget.init();productTile.init();progress.hide();history.pushState(undefined,'',url);});}/** + * @private + * @function + * @description Initializes events for the following elements:
        + *

        refinement blocks

        + *

        updating grid: refinements, pagination, breadcrumb

        + *

        item click

        + *

        sorting changes

        + */function initializeEvents(){var $main=$('#main');// compare checked +$main.on('click','input[type="checkbox"].compare-check',function(){var cb=$(this);var tile=cb.closest('.product-tile');var func=this.checked?compareWidget.addProduct:compareWidget.removeProduct;var itemImg=tile.find('.product-image a img').first();func({itemid:tile.data('itemid'),uuid:tile[0].id,img:itemImg,cb:cb});});// handle toggle refinement blocks +$main.on('click','.refinement h3',function(){$(this).toggleClass('expanded').siblings('ul').toggle();});// handle events for updating grid +$main.on('click','.refinements a, .pagination a, .breadcrumb-refinement-value a',function(e){// don't intercept for category and folder refinements, as well as unselectable +if($(this).parents('.category-refinement').length>0||$(this).parents('.folder-refinement').length>0||$(this).parent().hasClass('unselectable')){return;}e.preventDefault();updateProductListing(this.href);});// handle events item click. append params. +$main.on('click','.product-tile a:not("#quickviewbutton")',function(){var a=$(this);// get current page refinement values +var wl=window.location;var qsParams=wl.search.length>1?util.getQueryStringParams(wl.search.substr(1)):{};var hashParams=wl.hash.length>1?util.getQueryStringParams(wl.hash.substr(1)):{};// merge hash params with querystring params +var params=$.extend(hashParams,qsParams);if(!params.start){params.start=0;}// get the index of the selected item and save as start parameter +var tile=a.closest('.product-tile');var idx=tile.data('idx')?+tile.data('idx'):0;// convert params.start to integer and add index +params.start=+params.start+(idx+1);// set the hash and allow normal action to continue +a[0].hash=$.param(params);});// handle sorting change +$main.on('change','.sort-by select',function(e){e.preventDefault();updateProductListing($(this).find('option:selected').val());}).on('change','.items-per-page select',function(){var refineUrl=$(this).find('option:selected').val();if(refineUrl==='INFINITE_SCROLL'){$('html').addClass('infinite-scroll').removeClass('disable-infinite-scroll');}else{$('html').addClass('disable-infinite-scroll').removeClass('infinite-scroll');updateProductListing(refineUrl);}});}exports.init=function(){compareWidget.init();if(SitePreferences.LISTING_INFINITE_SCROLL){$(window).on('scroll',infiniteScroll);}productTile.init();initializeEvents();};},{"../compare-widget":8,"../product-tile":41,"../progress":42,"../util":53}],38:[function(require,module,exports){'use strict';exports.init=function(){$('#homepage-slider')// responsive slides +.on('jcarousel:create jcarousel:reload',function(){var element=$(this),width=element.innerWidth();element.jcarousel('items').css('width',width+'px');}).jcarousel({wrap:'circular'}).jcarouselAutoscroll({interval:5000});$('#homepage-slider .jcarousel-control').on('jcarouselpagination:active','a',function(){$(this).addClass('active');}).on('jcarouselpagination:inactive','a',function(){$(this).removeClass('active');}).jcarouselPagination({item:function(page){return'
        '+page+'';}});$('#vertical-carousel').jcarousel({vertical:true}).jcarouselAutoscroll({interval:5000});$('#vertical-carousel .jcarousel-prev').on('jcarouselcontrol:active',function(){$(this).removeClass('inactive');}).on('jcarouselcontrol:inactive',function(){$(this).addClass('inactive');}).jcarouselControl({target:'-=1'});$('#vertical-carousel .jcarousel-next').on('jcarouselcontrol:active',function(){$(this).removeClass('inactive');}).on('jcarouselcontrol:inactive',function(){$(this).addClass('inactive');}).jcarouselControl({target:'+=1'});};},{}],39:[function(require,module,exports){'use strict';var dialog=require('../dialog');exports.init=function(){$('.store-details-link').on('click',function(e){e.preventDefault();dialog.open({url:$(e.target).attr('href')});});};},{"../dialog":12}],40:[function(require,module,exports){'use strict';var addProductToCart=require('./product/addToCart'),page=require('../page'),login=require('../login'),util=require('../util');exports.init=function(){addProductToCart();$('#editAddress').on('change',function(){page.redirect(util.appendParamToURL(Urls.wishlistAddress,'AddressID',$(this).val()));});//add js logic to remove the , from the qty feild to pass regex expression on client side +$('.option-quantity-desired input').on('focusout',function(){$(this).val($(this).val().replace(',',''));});login.init();};},{"../login":16,"../page":18,"../util":53,"./product/addToCart":28}],41:[function(require,module,exports){'use strict';var imagesLoaded=require('imagesloaded'),quickview=require('./quickview');function initQuickViewButtons(){$('.tiles-container .product-image').on('mouseenter',function(){var $qvButton=$('#quickviewbutton');if($qvButton.length===0){$qvButton=$(''+Resources.QUICK_VIEW+'');}var $link=$(this).find('.thumb-link');$qvButton.attr({'href':$link.attr('href'),'title':$link.attr('title')}).appendTo(this);$qvButton.on('click',function(e){e.preventDefault();quickview.show({url:$(this).attr('href'),source:'quickview'});});});}function gridViewToggle(){$('.toggle-grid').on('click',function(){$('.search-result-content').toggleClass('wide-tiles');$(this).toggleClass('wide');});}/** + * @private + * @function + * @description Initializes events on the product-tile for the following elements: + * - swatches + * - thumbnails + */function initializeEvents(){initQuickViewButtons();gridViewToggle();$('.swatch-list').on('mouseleave',function(){// Restore current thumb image +var $tile=$(this).closest('.product-tile'),$thumb=$tile.find('.product-image .thumb-link img').eq(0),data=$thumb.data('current');$thumb.attr({src:data.src,alt:data.alt,title:data.title});});$('.swatch-list .swatch').on('click',function(e){e.preventDefault();if($(this).hasClass('selected')){return;}var $tile=$(this).closest('.product-tile');$(this).closest('.swatch-list').find('.swatch.selected').removeClass('selected');$(this).addClass('selected');$tile.find('.thumb-link').attr('href',$(this).attr('href'));$tile.find('name-link').attr('href',$(this).attr('href'));var data=$(this).children('img').filter(':first').data('thumb');var $thumb=$tile.find('.product-image .thumb-link img').eq(0);var currentAttrs={src:data.src,alt:data.alt,title:data.title};$thumb.attr(currentAttrs);$thumb.data('current',currentAttrs);}).on('mouseenter',function(){// get current thumb details +var $tile=$(this).closest('.product-tile'),$thumb=$tile.find('.product-image .thumb-link img').eq(0),data=$(this).children('img').filter(':first').data('thumb'),current=$thumb.data('current');// If this is the first time, then record the current img +if(!current){$thumb.data('current',{src:$thumb[0].src,alt:$thumb[0].alt,title:$thumb[0].title});}// Set the tile image to the values provided on the swatch data attributes +$thumb.attr({src:data.src,alt:data.alt,title:data.title});});}exports.init=function(){var $tiles=$('.tiles-container .product-tile');if($tiles.length===0){return;}imagesLoaded('.tiles-container').on('done',function(){$tiles.syncHeight().each(function(idx){$(this).data('idx',idx);});});initializeEvents();};},{"./quickview":43,"imagesloaded":67}],42:[function(require,module,exports){'use strict';var $loader;/** + * @function + * @description Shows an AJAX-loader on top of a given container + * @param {Element} container The Element on top of which the AJAX-Loader will be shown + */var show=function(container){var target=!container||$(container).length===0?$('body'):$(container);$loader=$loader||$('.loader');if($loader.length===0){$loader=$('
        ').addClass('loader').append($('
        ').addClass('loader-indicator'),$('
        ').addClass('loader-bg'));}return $loader.appendTo(target).show();};/** + * @function + * @description Hides an AJAX-loader + */var hide=function(){if($loader){$loader.hide();}};exports.show=show;exports.hide=hide;},{}],43:[function(require,module,exports){'use strict';var dialog=require('./dialog'),product=require('./pages/product'),util=require('./util'),_=require('lodash');var makeUrl=function(url,source,productListID){if(source){url=util.appendParamToURL(url,'source',source);}if(productListID){url=util.appendParamToURL(url,'productlistid',productListID);}return url;};var removeParam=function(url){if(url.indexOf('?')!==-1){return url.substring(0,url.indexOf('?'));}else{return url;}};var quickview={init:function(){if(!this.exists()){this.$container=$('
        ').attr('id','QuickViewDialog').appendTo(document.body);}this.productLinks=$('#search-result-items .thumb-link').map(function(index,thumbLink){return $(thumbLink).attr('href');});},setup:function(qvUrl){var $btnNext=$('.quickview-next'),$btnPrev=$('.quickview-prev');product.initializeEvents();this.productLinkIndex=_(this.productLinks).findIndex(function(url){return removeParam(url)===removeParam(qvUrl);});// hide the buttons on the compare page or when there are no other products +if(this.productLinks.length<=1||$('.compareremovecell').length>0){$btnNext.hide();$btnPrev.hide();return;}if(this.productLinkIndex===this.productLinks.length-1){$btnNext.attr('disabled','disabled');}if(this.productLinkIndex===0){$btnPrev.attr('disabled','disabled');}$btnNext.on('click',function(e){e.preventDefault();this.navigateQuickview(1);}.bind(this));$btnPrev.on('click',function(e){e.preventDefault();this.navigateQuickview(-1);}.bind(this));},/** + * @param {Number} step - How many products away from current product to navigate to. Negative number means navigate backward + */navigateQuickview:function(step){// default step to 0 +this.productLinkIndex+=step?step:0;var url=makeUrl(this.productLinks[this.productLinkIndex],'quickview');dialog.replace({url:url,callback:this.setup.bind(this,url)});},/** + * @description show quick view dialog + * @param {Object} options + * @param {String} options.url - url of the product details + * @param {String} options.source - source of the dialog to be appended to URL + * @param {String} options.productlistid - to be appended to URL + * @param {Function} options.callback - callback once the dialog is opened + */show:function(options){var url;if(!this.exists()){this.init();}url=makeUrl(options.url,options.source,options.productlistid);dialog.open({target:this.$container,url:url,options:{width:920,title:Resources.QUICK_VIEW_POPUP,open:function(){this.setup(url);if(typeof options.callback==='function'){options.callback();}}.bind(this)}});},exists:function(){return this.$container&&this.$container.length>0;}};module.exports=quickview;},{"./dialog":12,"./pages/product":31,"./util":53,"lodash":68}],44:[function(require,module,exports){'use strict';/** + * copied from https://github.com/darkskyapp/string-hash + */function hashFn(str){var hash=5381,i=str.length;while(i){hash=hash*33^str.charCodeAt(--i);}/* JavaScript does bitwise operations (like XOR, above) on 32-bit signed + * integers. Since we want the results to be always positive, convert the + * signed int to an unsigned by doing an unsigned bitshift. */return hash>>>0;}/** + * Create rating based on hash ranging from 2-5 + * @param pid + */function getRating(pid){return hashFn(pid.toString())%30/10+2;}module.exports={init:function(){$('.product-review').each(function(index,review){var pid=$(review).data('pid');if(!pid){return;}// rating range from 2 - 5 +var rating=getRating(pid);var baseRating=Math.floor(rating);var starsCount=0;for(var i=0;i');starsCount++;}// give half star for anything in between +if(rating>baseRating){$('.rating',review).append('');starsCount++;}if(starsCount<5){for(var j=0;j<5-starsCount;j++){$('.rating',review).append('');}}});}};},{}],45:[function(require,module,exports){'use strict';/** + * @private + * @function + * @description Binds event to the place holder (.blur) + */function initializeEvents(){$('#q').focus(function(){var input=$(this);if(input.val()===input.attr('placeholder')){input.val('');}}).blur(function(){var input=$(this);if(input.val()===''||input.val()===input.attr('placeholder')){input.val(input.attr('placeholder'));}}).blur();}exports.init=initializeEvents;},{}],46:[function(require,module,exports){'use strict';var util=require('./util');var currentQuery=null,lastQuery=null,runningQuery=null,listTotal=-1,listCurrent=-1,delay=30,$resultsContainer;/** + * @function + * @description Handles keyboard's arrow keys + * @param keyCode Code of an arrow key to be handled + */function handleArrowKeys(keyCode){switch(keyCode){case 38:// keyUp +listCurrent=listCurrent<=0?listTotal-1:listCurrent-1;break;case 40:// keyDown +listCurrent=listCurrent>=listTotal-1?0:listCurrent+1;break;default:// reset +listCurrent=-1;return false;}$resultsContainer.children().removeClass('selected').eq(listCurrent).addClass('selected');$('input[name="q"]').val($resultsContainer.find('.selected .suggestionterm').first().text());return true;}var searchsuggest={/** + * @function + * @description Configures parameters and required object instances + */init:function(container,defaultValue){var $searchContainer=$(container);var $searchForm=$searchContainer.find('form[name="simpleSearch"]');var $searchField=$searchForm.find('input[name="q"]');// disable browser auto complete +$searchField.attr('autocomplete','off');// on focus listener (clear default value) +$searchField.focus(function(){if(!$resultsContainer){// create results container if needed +$resultsContainer=$('
        ').attr('id','search-suggestions').appendTo($searchContainer);}if($searchField.val()===defaultValue){$searchField.val('');}});$(document).on('click',function(e){if(!$searchContainer.is(e.target)){setTimeout(this.clearResults,200);}}.bind(this));// on key up listener +$searchField.keyup(function(e){// get keyCode (window.event is for IE) +var keyCode=e.keyCode||window.event.keyCode;// check and treat up and down arrows +if(handleArrowKeys(keyCode)){return;}// check for an ENTER or ESC +if(keyCode===13||keyCode===27){this.clearResults();return;}currentQuery=$searchField.val().trim();// no query currently running, init an update +if(!runningQuery){runningQuery=currentQuery;setTimeout(this.suggest.bind(this),delay);}}.bind(this));},/** + * @function + * @description trigger suggest action + */suggest:function(){// check whether query to execute (runningQuery) is still up to date and had not changed in the meanwhile +// (we had a little delay) +if(runningQuery!==currentQuery){// update running query to the most recent search phrase +runningQuery=currentQuery;}// if it's empty clear the results box and return +if(runningQuery.length===0){this.clearResults();runningQuery=null;return;}// if the current search phrase is the same as for the last suggestion call, just return +if(lastQuery===runningQuery){runningQuery=null;return;}// build the request url +var reqUrl=util.appendParamToURL(Urls.searchsuggest,'q',runningQuery);// execute server call +$.get(reqUrl,function(data){var suggestionHTML=data,ansLength=suggestionHTML.trim().length;// if there are results populate the results div +if(ansLength===0){this.clearResults();}else{// update the results div +$resultsContainer.html(suggestionHTML).fadeIn(200);}// record the query that has been executed +lastQuery=runningQuery;// reset currently running query +runningQuery=null;// check for another required update (if current search phrase is different from just executed call) +if(currentQuery!==lastQuery){// ... and execute immediately if search has changed while this server call was in transit +runningQuery=currentQuery;setTimeout(this.suggest.bind(this),delay);}this.hideLeftPanel();}.bind(this));},/** + * @function + * @description + */clearResults:function(){if(!$resultsContainer){return;}$resultsContainer.fadeOut(200,function(){$resultsContainer.empty();});},/** + * @function + * @description + */hideLeftPanel:function(){//hide left panel if there is only a matching suggested custom phrase +if($('.search-suggestion-left-panel-hit').length===1&&$('.search-phrase-suggestion a').text().replace(/(^[\s]+|[\s]+$)/g,'').toUpperCase()===$('.search-suggestion-left-panel-hit a').text().toUpperCase()){$('.search-suggestion-left-panel').css('display','none');$('.search-suggestion-wrapper-full').addClass('search-suggestion-wrapper');$('.search-suggestion-wrapper').removeClass('search-suggestion-wrapper-full');}}};module.exports=searchsuggest;},{"./util":53}],47:[function(require,module,exports){'use strict';var inventory=require('./');var cartInventory={setSelectedStore:function(storeId){var $selectedStore=$('.store-tile.'+storeId),$lineItem=$('.cart-row[data-uuid="'+this.uuid+'"]'),storeAddress=$selectedStore.find('.store-address').html(),storeStatus=$selectedStore.find('.store-status').data('status'),storeStatusText=$selectedStore.find('.store-status').text();this.selectedStore=storeId;$lineItem.find('.instore-delivery .selected-store-address').data('storeId',storeId).attr('data-store-id',storeId).html(storeAddress);$lineItem.find('.instore-delivery .selected-store-availability').data('status',storeStatus).attr('data-status',storeStatus).text(storeStatusText);$lineItem.find('.instore-delivery .delivery-option').removeAttr('disabled').trigger('click');},cartSelectStore:function(selectedStore){var self=this;inventory.getStoresInventory(this.uuid).then(function(stores){inventory.selectStoreDialog({stores:stores,selectedStoreId:selectedStore,selectedStoreText:Resources.SELECTED_STORE,continueCallback:function(){},selectStoreCallback:self.setSelectedStore.bind(self)});}).done();},setDeliveryOption:function(value,storeId){// set loading state +$('.item-delivery-options').addClass('loading').children().hide();var data={plid:this.uuid,storepickup:value==='store'?true:false};if(value==='store'){data.storepickup=true;data.storeid=storeId;}else{data.storepickup=false;}$.ajax({url:Urls.setStorePickup,data:data,success:function(){// remove loading state +$('.item-delivery-options').removeClass('loading').children().show();}});},init:function(){var self=this;$('.item-delivery-options .set-preferred-store').on('click',function(e){e.preventDefault();self.uuid=$(this).data('uuid');var selectedStore=$(this).closest('.instore-delivery').find('.selected-store-address').data('storeId');if(!User.zip){inventory.zipPrompt(function(){self.cartSelectStore(selectedStore);});}else{self.cartSelectStore(selectedStore);}});$('.item-delivery-options .delivery-option').on('click',function(){// reset the uuid +var selectedStore=$(this).closest('.instore-delivery').find('.selected-store-address').data('storeId');self.uuid=$(this).closest('.cart-row').data('uuid');self.setDeliveryOption($(this).val(),selectedStore);});}};module.exports=cartInventory;},{"./":48}],48:[function(require,module,exports){'use strict';var _=require('lodash'),dialog=require('../dialog'),TPromise=require('promise'),util=require('../util');var newLine='\n';var storeTemplate=function(store,selectedStoreId,selectedStoreText){return['
      • ','

        ',' '+store.address1+'
        ',' '+store.city+', '+store.stateCode+' '+store.postalCode,'

        ','

        '+store.status+'

        ',' ','
      • '].join(newLine);};var storeListTemplate=function(stores,selectedStoreId,selectedStoreText){if(stores&&stores.length){return['
        ','
          ',_.map(stores,function(store){return storeTemplate(store,selectedStoreId,selectedStoreText);}).join(newLine),'
        ','
        ','
        ','
        '].join(newLine);}else{return'
        '+Resources.INVALID_ZIP+'
        ';}};var zipPromptTemplate=function(){return['
        ',' ','
        '].join(newLine);};/** + * @description test whether zipcode is valid for either US or Canada + * @return {Boolean} true if the zipcode is valid for either country, false if it's invalid for both + **/var validateZipCode=function(zipCode){var regexes={canada:/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i,usa:/^\d{5}(-\d{4})?$/},valid=false;if(!zipCode){return;}_.each(regexes,function(re){var regexp=new RegExp(re);valid=regexp.test(zipCode);});return valid;};var storeinventory={zipPrompt:function(callback){var self=this;dialog.open({html:zipPromptTemplate(),options:{title:Resources.STORE_NEAR_YOU,width:500,buttons:[{text:Resources.SEARCH,click:function(){var zipCode=$('#user-zip').val();if(validateZipCode(zipCode)){self.setUserZip(zipCode);if(callback){callback(zipCode);}}}}],open:function(){$('#user-zip').on('keypress',function(e){if(e.which===13){// trigger the search button +$('.ui-dialog-buttonset .ui-button').trigger('click');}});}}});},getStoresInventory:function(pid){return TPromise.resolve($.ajax({url:util.appendParamsToUrl(Urls.storesInventory,{pid:pid,zipCode:User.zip}),dataType:'json'}));},/** + * @description open the dialog to select store + * @param {Array} options.stores + * @param {String} options.selectedStoreId + * @param {String} options.selectedStoreText + * @param {Function} options.continueCallback + * @param {Function} options.selectStoreCallback + **/selectStoreDialog:function(options){var self=this,stores=options.stores,selectedStoreId=options.selectedStoreId,selectedStoreText=options.selectedStoreText,storeList=storeListTemplate(stores,selectedStoreId,selectedStoreText);dialog.open({html:storeList,options:{title:Resources.SELECT_STORE+' - '+User.zip,buttons:[{text:Resources.CHANGE_LOCATION,click:function(){self.setUserZip(null);// trigger the event to start the process all over again +$('.set-preferred-store').trigger('click');}.bind(this)},{text:Resources.CONTINUE,click:function(){if(options.continueCallback){options.continueCallback(stores);}dialog.close();}}],open:function(){$('.select-store-button').on('click',function(e){e.preventDefault();var storeId=$(this).data('storeId');// if the store is already selected, don't select again +if(storeId===selectedStoreId){return;}$('.store-list .store-tile.selected').removeClass('selected').find('.select-store-button').text(Resources.SELECT_STORE);$(this).text(selectedStoreText).closest('.store-tile').addClass('selected');if(options.selectStoreCallback){options.selectStoreCallback(storeId);}});}}});},setUserZip:function(zip){User.zip=zip;$.ajax({type:'POST',url:Urls.setZipCode,data:{zipCode:zip}});},shippingLoad:function(){var $checkoutForm=$('.address');$checkoutForm.off('click');$checkoutForm.on('click','input[name$="_shippingAddress_isGift"]',function(){$(this).parent().siblings('.gift-message-text').toggleClass('hidden',$('input[name$="_shippingAddress_isGift"]:checked').val());});}};module.exports=storeinventory;},{"../dialog":12,"../util":53,"lodash":68,"promise":70}],49:[function(require,module,exports){'use strict';var _=require('lodash'),inventory=require('./');var newLine='\n';var pdpStoreTemplate=function(store){return['
      • ','
        '+store.address1+', '+store.city+' '+store.stateCode+' '+store.postalCode+'
        ','
        '+store.status+'
        ','
      • '].join(newLine);};var pdpStoresListingTemplate=function(stores){if(stores&&stores.length){return['
        ',stores.length>1?' ':'','
          ',_.map(stores,pdpStoreTemplate).join(newLine),'
        ','
        '].join(newLine);}};var storesListing=function(stores){// list all stores on PDP page +if($('.store-list-pdp-container').length){$('.store-list-pdp-container').remove();}$('.availability-results').append(pdpStoresListingTemplate(stores));};var productInventory={setPreferredStore:function(storeId){User.storeId=storeId;$.ajax({url:Urls.setPreferredStore,type:'POST',data:{storeId:storeId}});},productSelectStore:function(){var self=this;inventory.getStoresInventory(this.pid).then(function(stores){inventory.selectStoreDialog({stores:stores,selectedStoreId:User.storeId,selectedStoreText:Resources.PREFERRED_STORE,continueCallback:storesListing,selectStoreCallback:self.setPreferredStore});}).done();},init:function(){var $availabilityContainer=$('.availability-results'),self=this;this.pid=$('input[name="pid"]').val();$('#product-content .set-preferred-store').on('click',function(e){e.preventDefault();if(!User.zip){inventory.zipPrompt(function(){self.productSelectStore();});}else{self.productSelectStore();}});if($availabilityContainer.length){if(User.storeId){inventory.getStoresInventory(this.pid).then(storesListing);}// See more or less stores in the listing +$availabilityContainer.on('click','.stores-toggle',function(e){e.preventDefault();$('.store-list-pdp .store-list-item').toggleClass('visible');if($(this).hasClass('collapsed')){$(this).text(Resources.SEE_LESS);}else{$(this).text(Resources.SEE_MORE);}$(this).toggleClass('collapsed');});}}};module.exports=productInventory;},{"./":48,"lodash":68}],50:[function(require,module,exports){// This script is executed only on the checkout summary page +if((window.location.pathname.includes('COBilling-Billing')||window.location.pathname.includes('Adyen-ShowConfirmation'))&&window.isAdyenPayment){async function handleAction(action){window.Configuration.onAdditionalDetails=onAdditionalDetails;const checkout=await AdyenCheckout(window.Configuration);const actionContainer=document.getElementById('action-container');checkout.createFromAction(action).mount(actionContainer);}// onAdditionalDetails event handler to be included in Adyen Component configuration +var onAdditionalDetails=function(state){$.ajax({type:'POST',url:'Adyen-PaymentsDetails',data:JSON.stringify({data:state.data,orderToken:window.orderToken}),contentType:'application/json; charset=utf-8',async:false,success:function(data){if(!data.response.isFinal&&typeof data.response.action==='object'){handleAction(data.action);}else{window.location.href=data.response.redirectUrl;}}});};// serializes form data and submits to place order. Then proceeds to handle the result +function placeOrder(formId){const form=$('#'+formId);$.ajax({method:'POST',url:window.summarySubmitUrl,data:$(form).serialize(),success:function(data){if(data.action){window.orderToken=data.orderToken;document.getElementById('action-modal-SG').style.display="block";handleAction(data.action);}else{window.location.href=data.continueUrl;}},error:function(err){}});}window.addEventListener("load",function(){// Override default submit form behavior +const formId='submit-order-form';const form=document.getElementById(formId);form.addEventListener("submit",function(event){event.preventDefault();placeOrder(formId);});});}},{}],51:[function(require,module,exports){'use strict';/** + * Checks the TLS and displays a warning if appropriate + * @function getUserAgent Checks the TLS and displays a warning if appropriate + **/function getUserAgent(){// Use an external service to check the TLS of the browser +// NOTE: this implementation uses https://www.howsmyssl.com +// you may also wish to consider the API available at https://www.ssllabs.com/projects/ssllabs-apis/index.html +var url='https://www.howsmyssl.com/a/check';var cookieName='dw_TLSWarning';var cookieValue=getCookie(cookieName);// Test to see if this browser has already been flagged by looking at its cookies +if(!cookieValue){getTLS(url,function(message){if(message.length>0){showWarning(message[0]);// the browser is bad - set the cookie to true (for 15 minutes) +setCookie(cookieName,'true',15);}else{// else the browser is good, set the cookie to false (for 30 days) so we don't check again +setCookie(cookieName,'false',60*24*30);}});}else if(cookieValue==='true'){// if we already know that this is an invalid browser, show the warning +showWarning(Resources.TLS_WARNING);}}/** + * Calls out to the TLS service and calls the callback with a message (if necessary) + * @function getTLS + * + * @param {string} url - URL of external TLS-checking API + * @param {function} callback - function to call with response + **/function getTLS(url,callback){var message=[];// First, see if the browser is among the suspect browsers to see if a TLS check is necessary +var userAgent=navigator.userAgent;/** This list derived from https://www.ssllabs.com/ssltest/clients.html **/var badBrowsers=['MSIE 6.0','MSIE 7.0','MSIE 8.0','MSIE 9.0','MSIE 10.0','Android 2.3.7','Android 4.0.4','Android 4.1.1','Android 4.2.2','Android 4.3','Safari 5.1.9 / OS X 10.6.8','Safari 6.0.4 / OS X 10.8.4 '];function checkTLSLevel(data){// If we can determine the TLS level, check to see if it's less than 1.2 +if(parseFloat(data.tls_version.split(' ')[1])<1.1){message.push(Resources.TLS_WARNING);callback(message);//If you want to track statistics on bad TLS hits, include this call +$.ajax({url:Urls.TLSBadTLS});}}function reportBadBrowser(){// If the TLS level cannot be determined just report that this browser is suspect +message.push(Resources.TLS_WARNING);callback(message);//If you want to track statistics on deprecated browsers, include this call +$.ajax({url:Urls.TLSBadBrowser});}for(var i=0;i').addClass('browser-compatibility-alert').append($('

        ').addClass('browser-error').html(message)).appendTo('#browser-check');}/** + * @function getCookie + * + * @param {string} key - The cookie name + * @returns {string} value - the value of the cookie if found, null otherwise + **/function getCookie(key){var cookies=document.cookie.split(';');for(var i=0;i-1){hash=paramUrl.split('#')[1]||'';paramUrl=paramUrl.split('#')[0];}params=paramUrl.split('&');for(var i=0;iwindow.pageYOffset&&left+width>window.pageXOffset;}if(document.compatMode==='CSS1Compat'){return topwindow.document.documentElement.scrollTop&&left+width>window.document.documentElement.scrollLeft;}},/** + * @function + * @description Appends the parameter 'format=ajax' to a given path + * @param {String} path the relative path + */ajaxUrl:function(path){return this.appendParamToURL(path,'format','ajax');},/** + * @function + * @description + * @param {String} url + */toAbsoluteUrl:function(url){if(url.indexOf('http')!==0&&url.charAt(0)!=='/'){url='/'+url;}return url;},/** + * @function + * @description Loads css dynamically from given urls + * @param {Array} urls Array of urls from which css will be dynamically loaded. + */loadDynamicCss:function(urls){var i,len=urls.length;for(i=0;i').appendTo($('head')).attr({type:'text/css',rel:'stylesheet'}).attr('href',url);// for i.e. <9, href must be added after link has been appended to head +},// array to keep track of the dynamically loaded CSS files +loadedCssFiles:[],/** + * @function + * @description Removes all css files which were dynamically loaded + */clearDynamicCss:function(){var i=this.loadedCssFiles.length;while(0>i--){$(this.loadedCssFiles[i]).remove();}this.loadedCssFiles=[];},/** + * @function + * @description Extracts all parameters from a given query string into an object + * @param {String} qs The query string from which the parameters will be extracted + */getQueryStringParams:function(qs){if(!qs||qs.length===0){return{};}var params={},unescapedQS=decodeURIComponent(qs);// Use the String::replace method to iterate over each +// name-value pair in the string. +unescapedQS.replace(new RegExp('([^?=&]+)(=([^&]*))?','g'),function($0,$1,$2,$3){params[$1]=$3;});return params;},fillAddressFields:function(address,$form){for(var field in address){if(field==='ID'||field==='UUID'||field==='key'){continue;}// if the key in address object ends with 'Code', remove that suffix +// keys that ends with 'Code' are postalCode, stateCode and countryCode +$form.find('[name$="'+field.replace('Code','')+'"]').val(address[field]);// update the state fields +if(field==='countryCode'){$form.find('[name$="country"]').trigger('change');// retrigger state selection after country has changed +// this results in duplication of the state code, but is a necessary evil +// for now because sometimes countryCode comes after stateCode +$form.find('[name$="state"]').val(address.stateCode);}}},/** + * @function + * @description Updates the number of the remaining character + * based on the character limit in a text area + */limitCharacters:function(){$('form').find('textarea[data-character-limit]').each(function(){var characterLimit=$(this).data('character-limit');var charCountHtml=String.format(Resources.CHAR_LIMIT_MSG,''+characterLimit+'',''+characterLimit+'');var charCountContainer=$(this).next('div.char-count');if(charCountContainer.length===0){charCountContainer=$('

        ').insertAfter($(this));}charCountContainer.html(charCountHtml);// trigger the keydown event so that any existing character data is calculated +$(this).change();});},/** + * @function + * @description Binds the onclick-event to a delete button on a given container, + * which opens a confirmation box with a given message + * @param {String} container The name of element to which the function will be bind + * @param {String} message The message the will be shown upon a click + */setDeleteConfirmation:function(container,message){$(container).on('click','.delete',function(){return window.confirm(message);});},/** + * @function + * @description Scrolls a browser window to a given x point + * @param {String} The x coordinate + */scrollBrowser:function(xLocation){$('html, body').animate({scrollTop:xLocation},500);},isMobile:function(){var mobileAgentHash=['mobile','tablet','phone','ipad','ipod','android','blackberry','windows ce','opera mini','palm'];var idx=0;var isMobile=false;var userAgent=navigator.userAgent.toLowerCase();while(mobileAgentHash[idx]&&!isMobile){isMobile=userAgent.indexOf(mobileAgentHash[idx])>=0;idx++;}return isMobile;}};module.exports=util;},{"lodash":68}],54:[function(require,module,exports){'use strict';var naPhone=/^\(?([2-9][0-8][0-9])\)?[\-\. ]?([2-9][0-9]{2})[\-\. ]?([0-9]{4})(\s*x[0-9]+)?$/;var regex={phone:{us:naPhone,ca:naPhone,fr:/^0[1-6]{1}(([0-9]{2}){4})|((\s[0-9]{2}){4})|((-[0-9]{2}){4})$/,it:/^(([0-9]{2,4})([-\s\/]{0,1})([0-9]{4,8}))?$/,jp:/^(0\d{1,4}- ?)?\d{1,4}-\d{4}$/,cn:/.*/,gb:/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/},postal:{us:/^\d{5}(-\d{4})?$/,ca:/^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/,fr:/^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$/,it:/^([0-9]){5}$/,jp:/^([0-9]){3}[-]([0-9]){4}$/,cn:/^([0-9]){6}$/,gb:/^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/},notCC:/^(?!(([0-9 -]){13,19})).*$/};// global form validator settings +var settings={errorClass:'error',errorElement:'span',onkeyup:false,onfocusout:function(element){if(!this.checkable(element)){this.element(element);}}};/** + * @function + * @description Validates a given phone number against the countries phone regex + * @param {String} value The phone number which will be validated + * @param {String} el The input field + */var validatePhone=function(value,el){var country=$(el).closest('form').find('.country');if(country.length===0||country.val().length===0||!regex.phone[country.val().toLowerCase()]){return true;}var rgx=regex.phone[country.val().toLowerCase()];var isOptional=this.optional(el);var isValid=rgx.test($.trim(value));return isOptional||isValid;};/** + * @function + * @description Validates that a credit card owner is not a Credit card number + * @param {String} value The owner field which will be validated + * @param {String} el The input field + */var validateOwner=function(value){var isValid=regex.notCC.test($.trim(value));return isValid;};/** + * Add phone validation method to jQuery validation plugin. + * Text fields must have 'phone' css class to be validated as phone + */$.validator.addMethod('phone',validatePhone,Resources.INVALID_PHONE);/** + * Add CCOwner validation method to jQuery validation plugin. + * Text fields must have 'owner' css class to be validated as not a credit card + */$.validator.addMethod('owner',validateOwner,Resources.INVALID_OWNER);/** + * Add gift cert amount validation method to jQuery validation plugin. + * Text fields must have 'gift-cert-amont' css class to be validated + */$.validator.addMethod('gift-cert-amount',function(value,el){var isOptional=this.optional(el);var isValid=!isNaN(value)&&parseFloat(value)>=5&&parseFloat(value)<=5000;return isOptional||isValid;},Resources.GIFT_CERT_AMOUNT_INVALID);/** + * Add positive number validation method to jQuery validation plugin. + * Text fields must have 'positivenumber' css class to be validated as positivenumber + */$.validator.addMethod('positivenumber',function(value){if($.trim(value).length===0){return true;}return!isNaN(value)&&Number(value)>=0;},'');// '' should be replaced with error message if needed +$.extend($.validator.messages,{required:Resources.VALIDATE_REQUIRED,remote:Resources.VALIDATE_REMOTE,email:Resources.VALIDATE_EMAIL,url:Resources.VALIDATE_URL,date:Resources.VALIDATE_DATE,dateISO:Resources.VALIDATE_DATEISO,number:Resources.VALIDATE_NUMBER,digits:Resources.VALIDATE_DIGITS,creditcard:Resources.VALIDATE_CREDITCARD,equalTo:Resources.VALIDATE_EQUALTO,maxlength:$.validator.format(Resources.VALIDATE_MAXLENGTH),minlength:$.validator.format(Resources.VALIDATE_MINLENGTH),rangelength:$.validator.format(Resources.VALIDATE_RANGELENGTH),range:$.validator.format(Resources.VALIDATE_RANGE),max:$.validator.format(Resources.VALIDATE_MAX),min:$.validator.format(Resources.VALIDATE_MIN)});var validator={regex:regex,settings:settings,init:function(){var self=this;$('form:not(.suppress)').each(function(){$(this).validate(self.settings);});},initForm:function(f){$(f).validate(this.settings);}};module.exports=validator;},{}],55:[function(require,module,exports){"use strict";// rawAsap provides everything we need except exception management. +var rawAsap=require("./raw");// RawTasks are recycled to reduce GC churn. +var freeTasks=[];// We queue errors to ensure they are thrown in right order (FIFO). +// Array-as-queue is good enough here, since we are just dealing with exceptions. +var pendingErrors=[];var requestErrorThrow=rawAsap.makeRequestCallFromTimer(throwFirstError);function throwFirstError(){if(pendingErrors.length){throw pendingErrors.shift();}}/** + * Calls a task as soon as possible after returning, in its own event, with priority + * over other events like animation, reflow, and repaint. An error thrown from an + * event will not interrupt, nor even substantially slow down the processing of + * other events, but will be rather postponed to a lower priority event. + * @param {{call}} task A callable object, typically a function that takes no + * arguments. + */module.exports=asap;function asap(task){var rawTask;if(freeTasks.length){rawTask=freeTasks.pop();}else{rawTask=new RawTask();}rawTask.task=task;rawAsap(rawTask);}// We wrap tasks with recyclable task objects. A task object implements +// `call`, just like a function. +function RawTask(){this.task=null;}// The sole purpose of wrapping the task is to catch the exception and recycle +// the task object after its single use. +RawTask.prototype.call=function(){try{this.task.call();}catch(error){if(asap.onerror){// This hook exists purely for testing purposes. +// Its name will be periodically randomized to break any code that +// depends on its existence. +asap.onerror(error);}else{// In a web browser, exceptions are not fatal. However, to avoid +// slowing down the queue of pending tasks, we rethrow the error in a +// lower priority turn. +pendingErrors.push(error);requestErrorThrow();}}finally{this.task=null;freeTasks[freeTasks.length]=this;}};},{"./raw":56}],56:[function(require,module,exports){(function(global){(function(){"use strict";// Use the fastest means possible to execute a task in its own turn, with +// priority over other events including IO, animation, reflow, and redraw +// events in browsers. +// +// An exception thrown by a task will permanently interrupt the processing of +// subsequent tasks. The higher level `asap` function ensures that if an +// exception is thrown by a task, that the task queue will continue flushing as +// soon as possible, but if you use `rawAsap` directly, you are responsible to +// either ensure that no exceptions are thrown from your task, or to manually +// call `rawAsap.requestFlush` if an exception is thrown. +module.exports=rawAsap;function rawAsap(task){if(!queue.length){requestFlush();flushing=true;}// Equivalent to push, but avoids a function call. +queue[queue.length]=task;}var queue=[];// Once a flush has been requested, no further calls to `requestFlush` are +// necessary until the next `flush` completes. +var flushing=false;// `requestFlush` is an implementation-specific method that attempts to kick +// off a `flush` event as quickly as possible. `flush` will attempt to exhaust +// the event queue before yielding to the browser's own event loop. +var requestFlush;// The position of the next task to execute in the task queue. This is +// preserved between calls to `flush` so that it can be resumed if +// a task throws an exception. +var index=0;// If a task schedules additional tasks recursively, the task queue can grow +// unbounded. To prevent memory exhaustion, the task queue will periodically +// truncate already-completed tasks. +var capacity=1024;// The flush function processes all tasks that have been scheduled with +// `rawAsap` unless and until one of those tasks throws an exception. +// If a task throws an exception, `flush` ensures that its state will remain +// consistent and will resume where it left off when called again. +// However, `flush` does not make any arrangements to be called again if an +// exception is thrown. +function flush(){while(indexcapacity){// Manually shift all values starting at the index back to the +// beginning of the queue. +for(var scan=0,newLength=queue.length-index;scan-1){return callBind(intrinsic);}return intrinsic;};},{"./":59,"get-intrinsic":63}],59:[function(require,module,exports){'use strict';var bind=require('function-bind');var GetIntrinsic=require('get-intrinsic');var $apply=GetIntrinsic('%Function.prototype.apply%');var $call=GetIntrinsic('%Function.prototype.call%');var $reflectApply=GetIntrinsic('%Reflect.apply%',true)||bind.call($call,$apply);var $gOPD=GetIntrinsic('%Object.getOwnPropertyDescriptor%',true);var $defineProperty=GetIntrinsic('%Object.defineProperty%',true);var $max=GetIntrinsic('%Math.max%');if($defineProperty){try{$defineProperty({},'a',{value:1});}catch(e){// IE 8 has a broken defineProperty +$defineProperty=null;}}module.exports=function callBind(originalFunction){var func=$reflectApply(bind,$call,arguments);if($gOPD&&$defineProperty){var desc=$gOPD(func,'length');if(desc.configurable){// original length, plus the receiver, minus any additional arguments (after the receiver) +$defineProperty(func,'length',{value:1+$max(0,originalFunction.length-(arguments.length-1))});}}return func;};var applyBind=function applyBind(){return $reflectApply(bind,$apply,arguments);};if($defineProperty){$defineProperty(module.exports,'apply',{value:applyBind});}else{module.exports.apply=applyBind;}},{"function-bind":62,"get-intrinsic":63}],60:[function(require,module,exports){/*! + * eventie v1.0.6 + * event binding helper + * eventie.bind( elem, 'click', myFn ) + * eventie.unbind( elem, 'click', myFn ) + * MIT license + */ /*jshint browser: true, undef: true, unused: true */ /*global define: false, module: false */(function(window){'use strict';var docElem=document.documentElement;var bind=function(){};function getIEEvent(obj){var event=window.event;// add event.target +event.target=event.target||event.srcElement||obj;return event;}if(docElem.addEventListener){bind=function(obj,type,fn){obj.addEventListener(type,fn,false);};}else if(docElem.attachEvent){bind=function(obj,type,fn){obj[type+fn]=fn.handleEvent?function(){var event=getIEEvent(obj);fn.handleEvent.call(fn,event);}:function(){var event=getIEEvent(obj);fn.call(obj,event);};obj.attachEvent("on"+type,obj[type+fn]);};}var unbind=function(){};if(docElem.removeEventListener){unbind=function(obj,type,fn){obj.removeEventListener(type,fn,false);};}else if(docElem.detachEvent){unbind=function(obj,type,fn){obj.detachEvent("on"+type,obj[type+fn]);try{delete obj[type+fn];}catch(err){// can't delete window object properties +obj[type+fn]=undefined;}};}var eventie={bind:bind,unbind:unbind};// ----- module definition ----- // +if(typeof define==='function'&&define.amd){// AMD +define(eventie);}else if(typeof exports==='object'){// CommonJS +module.exports=eventie;}else{// browser global +window.eventie=eventie;}})(window);},{}],61:[function(require,module,exports){'use strict';/* eslint no-invalid-this: 1 */var ERROR_MESSAGE='Function.prototype.bind called on incompatible ';var slice=Array.prototype.slice;var toStr=Object.prototype.toString;var funcType='[object Function]';module.exports=function bind(that){var target=this;if(typeof target!=='function'||toStr.call(target)!==funcType){throw new TypeError(ERROR_MESSAGE+target);}var args=slice.call(arguments,1);var bound;var binder=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));if(Object(result)===result){return result;}return this;}else{return target.apply(that,args.concat(slice.call(arguments)));}};var boundLength=Math.max(0,target.length-args.length);var boundArgs=[];for(var i=0;i1&&typeof allowMissing!=='boolean'){throw new $TypeError('"allowMissing" argument must be a boolean');}var parts=stringToPath(name);var intrinsicBaseName=parts.length>0?parts[0]:'';var intrinsic=getBaseIntrinsic('%'+intrinsicBaseName+'%',allowMissing);var intrinsicRealName=intrinsic.name;var value=intrinsic.value;var skipFurtherCaching=false;var alias=intrinsic.alias;if(alias){intrinsicBaseName=alias[0];$spliceApply(parts,$concat([0,1],alias));}for(var i=1,isOwn=true;i=parts.length){var desc=$gOPD(value,part);isOwn=!!desc;// By convention, when a data property is converted to an accessor +// property to emulate a data property that does not suffer from +// the override mistake, that accessor's getter is marked with +// an `originalValue` property. Here, when we detect this, we +// uphold the illusion by pretending to see that original data +// property, i.e., returning the value rather than the getter +// itself. +if(isOwn&&'get'in desc&&!('originalValue'in desc.get)){value=desc.get;}else{value=value[part];}}else{isOwn=hasOwn(value,part);value=value[part];}if(isOwn&&!skipFurtherCaching){INTRINSICS[intrinsicRealName]=value;}}}return value;};},{"function-bind":62,"has":66,"has-symbols":64}],64:[function(require,module,exports){'use strict';var origSymbol=typeof Symbol!=='undefined'&&Symbol;var hasSymbolSham=require('./shams');module.exports=function hasNativeSymbols(){if(typeof origSymbol!=='function'){return false;}if(typeof Symbol!=='function'){return false;}if(typeof origSymbol('foo')!=='symbol'){return false;}if(typeof Symbol('bar')!=='symbol'){return false;}return hasSymbolSham();};},{"./shams":65}],65:[function(require,module,exports){'use strict';/* eslint complexity: [2, 18], max-statements: [2, 33] */module.exports=function hasSymbols(){if(typeof Symbol!=='function'||typeof Object.getOwnPropertySymbols!=='function'){return false;}if(typeof Symbol.iterator==='symbol'){return true;}var obj={};var sym=Symbol('test');var symObj=Object(sym);if(typeof sym==='string'){return false;}if(Object.prototype.toString.call(sym)!=='[object Symbol]'){return false;}if(Object.prototype.toString.call(symObj)!=='[object Symbol]'){return false;}// temp disabled per https://github.com/ljharb/object.assign/issues/17 +// if (sym instanceof Symbol) { return false; } +// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 +// if (!(symObj instanceof Symbol)) { return false; } +// if (typeof Symbol.prototype.toString !== 'function') { return false; } +// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } +var symVal=42;obj[sym]=symVal;for(sym in obj){return false;}// eslint-disable-line no-restricted-syntax, no-unreachable-loop +if(typeof Object.keys==='function'&&Object.keys(obj).length!==0){return false;}if(typeof Object.getOwnPropertyNames==='function'&&Object.getOwnPropertyNames(obj).length!==0){return false;}var syms=Object.getOwnPropertySymbols(obj);if(syms.length!==1||syms[0]!==sym){return false;}if(!Object.prototype.propertyIsEnumerable.call(obj,sym)){return false;}if(typeof Object.getOwnPropertyDescriptor==='function'){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(descriptor.value!==symVal||descriptor.enumerable!==true){return false;}}return true;};},{}],66:[function(require,module,exports){'use strict';var bind=require('function-bind');module.exports=bind.call(Function.call,Object.prototype.hasOwnProperty);},{"function-bind":62}],67:[function(require,module,exports){/*! + * imagesLoaded v3.2.0 + * JavaScript is all like "You images are done yet or what?" + * MIT License + */(function(window,factory){'use strict';// universal module definition +/*global define: false, module: false, require: false */if(typeof define=='function'&&define.amd){// AMD +define(['eventEmitter/EventEmitter','eventie/eventie'],function(EventEmitter,eventie){return factory(window,EventEmitter,eventie);});}else if(typeof module=='object'&&module.exports){// CommonJS +module.exports=factory(window,require('wolfy87-eventemitter'),require('eventie'));}else{// browser global +window.imagesLoaded=factory(window,window.EventEmitter,window.eventie);}})(window,// -------------------------- factory -------------------------- // +function factory(window,EventEmitter,eventie){'use strict';var $=window.jQuery;var console=window.console;// -------------------------- helpers -------------------------- // +// extend objects +function extend(a,b){for(var prop in b){a[prop]=b[prop];}return a;}var objToString=Object.prototype.toString;function isArray(obj){return objToString.call(obj)=='[object Array]';}// turn element or nodeList into an array +function makeArray(obj){var ary=[];if(isArray(obj)){// use object if already an array +ary=obj;}else if(typeof obj.length=='number'){// convert nodeList to array +for(var i=0;i + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */;(function(){/** Used as a safe reference for `undefined` in pre-ES5 environments. */var undefined;/** Used as the semantic version number. */var VERSION='4.17.21';/** Used as the size to enable large array optimizations. */var LARGE_ARRAY_SIZE=200;/** Error message constants. */var CORE_ERROR_TEXT='Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',FUNC_ERROR_TEXT='Expected a function',INVALID_TEMPL_VAR_ERROR_TEXT='Invalid `variable` option passed into `_.template`';/** Used to stand-in for `undefined` hash values. */var HASH_UNDEFINED='__lodash_hash_undefined__';/** Used as the maximum memoize cache size. */var MAX_MEMOIZE_SIZE=500;/** Used as the internal argument placeholder. */var PLACEHOLDER='__lodash_placeholder__';/** Used to compose bitmasks for cloning. */var CLONE_DEEP_FLAG=1,CLONE_FLAT_FLAG=2,CLONE_SYMBOLS_FLAG=4;/** Used to compose bitmasks for value comparisons. */var COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;/** Used to compose bitmasks for function metadata. */var WRAP_BIND_FLAG=1,WRAP_BIND_KEY_FLAG=2,WRAP_CURRY_BOUND_FLAG=4,WRAP_CURRY_FLAG=8,WRAP_CURRY_RIGHT_FLAG=16,WRAP_PARTIAL_FLAG=32,WRAP_PARTIAL_RIGHT_FLAG=64,WRAP_ARY_FLAG=128,WRAP_REARG_FLAG=256,WRAP_FLIP_FLAG=512;/** Used as default options for `_.truncate`. */var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION='...';/** Used to detect hot functions by number of calls within a span of milliseconds. */var HOT_COUNT=800,HOT_SPAN=16;/** Used to indicate the type of lazy iteratees. */var LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3;/** Used as references for various `Number` constants. */var INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e+308,NAN=0/0;/** Used as references for the maximum length and index of an array. */var MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1;/** Used to associate wrap methods with their bit flags. */var wrapFlags=[['ary',WRAP_ARY_FLAG],['bind',WRAP_BIND_FLAG],['bindKey',WRAP_BIND_KEY_FLAG],['curry',WRAP_CURRY_FLAG],['curryRight',WRAP_CURRY_RIGHT_FLAG],['flip',WRAP_FLIP_FLAG],['partial',WRAP_PARTIAL_FLAG],['partialRight',WRAP_PARTIAL_RIGHT_FLAG],['rearg',WRAP_REARG_FLAG]];/** `Object#toString` result references. */var argsTag='[object Arguments]',arrayTag='[object Array]',asyncTag='[object AsyncFunction]',boolTag='[object Boolean]',dateTag='[object Date]',domExcTag='[object DOMException]',errorTag='[object Error]',funcTag='[object Function]',genTag='[object GeneratorFunction]',mapTag='[object Map]',numberTag='[object Number]',nullTag='[object Null]',objectTag='[object Object]',promiseTag='[object Promise]',proxyTag='[object Proxy]',regexpTag='[object RegExp]',setTag='[object Set]',stringTag='[object String]',symbolTag='[object Symbol]',undefinedTag='[object Undefined]',weakMapTag='[object WeakMap]',weakSetTag='[object WeakSet]';var arrayBufferTag='[object ArrayBuffer]',dataViewTag='[object DataView]',float32Tag='[object Float32Array]',float64Tag='[object Float64Array]',int8Tag='[object Int8Array]',int16Tag='[object Int16Array]',int32Tag='[object Int32Array]',uint8Tag='[object Uint8Array]',uint8ClampedTag='[object Uint8ClampedArray]',uint16Tag='[object Uint16Array]',uint32Tag='[object Uint32Array]';/** Used to match empty string literals in compiled template source. */var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;/** Used to match HTML entities and HTML characters. */var reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source);/** Used to match template delimiters. */var reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g;/** Used to match property names within property paths. */var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source);/** Used to match leading whitespace. */var reTrimStart=/^\s+/;/** Used to match a single whitespace character. */var reWhitespace=/\s/;/** Used to match wrap detail comments. */var reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /;/** Used to match words composed of alphanumeric characters. */var reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;/** + * Used to validate the `validate` option in `_.template` variable. + * + * Forbids characters which could potentially change the meaning of the function argument definition: + * - "()," (modification of function parameters) + * - "=" (default value) + * - "[]{}" (destructuring of function parameters) + * - "/" (beginning of a comment) + * - whitespace + */var reForbiddenIdentifierChars=/[()=,{}\[\]\/\s]/;/** Used to match backslashes in property paths. */var reEscapeChar=/\\(\\)?/g;/** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;/** Used to match `RegExp` flags from their coerced string values. */var reFlags=/\w*$/;/** 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 host constructors (Safari). */var reIsHostCtor=/^\[object .+?Constructor\]$/;/** Used to detect octal string values. */var reIsOctal=/^0o[0-7]+$/i;/** Used to detect unsigned integer values. */var reIsUint=/^(?:0|[1-9]\d*)$/;/** Used to match Latin Unicode letters (excluding mathematical operators). */var reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;/** Used to ensure capturing order of template delimiters. */var reNoMatch=/($^)/;/** Used to match unescaped characters in compiled string literals. */var reUnescapedString=/['\n\r\u2028\u2029\\]/g;/** Used to compose unicode character classes. */var rsAstralRange='\\ud800-\\udfff',rsComboMarksRange='\\u0300-\\u036f',reComboHalfMarksRange='\\ufe20-\\ufe2f',rsComboSymbolsRange='\\u20d0-\\u20ff',rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsDingbatRange='\\u2700-\\u27bf',rsLowerRange='a-z\\xdf-\\xf6\\xf8-\\xff',rsMathOpRange='\\xac\\xb1\\xd7\\xf7',rsNonCharRange='\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',rsPunctuationRange='\\u2000-\\u206f',rsSpaceRange=' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',rsUpperRange='A-Z\\xc0-\\xd6\\xd8-\\xde',rsVarRange='\\ufe0e\\ufe0f',rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange;/** Used to compose unicode capture groups. */var rsApos="['\u2019]",rsAstral='['+rsAstralRange+']',rsBreak='['+rsBreakRange+']',rsCombo='['+rsComboRange+']',rsDigits='\\d+',rsDingbat='['+rsDingbatRange+']',rsLower='['+rsLowerRange+']',rsMisc='[^'+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+']',rsFitz='\\ud83c[\\udffb-\\udfff]',rsModifier='(?:'+rsCombo+'|'+rsFitz+')',rsNonAstral='[^'+rsAstralRange+']',rsRegional='(?:\\ud83c[\\udde6-\\uddff]){2}',rsSurrPair='[\\ud800-\\udbff][\\udc00-\\udfff]',rsUpper='['+rsUpperRange+']',rsZWJ='\\u200d';/** Used to compose unicode regexes. */var rsMiscLower='(?:'+rsLower+'|'+rsMisc+')',rsMiscUpper='(?:'+rsUpper+'|'+rsMisc+')',rsOptContrLower='(?:'+rsApos+'(?:d|ll|m|re|s|t|ve))?',rsOptContrUpper='(?:'+rsApos+'(?:D|LL|M|RE|S|T|VE))?',reOptMod=rsModifier+'?',rsOptVar='['+rsVarRange+']?',rsOptJoin='(?:'+rsZWJ+'(?:'+[rsNonAstral,rsRegional,rsSurrPair].join('|')+')'+rsOptVar+reOptMod+')*',rsOrdLower='\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',rsOrdUpper='\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji='(?:'+[rsDingbat,rsRegional,rsSurrPair].join('|')+')'+rsSeq,rsSymbol='(?:'+[rsNonAstral+rsCombo+'?',rsCombo,rsRegional,rsSurrPair,rsAstral].join('|')+')';/** Used to match apostrophes. */var reApos=RegExp(rsApos,'g');/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */var reComboMark=RegExp(rsCombo,'g');/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */var reUnicode=RegExp(rsFitz+'(?='+rsFitz+')|'+rsSymbol+rsSeq,'g');/** Used to match complex or compound words. */var reUnicodeWord=RegExp([rsUpper+'?'+rsLower+'+'+rsOptContrLower+'(?='+[rsBreak,rsUpper,'$'].join('|')+')',rsMiscUpper+'+'+rsOptContrUpper+'(?='+[rsBreak,rsUpper+rsMiscLower,'$'].join('|')+')',rsUpper+'?'+rsMiscLower+'+'+rsOptContrLower,rsUpper+'+'+rsOptContrUpper,rsOrdUpper,rsOrdLower,rsDigits,rsEmoji].join('|'),'g');/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */var reHasUnicode=RegExp('['+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+']');/** Used to detect strings that need a more robust regexp to match words. */var reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;/** Used to assign default `context` object properties. */var contextProps=['Array','Buffer','DataView','Date','Error','Float32Array','Float64Array','Function','Int8Array','Int16Array','Int32Array','Map','Math','Object','Promise','RegExp','Set','String','Symbol','TypeError','Uint8Array','Uint8ClampedArray','Uint16Array','Uint32Array','WeakMap','_','clearTimeout','isFinite','parseInt','setTimeout'];/** Used to make template sourceURLs easier to identify. */var templateCounter=-1;/** Used to identify `toStringTag` values of typed arrays. */var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;/** Used to identify `toStringTag` values supported by `_.clone`. */var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=false;/** Used to map Latin Unicode letters to basic Latin letters. */var deburredLetters={// Latin-1 Supplement block. +'\xc0':'A','\xc1':'A','\xc2':'A','\xc3':'A','\xc4':'A','\xc5':'A','\xe0':'a','\xe1':'a','\xe2':'a','\xe3':'a','\xe4':'a','\xe5':'a','\xc7':'C','\xe7':'c','\xd0':'D','\xf0':'d','\xc8':'E','\xc9':'E','\xca':'E','\xcb':'E','\xe8':'e','\xe9':'e','\xea':'e','\xeb':'e','\xcc':'I','\xcd':'I','\xce':'I','\xcf':'I','\xec':'i','\xed':'i','\xee':'i','\xef':'i','\xd1':'N','\xf1':'n','\xd2':'O','\xd3':'O','\xd4':'O','\xd5':'O','\xd6':'O','\xd8':'O','\xf2':'o','\xf3':'o','\xf4':'o','\xf5':'o','\xf6':'o','\xf8':'o','\xd9':'U','\xda':'U','\xdb':'U','\xdc':'U','\xf9':'u','\xfa':'u','\xfb':'u','\xfc':'u','\xdd':'Y','\xfd':'y','\xff':'y','\xc6':'Ae','\xe6':'ae','\xde':'Th','\xfe':'th','\xdf':'ss',// Latin Extended-A block. +'\u0100':'A','\u0102':'A','\u0104':'A','\u0101':'a','\u0103':'a','\u0105':'a','\u0106':'C','\u0108':'C','\u010a':'C','\u010c':'C','\u0107':'c','\u0109':'c','\u010b':'c','\u010d':'c','\u010e':'D','\u0110':'D','\u010f':'d','\u0111':'d','\u0112':'E','\u0114':'E','\u0116':'E','\u0118':'E','\u011a':'E','\u0113':'e','\u0115':'e','\u0117':'e','\u0119':'e','\u011b':'e','\u011c':'G','\u011e':'G','\u0120':'G','\u0122':'G','\u011d':'g','\u011f':'g','\u0121':'g','\u0123':'g','\u0124':'H','\u0126':'H','\u0125':'h','\u0127':'h','\u0128':'I','\u012a':'I','\u012c':'I','\u012e':'I','\u0130':'I','\u0129':'i','\u012b':'i','\u012d':'i','\u012f':'i','\u0131':'i','\u0134':'J','\u0135':'j','\u0136':'K','\u0137':'k','\u0138':'k','\u0139':'L','\u013b':'L','\u013d':'L','\u013f':'L','\u0141':'L','\u013a':'l','\u013c':'l','\u013e':'l','\u0140':'l','\u0142':'l','\u0143':'N','\u0145':'N','\u0147':'N','\u014a':'N','\u0144':'n','\u0146':'n','\u0148':'n','\u014b':'n','\u014c':'O','\u014e':'O','\u0150':'O','\u014d':'o','\u014f':'o','\u0151':'o','\u0154':'R','\u0156':'R','\u0158':'R','\u0155':'r','\u0157':'r','\u0159':'r','\u015a':'S','\u015c':'S','\u015e':'S','\u0160':'S','\u015b':'s','\u015d':'s','\u015f':'s','\u0161':'s','\u0162':'T','\u0164':'T','\u0166':'T','\u0163':'t','\u0165':'t','\u0167':'t','\u0168':'U','\u016a':'U','\u016c':'U','\u016e':'U','\u0170':'U','\u0172':'U','\u0169':'u','\u016b':'u','\u016d':'u','\u016f':'u','\u0171':'u','\u0173':'u','\u0174':'W','\u0175':'w','\u0176':'Y','\u0177':'y','\u0178':'Y','\u0179':'Z','\u017b':'Z','\u017d':'Z','\u017a':'z','\u017c':'z','\u017e':'z','\u0132':'IJ','\u0133':'ij','\u0152':'Oe','\u0153':'oe','\u0149':"'n",'\u017f':'s'};/** Used to map characters to HTML entities. */var htmlEscapes={'&':'&','<':'<','>':'>','"':'"',"'":'''};/** Used to map HTML entities to characters. */var htmlUnescapes={'&':'&','<':'<','>':'>','"':'"',''':"'"};/** Used to escape characters for inclusion in compiled string literals. */var stringEscapes={'\\':'\\',"'":"'",'\n':'n','\r':'r','\u2028':'u2028','\u2029':'u2029'};/** Built-in method references without a dependency on `root`. */var freeParseFloat=parseFloat,freeParseInt=parseInt;/** Detect free variable `global` from Node.js. */var freeGlobal=typeof global=='object'&&global&&global.Object===Object&&global;/** Detect free variable `self`. */var freeSelf=typeof self=='object'&&self&&self.Object===Object&&self;/** Used as a reference to the global object. */var root=freeGlobal||freeSelf||Function('return this')();/** Detect free variable `exports`. */var freeExports=typeof exports=='object'&&exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule=freeExports&&typeof module=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports=freeModule&&freeModule.exports===freeExports;/** Detect free variable `process` from Node.js. */var freeProcess=moduleExports&&freeGlobal.process;/** Used to access faster Node.js helpers. */var nodeUtil=function(){try{// Use `util.types` for Node.js 10+. +var types=freeModule&&freeModule.require&&freeModule.require('util').types;if(types){return types;}// Legacy `process.binding('util')` for Node.js < 10. +return freeProcess&&freeProcess.binding&&freeProcess.binding('util');}catch(e){}}();/* Node.js helper references. */var nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray;/*--------------------------------------------------------------------------*/ /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2]);}return func.apply(thisArg,args);}/** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */function arrayAggregator(array,setter,iteratee,accumulator){var index=-1,length=array==null?0:array.length;while(++index-1;}/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */function arrayIncludesWith(array,value,comparator){var index=-1,length=array==null?0:array.length;while(++index-1){}return index;}/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */function charsEndIndex(strSymbols,chrSymbols){var index=strSymbols.length;while(index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}return index;}/** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */function countHolders(array,placeholder){var length=array.length,result=0;while(length--){if(array[length]===placeholder){++result;}}return result;}/** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */var deburrLetter=basePropertyOf(deburredLetters);/** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */var escapeHtmlChar=basePropertyOf(htmlEscapes);/** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */function escapeStringChar(chr){return'\\'+stringEscapes[chr];}/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */function getValue(object,key){return object==null?undefined:object[key];}/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */function hasUnicode(string){return reHasUnicode.test(string);}/** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */function hasUnicodeWord(string){return reHasUnicodeWord.test(string);}/** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */function iteratorToArray(iterator){var data,result=[];while(!(data=iterator.next()).done){result.push(data.value);}return result;}/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */function mapToArray(map){var index=-1,result=Array(map.size);map.forEach(function(value,key){result[++index]=[key,value];});return result;}/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */function overArg(func,transform){return function(arg){return func(transform(arg));};}/** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */function replaceHolders(array,placeholder){var index=-1,length=array.length,resIndex=0,result=[];while(++index true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */var runInContext=function runInContext(context){context=context==null?root:_.defaults(root.Object(),context,_.pick(root,contextProps));/** Built-in constructor references. */var Array=context.Array,Date=context.Date,Error=context.Error,Function=context.Function,Math=context.Math,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;/** Used for built-in method references. */var arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype;/** Used to detect overreaching core-js shims. */var coreJsData=context['__core-js_shared__'];/** Used to resolve the decompiled source of functions. */var funcToString=funcProto.toString;/** Used to check objects for own properties. */var hasOwnProperty=objectProto.hasOwnProperty;/** Used to generate unique IDs. */var idCounter=0;/** Used to detect methods masquerading as native. */var maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||'');return uid?'Symbol(src)_1.'+uid:'';}();/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */var nativeObjectToString=objectProto.toString;/** Used to infer the `Object` constructor. */var objectCtorString=funcToString.call(Object);/** Used to restore the original `_` reference in `_.noConflict`. */var oldDash=root._;/** Used to detect if a method is native. */var reIsNative=RegExp('^'+funcToString.call(hasOwnProperty).replace(reRegExpChar,'\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,'$1.*?')+'$');/** Built-in value references. */var Buffer=moduleExports?context.Buffer:undefined,Symbol=context.Symbol,Uint8Array=context.Uint8Array,allocUnsafe=Buffer?Buffer.allocUnsafe:undefined,getPrototype=overArg(Object.getPrototypeOf,Object),objectCreate=Object.create,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:undefined,symIterator=Symbol?Symbol.iterator:undefined,symToStringTag=Symbol?Symbol.toStringTag:undefined;var defineProperty=function(){try{var func=getNative(Object,'defineProperty');func({},'',{});return func;}catch(e){}}();/** Mocked built-ins. */var ctxClearTimeout=context.clearTimeout!==root.clearTimeout&&context.clearTimeout,ctxNow=Date&&Date.now!==root.Date.now&&Date.now,ctxSetTimeout=context.setTimeout!==root.setTimeout&&context.setTimeout;/* Built-in method references for those with the same name as other `lodash` methods. */var nativeCeil=Math.ceil,nativeFloor=Math.floor,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:undefined,nativeIsFinite=context.isFinite,nativeJoin=arrayProto.join,nativeKeys=overArg(Object.keys,Object),nativeMax=Math.max,nativeMin=Math.min,nativeNow=Date.now,nativeParseInt=context.parseInt,nativeRandom=Math.random,nativeReverse=arrayProto.reverse;/* Built-in method references that are verified to be native. */var DataView=getNative(context,'DataView'),Map=getNative(context,'Map'),Promise=getNative(context,'Promise'),Set=getNative(context,'Set'),WeakMap=getNative(context,'WeakMap'),nativeCreate=getNative(Object,'create');/** Used to store function metadata. */var metaMap=WeakMap&&new WeakMap();/** Used to lookup unminified function names. */var realNames={};/** Used to detect maps, sets, and weakmaps. */var dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap);/** Used to convert symbols to primitives and strings. */var symbolProto=Symbol?Symbol.prototype:undefined,symbolValueOf=symbolProto?symbolProto.valueOf:undefined,symbolToString=symbolProto?symbolProto.toString:undefined;/*------------------------------------------------------------------------*/ /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper){return value;}if(hasOwnProperty.call(value,'__wrapped__')){return wrapperClone(value);}}return new LodashWrapper(value);}/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */var baseCreate=function(){function object(){}return function(proto){if(!isObject(proto)){return{};}if(objectCreate){return objectCreate(proto);}object.prototype=proto;var result=new object();object.prototype=undefined;return result;};}();/** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */function baseLodash(){// No operation performed. +}/** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */function LodashWrapper(value,chainAll){this.__wrapped__=value;this.__actions__=[];this.__chain__=!!chainAll;this.__index__=0;this.__values__=undefined;}/** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */lodash.templateSettings={/** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */'escape':reEscape,/** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */'evaluate':reEvaluate,/** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */'interpolate':reInterpolate,/** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */'variable':'',/** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */'imports':{/** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */'_':lodash}};// Ensure wrappers are instances of `baseLodash`. +lodash.prototype=baseLodash.prototype;lodash.prototype.constructor=lodash;LodashWrapper.prototype=baseCreate(baseLodash.prototype);LodashWrapper.prototype.constructor=LodashWrapper;/*------------------------------------------------------------------------*/ /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */function LazyWrapper(value){this.__wrapped__=value;this.__actions__=[];this.__dir__=1;this.__filtered__=false;this.__iteratees__=[];this.__takeCount__=MAX_ARRAY_LENGTH;this.__views__=[];}/** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */function lazyClone(){var result=new LazyWrapper(this.__wrapped__);result.__actions__=copyArray(this.__actions__);result.__dir__=this.__dir__;result.__filtered__=this.__filtered__;result.__iteratees__=copyArray(this.__iteratees__);result.__takeCount__=this.__takeCount__;result.__views__=copyArray(this.__views__);return result;}/** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1;result.__filtered__=true;}else{result=this.clone();result.__dir__*=-1;}return result;}/** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=dir<0,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||!isRight&&arrLength==length&&takeCount==length){return baseWrapperValue(array,this.__actions__);}var result=[];outer:while(length--&&resIndex-1;}/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){++this.size;data.push([key,value]);}else{data[index][1]=value;}return this;}// Add methods to `ListCache`. +ListCache.prototype.clear=listCacheClear;ListCache.prototype['delete']=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;/*------------------------------------------------------------------------*/ /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */function MapCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index=lower?number:lower;}}return number;}/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */function baseClone(value,bitmask,customizer,key,object,stack){var result,isDeep=bitmask&CLONE_DEEP_FLAG,isFlat=bitmask&CLONE_FLAT_FLAG,isFull=bitmask&CLONE_SYMBOLS_FLAG;if(customizer){result=object?customizer(value,key,object,stack):customizer(value);}if(result!==undefined){return result;}if(!isObject(value)){return value;}var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return copyArray(value,result);}}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value)){return cloneBuffer(value,isDeep);}if(tag==objectTag||tag==argsTag||isFunc&&!object){result=isFlat||isFunc?{}:initCloneObject(value);if(!isDeep){return isFlat?copySymbolsIn(value,baseAssignIn(result,value)):copySymbols(value,baseAssign(result,value));}}else{if(!cloneableTags[tag]){return object?value:{};}result=initCloneByTag(value,tag,isDeep);}}// Check for circular references and return its corresponding clone. +stack||(stack=new Stack());var stacked=stack.get(value);if(stacked){return stacked;}stack.set(value,result);if(isSet(value)){value.forEach(function(subValue){result.add(baseClone(subValue,bitmask,customizer,subValue,value,stack));});}else if(isMap(value)){value.forEach(function(subValue,key){result.set(key,baseClone(subValue,bitmask,customizer,key,value,stack));});}var keysFunc=isFull?isFlat?getAllKeysIn:getAllKeys:isFlat?keysIn:keys;var props=isArr?undefined:keysFunc(value);arrayEach(props||value,function(subValue,key){if(props){key=subValue;subValue=value[key];}// Recursively populate clone (susceptible to call stack limits). +assignValue(result,key,baseClone(subValue,bitmask,customizer,key,value,stack));});return result;}/** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props);};}/** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */function baseConformsTo(object,source,props){var length=props.length;if(object==null){return!length;}object=Object(object);while(length--){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value)){return false;}}return true;}/** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */function baseDelay(func,wait,args){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return setTimeout(function(){func.apply(undefined,args);},wait);}/** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=true,length=array.length,result=[],valuesLength=values.length;if(!length){return result;}if(iteratee){values=arrayMap(values,baseUnary(iteratee));}if(comparator){includes=arrayIncludesWith;isCommon=false;}else if(values.length>=LARGE_ARRAY_SIZE){includes=cacheHas;isCommon=false;values=new SetCache(values);}outer:while(++indexlength?0:length+start;}end=end===undefined||end>length?length:toInteger(end);if(end<0){end+=length;}end=start>end?0:toLength(end);while(start0&&predicate(value)){if(depth>1){// Recursively flatten arrays (susceptible to call stack limits). +baseFlatten(value,depth-1,predicate,isStrict,result);}else{arrayPush(result,value);}}else if(!isStrict){result[result.length]=value;}}return result;}/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */var baseFor=createBaseFor();/** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */var baseForRight=createBaseFor(true);/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys);}/** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys);}/** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key]);});}/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */function baseGet(object,path){path=castPath(path,object);var index=0,length=path.length;while(object!=null&&indexother;}/** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */function baseHas(object,key){return object!=null&&hasOwnProperty.call(object,key);}/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */function baseHasIn(object,key){return object!=null&&key in Object(object);}/** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined;}array=arrays[0];var index=-1,seen=caches[0];outer:while(++index-1){if(seen!==array){splice.call(seen,fromIndex,1);}splice.call(array,fromIndex,1);}}return array;}/** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */function basePullAt(array,indexes){var length=array?indexes.length:0,lastIndex=length-1;while(length--){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index)){splice.call(array,index,1);}else{baseUnset(array,index);}}}return array;}/** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1));}/** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */function baseRange(start,end,step,fromRight){var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);while(length--){result[fromRight?length:++index]=start;start+=step;}return result;}/** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */function baseRepeat(string,n){var result='';if(!string||n<1||n>MAX_SAFE_INTEGER){return result;}// Leverage the exponentiation by squaring algorithm for a faster repeat. +// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. +do{if(n%2){result+=string;}n=nativeFloor(n/2);if(n){string+=string;}}while(n);return result;}/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */function baseRest(func,start){return setToString(overRest(func,start,identity),func+'');}/** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */function baseSample(collection){return arraySample(values(collection));}/** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length));}/** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */function baseSet(object,path,value,customizer){if(!isObject(object)){return object;}path=castPath(path,object);var index=-1,length=path.length,lastIndex=length-1,nested=object;while(nested!=null&&++indexlength?0:length+start;}end=end>length?length:end;if(end<0){end+=length;}length=start>end?0:end-start>>>0;start>>>=0;var result=Array(length);while(++index>>1,computed=array[mid];if(computed!==null&&!isSymbol(computed)&&(retHighest?computed<=value:computed=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set){return setToArray(set);}isCommon=false;includes=cacheHas;seen=new SetCache();}else{seen=iteratee?[]:result;}outer:while(++index=length?array:baseSlice(array,start,end);}/** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */var clearTimeout=ctxClearTimeout||function(id){return root.clearTimeout(id);};/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */function cloneBuffer(buffer,isDeep){if(isDeep){return buffer.slice();}var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);buffer.copy(result);return result;}/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);new Uint8Array(result).set(new Uint8Array(arrayBuffer));return result;}/** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength);}/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));result.lastIndex=regexp.lastIndex;return result;}/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{};}/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length);}/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=value===null,valIsReflexive=value===value,valIsSymbol=isSymbol(value);var othIsDefined=other!==undefined,othIsNull=other===null,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive){return 1;}if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&value=ordersLength){return result;}var order=orders[index];return result*(order=='desc'?-1:1);}}// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications +// that causes it, under certain circumstances, to provide the same value for +// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 +// for more details. +// +// This also ensures a stable sort in V8 and other engines. +// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. +return object.index-other.index;}/** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */function composeArgs(args,partials,holders,isCurried){var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;while(++leftIndex1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;customizer=assigner.length>3&&typeof customizer=='function'?(length--,customizer):undefined;if(guard&&isIterateeCall(sources[0],sources[1],guard)){customizer=length<3?undefined:customizer;length=1;}object=Object(object);while(++index-1?iterable[iteratee?collection[index]:index]:undefined;};}/** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;if(fromRight){funcs.reverse();}while(index--){var func=funcs[index];if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}if(prereq&&!wrapper&&getFuncName(func)=='wrapper'){var wrapper=new LodashWrapper([],true);}}index=wrapper?index:length;while(++index1){args.reverse();}if(isAry&&aryarrLength)){return false;}// Check that cyclic values are equal. +var arrStacked=stack.get(array);var othStacked=stack.get(other);if(arrStacked&&othStacked){return arrStacked==other&&othStacked==array;}var index=-1,result=true,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache():undefined;stack.set(array,other);stack.set(other,array);// Ignore non-index properties. +while(++index1?'& ':'')+details[lastIndex];details=details.join(length>2?', ':' ');return source.replace(reWrapComment,'{\n/* [wrapped with '+details+'] */\n');}/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol]);}/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */function isIndex(value,length){var type=typeof value;length=length==null?MAX_SAFE_INTEGER:length;return!!length&&(type=='number'||type!='symbol'&&reIsUint.test(value))&&value>-1&&value%1==0&&value0){if(++count>=HOT_COUNT){return arguments[0];}}else{count=0;}return func.apply(undefined,arguments);};}/** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;size=size===undefined?length:size;while(++index [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */function chunk(array,size,guard){if(guard?isIterateeCall(array,size,guard):size===undefined){size=1;}else{size=nativeMax(toInteger(size),0);}var length=array==null?0:array.length;if(!length||size<1){return[];}var index=0,resIndex=0,result=Array(nativeCeil(length/size));while(index [1, 2, 3] + */function compact(array){var index=-1,length=array==null?0:array.length,resIndex=0,result=[];while(++index [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */function concat(){var length=arguments.length;if(!length){return[];}var args=Array(length-1),array=arguments[0],index=length;while(index--){args[index-1]=arguments[index];}return arrayPush(isArray(array)?copyArray(array):[array],baseFlatten(args,1));}/** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */var difference=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true)):[];});/** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */var differenceBy=baseRest(function(array,values){var iteratee=last(values);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),getIteratee(iteratee,2)):[];});/** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */var differenceWith=baseRest(function(array,values){var comparator=last(values);if(isArrayLikeObject(comparator)){comparator=undefined;}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),undefined,comparator):[];});/** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */function drop(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);return baseSlice(array,n<0?0:n,length);}/** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */function dropRight(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);n=length-n;return baseSlice(array,0,n<0?0:n);}/** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true,true):[];}/** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true):[];}/** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */function fill(array,value,start,end){var length=array==null?0:array.length;if(!length){return[];}if(start&&typeof start!='number'&&isIterateeCall(array,value,start)){start=0;end=length;}return baseFill(array,value,start,end);}/** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */function findIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseFindIndex(array,getIteratee(predicate,3),index);}/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */function findLastIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=length-1;if(fromIndex!==undefined){index=toInteger(fromIndex);index=fromIndex<0?nativeMax(length+index,0):nativeMin(index,length-1);}return baseFindIndex(array,getIteratee(predicate,3),index,true);}/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */function flatten(array){var length=array==null?0:array.length;return length?baseFlatten(array,1):[];}/** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */function flattenDeep(array){var length=array==null?0:array.length;return length?baseFlatten(array,INFINITY):[];}/** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */function flattenDepth(array,depth){var length=array==null?0:array.length;if(!length){return[];}depth=depth===undefined?1:toInteger(depth);return baseFlatten(array,depth);}/** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */function fromPairs(pairs){var index=-1,length=pairs==null?0:pairs.length,result={};while(++index 1 + * + * _.head([]); + * // => undefined + */function head(array){return array&&array.length?array[0]:undefined;}/** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */function indexOf(array,value,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseIndexOf(array,value,index);}/** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */function initial(array){var length=array==null?0:array.length;return length?baseSlice(array,0,-1):[];}/** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */var intersection=baseRest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[];});/** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */var intersectionBy=baseRest(function(arrays){var iteratee=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);if(iteratee===last(mapped)){iteratee=undefined;}else{mapped.pop();}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,getIteratee(iteratee,2)):[];});/** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */var intersectionWith=baseRest(function(arrays){var comparator=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);comparator=typeof comparator=='function'?comparator:undefined;if(comparator){mapped.pop();}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,undefined,comparator):[];});/** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */function join(array,separator){return array==null?'':nativeJoin.call(array,separator);}/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */function last(array){var length=array==null?0:array.length;return length?array[length-1]:undefined;}/** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */function lastIndexOf(array,value,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=length;if(fromIndex!==undefined){index=toInteger(fromIndex);index=index<0?nativeMax(length+index,0):nativeMin(index,length-1);}return value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,true);}/** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined;}/** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */var pull=baseRest(pullAll);/** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array;}/** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array;}/** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array;}/** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */var pullAt=flatRest(function(array,indexes){var length=array==null?0:array.length,result=baseAt(array,indexes);basePullAt(array,arrayMap(indexes,function(index){return isIndex(index,length)?+index:index;}).sort(compareAscending));return result;});/** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */function remove(array,predicate){var result=[];if(!(array&&array.length)){return result;}var index=-1,indexes=[],length=array.length;predicate=getIteratee(predicate,3);while(++index [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */function reverse(array){return array==null?array:nativeReverse.call(array);}/** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */function slice(array,start,end){var length=array==null?0:array.length;if(!length){return[];}if(end&&typeof end!='number'&&isIterateeCall(array,start,end)){start=0;end=length;}else{start=start==null?0:toInteger(start);end=end===undefined?length:toInteger(end);}return baseSlice(array,start,end);}/** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */function sortedIndex(array,value){return baseSortedIndex(array,value);}/** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */function sortedIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2));}/** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */function sortedIndexOf(array,value){var length=array==null?0:array.length;if(length){var index=baseSortedIndex(array,value);if(index 4 + */function sortedLastIndex(array,value){return baseSortedIndex(array,value,true);}/** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),true);}/** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */function sortedLastIndexOf(array,value){var length=array==null?0:array.length;if(length){var index=baseSortedIndex(array,value,true)-1;if(eq(array[index],value)){return index;}}return-1;}/** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[];}/** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[];}/** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */function tail(array){var length=array==null?0:array.length;return length?baseSlice(array,1,length):[];}/** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */function take(array,n,guard){if(!(array&&array.length)){return[];}n=guard||n===undefined?1:toInteger(n);return baseSlice(array,0,n<0?0:n);}/** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */function takeRight(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);n=length-n;return baseSlice(array,n<0?0:n,length);}/** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),false,true):[];}/** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[];}/** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */var union=baseRest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true));});/** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */var unionBy=baseRest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),getIteratee(iteratee,2));});/** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */var unionWith=baseRest(function(arrays){var comparator=last(arrays);comparator=typeof comparator=='function'?comparator:undefined;return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),undefined,comparator);});/** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */function uniq(array){return array&&array.length?baseUniq(array):[];}/** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[];}/** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */function uniqWith(array,comparator){comparator=typeof comparator=='function'?comparator:undefined;return array&&array.length?baseUniq(array,undefined,comparator):[];}/** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */function unzip(array){if(!(array&&array.length)){return[];}var length=0;array=arrayFilter(array,function(group){if(isArrayLikeObject(group)){length=nativeMax(group.length,length);return true;}});return baseTimes(length,function(index){return arrayMap(array,baseProperty(index));});}/** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */function unzipWith(array,iteratee){if(!(array&&array.length)){return[];}var result=unzip(array);if(iteratee==null){return result;}return arrayMap(result,function(group){return apply(iteratee,undefined,group);});}/** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */var without=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,values):[];});/** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */var xor=baseRest(function(arrays){return baseXor(arrayFilter(arrays,isArrayLikeObject));});/** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */var xorBy=baseRest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return baseXor(arrayFilter(arrays,isArrayLikeObject),getIteratee(iteratee,2));});/** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */var xorWith=baseRest(function(arrays){var comparator=last(arrays);comparator=typeof comparator=='function'?comparator:undefined;return baseXor(arrayFilter(arrays,isArrayLikeObject),undefined,comparator);});/** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */var zip=baseRest(unzip);/** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue);}/** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet);}/** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */var zipWith=baseRest(function(arrays){var length=arrays.length,iteratee=length>1?arrays[length-1]:undefined;iteratee=typeof iteratee=='function'?(arrays.pop(),iteratee):undefined;return unzipWith(arrays,iteratee);});/*------------------------------------------------------------------------*/ /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */function chain(value){var result=lodash(value);result.__chain__=true;return result;}/** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */function tap(value,interceptor){interceptor(value);return value;}/** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */function thru(value,interceptor){return interceptor(value);}/** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */var wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths);};if(length>1||this.__actions__.length||!(value instanceof LazyWrapper)||!isIndex(start)){return this.thru(interceptor);}value=value.slice(start,+start+(length?1:0));value.__actions__.push({'func':thru,'args':[interceptor],'thisArg':undefined});return new LodashWrapper(value,this.__chain__).thru(function(array){if(length&&!array.length){array.push(undefined);}return array;});});/** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */function wrapperChain(){return chain(this);}/** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__);}/** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */function wrapperNext(){if(this.__values__===undefined){this.__values__=toArray(this.value());}var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{'done':done,'value':value};}/** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */function wrapperToIterator(){return this;}/** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */function wrapperPlant(value){var result,parent=this;while(parent instanceof baseLodash){var clone=wrapperClone(parent);clone.__index__=0;clone.__values__=undefined;if(result){previous.__wrapped__=clone;}else{result=clone;}var previous=clone;parent=parent.__wrapped__;}previous.__wrapped__=value;return result;}/** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;if(this.__actions__.length){wrapped=new LazyWrapper(this);}wrapped=wrapped.reverse();wrapped.__actions__.push({'func':thru,'args':[reverse],'thisArg':undefined});return new LodashWrapper(wrapped,this.__chain__);}return this.thru(reverse);}/** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__);}/*------------------------------------------------------------------------*/ /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */var countBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){++result[key];}else{baseAssignValue(result,key,1);}});/** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined;}return func(collection,getIteratee(predicate,3));}/** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + * + * // Combining several predicates using `_.overEvery` or `_.overSome`. + * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); + * // => objects for ['fred', 'barney'] + */function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3));}/** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */var find=createFind(findIndex);/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */var findLast=createFind(findLastIndex);/** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1);}/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY);}/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */function flatMapDepth(collection,iteratee,depth){depth=depth===undefined?1:toInteger(depth);return baseFlatten(map(collection,iteratee),depth);}/** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3));}/** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3));}/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value);}else{baseAssignValue(result,key,[value]);}});/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection);fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;if(fromIndex<0){fromIndex=nativeMax(length+fromIndex,0);}return isString(collection)?fromIndex<=length&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1;}/** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */var invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc=typeof path=='function',result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value){result[++index]=isFunc?apply(path,value,args):baseInvoke(value,path,args);});return result;});/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */var keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value);});/** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3));}/** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */function orderBy(collection,iteratees,orders,guard){if(collection==null){return[];}if(!isArray(iteratees)){iteratees=iteratees==null?[]:[iteratees];}orders=guard?undefined:orders;if(!isArray(orders)){orders=orders==null?[]:[orders];}return baseOrderBy(collection,iteratees,orders);}/** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */var partition=createAggregator(function(result,value,key){result[key?0:1].push(value);},function(){return[[],[]];});/** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach);}/** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight);}/** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)));}/** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection);}/** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */function sampleSize(collection,n,guard){if(guard?isIterateeCall(collection,n,guard):n===undefined){n=1;}else{n=toInteger(n);}var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n);}/** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection);}/** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */function size(collection){if(collection==null){return 0;}if(isArrayLike(collection)){return isString(collection)?stringSize(collection):collection.length;}var tag=getTag(collection);if(tag==mapTag||tag==setTag){return collection.size;}return baseKeys(collection).length;}/** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined;}return func(collection,getIteratee(predicate,3));}/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */var sortBy=baseRest(function(collection,iteratees){if(collection==null){return[];}var length=iteratees.length;if(length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])){iteratees=[];}else if(length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])){iteratees=[iteratees[0]];}return baseOrderBy(collection,baseFlatten(iteratees,1),[]);});/*------------------------------------------------------------------------*/ /** + * 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=ctxNow||function(){return root.Date.now();};/*------------------------------------------------------------------------*/ /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */function after(n,func){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}n=toInteger(n);return function(){if(--n<1){return func.apply(this,arguments);}};}/** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */function ary(func,n,guard){n=guard?undefined:n;n=func&&n==null?func.length:n;return createWrap(func,WRAP_ARY_FLAG,undefined,undefined,undefined,undefined,n);}/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */function before(n,func){var result;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}n=toInteger(n);return function(){if(--n>0){result=func.apply(this,arguments);}if(n<=1){func=undefined;}return result;};}/** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */var bind=baseRest(function(func,thisArg,partials){var bitmask=WRAP_BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=WRAP_PARTIAL_FLAG;}return createWrap(func,bitmask,thisArg,partials,holders);});/** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */var bindKey=baseRest(function(object,key,partials){var bitmask=WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=WRAP_PARTIAL_FLAG;}return createWrap(key,bitmask,object,partials,holders);});/** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,WRAP_CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curry.placeholder;return result;}/** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,WRAP_CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curryRight.placeholder;return result;}/** + * 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(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;}/** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */var defer=baseRest(function(func,args){return baseDelay(func,1,args);});/** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */var delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args);});/** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */function flip(func){return createWrap(func,WRAP_FLIP_FLAG);}/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */function memoize(func,resolver){if(typeof func!='function'||resolver!=null&&typeof resolver!='function'){throw new TypeError(FUNC_ERROR_TEXT);}var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key);}var result=func.apply(this,args);memoized.cache=cache.set(key,result)||cache;return result;};memoized.cache=new(memoize.Cache||MapCache)();return memoized;}// Expose `MapCache`. +memoize.Cache=MapCache;/** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */function negate(predicate){if(typeof predicate!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2]);}return!predicate.apply(this,args);};}/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */function once(func){return before(2,func);}/** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */var overArgs=castRest(function(func,transforms){transforms=transforms.length==1&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){var index=-1,length=nativeMin(args.length,funcsLength);while(++index 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */var partial=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partial));return createWrap(func,WRAP_PARTIAL_FLAG,undefined,partials,holders);});/** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */var partialRight=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partialRight));return createWrap(func,WRAP_PARTIAL_RIGHT_FLAG,undefined,partials,holders);});/** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */var rearg=flatRest(function(func,indexes){return createWrap(func,WRAP_REARG_FLAG,undefined,undefined,undefined,indexes);});/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */function rest(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}start=start===undefined?start:toInteger(start);return baseRest(func,start);}/** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */function spread(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}start=start==null?0:nativeMax(toInteger(start),0);return baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);if(array){arrayPush(otherArgs,array);}return apply(func,this,otherArgs);});}/** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled 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 + * throttled function. Subsequent calls to the throttled 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 throttled 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 `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */function throttle(func,wait,options){var leading=true,trailing=true;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}if(isObject(options)){leading='leading'in options?!!options.leading:leading;trailing='trailing'in options?!!options.trailing:trailing;}return debounce(func,wait,{'leading':leading,'maxWait':wait,'trailing':trailing});}/** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */function unary(func){return ary(func,1);}/** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

        ' + func(text) + '

        '; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

        fred, barney, & pebbles

        ' + */function wrap(value,wrapper){return partial(castFunction(wrapper),value);}/*------------------------------------------------------------------------*/ /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */function castArray(){if(!arguments.length){return[];}var value=arguments[0];return isArray(value)?value:[value];}/** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */function clone(value){return baseClone(value,CLONE_SYMBOLS_FLAG);}/** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */function cloneWith(value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseClone(value,CLONE_SYMBOLS_FLAG,customizer);}/** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */function cloneDeep(value){return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG);}/** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */function cloneDeepWith(value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG,customizer);}/** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */function conformsTo(object,source){return source==null||baseConformsTo(object,source,keys(source));}/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */function eq(value,other){return value===other||value!==value&&other!==other;}/** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */var gt=createRelationalOperation(baseGt);/** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */var gte=createRelationalOperation(function(value,other){return value>=other;});/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */var isArguments=baseIsArguments(function(){return arguments;}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,'callee')&&!propertyIsEnumerable.call(value,'callee');};/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */var isArray=Array.isArray;/** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */var isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer;/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value);}/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value);}/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */function isBoolean(value){return value===true||value===false||isObjectLike(value)&&baseGetTag(value)==boolTag;}/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */var isBuffer=nativeIsBuffer||stubFalse;/** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */var isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate;/** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */function isElement(value){return isObjectLike(value)&&value.nodeType===1&&!isPlainObject(value);}/** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */function isEmpty(value){if(value==null){return true;}if(isArrayLike(value)&&(isArray(value)||typeof value=='string'||typeof value.splice=='function'||isBuffer(value)||isTypedArray(value)||isArguments(value))){return!value.length;}var tag=getTag(value);if(tag==mapTag||tag==setTag){return!value.size;}if(isPrototype(value)){return!baseKeys(value).length;}for(var key in value){if(hasOwnProperty.call(value,key)){return false;}}return true;}/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */function isEqual(value,other){return baseIsEqual(value,other);}/** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */function isEqualWith(value,other,customizer){customizer=typeof customizer=='function'?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,undefined,customizer):!!result;}/** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */function isError(value){if(!isObjectLike(value)){return false;}var tag=baseGetTag(value);return tag==errorTag||tag==domExcTag||typeof value.message=='string'&&typeof value.name=='string'&&!isPlainObject(value);}/** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */function isFinite(value){return typeof value=='number'&&nativeIsFinite(value);}/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */function isFunction(value){if(!isObject(value)){return false;}// The use of `Object#toString` avoids issues with the `typeof` operator +// in Safari 9 which returns 'object' for typed arrays and other constructors. +var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag;}/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */function isInteger(value){return typeof value=='number'&&value==toInteger(value);}/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */function isLength(value){return typeof value=='number'&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER;}/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */function isObject(value){var type=typeof value;return value!=null&&(type=='object'||type=='function');}/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */function isObjectLike(value){return value!=null&&typeof value=='object';}/** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */var isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap;/** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source));}/** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */function isMatchWith(object,source,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseIsMatch(object,source,getMatchData(source),customizer);}/** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */function isNaN(value){// An `NaN` primitive is the only value that is not equal to itself. +// Perform the `toStringTag` check first to avoid errors with some +// ActiveX objects in IE. +return isNumber(value)&&value!=+value;}/** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */function isNative(value){if(isMaskable(value)){throw new Error(CORE_ERROR_TEXT);}return baseIsNative(value);}/** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */function isNull(value){return value===null;}/** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */function isNil(value){return value==null;}/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */function isNumber(value){return typeof value=='number'||isObjectLike(value)&&baseGetTag(value)==numberTag;}/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!=objectTag){return false;}var proto=getPrototype(value);if(proto===null){return true;}var Ctor=hasOwnProperty.call(proto,'constructor')&&proto.constructor;return typeof Ctor=='function'&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString;}/** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */var isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp;/** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&value<=MAX_SAFE_INTEGER;}/** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */var isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet;/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */function isString(value){return typeof value=='string'||!isArray(value)&&isObjectLike(value)&&baseGetTag(value)==stringTag;}/** + * 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(value){return typeof value=='symbol'||isObjectLike(value)&&baseGetTag(value)==symbolTag;}/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;/** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */function isUndefined(value){return value===undefined;}/** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag;}/** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */function isWeakSet(value){return isObjectLike(value)&&baseGetTag(value)==weakSetTag;}/** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */var lt=createRelationalOperation(baseLt);/** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */var lte=createRelationalOperation(function(value,other){return value<=other;});/** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */function toArray(value){if(!value){return[];}if(isArrayLike(value)){return isString(value)?stringToArray(value):copyArray(value);}if(symIterator&&value[symIterator]){return iteratorToArray(value[symIterator]());}var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value);}/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */function toFinite(value){if(!value){return value===0?value:0;}value=toNumber(value);if(value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER;}return value===value?value:0;}/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0;}/** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0;}/** + * 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(value){if(typeof value=='number'){return value;}if(isSymbol(value)){return NAN;}if(isObject(value)){var other=typeof value.valueOf=='function'?value.valueOf():value;value=isObject(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;}/** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */function toPlainObject(value){return copyObject(value,keysIn(value));}/** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */function toSafeInteger(value){return value?baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER):value===0?value:0;}/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */function toString(value){return value==null?'':baseToString(value);}/*------------------------------------------------------------------------*/ /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */var assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source)){copyObject(source,keys(source),object);return;}for(var key in source){if(hasOwnProperty.call(source,key)){assignValue(object,key,source[key]);}}});/** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */var assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object);});/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */var assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer);});/** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */var assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer);});/** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */var at=flatRest(baseAt);/** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */function create(prototype,properties){var result=baseCreate(prototype);return properties==null?result:baseAssign(result,properties);}/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */var defaults=baseRest(function(object,sources){object=Object(object);var index=-1;var length=sources.length;var guard=length>2?sources[2]:undefined;if(guard&&isIterateeCall(sources[0],sources[1],guard)){length=1;}while(++index { 'a': { 'b': 2, 'c': 3 } } + */var defaultsDeep=baseRest(function(args){args.push(undefined,customDefaultsMerge);return apply(mergeWith,undefined,args);});/** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn);}/** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight);}/** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */function forIn(object,iteratee){return object==null?object:baseFor(object,getIteratee(iteratee,3),keysIn);}/** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */function forInRight(object,iteratee){return object==null?object:baseForRight(object,getIteratee(iteratee,3),keysIn);}/** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3));}/** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3));}/** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */function functions(object){return object==null?[]:baseFunctions(object,keys(object));}/** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */function functionsIn(object){return object==null?[]:baseFunctions(object,keysIn(object));}/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */function get(object,path,defaultValue){var result=object==null?undefined:baseGet(object,path);return result===undefined?defaultValue:result;}/** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */function has(object,path){return object!=null&&hasPath(object,path,baseHas);}/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */function hasIn(object,path){return object!=null&&hasPath(object,path,baseHasIn);}/** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */var invert=createInverter(function(result,value,key){if(value!=null&&typeof value.toString!='function'){value=nativeObjectToString.call(value);}result[value]=key;},constant(identity));/** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */var invertBy=createInverter(function(result,value,key){if(value!=null&&typeof value.toString!='function'){value=nativeObjectToString.call(value);}if(hasOwnProperty.call(result,value)){result[value].push(key);}else{result[value]=[key];}},getIteratee);/** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */var invoke=baseRest(baseInvoke);/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object);}/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,true):baseKeysIn(object);}/** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */function mapKeys(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value);});return result;}/** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */function mapValues(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object));});return result;}/** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */var merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex);});/** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */var mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer);});/** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */var omit=flatRest(function(object,paths){var result={};if(object==null){return result;}var isDeep=false;paths=arrayMap(paths,function(path){path=castPath(path,object);isDeep||(isDeep=path.length>1);return path;});copyObject(object,getAllKeysIn(object),result);if(isDeep){result=baseClone(result,CLONE_DEEP_FLAG|CLONE_FLAT_FLAG|CLONE_SYMBOLS_FLAG,customOmitClone);}var length=paths.length;while(length--){baseUnset(result,paths[length]);}return result;});/** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)));}/** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */var pick=flatRest(function(object,paths){return object==null?{}:basePick(object,paths);});/** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */function pickBy(object,predicate){if(object==null){return{};}var props=arrayMap(getAllKeysIn(object),function(prop){return[prop];});predicate=getIteratee(predicate);return basePickBy(object,props,function(value,path){return predicate(value,path[0]);});}/** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */function result(object,path,defaultValue){path=castPath(path,object);var index=-1,length=path.length;// Ensure the loop is entered when path is empty. +if(!length){length=1;object=undefined;}while(++index 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */function set(object,path,value){return object==null?object:baseSet(object,path,value);}/** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */function setWith(object,path,value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return object==null?object:baseSet(object,path,value,customizer);}/** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */var toPairs=createToPairs(keys);/** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */var toPairsIn=createToPairs(keysIn);/** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */function transform(object,iteratee,accumulator){var isArr=isArray(object),isArrLike=isArr||isBuffer(object)||isTypedArray(object);iteratee=getIteratee(iteratee,4);if(accumulator==null){var Ctor=object&&object.constructor;if(isArrLike){accumulator=isArr?new Ctor():[];}else if(isObject(object)){accumulator=isFunction(Ctor)?baseCreate(getPrototype(object)):{};}else{accumulator={};}}(isArrLike?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object);});return accumulator;}/** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */function unset(object,path){return object==null?true:baseUnset(object,path);}/** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */function update(object,path,updater){return object==null?object:baseUpdate(object,path,castFunction(updater));}/** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */function updateWith(object,path,updater,customizer){customizer=typeof customizer=='function'?customizer:undefined;return object==null?object:baseUpdate(object,path,castFunction(updater),customizer);}/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */function values(object){return object==null?[]:baseValues(object,keys(object));}/** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */function valuesIn(object){return object==null?[]:baseValues(object,keysIn(object));}/*------------------------------------------------------------------------*/ /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */function clamp(number,lower,upper){if(upper===undefined){upper=lower;lower=undefined;}if(upper!==undefined){upper=toNumber(upper);upper=upper===upper?upper:0;}if(lower!==undefined){lower=toNumber(lower);lower=lower===lower?lower:0;}return baseClamp(toNumber(number),lower,upper);}/** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */function inRange(number,start,end){start=toFinite(start);if(end===undefined){end=start;start=0;}else{end=toFinite(end);}number=toNumber(number);return baseInRange(number,start,end);}/** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */function random(lower,upper,floating){if(floating&&typeof floating!='boolean'&&isIterateeCall(lower,upper,floating)){upper=floating=undefined;}if(floating===undefined){if(typeof upper=='boolean'){floating=upper;upper=undefined;}else if(typeof lower=='boolean'){floating=lower;lower=undefined;}}if(lower===undefined&&upper===undefined){lower=0;upper=1;}else{lower=toFinite(lower);if(upper===undefined){upper=lower;lower=0;}else{upper=toFinite(upper);}}if(lower>upper){var temp=lower;lower=upper;upper=temp;}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat('1e-'+((rand+'').length-1))),upper);}return baseRandom(lower,upper);}/*------------------------------------------------------------------------*/ /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */var camelCase=createCompounder(function(result,word,index){word=word.toLowerCase();return result+(index?capitalize(word):word);});/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */function capitalize(string){return upperFirst(toString(string).toLowerCase());}/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */function deburr(string){string=toString(string);return string&&string.replace(reLatin,deburrLetter).replace(reComboMark,'');}/** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */function endsWith(string,target,position){string=toString(string);target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;position-=target.length;return position>=0&&string.slice(position,end)==target;}/** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */function escape(string){string=toString(string);return string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string;}/** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */function escapeRegExp(string){string=toString(string);return string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,'\\$&'):string;}/** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */var kebabCase=createCompounder(function(result,word,index){return result+(index?'-':'')+word.toLowerCase();});/** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */var lowerCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toLowerCase();});/** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */var lowerFirst=createCaseFirst('toLowerCase');/** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */function pad(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length){return string;}var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars);}/** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */function padEnd(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */function padStart(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */function parseInt(string,radix,guard){if(guard||radix==null){radix=0;}else if(radix){radix=+radix;}return nativeParseInt(toString(string).replace(reTrimStart,''),radix||0);}/** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */function repeat(string,n,guard){if(guard?isIterateeCall(string,n,guard):n===undefined){n=1;}else{n=toInteger(n);}return baseRepeat(toString(string),n);}/** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2]);}/** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */var snakeCase=createCompounder(function(result,word,index){return result+(index?'_':'')+word.toLowerCase();});/** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */function split(string,separator,limit){if(limit&&typeof limit!='number'&&isIterateeCall(string,separator,limit)){separator=limit=undefined;}limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0;if(!limit){return[];}string=toString(string);if(string&&(typeof separator=='string'||separator!=null&&!isRegExp(separator))){separator=baseToString(separator);if(!separator&&hasUnicode(string)){return castSlice(stringToArray(string),0,limit);}}return string.split(separator,limit);}/** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */var startCase=createCompounder(function(result,word,index){return result+(index?' ':'')+upperFirst(word);});/** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */function startsWith(string,target,position){string=toString(string);position=position==null?0:baseClamp(toInteger(position),0,string.length);target=baseToString(target);return string.slice(position,position+target.length)==target;}/** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' + diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/checkout/billing/paymentmethods.isml b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/checkout/billing/paymentmethods.isml new file mode 100644 index 000000000..adbb359d9 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/checkout/billing/paymentmethods.isml @@ -0,0 +1,161 @@ + + TEMPLATENAME: paymentmethods.isml + + + +
        + + + ${Resource.msg('billing.paymentheader','checkout',null)} +
        ${Resource.msg('global.requiredfield','locale',null)}
        +
        + +
        + + + Ignore GIFT_CERTIFICATE method, GCs are handled separately before other payment methods. + + +
        + +
        + checked="checked" /> +
        + +
        + +
        +
        + +
        + +
        + + +
        ${Resource.msg('billing.missingprocessorerror','checkout',null)}
        +
        + + + Credit card block + -------------------------------------------------------------- + + +
        payment-method-expanded" data-method="CREDIT_CARD"> + + display select box with stored credit cards if customer is authenticated + + +
        + +
        + +
        +
        + +
        + +
        + + + + + () + + - ${Resource.msg('billing.creditcardlistexp','checkout',null)} + + . + + + + + + + + + + +
        + + + var currentCountry = require('~/cartridge/scripts/util/Countries').getCurrent(pdict); + + + + +
        + + + var help = { + label: Resource.msg('billing.linkcvn', 'checkout', null), + cid: 'checkout-security-code' + }; + + + + + + +
        +
        + + + + Bill me later + -------------------------------------------------------------- + + +
        payment-method-expanded" data-method="BML"> + +

        ${Resource.msg('billing.bmlhelp','checkout',null)}

        + +
        Date of Birth:
        + + + + + + +
        + +
        + +
        + +
        + +
        + + + + Custom processor + -------------------------------------------------------------- + + +
        payment-method-expanded" data-method="Custom"> + + ${Resource.msg('billing.custompaymentmethod','checkout',null)} +
        + +
        payment-method-expanded" data-method="AdyenComponent"> + +
        + +
        payment-method-expanded" data-method="AdyenPOS"> + +
        +
        + +
        + ${Resource.msg('billing.giftcertnomethod','checkout',null)}${Resource.msg('billing.zerobalance','checkout',null)} + + +
        +
        diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/checkout/summary/summary.isml b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/checkout/summary/summary.isml new file mode 100644 index 000000000..2b37ea459 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/checkout/summary/summary.isml @@ -0,0 +1,245 @@ + + + + + + This template visualizes the last step of the checkout, the order summary + page prior to the actual order placing. + It displays the complete content of the cart including product line items, + bonus products, redeemed coupons and gift certificate line items. + + + + + + + + + + +
        ${Resource.msg(pdict.PlaceOrderError.code,'checkout',null)}
        +
        + + + + + + + + + + + + render each shipment + + + + + + + + + + + + + + + + first last"> + + + + + + + + + + + + + + + + + + first last"> + + + + + + + + + + + + + + + + + + + + RENDER COUPON/ORDER DISCOUNTS + + + + + first last"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        ${Resource.msg('global.product','locale',null)}${Resource.msg('global.qty','locale',null)}${Resource.msg('global.totalprice','locale',null)}
        +
        ${Resource.msgf('multishippingshipments.shipment','checkout',null, shipmentCount)}
        +
        + + ${productLineItem.product.getImage('small',0).alt} + + ${productLineItem.productName} + + +
        + + + +
        +
        +
        + Display product line and product using module + + + + +
        + +
        +
        + +
        + +
        + + Otherwise, render price using call to adjusted price + +
        + + + +

        +

        +
        +
        +
        +
        + <isprint value=" /> + +
        + ${Resource.msg('global.to','locale',null)}: + + + () + +
        +
        + ${Resource.msg('global.from','locale',null)}: + +
        +
        1 + +
        +
        ${Resource.msg('summary.coupon','checkout',null)}
        +
        + ${Resource.msg('summary.couponnumber','checkout',null)} + +
        + +
        first last"> + + () +
        +
        +
          + + + + ${Resource.msg('summary.applied','checkout',null)} + + ${Resource.msg('summary.notapplied','checkout',null)} + +
        +
        + ${Resource.msg('summary.orderdiscount','checkout',null)} + +
        +
        + + + + + +
        diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/components/order/orderdetails.isml b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/components/order/orderdetails.isml new file mode 100644 index 000000000..d44e01c33 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/components/order/orderdetails.isml @@ -0,0 +1,226 @@ + + + + Displays order details, such as order number, creation date, payment information, + order totals and information for each contained shipment. + This template module can be used in order confirmation pages as well as in the + order history to render the details of a given order. Depending on the context + being used in, one might omit rendering certain information. + + Parameters: + + order : the order whose details to render + orderstatus : if set to true, the order status will be rendered + if set to false or not existing, the order status will not be rendered + + + + +
        +
        +

        + ${Resource.msg('order.orderdetails.ordernumber','order',null)} + +

        + Order Status + + + +
        + ${Resource.msg('order.orderdetails.orderplaced','order',null)} + +
        +
        +
        +
        ${Resource.msg('order.orderdetails.paymenttotal','order',null)}
        +
        + + + + + +
        +
        +
        +
        + + ${Resource.msg('order.orderdetails.paymentmethod','order',null)} + + ${Resource.msg('order.orderdetails.paymentmethods','order',null)} + +
        + + +
        + + + + ${Resource.msg('global.amount','locale',null)}: + + +
        + +
        + +
        + ${Resource.msg('global.amount','locale',null)}: + + ### Custom Adyen cartridge start ### +
        +
        + + ### Custom Adyen cartridge end ### +
        +
        +
        +
        +
        ${Resource.msg('order.orderdetails.billingaddress','order',null)}
        + +
        + + render a box for each shipment +
        + +

        ${Resource.msgf('multishippingshipments.shipment','checkout',null, shipmentloopstate.count)}

        + + + Shipment Items +
        +
        +
        + +
        ${Resource.msg('cart.store.instorepickup','checkout',null)}
        + +
        ${Resource.msg('order.orderdetails.shippingto','order',null)}
        +
        + +
        + +
        +
        ${Resource.msg('order.orderdetails.shippingstatus','order',null)}
        + +
        ${Resource.msg('order.orderdetails.notshipped','order',null)}
        + +
        ${Resource.msg('order.orderdetails.shipped','order',null)}
        + +
        ${Resource.msg('order.orderdetails.notknown','order',null)}
        +
        +
        +
        + +
        +
        ${Resource.msg('order.orderdetails.tracking','order',null)}
        +
        +
        +
        +
        +
        ${Resource.msg('order.orderdetails.shippingmethod','order',null)}
        + +
        + +
        +
        +
        + Shipment Gift Message + + +
        +
        ${Resource.msg('order.orderdetails.giftmessage','order',null)}
        +
        +
        +
        +
        +
        +
        + +
        +
        + +
        ${Resource.msg('global.item','locale',null)}
        +
        + Display product line and product using module + +
        +
        + +
        ${Resource.msg('global.qty','locale',null)}
        +
        + +
        +
        + +
        ${Resource.msg('global.price','locale',null)}
        +
        + Render quantity. If it is a bonus product render word 'Bonus' + +
        + + + +
        + + + + +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        + + +
        +
        + Shipment Gift Certificate + +
        +
        +
        ${Resource.msg('order.orderdetails.giftcertto','order',null)}
        +
        +
        +
        +
        +
        ${Resource.msg('order.orderdetails.giftcertfrom','order',null)}
        +
        +
        +
        +
        +
        +
        ${Resource.msg('global.giftcertificate','locale',null)}
        +
        +
        +
        +
        ${Resource.msg('order.orderdetails.shippingmethod','order',null)}
        +
        ${Resource.msg('order.orderdetails.giftcertshipping','order',null)}
        +
        +
        +
        + + if shipment is marked as gift + +
        +
        ${Resource.msg('order.orderdetails.giftmessage','order',null)}
        + +
        +
        +
        + +
        + +
        ${Resource.msg('order.orderdetails.giftmessage','order',null)}
        + +
        +
        +
        +
        +
        +
        +
        +
        +
        +
        diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/components/order/orderdetailsemail.isml b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/components/order/orderdetailsemail.isml new file mode 100644 index 000000000..facdc2017 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/cartridge/templates/default/components/order/orderdetailsemail.isml @@ -0,0 +1,258 @@ + + + Displays order details, such as order number, creation date, payment information, + order totals and information for each contained shipment. + This template module can be used in order confirmation pages as well as in the + order history to render the details of a given order. Depending on the context + being used in, one might omit rendering certain information. + + Parameters: + + order : the order whose details to render + orderstatus : if set to true, the order status will be rendered + if set to false or not existing, the order status will not be rendered + + + +

        + ${Resource.msg('order.orderdetails.orderplaced','order',null)} + +

        + +

        + ${Resource.msg('order.orderdetails.ordernumber','order',null)} + +

        + + + + + + + + + + + +
        ${Resource.msg('order.orderdetails.paymentinfo','order',null)}
        + ${Resource.msg('order.orderdetails.billingaddress','order',null)} + + + + + ${Resource.msg('order.orderdetails.paymentmethod','order',null)} + + ${Resource.msg('order.orderdetails.paymentmethods','order',null)} + + + Render All Payment Instruments + +
        + +
        +
        + +
        + ${Resource.msg('global.amount','locale',null)}: + + ### Custom Adyen cartridge start ### +
        + + ### Custom Adyen cartridge end ### +
        +
        +
        + ${Resource.msg('order.orderdetails.paymenttotal','order',null)} + + + + +
        +
        +
        + + +render a box for each shipment + + + +

        ${(Resource.msg('order.orderconfirmation-email.shipmentnumber','order',null)) + shipmentloopstate.count}

        + + + + Shipment items table + + + + + + + + + + + + + + + + + + + + + + + only show shipping address for first pli in shipment + + + + + + + Shipment Gift Message + + + + + + + + +
        ${Resource.msg('global.item','locale',null)}${Resource.msg('global.quantity','locale',null)}${Resource.msg('global.price','locale',null)}${Resource.msg('order.orderdetails.shippingto','order',null)}${Resource.msg('cart.store.instorepickup','checkout',null)}
        + Display product line and product using module + + + + + Render quantity. If it is a bonus product render word 'Bonus' + + + + + + + + +

        +

        +
        +
        +
        +
        +
        + +
        +
        + ${Resource.msg('order.orderdetails.shippingmethod','order',null)} + + + + + +
        +
        + ${Resource.msg('order.orderdetails.shippingstatus','order',null)} + + ${Resource.msg('order.orderdetails.notshipped','order',null)} + + ${Resource.msg('order.orderdetails.shipped','order',null)} + + ${Resource.msg('order.orderdetails.notknown','order',null)} + +
        + +
        + ${Resource.msg('order.orderdetails.tracking','order',null)} + +
        +
        +
        + ${Resource.msg('order.orderdetails.giftmessage','order',null)} +
        + + + +   + +
        + +
        + + + + Shipment Gift Certificate + + + + + + + + + + + + + + + + + if shipment is marked as gift + + + + + + + + + + + + + +
        ${Resource.msg('global.item','locale',null)}${Resource.msg('global.price','locale',null)}${Resource.msg('order.orderdetails.shippingto','order',null)}
        + ${Resource.msg('global.giftcertificate','locale',null)} +
        + ${Resource.msg('order.orderdetails.giftcertto','order',null)} +
        + +
        +
        + ${Resource.msg('order.orderdetails.giftcertfrom','order',null)} +
        + +
        +
        + + +
        + ${Resource.msg('order.orderdetails.giftcertshippingaddress','order',null)} +
        + + +
        +
        +
        + ${Resource.msg('order.orderdetails.shippingmethod','order',null)} + ${Resource.msg('order.orderdetails.giftcertshipping','order',null)} +
        +
        + ${Resource.msg('order.orderdetails.giftmessage','order',null)} +
        + + + +   + +
        + + + + +   + +
        + +
        +
        diff --git a/cartridges/adyen_controllers_changes/app_storefront_core_changes/package.json b/cartridges/adyen_controllers_changes/app_storefront_core_changes/package.json new file mode 100644 index 000000000..623254b69 --- /dev/null +++ b/cartridges/adyen_controllers_changes/app_storefront_core_changes/package.json @@ -0,0 +1,3 @@ +{ + "hooks": "./cartridge/scripts/hooks.json" +} \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/bm_adyen.properties b/cartridges/bm_adyen/cartridge/bm_adyen.properties new file mode 100644 index 000000000..bb79bd13d --- /dev/null +++ b/cartridges/bm_adyen/cartridge/bm_adyen.properties @@ -0,0 +1,4 @@ +## cartridge.properties for cartridge bm_adyen +#Wed Jun 05 17:06:42 CEST 2013 +demandware.cartridges.bm_adyen.multipleLanguageStorefront=true +demandware.cartridges.bm_adyen.id=bm_adyen diff --git a/cartridges/bm_adyen/cartridge/bm_extensions.xml b/cartridges/bm_adyen/cartridge/bm_extensions.xml new file mode 100644 index 000000000..1ee493760 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/bm_extensions.xml @@ -0,0 +1,113 @@ + + + + Adyen settings + Adyen settings + Adyen settings + + + + + adyen_logo.svg + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/controllers/AdyenSettings.js b/cartridges/bm_adyen/cartridge/controllers/AdyenSettings.js new file mode 100644 index 000000000..786d69543 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/controllers/AdyenSettings.js @@ -0,0 +1,72 @@ +"use strict"; + +var server = require('server'); +var Transaction = require('dw/system/Transaction'); +var csrfProtection = require('*/cartridge/scripts/middleware/csrf'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var constants = require('*/cartridge/adyenConstants/constants'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +server.get('Start', csrfProtection.generateToken, function (_req, res, next) { + res.render('adyenSettings/settings'); + return next(); +}); +server.post('Save', server.middleware.https, function (req, res, next) { + try { + var requestBody = JSON.parse(req.body); + requestBody.settings.forEach(function (setting) { + Transaction.wrap(function () { + AdyenConfigs.setCustomPreference(setting.key, setting.value); + }); + }); + res.json({ + success: true + }); + } catch (error) { + AdyenLogs.error_log("Error while saving settings in BM configuration: ".concat(error)); + res.json({ + success: false + }); + } + return next(); +}); +server.post('TestConnection', server.middleware.https, function (req, res, next) { + try { + var service = AdyenHelper.getService(constants.SERVICE.CHECKOUTPAYMENTMETHODS); + if (!service) { + throw new Error('Could not do /paymentMethods call'); + } + var requestBody = JSON.parse(req.body); + var xApiKey = requestBody.xApiKey, + merchantAccount = requestBody.merchantAccount; + service.addHeader('Content-type', 'application/json'); + service.addHeader('charset', 'UTF-8'); + service.addHeader('X-API-key', xApiKey); + var callResult = service.call(JSON.stringify({ + merchantAccount: merchantAccount + })); + if (!callResult.isOk()) { + var _JSON$parse = JSON.parse(callResult.getErrorMessage()), + message = _JSON$parse.message; + res.json({ + success: false, + message: message, + error: true + }); + return next(); + } + res.json({ + success: true, + error: false + }); + } catch (error) { + AdyenLogs.error_log("Error while testing API credentials: ".concat(error)); + res.json({ + error: true, + message: 'an unknown error has occurred', + success: false + }); + } + return next(); +}); +module.exports = server.exports(); \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/static/default/css/configurationSettings.css b/cartridges/bm_adyen/cartridge/static/default/css/configurationSettings.css new file mode 100644 index 000000000..156893734 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/css/configurationSettings.css @@ -0,0 +1,497 @@ +.input-fields{ + padding-left: 48px; + padding-right: 51px; +} + +.first-subtitle{ + padding-left: 48px; + padding-right: 51px; +} + +.radio-buttons{ + padding-left: 48px; +} + +.form-title{ + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 14px; + line-height: 16px; + color: #00112C; + padding-left: 48px; + padding-right: 51px; +} + +.links-header { + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 15px; + line-height: 21px; + color: #20304C; +} + +.card-body .card-title { + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 24px; + line-height: 32px; + color: #00112C; + height: 32px; + padding-left: 48px; + padding-right: 51px; +} + +.card-body .card-subtitle { + font-family: 'Fakt'; + font-style: normal; + font-weight: 400; + font-size: 16px; + line-height: 24px; + color: #69778C; + width: 699px; +} + +.form-group .form-text { + font-family: 'Fakt'; + font-style: normal; + font-weight: 400; + font-size: 14px; + line-height: 20px; + color: #20304C; + padding-left: 48px; + padding-right: 51px; +} + + +.form-check-input, .form-check-label{ + width: 26px; + height: 20px; + + font-family: 'Fakt'; + font-style: normal; + font-weight: 400; + font-size: 14px; + line-height: 20px; + + display: flex; + align-items: center; + color: #20304C; +} + +.list-group .navigation-item { + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 15px; + line-height: 21px; + display: flex; + align-items: center; + color: #394962; +} + +.row .sticky-top { + top: 10%; + z-index: 10; +} + +.btn-toolbar{ + position: absolute; + display: flex; + flex-direction: column; + align-items: flex-start; + padding: 12px 107px; + gap: 10px; + + width: 1434px; + height: 75px; + left: 2px; + top: 92px; + + background: #FFFFFF; + box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.06); +} + +.btn-toolbar .sec-group{ + padding-left: 70%; +} + +.btn-toolbar .sec-group .btn-light{ + width: 135px; + height: 28px; + + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 13px; + line-height: 17px; + + align-items: center; + + background: #FFFFFF; + border: 1px solid #F3F2F2; + color: #394962; + + border-radius: 6px; + margin-top: 10px; +} + +.img-fluid{ + margin-top: 10px; +} + +.first, .second, .third { + outline: none; + border: 0 !important; + box-shadow: none !important; +} + +.bi-eye, .bi-eye-slash{ + position: absolute !important; + margin-top: 6px !important; + margin-right: 70px !important; + left: 75px !important; +} + +#notificationsPassword{ + padding-left: 30px; +} + +#toggleApi{ + margin-top: 5px !important; + left: 75px; +} + +#apiKey{ + padding-left: 30px; +} + +#hmacKey{ + padding-left: 30px; +} + +.line-divider{ + padding-left: 48px; + padding-right: 51px; +} + +.switch-button{ + position: absolute; + left: 80%; + right: auto; + top: auto; + bottom: auto; + border-radius: 8.5px; +} + +html { + scroll-padding-top: 6rem; + overflow-x: hidden; +} + +.list-group-item { + border: 1.0px solid rgb(204, 204, 204); +} + +.list-group-item:hover{ + background: rgb(184, 225, 252); +} + +.form-buttons{ + padding-right:5%; + padding-top:9px; +} + +#settingsFormCancelButton{ + top:20px; + + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 15px; + line-height: 21px; + + display: flex; + align-items: center; + + color: #394962; + border-radius: 6px; +} + +#settingsFormSubmitButton{ + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 15px; + line-height: 21px; + + display: flex; + align-items: center; + border-radius: 6px; +} + +#bm_content_column{ + padding-bottom: 0; + padding-left: 0; +} + +#saveChangesAlert{ + width: 420px; + left: 0; + margin: auto; // Centers alert component + right: 0; + text-align: center; + top: 1em; + + background: #00112C; + box-shadow: 0px 8px 8px rgba(0, 17, 44, 0.02), 0px 2px 4px rgba(0, 17, 44, 0.04); + border-radius: 8px; + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 15px; + line-height: 21px; + color: #FFFFFF; + height: auto; + + align-items: center; + flex: none; + order: 0; + align-self: stretch; + flex-grow: 0; + padding: 0.15rem; +} + +#saveChangesAlert .img-fluid { + position: static; + padding-bottom: 12px; +} + +#notSavedChangesAlert .img-fluid { + position: static; + padding-bottom: 12px; +} + +#notSavedChangesAlert{ + left: 0; + margin: auto; // Centers alert component + position: absolute; // So that it will display relative to the entire page + right: 0; + text-align: center; + top: 1em; + + background: #00112C; + box-shadow: 0px 8px 8px rgba(0, 17, 44, 0.02), 0px 2px 4px rgba(0, 17, 44, 0.04); + border-radius: 8px; + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 15px; + line-height: 21px; + color: #FFFFFF; + +} + +.footer{ + position: absolute; + height: 52px; +} + +#settingsFormCancelButton{ + top:20px; + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 15px; + line-height: 21px; + + display: flex; + align-items: center; + color: #394962; + + border-radius: 6px; + background: #FFFFFF; + border: 1px solid #DCE0E5; +} + +#settingsFormSubmitButton{ + bottom:10px; + + font-family: 'Fakt'; + font-style: normal; + font-weight: 600; + font-size: 15px; + line-height: 21px; + display: flex; + align-items: center; + border-radius: 6px; +} + +#logos{ + margin:0 auto; + justify-content:flex-start; + display:flex; + width:100%; + height:100%; + left:3.2%; +} + +#adyen-logo{ + margin-right: 20px; +} + + +#apiKey{ + overflow: hidden; + text-overflow: ellipsis; +} + +#invalidFeedbackApi{ + position: absolute; + bottom: 60px; +} + +#testConnectionButton{ + position: relative; + bottom: -10px; +} + +.form-group .wrapper-class{ + width:320px; + height: 69px; + margin-top:10px; + padding-left: 48px; + padding-right: 51px; +} + +#fileDropBoxCharitybackground, #fileDropBoxGivingLogo{ + width: 320px; + height: 69px; + border: 1px dashed gray; + color: #69778C; + border-radius: 7px; + font-family: 'Fakt'; + text-align: center; + background:#F3F6F9; + padding: 20px 0; +} + +.paperclip{ + position: absolute; + right: auto; + margin-left: 22px; + margin-top: 24px; +} + +#backgroundList{ + position: absolute; + padding-left: 0; +} + +#logoList{ + position: absolute; + padding-left:0; + +} + +ul{ + list-style-type: none; +} + +.draggable-list { + border: 1px solid #ced4da; + color: #34444f; + padding: 0; + list-style-type: none; + margin-left: 48px; + margin-right: 48px; +} + +.log-list{ + margin-left: 17px; + margin-right: 48px; +} + +.log-list > li { + border: 1px solid #ced4da; + color: #34444f; + height: 95px; + border-bottom: none; + padding-bottom: 110px; +} + +.log-list > li .form-check-input{ + margin-left: 23px; +} + +.log-list .log-checkbox-fatal { + border-bottom: 1px solid #ced4da; + padding-bottom: 95px; +} + +.draggable-list li { + background-color: #fff; + display: flex; + flex: 1; +} + +.draggable-list li:not(:last-of-type) { + border-bottom: 1px solid #ced4da; +} + +.draggable-list li.over .draggable { + background-color: #eaeaea; +} + +.draggable-list .item-name { + margin: 0 20px 0 0; +} + +.draggable-list li.right .item-name { + color: #3ae374; +} + +.draggable-list li.wrong .item-name { + color: #ff3838; +} + +.draggable { + cursor: move; + display: flex; + align-items: center; + justify-content: space-between; + padding: 15px; + flex: 1; + position: relative; +} + +.draggable .switch-button { + position: initial; + left: 95.5%; +} + +.draggable .title { + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; +} + +.draggable .title p { + margin: 0 10px; +} + +.draggable .title .logo { + margin-left: 10px; +} + +.form-select { + font-family: 'Fakt'; + font-style: normal; + font-weight: 250; + font-size: 14px; + line-height: 24px; + color: #69778C; +} \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/ external-link-small.svg b/cartridges/bm_adyen/cartridge/static/default/icons/ external-link-small.svg new file mode 100644 index 000000000..f94bcc660 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/ external-link-small.svg @@ -0,0 +1,3 @@ + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/ notification.svg b/cartridges/bm_adyen/cartridge/static/default/icons/ notification.svg new file mode 100644 index 000000000..730c56c55 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/ notification.svg @@ -0,0 +1,4 @@ + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/account-setting-tag.svg b/cartridges/bm_adyen/cartridge/static/default/icons/account-setting-tag.svg new file mode 100644 index 000000000..9abdc1fbe --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/account-setting-tag.svg @@ -0,0 +1,4 @@ + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/adyen-giving.svg b/cartridges/bm_adyen/cartridge/static/default/icons/adyen-giving.svg new file mode 100644 index 000000000..b6bac5005 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/adyen-giving.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/adyen.svg b/cartridges/bm_adyen/cartridge/static/default/icons/adyen.svg new file mode 100644 index 000000000..468dd4564 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/adyen.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/amazonpay.svg b/cartridges/bm_adyen/cartridge/static/default/icons/amazonpay.svg new file mode 100644 index 000000000..a37fd19ce --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/amazonpay.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/applepay.svg b/cartridges/bm_adyen/cartridge/static/default/icons/applepay.svg new file mode 100644 index 000000000..bac18bf63 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/applepay.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/card-lock.svg b/cartridges/bm_adyen/cartridge/static/default/icons/card-lock.svg new file mode 100644 index 000000000..f935f44d3 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/card-lock.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/card.svg b/cartridges/bm_adyen/cartridge/static/default/icons/card.svg new file mode 100644 index 000000000..d0957d4bf --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/card.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/checkmark-circle-fill.svg b/cartridges/bm_adyen/cartridge/static/default/icons/checkmark-circle-fill.svg new file mode 100644 index 000000000..f5a98edbb --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/checkmark-circle-fill.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/creditcard-small.svg b/cartridges/bm_adyen/cartridge/static/default/icons/creditcard-small.svg new file mode 100644 index 000000000..d0957d4bf --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/creditcard-small.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/drag.svg b/cartridges/bm_adyen/cartridge/static/default/icons/drag.svg new file mode 100644 index 000000000..5efa86bbc --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/drag.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/express.svg b/cartridges/bm_adyen/cartridge/static/default/icons/express.svg new file mode 100644 index 000000000..5c85dff27 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/express.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/external-link-small.svg b/cartridges/bm_adyen/cartridge/static/default/icons/external-link-small.svg new file mode 100644 index 000000000..f94bcc660 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/external-link-small.svg @@ -0,0 +1,3 @@ + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/icon-error.svg b/cartridges/bm_adyen/cartridge/static/default/icons/icon-error.svg new file mode 100644 index 000000000..10896dfc3 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/icon-error.svg @@ -0,0 +1,4 @@ + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/icon-success.svg b/cartridges/bm_adyen/cartridge/static/default/icons/icon-success.svg new file mode 100644 index 000000000..fe1a1a6f1 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/icon-success.svg @@ -0,0 +1,4 @@ + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/notification.svg b/cartridges/bm_adyen/cartridge/static/default/icons/notification.svg new file mode 100644 index 000000000..730c56c55 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/notification.svg @@ -0,0 +1,4 @@ + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/paperclip.svg b/cartridges/bm_adyen/cartridge/static/default/icons/paperclip.svg new file mode 100644 index 000000000..5c4c4fb95 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/paperclip.svg @@ -0,0 +1,3 @@ + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/pos.svg b/cartridges/bm_adyen/cartridge/static/default/icons/pos.svg new file mode 100644 index 000000000..97eb1040b --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/pos.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/rules.svg b/cartridges/bm_adyen/cartridge/static/default/icons/rules.svg new file mode 100644 index 000000000..0c3c7d44d --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/rules.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/settings.svg b/cartridges/bm_adyen/cartridge/static/default/icons/settings.svg new file mode 100644 index 000000000..8bbdff74e --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/settings.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/terminal-3.svg b/cartridges/bm_adyen/cartridge/static/default/icons/terminal-3.svg new file mode 100644 index 000000000..97eb1040b --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/terminal-3.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/icons/tools.svg b/cartridges/bm_adyen/cartridge/static/default/icons/tools.svg new file mode 100644 index 000000000..999e4da9c --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/icons/tools.svg @@ -0,0 +1,3 @@ + + + diff --git a/cartridges/bm_adyen/cartridge/static/default/js/adyenSettings.js b/cartridges/bm_adyen/cartridge/static/default/js/adyenSettings.js new file mode 100644 index 000000000..e5a76e67c --- /dev/null +++ b/cartridges/bm_adyen/cartridge/static/default/js/adyenSettings.js @@ -0,0 +1,375 @@ +const expressPaymentMethods = [{ + id: 'applepay', + name: 'ApplePayExpress_Enabled', + text: 'Apple Pay', + icon: window.applePayIcon, + checked: window.isApplePayEnabled +}, { + id: 'amazonpay', + name: 'AmazonPayExpress_Enabled', + text: 'Amazon Pay', + icon: window.amazonPayIcon, + checked: window.isAmazonPayEnabled +}]; +document.addEventListener('DOMContentLoaded', () => { + const form = document.querySelector('#settingsForm'); + const troubleshootingForm = document.querySelector('#troubleshootingForm'); + const submitButton = document.querySelector('#settingsFormSubmitButton'); + const cancelButton = document.querySelector('#settingsFormCancelButton'); + const formButtons = Array.from(document.getElementsByClassName('formButton')); + const testConnectionButton = document.querySelector('#testConnectionButton'); + const togglePassword = document.querySelector('#togglePassword'); + const toggleHmacKey = document.querySelector('#toggleHmacKey'); + const toggleApi = document.querySelector('#toggleApi'); + const formBody = document.querySelector('#formBody'); + const password = document.querySelector('#notificationsPassword'); + const hmacKey = document.querySelector('#hmacKey'); + const merchAccount = document.getElementById('merchantAccount'); + const classicPageButton = document.querySelector('#classicButton'); + const debugLogCheckbox = document.getElementById('debugLogs'); + const infoLogCheckbox = document.getElementById('infoLogs'); + const errorLogCheckbox = document.getElementById('errorLogs'); + const fatalLogCheckbox = document.getElementById('fatalLogs'); + const troubleshootingCheckboxes = [debugLogCheckbox, infoLogCheckbox, errorLogCheckbox, fatalLogCheckbox]; + const downloadLogsButton = document.getElementById('downloadLogsButton'); + const apiKeyVal = document.getElementById('apiKey'); + const changedSettings = []; + const isValid = 'is-valid'; + const isInvalid = 'is-invalid'; + const adyenGivingBackground = document.querySelector('#fileDropBoxCharitybackground'); + const adyenGivingLogo = document.querySelector('#fileDropBoxGivingLogo'); + const params = 'resizable=yes,width=1000,height=500,left=100,top=100'; + const draggableList = document.getElementById('draggable-list'); + const listItems = []; + let dragStartIndex; + function settingChanged(key, value) { + const settingIndex = changedSettings.findIndex(setting => setting.key === key); + if (settingIndex >= 0) { + changedSettings[settingIndex] = { + key, + value + }; + } else { + changedSettings.push({ + key, + value + }); + } + } + function swapItems(fromIndex, toIndex) { + const itemOne = listItems[fromIndex].querySelector('.draggable'); + const itemTwo = listItems[toIndex].querySelector('.draggable'); + listItems[fromIndex].appendChild(itemTwo); + listItems[toIndex].appendChild(itemOne); + formButtons.forEach(button => { + button.classList.remove('disabled'); + button.classList.add('enabled'); + }); + const expressPaymentsOrder = []; + const liItemsP = draggableList.querySelectorAll('p.item'); + liItemsP.forEach(p => { + expressPaymentsOrder.push(p.dataset.id); + }); + settingChanged('ExpressPayments_order', expressPaymentsOrder.join(',')); + } + function dragStart() { + dragStartIndex = +this.closest('li').getAttribute('data-index'); + } + function dragDrop() { + const dragEndIndex = +this.getAttribute('data-index'); + swapItems(dragStartIndex, dragEndIndex); + this.classList.remove('over'); + } + function dragEnter() { + this.classList.add('over'); + } + function dragLeave() { + this.classList.remove('over'); + } + function dragOver(e) { + e.preventDefault(); + } + function addExpressEventListeners() { + const draggables = document.querySelectorAll('.draggable'); + const dragListItems = document.querySelectorAll('.draggable-list li'); + draggables.forEach(draggable => { + draggable.addEventListener('dragstart', dragStart); + }); + dragListItems.forEach(item => { + item.addEventListener('dragover', dragOver); + item.addEventListener('drop', dragDrop); + item.addEventListener('dragenter', dragEnter); + item.addEventListener('dragleave', dragLeave); + }); + } + function createExpressPaymentsComponent() { + const { + expressMethodsOrder + } = window; + if (expressMethodsOrder) { + const sortOrder = expressMethodsOrder.split(','); + expressPaymentMethods.sort((a, b) => sortOrder.indexOf(a.id) - sortOrder.indexOf(b.id)); + } + expressPaymentMethods.forEach((item, index) => { + const listItem = document.createElement('li'); + listItem.setAttribute('data-index', index.toString()); + listItem.innerHTML = ` +
        +
        + + +

        ${item.text}

        +
        +
        +
        + +
        +
        +
        + `; + listItems.push(listItem); + draggableList.appendChild(listItem); + }); + addExpressEventListeners(); + } + + // redirect to classic page + function getLink() { + window.open(window.classicConfigPageUrl); + } + function downloadFile(filePath) { + const link = document.createElement('a'); + link.href = filePath; + link.download = filePath.substr(filePath.lastIndexOf('/') + 1); + link.click(); + } + function enableformButtons() { + formButtons.forEach(button => { + button.classList.remove('disabled'); + button.classList.add('enabled'); + form.removeEventListener('input', enableformButtons); + }); + } + function disableFormButtons() { + formButtons.forEach(button => { + button.classList.remove('enabled'); + button.classList.add('disabled'); + form.removeEventListener('input', enableformButtons); + }); + } + function saveAndHideAlerts() { + document.getElementById('settingsFormSubmitButton').click(); + document.getElementById('saveChangesAlert').hide(); + document.getElementById('notSavedChangesAlert').hide(); + } + function showAlertsOnSave() { + document.getElementById('saveChangesAlert').show(); + document.getElementById('notSavedChangesAlert').show(); + } + + // if browser is safari it sets custom padding + function checkBrowserSupport() { + if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + formBody.style.setProperty('padding-top', '3rem'); + } + } + function showPassword() { + const type = password.getAttribute('type') === 'password' ? 'text' : 'password'; + password.setAttribute('type', type); + this.classList.toggle('bi-eye'); + } + function showApiKey() { + const type = apiKeyVal.getAttribute('type') === 'password' ? 'text' : 'password'; + apiKeyVal.setAttribute('type', type); + this.classList.toggle('bi-eye'); + } + function showHmacKey() { + const type = hmacKey.getAttribute('type') === 'password' ? 'text' : 'password'; + hmacKey.setAttribute('type', type); + this.classList.toggle('bi-eye'); + } + + // open Adyen Giving Background upload page + function uploadAdyenGivingBackground() { + const openedWindow = window.open(window.adyenGivingBackgroundUrl, 'backgroundPopUp', params); + const loop = setInterval(() => { + if (openedWindow.closed) { + window.location.reload(); + clearInterval(loop); + } + }, 1000); + } + + // open Adyen Giving Logo upload page + function uploadAdyenGivingLogo() { + const openedWindowLogo = window.open(window.adyenGivingLogoUrl, 'logoPopUp', params); + const loop = setInterval(() => { + if (openedWindowLogo.closed) { + window.location.reload(); + clearInterval(loop); + } + }, 1000); + } + function getImageName(imageUrl) { + const parts = imageUrl.split('/'); + const imageName = parts.pop(); + return imageName; + } + function createImageNameStyling(list, imageName) { + document.getElementById(list).innerHTML = ''; + const unorderedList = document.getElementById(list); + const nameOfImage = getImageName(imageName); + if (nameOfImage?.length > 0) { + const checkMarkImage = document.createElement('img'); + checkMarkImage.src = window.successImage; + const text = document.createTextNode(nameOfImage); + const listElement = document.createElement('li'); + listElement.appendChild(checkMarkImage); + listElement.appendChild(document.createTextNode(' ')); + listElement.appendChild(text); + unorderedList.appendChild(listElement); + } + } + function printBackgroundImageName() { + createImageNameStyling('backgroundList', window.backgroundValueField); + } + function printLogoImageName() { + createImageNameStyling('logoList', window.logoValueField); + } + testConnectionButton.addEventListener('click', saveAndHideAlerts); + classicPageButton.addEventListener('click', getLink); + form.addEventListener('input', enableformButtons); + submitButton.addEventListener('click', showAlertsOnSave); + window.addEventListener('load', checkBrowserSupport); + togglePassword.addEventListener('click', showPassword); + toggleHmacKey.addEventListener('click', showHmacKey); + toggleApi.addEventListener('click', showApiKey); + adyenGivingBackground.addEventListener('click', uploadAdyenGivingBackground); + adyenGivingLogo.addEventListener('click', uploadAdyenGivingLogo); + window.addEventListener('load', printBackgroundImageName); + window.addEventListener('load', printLogoImageName); + adyenGivingBackground.addEventListener('click', saveAndHideAlerts); + adyenGivingLogo.addEventListener('click', saveAndHideAlerts); + troubleshootingForm.addEventListener('input', () => { + downloadLogsButton.classList.add('disabled'); + troubleshootingCheckboxes.forEach(checkbox => { + if (checkbox.checked) { + downloadLogsButton.classList.remove('disabled'); + downloadLogsButton.classList.add('enabled'); + } + }); + }); + downloadLogsButton.addEventListener('click', () => { + (async () => { + const htmlContent = await (await fetch(window.logCenterUrl)).text(); + const doc = new DOMParser().parseFromString(htmlContent, 'text/html'); + const logLocations = Array.from(doc.body.getElementsByTagName('a')).map(log => log.href); + const logsToDownload = []; + troubleshootingCheckboxes.forEach(checkbox => { + if (checkbox.checked) { + // eslint-disable-next-line + logsToDownload.push(logLocations.filter(name => name.includes(`custom-Adyen_${checkbox.value}`))); + } + }); + const selectedLogs = Array.prototype.concat.apply([], logsToDownload); + selectedLogs.forEach(item => downloadFile(item)); + downloadLogsButton.classList.add('disabled'); + troubleshootingCheckboxes.forEach(checkbox => { + checkbox.checked = false; + }); + })(); + }); + + // add event listener to maintain form updates + form.addEventListener('change', event => { + const { + name + } = event.target; + let { + value + } = event.target; // get checked boolean value for checkboxes + + if (event.target.type === 'checkbox') { + value = event.target.checked; + } + + // convert radio button strings to boolean if values are 'true' or 'false' + if (event.target.type === 'radio') { + if (event.target.value === 'true') { + value = true; + } + if (event.target.value === 'false') { + value = false; + } + } + settingChanged(name, value); + }); + + // add event listener to test connection based on current form contents + testConnectionButton.addEventListener('click', async () => { + const response = await fetch('AdyenSettings-TestConnection', { + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: JSON.stringify({ + xApiKey: document.getElementById('apiKey').value, + merchantAccount: document.getElementById('merchantAccount').value + }) + }); + const data = await response.json(); + if (data.success) { + merchAccount.classList.add(isValid); + merchAccount.classList.remove(isInvalid); + apiKeyVal.classList.add(isValid); + apiKeyVal.classList.remove(isInvalid); + } else { + merchAccount.classList.add(isInvalid); + merchAccount.classList.remove(isValid); + apiKeyVal.classList.add(isInvalid); + apiKeyVal.classList.remove(isValid); + } + }); + submitButton.addEventListener('click', async () => { + // disable form buttons and reattach event listener for enabling it on form change + disableFormButtons(); + form.addEventListener('input', enableformButtons); + const response = await fetch('AdyenSettings-Save', { + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + method: 'POST', + body: JSON.stringify({ + settings: changedSettings + }) + }); + const data = await response.json(); + if (data.success) { + const alertBar = document.getElementById('saveChangesAlert'); + alertBar.classList.add('show'); + window.setTimeout(() => { + alertBar.classList.remove('show'); + }, 2000); + } else { + const cancelAlertBar = document.getElementById('notSavedChangesAlert'); + cancelAlertBar.classList.add('show'); + window.setTimeout(() => { + cancelAlertBar.classList.remove('show'); + }, 2000); + } + }); + cancelButton.addEventListener('click', async () => { + window.location.reload(); + }); + createExpressPaymentsComponent(); +}); \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/navigationCard.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/navigationCard.isml new file mode 100644 index 000000000..345074b60 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/navigationCard.isml @@ -0,0 +1,42 @@ + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/quickLinksCard.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/quickLinksCard.isml new file mode 100644 index 000000000..b93974a07 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/quickLinksCard.isml @@ -0,0 +1,33 @@ + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/adyenGivingSettings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/adyenGivingSettings.isml new file mode 100644 index 000000000..30f16bcfd --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/adyenGivingSettings.isml @@ -0,0 +1,101 @@ + + +
        + +
        +
        Adyen Giving (optional)
        + +
        + Give your shoppers the option to donate to a charity during their payment. + Not sure how to register to Adyen Giving? Contact your Account Manager or Support. +
        +
        +
        +
        + +
        +
        +  Create a charity account to enable Adyen Giving. +
        +
        +
        + +
        +
        +
        +
        +
        +
        + + Enter the name of the charity displayed on the Adyen Giving Component. +
        + +
        +
        +
        + + Enter the name of your charity’s merchant account. +
        + +
        +
        +
        + + Enter the suggested amounts shoppers can choose to donate. +
        + +
        +
        +
        + + Create a short description of up to 70 characters to be displayed to your shoppers before they donate. +
        + +
        +
        +
        + + Enter the link to the charity website. +
        + +
        +
        +
        + + Your image needs to be in PNG, JPG, JPEG, or SVG format. + +
        + +
        Click here to upload.
        +
        +
          +
          +
          +
          +
          +
          + + Your image needs to be in PNG, JPG, JPEG, or SVG format. + +
          + + + +
          +
          +
          +
          +
          +
          \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/cardSettings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/cardSettings.isml new file mode 100644 index 000000000..409b8ff01 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/cardSettings.isml @@ -0,0 +1,37 @@ + + +
          +
          +
          + Card settings +
          + +
          Choose additional payment features you want to offer to your shoppers.
          +
          +
          +
          + + This allows you to show the input field for the cardholder’s name. +
          +
          + + +
          +
          + + +
          +
          +
          +
          + + + If you’re offering an installments option to your shoppers, go to our GitHub to create the required configuration value and paste it here. + +
          + +
          +
          +
          +
          +
          diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/epmSettings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/epmSettings.isml new file mode 100644 index 000000000..6be708d4a --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/epmSettings.isml @@ -0,0 +1,41 @@ + + + +
          +
          +
          + Express checkout (optional) +
          + +
          Allow your shoppers to pay instantly with the payment methods they trust across multiple stores.
          +
          +
          +
          + + Make sure the payment methods are also enabled in the Customer Area. +
          +
          +
          + +
          +
          +
          + + Customize the order that you would like to place the express buttons in the checkout. +
          +
          +
          +
            +
            +
            +
            +
            +
            \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/lpmSettings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/lpmSettings.isml new file mode 100644 index 000000000..4ac0d32d1 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/lpmSettings.isml @@ -0,0 +1,70 @@ + + +
            +
            +
            + Local payment method settings +
            + +
            Configure required additional settings for payment methods. Most payment methods work without additional settings, find an overview of all payment methods here.
            +
            +
            +
            + + If your SFCC is connected to an OMS instance, you need to add the same payment methods you selected in the Customer Area. Make sure that all letters are lowercase, and separate multiple payment methods with commas. +
            + +
            +
            +
            + + This is an open invoice and secured direct debit provider available in Germany, Austria, Switzerland, and the Netherlands. Enter the unique ID provided by your Ratepay integration consultant. +
            + +
            +
            +
            + + Google Pay is enabled by default in the Test environment. If you also want to activate it in the Live environment, enter your Google Merchant ID +
            + +
            +
            +
            + + Apple Pay is enabled by default in the Test environment. If you also want to activate it in the Live environment, enter Apple Pay Domain Association +
            + +
            +
            +
            + + One-click stores payment details of your shoppers securely. It allows you to offer subscriptions, automatic top-ups to shoppers’ accounts, and give them a faster checkout experience. +
            +
            + + +
            +
            + + +
            +
            +
            +
            + + Klarna inline widget allows you to complete Klarna payments without browser redirect. +
            +
            + + +
            +
            + + +
            +
            +
            +
            +
            +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/optionalSettings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/optionalSettings.isml new file mode 100644 index 000000000..16cced87e --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/optionalSettings.isml @@ -0,0 +1,78 @@ + + +
            +
            +
            + Additional settings (optional) +
            + +
            Improve your business’s transparency and security.
            +
            +
            +
            + + + 2/3 Data gives you interchange discounts on US domestic transactions. Your shoppers will also see additional data about their purchases on their credit card statements. + Check if your business is eligible for Level 2/3 Data. + +
            +
            + + +
            +
            + + +
            +
            +
            +
            + + Enter the UNSPSC commodity code to classify your products or services. +
            + +
            +
            +
            + + + We got you covered with our Revenue protect, risk engine. But if you want to create specific basket fields items in your risk set up, you can. + Please set up these custom fields in the Adyen Customer Area and enable this setting. + +
            +
            + + +
            +
            + + +
            +
            +
            +
            + + + To tokenize payment details for all payment methods, make sure you have this feature enabled. + +
            +
            + + +
            +
            + + +
            +
            +
            +
            + + Let us know the name of the company that built your integration with Adyen to get custom support. +
            + +
            +
            +
            +
            +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/posSettings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/posSettings.isml new file mode 100644 index 000000000..a6addfd14 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/posSettings.isml @@ -0,0 +1,21 @@ + + +
            +
            +
            + In-person payments settings (optional) +
            + +
            Set up your POS to process payments in your web store.
            +
            +
            +
            + + If you want a POS in your physical store, enter the unique store ID. Keep in mind that you can only assign your POS to a single store. +
            + +
            +
            +
            +
            +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/requiredSettings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/requiredSettings.isml new file mode 100644 index 000000000..d64de70a9 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/requiredSettings.isml @@ -0,0 +1,99 @@ + + + +
            +
            +
            + Account settings +
            + +
            Make sure that you’re logged into the Customer Area as you will need to copy several settings to fill in the following information.
            +
            +
            +
            + + Use the "Test" option in order to connect to your Adyen test environment. Use live to connect to your Adyen Live environment. +
            +
            + + +
            +
            + + +
            +
            +
            +
            + + + How to set up your client key? + +
            + +
            +
            +
            + + SFRA combines best practices in site design and technical architecture so you can customize your store’s website. This setting should only be enabled if you’re using SFRA v6. +
            +
            + + +
            +
            + + +
            +
            +
            +
            + + + Enter the closest regions to your shoppers. This setup influences the speed of the Adyen Checkout Component during checkout. + Check the list of regions + +
            +
            +
            +
            +
            + + Please note that you can enter only one merchant account per storefront. +
            + +
            +
            Please make sure the combination of merchant account and API key is correct.
            +
            +
            +
            + + This is the API key you generated in the Customer Area. +
            + + + + +
            +
            +
            + Please make sure the combination of merchant account and API key is correct. +
            +
            +
            +
            +
            +
            + +
            +
            +
            +
            +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/troubleshooting.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/troubleshooting.isml new file mode 100644 index 000000000..45094c7ad --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/troubleshooting.isml @@ -0,0 +1,57 @@ + + +
            +
            +
            + Troubleshooting +
            + +
            You can download Adyen Logs from here.
            +
            +
            +
            + + + The logs are generated from the last 14 days. The downloaded files don’t include visuals, just text. + +
            +
            +
              +
            • + + + + For checking order data, order create date delay, current date, and service config calls to Adyen Checkout API. + +
            • +
            • + + + + For informational messages about payment results, webhooks processing, authorization, and order updates. + +
            • +
            • + + + + For errors related to configuration, payment, order processing, card details, and components. + +
            • +
            • + + + + For severe errors preventing the cartridge from functioning properly. + +
            • +
            +
            +
            +
            + +
            +
            +
            +
            +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/webhookSettings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/webhookSettings.isml new file mode 100644 index 000000000..cc70b092d --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settingCards/webhookSettings.isml @@ -0,0 +1,51 @@ + + + + +
            +
            +
            + Webhook settings +
            + +
            + To receive authorization status updates, you need to set up your webhook notification credentials in your Customer Area. +
            +
            +
            +
            + + This is the username you created under the Developers section in the Customer Area. +
            + +
            +
            +
            + + This is the password you created under the Developers section in the Customer Area. + + + +
            + +
            +
            +
            + + This is the HMAC key you created under the Developers section in the Customer Area. + + + +
            + +
            +
            +
            +
            +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settings.isml b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settings.isml new file mode 100644 index 000000000..38d1d3e48 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/adyenSettings/settings.isml @@ -0,0 +1,78 @@ + + + + + + + + + + + +
            + +
            + + + + +
            +
            +
            +
            +
            + + +
            +
            +
            +
            +
            + + + + + + + + + +
            + + +
            +
            +
            +
            +
            + + +
            +
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/application/MenuFrame.isml b/cartridges/bm_adyen/cartridge/templates/default/application/MenuFrame.isml new file mode 100644 index 000000000..878b80f5d --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/application/MenuFrame.isml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/custom/modules.isml b/cartridges/bm_adyen/cartridge/templates/default/custom/modules.isml new file mode 100644 index 000000000..c07052c9a --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/custom/modules.isml @@ -0,0 +1,20 @@ + + + + + + + + + + \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/extensions/custom_adminmenupageextension.isml b/cartridges/bm_adyen/cartridge/templates/default/extensions/custom_adminmenupageextension.isml new file mode 100644 index 000000000..0d3d6e394 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/extensions/custom_adminmenupageextension.isml @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + +
            +

            Custom Error ...: hasn't been defined. This is an error message sample.
            +

            +
            + + + + + + + + + + +
            +

            This page allows to view and configure custom values. +

            + To save your settings, press the 'Apply' button. +

            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            NameValueTypeDefault Value
            + Parametername + + + + + CustomType   + + DefaultValue   +
            Instance times: + + + + + + +
            +
            There are no custom values defined yet.
            +
            Instance time:
            + + + + + + + +
            + +
            + + +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/extensions/custom_sitemenupageextension.isml b/cartridges/bm_adyen/cartridge/templates/default/extensions/custom_sitemenupageextension.isml new file mode 100644 index 000000000..0d1529e24 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/extensions/custom_sitemenupageextension.isml @@ -0,0 +1,106 @@ + + + + + + + + + + + + + + + + +
            +

            Custom Error ...: hasn't been defined. This is an error message sample.
            +

            +
            + + + + + + + + + + +
            +

            This page allows to view and configure custom values. +

            + To save your settings, press the 'Apply' button.
            +

            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            NameValueTypeDefault Value
            + Parametername + + class="inputfield_en w100"/> + + + CustomType   + + DefaultValue   +
            Site time: + + + + + + "/> + "/> + +
            +
            There are no custom values defined yet.
            +
            Site time:
            + + + + + + + + +
            + +
            + + +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/marketing/giftcertificateemail.isml b/cartridges/bm_adyen/cartridge/templates/default/marketing/giftcertificateemail.isml new file mode 100644 index 000000000..109117276 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/marketing/giftcertificateemail.isml @@ -0,0 +1,45 @@ + + + + + + +A Gift Certificate for You + + +
            + + Dear Valued Customer, + + Dear , + +
            +
            + A Gift Certificate has been issued to you in the amount of . +
            +
            + + Message: +
            +
            + +
            +
            +
            + You can redeem your gift certificate at our online store. +
            +
            + Your gift certificate code is . +
            +
            + Sincerely, +
            +
            + + Customer Support + + + +
            + + \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_ADYEN_CREDIT.isml b/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_ADYEN_CREDIT.isml new file mode 100644 index 000000000..360e3670f --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_ADYEN_CREDIT.isml @@ -0,0 +1,54 @@ + + + + + + var order = pdict.Order; + var paymentInstruments = order.getPaymentInstruments().iterator(); + if (paymentInstruments.hasNext()) { + var paymentInstrument = paymentInstruments.next(); + var paymentMethod = dw.order.PaymentMgr.getPaymentMethod(paymentInstrument.paymentMethod); + var amount = order.custom.Adyen_value/100; + } + +

            + +
            + + + + + + + + + + + + + + + + + + +
            + + Payment info

            PSP reference + + var mode : String = dw.system.Site.getCurrent().getCustomPreferenceValue("Adyen_Mode"); + var urlPrefixType : String = 'test'; + if (mode == 'LIVE') { + urlPrefixType = 'live'; + } + + + + +
            Payment Method
            Eventcode
            Amount
            +
            +
            + \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_Adyen.isml b/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_Adyen.isml new file mode 100644 index 000000000..2d12c1758 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_Adyen.isml @@ -0,0 +1,83 @@ + + + + + + var order = pdict.Order; + var paymentInstruments = order.getPaymentInstruments().iterator(); + if (paymentInstruments.hasNext()) { + var paymentInstrument = paymentInstruments.next(); + var paymentMethod = dw.order.PaymentMgr.getPaymentMethod(paymentInstrument.paymentMethod); + var amount = order.custom.Adyen_value/100; + var adyenAdditionalPaymentData = JSON.parse(paymentInstrument.custom.adyenAdditionalPaymentData); + var adyenAction = JSON.parse(paymentInstrument.custom.adyenAction); + } + +

            + +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            + + Payment info
            PSP reference
            Payment Method
            Eventcode
            Reference:${bankTransferItem.value}
            Beneficiary Name:${bankTransferItem.value}
            Bankaccount:${bankTransferItem.value}
            ${adyenAction.reference}
            ${adyenAction.maskedTelephoneNumber}
            ${adyenAction.expiresAt}
            +
            +
            + + \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_Adyen_Component.isml b/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_Adyen_Component.isml new file mode 100644 index 000000000..01a9ba00c --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/PaymentInstrumentInfo_Adyen_Component.isml @@ -0,0 +1,93 @@ + + + + + + var order = pdict.Order; + var paymentInstruments = order.getPaymentInstruments().iterator(); + if (paymentInstruments.hasNext()) { + var paymentInstrument = paymentInstruments.next(); + var paymentMethod = dw.order.PaymentMgr.getPaymentMethod(paymentInstrument.paymentMethod); + var amount = order.custom.Adyen_value/100; + var adyenAdditionalPaymentData = JSON.parse(paymentInstrument.custom.adyenAdditionalPaymentData); + var adyenAction = JSON.parse(paymentInstrument.custom.adyenAction); + var adyenPaymentMethod = paymentInstrument.custom.adyenPaymentMethod; + } + +

            + +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            + + Payment info
            PSP reference
            Payment Method
            Eventcode
            Reference:${bankTransferItem.value}
            Beneficiary Name:${bankTransferItem.value}
            Bankaccount:${bankTransferItem.value}
            Reference:${adyenAction.reference}
            Phonenumber:${adyenAction.maskedTelephoneNumber}
            Expires at:${adyenAction.expiresAt}
            Download URL:Download here
            Entity:${adyenAction.entity}
            +
            +
            + + \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/orderdetails.isml b/cartridges/bm_adyen/cartridge/templates/default/order/orderdetails.isml new file mode 100644 index 000000000..45ff7b7c2 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/orderdetails.isml @@ -0,0 +1,181 @@ +
            + + + + + + + + var plis : dw.util.Collection = Group.productLineItems; + var shipRowSpanCount : Number = plis.size(); + var shipRowSpanValue : String = "1"; + var iter : dw.util.Iterator = plis.iterator(); + while (iter != null && iter.hasNext()) + { + var pli : dw.order.ProductLineItme = iter.next(); + shipRowSpanCount = shipRowSpanCount + pli.getBundledProductLineItems().size() + pli.getOptionProductLineItems().size(); + } + shipRowSpanValue = shipRowSpanCount.toFixed(); + + +

            + Shipment  +

            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Product DetailsQty.TotalShipping Details
            + + + + + + + + +
            + Item Number: +
            + + + + + +
            + : + + + + - + +
            +
            +
            +
            + + + + + + +

            +
            + +
            + + Bonus + + + + + + + +

            +
            + +
            + +
            +
            + +
            +
            + + included
            +
            + Option Product -  +
            + + +

            +
            + +
            + + + + + +

            +
            + +
            +
            +
            + + + +

            Gift Certificates

            + + + + + + + + + + + + + + + + + + + + + + +
            Gift Certificate DetailsQty.TotalShipping Details
             for 1Electronic Delivery to 
            +
            + +
            +
            \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/orderemailcancellation.isml b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailcancellation.isml new file mode 100644 index 000000000..4f46bfe9c --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailcancellation.isml @@ -0,0 +1,63 @@ + + + + + + + + + + of your Order #'#'# + + + + + + + + + + + + + +
            SiteGenesisDemo SiteGenesis
            + 5 Wall Street
            + Burlington, MA 01803
            + SiteGenesis
            + Phone: +1.888.553.9216
            + +
            +
            + Order Cancellation: Order Number: - Your order was cancelled! +
            +
            +

            This email confirms we cancelled your order at SiteGenesis. + You can check your order's status on your account pages at SiteGenesis

            +

            Thank you for shopping with us!

            + +

            Please print and save a copy for reference.

            +

            PLEASE NOTE: + Please don't hesitate to contact us for any further questions via PHONE ONLY, at + +1.888.553.9216 +

            +
            + +
            + + + + +
            + +
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/orderemailconfirmation.isml b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailconfirmation.isml new file mode 100644 index 000000000..5b5cbb014 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailconfirmation.isml @@ -0,0 +1,78 @@ + + + + + + + + + +Confirmation of your Order + + + + + + + + + + + + + + + + +
            SiteGenesisDemo SiteGenesis
            + 5 Wall Street
            + Burlington, MA 01803
            + SiteGenesis
            + Phone: +1.888.553.9216
            + +
            +
            + Order Confirmation: Order Number: - Thank you for your order! +
            +
            +

            This email confirms we received your order at SiteGenesis. We will email your shipping + confirmation with your tracking number when your items have been shipped. + Your order will generally be shipped within 24 hours after we've received it. + You can check your order's status on your account pages at SiteGenesis

            +

            Thank you for shopping with us!

            + +

            Please print and save a copy for reference.

            +

            Please review the order below and verify that everything is correct.

            +

            PLEASE NOTE: + Since we begin processing your order shortly after you submit it on our web site, if any changes are necessary you MUST contact us via PHONE ONLY, at + +1.888.553.9216 +

            +
            + +
            + + + + + +

            + +
            +
            + + \ No newline at end of file diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/orderemailcss.isml b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailcss.isml new file mode 100644 index 000000000..0c0ae3eee --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailcss.isml @@ -0,0 +1,311 @@ + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/orderemailgeneral.isml b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailgeneral.isml new file mode 100644 index 000000000..cede5a241 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailgeneral.isml @@ -0,0 +1,64 @@ + + + + + + + + + + - Order + + + + + + + + + + + + + + + +
            +
            + Order Information: Order Number: - Thank you for your order! +
            +
            +

            This email gives you all details of your order at SiteGenesis. + You can check your order's status on your account pages at SiteGenesis

            +

            Thank you for shopping with us!

            + +

            Please print and save a copy for reference.

            +

            Please review the order below and verify that everything is correct.

            +

            PLEASE NOTE: + If you have any questions about your order, order status, etc. you MUST contact us via PHONE ONLY, at + +1.888.553.9216 +

            +
            + +
            + + + + +
            + +
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/orderemailpaymentconfirmation.isml b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailpaymentconfirmation.isml new file mode 100644 index 000000000..bd5fbc8e6 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailpaymentconfirmation.isml @@ -0,0 +1,67 @@ + + + + + + + + + + of your Order + + + + + + + + + + + + + +
            SiteGenesisDemo SiteGenesis
            + 5 Wall Street
            + Burlington, MA 01803
            + SiteGenesis
            + Phone: +1.888.553.9216
            + +
            +
            + Payment Confirmation: Order Number: - Thank you for your order! +
            +
            +

            This email confirms we received your payment at SiteGenesis. + We will email your shipping confirmation with your tracking number when your items have been shipped. + Your order will generally be shipped within 24 hours after we've received it. + You can check your order's status on your account pages at SiteGenesis

            +

            Thank you for shopping with us!

            + +

            Please print and save a copy for reference.

            +

            Please review the order below and verify that everything is correct.

            +

            PLEASE NOTE: + Since we begin processing your order shortly after you submit it on our web site, if any changes are necessary you MUST contact us via PHONE ONLY, at + +1.888.553.9216 +

            +
            + +
            + + + + + +
            + +
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/orderemailshippingconfirmation.isml b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailshippingconfirmation.isml new file mode 100644 index 000000000..f60690836 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/orderemailshippingconfirmation.isml @@ -0,0 +1,58 @@ + + + + + + + + + of your Order #'#'# + + + + + + + + + + + + + +
            SiteGenesisDemo SiteGenesis
            + 5 Wall Street
            + Burlington, MA 01803
            + SiteGenesis
            + Phone: +1.888.553.9216
            + +
            +
            + Shipping Confirmation: Order Number: - Thank you for your order! +
            +
            +

            This email confirms we shipped your order at SiteGenesis. + You can check your order's status on your account pages at SiteGenesis

            +

            Thank you for shopping with us!

            + +

            Please print and save a copy for reference.

            +
            + +
            + + + + +
            + +
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/paymentdetails.isml b/cartridges/bm_adyen/cartridge/templates/default/order/paymentdetails.isml new file mode 100644 index 000000000..29d776feb --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/paymentdetails.isml @@ -0,0 +1,53 @@ +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            Payment MethodAmount
            Payment Total
            + +
            + +
            + +
            + Gift Certificate +
            + +
            + +
            +
            diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/printordergeneral.isml b/cartridges/bm_adyen/cartridge/templates/default/order/printordergeneral.isml new file mode 100644 index 000000000..dbf86f3f2 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/printordergeneral.isml @@ -0,0 +1,174 @@ + + + + + + + Order <isprint value="${pdict.Order.orderNo}"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
             

            Order:

             
            + + + + + + + + + + +
            SiteGenesis
            5 Wall Street
            Burlington, MA 01803 USA
            +
            + + + + + + + + + + + + + +
            Order:
            Date:
            Total:
            +
             
             
            Bill To:  + + + + + + + + + + + + + + + + + + + +
            Phone: n/a
            Email:
            +
             
             
             
            +
            + + +
            +
             
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/printorderinvoice.isml b/cartridges/bm_adyen/cartridge/templates/default/order/printorderinvoice.isml new file mode 100644 index 000000000..a80053002 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/printorderinvoice.isml @@ -0,0 +1,109 @@ + + + + + + + Invoice <isprint value="${pdict.Order.orderNo}"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

            Invoice:

              + + + + +
            SiteGenesis
            5 Wall Street
            Burlington, MA 01803 USA
            +
            + + + + + + + +
            Order:
            Date:
            Total:
            +
            Bill To: + + + + + +
            +
            + + + + + +
            Phone:n/a
            Email:
            +
            Payment Methods:Payment Method: + + + +
            Amount:
            + +
            + + + +
            +
            Gift Certificate: +
            Amount: +
            +
            + + + + +

            Unknown payment processor. Cannot display payment data.
            +
            +
            +
            + + +
            +
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/order/printorderpackingslip.isml b/cartridges/bm_adyen/cartridge/templates/default/order/printorderpackingslip.isml new file mode 100644 index 000000000..e62691e15 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/order/printorderpackingslip.isml @@ -0,0 +1,163 @@ + + + + + + + + Packing Slip <isprint value="${pdict.LineItemGroup.shipmentNo}"> For Order <isprint value="${pdict.Order.orderNo}"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

            Packing Slip For Order

             
            Ship To: + + + + +
            + + + + + + + + + + + + + + + + +
            ${pdict.LineItemGroup.shippingAddress.firstName} ${pdict.LineItemGroup.shippingAddress.lastName}
            ${pdict.LineItemGroup.shippingAddress.address1}
            ${pdict.LineItemGroup.shippingAddress.address2}
            ${pdict.LineItemGroup.shippingAddress.city}, ${pdict.LineItemGroup.shippingAddress.stateCode} ${pdict.LineItemGroup.shippingAddress.postalCode}
            ${pdict.Order.customerEmail}
            +
            +
            Ship From: + + + + +
            + + + + + + + + + + +
            SiteGenesis
            5 Wall Street
            Burlington, MA 01803 USA
            +
            +
             
             
            Shipping Method:  + + + Shipping () + + + Shipping () + + Shipping () + + + + Not Applicable (Email Delivery of Gift Certificate) + + Not Applicable + +
             
             
            This package includes:
             
              + + + + + + +  
              of
            of
             
             
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/user/miniaddress.isml b/cartridges/bm_adyen/cartridge/templates/default/user/miniaddress.isml new file mode 100644 index 000000000..fb0c20345 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/user/miniaddress.isml @@ -0,0 +1,47 @@ + + + + +
            + +
            + + + +   + +
            +
            + +
            + + +
            +
            + +
            +
            + +
            + +
             
            +
            +
            +
            +
            + + + +   +
            +
            +
            +
            + diff --git a/cartridges/bm_adyen/cartridge/templates/default/user/minicreditcard.isml b/cartridges/bm_adyen/cartridge/templates/default/user/minicreditcard.isml new file mode 100644 index 000000000..7fc931c28 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/user/minicreditcard.isml @@ -0,0 +1,51 @@ + + + + + + var ccType : String; + var ccNumber : String; + var ccMonth : Integer; + var ccYear : Integer; + var ccOwner : String; + + if( pdict.p_card != null ) + { + ccType = pdict.p_card.creditCardType; + ccNumber = pdict.p_card.maskedCreditCardNumber; + ccMonth = pdict.p_card.creditCardExpirationMonth; + ccYear = pdict.p_card.creditCardExpirationYear; + ccOwner = pdict.p_card.creditCardHolder; + } + else + { + ccType = pdict.p_cc_formfield.type.htmlValue; + ccNumber = pdict.p_cc_formfield.number.htmlValue; + ccMonth = pdict.p_cc_formfield.month.value; + ccYear = pdict.p_cc_formfield.year.value; + ccOwner = pdict.p_cc_formfield.owner.htmlValue; + } + + +
            +
            + +
            +
            + +
            +
            + / +
            +
            + +
            +
            + diff --git a/cartridges/bm_adyen/cartridge/templates/default/user/minishippingaddress.isml b/cartridges/bm_adyen/cartridge/templates/default/user/minishippingaddress.isml new file mode 100644 index 000000000..8f79b9875 --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/user/minishippingaddress.isml @@ -0,0 +1,66 @@ + + + + + +
            + + +
            + +
            +
            +
            + + +
            +
            + +
            + +
            +
            +
            + + + +   +
            + + +
            + +
            + + + + + + - + + + + + +
            + + + + +
            +
            +
            + +
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/default/user/passwordemail.isml b/cartridges/bm_adyen/cartridge/templates/default/user/passwordemail.isml new file mode 100644 index 000000000..4d8e6d12a --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/default/user/passwordemail.isml @@ -0,0 +1,24 @@ + + + +Your New Password + + +
            + + Dear ${pdict.Profile.firstName} ${pdict.Profile.lastName}, +

            + Your password has been reset. Your new Password is + .
            + It is recommended that you reset your password the next time you + log on + to our site. +
            + This is an automatic generated E-Mail, please do not reply. +

            +   + +
            + + + diff --git a/cartridges/bm_adyen/cartridge/templates/resources/adyen.properties b/cartridges/bm_adyen/cartridge/templates/resources/adyen.properties new file mode 100644 index 000000000..226b812ea --- /dev/null +++ b/cartridges/bm_adyen/cartridge/templates/resources/adyen.properties @@ -0,0 +1,3 @@ +settings.input.apiKey.name=apiKey +settings.input.apiKey.label=Api key of Web service +settings.input.apiKey.description=To connect your Commerce Cloud store to the Adyen API, you need to generate an API key in the Customer Area. Once you generated an API key, enter this key in the field below. \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenAccount.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenAccount.js new file mode 100644 index 000000000..698ef48e9 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenAccount.js @@ -0,0 +1,131 @@ +"use strict"; + +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +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); }); }; } +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +var _require = require('./commons/index'), + onFieldValid = _require.onFieldValid, + onBrand = _require.onBrand, + createSession = _require.createSession; +var store = require('../../../store'); +var checkout; +var card; + +// Store configuration +store.checkoutConfiguration.amount = { + value: 0, + currency: 'EUR' +}; +store.checkoutConfiguration.paymentMethodsConfiguration = { + card: { + enableStoreDetails: false, + hasHolderName: true, + holderNameRequired: true, + installments: [], + onBrand: onBrand, + onFieldValid: onFieldValid, + onChange: function onChange(state) { + store.isValid = state.isValid; + store.componentState = state; + } + } +}; + +// Handle Payment action +function handleAction(action) { + checkout.createFromAction(action).mount('#action-container'); + $('#action-modal').modal({ + backdrop: 'static', + keyboard: false + }); +} + +// confirm onAdditionalDetails event and paymentsDetails response +store.checkoutConfiguration.onAdditionalDetails = function (state) { + $.ajax({ + type: 'POST', + url: 'Adyen-PaymentsDetails', + data: JSON.stringify({ + data: state.data + }), + contentType: 'application/json; charset=utf-8', + async: false, + success: function success(data) { + if (data.isSuccessful) { + window.location.href = window.redirectUrl; + } else if (!data.isFinal && _typeof(data.action) === 'object') { + handleAction(data.action); + } else { + $('#action-modal').modal('hide'); + document.getElementById('cardError').style.display = 'block'; + } + } + }); +}; +function initializeCardComponent() { + return _initializeCardComponent.apply(this, arguments); +} +function _initializeCardComponent() { + _initializeCardComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var session, cardNode; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return createSession(); + case 2: + session = _context.sent; + store.checkoutConfiguration.session = { + id: session.id, + sessionData: session.sessionData + }; + cardNode = document.getElementById('card'); + _context.next = 7; + return AdyenCheckout(store.checkoutConfiguration); + case 7: + checkout = _context.sent; + card = checkout.create('card').mount(cardNode); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _initializeCardComponent.apply(this, arguments); +} +var formErrorsExist = false; +function submitAddCard() { + var form = $(document.getElementById('payment-form')); + $.ajax({ + type: 'POST', + url: form.attr('action'), + data: form.serialize(), + async: false, + success: function success(data) { + if (data.redirectAction) { + handleAction(data.redirectAction); + } else if (data.redirectUrl) { + window.location.href = data.redirectUrl; + } else if (data.error) { + formErrorsExist = true; + } + } + }); +} +initializeCardComponent(); + +// Add Payment Button event handler +$('button[value="add-new-payment"]').on('click', function (event) { + if (store.isValid) { + document.querySelector('#adyenStateData').value = JSON.stringify(store.componentState.data); + submitAddCard(); + if (formErrorsExist) { + return; + } + event.preventDefault(); + } else { + var _card; + (_card = card) === null || _card === void 0 ? void 0 : _card.showValidation(); + } +}); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenCheckout.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenCheckout.js new file mode 100644 index 000000000..6ea7adddd --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenCheckout.js @@ -0,0 +1,62 @@ +"use strict"; + +var store = require('../../../store'); +var _require = require('./adyen_checkout/renderGenericComponent'), + renderGenericComponent = _require.renderGenericComponent; +var _require2 = require('./adyen_checkout/checkoutConfiguration'), + setCheckoutConfiguration = _require2.setCheckoutConfiguration, + actionHandler = _require2.actionHandler; +var _require3 = require('./adyen_checkout/helpers'), + assignPaymentMethodValue = _require3.assignPaymentMethodValue, + showValidation = _require3.showValidation, + paymentFromComponent = _require3.paymentFromComponent; +var _require4 = require('./adyen_checkout/validateComponents'), + validateComponents = _require4.validateComponents; +$('#dwfrm_billing').submit(function apiRequest(e) { + e.preventDefault(); + var form = $(this); + var url = form.attr('action'); + $.ajax({ + type: 'POST', + url: url, + data: form.serialize(), + async: false, + success: function success(data) { + store.formErrorsExist = 'fieldErrors' in data; + } + }); +}); +setCheckoutConfiguration(); +if (window.cardholderNameBool !== 'null') { + store.checkoutConfiguration.paymentMethodsConfiguration.card.hasHolderName = true; + store.checkoutConfiguration.paymentMethodsConfiguration.card.holderNameRequired = true; +} +if (window.googleMerchantID !== 'null' && window.Configuration.environment === 'live') { + var id = 'merchantId'; + store.checkoutConfiguration.paymentMethodsConfiguration.paywithgoogle.configuration[id] = window.googleMerchantID; + store.checkoutConfiguration.paymentMethodsConfiguration.googlepay.configuration[id] = window.googleMerchantID; +} + +// Submit the payment +$('button[value="submit-payment"]').on('click', function () { + if (store.paypalTerminatedEarly) { + paymentFromComponent({ + cancelTransaction: true, + merchantReference: document.querySelector('#merchantReference').value + }); + store.paypalTerminatedEarly = false; + } + if (document.querySelector('#selectedPaymentOption').value === 'AdyenPOS') { + document.querySelector('#terminalId').value = document.querySelector('#terminalList').value; + } + if (document.querySelector('#selectedPaymentOption').value === 'AdyenComponent' || document.querySelector('#selectedPaymentOption').value === 'CREDIT_CARD') { + assignPaymentMethodValue(); + validateComponents(); + return showValidation(); + } + return true; +}); +module.exports = { + renderGenericComponent: renderGenericComponent, + actionHandler: actionHandler +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenGiving.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenGiving.js new file mode 100644 index 000000000..f311a16b4 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenGiving.js @@ -0,0 +1,50 @@ +"use strict"; + +var adyenGivingNode = document.getElementById('donate-container'); +function handleOnDonate(state, component) { + if (!state.isValid) { + return; + } + var selectedAmount = state.data.amount; + var donationData = { + amountValue: selectedAmount.value, + amountCurrency: selectedAmount.currency, + orderNo: window.orderNo, + orderToken: window.orderToken + }; + $.ajax({ + url: window.donateURL, + type: 'post', + data: donationData, + success: function success() { + component.setStatus('success'); + } + }); +} +function handleOnCancel(state, component) { + var adyenGiving = document.getElementById('adyenGiving'); + adyenGiving.style.transition = 'all 3s ease-in-out'; + adyenGiving.style.display = 'none'; + component.unmount(); +} +function getAmounts() { + try { + return JSON.parse(donationAmounts); + } catch (e) { + return []; + } +} +var donationConfig = { + amounts: getAmounts(), + backgroundUrl: adyenGivingBackgroundUrl, + description: decodeURI(charityDescription), + logoUrl: adyenGivingLogoUrl, + name: decodeURI(charityName), + url: charityWebsite, + showCancelButton: true, + onDonate: handleOnDonate, + onCancel: handleOnCancel +}; +AdyenCheckout(window.Configuration).then(function (checkout) { + checkout.create('donation', donationConfig).mount(adyenGivingNode); +}); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/checkoutConfiguration.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/checkoutConfiguration.js new file mode 100644 index 000000000..79536aced --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/checkoutConfiguration.js @@ -0,0 +1,398 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +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); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var helpers = require('./helpers'); +var _require = require('./makePartialPayment'), + makePartialPayment = _require.makePartialPayment; +var _require2 = require('../commons'), + onBrand = _require2.onBrand, + onFieldValid = _require2.onFieldValid; +var store = require('../../../../store'); +var constants = require('../constants'); +var _require3 = require('./renderGiftcardComponent'), + createElementsToShowRemainingGiftCardAmount = _require3.createElementsToShowRemainingGiftCardAmount, + renderAddedGiftCard = _require3.renderAddedGiftCard, + getGiftCardElements = _require3.getGiftCardElements, + showGiftCardInfoMessage = _require3.showGiftCardInfoMessage, + showGiftCardCancelButton = _require3.showGiftCardCancelButton, + attachGiftCardCancelListener = _require3.attachGiftCardCancelListener; +function getCardConfig() { + return { + enableStoreDetails: window.showStoreDetails, + showBrandsUnderCardNumber: false, + clickToPayConfiguration: { + shopperEmail: window.customerEmail, + merchantDisplayName: window.merchantAccount + }, + onChange: function onChange(state) { + store.isValid = state.isValid; + var method = state.data.paymentMethod.storedPaymentMethodId ? "storedCard".concat(state.data.paymentMethod.storedPaymentMethodId) : store.selectedMethod; + store.updateSelectedPayment(method, 'isValid', store.isValid); + store.updateSelectedPayment(method, 'stateData', state.data); + }, + onSubmit: function onSubmit() { + helpers.assignPaymentMethodValue(); + document.querySelector('button[value="submit-payment"]').disabled = false; + document.querySelector('button[value="submit-payment"]').click(); + }, + onFieldValid: onFieldValid, + onBrand: onBrand + }; +} +function getPaypalConfig() { + store.paypalTerminatedEarly = false; + return { + showPayButton: true, + environment: window.Configuration.environment, + onSubmit: function onSubmit(state, component) { + helpers.assignPaymentMethodValue(); + document.querySelector('#adyenStateData').value = JSON.stringify(store.selectedPayment.stateData); + helpers.paymentFromComponent(state.data, component); + }, + onCancel: function onCancel(data, component) { + store.paypalTerminatedEarly = false; + helpers.paymentFromComponent({ + cancelTransaction: true, + merchantReference: document.querySelector('#merchantReference').value, + orderToken: document.querySelector('#orderToken').value + }, component); + }, + onError: function onError(error, component) { + store.paypalTerminatedEarly = false; + if (component) { + component.setStatus('ready'); + } + document.querySelector('#showConfirmationForm').submit(); + }, + onAdditionalDetails: function onAdditionalDetails(state) { + store.paypalTerminatedEarly = false; + document.querySelector('#additionalDetailsHidden').value = JSON.stringify(state.data); + document.querySelector('#showConfirmationForm').submit(); + }, + onClick: function onClick(data, actions) { + $('#dwfrm_billing').trigger('submit'); + if (store.formErrorsExist) { + return actions.reject(); + } + if (store.paypalTerminatedEarly) { + helpers.paymentFromComponent({ + cancelTransaction: true, + merchantReference: document.querySelector('#merchantReference').value + }); + store.paypalTerminatedEarly = false; + return actions.resolve(); + } + store.paypalTerminatedEarly = true; + return null; + } + }; +} +function getGooglePayConfig() { + return { + environment: window.Configuration.environment, + onSubmit: function onSubmit() { + helpers.assignPaymentMethodValue(); + document.querySelector('button[value="submit-payment"]').disabled = false; + document.querySelector('button[value="submit-payment"]').click(); + }, + configuration: { + gatewayMerchantId: window.merchantAccount + }, + showPayButton: true, + buttonColor: 'white' + }; +} +function handlePartialPaymentSuccess() { + var _store$addedGiftCards; + var _getGiftCardElements = getGiftCardElements(), + giftCardSelectContainer = _getGiftCardElements.giftCardSelectContainer, + giftCardSelect = _getGiftCardElements.giftCardSelect, + giftCardsList = _getGiftCardElements.giftCardsList, + cancelMainPaymentGiftCard = _getGiftCardElements.cancelMainPaymentGiftCard, + giftCardAddButton = _getGiftCardElements.giftCardAddButton; + giftCardSelectContainer.classList.add('invisible'); + giftCardSelect.value = null; + giftCardsList.innerHTML = ''; + cancelMainPaymentGiftCard.addEventListener('click', function () { + store.componentsObj.giftcard.node.unmount('component_giftcard'); + cancelMainPaymentGiftCard.classList.add('invisible'); + giftCardAddButton.style.display = 'block'; + giftCardSelect.value = 'null'; + }); + if (store.componentsObj.giftcard) { + store.componentsObj.giftcard.node.unmount('component_giftcard'); + } + store.addedGiftCards.forEach(function (card) { + renderAddedGiftCard(card); + }); + if ((_store$addedGiftCards = store.addedGiftCards) !== null && _store$addedGiftCards !== void 0 && _store$addedGiftCards.length) { + showGiftCardInfoMessage(); + } + showGiftCardCancelButton(true); + attachGiftCardCancelListener(); + createElementsToShowRemainingGiftCardAmount(); +} +function makeGiftcardPaymentRequest(giftCardData, giftcardBalance, reject) { + var brandSelect = document.getElementById('giftCardSelect'); + var selectedBrandIndex = brandSelect.selectedIndex; + var giftcardBrand = brandSelect.options[selectedBrandIndex].text; + var partialPaymentRequest = { + paymentMethod: giftCardData, + amount: giftcardBalance, + partialPaymentsOrder: { + pspReference: store.adyenOrderData.pspReference, + orderData: store.adyenOrderData.orderData + }, + giftcardBrand: giftcardBrand + }; + var partialPaymentResponse = makePartialPayment(partialPaymentRequest); + if (partialPaymentResponse !== null && partialPaymentResponse !== void 0 && partialPaymentResponse.error) { + reject(); + } else { + handlePartialPaymentSuccess(); + } +} +function getGiftCardConfig() { + var giftcardBalance; + return { + showPayButton: true, + onChange: function onChange(state) { + store.updateSelectedPayment(constants.GIFTCARD, 'isValid', state.isValid); + store.updateSelectedPayment(constants.GIFTCARD, 'stateData', state.data); + }, + onBalanceCheck: function onBalanceCheck(resolve, reject, requestData) { + $.ajax({ + type: 'POST', + url: window.checkBalanceUrl, + data: JSON.stringify(requestData), + contentType: 'application/json; charset=utf-8', + async: false, + success: function success(data) { + giftcardBalance = data.balance; + document.querySelector('button[value="submit-payment"]').disabled = false; + if (data.resultCode === constants.SUCCESS) { + var _getGiftCardElements2 = getGiftCardElements(), + giftCardsInfoMessageContainer = _getGiftCardElements2.giftCardsInfoMessageContainer, + giftCardSelect = _getGiftCardElements2.giftCardSelect, + cancelMainPaymentGiftCard = _getGiftCardElements2.cancelMainPaymentGiftCard, + giftCardAddButton = _getGiftCardElements2.giftCardAddButton, + giftCardSelectWrapper = _getGiftCardElements2.giftCardSelectWrapper; + if (giftCardSelectWrapper) { + giftCardSelectWrapper.classList.add('invisible'); + } + var initialPartialObject = _objectSpread({}, store.partialPaymentsOrderObj); + cancelMainPaymentGiftCard.classList.remove('invisible'); + cancelMainPaymentGiftCard.addEventListener('click', function () { + store.componentsObj.giftcard.node.unmount('component_giftcard'); + cancelMainPaymentGiftCard.classList.add('invisible'); + giftCardAddButton.style.display = 'block'; + giftCardSelect.value = 'null'; + store.partialPaymentsOrderObj.remainingAmountFormatted = initialPartialObject.remainingAmountFormatted; + store.partialPaymentsOrderObj.totalDiscountedAmount = initialPartialObject.totalDiscountedAmount; + }); + document.querySelector('button[value="submit-payment"]').disabled = true; + giftCardsInfoMessageContainer.innerHTML = ''; + giftCardsInfoMessageContainer.classList.remove('gift-cards-info-message-container'); + store.partialPaymentsOrderObj.remainingAmountFormatted = data.remainingAmountFormatted; + store.partialPaymentsOrderObj.totalDiscountedAmount = data.totalAmountFormatted; + resolve(data); + } else if (data.resultCode === constants.NOTENOUGHBALANCE) { + resolve(data); + } else { + reject(); + } + }, + fail: function fail() { + reject(); + } + }); + }, + onOrderRequest: function onOrderRequest(resolve, reject, requestData) { + // Make a POST /orders request + // Create an order for the total transaction amount + var giftCardData = requestData.paymentMethod; + if (store.adyenOrderData) { + makeGiftcardPaymentRequest(giftCardData, giftcardBalance, reject); + } else { + $.ajax({ + type: 'POST', + url: window.partialPaymentsOrderUrl, + data: JSON.stringify(requestData), + contentType: 'application/json; charset=utf-8', + async: false, + success: function success(data) { + if (data.resultCode === 'Success') { + store.adyenOrderData = data; + // make payments call including giftcard data and order data + makeGiftcardPaymentRequest(giftCardData, giftcardBalance, reject); + } + } + }); + } + }, + onSubmit: function onSubmit(state, component) { + store.selectedMethod = state.data.paymentMethod.type; + store.brand = component === null || component === void 0 ? void 0 : component.displayName; + document.querySelector('input[name="brandCode"]').checked = false; + document.querySelector('button[value="submit-payment"]').disabled = false; + document.querySelector('button[value="submit-payment"]').click(); + } + }; +} +function handleOnChange(state) { + store.isValid = state.isValid; + if (!store.componentsObj[store.selectedMethod]) { + store.componentsObj[store.selectedMethod] = {}; + } + store.componentsObj[store.selectedMethod].isValid = store.isValid; + store.componentsObj[store.selectedMethod].stateData = state.data; +} +var actionHandler = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(action) { + var checkout; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return AdyenCheckout(store.checkoutConfiguration); + case 2: + checkout = _context.sent; + checkout.createFromAction(action).mount('#action-container'); + $('#action-modal').modal({ + backdrop: 'static', + keyboard: false + }); + if (action.type === constants.ACTIONTYPE.QRCODE) { + document.getElementById('cancelQrMethodsButton').classList.remove('invisible'); + } + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function actionHandler(_x) { + return _ref.apply(this, arguments); + }; +}(); +function handleOnAdditionalDetails(state) { + $.ajax({ + type: 'POST', + url: window.paymentsDetailsURL, + data: JSON.stringify({ + data: state.data, + orderToken: window.orderToken + }), + contentType: 'application/json; charset=utf-8', + async: false, + success: function success(data) { + if (!data.isFinal && _typeof(data.action) === 'object') { + actionHandler(data.action); + } else { + window.location.href = data.redirectUrl; + } + } + }); +} +function getAmazonpayConfig() { + return { + showPayButton: true, + productType: 'PayAndShip', + checkoutMode: 'ProcessOrder', + locale: window.Configuration.locale, + returnUrl: window.returnURL, + onClick: function onClick(resolve, reject) { + $('#dwfrm_billing').trigger('submit'); + if (store.formErrorsExist) { + reject(); + } else { + helpers.assignPaymentMethodValue(); + resolve(); + } + }, + onError: function onError() {} + }; +} +function getApplePayConfig() { + return { + showPayButton: true, + onSubmit: function onSubmit(state, component) { + helpers.assignPaymentMethodValue(); + helpers.paymentFromComponent(state.data, component); + } + }; +} +function getCashAppConfig() { + return { + showPayButton: true, + onSubmit: function onSubmit(state, component) { + $('#dwfrm_billing').trigger('submit'); + helpers.assignPaymentMethodValue(); + helpers.paymentFromComponent(state.data, component); + } + }; +} +function getKlarnaConfig() { + var _window = window, + klarnaWidgetEnabled = _window.klarnaWidgetEnabled; + if (klarnaWidgetEnabled) { + return { + showPayButton: true, + useKlarnaWidget: true, + onSubmit: function onSubmit(state, component) { + helpers.assignPaymentMethodValue(); + helpers.paymentFromComponent(state.data, component); + }, + onAdditionalDetails: function onAdditionalDetails(state) { + document.querySelector('#additionalDetailsHidden').value = JSON.stringify(state.data); + document.querySelector('#showConfirmationForm').submit(); + } + }; + } + return null; +} +function setCheckoutConfiguration() { + store.checkoutConfiguration.onChange = handleOnChange; + store.checkoutConfiguration.onAdditionalDetails = handleOnAdditionalDetails; + store.checkoutConfiguration.showPayButton = false; + store.checkoutConfiguration.clientKey = window.adyenClientKey; + store.checkoutConfiguration.paymentMethodsConfiguration = { + card: getCardConfig(), + bcmc: getCardConfig(), + storedCard: getCardConfig(), + boletobancario: { + personalDetailsRequired: true, + // turn personalDetails section on/off + billingAddressRequired: false, + // turn billingAddress section on/off + showEmailAddress: false // allow shopper to specify their email address + }, + + paywithgoogle: getGooglePayConfig(), + googlepay: getGooglePayConfig(), + paypal: getPaypalConfig(), + amazonpay: getAmazonpayConfig(), + giftcard: getGiftCardConfig(), + applepay: getApplePayConfig(), + klarna: getKlarnaConfig(), + klarna_account: getKlarnaConfig(), + klarna_paynow: getKlarnaConfig(), + cashapp: getCashAppConfig() + }; +} +module.exports = { + getCardConfig: getCardConfig, + getPaypalConfig: getPaypalConfig, + getGooglePayConfig: getGooglePayConfig, + getAmazonpayConfig: getAmazonpayConfig, + setCheckoutConfiguration: setCheckoutConfiguration, + actionHandler: actionHandler +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js new file mode 100644 index 000000000..312e04b65 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js @@ -0,0 +1,127 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var store = require('../../../../store'); +var constants = require('../constants'); +function assignPaymentMethodValue() { + var adyenPaymentMethod = document.querySelector('#adyenPaymentMethodName'); + // if currently selected paymentMethod contains a brand it will be part of the label ID + var paymentMethodlabelId = "#lb_".concat(store.selectedMethod); + if (adyenPaymentMethod) { + var _document$querySelect; + adyenPaymentMethod.value = store.brand ? store.brand : (_document$querySelect = document.querySelector(paymentMethodlabelId)) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.innerHTML; + } +} +function setOrderFormData(response) { + if (response.orderNo) { + document.querySelector('#merchantReference').value = response.orderNo; + } + if (response.orderToken) { + document.querySelector('#orderToken').value = response.orderToken; + } +} + +/** + * Makes an ajax call to the controller function PaymentFromComponent. + * Used by certain payment methods like paypal + */ +function paymentFromComponent(data) { + var component = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var requestData = store.partialPaymentsOrderObj ? _objectSpread(_objectSpread({}, data), {}, { + partialPaymentsOrder: store.partialPaymentsOrderObj + }) : data; + $.ajax({ + url: window.paymentFromComponentURL, + type: 'post', + data: { + data: JSON.stringify(requestData), + paymentMethod: document.querySelector('#adyenPaymentMethodName').value + }, + success: function success(response) { + var _response$fullRespons; + setOrderFormData(response); + if ((_response$fullRespons = response.fullResponse) !== null && _response$fullRespons !== void 0 && _response$fullRespons.action) { + component.handleAction(response.fullResponse.action); + } else if (response.skipSummaryPage) { + document.querySelector('#result').value = JSON.stringify(response); + document.querySelector('#showConfirmationForm').submit(); + } else if (response.paymentError || response.error) { + component.handleError(); + } + } + }); +} +function resetPaymentMethod() { + $('#requiredBrandCode').hide(); + $('#selectedIssuer').val(''); + $('#adyenIssuerName').val(''); + $('#dateOfBirth').val(''); + $('#telephoneNumber').val(''); + $('#gender').val(''); + $('#bankAccountOwnerName').val(''); + $('#bankAccountNumber').val(''); + $('#bankLocationId').val(''); + $('.additionalFields').hide(); +} + +/** + * Changes the "display" attribute of the selected method from hidden to visible + */ +function displaySelectedMethod(type) { + var _document$querySelect2; + // If 'type' input field is present use this as type, otherwise default to function input param + store.selectedMethod = document.querySelector("#component_".concat(type, " .type")) ? document.querySelector("#component_".concat(type, " .type")).value : type; + resetPaymentMethod(); + var disabledSubmitButtonMethods = constants.DISABLED_SUBMIT_BUTTON_METHODS; + if (window.klarnaWidgetEnabled) { + disabledSubmitButtonMethods.push('klarna'); + } + document.querySelector('button[value="submit-payment"]').disabled = disabledSubmitButtonMethods.findIndex(function (pm) { + return type.includes(pm); + }) > -1; + document.querySelector("#component_".concat(type)).setAttribute('style', 'display:block'); + // set brand for giftcards if hidden inputfield is present + store.brand = (_document$querySelect2 = document.querySelector("#component_".concat(type, " .brand"))) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value; +} +function displayValidationErrors() { + store.selectedPayment.node.showValidation(); + return false; +} +var selectedMethods = {}; +function doCustomValidation() { + return store.selectedMethod in selectedMethods ? selectedMethods[store.selectedMethod]() : true; +} +function showValidation() { + return store.selectedPaymentIsValid ? doCustomValidation() : displayValidationErrors(); +} +function getInstallmentValues(maxValue) { + var values = []; + for (var i = 1; i <= maxValue; i += 1) { + values.push(i); + } + return values; +} +function createShowConfirmationForm(action) { + if (document.querySelector('#showConfirmationForm')) { + return; + } + var template = document.createElement('template'); + var form = "
            \n \n \n \n \n
            "); + template.innerHTML = form; + document.querySelector('body').appendChild(template.content); +} +module.exports = { + setOrderFormData: setOrderFormData, + assignPaymentMethodValue: assignPaymentMethodValue, + paymentFromComponent: paymentFromComponent, + resetPaymentMethod: resetPaymentMethod, + displaySelectedMethod: displaySelectedMethod, + showValidation: showValidation, + createShowConfirmationForm: createShowConfirmationForm, + getInstallmentValues: getInstallmentValues +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/localesUsingInstallments.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/localesUsingInstallments.js new file mode 100644 index 000000000..5a13c61fb --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/localesUsingInstallments.js @@ -0,0 +1,3 @@ +"use strict"; + +module.exports.installmentLocales = ['pt_BR', 'ja_JP', 'tr_TR', 'es_MX']; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/makePartialPayment.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/makePartialPayment.js new file mode 100644 index 000000000..1a3790f5c --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/makePartialPayment.js @@ -0,0 +1,40 @@ +"use strict"; + +var _excluded = ["giftCards"]; +function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } +var store = require('../../../../store'); +var _require = require('./renderGenericComponent'), + initializeCheckout = _require.initializeCheckout; +var helpers = require('./helpers'); +function makePartialPayment(requestData) { + var error; + $.ajax({ + url: window.partialPaymentUrl, + type: 'POST', + data: JSON.stringify(requestData), + contentType: 'application/json; charset=utf-8', + async: false, + success: function success(response) { + if (response.error) { + error = { + error: true + }; + } else { + var giftCards = response.giftCards, + rest = _objectWithoutProperties(response, _excluded); + store.checkout.options.amount = rest.remainingAmount; + store.adyenOrderData = rest.partialPaymentsOrder; + store.partialPaymentsOrderObj = rest; + sessionStorage.setItem('partialPaymentsObj', JSON.stringify(rest)); + store.addedGiftCards = giftCards; + helpers.setOrderFormData(response); + initializeCheckout(); + } + } + }).fail(function () {}); + return error; +} +module.exports = { + makePartialPayment: makePartialPayment +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/qrCodeMethods.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/qrCodeMethods.js new file mode 100644 index 000000000..cefb5a4e6 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/qrCodeMethods.js @@ -0,0 +1,3 @@ +"use strict"; + +module.exports.qrCodeMethods = ['swish', 'wechatpayQR', 'bcmc_mobile', 'pix']; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js new file mode 100644 index 000000000..4103a3e8b --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js @@ -0,0 +1,339 @@ +"use strict"; + +var _document$getElementB; +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +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); }); }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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 _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 _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 _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +/* eslint-disable no-unsafe-optional-chaining */ +var store = require('../../../../store'); +var _require = require('./renderPaymentMethod'), + renderPaymentMethod = _require.renderPaymentMethod; +var helpers = require('./helpers'); +var _require2 = require('./localesUsingInstallments'), + installmentLocales = _require2.installmentLocales; +var _require3 = require('../commons'), + createSession = _require3.createSession, + fetchGiftCards = _require3.fetchGiftCards; +var constants = require('../constants'); +var _require4 = require('./renderGiftcardComponent'), + createElementsToShowRemainingGiftCardAmount = _require4.createElementsToShowRemainingGiftCardAmount, + removeGiftCards = _require4.removeGiftCards, + renderAddedGiftCard = _require4.renderAddedGiftCard, + showGiftCardWarningMessage = _require4.showGiftCardWarningMessage, + attachGiftCardAddButtonListener = _require4.attachGiftCardAddButtonListener, + showGiftCardInfoMessage = _require4.showGiftCardInfoMessage, + giftCardBrands = _require4.giftCardBrands, + clearGiftCardsContainer = _require4.clearGiftCardsContainer, + attachGiftCardCancelListener = _require4.attachGiftCardCancelListener, + showGiftCardCancelButton = _require4.showGiftCardCancelButton; +var INIT_CHECKOUT_EVENT = 'INIT_CHECKOUT_EVENT'; +function addPosTerminals(terminals) { + var ddTerminals = document.createElement('select'); + ddTerminals.id = 'terminalList'; + Object.keys(terminals).forEach(function (t) { + var option = document.createElement('option'); + option.value = terminals[t]; + option.text = terminals[t]; + ddTerminals.appendChild(option); + }); + document.querySelector('#adyenPosTerminals').append(ddTerminals); +} +function setCheckoutConfiguration(checkoutOptions) { + var setField = function setField(key, val) { + return val && _defineProperty({}, key, val); + }; + store.checkoutConfiguration = _objectSpread(_objectSpread(_objectSpread({}, store.checkoutConfiguration), setField('amount', checkoutOptions.amount)), setField('countryCode', checkoutOptions.countryCode)); +} +function resolveUnmount(key, val) { + try { + return Promise.resolve(val.node.unmount("component_".concat(key))); + } catch (e) { + // try/catch block for val.unmount + return Promise.resolve(false); + } +} + +/** + * To avoid re-rendering components twice, unmounts existing components from payment methods list + */ +function unmountComponents() { + var promises = Object.entries(store.componentsObj).map(function (_ref2) { + var _ref3 = _slicedToArray(_ref2, 2), + key = _ref3[0], + val = _ref3[1]; + delete store.componentsObj[key]; + return resolveUnmount(key, val); + }); + return Promise.all(promises); +} +function isCartModified(amount, orderAmount) { + return amount.currency !== orderAmount.currency || amount.value !== orderAmount.value; +} +function renderGiftCardLogo(imagePath) { + var headingImg = document.querySelector('#headingImg'); + if (headingImg) { + headingImg.src = "".concat(imagePath, "genericgiftcard.png"); + } +} +function applyGiftCards() { + var now = new Date().toISOString(); + var amount = store.checkoutConfiguration.amount; + var orderAmount = store.partialPaymentsOrderObj.orderAmount; + var isPartialPaymentExpired = store.addedGiftCards.some(function (cart) { + return now > cart.expiresAt; + }); + var cartModified = isCartModified(amount, orderAmount); + if (isPartialPaymentExpired) { + removeGiftCards(); + } else if (cartModified) { + removeGiftCards(); + showGiftCardWarningMessage(); + } else { + var _store$addedGiftCards; + clearGiftCardsContainer(); + store.addedGiftCards.forEach(function (card) { + renderAddedGiftCard(card); + }); + if ((_store$addedGiftCards = store.addedGiftCards) !== null && _store$addedGiftCards !== void 0 && _store$addedGiftCards.length) { + showGiftCardInfoMessage(); + } + store.checkout.options.amount = store.addedGiftCards[store.addedGiftCards.length - 1].remainingAmount; + showGiftCardCancelButton(true); + attachGiftCardCancelListener(); + createElementsToShowRemainingGiftCardAmount(); + } +} +function renderStoredPaymentMethod(imagePath) { + return function (pm) { + if (pm.supportedShopperInteractions.includes('Ecommerce')) { + renderPaymentMethod(pm, true, imagePath); + } + }; +} +function renderStoredPaymentMethods(data, imagePath) { + if (data.storedPaymentMethods) { + var storedPaymentMethods = data.storedPaymentMethods; + storedPaymentMethods.forEach(renderStoredPaymentMethod(imagePath)); + } +} +function renderPaymentMethods(paymentMethods, imagePath, adyenDescriptions) { + var promises = []; + for (var i = 0; i < paymentMethods.length; i += 1) { + var pm = paymentMethods[i]; + promises.push(renderPaymentMethod(pm, false, imagePath, adyenDescriptions[pm.type])); + } + return Promise.all(promises); +} +function renderPosTerminals(adyenConnectedTerminals) { + var _adyenConnectedTermin; + var removeChilds = function removeChilds() { + var posTerminals = document.querySelector('#adyenPosTerminals'); + while (posTerminals.firstChild) { + posTerminals.removeChild(posTerminals.firstChild); + } + }; + if (adyenConnectedTerminals !== null && adyenConnectedTerminals !== void 0 && (_adyenConnectedTermin = adyenConnectedTerminals.uniqueTerminalIds) !== null && _adyenConnectedTermin !== void 0 && _adyenConnectedTermin.length) { + removeChilds(); + addPosTerminals(adyenConnectedTerminals.uniqueTerminalIds); + } +} +function setAmazonPayConfig(adyenPaymentMethods) { + var amazonpay = adyenPaymentMethods.paymentMethods.find(function (paymentMethod) { + return paymentMethod.type === 'amazonpay'; + }); + if (amazonpay) { + var _document$querySelect, _document$querySelect2, _document$querySelect3, _document$querySelect4, _document$querySelect5, _document$querySelect6, _document$querySelect7, _document$querySelect8; + store.checkoutConfiguration.paymentMethodsConfiguration.amazonpay.configuration = amazonpay.configuration; + store.checkoutConfiguration.paymentMethodsConfiguration.amazonpay.addressDetails = { + name: "".concat((_document$querySelect = document.querySelector('#shippingFirstNamedefault')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.value, " ").concat((_document$querySelect2 = document.querySelector('#shippingLastNamedefault')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value), + addressLine1: (_document$querySelect3 = document.querySelector('#shippingAddressOnedefault')) === null || _document$querySelect3 === void 0 ? void 0 : _document$querySelect3.value, + city: (_document$querySelect4 = document.querySelector('#shippingAddressCitydefault')) === null || _document$querySelect4 === void 0 ? void 0 : _document$querySelect4.value, + stateOrRegion: (_document$querySelect5 = document.querySelector('#shippingAddressCitydefault')) === null || _document$querySelect5 === void 0 ? void 0 : _document$querySelect5.value, + postalCode: (_document$querySelect6 = document.querySelector('#shippingZipCodedefault')) === null || _document$querySelect6 === void 0 ? void 0 : _document$querySelect6.value, + countryCode: (_document$querySelect7 = document.querySelector('#shippingCountrydefault')) === null || _document$querySelect7 === void 0 ? void 0 : _document$querySelect7.value, + phoneNumber: (_document$querySelect8 = document.querySelector('#shippingPhoneNumberdefault')) === null || _document$querySelect8 === void 0 ? void 0 : _document$querySelect8.value + }; + } +} +function setInstallments(amount) { + try { + var _window$installments; + if (installmentLocales.indexOf(window.Configuration.locale) < 0) { + return; + } + var _window$installments$ = (_window$installments = window.installments) === null || _window$installments === void 0 ? void 0 : _window$installments.replace(/\[|]/g, '').split(','), + _window$installments$2 = _slicedToArray(_window$installments$, 2), + minAmount = _window$installments$2[0], + numOfInstallments = _window$installments$2[1]; + if (minAmount <= amount.value) { + store.checkoutConfiguration.paymentMethodsConfiguration.card.installmentOptions = { + card: {} + }; // eslint-disable-next-line max-len + store.checkoutConfiguration.paymentMethodsConfiguration.card.installmentOptions.card.values = helpers.getInstallmentValues(numOfInstallments); + store.checkoutConfiguration.paymentMethodsConfiguration.card.showInstallmentAmounts = true; + } + } catch (e) {} // eslint-disable-line no-empty +} + +function setGiftCardContainerVisibility() { + var availableGiftCards = giftCardBrands(); + if (availableGiftCards.length === 0) { + var giftCardContainer = document.querySelector('.gift-card-selection'); + giftCardContainer.style.display = 'none'; + var giftCardSeparator = document.querySelector('.gift-card-separator'); + giftCardSeparator.style.display = 'none'; + } +} +function initializeCheckout() { + return _initializeCheckout.apply(this, arguments); +} +function _initializeCheckout() { + _initializeCheckout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var session, giftCardsData, totalDiscountedAmount, giftCards, lastGiftCard, paymentMethodsWithoutGiftCards, firstPaymentMethod; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return createSession(); + case 2: + session = _context2.sent; + _context2.next = 5; + return fetchGiftCards(); + case 5: + giftCardsData = _context2.sent; + store.checkoutConfiguration.session = { + id: session.id, + sessionData: session.sessionData, + imagePath: session.imagePath, + adyenDescriptions: session.adyenDescriptions + }; + _context2.next = 9; + return AdyenCheckout(store.checkoutConfiguration); + case 9: + store.checkout = _context2.sent; + setGiftCardContainerVisibility(); + totalDiscountedAmount = giftCardsData.totalDiscountedAmount, giftCards = giftCardsData.giftCards; + if (giftCards !== null && giftCards !== void 0 && giftCards.length) { + store.addedGiftCards = giftCards; + lastGiftCard = store.addedGiftCards[store.addedGiftCards.length - 1]; + store.partialPaymentsOrderObj = _objectSpread(_objectSpread({}, lastGiftCard), {}, { + totalDiscountedAmount: totalDiscountedAmount + }); + } + setCheckoutConfiguration(store.checkout.options); + setInstallments(store.checkout.options.amount); + setAmazonPayConfig(store.checkout.paymentMethodsResponse); + document.querySelector('#paymentMethodsList').innerHTML = ''; + paymentMethodsWithoutGiftCards = store.checkout.paymentMethodsResponse.paymentMethods.filter(function (pm) { + return pm.type !== constants.GIFTCARD; + }); + renderStoredPaymentMethods(paymentMethodsWithoutGiftCards, session.imagePath); + _context2.next = 21; + return renderPaymentMethods(paymentMethodsWithoutGiftCards, session.imagePath, session.adyenDescriptions); + case 21: + renderPosTerminals(session.adyenConnectedTerminals); + renderGiftCardLogo(session.imagePath); + firstPaymentMethod = document.querySelector('input[type=radio][name=brandCode]'); + if (firstPaymentMethod) { + firstPaymentMethod.checked = true; + helpers.displaySelectedMethod(firstPaymentMethod.value); + } + helpers.createShowConfirmationForm(window.ShowConfirmationPaymentFromComponent); + case 26: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _initializeCheckout.apply(this, arguments); +} +(_document$getElementB = document.getElementById('email')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.addEventListener('change', function (e) { + var emailPattern = /^[\w.%+-]+@[\w.-]+\.[\w]{2,6}$/; + if (emailPattern.test(e.target.value)) { + var paymentMethodsConfiguration = store.checkoutConfiguration.paymentMethodsConfiguration; + paymentMethodsConfiguration.card.clickToPayConfiguration.shopperEmail = e.target.value; + var event = new Event(INIT_CHECKOUT_EVENT); + document.dispatchEvent(event); + } +}); + +// used by renderGiftCardComponent.js +document.addEventListener(INIT_CHECKOUT_EVENT, function () { + var handleCheckoutEvent = /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(Object.keys(store.componentsObj).length !== 0)) { + _context.next = 3; + break; + } + _context.next = 3; + return unmountComponents(); + case 3: + _context.next = 5; + return initializeCheckout(); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function handleCheckoutEvent() { + return _ref4.apply(this, arguments); + }; + }(); + handleCheckoutEvent(); +}); + +/** + * Calls createSession and then renders the retrieved payment methods (including card component) + */ +function renderGenericComponent() { + return _renderGenericComponent.apply(this, arguments); +} +function _renderGenericComponent() { + _renderGenericComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + var _store$addedGiftCards2; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!(Object.keys(store.componentsObj).length !== 0)) { + _context3.next = 3; + break; + } + _context3.next = 3; + return unmountComponents(); + case 3: + _context3.next = 5; + return initializeCheckout(); + case 5: + if ((_store$addedGiftCards2 = store.addedGiftCards) !== null && _store$addedGiftCards2 !== void 0 && _store$addedGiftCards2.length) { + applyGiftCards(); + } + attachGiftCardAddButtonListener(); + case 7: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _renderGenericComponent.apply(this, arguments); +} +module.exports = { + renderGenericComponent: renderGenericComponent, + initializeCheckout: initializeCheckout, + INIT_CHECKOUT_EVENT: INIT_CHECKOUT_EVENT +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGiftcardComponent.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGiftcardComponent.js new file mode 100644 index 000000000..1b670bebc --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGiftcardComponent.js @@ -0,0 +1,355 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var store = require('../../../../store'); +var constants = require('../constants'); +var _require = require('./renderGenericComponent'), + INIT_CHECKOUT_EVENT = _require.INIT_CHECKOUT_EVENT; +function getGiftCardElements() { + var giftCardSelect = document.querySelector('#giftCardSelect'); + var giftCardUl = document.querySelector('#giftCardUl'); + var giftCardContainer = document.querySelector('#giftCardContainer'); + var giftCardAddButton = document.querySelector('#giftCardAddButton'); + var giftCardCancelContainer = document.querySelector('#giftCardsCancelContainer'); + var giftCardCancelButton = document.querySelector('#giftCardCancelButton'); + var giftCardSelectContainer = document.querySelector('#giftCardSelectContainer'); + var giftCardSelectWrapper = document.querySelector('#giftCardSelectWrapper'); + var giftCardsList = document.querySelector('#giftCardsList'); + var giftCardsInfoMessageContainer = document.querySelector('#giftCardsInfoMessage'); + var cancelMainPaymentGiftCard = document.querySelector('#cancelGiftCardButton'); + var giftCardInformation = document.querySelector('#giftCardInformation'); + return { + giftCardSelect: giftCardSelect, + giftCardUl: giftCardUl, + giftCardContainer: giftCardContainer, + giftCardAddButton: giftCardAddButton, + giftCardSelectContainer: giftCardSelectContainer, + giftCardsList: giftCardsList, + giftCardsInfoMessageContainer: giftCardsInfoMessageContainer, + giftCardSelectWrapper: giftCardSelectWrapper, + giftCardCancelContainer: giftCardCancelContainer, + giftCardCancelButton: giftCardCancelButton, + cancelMainPaymentGiftCard: cancelMainPaymentGiftCard, + giftCardInformation: giftCardInformation + }; +} +function showGiftCardCancelButton(show) { + var _getGiftCardElements = getGiftCardElements(), + giftCardCancelContainer = _getGiftCardElements.giftCardCancelContainer; + if (show) { + giftCardCancelContainer.classList.remove('invisible'); + } else { + giftCardCancelContainer.classList.add('invisible'); + } +} +function removeGiftCards() { + var _store$addedGiftCards; + (_store$addedGiftCards = store.addedGiftCards) === null || _store$addedGiftCards === void 0 ? void 0 : _store$addedGiftCards.forEach(function (card) { + $.ajax({ + type: 'POST', + url: window.cancelPartialPaymentOrderUrl, + data: JSON.stringify(card), + contentType: 'application/json; charset=utf-8', + async: false, + success: function success(res) { + var adyenPartialPaymentsOrder = document.querySelector('#adyenPartialPaymentsOrder'); + var _getGiftCardElements2 = getGiftCardElements(), + giftCardsList = _getGiftCardElements2.giftCardsList, + giftCardAddButton = _getGiftCardElements2.giftCardAddButton, + giftCardSelect = _getGiftCardElements2.giftCardSelect, + giftCardUl = _getGiftCardElements2.giftCardUl, + giftCardsInfoMessageContainer = _getGiftCardElements2.giftCardsInfoMessageContainer, + giftCardSelectContainer = _getGiftCardElements2.giftCardSelectContainer, + cancelMainPaymentGiftCard = _getGiftCardElements2.cancelMainPaymentGiftCard, + giftCardInformation = _getGiftCardElements2.giftCardInformation; + adyenPartialPaymentsOrder.value = null; + giftCardsList.innerHTML = ''; + giftCardAddButton.style.display = 'block'; + giftCardSelect.value = null; + giftCardSelectContainer.classList.add('invisible'); + giftCardSelect.classList.remove('invisible'); + giftCardUl.innerHTML = ''; + cancelMainPaymentGiftCard.classList.add('invisible'); + showGiftCardCancelButton(false); + giftCardInformation === null || giftCardInformation === void 0 ? void 0 : giftCardInformation.remove(); + store.checkout.options.amount = res.amount; + store.partialPaymentsOrderObj = null; + store.addedGiftCards = null; + store.adyenOrderData = null; + giftCardsInfoMessageContainer.innerHTML = ''; + giftCardsInfoMessageContainer.classList.remove('gift-cards-info-message-container'); + document.querySelector('button[value="submit-payment"]').disabled = false; + if (res.resultCode === constants.RECEIVED) { + var _document$querySelect, _store$componentsObj, _store$componentsObj$; + (_document$querySelect = document.querySelector('#cancelGiftCardContainer')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.parentNode.remove(); + (_store$componentsObj = store.componentsObj) === null || _store$componentsObj === void 0 ? void 0 : (_store$componentsObj$ = _store$componentsObj.giftcard) === null || _store$componentsObj$ === void 0 ? void 0 : _store$componentsObj$.node.unmount('component_giftcard'); + } + var event = new Event(INIT_CHECKOUT_EVENT); + document.dispatchEvent(event); + } + }); + }); +} +function giftCardBrands() { + var paymentMethodsResponse = store.checkout.paymentMethodsResponse; + return paymentMethodsResponse.paymentMethods.filter(function (pm) { + return pm.type === constants.GIFTCARD; + }); +} +function renderGiftCardSelectForm() { + var _getGiftCardElements3 = getGiftCardElements(), + giftCardUl = _getGiftCardElements3.giftCardUl, + giftCardSelect = _getGiftCardElements3.giftCardSelect; + if (giftCardUl !== null && giftCardUl !== void 0 && giftCardUl.innerHTML) { + giftCardSelect.classList.remove('invisible'); + return; + } + var imagePath = store.checkoutConfiguration.session.imagePath; + giftCardBrands().forEach(function (giftCard) { + var newListItem = document.createElement('li'); + newListItem.setAttribute('data-brand', giftCard.brand); + newListItem.setAttribute('data-name', giftCard.name); + newListItem.setAttribute('data-type', giftCard.type); + var span = document.createElement('span'); + span.textContent = giftCard.name; + var img = document.createElement('img'); + img.src = "".concat(imagePath).concat(giftCard.brand, ".png"); + img.width = 40; + img.height = 26; + newListItem.appendChild(span); + newListItem.appendChild(img); + giftCardUl.appendChild(newListItem); + }); +} +function attachGiftCardFormListeners() { + if (store.giftCardComponentListenersAdded) { + return; + } + var _getGiftCardElements4 = getGiftCardElements(), + giftCardUl = _getGiftCardElements4.giftCardUl, + giftCardSelect = _getGiftCardElements4.giftCardSelect, + giftCardContainer = _getGiftCardElements4.giftCardContainer, + giftCardSelectWrapper = _getGiftCardElements4.giftCardSelectWrapper; + if (giftCardUl) { + giftCardUl.addEventListener('click', function (event) { + var _store$componentsObj2; + giftCardUl.classList.toggle('invisible'); + var selectedGiftCard = { + name: event.target.dataset.name, + brand: event.target.dataset.brand, + type: event.target.dataset.type + }; + if ((_store$componentsObj2 = store.componentsObj) !== null && _store$componentsObj2 !== void 0 && _store$componentsObj2.giftcard) { + store.componentsObj.giftcard.node.unmount('component_giftcard'); + } + if (!store.partialPaymentsOrderObj) { + store.partialPaymentsOrderObj = {}; + } + var newOption = document.createElement('option'); + newOption.textContent = selectedGiftCard.name; + newOption.value = selectedGiftCard.brand; + newOption.style.visibility = 'hidden'; + giftCardSelect.appendChild(newOption); + giftCardSelect.value = selectedGiftCard.brand; + giftCardContainer.innerHTML = ''; + var giftCardNode = store.checkout.create(constants.GIFTCARD, _objectSpread(_objectSpread({}, store.checkoutConfiguration.giftcard), {}, { + brand: selectedGiftCard.brand, + name: selectedGiftCard.name + })).mount(giftCardContainer); + store.componentsObj.giftcard = { + node: giftCardNode + }; + }); + } + if (giftCardSelect) { + giftCardSelectWrapper.addEventListener('mousedown', function () { + giftCardUl.classList.toggle('invisible'); + }); + } + store.giftCardComponentListenersAdded = true; +} +function showGiftCardWarningMessage() { + var alertContainer = document.createElement('div'); + alertContainer.setAttribute('id', 'giftCardWarningMessage'); + alertContainer.classList.add('alert', 'alert-warning', 'error-message', 'gift-card-warning-msg'); + alertContainer.setAttribute('role', 'alert'); + var alertContainerP = document.createElement('p'); + alertContainerP.classList.add('error-message-text'); + alertContainerP.textContent = window.giftCardWarningMessage; + alertContainer.appendChild(alertContainerP); + var orderTotalSummaryEl = document.querySelector('.card-body.order-total-summary'); + orderTotalSummaryEl === null || orderTotalSummaryEl === void 0 ? void 0 : orderTotalSummaryEl.appendChild(alertContainer); +} +function attachGiftCardAddButtonListener() { + var _getGiftCardElements5 = getGiftCardElements(), + giftCardAddButton = _getGiftCardElements5.giftCardAddButton, + giftCardSelectContainer = _getGiftCardElements5.giftCardSelectContainer, + giftCardSelectWrapper = _getGiftCardElements5.giftCardSelectWrapper, + giftCardSelect = _getGiftCardElements5.giftCardSelect; + if (giftCardAddButton) { + giftCardAddButton.addEventListener('click', function () { + renderGiftCardSelectForm(); + attachGiftCardFormListeners(); + var giftCardWarningMessageEl = document.querySelector('#giftCardWarningMessage'); + if (giftCardWarningMessageEl) { + giftCardWarningMessageEl.style.display = 'none'; + } + giftCardSelect.value = 'null'; + giftCardAddButton.style.display = 'none'; + giftCardSelectContainer.classList.remove('invisible'); + giftCardSelectWrapper.classList.remove('invisible'); + }); + } +} +function attachGiftCardCancelListener() { + var _getGiftCardElements6 = getGiftCardElements(), + giftCardCancelButton = _getGiftCardElements6.giftCardCancelButton; + giftCardCancelButton === null || giftCardCancelButton === void 0 ? void 0 : giftCardCancelButton.addEventListener('click', function () { + removeGiftCards(); + }); +} +function removeGiftCardFormListeners() { + var _getGiftCardElements7 = getGiftCardElements(), + giftCardUl = _getGiftCardElements7.giftCardUl, + giftCardSelect = _getGiftCardElements7.giftCardSelect; + giftCardUl.replaceWith(giftCardUl.cloneNode(true)); + giftCardSelect.replaceWith(giftCardSelect.cloneNode(true)); + store.giftCardComponentListenersAdded = false; +} +function clearGiftCardsContainer() { + var _getGiftCardElements8 = getGiftCardElements(), + giftCardsList = _getGiftCardElements8.giftCardsList; + giftCardsList.innerHTML = ''; +} +function renderAddedGiftCard(card) { + var giftCardData = card.giftCard; + var imagePath = store.checkoutConfiguration.session.imagePath; + var _getGiftCardElements9 = getGiftCardElements(), + giftCardsList = _getGiftCardElements9.giftCardsList, + giftCardAddButton = _getGiftCardElements9.giftCardAddButton; + var giftCardDiv = document.createElement('div'); + giftCardDiv.classList.add('gift-card'); + var brandContainer = document.createElement('div'); + brandContainer.classList.add('brand-container'); + var giftCardImg = document.createElement('img'); + var giftCardImgSrc = "".concat(imagePath).concat(giftCardData.brand, ".png"); + giftCardImg.setAttribute('src', giftCardImgSrc); + giftCardImg.classList.add('gift-card-logo'); + var giftCardNameP = document.createElement('p'); + giftCardNameP.textContent = giftCardData.name; + brandContainer.appendChild(giftCardImg); + brandContainer.appendChild(giftCardNameP); + var giftCardAction = document.createElement('div'); + giftCardAction.classList.add('gift-card-action'); + var brandAndRemoveActionWrapper = document.createElement('div'); + brandAndRemoveActionWrapper.classList.add('wrapper'); + brandAndRemoveActionWrapper.appendChild(brandContainer); + brandAndRemoveActionWrapper.appendChild(giftCardAction); + var giftCardAmountDiv = document.createElement('div'); + giftCardAmountDiv.classList.add('wrapper'); + var amountLabel = document.createElement('p'); + amountLabel.textContent = window.deductedBalanceGiftCardResource; + var amountValue = document.createElement('strong'); + amountValue.textContent = card.discountedAmount ? "-".concat(card.discountedAmount) : ''; + giftCardAmountDiv.appendChild(amountLabel); + giftCardAmountDiv.appendChild(amountValue); + giftCardDiv.appendChild(brandAndRemoveActionWrapper); + giftCardDiv.appendChild(giftCardAmountDiv); + giftCardsList.appendChild(giftCardDiv); + giftCardAddButton.style.display = 'block'; + removeGiftCardFormListeners(); +} +function createElementsToShowRemainingGiftCardAmount() { + var renderedRemainingAmountEndSpan = document.getElementById('remainingAmountEndSpan'); + var renderedDiscountedAmountEndSpan = document.getElementById('discountedAmountEndSpan'); + if (renderedRemainingAmountEndSpan && renderedDiscountedAmountEndSpan) { + renderedRemainingAmountEndSpan.innerText = store.partialPaymentsOrderObj.remainingAmountFormatted; + renderedDiscountedAmountEndSpan.innerText = store.partialPaymentsOrderObj.totalDiscountedAmount; + return; + } + var mainContainer = document.createElement('div'); + var remainingAmountContainer = document.createElement('div'); + var remainingAmountStart = document.createElement('div'); + var remainingAmountEnd = document.createElement('div'); + var discountedAmountContainer = document.createElement('div'); + var discountedAmountStart = document.createElement('div'); + var discountedAmountEnd = document.createElement('div'); + var remainingAmountStartP = document.createElement('p'); + var remainingAmountEndP = document.createElement('p'); + var discountedAmountStartP = document.createElement('p'); + var discountedAmountEndP = document.createElement('p'); + var remainingAmountStartSpan = document.createElement('span'); + var discountedAmountStartSpan = document.createElement('span'); + var remainingAmountEndSpan = document.createElement('span'); + remainingAmountEndSpan.id = 'remainingAmountEndSpan'; + var discountedAmountEndSpan = document.createElement('span'); + discountedAmountEndSpan.id = 'discountedAmountEndSpan'; + remainingAmountContainer.classList.add('row', 'grand-total', 'leading-lines'); + remainingAmountStart.classList.add('col-6', 'start-lines'); + remainingAmountEnd.classList.add('col-6', 'end-lines'); + remainingAmountStartP.classList.add('order-receipt-label'); + discountedAmountContainer.classList.add('row', 'grand-total', 'leading-lines'); + discountedAmountStart.classList.add('col-6', 'start-lines'); + discountedAmountEnd.classList.add('col-6', 'end-lines'); + discountedAmountStartP.classList.add('order-receipt-label'); + remainingAmountEndP.classList.add('text-right'); + discountedAmountEndP.classList.add('text-right'); + discountedAmountContainer.id = 'discountedAmountContainer'; + remainingAmountContainer.id = 'remainingAmountContainer'; + remainingAmountStartSpan.innerText = window.remainingAmountGiftCardResource; + discountedAmountStartSpan.innerText = window.discountedAmountGiftCardResource; + remainingAmountEndSpan.innerText = store.partialPaymentsOrderObj.remainingAmountFormatted; + discountedAmountEndSpan.innerText = store.partialPaymentsOrderObj.totalDiscountedAmount; + remainingAmountContainer.appendChild(remainingAmountStart); + remainingAmountContainer.appendChild(remainingAmountEnd); + remainingAmountStart.appendChild(remainingAmountStartP); + discountedAmountContainer.appendChild(discountedAmountStart); + discountedAmountContainer.appendChild(discountedAmountEnd); + discountedAmountStart.appendChild(discountedAmountStartP); + remainingAmountEnd.appendChild(remainingAmountEndP); + remainingAmountStartP.appendChild(remainingAmountStartSpan); + discountedAmountEnd.appendChild(discountedAmountEndP); + discountedAmountStartP.appendChild(discountedAmountStartSpan); + remainingAmountEndP.appendChild(remainingAmountEndSpan); + discountedAmountEndP.appendChild(discountedAmountEndSpan); + var pricingContainer = document.querySelector('.card-body.order-total-summary'); + mainContainer.id = 'giftCardInformation'; + mainContainer.appendChild(discountedAmountContainer); + mainContainer.appendChild(remainingAmountContainer); + pricingContainer.appendChild(mainContainer); +} +function showGiftCardInfoMessage() { + var messageText = store.partialPaymentsOrderObj.message; + var _getGiftCardElements10 = getGiftCardElements(), + giftCardsInfoMessageContainer = _getGiftCardElements10.giftCardsInfoMessageContainer; + giftCardsInfoMessageContainer.innerHTML = ''; + giftCardsInfoMessageContainer.classList.remove('gift-cards-info-message-container'); + if (!messageText) return; + var giftCardsInfoMessage = document.createElement('div'); + giftCardsInfoMessage.classList.add('adyen-checkout__alert-message', 'adyen-checkout__alert-message--warning'); + giftCardsInfoMessage.setAttribute('role', 'alert'); + var infoMessage = document.createElement('span'); + infoMessage.textContent = messageText; + giftCardsInfoMessage.appendChild(infoMessage); + giftCardsInfoMessageContainer.appendChild(giftCardsInfoMessage); + giftCardsInfoMessageContainer.classList.add('gift-cards-info-message-container'); +} +module.exports = { + removeGiftCards: removeGiftCards, + renderAddedGiftCard: renderAddedGiftCard, + attachGiftCardAddButtonListener: attachGiftCardAddButtonListener, + getGiftCardElements: getGiftCardElements, + showGiftCardWarningMessage: showGiftCardWarningMessage, + createElementsToShowRemainingGiftCardAmount: createElementsToShowRemainingGiftCardAmount, + renderGiftCardSelectForm: renderGiftCardSelectForm, + showGiftCardInfoMessage: showGiftCardInfoMessage, + giftCardBrands: giftCardBrands, + clearGiftCardsContainer: clearGiftCardsContainer, + attachGiftCardCancelListener: attachGiftCardCancelListener, + showGiftCardCancelButton: showGiftCardCancelButton +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderPaymentMethod.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderPaymentMethod.js new file mode 100644 index 000000000..ee62bd8be --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderPaymentMethod.js @@ -0,0 +1,290 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +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); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var store = require('../../../../store'); +var helpers = require('./helpers'); +var constants = require('../constants'); +function getFallback(paymentMethod) { + var fallback = {}; + if (fallback[paymentMethod.type]) { + store.componentsObj[paymentMethod.type] = {}; + } + return fallback[paymentMethod.type]; +} +function getPersonalDetails() { + var _document$querySelect, _document$querySelect2, _document$querySelect3, _document$querySelect4; + return { + firstName: (_document$querySelect = document.querySelector('#shippingFirstNamedefault')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.value, + lastName: (_document$querySelect2 = document.querySelector('#shippingLastNamedefault')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value, + telephoneNumber: (_document$querySelect3 = document.querySelector('#shippingPhoneNumberdefault')) === null || _document$querySelect3 === void 0 ? void 0 : _document$querySelect3.value, + shopperEmail: (_document$querySelect4 = document.querySelector('.customer-summary-email')) === null || _document$querySelect4 === void 0 ? void 0 : _document$querySelect4.textContent + }; +} +function setNode(paymentMethodID) { + var createNode = function createNode() { + if (!store.componentsObj[paymentMethodID]) { + store.componentsObj[paymentMethodID] = {}; + } + try { + var _store$checkout; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + // ALl nodes created for the checkout component are enriched with shopper personal details + var node = (_store$checkout = store.checkout).create.apply(_store$checkout, args.concat([{ + data: _objectSpread(_objectSpread({}, getPersonalDetails()), {}, { + personalDetails: getPersonalDetails() + }), + visibility: { + personalDetails: 'editable', + billingAddress: 'hidden', + deliveryAddress: 'hidden' + } + }])); + store.componentsObj[paymentMethodID].node = node; + store.componentsObj[paymentMethodID].isValid = node.isValid; + } catch (e) { + /* No component for payment method */ + } + }; + return createNode; +} +function getPaymentMethodID(isStored, paymentMethod) { + if (isStored) { + return "storedCard".concat(paymentMethod.id); + } + if (paymentMethod.type === constants.GIFTCARD) { + return constants.GIFTCARD; + } + if (paymentMethod.brand) { + return "".concat(paymentMethod.type, "_").concat(paymentMethod.brand); + } + return paymentMethod.type; +} +function getImage(isStored, paymentMethod) { + return isStored ? paymentMethod.brand : paymentMethod.type; +} +function getLabel(isStored, paymentMethod) { + var label = isStored ? " ".concat(store.MASKED_CC_PREFIX).concat(paymentMethod.lastFour) : ''; + return "".concat(paymentMethod.name).concat(label); +} +function handleFallbackPayment(_ref) { + var paymentMethod = _ref.paymentMethod, + container = _ref.container, + paymentMethodID = _ref.paymentMethodID; + var fallback = getFallback(paymentMethod); + var createTemplate = function createTemplate() { + var template = document.createElement('template'); + template.innerHTML = fallback; + container.append(template.content); + }; + return fallback ? createTemplate() : setNode(paymentMethod.type)(paymentMethodID); +} +function handlePayment(options) { + return options.isStored ? setNode(options.paymentMethodID)('card', options.paymentMethod) : handleFallbackPayment(options); +} +function getListContents(_ref2) { + var imagePath = _ref2.imagePath, + isStored = _ref2.isStored, + paymentMethod = _ref2.paymentMethod, + description = _ref2.description; + var paymentMethodID = getPaymentMethodID(isStored, paymentMethod); + var label = getLabel(isStored, paymentMethod); + var liContents = "\n \n \n \n "); + return description ? "".concat(liContents, "

            ").concat(description, "

            ") : liContents; +} +function getImagePath(_ref3) { + var isStored = _ref3.isStored, + paymentMethod = _ref3.paymentMethod, + path = _ref3.path, + isSchemeNotStored = _ref3.isSchemeNotStored; + var paymentMethodImage = "".concat(path).concat(getImage(isStored, paymentMethod), ".png"); + var cardImage = "".concat(path, "card.png"); + return isSchemeNotStored ? cardImage : paymentMethodImage; +} +function setValid(_ref4) { + var isStored = _ref4.isStored, + paymentMethodID = _ref4.paymentMethodID; + if (isStored && ['bcmc', 'scheme'].indexOf(paymentMethodID) > -1) { + store.componentsObj[paymentMethodID].isValid = true; + } +} +function configureContainer(_ref5) { + var paymentMethodID = _ref5.paymentMethodID, + container = _ref5.container; + container.classList.add('additionalFields'); + container.setAttribute('id', "component_".concat(paymentMethodID)); + container.setAttribute('style', 'display:none'); +} +function handleInput(_ref6) { + var paymentMethodID = _ref6.paymentMethodID; + var input = document.querySelector("#rb_".concat(paymentMethodID)); + input.onchange = /*#__PURE__*/function () { + var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(event) { + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + helpers.displaySelectedMethod(event.target.value); + case 1: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref7.apply(this, arguments); + }; + }(); +} +function createListItem(rerender, paymentMethodID, liContents) { + var li; + if (rerender) { + li = document.querySelector("#rb_".concat(paymentMethodID)).closest('li'); + } else { + li = document.createElement('li'); + li.innerHTML = liContents; + li.classList.add('paymentMethod'); + } + return li; +} +function checkIfNodeIsAvailable(_x2) { + return _checkIfNodeIsAvailable.apply(this, arguments); +} +function _checkIfNodeIsAvailable() { + _checkIfNodeIsAvailable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(node) { + var isNodeAvailable; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!node.isAvailable) { + _context3.next = 6; + break; + } + _context3.next = 3; + return node.isAvailable(); + case 3: + isNodeAvailable = _context3.sent; + if (isNodeAvailable) { + _context3.next = 6; + break; + } + return _context3.abrupt("return", false); + case 6: + return _context3.abrupt("return", true); + case 7: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _checkIfNodeIsAvailable.apply(this, arguments); +} +function appendNodeToContainerIfAvailable(_x3, _x4, _x5, _x6) { + return _appendNodeToContainerIfAvailable.apply(this, arguments); +} +function _appendNodeToContainerIfAvailable() { + _appendNodeToContainerIfAvailable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(paymentMethodsUI, li, node, container) { + var canBeMounted; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!node) { + _context4.next = 5; + break; + } + _context4.next = 3; + return checkIfNodeIsAvailable(node); + case 3: + canBeMounted = _context4.sent; + if (canBeMounted) { + paymentMethodsUI.append(li); + node.mount(container); + } + case 5: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _appendNodeToContainerIfAvailable.apply(this, arguments); +} +module.exports.renderPaymentMethod = /*#__PURE__*/function () { + var _renderPaymentMethod = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(paymentMethod, isStored, path) { + var description, + rerender, + _store$componentsObj$, + paymentMethodsUI, + paymentMethodID, + isSchemeNotStored, + container, + options, + imagePath, + liContents, + li, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + description = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : null; + rerender = _args2.length > 4 && _args2[4] !== undefined ? _args2[4] : false; + _context2.prev = 2; + paymentMethodsUI = document.querySelector('#paymentMethodsList'); + paymentMethodID = getPaymentMethodID(isStored, paymentMethod); + if (!(paymentMethodID === constants.GIFTCARD)) { + _context2.next = 7; + break; + } + return _context2.abrupt("return"); + case 7: + isSchemeNotStored = paymentMethod.type === 'scheme' && !isStored; + container = document.createElement('div'); + options = { + container: container, + paymentMethod: paymentMethod, + isStored: isStored, + path: path, + description: description, + paymentMethodID: paymentMethodID, + isSchemeNotStored: isSchemeNotStored + }; + imagePath = getImagePath(options); + liContents = getListContents(_objectSpread(_objectSpread({}, options), {}, { + imagePath: imagePath, + description: description + })); + li = createListItem(rerender, paymentMethodID, liContents); + handlePayment(options); + configureContainer(options); + li.append(container); + _context2.next = 18; + return appendNodeToContainerIfAvailable(paymentMethodsUI, li, (_store$componentsObj$ = store.componentsObj[paymentMethodID]) === null || _store$componentsObj$ === void 0 ? void 0 : _store$componentsObj$.node, container); + case 18: + if (paymentMethodID === constants.GIROPAY) { + container.innerHTML = ''; + } + handleInput(options); + setValid(options); + _context2.next = 25; + break; + case 23: + _context2.prev = 23; + _context2.t0 = _context2["catch"](2); + case 25: + case "end": + return _context2.stop(); + } + }, _callee2, null, [[2, 23]]); + })); + function renderPaymentMethod(_x7, _x8, _x9) { + return _renderPaymentMethod.apply(this, arguments); + } + return renderPaymentMethod; +}(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/validateComponents.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/validateComponents.js new file mode 100644 index 000000000..8f65853c4 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/validateComponents.js @@ -0,0 +1,13 @@ +"use strict"; + +var store = require('../../../../store'); +module.exports.validateComponents = function validateComponents() { + var customMethods = {}; + if (store.selectedMethod in customMethods) { + customMethods[store.selectedMethod](); + } + document.querySelector('#adyenStateData').value = JSON.stringify(store.stateData); + if (store.partialPaymentsOrderObj) { + document.querySelector('#adyenPartialPaymentsOrder').value = JSON.stringify(store.partialPaymentsOrderObj); + } +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayCheckout.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayCheckout.js new file mode 100644 index 000000000..cbd636c51 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayCheckout.js @@ -0,0 +1,143 @@ +"use strict"; + +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _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); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var store = require('../../../store'); +var helpers = require('./adyen_checkout/helpers'); +function handleAuthorised(response) { + var _response$fullRespons, _response$fullRespons2, _response$fullRespons3, _response$fullRespons4, _response$fullRespons5; + document.querySelector('#result').value = JSON.stringify({ + pspReference: (_response$fullRespons = response.fullResponse) === null || _response$fullRespons === void 0 ? void 0 : _response$fullRespons.pspReference, + resultCode: (_response$fullRespons2 = response.fullResponse) === null || _response$fullRespons2 === void 0 ? void 0 : _response$fullRespons2.resultCode, + paymentMethod: (_response$fullRespons3 = response.fullResponse) !== null && _response$fullRespons3 !== void 0 && _response$fullRespons3.paymentMethod ? response.fullResponse.paymentMethod : (_response$fullRespons4 = response.fullResponse) === null || _response$fullRespons4 === void 0 ? void 0 : (_response$fullRespons5 = _response$fullRespons4.additionalData) === null || _response$fullRespons5 === void 0 ? void 0 : _response$fullRespons5.paymentMethod + }); + document.querySelector('#showConfirmationForm').submit(); +} +function handleError() { + document.querySelector('#result').value = JSON.stringify({ + error: true + }); + document.querySelector('#showConfirmationForm').submit(); +} +function handleAmazonResponse(response, component) { + var _response$fullRespons6; + if ((_response$fullRespons6 = response.fullResponse) !== null && _response$fullRespons6 !== void 0 && _response$fullRespons6.action) { + component.handleAction(response.fullResponse.action); + } else if (response.resultCode === window.resultCodeAuthorised) { + handleAuthorised(response); + } else { + // first try the amazon decline flow + component.handleDeclineFlow(); + // if this does not trigger a redirect, try the regular handleError flow + handleError(); + } +} +function paymentFromComponent(data, component) { + var partialPaymentsOrder = sessionStorage.getItem('partialPaymentsObj'); + var requestData = partialPaymentsOrder ? _objectSpread(_objectSpread({}, data), {}, { + partialPaymentsOrder: JSON.parse(partialPaymentsOrder) + }) : data; + $.ajax({ + url: window.paymentFromComponentURL, + type: 'post', + data: { + data: JSON.stringify(requestData), + paymentMethod: 'amazonpay', + merchantReference: document.querySelector('#merchantReference').value, + orderToken: document.querySelector('#orderToken').value + }, + success: function success(response) { + sessionStorage.removeItem('partialPaymentsObj'); + helpers.setOrderFormData(response); + handleAmazonResponse(response, component); + } + }); +} +function mountAmazonPayComponent() { + return _mountAmazonPayComponent.apply(this, arguments); +} +function _mountAmazonPayComponent() { + _mountAmazonPayComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var amazonPayNode, checkout, amazonConfig, amazonPayComponent; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + amazonPayNode = document.getElementById('amazon-container'); + _context.next = 3; + return AdyenCheckout(window.Configuration); + case 3: + checkout = _context.sent; + amazonConfig = { + showOrderButton: false, + returnUrl: window.returnURL, + configuration: { + merchantId: window.amazonMerchantID, + storeId: window.amazonStoreID, + publicKeyId: window.amazonPublicKeyID + }, + amazonCheckoutSessionId: window.amazonCheckoutSessionId, + onSubmit: function onSubmit(state, component) { + document.querySelector('#adyenStateData').value = JSON.stringify(state.data); + document.querySelector('#additionalDetailsHidden').value = JSON.stringify(state.data); + paymentFromComponent(state.data, component); + }, + onAdditionalDetails: function onAdditionalDetails(state) { + state.data.paymentMethod = 'amazonpay'; + $.ajax({ + type: 'post', + url: window.paymentsDetailsURL, + data: JSON.stringify({ + data: state.data, + orderToken: window.orderToken + }), + contentType: 'application/json; charset=utf-8', + success: function success(data) { + if (data.isSuccessful) { + handleAuthorised(data); + } else if (!data.isFinal && _typeof(data.action) === 'object') { + checkout.createFromAction(data.action).mount('#amazon-container'); + } else { + $('#action-modal').modal('hide'); + handleError(); + } + } + }); + } + }; + amazonPayComponent = checkout.create('amazonpay', amazonConfig).mount(amazonPayNode); + helpers.createShowConfirmationForm(window.ShowConfirmationPaymentFromComponent); + $('#dwfrm_billing').submit(function apiRequest(e) { + e.preventDefault(); + var form = $(this); + var url = form.attr('action'); + $.ajax({ + type: 'POST', + url: url, + data: form.serialize(), + async: false, + success: function success(data) { + store.formErrorsExist = 'fieldErrors' in data; + } + }); + }); + $('#action-modal').modal({ + backdrop: 'static', + keyboard: false + }); + amazonPayComponent.submit(); + case 10: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _mountAmazonPayComponent.apply(this, arguments); +} +mountAmazonPayComponent(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart1.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart1.js new file mode 100644 index 000000000..cd0a69323 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart1.js @@ -0,0 +1,86 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +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); }); }; } +var _require = require('./commons'), + checkIfExpressMethodsAreReady = _require.checkIfExpressMethodsAreReady, + updateLoadedExpressMethods = _require.updateLoadedExpressMethods; +var AMAZON_PAY = 'amazonpay'; +function mountAmazonPayComponent() { + return _mountAmazonPayComponent.apply(this, arguments); +} +function _mountAmazonPayComponent() { + _mountAmazonPayComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var getPaymentMethods; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + getPaymentMethods = function _getPaymentMethods(paymentMethods) { + $.ajax({ + url: window.getPaymentMethodsURL, + type: 'get', + success: function success(data) { + paymentMethods(data); + }, + error: function error() { + updateLoadedExpressMethods(AMAZON_PAY); + checkIfExpressMethodsAreReady(); + } + }); + }; + getPaymentMethods( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(data) { + var _paymentMethodsRespon; + var paymentMethodsResponse, checkout, amazonPayConfig, amazonPayButtonConfig, amazonPayButton; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + paymentMethodsResponse = data.AdyenPaymentMethods; + _context.next = 3; + return AdyenCheckout({ + environment: window.environment, + clientKey: window.clientKey, + locale: window.locale + }); + case 3: + checkout = _context.sent; + amazonPayConfig = (_paymentMethodsRespon = paymentMethodsResponse.find(function (pm) { + return pm.type === AMAZON_PAY; + })) === null || _paymentMethodsRespon === void 0 ? void 0 : _paymentMethodsRespon.configuration; + if (amazonPayConfig) { + _context.next = 7; + break; + } + return _context.abrupt("return"); + case 7: + amazonPayButtonConfig = { + showPayButton: true, + productType: 'PayAndShip', + configuration: amazonPayConfig, + returnUrl: window.returnUrl + }; + amazonPayButton = checkout.create(AMAZON_PAY, amazonPayButtonConfig); + amazonPayButton.mount('#amazonpay-container'); + updateLoadedExpressMethods(AMAZON_PAY); + checkIfExpressMethodsAreReady(); + case 12: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _mountAmazonPayComponent.apply(this, arguments); +} +mountAmazonPayComponent(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js new file mode 100644 index 000000000..a22747c3b --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js @@ -0,0 +1,110 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +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); }); }; } +function saveShopperDetails(details) { + $.ajax({ + url: window.saveShopperDetailsURL, + type: 'post', + data: { + shopperDetails: JSON.stringify(details), + paymentMethod: 'amazonpay' + }, + success: function success(data) { + var select = document.querySelector('#shippingMethods'); + select.innerHTML = ''; + data.shippingMethods.forEach(function (shippingMethod) { + var option = document.createElement('option'); + option.setAttribute('data-shipping-id', shippingMethod.ID); + option.innerText = "".concat(shippingMethod.displayName, " (").concat(shippingMethod.estimatedArrivalTime, ")"); + select.appendChild(option); + }); + select.options[0].selected = true; + select.dispatchEvent(new Event('change')); + } + }); +} +function constructAddress(shopperDetails) { + var addressKeys = Object.keys(shopperDetails.shippingAddress); + var addressValues = Object.values(shopperDetails.shippingAddress); + var addressStr = "".concat(shopperDetails.shippingAddress.name, "\n"); + for (var i = 0; i < addressKeys.length; i += 1) { + if (addressValues[i] && addressKeys[i] !== 'name') { + addressStr += "".concat(addressValues[i], " "); + } + } + return addressStr; +} +function positionElementBefore(elm) { + var addressDetails = document.querySelector('#amazonPayAddressDetails'); + var containerNode = addressDetails.parentNode.parentNode.parentNode; + containerNode.insertBefore(addressDetails, document.querySelector(elm)); +} +function wrapChangeAddressButton() { + // hide component button and use custom "Edit" buttons instead + var changeDetailsBtn = document.getElementsByClassName('adyen-checkout__button adyen-checkout__button--ghost adyen-checkout__amazonpay__button--changeAddress')[0]; + changeDetailsBtn.classList.add('invisible'); + var editAddressBtns = document.querySelectorAll('.editAddressBtn'); + editAddressBtns.forEach(function (btn) { + btn.addEventListener('click', function () { + changeDetailsBtn.click(); + }); + }); +} +function showAddressDetails(shopperDetails) { + var addressText = constructAddress(shopperDetails); + var addressElement = document.querySelector('#address'); + var paymentDiscriptorElement = document.querySelector('#paymentStr'); + addressElement.innerText = addressText; + paymentDiscriptorElement.innerText = shopperDetails.paymentDescriptor; + positionElementBefore('.coupons-and-promos'); + wrapChangeAddressButton(); + var payBtn = document.getElementsByClassName('adyen-checkout__button adyen-checkout__button--standalone adyen-checkout__button--pay')[0]; + payBtn.style.background = '#00a1e0'; +} +function mountAmazonPayComponent() { + return _mountAmazonPayComponent.apply(this, arguments); +} +function _mountAmazonPayComponent() { + _mountAmazonPayComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var amazonPayNode, checkout, amazonConfig, amazonPayComponent, shopperDetails; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + amazonPayNode = document.getElementById('amazon-container'); + _context.next = 3; + return AdyenCheckout(window.Configuration); + case 3: + checkout = _context.sent; + _context.prev = 4; + amazonConfig = { + showOrderButton: true, + returnUrl: window.returnUrl, + showChangePaymentDetailsButton: true, + amount: JSON.parse(window.basketAmount), + amazonCheckoutSessionId: window.amazonCheckoutSessionId + }; + amazonPayComponent = checkout.create('amazonpay', amazonConfig).mount(amazonPayNode); + _context.next = 9; + return amazonPayComponent.getShopperDetails(); + case 9: + shopperDetails = _context.sent; + saveShopperDetails(shopperDetails); + showAddressDetails(shopperDetails); + _context.next = 16; + break; + case 14: + _context.prev = 14; + _context.t0 = _context["catch"](4); + case 16: + case "end": + return _context.stop(); + } + }, _callee, null, [[4, 14]]); + })); + return _mountAmazonPayComponent.apply(this, arguments); +} +mountAmazonPayComponent(); +module.exports = saveShopperDetails; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/applePayExpress.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/applePayExpress.js new file mode 100644 index 000000000..bb2b3ee70 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/applePayExpress.js @@ -0,0 +1,422 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +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); }); }; } +var helpers = require('./adyen_checkout/helpers'); +var _require = require('./commons/index'), + checkIfExpressMethodsAreReady = _require.checkIfExpressMethodsAreReady; +var _require2 = require('./commons'), + updateLoadedExpressMethods = _require2.updateLoadedExpressMethods; +var _require3 = require('./constants'), + APPLE_PAY = _require3.APPLE_PAY; +var checkout; +var shippingMethodsData; +function initializeCheckout() { + return _initializeCheckout.apply(this, arguments); +} +function _initializeCheckout() { + _initializeCheckout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() { + var session, sessionData, shippingMethods; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return fetch(window.sessionsUrl); + case 2: + session = _context5.sent; + _context5.next = 5; + return session.json(); + case 5: + sessionData = _context5.sent; + _context5.next = 8; + return fetch(window.shippingMethodsUrl); + case 8: + shippingMethods = _context5.sent; + _context5.next = 11; + return shippingMethods.json(); + case 11: + shippingMethodsData = _context5.sent; + _context5.next = 14; + return AdyenCheckout({ + environment: window.environment, + clientKey: window.clientKey, + locale: window.locale, + session: sessionData + }); + case 14: + checkout = _context5.sent; + case 15: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _initializeCheckout.apply(this, arguments); +} +function createApplePayButton(_x) { + return _createApplePayButton.apply(this, arguments); +} +function _createApplePayButton() { + _createApplePayButton = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(applePayButtonConfig) { + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", checkout.create(APPLE_PAY, applePayButtonConfig)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _createApplePayButton.apply(this, arguments); +} +function formatCustomerObject(customerData, billingData) { + return { + addressBook: { + addresses: {}, + preferredAddress: { + address1: customerData.addressLines[0], + address2: customerData.addressLines.length > 1 ? customerData.addressLines[1] : null, + city: customerData.locality, + countryCode: { + displayValue: customerData.country, + value: customerData.countryCode + }, + firstName: customerData.givenName, + lastName: customerData.familyName, + ID: customerData.emailAddress, + postalCode: customerData.postalCode, + stateCode: customerData.administrativeArea + } + }, + billingAddressDetails: { + address1: billingData.addressLines[0], + address2: billingData.addressLines.length > 1 ? billingData.addressLines[1] : null, + city: billingData.locality, + countryCode: { + displayValue: billingData.country, + value: billingData.countryCode + }, + firstName: billingData.givenName, + lastName: billingData.familyName, + postalCode: billingData.postalCode, + stateCode: billingData.administrativeArea + }, + customer: {}, + profile: { + firstName: customerData.givenName, + lastName: customerData.familyName, + email: customerData.emailAddress, + phone: customerData.phoneNumber + } + }; +} +function handleAuthorised(response, resolveApplePay) { + var _response$fullRespons, _response$fullRespons2, _response$fullRespons3, _response$fullRespons4, _response$fullRespons5; + resolveApplePay(); + document.querySelector('#result').value = JSON.stringify({ + pspReference: (_response$fullRespons = response.fullResponse) === null || _response$fullRespons === void 0 ? void 0 : _response$fullRespons.pspReference, + resultCode: (_response$fullRespons2 = response.fullResponse) === null || _response$fullRespons2 === void 0 ? void 0 : _response$fullRespons2.resultCode, + paymentMethod: (_response$fullRespons3 = response.fullResponse) !== null && _response$fullRespons3 !== void 0 && _response$fullRespons3.paymentMethod ? response.fullResponse.paymentMethod : (_response$fullRespons4 = response.fullResponse) === null || _response$fullRespons4 === void 0 ? void 0 : (_response$fullRespons5 = _response$fullRespons4.additionalData) === null || _response$fullRespons5 === void 0 ? void 0 : _response$fullRespons5.paymentMethod + }); + document.querySelector('#showConfirmationForm').submit(); +} +function handleError(rejectApplePay) { + rejectApplePay(); + document.querySelector('#result').value = JSON.stringify({ + error: true + }); + document.querySelector('#showConfirmationForm').submit(); +} +function handleApplePayResponse(response, resolveApplePay, rejectApplePay) { + if (response.resultCode === 'Authorised') { + handleAuthorised(response, resolveApplePay); + } else { + handleError(rejectApplePay); + } +} +function callPaymentFromComponent(data, resolveApplePay, rejectApplePay) { + return $.ajax({ + url: window.paymentFromComponentURL, + type: 'post', + data: { + data: JSON.stringify(data), + paymentMethod: APPLE_PAY + }, + success: function success(response) { + helpers.createShowConfirmationForm(window.showConfirmationAction); + helpers.setOrderFormData(response); + document.querySelector('#additionalDetailsHidden').value = JSON.stringify(data); + handleApplePayResponse(response, resolveApplePay, rejectApplePay); + } + }).fail(function () { + rejectApplePay(); + }); +} +initializeCheckout().then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var applePayPaymentMethod, applePayConfig, applePayButtonConfig, cartContainer, applePayButton, isApplePayButtonAvailable, expressCheckoutNodesIndex; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + applePayPaymentMethod = checkout.paymentMethodsResponse.paymentMethods.find(function (pm) { + return pm.type === APPLE_PAY; + }); + if (applePayPaymentMethod) { + _context4.next = 5; + break; + } + updateLoadedExpressMethods(APPLE_PAY); + checkIfExpressMethodsAreReady(); + return _context4.abrupt("return"); + case 5: + applePayConfig = applePayPaymentMethod.configuration; + applePayButtonConfig = { + showPayButton: true, + configuration: applePayConfig, + amount: checkout.options.amount, + requiredShippingContactFields: ['postalAddress', 'email', 'phone'], + requiredBillingContactFields: ['postalAddress', 'phone'], + shippingMethods: shippingMethodsData.shippingMethods.map(function (sm) { + return { + label: sm.displayName, + detail: sm.description, + identifier: sm.ID, + amount: "".concat(sm.shippingCost.value) + }; + }), + onAuthorized: function () { + var _onAuthorized = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(resolve, reject, event) { + var customerData, billingData, customer, stateData, resolveApplePay; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + customerData = event.payment.shippingContact; + billingData = event.payment.billingContact; + customer = formatCustomerObject(customerData, billingData); + stateData = { + paymentMethod: { + type: APPLE_PAY, + applePayToken: event.payment.token.paymentData + }, + paymentType: 'express' + }; + resolveApplePay = function resolveApplePay() { + // ** is used instead of Math.pow + var value = applePayButtonConfig.amount.value * Math.pow(10, parseInt(window.digitsNumber, 10)); + var finalPriceUpdate = { + newTotal: { + type: 'final', + label: applePayConfig.merchantName, + amount: "".concat(Math.round(value)) + } + }; + resolve(finalPriceUpdate); + }; + _context.next = 8; + return callPaymentFromComponent(_objectSpread(_objectSpread({}, stateData), {}, { + customer: customer + }), resolveApplePay, reject); + case 8: + _context.next = 13; + break; + case 10: + _context.prev = 10; + _context.t0 = _context["catch"](0); + reject(_context.t0); + case 13: + case "end": + return _context.stop(); + } + }, _callee, null, [[0, 10]]); + })); + function onAuthorized(_x2, _x3, _x4) { + return _onAuthorized.apply(this, arguments); + } + return onAuthorized; + }(), + onSubmit: function onSubmit() { + // This handler is empty to prevent sending a second payment request + // We already do the payment in paymentFromComponent + }, + onShippingMethodSelected: function () { + var _onShippingMethodSelected = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(resolve, reject, event) { + var shippingMethod, matchingShippingMethod, calculationResponse, newCalculation, applePayShippingMethodUpdate; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + shippingMethod = event.shippingMethod; + matchingShippingMethod = shippingMethodsData.shippingMethods.find(function (sm) { + return sm.ID === shippingMethod.identifier; + }); + _context2.next = 4; + return fetch("".concat(window.calculateAmountUrl, "?").concat(new URLSearchParams({ + shipmentUUID: matchingShippingMethod.shipmentUUID, + methodID: matchingShippingMethod.ID + })), { + method: 'POST' + }); + case 4: + calculationResponse = _context2.sent; + if (!calculationResponse.ok) { + _context2.next = 14; + break; + } + _context2.next = 8; + return calculationResponse.json(); + case 8: + newCalculation = _context2.sent; + applePayButtonConfig.amount = { + value: newCalculation.grandTotalAmount.value, + currency: newCalculation.grandTotalAmount.currency + }; + applePayShippingMethodUpdate = { + newTotal: { + type: 'final', + label: applePayConfig.merchantName, + amount: newCalculation.grandTotalAmount.value + } + }; + resolve(applePayShippingMethodUpdate); + _context2.next = 15; + break; + case 14: + reject(); + case 15: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function onShippingMethodSelected(_x5, _x6, _x7) { + return _onShippingMethodSelected.apply(this, arguments); + } + return onShippingMethodSelected; + }(), + onShippingContactSelected: function () { + var _onShippingContactSelected = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(resolve, reject, event) { + var shippingContact, shippingMethods, _shippingMethodsData$, selectedShippingMethod, calculationResponse, shippingMethodsStructured, newCalculation, applePayShippingContactUpdate; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + shippingContact = event.shippingContact; + _context3.next = 3; + return fetch("".concat(window.shippingMethodsUrl, "?").concat(new URLSearchParams({ + city: shippingContact.locality, + country: shippingContact.country, + countryCode: shippingContact.countryCode, + stateCode: shippingContact.administrativeArea + }))); + case 3: + shippingMethods = _context3.sent; + if (!shippingMethods.ok) { + _context3.next = 28; + break; + } + _context3.next = 7; + return shippingMethods.json(); + case 7: + shippingMethodsData = _context3.sent; + if (!((_shippingMethodsData$ = shippingMethodsData.shippingMethods) !== null && _shippingMethodsData$ !== void 0 && _shippingMethodsData$.length)) { + _context3.next = 25; + break; + } + selectedShippingMethod = shippingMethodsData.shippingMethods[0]; + _context3.next = 12; + return fetch("".concat(window.calculateAmountUrl, "?").concat(new URLSearchParams({ + shipmentUUID: selectedShippingMethod.shipmentUUID, + methodID: selectedShippingMethod.ID + })), { + method: 'POST' + }); + case 12: + calculationResponse = _context3.sent; + if (!calculationResponse.ok) { + _context3.next = 22; + break; + } + shippingMethodsStructured = shippingMethodsData.shippingMethods.map(function (sm) { + return { + label: sm.displayName, + detail: sm.description, + identifier: sm.ID, + amount: "".concat(sm.shippingCost.value) + }; + }); + _context3.next = 17; + return calculationResponse.json(); + case 17: + newCalculation = _context3.sent; + applePayShippingContactUpdate = { + newShippingMethods: shippingMethodsStructured, + newTotal: { + type: 'final', + label: applePayConfig.merchantName, + amount: newCalculation.grandTotalAmount.value + } + }; + resolve(applePayShippingContactUpdate); + _context3.next = 23; + break; + case 22: + reject(); + case 23: + _context3.next = 26; + break; + case 25: + reject(); + case 26: + _context3.next = 29; + break; + case 28: + reject(); + case 29: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function onShippingContactSelected(_x8, _x9, _x10) { + return _onShippingContactSelected.apply(this, arguments); + } + return onShippingContactSelected; + }() + }; + cartContainer = document.getElementsByClassName(APPLE_PAY); + _context4.next = 10; + return createApplePayButton(applePayButtonConfig); + case 10: + applePayButton = _context4.sent; + _context4.next = 13; + return applePayButton.isAvailable(); + case 13: + isApplePayButtonAvailable = _context4.sent; + if (isApplePayButtonAvailable) { + for (expressCheckoutNodesIndex = 0; expressCheckoutNodesIndex < cartContainer.length; expressCheckoutNodesIndex += 1) { + applePayButton.mount(cartContainer[expressCheckoutNodesIndex]); + } + } + updateLoadedExpressMethods(APPLE_PAY); + checkIfExpressMethodsAreReady(); + case 17: + case "end": + return _context4.stop(); + } + }, _callee4); +})))["catch"](function () { + updateLoadedExpressMethods(APPLE_PAY); + checkIfExpressMethodsAreReady(); +}); +module.exports = { + handleAuthorised: handleAuthorised, + handleError: handleError, + handleApplePayResponse: handleApplePayResponse, + callPaymentFromComponent: callPaymentFromComponent +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout.js new file mode 100644 index 000000000..715eb0e21 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout.js @@ -0,0 +1,30 @@ +"use strict"; + +/* eslint-disable prefer-regex-literals */ +var processInclude = require('base/util'); +var baseCheckout = require('base/checkout/checkout'); +var adyenCheckout = require('./adyenCheckout'); +var billing = require('./checkout/billing'); + +// Compatibility Adyen SFRA 5.x.x & 6.x.x +var checkout = window.AdyenSFRA6Enabled !== 'null' ? require('./checkout/checkoutSFRA6') : require('./checkout/checkoutSFRA5'); +$(document).ready(function () { + // eslint-disable-line + var name = 'paymentError'; + var error = new RegExp("[?&]".concat(encodeURIComponent(name), "=([^&]*)")).exec(window.location.search); + var paymentStage = new RegExp('[?&]stage=payment([^&]*)').exec(window.location.search); + if (error || paymentStage) { + if (error) { + $('.error-message').show(); + $('.error-message-text').text(decodeURIComponent(error[1])); + } + adyenCheckout.renderGenericComponent(); + } + processInclude(baseCheckout); + processInclude(billing); + processInclude(checkout); + $('#selectedPaymentOption').val($('.payment-options .nav-item .active').parent().attr('data-method-id')); +}); +$('.payment-options .nav-link').click(function setAttr() { + $('#selectedPaymentOption').val($(this).parent().attr('data-method-id')); +}); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/billing.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/billing.js new file mode 100644 index 000000000..432cbca36 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/billing.js @@ -0,0 +1,55 @@ +"use strict"; + +function hasData() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return args.every(function (arg) { + return !!arg; + }); +} +function appendToPaymentSummary(html) { + // update payment details + var paymentSummary = document.querySelector('.payment-details'); + paymentSummary.innerHTML += html; +} +function appendMaskedCC(_ref) { + var maskedCreditCardNumber = _ref.maskedCreditCardNumber; + var innerHTML = "
            ".concat(maskedCreditCardNumber, "
            "); + return maskedCreditCardNumber && appendToPaymentSummary(innerHTML); +} +function appendIssuerName(_ref2) { + var selectedIssuerName = _ref2.selectedIssuerName; + var innerHTML = "
            ".concat(selectedIssuerName, "
            "); + return selectedIssuerName && appendToPaymentSummary(innerHTML); +} +function appendExpiration(_ref3, order) { + var expirationMonth = _ref3.expirationMonth, + expirationYear = _ref3.expirationYear; + var innerHTML = "
            ".concat(order.resources.cardEnding, " ").concat(expirationMonth, "/").concat(expirationYear, "
            "); + return hasData(expirationMonth, expirationYear) && appendToPaymentSummary(innerHTML); +} +function appendPaymentMethod(_ref4) { + var selectedAdyenPM = _ref4.selectedAdyenPM; + var innerHTML = "
            ".concat(selectedAdyenPM, "
            "); + return selectedAdyenPM && appendToPaymentSummary(innerHTML); +} + +/** + * Updates the payment information in checkout, based on the supplied order model + * @param {Object} order - checkout model to use as basis of new truth + */ +function updatePaymentInformation(order) { + var _order$billing$paymen; + if ((_order$billing$paymen = order.billing.payment.selectedPaymentInstruments) !== null && _order$billing$paymen !== void 0 && _order$billing$paymen.length) { + var selectedPaymentInstrument = order.billing.payment.selectedPaymentInstruments[0]; + document.querySelector('.payment-details').innerHTML = ''; + appendPaymentMethod(selectedPaymentInstrument); + appendIssuerName(selectedPaymentInstrument); + appendMaskedCC(selectedPaymentInstrument); + appendExpiration(selectedPaymentInstrument, order); + } +} +module.exports.methods = { + updatePaymentInformation: updatePaymentInformation +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/checkoutSFRA5.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/checkoutSFRA5.js new file mode 100644 index 000000000..a7a313ce0 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/checkoutSFRA5.js @@ -0,0 +1,469 @@ +'use strict'; + +var shippingHelpers = require('base/checkout/shipping'); +var billingHelpers = require('base/checkout/billing'); +var summaryHelpers = require('base/checkout/summary'); +var formHelpers = require('base/checkout/formErrors'); +var scrollAnimate = require('base/components/scrollAnimate'); +var billing = require('./billing'); +// ### Custom Adyen cartridge start ### +var adyenCheckout = require('../adyenCheckout'); +// ### Custom Adyen cartridge end ### + +/** + * Create the jQuery Checkout Plugin. + * + * This jQuery plugin will be registered on the dom element in checkout.isml with the + * id of "checkout-main". + * + * The checkout plugin will handle the different state the user interface is in as the user + * progresses through the varying forms such as shipping and payment. + * + * Billing info and payment info are used a bit synonymously in this code. + * + */ +(function ($) { + $.fn.checkout = function () { + // eslint-disable-line + var plugin = this; + + // + // Collect form data from user input + // + var formData = { + // Shipping Address + shipping: {}, + // Billing Address + billing: {}, + // Payment + payment: {}, + // Gift Codes + giftCode: {} + }; + + // + // The different states/stages of checkout + // + var checkoutStages = ['shipping', 'payment', 'placeOrder', 'submitted']; + + /** + * Updates the URL to determine stage + * @param {number} currentStage - The current stage the user is currently on in the checkout + */ + function updateUrl(currentStage) { + history.pushState(checkoutStages[currentStage], document.title, location.pathname + '?stage=' + checkoutStages[currentStage] + '#' + checkoutStages[currentStage]); + } + + // + // Local member methods of the Checkout plugin + // + var members = { + // initialize the currentStage variable for the first time + currentStage: 0, + /** + * Set or update the checkout stage (AKA the shipping, billing, payment, etc... steps) + * @returns {Object} a promise + */ + updateStage: function updateStage() { + var stage = checkoutStages[members.currentStage]; + var defer = $.Deferred(); // eslint-disable-line + + if (stage === 'shipping') { + // + // Clear Previous Errors + // + formHelpers.clearPreviousErrors('.shipping-form'); + + // + // Submit the Shipping Address Form + // + var isMultiShip = $('#checkout-main').hasClass('multi-ship'); + var formSelector = isMultiShip ? '.multi-shipping .active form' : '.single-shipping .shipping-form'; + var form = $(formSelector); + if (isMultiShip && form.length === 0) { + // disable the next:Payment button here + $('body').trigger('checkout:disableButton', '.next-step-button button'); + // in case the multi ship form is already submitted + var url = $('#checkout-main').attr('data-checkout-get-url'); + $.ajax({ + url: url, + method: 'GET', + success: function success(data) { + // enable the next:Payment button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + if (!data.error) { + $('body').trigger('checkout:updateCheckoutView', { + order: data.order, + customer: data.customer + }); + defer.resolve(); + } else if (data.message && $('.shipping-error .alert-danger').length < 1) { + var errorMsg = data.message; + var errorHtml = ''; + $('.shipping-error').append(errorHtml); + scrollAnimate($('.shipping-error')); + defer.reject(); + } else if (data.redirectUrl) { + window.location.href = data.redirectUrl; + } + }, + error: function error() { + // enable the next:Payment button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + // Server error submitting form + defer.reject(); + } + }); + } else { + var shippingFormData = form.serialize(); + $('body').trigger('checkout:serializeShipping', { + form: form, + data: shippingFormData, + callback: function callback(data) { + shippingFormData = data; + } + }); + // disable the next:Payment button here + $('body').trigger('checkout:disableButton', '.next-step-button button'); + $.ajax({ + url: form.attr('action'), + type: 'post', + data: shippingFormData, + success: function success(data) { + // enable the next:Payment button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + shippingHelpers.methods.shippingFormResponse(defer, data); + }, + error: function error(err) { + // enable the next:Payment button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + if (err.responseJSON && err.responseJSON.redirectUrl) { + window.location.href = err.responseJSON.redirectUrl; + } + // Server error submitting form + defer.reject(err.responseJSON); + } + }); + } + return defer; + } else if (stage === 'payment') { + // + // Submit the Billing Address Form + // + + formHelpers.clearPreviousErrors('.payment-form'); + var billingAddressForm = $('#dwfrm_billing .billing-address-block :input').serialize(); + $('body').trigger('checkout:serializeBilling', { + form: $('#dwfrm_billing .billing-address-block'), + data: billingAddressForm, + callback: function callback(data) { + if (data) { + billingAddressForm = data; + } + } + }); + var contactInfoForm = $('#dwfrm_billing .contact-info-block :input').serialize(); + $('body').trigger('checkout:serializeBilling', { + form: $('#dwfrm_billing .contact-info-block'), + data: contactInfoForm, + callback: function callback(data) { + if (data) { + contactInfoForm = data; + } + } + }); + var activeTabId = $('.tab-pane.active').attr('id'); + var paymentInfoSelector = '#dwfrm_billing .' + activeTabId + ' .payment-form-fields :input'; + var paymentInfoForm = $(paymentInfoSelector).serialize(); + $('body').trigger('checkout:serializeBilling', { + form: $(paymentInfoSelector), + data: paymentInfoForm, + callback: function callback(data) { + if (data) { + paymentInfoForm = data; + } + } + }); + var paymentForm = billingAddressForm + '&' + contactInfoForm + '&' + paymentInfoForm; + if ($('.data-checkout-stage').data('customer-type') === 'registered') { + // if payment method is credit card + if ($('.payment-information').data('payment-method-id') === 'CREDIT_CARD') { + if (!$('.payment-information').data('is-new-payment')) { + var cvvCode = $('.saved-payment-instrument.' + 'selected-payment .saved-payment-security-code').val(); + if (cvvCode === '') { + var cvvElement = $('.saved-payment-instrument.' + 'selected-payment ' + '.form-control'); + cvvElement.addClass('is-invalid'); + scrollAnimate(cvvElement); + defer.reject(); + return defer; + } + var $savedPaymentInstrument = $('.saved-payment-instrument' + '.selected-payment'); + paymentForm += '&storedPaymentUUID=' + $savedPaymentInstrument.data('uuid'); + paymentForm += '&securityCode=' + cvvCode; + } + } + } + // disable the next:Place Order button here + $('body').trigger('checkout:disableButton', '.next-step-button button'); + $.ajax({ + url: $('#dwfrm_billing').attr('action'), + method: 'POST', + data: paymentForm, + success: function success(data) { + // enable the next:Place Order button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + // look for field validation errors + if (data.error) { + if (data.fieldErrors.length) { + data.fieldErrors.forEach(function (error) { + if (Object.keys(error).length) { + formHelpers.loadFormErrors('.payment-form', error); + } + }); + } + if (data.serverErrors.length) { + data.serverErrors.forEach(function (error) { + $('.error-message').show(); + $('.error-message-text').text(error); + scrollAnimate($('.error-message')); + }); + } + if (data.cartError) { + window.location.href = data.redirectUrl; + } + defer.reject(); + } else { + // + // Populate the Address Summary + // + $('body').trigger('checkout:updateCheckoutView', { + order: data.order, + customer: data.customer + }); + if (data.renderedPaymentInstruments) { + $('.stored-payments').empty().html(data.renderedPaymentInstruments); + } + if (data.customer.registeredUser && data.customer.customerPaymentInstruments.length) { + $('.cancel-new-payment').removeClass('checkout-hidden'); + } + scrollAnimate(); + defer.resolve(data); + } + }, + error: function error(err) { + // enable the next:Place Order button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + if (err.responseJSON && err.responseJSON.redirectUrl) { + window.location.href = err.responseJSON.redirectUrl; + } + } + }); + return defer; + } else if (stage === 'placeOrder') { + // disable the placeOrder button here + $('body').trigger('checkout:disableButton', '.next-step-button button'); + $.ajax({ + url: $('.place-order').data('action'), + method: 'POST', + success: function success(data) { + // enable the placeOrder button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + if (data.error) { + if (data.cartError) { + window.location.href = data.redirectUrl; + defer.reject(); + } else { + // go to appropriate stage and display error message + defer.reject(data); + } + // ### Custom Adyen cartridge start ### + } else if (data.adyenAction) { + window.orderToken = data.orderToken; + adyenCheckout.actionHandler(data.adyenAction); + // ### Custom Adyen cartridge end ### + } else { + var continueUrl = data.continueUrl; + var urlParams = { + ID: data.orderID, + token: data.orderToken + }; + continueUrl += (continueUrl.indexOf('?') !== -1 ? '&' : '?') + Object.keys(urlParams).map(function (key) { + return key + '=' + encodeURIComponent(urlParams[key]); + }).join('&'); + window.location.href = continueUrl; + defer.resolve(data); + } + }, + error: function error() { + // enable the placeOrder button here + $('body').trigger('checkout:enableButton', $('.next-step-button button')); + } + }); + return defer; + } + var p = $('
            ').promise(); // eslint-disable-line + setTimeout(function () { + p.done(); // eslint-disable-line + }, 500); + return p; // eslint-disable-line + }, + + /** + * Initialize the checkout stage. + * + * TODO: update this to allow stage to be set from server? + */ + initialize: function initialize() { + // set the initial state of checkout + members.currentStage = checkoutStages.indexOf($('.data-checkout-stage').data('checkout-stage')); + $(plugin).attr('data-checkout-stage', checkoutStages[members.currentStage]); + + // + // Handle Payment option selection + // + $('input[name$="paymentMethod"]', plugin).on('change', function () { + $('.credit-card-form').toggle($(this).val() === 'CREDIT_CARD'); + }); + + // + // Handle Next State button click + // + $(plugin).on('click', '.next-step-button button', function () { + members.nextStage(); + }); + + // + // Handle Edit buttons on shipping and payment summary cards + // + $('.shipping-summary .edit-button', plugin).on('click', function () { + if (!$('#checkout-main').hasClass('multi-ship')) { + $('body').trigger('shipping:selectSingleShipping'); + } + members.gotoStage('shipping'); + }); + $('.payment-summary .edit-button', plugin).on('click', function () { + members.gotoStage('payment'); + }); + + // + // remember stage (e.g. shipping) + // + updateUrl(members.currentStage); + + // + // Listen for foward/back button press and move to correct checkout-stage + // + $(window).on('popstate', function (e) { + // + // Back button when event state less than current state in ordered + // checkoutStages array. + // + if (e.state === null || checkoutStages.indexOf(e.state) < members.currentStage) { + members.handlePrevStage(false); + } else if (checkoutStages.indexOf(e.state) > members.currentStage) { + // Forward button pressed + members.handleNextStage(false); + } + }); + + // + // Set the form data + // + plugin.data('formData', formData); + }, + /** + * The next checkout state step updates the css for showing correct buttons etc... + */ + nextStage: function nextStage() { + var promise = members.updateStage(); + promise.done(function () { + // Update UI with new stage + members.handleNextStage(true); + }); + promise.fail(function (data) { + // show errors + if (data) { + if (data.errorStage) { + members.gotoStage(data.errorStage.stage); + if (data.errorStage.step === 'billingAddress') { + var $billingAddressSameAsShipping = $('input[name$="_shippingAddressUseAsBillingAddress"]'); + if ($billingAddressSameAsShipping.is(':checked')) { + $billingAddressSameAsShipping.prop('checked', false); + } + } + } + if (data.errorMessage) { + $('.error-message').show(); + $('.error-message-text').text(data.errorMessage); + } + } + }); + }, + /** + * The next checkout state step updates the css for showing correct buttons etc... + * + * @param {boolean} bPushState - boolean when true pushes state using the history api. + */ + handleNextStage: function handleNextStage(bPushState) { + if (members.currentStage < checkoutStages.length - 1) { + // move stage forward + members.currentStage++; + + // + // show new stage in url (e.g.payment) + // + if (bPushState) { + updateUrl(members.currentStage); + } + } + + // Set the next stage on the DOM + $(plugin).attr('data-checkout-stage', checkoutStages[members.currentStage]); + }, + /** + * Previous State + */ + handlePrevStage: function handlePrevStage() { + if (members.currentStage > 0) { + // move state back + members.currentStage--; + updateUrl(members.currentStage); + } + $(plugin).attr('data-checkout-stage', checkoutStages[members.currentStage]); + }, + /** + * Use window history to go to a checkout stage + * @param {string} stageName - the checkout state to goto + */ + gotoStage: function gotoStage(stageName) { + members.currentStage = checkoutStages.indexOf(stageName); + updateUrl(members.currentStage); + $(plugin).attr('data-checkout-stage', checkoutStages[members.currentStage]); + } + }; + + // + // Initialize the checkout + // + members.initialize(); + return this; + }; +})(jQuery); +module.exports = { + updateCheckoutView: function updateCheckoutView() { + $('body').on('checkout:updateCheckoutView', function (e, data) { + shippingHelpers.methods.updateMultiShipInformation(data.order); + summaryHelpers.updateTotals(data.order.totals); + data.order.shipping.forEach(function (shipping) { + shippingHelpers.methods.updateShippingInformation(shipping, data.order, data.customer, data.options); + }); + var currentStage = window.location.search.substring(window.location.search.indexOf('=') + 1); + if (currentStage === ('shipping' || 'payment')) { + adyenCheckout.renderGenericComponent(); + } + billingHelpers.methods.updateBillingInformation(data.order, data.customer, data.options); + billing.methods.updatePaymentInformation(data.order, data.options); + summaryHelpers.updateOrderProductSummaryInformation(data.order, data.options); + }); + } +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/checkoutSFRA6.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/checkoutSFRA6.js new file mode 100644 index 000000000..ce1ff4c9c --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout/checkoutSFRA6.js @@ -0,0 +1,521 @@ +"use strict"; + +var customerHelpers = require('base/checkout/customer'); +var shippingHelpers = require('base/checkout/shipping'); +var billingHelpers = require('base/checkout/billing'); +var summaryHelpers = require('base/checkout/summary'); +var formHelpers = require('base/checkout/formErrors'); +var scrollAnimate = require('base/components/scrollAnimate'); +var billing = require('./billing'); +// ### Custom Adyen cartridge start ### +var adyenCheckout = require('../adyenCheckout'); +// ### Custom Adyen cartridge end ### + +/** + * Create the jQuery Checkout Plugin. + * + * This jQuery plugin will be registered on the dom element in checkout.isml with the + * id of "checkout-main". + * + * The checkout plugin will handle the different state the user interface is in as the user + * progresses through the varying forms such as shipping and payment. + * + * Billing info and payment info are used a bit synonymously in this code. + * + */ +(function ($) { + $.fn.checkout = function () { + var plugin = this; + + // + // Collect form data from user input + // + var formData = { + // Customer Data + customer: {}, + // Shipping Address + shipping: {}, + // Billing Address + billing: {}, + // Payment + payment: {}, + // Gift Codes + giftCode: {} + }; + + // + // The different states/stages of checkout + // + var checkoutStages = ['customer', 'shipping', 'payment', 'placeOrder', 'submitted']; + + /** + * Updates the URL to determine stage + * @param {number} currentStage - The current stage the user is currently on in the checkout + */ + function updateUrl(currentStage) { + history.pushState(checkoutStages[currentStage], document.title, location.pathname + '?stage=' + checkoutStages[currentStage] + '#' + checkoutStages[currentStage]); + } + + // + // Local member methods of the Checkout plugin + // + var members = { + // initialize the currentStage variable for the first time + currentStage: 0, + /** + * Set or update the checkout stage (AKA the shipping, billing, payment, etc... steps) + * @returns {Object} a promise + */ + updateStage: function updateStage() { + var stage = checkoutStages[members.currentStage]; + var defer = $.Deferred(); // eslint-disable-line + + if (stage === 'customer') { + // + // Clear Previous Errors + // + customerHelpers.methods.clearErrors(); + // + // Submit the Customer Form + // + var customerFormSelector = customerHelpers.methods.isGuestFormActive() ? customerHelpers.vars.GUEST_FORM : customerHelpers.vars.REGISTERED_FORM; + var customerForm = $(customerFormSelector); + $.ajax({ + url: customerForm.attr('action'), + type: 'post', + data: customerForm.serialize(), + success: function success(data) { + if (data.redirectUrl) { + window.location.href = data.redirectUrl; + } else { + customerHelpers.methods.customerFormResponse(defer, data); + } + }, + error: function error(err) { + if (err.responseJSON && err.responseJSON.redirectUrl) { + window.location.href = err.responseJSON.redirectUrl; + } + // Server error submitting form + defer.reject(err.responseJSON); + } + }); + return defer; + } else if (stage === 'shipping') { + // + // Clear Previous Errors + // + formHelpers.clearPreviousErrors('.shipping-form'); + + // + // Submit the Shipping Address Form + // + var isMultiShip = $('#checkout-main').hasClass('multi-ship'); + var formSelector = isMultiShip ? '.multi-shipping .active form' : '.single-shipping .shipping-form'; + var form = $(formSelector); + if (isMultiShip && form.length === 0) { + // disable the next:Payment button here + $('body').trigger('checkout:disableButton', '.next-step-button button'); + // in case the multi ship form is already submitted + var url = $('#checkout-main').attr('data-checkout-get-url'); + $.ajax({ + url: url, + method: 'GET', + success: function success(data) { + // enable the next:Payment button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + if (!data.error) { + $('body').trigger('checkout:updateCheckoutView', { + order: data.order, + customer: data.customer + }); + defer.resolve(); + } else if (data.message && $('.shipping-error .alert-danger').length < 1) { + var errorMsg = data.message; + var errorHtml = ''; + $('.shipping-error').append(errorHtml); + scrollAnimate($('.shipping-error')); + defer.reject(); + } else if (data.redirectUrl) { + window.location.href = data.redirectUrl; + } + }, + error: function error() { + // enable the next:Payment button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + // Server error submitting form + defer.reject(); + } + }); + } else { + var shippingFormData = form.serialize(); + $('body').trigger('checkout:serializeShipping', { + form: form, + data: shippingFormData, + callback: function callback(data) { + shippingFormData = data; + } + }); + // disable the next:Payment button here + $('body').trigger('checkout:disableButton', '.next-step-button button'); + $.ajax({ + url: form.attr('action'), + type: 'post', + data: shippingFormData, + success: function success(data) { + // enable the next:Payment button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + shippingHelpers.methods.shippingFormResponse(defer, data); + }, + error: function error(err) { + // enable the next:Payment button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + if (err.responseJSON && err.responseJSON.redirectUrl) { + window.location.href = err.responseJSON.redirectUrl; + } + // Server error submitting form + defer.reject(err.responseJSON); + } + }); + } + return defer; + } else if (stage === 'payment') { + // + // Submit the Billing Address Form + // + + formHelpers.clearPreviousErrors('.payment-form'); + var billingAddressForm = $('#dwfrm_billing .billing-address-block :input').serialize(); + $('body').trigger('checkout:serializeBilling', { + form: $('#dwfrm_billing .billing-address-block'), + data: billingAddressForm, + callback: function callback(data) { + if (data) { + billingAddressForm = data; + } + } + }); + var contactInfoForm = $('#dwfrm_billing .contact-info-block :input').serialize(); + $('body').trigger('checkout:serializeBilling', { + form: $('#dwfrm_billing .contact-info-block'), + data: contactInfoForm, + callback: function callback(data) { + if (data) { + contactInfoForm = data; + } + } + }); + var activeTabId = $('.tab-pane.active').attr('id'); + var paymentInfoSelector = '#dwfrm_billing .' + activeTabId + ' .payment-form-fields :input'; + var paymentInfoForm = $(paymentInfoSelector).serialize(); + $('body').trigger('checkout:serializeBilling', { + form: $(paymentInfoSelector), + data: paymentInfoForm, + callback: function callback(data) { + if (data) { + paymentInfoForm = data; + } + } + }); + var paymentForm = billingAddressForm + '&' + contactInfoForm + '&' + paymentInfoForm; + if ($('.data-checkout-stage').data('customer-type') === 'registered') { + // if payment method is credit card + if ($('.payment-information').data('payment-method-id') === 'CREDIT_CARD') { + if (!$('.payment-information').data('is-new-payment')) { + var cvvCode = $('.saved-payment-instrument.' + 'selected-payment .saved-payment-security-code').val(); + if (cvvCode === '') { + var cvvElement = $('.saved-payment-instrument.' + 'selected-payment ' + '.form-control'); + cvvElement.addClass('is-invalid'); + scrollAnimate(cvvElement); + defer.reject(); + return defer; + } + var $savedPaymentInstrument = $('.saved-payment-instrument' + '.selected-payment'); + paymentForm += '&storedPaymentUUID=' + $savedPaymentInstrument.data('uuid'); + paymentForm += '&securityCode=' + cvvCode; + } + } + } + // disable the next:Place Order button here + $('body').trigger('checkout:disableButton', '.next-step-button button'); + $.ajax({ + url: $('#dwfrm_billing').attr('action'), + method: 'POST', + data: paymentForm, + success: function success(data) { + // enable the next:Place Order button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + // look for field validation errors + if (data.error) { + if (data.fieldErrors.length) { + data.fieldErrors.forEach(function (error) { + if (Object.keys(error).length) { + formHelpers.loadFormErrors('.payment-form', error); + } + }); + } + if (data.serverErrors.length) { + data.serverErrors.forEach(function (error) { + $('.error-message').show(); + $('.error-message-text').text(error); + scrollAnimate($('.error-message')); + }); + } + if (data.cartError) { + window.location.href = data.redirectUrl; + } + defer.reject(); + } else { + // + // Populate the Address Summary + // + $('body').trigger('checkout:updateCheckoutView', { + order: data.order, + customer: data.customer + }); + if (data.renderedPaymentInstruments) { + $('.stored-payments').empty().html(data.renderedPaymentInstruments); + } + if (data.customer.registeredUser && data.customer.customerPaymentInstruments.length) { + $('.cancel-new-payment').removeClass('checkout-hidden'); + } + scrollAnimate(); + defer.resolve(data); + } + }, + error: function error(err) { + // enable the next:Place Order button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + if (err.responseJSON && err.responseJSON.redirectUrl) { + window.location.href = err.responseJSON.redirectUrl; + } + } + }); + return defer; + } else if (stage === 'placeOrder') { + // disable the placeOrder button here + $('body').trigger('checkout:disableButton', '.next-step-button button'); + $.ajax({ + url: $('.place-order').data('action'), + method: 'POST', + success: function success(data) { + // enable the placeOrder button here + $('body').trigger('checkout:enableButton', '.next-step-button button'); + if (data.error) { + if (data.cartError) { + window.location.href = data.redirectUrl; + defer.reject(); + } else { + // go to appropriate stage and display error message + defer.reject(data); + } + // ### Custom Adyen cartridge start ### + } else if (data.adyenAction) { + window.orderToken = data.orderToken; + adyenCheckout.actionHandler(data.adyenAction); + // ### Custom Adyen cartridge end ### + } else { + var redirect = $('
            ').appendTo(document.body).attr({ + method: 'POST', + action: data.continueUrl + }); + $('').appendTo(redirect).attr({ + name: 'orderID', + value: data.orderID + }); + $('').appendTo(redirect).attr({ + name: 'orderToken', + value: data.orderToken + }); + redirect.submit(); + defer.resolve(data); + } + }, + error: function error() { + // enable the placeOrder button here + $('body').trigger('checkout:enableButton', $('.next-step-button button')); + } + }); + return defer; + } + var p = $('
            ').promise(); // eslint-disable-line + setTimeout(function () { + p.done(); // eslint-disable-line + }, 500); + return p; // eslint-disable-line + }, + + /** + * Initialize the checkout stage. + * + * TODO: update this to allow stage to be set from server? + */ + initialize: function initialize() { + // set the initial state of checkout + members.currentStage = checkoutStages.indexOf($('.data-checkout-stage').data('checkout-stage')); + $(plugin).attr('data-checkout-stage', checkoutStages[members.currentStage]); + $('body').on('click', '.submit-customer-login', function (e) { + e.preventDefault(); + members.nextStage(); + }); + $('body').on('click', '.submit-customer', function (e) { + e.preventDefault(); + members.nextStage(); + }); + + // + // Handle Payment option selection + // + $('input[name$="paymentMethod"]', plugin).on('change', function () { + $('.credit-card-form').toggle($(this).val() === 'CREDIT_CARD'); + }); + + // + // Handle Next State button click + // + $(plugin).on('click', '.next-step-button button', function () { + members.nextStage(); + }); + + // + // Handle Edit buttons on shipping and payment summary cards + // + $('.customer-summary .edit-button', plugin).on('click', function () { + members.gotoStage('customer'); + }); + $('.shipping-summary .edit-button', plugin).on('click', function () { + if (!$('#checkout-main').hasClass('multi-ship')) { + $('body').trigger('shipping:selectSingleShipping'); + } + members.gotoStage('shipping'); + }); + $('.payment-summary .edit-button', plugin).on('click', function () { + members.gotoStage('payment'); + }); + + // + // remember stage (e.g. shipping) + // + updateUrl(members.currentStage); + + // + // Listen for foward/back button press and move to correct checkout-stage + // + $(window).on('popstate', function (e) { + // + // Back button when event state less than current state in ordered + // checkoutStages array. + // + if (e.state === null || checkoutStages.indexOf(e.state) < members.currentStage) { + members.handlePrevStage(false); + } else if (checkoutStages.indexOf(e.state) > members.currentStage) { + // Forward button pressed + members.handleNextStage(false); + } + }); + + // + // Set the form data + // + plugin.data('formData', formData); + }, + /** + * The next checkout state step updates the css for showing correct buttons etc... + */ + nextStage: function nextStage() { + var promise = members.updateStage(); + promise.done(function () { + // Update UI with new stage + $('.error-message').hide(); + members.handleNextStage(true); + }); + promise.fail(function (data) { + // show errors + if (data) { + if (data.errorStage) { + members.gotoStage(data.errorStage.stage); + if (data.errorStage.step === 'billingAddress') { + var $billingAddressSameAsShipping = $('input[name$="_shippingAddressUseAsBillingAddress"]'); + if ($billingAddressSameAsShipping.is(':checked')) { + $billingAddressSameAsShipping.prop('checked', false); + } + } + } + if (data.errorMessage) { + $('.error-message').show(); + $('.error-message-text').text(data.errorMessage); + } + } + }); + }, + /** + * The next checkout state step updates the css for showing correct buttons etc... + * + * @param {boolean} bPushState - boolean when true pushes state using the history api. + */ + handleNextStage: function handleNextStage(bPushState) { + if (members.currentStage < checkoutStages.length - 1) { + // move stage forward + members.currentStage++; + + // + // show new stage in url (e.g.payment) + // + if (bPushState) { + updateUrl(members.currentStage); + } + } + + // Set the next stage on the DOM + $(plugin).attr('data-checkout-stage', checkoutStages[members.currentStage]); + }, + /** + * Previous State + */ + handlePrevStage: function handlePrevStage() { + if (members.currentStage > 0) { + // move state back + members.currentStage--; + updateUrl(members.currentStage); + } + $(plugin).attr('data-checkout-stage', checkoutStages[members.currentStage]); + }, + /** + * Use window history to go to a checkout stage + * @param {string} stageName - the checkout state to goto + */ + gotoStage: function gotoStage(stageName) { + members.currentStage = checkoutStages.indexOf(stageName); + updateUrl(members.currentStage); + $(plugin).attr('data-checkout-stage', checkoutStages[members.currentStage]); + } + }; + + // + // Initialize the checkout + // + members.initialize(); + return this; + }; +})(jQuery); +module.exports = { + updateCheckoutView: function updateCheckoutView() { + $('body').on('checkout:updateCheckoutView', function (e, data) { + if (data.csrfToken) { + $("input[name*='csrf_token']").val(data.csrfToken); + } + customerHelpers.methods.updateCustomerInformation(data.customer, data.order); + shippingHelpers.methods.updateMultiShipInformation(data.order); + summaryHelpers.updateTotals(data.order.totals); + data.order.shipping.forEach(function (shipping) { + shippingHelpers.methods.updateShippingInformation(shipping, data.order, data.customer, data.options); + }); + var currentStage = window.location.search.substring(window.location.search.indexOf('=') + 1); + if (currentStage === ('shipping' || 'payment')) { + adyenCheckout.renderGenericComponent(); + } + billingHelpers.methods.updateBillingInformation(data.order, data.customer, data.options); + billing.methods.updatePaymentInformation(data.order, data.options); + summaryHelpers.updateOrderProductSummaryInformation(data.order, data.options); + }); + } +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js new file mode 100644 index 000000000..b94a2fa10 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js @@ -0,0 +1,92 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +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); }); }; } +var store = require('../../../../store'); +module.exports.onFieldValid = function onFieldValid(data) { + if (data.endDigits) { + store.endDigits = data.endDigits; + document.querySelector('#cardNumber').value = store.maskedCardNumber; + } +}; +module.exports.onBrand = function onBrand(brandObject) { + document.querySelector('#cardType').value = brandObject.brand; +}; + +/** + * Makes an ajax call to the controller function CreateSession + */ +module.exports.createSession = /*#__PURE__*/function () { + var _createSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + return _context.abrupt("return", $.ajax({ + url: window.sessionsUrl, + type: 'get' + })); + case 1: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createSession() { + return _createSession.apply(this, arguments); + } + return createSession; +}(); + +/** + * Makes an ajax call to the controller function FetchGiftCards + */ +module.exports.fetchGiftCards = /*#__PURE__*/function () { + var _fetchGiftCards = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", $.ajax({ + url: window.fetchGiftCardsUrl, + type: 'get' + })); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fetchGiftCards() { + return _fetchGiftCards.apply(this, arguments); + } + return fetchGiftCards; +}(); +module.exports.checkIfExpressMethodsAreReady = function checkIfExpressMethodsAreReady() { + var expressMethodsConfig = { + applepay: window.isApplePayExpressEnabled === 'true', + amazonpay: window.isAmazonPayExpressEnabled === 'true' + }; + var enabledExpressMethods = []; + Object.keys(expressMethodsConfig).forEach(function (key) { + if (expressMethodsConfig[key]) { + enabledExpressMethods.push(key); + } + }); + enabledExpressMethods = enabledExpressMethods.sort(); + var loadedExpressMethods = window.loadedExpressMethods && window.loadedExpressMethods.length ? window.loadedExpressMethods.sort() : []; + var areAllMethodsReady = JSON.stringify(enabledExpressMethods) === JSON.stringify(loadedExpressMethods); + if (!enabledExpressMethods.length || areAllMethodsReady) { + var _document$getElementB, _document$getElementB2; + (_document$getElementB = document.getElementById('express-loader-container')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.classList.add('hidden'); + (_document$getElementB2 = document.getElementById('express-container')) === null || _document$getElementB2 === void 0 ? void 0 : _document$getElementB2.classList.remove('hidden'); + } +}; +module.exports.updateLoadedExpressMethods = function updateLoadedExpressMethods(method) { + if (!window.loadedExpressMethods) { + window.loadedExpressMethods = []; + } + if (!window.loadedExpressMethods.includes(method)) { + window.loadedExpressMethods.push(method); + } +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js new file mode 100644 index 000000000..12977c01d --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js @@ -0,0 +1,20 @@ +"use strict"; + +// Adyen constants + +module.exports = { + METHOD_ADYEN: 'Adyen', + METHOD_ADYEN_POS: 'AdyenPOS', + METHOD_ADYEN_COMPONENT: 'AdyenComponent', + RECEIVED: 'Received', + NOTENOUGHBALANCE: 'NotEnoughBalance', + SUCCESS: 'Success', + GIFTCARD: 'giftcard', + GIROPAY: 'giropay', + APPLE_PAY: 'applepay', + ACTIONTYPE: { + QRCODE: 'qrCode' + }, + DISABLED_SUBMIT_BUTTON_METHODS: ['paypal', 'paywithgoogle', 'googlepay', 'amazonpay', 'applepay', 'cashapp'], + APPLE_DOMAIN_URL: '/.well-known/apple-developer-merchantid-domain-association' +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/client/default/js/expressPaymentMethodsVisibility.js b/cartridges/int_adyen_SFRA/cartridge/client/default/js/expressPaymentMethodsVisibility.js new file mode 100644 index 000000000..18efb6cfc --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/client/default/js/expressPaymentMethodsVisibility.js @@ -0,0 +1,46 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(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 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); }); }; } +var _require = require('./commons'), + checkIfExpressMethodsAreReady = _require.checkIfExpressMethodsAreReady; +function handleExpressPaymentsVisibility() { + return _handleExpressPaymentsVisibility.apply(this, arguments); +} +function _handleExpressPaymentsVisibility() { + _handleExpressPaymentsVisibility = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var _window, expressMethodsOrder, sortOrder, container, toSort; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _window = window, expressMethodsOrder = _window.expressMethodsOrder; + if (expressMethodsOrder) { + sortOrder = expressMethodsOrder.split(','); + container = document.getElementById('express-container'); + toSort = Array.prototype.slice.call(container.children, 0); + toSort.sort(function (a, b) { + return sortOrder.indexOf(a.dataset.method) - sortOrder.indexOf(b.dataset.method); + }); + container.innerHTML = ''; + _toConsumableArray(toSort).map(function (node) { + return container.appendChild(node); + }); + } + case 2: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _handleExpressPaymentsVisibility.apply(this, arguments); +} +handleExpressPaymentsVisibility(); +checkIfExpressMethodsAreReady(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/config/countries.json b/cartridges/int_adyen_SFRA/cartridge/config/countries.json new file mode 100644 index 000000000..d9ad44311 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/config/countries.json @@ -0,0 +1,37 @@ +[{ + "id": "en_US", + "currencyCode": "USD" +}, { + "id": "en_GB", + "currencyCode": "GBP" +}, { + "id": "ja_JP", + "currencyCode": "JPY" +}, { + "id": "zh_CN", + "currencyCode": "CNY" +}, { + "id": "fr_FR", + "currencyCode": "EUR" +}, { + "id": "it_IT", + "currencyCode": "EUR" +}, { + "id": "pt_BR", + "currencyCode": "BRL" +}, { + "id": "nb_NO", + "currencyCode": "NOK" +}, { + "id": "da_DK", + "currencyCode": "DKK" +}, { + "id": "sv_SE", + "currencyCode": "SEK" +}, { + "id": "hi_IN", + "currencyCode": "INR" +}, { + "id": "ja_JP", + "currencyCode": "JPY" +}] \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/Account.js b/cartridges/int_adyen_SFRA/cartridge/controllers/Account.js new file mode 100644 index 000000000..ed6de2241 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/Account.js @@ -0,0 +1,19 @@ +"use strict"; + +var server = require('server'); +var _require = require('*/cartridge/scripts/updateSavedCards'), + updateSavedCards = _require.updateSavedCards; +server.extend(module.superModule); +var userLoggedIn = require('*/cartridge/scripts/middleware/userLoggedIn'); +var consentTracking = require('*/cartridge/scripts/middleware/consentTracking'); + +/* + * Prepends Account's 'Show' function to update saved cards. + */ +server.prepend('Show', server.middleware.https, userLoggedIn.validateLoggedIn, consentTracking.consent, function (req, res, next) { + updateSavedCards({ + CurrentCustomer: req.currentCustomer.raw + }); + next(); +}); +module.exports = server.exports(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/Adyen.js b/cartridges/int_adyen_SFRA/cartridge/controllers/Adyen.js new file mode 100644 index 000000000..f0a463bc1 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/Adyen.js @@ -0,0 +1,92 @@ +"use strict"; + +var server = require('server'); +var consentTracking = require('*/cartridge/scripts/middleware/consentTracking'); +var adyenGiving = require('*/cartridge/scripts/adyenGiving'); +var _require = require('*/cartridge/controllers/middlewares/index'), + adyen = _require.adyen; +var EXTERNAL_PLATFORM_VERSION = 'SFRA'; + +/** + * Show confirmation after return from Adyen + */ +server.get('ShowConfirmation', server.middleware.https, adyen.showConfirmation); + +/** + * Confirm payment status after receiving redirectResult from Adyen + */ +server.post('PaymentsDetails', server.middleware.https, consentTracking.consent, adyen.paymentsDetails); +server.get('Sessions', server.middleware.https, adyen.callCreateSession); +server.get('ShippingMethods', server.middleware.https, adyen.callGetShippingMethods); +server.post('SelectShippingMethod', server.middleware.https, adyen.callSelectShippingMethod); + +/** + * Redirect to Adyen after 3DS1 Authentication When adding a card to an account + */ +server.get('Redirect3DS1Response', server.middleware.https, adyen.redirect3ds1Response); + +/** + * Show confirmation for payments completed from component directly e.g. paypal, QRcode, .. + */ +server.post('ShowConfirmationPaymentFromComponent', server.middleware.https, adyen.showConfirmationPaymentFromComponent); + +/** + * Complete a donation through adyenGiving + */ +server.post('Donate', server.middleware.https, function (req /* , res, next */) { + var _req$form = req.form, + orderNo = _req$form.orderNo, + orderToken = _req$form.orderToken; + var donationAmount = { + value: req.form.amountValue, + currency: req.form.amountCurrency + }; + var donationResult = adyenGiving.donate(orderNo, donationAmount, orderToken); + return donationResult.response; +}); + +/** + * Make a payment from inside a component (paypal) + */ +server.post('PaymentFromComponent', server.middleware.https, adyen.paymentFromComponent); + +/** + * Save shopper details that came from an Express component in the SFCC session + */ +server.post('SaveExpressShopperDetails', server.middleware.https, adyen.saveExpressShopperDetails); +server.get('GetPaymentMethods', server.middleware.https, adyen.getCheckoutPaymentMethods); + +/** + * Called by Adyen to update status of payments. It should always display [accepted] when finished. + */ +server.post('Notify', server.middleware.https, adyen.notify); + +/** + * Called by Adyen to check balance of gift card. + */ +server.post('CheckBalance', server.middleware.https, adyen.checkBalance); + +/** + * Called by Adyen to cancel a partial payment order. + */ +server.post('CancelPartialPaymentOrder', server.middleware.https, adyen.cancelPartialPaymentOrder); + +/** + * Called by Adyen to create a partial payments order + */ +server.post('PartialPaymentsOrder', server.middleware.https, adyen.partialPaymentsOrder); + +/** + * Called by Adyen to apply a giftcard + */ +server.post('partialPayment', server.middleware.https, adyen.partialPayment); + +/** + * Called by Adyen to fetch applied giftcards + */ +server.get('fetchGiftCards', server.middleware.https, adyen.fetchGiftCards); +function getExternalPlatformVersion() { + return EXTERNAL_PLATFORM_VERSION; +} +module.exports = server.exports(); +module.exports.getExternalPlatformVersion = getExternalPlatformVersion(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/Checkout.js b/cartridges/int_adyen_SFRA/cartridge/controllers/Checkout.js new file mode 100644 index 000000000..e8927f5c3 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/Checkout.js @@ -0,0 +1,14 @@ +"use strict"; + +var server = require('server'); +var csrfProtection = require('*/cartridge/scripts/middleware/csrf'); +var consentTracking = require('*/cartridge/scripts/middleware/consentTracking'); +var _require = require('*/cartridge/controllers/middlewares/index'), + checkout = _require.checkout; +server.extend(module.superModule); + +/* + * Prepends Checkout's 'Begin' function with Adyen-specific configuration. + */ +server.prepend('Begin', server.middleware.https, consentTracking.consent, csrfProtection.generateToken, checkout.begin); +module.exports = server.exports(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/CheckoutServices.js b/cartridges/int_adyen_SFRA/cartridge/controllers/CheckoutServices.js new file mode 100644 index 000000000..ad6f20b57 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/CheckoutServices.js @@ -0,0 +1,7 @@ +"use strict"; + +var server = require('server'); +server.extend(module.superModule); +var placeOrder = require('*/cartridge/controllers/middlewares/checkout_services/placeOrder'); +server.prepend('PlaceOrder', server.middleware.https, placeOrder); +module.exports = server.exports(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/Order.js b/cartridges/int_adyen_SFRA/cartridge/controllers/Order.js new file mode 100644 index 000000000..936bb846b --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/Order.js @@ -0,0 +1,14 @@ +"use strict"; + +var server = require('server'); +var csrfProtection = require('*/cartridge/scripts/middleware/csrf'); +var consentTracking = require('*/cartridge/scripts/middleware/consentTracking'); +var _require = require('*/cartridge/controllers/middlewares/index'), + order = _require.order; +server.extend(module.superModule); + +/* + * Prepends Order's 'Confirm' function to support Adyen Giving. + */ +server.prepend('Confirm', server.middleware.https, consentTracking.consent, csrfProtection.generateToken, order.confirm); +module.exports = server.exports(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/PaymentInstruments.js b/cartridges/int_adyen_SFRA/cartridge/controllers/PaymentInstruments.js new file mode 100644 index 000000000..68f831841 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/PaymentInstruments.js @@ -0,0 +1,51 @@ +"use strict"; + +var server = require('server'); +server.extend(module.superModule); +var userLoggedIn = require('*/cartridge/scripts/middleware/userLoggedIn'); +var consentTracking = require('*/cartridge/scripts/middleware/consentTracking'); +var csrfProtection = require('*/cartridge/scripts/middleware/csrf'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var _require = require('*/cartridge/scripts/updateSavedCards'), + updateSavedCards = _require.updateSavedCards; +var _require2 = require('*/cartridge/controllers/middlewares/index'), + paymentInstruments = _require2.paymentInstruments; + +/* + * Prepends PaymentInstruments' 'List' function to list saved cards. + */ +server.prepend('List', userLoggedIn.validateLoggedIn, consentTracking.consent, function (req, res, next) { + updateSavedCards({ + CurrentCustomer: req.currentCustomer.raw + }); + next(); +}); + +/* + * Prepends PaymentInstruments' 'AddPayment' function to pass Adyen-specific configurations. + */ +server.prepend('AddPayment', csrfProtection.generateToken, consentTracking.consent, userLoggedIn.validateLoggedIn, function (req, res, next) { + var clientKey = AdyenConfigs.getAdyenClientKey(); + var environment = AdyenHelper.getCheckoutEnvironment(); + var viewData = res.getViewData(); + viewData.adyen = { + clientKey: clientKey, + environment: environment + }; + res.setViewData(viewData); + next(); +}); + +/* + * Prepends PaymentInstruments' 'SavePayment' function to handle saving a payment instrument + * when the selected payment processor is Adyen. + */ +server.prepend('SavePayment', csrfProtection.validateAjaxRequest, paymentInstruments.savePayment); + +/* + * Prepends PaymentInstruments' 'DeletePayment' function to handle deleting a payment instrument + * when the selected payment processor is Adyen. + */ +server.append('DeletePayment', userLoggedIn.validateLoggedInAjax, paymentInstruments.deletePayment); +module.exports = server.exports(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/RedirectURL.js b/cartridges/int_adyen_SFRA/cartridge/controllers/RedirectURL.js new file mode 100644 index 000000000..05416eecf --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/RedirectURL.js @@ -0,0 +1,18 @@ +"use strict"; + +var server = require('server'); +var URLRedirectMgr = require('dw/web/URLRedirectMgr'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var constants = require('../client/default/js/constants'); +server.extend(module.superModule); +server.prepend('Start', function (req, res, next) { + var origin = URLRedirectMgr.redirectOrigin; + // Intercept the incoming path request + if (origin.match(constants.APPLE_DOMAIN_URL)) { + var applePayDomainAssociation = AdyenConfigs.getApplePayDomainAssociation(); + response.getWriter().print(applePayDomainAssociation); + return null; + } + return next(); +}); +module.exports = server.exports(); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/cancelPartialPaymentOrder.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/cancelPartialPaymentOrder.js new file mode 100644 index 000000000..0807c4815 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/cancelPartialPaymentOrder.js @@ -0,0 +1,60 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var BasketMgr = require('dw/order/BasketMgr'); +var Transaction = require('dw/system/Transaction'); +var Resource = require('dw/web/Resource'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var collections = require('*/cartridge/scripts/util/collections'); +var constants = require('*/cartridge/adyenConstants/constants'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +var _require = require('*/cartridge/controllers/utils/index'), + clearForms = _require.clearForms; +function cancelPartialPaymentOrder(req, res, next) { + try { + var currentBasket = BasketMgr.getCurrentBasket(); + var request = JSON.parse(req.body); + var partialPaymentsOrder = request.partialPaymentsOrder; + var cancelOrderRequest = { + merchantAccount: AdyenConfigs.getAdyenMerchantAccount(), + order: partialPaymentsOrder + }; + var response = adyenCheckout.doCancelPartialPaymentOrderCall(cancelOrderRequest); + if (response.resultCode === constants.RESULTCODES.RECEIVED) { + Transaction.wrap(function () { + collections.forEach(currentBasket.getPaymentInstruments(), function (item) { + if (item.custom.adyenPartialPaymentsOrder) { + currentBasket.removePaymentInstrument(item); + } + }); + clearForms.clearAdyenBasketData(currentBasket); + }); + session.privacy.giftCardResponse = null; + session.privacy.partialPaymentData = null; + } else { + throw new Error("received resultCode ".concat(response.resultCode)); + } + var amount = { + currency: currentBasket.currencyCode, + value: AdyenHelper.getCurrencyValueForApi(currentBasket.getTotalGrossPrice()).value + }; + res.json(_objectSpread(_objectSpread({}, response), {}, { + amount: amount + })); + } catch (error) { + AdyenLogs.error_log("Could not cancel partial payments order.. ".concat(error.toString())); + res.json({ + error: true, + errorMessage: Resource.msg('error.technical', 'checkout', null) + }); + } + return next(); +} +module.exports = cancelPartialPaymentOrder; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/checkBalance.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/checkBalance.js new file mode 100644 index 000000000..d3c93ccbc --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/checkBalance.js @@ -0,0 +1,69 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var BasketMgr = require('dw/order/BasketMgr'); +var Money = require('dw/value/Money'); +var OrderMgr = require('dw/order/OrderMgr'); +var Transaction = require('dw/system/Transaction'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var constants = require('*/cartridge/adyenConstants/constants'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +function getFormattedProperties(checkBalanceResponse, orderAmount) { + if (checkBalanceResponse.resultCode === 'Success') { + var remainingAmount = new Money(0, checkBalanceResponse.balance.currency); + var remainingDivideBy = AdyenHelper.getDivisorForCurrency(remainingAmount); + var remainingAmountFormatted = remainingAmount.divide(remainingDivideBy).toFormattedString(); + var totalAmount = new Money(orderAmount.value, orderAmount.currency); + var totalDivideBy = AdyenHelper.getDivisorForCurrency(totalAmount); + var totalAmountFormatted = totalAmount.divide(totalDivideBy).toFormattedString(); + return { + remainingAmountFormatted: remainingAmountFormatted, + totalAmountFormatted: totalAmountFormatted + }; + } + return {}; +} +function getAddedGiftCards(basket) { + var _basket$custom; + return (_basket$custom = basket.custom) !== null && _basket$custom !== void 0 && _basket$custom.adyenGiftCards ? JSON.parse(basket.custom.adyenGiftCards) : null; +} +function callCheckBalance(req, res, next) { + try { + var _currentBasket$custom; + var currentBasket = BasketMgr.getCurrentBasket(); + var orderNo = ((_currentBasket$custom = currentBasket.custom) === null || _currentBasket$custom === void 0 ? void 0 : _currentBasket$custom.adyenGiftCardsOrderNo) || OrderMgr.createOrderNo(); + var giftCardsAdded = getAddedGiftCards(currentBasket); + var orderAmount = { + currency: currentBasket.currencyCode, + value: AdyenHelper.getCurrencyValueForApi(currentBasket.getTotalGrossPrice()).value + }; + var amount = giftCardsAdded ? giftCardsAdded[giftCardsAdded.length - 1].remainingAmount : orderAmount; + var request = JSON.parse(req.body); + var paymentMethod = request.paymentMethod ? request.paymentMethod : constants.ACTIONTYPES.GIFTCARD; + var checkBalanceRequest = { + merchantAccount: AdyenConfigs.getAdyenMerchantAccount(), + amount: amount, + reference: orderNo, + paymentMethod: paymentMethod + }; + var checkBalanceResponse = adyenCheckout.doCheckBalanceCall(checkBalanceRequest); + Transaction.wrap(function () { + currentBasket.custom.adyenGiftCardsOrderNo = orderNo; + }); + res.json(_objectSpread(_objectSpread({}, checkBalanceResponse), getFormattedProperties(checkBalanceResponse, orderAmount))); + } catch (error) { + AdyenLogs.error_log("Failed to check gift card balance ".concat(error.toString())); + res.json({ + error: true + }); + } + return next(); +} +module.exports = callCheckBalance; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/fetchGiftCards.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/fetchGiftCards.js new file mode 100644 index 000000000..4b040f4a4 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/fetchGiftCards.js @@ -0,0 +1,37 @@ +"use strict"; + +var BasketMgr = require('dw/order/BasketMgr'); +var Money = require('dw/value/Money'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +var _require = require('*/cartridge/controllers/utils/index'), + clearForms = _require.clearForms; +function fetchGiftCards(req, res, next) { + try { + var _currentBasket$custom; + var currentBasket = BasketMgr.getCurrentBasket(); + var addedGiftCards = currentBasket !== null && currentBasket !== void 0 && (_currentBasket$custom = currentBasket.custom) !== null && _currentBasket$custom !== void 0 && _currentBasket$custom.adyenGiftCards ? JSON.parse(currentBasket.custom.adyenGiftCards) : []; + var totalDiscountedAmount = null; + if (addedGiftCards !== null && addedGiftCards !== void 0 && addedGiftCards.length) { + var divideBy = AdyenHelper.getDivisorForCurrency({ + currencyCode: currentBasket.currencyCode + }); + totalDiscountedAmount = new Money(addedGiftCards.reduce(function (accumulator, currentValue) { + return accumulator + currentValue.giftCard.amount.value; + }, 0), addedGiftCards[addedGiftCards.length - 1].giftCard.amount.currency).divide(divideBy).toFormattedString(); + } + res.json({ + giftCards: addedGiftCards, + totalDiscountedAmount: totalDiscountedAmount + }); + } catch (error) { + AdyenLogs.error_log("Failed to fetch gift cards ".concat(error.toString())); + var _currentBasket = BasketMgr.getCurrentBasket(); + clearForms.clearAdyenBasketData(_currentBasket); + res.json({ + error: true + }); + } + return next(); +} +module.exports = fetchGiftCards; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/getCheckoutPaymentMethods.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/getCheckoutPaymentMethods.js new file mode 100644 index 000000000..a5c305a21 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/getCheckoutPaymentMethods.js @@ -0,0 +1,24 @@ +"use strict"; + +var BasketMgr = require('dw/order/BasketMgr'); +var Locale = require('dw/util/Locale'); +var getPaymentMethods = require('*/cartridge/scripts/adyenGetPaymentMethods'); +function getCheckoutPaymentMethods(req, res, next) { + var countryCode = Locale.getLocale(req.locale.id).country; + var currentBasket = BasketMgr.getCurrentBasket(); + if (currentBasket.getShipments().length > 0 && currentBasket.getShipments()[0].shippingAddress) { + countryCode = currentBasket.getShipments()[0].shippingAddress.getCountryCode(); + } + var paymentMethods; + try { + var _countryCode$value; + paymentMethods = getPaymentMethods.getMethods(BasketMgr.getCurrentBasket(), ((_countryCode$value = countryCode.value) === null || _countryCode$value === void 0 ? void 0 : _countryCode$value.toString()) || countryCode.value).paymentMethods; + } catch (err) { + paymentMethods = []; + } + res.json({ + AdyenPaymentMethods: paymentMethods + }); + return next(); +} +module.exports = getCheckoutPaymentMethods; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/index.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/index.js new file mode 100644 index 000000000..4d6796922 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/index.js @@ -0,0 +1,36 @@ +"use strict"; + +var showConfirmation = require('*/cartridge/controllers/middlewares/adyen/showConfirmation'); +var paymentFromComponent = require('*/cartridge/controllers/middlewares/adyen/paymentFromComponent'); +var notify = require('*/cartridge/controllers/middlewares/adyen/notify'); +var showConfirmationPaymentFromComponent = require('*/cartridge/controllers/middlewares/adyen/showConfirmationPaymentFromComponent'); +var paymentsDetails = require('*/cartridge/controllers/middlewares/adyen/paymentsDetails'); +var redirect3ds1Response = require('*/cartridge/controllers/middlewares/adyen/redirect3ds1Response'); +var callCreateSession = require('*/cartridge/controllers/middlewares/adyen/sessions'); +var checkBalance = require('*/cartridge/controllers/middlewares/adyen/checkBalance'); +var cancelPartialPaymentOrder = require('*/cartridge/controllers/middlewares/adyen/cancelPartialPaymentOrder'); +var partialPaymentsOrder = require('*/cartridge/controllers/middlewares/adyen/partialPaymentsOrder'); +var partialPayment = require('*/cartridge/controllers/middlewares/adyen/partialPayment'); +var callGetShippingMethods = require('*/cartridge/controllers/middlewares/adyen/shippingMethods'); +var callSelectShippingMethod = require('*/cartridge/controllers/middlewares/adyen/selectShippingMethods'); +var fetchGiftCards = require('*/cartridge/controllers/middlewares/adyen/fetchGiftCards'); +var saveExpressShopperDetails = require('*/cartridge/controllers/middlewares/adyen/saveExpressShopperDetails'); +var getCheckoutPaymentMethods = require('*/cartridge/controllers/middlewares/adyen/getCheckoutPaymentMethods'); +module.exports = { + showConfirmation: showConfirmation, + paymentFromComponent: paymentFromComponent, + notify: notify, + showConfirmationPaymentFromComponent: showConfirmationPaymentFromComponent, + paymentsDetails: paymentsDetails, + redirect3ds1Response: redirect3ds1Response, + callCreateSession: callCreateSession, + checkBalance: checkBalance, + cancelPartialPaymentOrder: cancelPartialPaymentOrder, + partialPaymentsOrder: partialPaymentsOrder, + partialPayment: partialPayment, + callGetShippingMethods: callGetShippingMethods, + callSelectShippingMethod: callSelectShippingMethod, + fetchGiftCards: fetchGiftCards, + saveExpressShopperDetails: saveExpressShopperDetails, + getCheckoutPaymentMethods: getCheckoutPaymentMethods +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/notify.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/notify.js new file mode 100644 index 000000000..ec8296044 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/notify.js @@ -0,0 +1,39 @@ +"use strict"; + +var Transaction = require('dw/system/Transaction'); +var checkAuth = require('*/cartridge/scripts/checkNotificationAuth'); +var handleNotify = require('*/cartridge/scripts/handleNotify'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); + +/** + * Called by Adyen to update status of payments. It should always display [accepted] when finished. + */ + +function handleHmacVerification(hmacKey, req) { + if (hmacKey) { + return checkAuth.validateHmacSignature(req); + } + return true; +} +function notify(req, res, next) { + var status = checkAuth.check(req); + var hmacKey = AdyenConfigs.getAdyenHmacKey(); + var isHmacValid = handleHmacVerification(hmacKey, req); + if (!status || !isHmacValid) { + res.render('/adyen/error'); + return {}; + } + Transaction.begin(); + var notificationResult = handleNotify.notify(req.form); + if (notificationResult.success) { + Transaction.commit(); + res.render('/notify'); + } else { + res.render('/notifyError', { + errorMessage: notificationResult.errorMessage + }); + Transaction.rollback(); + } + return next(); +} +module.exports = notify; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/partialPayment.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/partialPayment.js new file mode 100644 index 000000000..3503be928 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/partialPayment.js @@ -0,0 +1,109 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var Transaction = require('dw/system/Transaction'); +var Money = require('dw/value/Money'); +var BasketMgr = require('dw/order/BasketMgr'); +var Resource = require('dw/web/Resource'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +var constants = require('*/cartridge/adyenConstants/constants'); +function responseContainsErrors(response) { + return (response === null || response === void 0 ? void 0 : response.error) || (response === null || response === void 0 ? void 0 : response.resultCode) !== constants.RESULTCODES.AUTHORISED; +} +function makePartialPayment(req, res, next) { + try { + var _response$order, _response$order2, _response$order3, _currentBasket$custom, _currentBasket$custom2; + var request = JSON.parse(req.body); + var currentBasket = BasketMgr.getCurrentBasket(); + var paymentMethod = request.paymentMethod, + partialPaymentsOrder = request.partialPaymentsOrder, + amount = request.amount, + giftcardBrand = request.giftcardBrand; + var partialPaymentRequest = { + merchantAccount: AdyenConfigs.getAdyenMerchantAccount(), + amount: amount, + reference: currentBasket.custom.adyenGiftCardsOrderNo, + paymentMethod: paymentMethod, + order: partialPaymentsOrder + }; + var response = adyenCheckout.doPaymentsCall(null, null, partialPaymentRequest); // no order created yet and no PI needed (for giftcards it will be created on Order level) + + if (responseContainsErrors(response)) { + var errorMsg = "partial payment request did not go through .. resultCode: ".concat(response === null || response === void 0 ? void 0 : response.resultCode); + throw new Error(errorMsg); + } + Transaction.wrap(function () { + session.privacy.giftCardResponse = JSON.stringify(_objectSpread(_objectSpread(_objectSpread({ + giftCardpspReference: response.pspReference, + orderPSPReference: response.order.pspReference + }, response.order), response.amount), {}, { + paymentMethod: response.paymentMethod, + brand: giftcardBrand + })); // entire response exceeds string length + }); + + var discountAmount = new Money(response.amount.value, response.amount.currency); + var remainingAmount = new Money(response.order.remainingAmount.value, response.order.remainingAmount.currency); + + // Update cached session data + var partialPaymentsOrderData = JSON.parse(session.privacy.partialPaymentData); + partialPaymentsOrderData.order = { + orderData: response === null || response === void 0 ? void 0 : (_response$order = response.order) === null || _response$order === void 0 ? void 0 : _response$order.orderData, + pspReference: response === null || response === void 0 ? void 0 : (_response$order2 = response.order) === null || _response$order2 === void 0 ? void 0 : _response$order2.pspReference + }; + partialPaymentsOrderData.remainingAmount = response === null || response === void 0 ? void 0 : (_response$order3 = response.order) === null || _response$order3 === void 0 ? void 0 : _response$order3.remainingAmount; + session.privacy.partialPaymentData = JSON.stringify(partialPaymentsOrderData); + var divideBy = AdyenHelper.getDivisorForCurrency(remainingAmount); + var remainingAmountFormatted = remainingAmount.divide(divideBy).toFormattedString(); + response.remainingAmountFormatted = remainingAmountFormatted; + var discountAmountFormatted = discountAmount.divide(divideBy).toFormattedString(); + response.discountAmountFormatted = discountAmountFormatted; + var addedGiftCards = currentBasket !== null && currentBasket !== void 0 && (_currentBasket$custom = currentBasket.custom) !== null && _currentBasket$custom !== void 0 && _currentBasket$custom.adyenGiftCards ? JSON.parse((_currentBasket$custom2 = currentBasket.custom) === null || _currentBasket$custom2 === void 0 ? void 0 : _currentBasket$custom2.adyenGiftCards) : []; + var dataToStore = { + discountedAmount: discountAmountFormatted, + expiresAt: response.order.expiresAt, + giftCard: _objectSpread(_objectSpread({}, response.paymentMethod), {}, { + amount: response.amount, + name: giftcardBrand, + pspReference: response.pspReference + }), + orderAmount: { + currency: currentBasket.currencyCode, + value: AdyenHelper.getCurrencyValueForApi(currentBasket.getTotalGrossPrice()).value + }, + partialPaymentsOrder: { + orderData: response.order.orderData, + pspReference: response.order.pspReference + }, + remainingAmount: response.order.remainingAmount, + remainingAmountFormatted: remainingAmountFormatted + }; + addedGiftCards.push(dataToStore); + Transaction.wrap(function () { + currentBasket.custom.adyenGiftCards = JSON.stringify(addedGiftCards); + }); + var totalDiscountedAmount = new Money(addedGiftCards.reduce(function (accumulator, currentValue) { + return accumulator + currentValue.giftCard.amount.value; + }, 0), response.order.remainingAmount.currency); + res.json(_objectSpread(_objectSpread({}, dataToStore), {}, { + totalDiscountedAmount: totalDiscountedAmount.divide(divideBy).toFormattedString(), + giftCards: addedGiftCards, + message: Resource.msgf('infoMessage.giftCard', 'adyen', null, remainingAmountFormatted) + })); + } catch (error) { + AdyenLogs.error_log("Failed to create partial payment.. ".concat(error.toString())); + res.json({ + error: true + }); + } + return next(); +} +module.exports = makePartialPayment; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/partialPaymentsOrder.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/partialPaymentsOrder.js new file mode 100644 index 000000000..7b5f58308 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/partialPaymentsOrder.js @@ -0,0 +1,59 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var BasketMgr = require('dw/order/BasketMgr'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var constants = require('*/cartridge/adyenConstants/constants'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +function addMinutes(minutes) { + var date = new Date(); + return new Date(date.getTime() + minutes * 60000); +} +function createPartialPaymentsOrder(req, res, next) { + try { + var _currentBasket$custom; + var currentBasket = BasketMgr.getCurrentBasket(); + var giftCardsAdded = (_currentBasket$custom = currentBasket.custom) !== null && _currentBasket$custom !== void 0 && _currentBasket$custom.adyenGiftCards ? JSON.parse(currentBasket.custom.adyenGiftCards) : null; + var orderAmount = { + currency: currentBasket.currencyCode, + value: AdyenHelper.getCurrencyValueForApi(currentBasket.getTotalGrossPrice()).value + }; + var amount = giftCardsAdded ? giftCardsAdded[giftCardsAdded.length - 1].remainingAmount : orderAmount; + var date = addMinutes(constants.GIFTCARD_EXPIRATION_MINUTES); + var partialPaymentsRequest = { + amount: amount, + merchantAccount: AdyenConfigs.getAdyenMerchantAccount(), + reference: currentBasket.custom.adyenGiftCardsOrderNo, + expiresAt: date.toISOString() + }; + var response = adyenCheckout.doCreatePartialPaymentOrderCall(partialPaymentsRequest); + + // Cache order data to reuse at payments + session.privacy.partialPaymentData = JSON.stringify({ + order: { + orderData: response === null || response === void 0 ? void 0 : response.orderData, + pspReference: response === null || response === void 0 ? void 0 : response.pspReference + }, + remainingAmount: response === null || response === void 0 ? void 0 : response.remainingAmount, + amount: orderAmount + }); + var responseData = _objectSpread(_objectSpread({}, response), {}, { + expiresAt: date.toISOString() + }); + res.json(responseData); + } catch (error) { + AdyenLogs.error_log("Failed to create partial payments order.. ".concat(error.toString())); + res.json({ + error: true + }); + } + return next(); +} +module.exports = createPartialPaymentsOrder; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/paymentFromComponent.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/paymentFromComponent.js new file mode 100644 index 000000000..94f0240be --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/paymentFromComponent.js @@ -0,0 +1,174 @@ +"use strict"; + +var BasketMgr = require('dw/order/BasketMgr'); +var PaymentMgr = require('dw/order/PaymentMgr'); +var Transaction = require('dw/system/Transaction'); +var OrderMgr = require('dw/order/OrderMgr'); +var URLUtils = require('dw/web/URLUtils'); +var Money = require('dw/value/Money'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers'); +var constants = require('*/cartridge/adyenConstants/constants'); +var collections = require('*/cartridge/scripts/util/collections'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +var GiftCardsHelper = require('*/cartridge/scripts/util/giftCardsHelper'); +var expressMethods = ['applepay', 'amazonpay']; +function setBillingAndShippingAddress(reqDataObj, currentBasket) { + var billingAddress = currentBasket.billingAddress; + var _currentBasket$getDef = currentBasket.getDefaultShipment(), + shippingAddress = _currentBasket$getDef.shippingAddress; + Transaction.wrap(function () { + if (!shippingAddress) { + shippingAddress = currentBasket.getDefaultShipment().createShippingAddress(); + } + if (!billingAddress) { + billingAddress = currentBasket.createBillingAddress(); + } + }); + var shopperDetails = reqDataObj.customer; + Transaction.wrap(function () { + billingAddress.setFirstName(shopperDetails.billingAddressDetails.firstName); + billingAddress.setLastName(shopperDetails.billingAddressDetails.lastName); + billingAddress.setPhone(shopperDetails.profile.phone); + billingAddress.setAddress1(shopperDetails.billingAddressDetails.address1); + billingAddress.setCity(shopperDetails.billingAddressDetails.city); + billingAddress.setCountryCode(shopperDetails.billingAddressDetails.countryCode.value); + if (shopperDetails.billingAddressDetails.address2) { + billingAddress.setAddress2(shopperDetails.billingAddressDetails.address2); + } + if (shopperDetails.billingAddressDetails.stateCode) { + billingAddress.setStateCode(shopperDetails.billingAddressDetails.stateCode); + } + currentBasket.setCustomerEmail(shopperDetails.profile.email); + shippingAddress.setFirstName(shopperDetails.profile.firstName); + shippingAddress.setLastName(shopperDetails.profile.lastName); + shippingAddress.setPhone(shopperDetails.profile.phone); + shippingAddress.setAddress1(shopperDetails.addressBook.preferredAddress.address1); + shippingAddress.setCity(shopperDetails.addressBook.preferredAddress.city); + shippingAddress.setCountryCode(shopperDetails.addressBook.preferredAddress.countryCode.value); + if (shopperDetails.addressBook.preferredAddress.address2) { + shippingAddress.setAddress2(shopperDetails.addressBook.preferredAddress.address2); + } + if (shopperDetails.addressBook.preferredAddress.stateCode) { + shippingAddress.setStateCode(shopperDetails.addressBook.preferredAddress.stateCode); + } + }); +} +function failOrder(order) { + Transaction.wrap(function () { + OrderMgr.failOrder(order, true); + }); +} +function handleGiftCardPayment(currentBasket, order) { + var _currentBasket$custom; + var giftCards = (_currentBasket$custom = currentBasket.custom) !== null && _currentBasket$custom !== void 0 && _currentBasket$custom.adyenGiftCards ? JSON.parse(currentBasket.custom.adyenGiftCards) : null; + if (giftCards) { + var mainPaymentInstrument = order.getPaymentInstruments(AdyenHelper.getOrderMainPaymentInstrumentType(order))[0]; + giftCards.forEach(function (giftCard) { + var divideBy = AdyenHelper.getDivisorForCurrency(mainPaymentInstrument.paymentTransaction.getAmount()); + var amount = { + value: giftCard.remainingAmount.value, + currency: giftCard.remainingAmount.currency + }; + var formattedAmount = new Money(amount.value, amount.currency).divide(divideBy); + Transaction.wrap(function () { + mainPaymentInstrument.paymentTransaction.setAmount(formattedAmount); + }); + GiftCardsHelper.createGiftCardPaymentInstrument(giftCard, divideBy, order); + }); + } +} +function handleCancellation(res, next, reqDataObj) { + AdyenLogs.info_log("Shopper cancelled paymentFromComponent transaction for order ".concat(reqDataObj.merchantReference)); + var order = OrderMgr.getOrder(reqDataObj.merchantReference, reqDataObj.orderToken); + failOrder(order); + res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'placeOrder')); + return next(); +} +function handleRefusedResultCode(result, reqDataObj, order) { + AdyenLogs.error_log("Payment refused for order ".concat(order.orderNo)); + result.paymentError = true; + + // Decline flow for Amazonpay or Applepay is handled different from other Component PMs + // Order needs to be failed here to handle decline flow. + if (expressMethods.indexOf(reqDataObj.paymentMethod) > -1) { + failOrder(order); + } +} +function isExpressPayment(reqDataObj) { + return reqDataObj.paymentType === 'express'; +} +function handleExpressPayment(reqDataObj, currentBasket) { + if (isExpressPayment(reqDataObj)) { + setBillingAndShippingAddress(reqDataObj, currentBasket); + } +} +function canSkipSummaryPage(reqDataObj) { + var _reqDataObj$paymentMe; + if (constants.CAN_SKIP_SUMMARY_PAGE.indexOf((_reqDataObj$paymentMe = reqDataObj.paymentMethod) === null || _reqDataObj$paymentMe === void 0 ? void 0 : _reqDataObj$paymentMe.type) >= 0) { + return true; + } + return false; +} + +/** + * Make a payment from inside a component, skipping the summary page. (paypal, QRcodes, MBWay) + */ +function paymentFromComponent(req, res, next) { + var _currentBasket$custom2; + var reqDataObj = JSON.parse(req.form.data); + if (reqDataObj.cancelTransaction) { + return handleCancellation(res, next, reqDataObj); + } + var currentBasket = BasketMgr.getCurrentBasket(); + var paymentInstrument; + Transaction.wrap(function () { + collections.forEach(currentBasket.getPaymentInstruments(), function (item) { + currentBasket.removePaymentInstrument(item); + }); + paymentInstrument = currentBasket.createPaymentInstrument(constants.METHOD_ADYEN_COMPONENT, currentBasket.totalGrossPrice); + var _PaymentMgr$getPaymen = PaymentMgr.getPaymentMethod(paymentInstrument.paymentMethod), + paymentProcessor = _PaymentMgr$getPaymen.paymentProcessor; + paymentInstrument.paymentTransaction.paymentProcessor = paymentProcessor; + paymentInstrument.custom.adyenPaymentData = req.form.data; + if (reqDataObj.partialPaymentsOrder) { + paymentInstrument.custom.adyenPartialPaymentsOrder = session.privacy.partialPaymentData; + } + paymentInstrument.custom.adyenPaymentMethod = AdyenHelper.getAdyenComponentType(req.form.paymentMethod); + paymentInstrument.custom["".concat(constants.OMS_NAMESPACE, "__Adyen_Payment_Method")] = AdyenHelper.getAdyenComponentType(req.form.paymentMethod); + paymentInstrument.custom.Adyen_Payment_Method_Variant = req.form.paymentMethod.toLowerCase(); + paymentInstrument.custom["".concat(constants.OMS_NAMESPACE, "__Adyen_Payment_Method_Variant")] = req.form.paymentMethod.toLowerCase(); + }); + handleExpressPayment(reqDataObj, currentBasket); + var order; + // Check if gift card was used + if ((_currentBasket$custom2 = currentBasket.custom) !== null && _currentBasket$custom2 !== void 0 && _currentBasket$custom2.adyenGiftCards) { + var giftCardsOrderNo = currentBasket.custom.adyenGiftCardsOrderNo; + order = OrderMgr.createOrder(currentBasket, giftCardsOrderNo); + handleGiftCardPayment(currentBasket, order); + } else { + order = COHelpers.createOrder(currentBasket); + } + session.privacy.orderNo = order.orderNo; + var result; + Transaction.wrap(function () { + result = adyenCheckout.createPaymentRequest({ + Order: order, + PaymentInstrument: paymentInstrument + }); + }); + currentBasket.custom.amazonExpressShopperDetails = null; + currentBasket.custom.adyenGiftCardsOrderNo = null; + if (result.resultCode === constants.RESULTCODES.REFUSED) { + handleRefusedResultCode(result, reqDataObj, order); + } + + // Check if summary page can be skipped in case payment is already authorized + result.skipSummaryPage = canSkipSummaryPage(reqDataObj); + result.orderNo = order.orderNo; + result.orderToken = order.orderToken; + res.json(result); + return next(); +} +module.exports = paymentFromComponent; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/paymentsDetails.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/paymentsDetails.js new file mode 100644 index 000000000..4f92ece14 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/paymentsDetails.js @@ -0,0 +1,56 @@ +"use strict"; + +var URLUtils = require('dw/web/URLUtils'); +var OrderMgr = require('dw/order/OrderMgr'); +var Transaction = require('dw/system/Transaction'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +function getSignature(paymentsDetailsResponse, orderToken) { + var order = OrderMgr.getOrder(paymentsDetailsResponse.merchantReference, orderToken); + if (order) { + var paymentInstruments = order.getPaymentInstruments(AdyenHelper.getOrderMainPaymentInstrumentType(order)); + var signature = AdyenHelper.createSignature(paymentInstruments[0], order.getUUID(), paymentsDetailsResponse.merchantReference); + Transaction.wrap(function () { + paymentInstruments[0].paymentTransaction.custom.Adyen_authResult = JSON.stringify(paymentsDetailsResponse); + }); + return signature; + } + return undefined; +} + +/* + * Makes a payment details call to Adyen to confirm the current status of a payment + */ +function paymentsDetails(req, res, next) { + try { + var _request$data; + var request = JSON.parse(req.body); + var isAmazonpay = (request === null || request === void 0 ? void 0 : (_request$data = request.data) === null || _request$data === void 0 ? void 0 : _request$data.paymentMethod) === 'amazonpay'; + if (request.data) { + request.data.paymentMethod = undefined; + } + var paymentsDetailsResponse = adyenCheckout.doPaymentsDetailsCall(request.data); + var response = AdyenHelper.createAdyenCheckoutResponse(paymentsDetailsResponse); + + // Create signature to verify returnUrl + var signature = getSignature(paymentsDetailsResponse, request.orderToken); + if (isAmazonpay) { + response.fullResponse = { + pspReference: paymentsDetailsResponse.pspReference, + paymentMethod: paymentsDetailsResponse.additionalData.paymentMethod, + resultCode: paymentsDetailsResponse.resultCode + }; + } + if (signature !== null) { + response.redirectUrl = URLUtils.https('Adyen-ShowConfirmation', 'merchantReference', response.merchantReference, 'signature', signature, 'orderToken', request.orderToken).toString(); + } + res.json(response); + return next(); + } catch (e) { + AdyenLogs.error_log("Could not verify /payment/details: ".concat(e.toString(), " in ").concat(e.fileName, ":").concat(e.lineNumber)); + res.redirect(URLUtils.url('Error-ErrorCode', 'err', 'general')); + return next(); + } +} +module.exports = paymentsDetails; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/redirect3ds1Response.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/redirect3ds1Response.js new file mode 100644 index 000000000..2a92d96cc --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/redirect3ds1Response.js @@ -0,0 +1,32 @@ +"use strict"; + +var URLUtils = require('dw/web/URLUtils'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var constants = require('*/cartridge/adyenConstants/constants'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); + +/* + * Redirects to list of added cards on success. Otherwise redirects to add payment with error + */ +function redirect(req, res, next) { + try { + var redirectResult = req.httpParameterMap.get('redirectResult').stringValue; + var jsonRequest = { + details: { + redirectResult: redirectResult + } + }; + var result = adyenCheckout.doPaymentsDetailsCall(jsonRequest); + if (result.resultCode === constants.RESULTCODES.AUTHORISED) { + res.redirect(URLUtils.url('PaymentInstruments-List')); + } else { + res.redirect(URLUtils.url('PaymentInstruments-AddPayment', 'isAuthorised', 'false')); + } + return next(); + } catch (e) { + AdyenLogs.error_log("Error during 3ds1 response verification: ".concat(e.toString(), " in ").concat(e.fileName, ":").concat(e.lineNumber)); + res.redirect(URLUtils.url('Error-ErrorCode', 'err', 'general')); + return next(); + } +} +module.exports = redirect; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/saveExpressShopperDetails.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/saveExpressShopperDetails.js new file mode 100644 index 000000000..e25a83809 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/saveExpressShopperDetails.js @@ -0,0 +1,63 @@ +"use strict"; + +var URLUtils = require('dw/web/URLUtils'); +var Transaction = require('dw/system/Transaction'); +var BasketMgr = require('dw/order/BasketMgr'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +function setBillingAndShippingAddress(currentBasket) { + var billingAddress = currentBasket.billingAddress; + var _currentBasket$getDef = currentBasket.getDefaultShipment(), + shippingAddress = _currentBasket$getDef.shippingAddress; + Transaction.wrap(function () { + if (!shippingAddress) { + shippingAddress = currentBasket.getDefaultShipment().createShippingAddress(); + } + if (!billingAddress) { + billingAddress = currentBasket.createBillingAddress(); + } + }); + var shopperDetails = JSON.parse(currentBasket.custom.amazonExpressShopperDetails); // apple pay or amazon pay + + Transaction.wrap(function () { + billingAddress.setFirstName(shopperDetails.billingAddress.name.split(' ')[0]); + billingAddress.setLastName(shopperDetails.billingAddress.name.split(' ')[1]); + billingAddress.setAddress1(shopperDetails.billingAddress.addressLine1); + billingAddress.setAddress2(shopperDetails.billingAddress.addressLine2); + billingAddress.setCity(shopperDetails.billingAddress.city); + billingAddress.setPhone(shopperDetails.billingAddress.phoneNumber); + billingAddress.setPostalCode(shopperDetails.billingAddress.postalCode); + billingAddress.setStateCode(shopperDetails.billingAddress.stateOrRegion); + billingAddress.setCountryCode(shopperDetails.billingAddress.countryCode); + shippingAddress.setFirstName(shopperDetails.shippingAddress.name.split(' ')[0]); + shippingAddress.setLastName(shopperDetails.shippingAddress.name.split(' ')[1]); + shippingAddress.setAddress1(shopperDetails.shippingAddress.addressLine1); + shippingAddress.setAddress2(shopperDetails.shippingAddress.addressLine2); + shippingAddress.setCity(shopperDetails.shippingAddress.city); + shippingAddress.setPhone(shopperDetails.shippingAddress.phoneNumber); + shippingAddress.setPostalCode(shopperDetails.shippingAddress.postalCode); + shippingAddress.setStateCode(shopperDetails.shippingAddress.stateOrRegion); + shippingAddress.setCountryCode(shopperDetails.shippingAddress.countryCode); + currentBasket.setCustomerEmail(shopperDetails.buyer.email); + }); +} +function saveExpressShopperDetails(req, res, next) { + try { + var currentBasket = BasketMgr.getCurrentBasket(); + var shopperDetails = JSON.parse(req.form.shopperDetails); + Transaction.wrap(function () { + currentBasket.custom.amazonExpressShopperDetails = JSON.stringify(shopperDetails); + }); + setBillingAndShippingAddress(currentBasket); + var shippingMethods = AdyenHelper.callGetShippingMethods(shopperDetails.shippingAddress); + res.json({ + shippingMethods: shippingMethods + }); + return next(); + } catch (e) { + AdyenLogs.error_log('Could not save amazon express shopper details'); + res.redirect(URLUtils.url('Error-ErrorCode', 'err', 'general')); + return next(); + } +} +module.exports = saveExpressShopperDetails; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/selectShippingMethods.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/selectShippingMethods.js new file mode 100644 index 000000000..074dcb957 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/selectShippingMethods.js @@ -0,0 +1,64 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var BasketMgr = require('dw/order/BasketMgr'); +var Resource = require('dw/web/Resource'); +var Transaction = require('dw/system/Transaction'); +var URLUtils = require('dw/web/URLUtils'); +var CartModel = require('*/cartridge/models/cart'); +var shippingHelper = require('*/cartridge/scripts/checkout/shippingHelpers'); +var basketCalculationHelpers = require('*/cartridge/scripts/helpers/basketCalculationHelpers'); + +/** + * Make a request to Adyen to select shipping methods + */ +// eslint-disable-next-line complexity +function callSelectShippingMethod(req, res, next) { + var currentBasket = BasketMgr.getCurrentBasket(); + if (!currentBasket) { + res.json({ + error: true, + redirectUrl: URLUtils.url('Cart-Show').toString() + }); + return next(); + } + var error = false; + var shipUUID = req.querystring.shipmentUUID || req.form.shipmentUUID; + var methodID = req.querystring.methodID || req.form.methodID; + var shipment; + if (shipUUID) { + shipment = shippingHelper.getShipmentByUUID(currentBasket, shipUUID); + } else { + shipment = currentBasket.defaultShipment; + } + Transaction.wrap(function () { + shippingHelper.selectShippingMethod(shipment, methodID); + if (currentBasket && !shipment.shippingMethod) { + error = true; + return; + } + basketCalculationHelpers.calculateTotals(currentBasket); + }); + if (!error) { + var basketModel = new CartModel(currentBasket); + var grandTotalAmount = { + value: currentBasket.getTotalGrossPrice().value, + currency: currentBasket.getTotalGrossPrice().currencyCode + }; + res.json(_objectSpread(_objectSpread({}, basketModel), {}, { + grandTotalAmount: grandTotalAmount + })); + } else { + res.setStatusCode(500); + res.json({ + errorMessage: Resource.msg('error.cannot.select.shipping.method', 'cart', null) + }); + } + return next(); +} +module.exports = callSelectShippingMethod; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/sessions.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/sessions.js new file mode 100644 index 000000000..96e669670 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/sessions.js @@ -0,0 +1,52 @@ +"use strict"; + +var BasketMgr = require('dw/order/BasketMgr'); +var Locale = require('dw/util/Locale'); +var PaymentMgr = require('dw/order/PaymentMgr'); +var _require = require('*/cartridge/scripts/adyenSessions'), + createSession = _require.createSession; +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var adyenTerminalApi = require('*/cartridge/scripts/adyenTerminalApi'); +var constants = require('*/cartridge/adyenConstants/constants'); +var paymentMethodDescriptions = require('*/cartridge/adyenConstants/paymentMethodDescriptions'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +function getCountryCode(currentBasket, locale) { + var _currentBasket$getShi; + var countryCode = Locale.getLocale(locale.id).country; + var firstItem = currentBasket === null || currentBasket === void 0 ? void 0 : (_currentBasket$getShi = currentBasket.getShipments()) === null || _currentBasket$getShi === void 0 ? void 0 : _currentBasket$getShi[0]; + if (firstItem !== null && firstItem !== void 0 && firstItem.shippingAddress) { + return firstItem.shippingAddress.getCountryCode().value; + } + return countryCode; +} +function getConnectedTerminals() { + if (PaymentMgr.getPaymentMethod(constants.METHOD_ADYEN_POS).isActive()) { + return adyenTerminalApi.getTerminals().response; + } + return '{}'; +} + +/** + * Make a request to Adyen to create a new session + */ +function callCreateSession(req, res, next) { + try { + var currentBasket = BasketMgr.getCurrentBasket(); + var countryCode = getCountryCode(currentBasket, req.locale); + var response = createSession(currentBasket, AdyenHelper.getCustomer(req.currentCustomer), countryCode); + var adyenURL = "".concat(AdyenHelper.getLoadingContext(), "images/logos/medium/"); + var connectedTerminals = getConnectedTerminals(); + res.json({ + id: response.id, + sessionData: response.sessionData, + imagePath: adyenURL, + adyenDescriptions: paymentMethodDescriptions, + adyenConnectedTerminals: JSON.parse(connectedTerminals) + }); + return next(); + } catch (error) { + AdyenLogs.fatal_log("Failed to create Adyen Checkout Session ".concat(JSON.stringify(error))); + return next(); + } +} +module.exports = callCreateSession; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/shippingMethods.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/shippingMethods.js new file mode 100644 index 000000000..c903b8a62 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/shippingMethods.js @@ -0,0 +1,32 @@ +"use strict"; + +var BasketMgr = require('dw/order/BasketMgr'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); + +/** + * Make a request to Adyen to get shipping methods + */ +function callGetShippingMethods(req, res, next) { + try { + var address = null; + if (req.querystring) { + address = { + city: req.querystring.city, + countryCode: req.querystring.countryCode, + stateCode: req.querystring.stateCode + }; + } + var currentBasket = BasketMgr.getCurrentBasket(); + var currentShippingMethodsModels = AdyenHelper.getApplicableShippingMethods(currentBasket.getDefaultShipment(), address); + res.json({ + shippingMethods: currentShippingMethodsModels + }); + return next(); + } catch (error) { + AdyenLogs.error_log('Failed to fetch shipping methods'); + AdyenLogs.error_log(error); + return next(); + } +} +module.exports = callGetShippingMethods; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation.js new file mode 100644 index 000000000..db3fc8440 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation.js @@ -0,0 +1,90 @@ +"use strict"; + +var URLUtils = require('dw/web/URLUtils'); +var OrderMgr = require('dw/order/OrderMgr'); +var Order = require('dw/order/Order'); +var Transaction = require('dw/system/Transaction'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var constants = require('*/cartridge/adyenConstants/constants'); +var payment = require('*/cartridge/controllers/middlewares/adyen/showConfirmation/payment'); +var _require = require('*/cartridge/controllers/utils/index'), + clearForms = _require.clearForms; +var handleAuthorised = require('*/cartridge/controllers/middlewares/adyen/showConfirmation/authorise'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +function getPaymentDetailsPayload(querystring) { + var details = querystring.redirectResult ? { + redirectResult: querystring.redirectResult + } : { + payload: querystring.payload + }; + return { + details: details + }; +} +function getPaymentsDetailsResult(adyenPaymentInstrument, redirectResult, payload, req) { + var hasQuerystringDetails = !!(redirectResult || payload); + // Saved response from Adyen-PaymentsDetails + var result = JSON.parse(adyenPaymentInstrument.paymentTransaction.custom.Adyen_authResult); + if (hasQuerystringDetails) { + var requestObject = getPaymentDetailsPayload(req.querystring); + result = adyenCheckout.doPaymentsDetailsCall(requestObject); + } + clearForms.clearPaymentTransactionData(adyenPaymentInstrument); + return result; +} +function handlePaymentsDetailsResult(adyenPaymentInstrument, detailsResult, order, options) { + if ([constants.RESULTCODES.AUTHORISED, constants.RESULTCODES.PENDING, constants.RESULTCODES.RECEIVED].indexOf(detailsResult.resultCode) > -1) { + return handleAuthorised(adyenPaymentInstrument, detailsResult, order, options); + } + Transaction.wrap(function () { + order.custom.Adyen_pspReference = detailsResult.pspReference; + order.custom.Adyen_eventCode = detailsResult.resultCode; + }); + return payment.handlePaymentError(order, 'placeOrder', options); +} +function isOrderAlreadyProcessed(order) { + return order.status.value !== Order.ORDER_STATUS_CREATED && order.status.value !== Order.ORDER_STATUS_FAILED; +} + +/* + * Makes a payment details call to Adyen and calls for the order confirmation to be shown + * if the payment was accepted. + */ +function showConfirmation(req, res, next) { + var options = { + req: req, + res: res, + next: next + }; + var _req$querystring = req.querystring, + redirectResult = _req$querystring.redirectResult, + payload = _req$querystring.payload, + signature = _req$querystring.signature, + merchantReference = _req$querystring.merchantReference, + orderToken = _req$querystring.orderToken; + try { + var order = OrderMgr.getOrder(merchantReference, orderToken); + var adyenPaymentInstrument = order.getPaymentInstruments(AdyenHelper.getOrderMainPaymentInstrumentType(order))[0]; + if (isOrderAlreadyProcessed(order)) { + AdyenLogs.info_log('ShowConfirmation called for an order which has already been processed. This is likely to be caused by shoppers using the back button after order confirmation'); + res.redirect(URLUtils.url('Cart-Show')); + return next(); + } + if (adyenPaymentInstrument.paymentTransaction.custom.Adyen_merchantSig === signature) { + if (order.status.value === Order.ORDER_STATUS_FAILED) { + AdyenLogs.error_log("Could not call payment/details for failed order ".concat(order.orderNo)); + return payment.handlePaymentError(order, 'placeOrder', options); + } + clearForms.clearAdyenData(adyenPaymentInstrument); + var detailsResult = getPaymentsDetailsResult(adyenPaymentInstrument, redirectResult, payload, req); + return handlePaymentsDetailsResult(adyenPaymentInstrument, detailsResult, order, options); + } + throw new Error("Incorrect signature for order ".concat(merchantReference)); + } catch (e) { + AdyenLogs.error_log("Could not verify /payment/details: ".concat(e.toString(), " in ").concat(e.fileName, ":").concat(e.lineNumber)); + res.redirect(URLUtils.url('Error-ErrorCode', 'err', 'general')); + return next(); + } +} +module.exports = showConfirmation; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/authorise.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/authorise.js new file mode 100644 index 000000000..a823ae359 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/authorise.js @@ -0,0 +1,19 @@ +"use strict"; + +var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers'); +var handleOrderConfirm = require('*/cartridge/controllers/middlewares/adyen/showConfirmation/order'); +var payment = require('*/cartridge/controllers/middlewares/adyen/showConfirmation/payment'); +function handleAuthorised(adyenPaymentInstrument, detailsResult, order, options) { + // custom fraudDetection + var fraudDetectionStatus = { + status: 'success' + }; + + // Places the order + var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus); + if (placeOrderResult.error) { + return payment.handlePaymentError(order, 'placeOrder', options); + } + return handleOrderConfirm(adyenPaymentInstrument, detailsResult, order, options); +} +module.exports = handleAuthorised; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/order.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/order.js new file mode 100644 index 000000000..19c024a54 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/order.js @@ -0,0 +1,27 @@ +"use strict"; + +var Transaction = require('dw/system/Transaction'); +var URLUtils = require('dw/web/URLUtils'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var _require = require('*/cartridge/controllers/utils/index'), + clearForms = _require.clearForms; +function handleOrderConfirm(adyenPaymentInstrument, result, order, _ref) { + var res = _ref.res, + next = _ref.next; + Transaction.wrap(function () { + AdyenHelper.savePaymentDetails(adyenPaymentInstrument, order, result); + }); + clearForms.clearForms(); + // determines SFRA version for backwards compatibility + if (AdyenConfigs.getAdyenSFRA6Compatibility() === true) { + res.render('orderConfirmForm', { + orderID: order.orderNo, + orderToken: order.orderToken + }); + } else { + res.redirect(URLUtils.url('Order-Confirm', 'ID', order.orderNo, 'token', order.orderToken).toString()); + } + return next(); +} +module.exports = handleOrderConfirm; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/payment.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/payment.js new file mode 100644 index 000000000..14b03bbc2 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmation/payment.js @@ -0,0 +1,55 @@ +"use strict"; + +var URLUtils = require('dw/web/URLUtils'); +var Resource = require('dw/web/Resource'); +var Transaction = require('dw/system/Transaction'); +var OrderMgr = require('dw/order/OrderMgr'); +function handleRedirect(page, _ref) { + var res = _ref.res; + res.redirect(URLUtils.url('Checkout-Begin', 'stage', page, 'paymentError', Resource.msg('error.payment.not.valid', 'checkout', null))); +} +function handlePaymentError(order, page, _ref2) { + var res = _ref2.res, + next = _ref2.next; + Transaction.wrap(function () { + OrderMgr.failOrder(order, true); + }); + handleRedirect(page, { + res: res + }); + return next(); +} +function handlePaymentInstruments(paymentInstruments, _ref3) { + var req = _ref3.req; + var adyenPaymentInstrument; + var paymentData; + var details; + + // looping through all Adyen payment methods, however, this only can be one. + var instrumentsIter = paymentInstruments.iterator(); + while (instrumentsIter.hasNext()) { + adyenPaymentInstrument = instrumentsIter.next(); + paymentData = adyenPaymentInstrument.custom.adyenPaymentData; + } + + // details is either redirectResult or payload + if (req.querystring.redirectResult) { + details = { + redirectResult: req.querystring.redirectResult + }; + } else if (req.querystring.payload) { + details = { + payload: req.querystring.payload + }; + } + return { + details: details, + paymentData: paymentData, + adyenPaymentInstrument: adyenPaymentInstrument + }; +} +module.exports = { + handleRedirect: handleRedirect, + handlePaymentError: handlePaymentError, + handlePaymentInstruments: handlePaymentInstruments +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmationPaymentFromComponent.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmationPaymentFromComponent.js new file mode 100644 index 000000000..3b998d453 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmationPaymentFromComponent.js @@ -0,0 +1,28 @@ +"use strict"; + +var OrderMgr = require('dw/order/OrderMgr'); +var URLUtils = require('dw/web/URLUtils'); +var handlePayment = require('*/cartridge/controllers/middlewares/adyen/showConfirmationPaymentFromComponent/payment'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); + +/* + * Show confirmation for payments completed from component directly e.g. paypal, QRcode, .. + */ +function showConfirmationPaymentFromComponent(req, res, next) { + var options = { + req: req, + res: res, + next: next + }; + try { + session.privacy.giftCardResponse = null; + var stateData = JSON.parse(req.form.additionalDetailsHidden); + var order = OrderMgr.getOrder(req.form.merchantReference, req.form.orderToken); + return handlePayment(stateData, order, options); + } catch (e) { + AdyenLogs.error_log("Could not verify /payment/details: ".concat(e.toString(), " in ").concat(e.fileName, ":").concat(e.lineNumber)); + res.redirect(URLUtils.url('Error-ErrorCode', 'err', 'general')); + return next(); + } +} +module.exports = showConfirmationPaymentFromComponent; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmationPaymentFromComponent/payment.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmationPaymentFromComponent/payment.js new file mode 100644 index 000000000..036137b71 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/adyen/showConfirmationPaymentFromComponent/payment.js @@ -0,0 +1,111 @@ +"use strict"; + +var OrderMgr = require('dw/order/OrderMgr'); +var Order = require('dw/order/Order'); +var Transaction = require('dw/system/Transaction'); +var URLUtils = require('dw/web/URLUtils'); +var Resource = require('dw/web/Resource'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var constants = require('*/cartridge/adyenConstants/constants'); +var _require = require('*/cartridge/controllers/utils/index'), + clearForms = _require.clearForms; +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +function handlePaymentError(order, adyenPaymentInstrument, _ref) { + var res = _ref.res, + next = _ref.next; + clearForms.clearAdyenData(adyenPaymentInstrument); + Transaction.wrap(function () { + OrderMgr.failOrder(order, true); + }); + res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'payment', 'paymentError', Resource.msg('error.payment.not.valid', 'checkout', null))); + return next(); +} +function handlePaymentsDetailsCall(stateData, adyenPaymentInstrument) { + var details = stateData.details, + paymentData = stateData.paymentData; + + // redirect to payment/details + var requestObject = { + details: details, + paymentData: paymentData + }; + var result = adyenCheckout.doPaymentsDetailsCall(requestObject); + return { + result: result, + adyenPaymentInstrument: adyenPaymentInstrument + }; +} +function handleAuthorisedPayment(order, result, adyenPaymentInstrument, _ref2) { + var res = _ref2.res, + next = _ref2.next; + // custom fraudDetection + var fraudDetectionStatus = { + status: 'success' + }; + + // Places the order + var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus); + if (placeOrderResult.error) { + return handlePaymentError(order, adyenPaymentInstrument, { + res: res, + next: next + }); + } + Transaction.wrap(function () { + AdyenHelper.savePaymentDetails(adyenPaymentInstrument, order, result); + }); + clearForms.clearAdyenData(adyenPaymentInstrument); + clearForms.clearForms(); + // determines SFRA version for backwards compatibility + if (AdyenConfigs.getAdyenSFRA6Compatibility() === true) { + res.render('orderConfirmForm', { + orderID: order.orderNo, + orderToken: order.orderToken + }); + } else { + res.redirect(URLUtils.url('Order-Confirm', 'ID', order.orderNo, 'token', order.orderToken).toString()); + } + return next(); +} +function handlePaymentResult(result, order, adyenPaymentInstrument, options) { + // Authorised: The payment authorisation was successfully completed. + if ([constants.RESULTCODES.AUTHORISED, constants.RESULTCODES.PENDING, constants.RESULTCODES.RECEIVED].indexOf(result.resultCode) > -1) { + return handleAuthorisedPayment(order, result, adyenPaymentInstrument, options); + } + Transaction.wrap(function () { + order.custom.Adyen_pspReference = result.pspReference; + order.custom.Adyen_eventCode = result.resultCode; + }); + return handlePaymentError(order, adyenPaymentInstrument, options); +} + +// eslint-disable-next-line complexity +function handlePayment(stateData, order, options) { + var _options$req$form; + var paymentInstruments = order.getPaymentInstruments(AdyenHelper.getOrderMainPaymentInstrumentType(order)); + var result = (_options$req$form = options.req.form) === null || _options$req$form === void 0 ? void 0 : _options$req$form.result; + var adyenPaymentInstrument = paymentInstruments[0]; + var hasStateData = (stateData === null || stateData === void 0 ? void 0 : stateData.paymentData) && (stateData === null || stateData === void 0 ? void 0 : stateData.details); + if (result !== null && result !== void 0 && result.error || order.status.value === Order.ORDER_STATUS_FAILED) { + AdyenLogs.error_log("Could not call payment/details for order ".concat(order.orderNo)); + return handlePaymentError(order, adyenPaymentInstrument, options); + } + var finalResult; + if (!hasStateData) { + if (result && (JSON.stringify(result).indexOf('amazonpay') > -1 || JSON.stringify(result).indexOf('applepay') > -1 || JSON.stringify(result).indexOf('cashapp') > -1)) { + finalResult = JSON.parse(result); + } else { + return handlePaymentError(order, adyenPaymentInstrument, options); + } + } + var detailsCall = hasStateData ? handlePaymentsDetailsCall(stateData, adyenPaymentInstrument) : null; + Transaction.wrap(function () { + adyenPaymentInstrument.custom.adyenPaymentData = null; + }); + finalResult = finalResult || (detailsCall === null || detailsCall === void 0 ? void 0 : detailsCall.result); + return handlePaymentResult(finalResult, order, adyenPaymentInstrument, options); +} +module.exports = handlePayment; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout/begin.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout/begin.js new file mode 100644 index 000000000..c6dbef5aa --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout/begin.js @@ -0,0 +1,81 @@ +"use strict"; + +var BasketMgr = require('dw/order/BasketMgr'); +var OrderMgr = require('dw/order/OrderMgr'); +var Order = require('dw/order/Order'); +var Transaction = require('dw/system/Transaction'); +var URLUtils = require('dw/web/URLUtils'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var _require = require('*/cartridge/scripts/updateSavedCards'), + updateSavedCards = _require.updateSavedCards; +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +function shouldRestoreBasket(cachedOrderNumber) { + // restore cart if order number was cached + if (cachedOrderNumber) { + var currentBasket = BasketMgr.getCurrentBasket(); + // check if cart is null or empty + if (!currentBasket || currentBasket.getAllProductLineItems().length === 0) { + return true; + } + } + return false; +} +function restoreBasket(cachedOrderNumber, cachedOrderToken) { + try { + var currentOrder = OrderMgr.getOrder(cachedOrderNumber, cachedOrderToken); + // if order status is CREATED we can fail it and restore basket + if (currentOrder.status.value === Order.ORDER_STATUS_CREATED) { + Transaction.wrap(function () { + currentOrder.trackOrderChange('Failing order so cart can be restored; Shopper navigated back to checkout during payment redirection'); + OrderMgr.failOrder(currentOrder, true); + }); + return true; + } + } catch (error) { + AdyenLogs.error_log("Failed to restore cart. error: ".concat(error)); + } + return false; +} +function begin(req, res, next) { + var _this = this; + if (req.currentCustomer.raw.isAuthenticated()) { + updateSavedCards({ + CurrentCustomer: req.currentCustomer.raw + }); + } + var cachedOrderNumber = req.session.privacyCache.get('currentOrderNumber'); + var cachedOrderToken = req.session.privacyCache.get('currentOrderToken'); + if (shouldRestoreBasket(cachedOrderNumber)) { + if (restoreBasket(cachedOrderNumber, cachedOrderToken)) { + var emit = function emit(route) { + return _this.emit(route, req, res); + }; + res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'shipping')); + emit('route:Complete'); + return true; + } + } + var clientKey = AdyenConfigs.getAdyenClientKey(); + var environment = AdyenHelper.getCheckoutEnvironment(); + var installments = AdyenConfigs.getCreditCardInstallments(); + var adyenClientKey = AdyenConfigs.getAdyenClientKey(); + var googleMerchantID = AdyenConfigs.getGoogleMerchantID(); + var merchantAccount = AdyenConfigs.getAdyenMerchantAccount(); + var cardholderNameBool = AdyenConfigs.getAdyenCardholderNameEnabled(); + var SFRA6Enabled = AdyenConfigs.getAdyenSFRA6Compatibility(); + var viewData = res.getViewData(); + viewData.adyen = { + clientKey: clientKey, + environment: environment, + installments: installments, + googleMerchantID: googleMerchantID, + merchantAccount: merchantAccount, + cardholderNameBool: cardholderNameBool, + adyenClientKey: adyenClientKey, + SFRA6Enabled: SFRA6Enabled + }; + res.setViewData(viewData); + return next(); +} +module.exports = begin; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout/index.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout/index.js new file mode 100644 index 000000000..2160c944f --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout/index.js @@ -0,0 +1,6 @@ +"use strict"; + +var begin = require('*/cartridge/controllers/middlewares/checkout/begin'); +module.exports = { + begin: begin +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout_services/adyenCheckoutServices.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout_services/adyenCheckoutServices.js new file mode 100644 index 000000000..376ef1071 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout_services/adyenCheckoutServices.js @@ -0,0 +1,26 @@ +"use strict"; + +var constants = require('*/cartridge/adyenConstants/constants'); +var collections = require('*/cartridge/scripts/util/collections'); +function processPayment(order, handlePaymentResult, req, res, emit) { + res.json({ + error: false, + adyenAction: handlePaymentResult.action, + orderID: order.orderNo, + orderToken: order.orderToken + }); + emit('route:Complete'); +} +function isNotAdyen(currentBasket) { + var isAdyenBool = false; + collections.forEach(currentBasket.getPaymentInstruments(), function (paymentInstrument) { + if ([constants.METHOD_ADYEN, paymentInstrument.METHOD_CREDIT_CARD, constants.METHOD_ADYEN_POS, constants.METHOD_ADYEN_COMPONENT].indexOf(paymentInstrument.paymentMethod) !== -1) { + isAdyenBool = true; + } + }); + return !isAdyenBool; +} +module.exports = { + processPayment: processPayment, + isNotAdyen: isNotAdyen +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout_services/placeOrder.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout_services/placeOrder.js new file mode 100644 index 000000000..3ada91b94 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/checkout_services/placeOrder.js @@ -0,0 +1,250 @@ +"use strict"; + +/* ### Custom Adyen cartridge start ### */ +var adyenHelpers = require('*/cartridge/scripts/checkout/adyenHelpers'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var GiftCardsHelper = require('*/cartridge/scripts/util/giftCardsHelper'); +var constants = require('*/cartridge/adyenConstants/constants'); +var _require = require('*/cartridge/controllers/middlewares/checkout_services/adyenCheckoutServices'), + processPayment = _require.processPayment, + isNotAdyen = _require.isNotAdyen; +var Money = require('dw/value/Money'); +var _require2 = require('*/cartridge/controllers/utils/index'), + clearForms = _require2.clearForms; + +/* ### Custom Adyen cartridge end ### */ + +function placeOrder(req, res, next) { + var _currentBasket$custom, + _this = this, + _handlePaymentResult$; + var BasketMgr = require('dw/order/BasketMgr'); + var OrderMgr = require('dw/order/OrderMgr'); + var Resource = require('dw/web/Resource'); + var Transaction = require('dw/system/Transaction'); + var URLUtils = require('dw/web/URLUtils'); + var basketCalculationHelpers = require('*/cartridge/scripts/helpers/basketCalculationHelpers'); + var hooksHelper = require('*/cartridge/scripts/helpers/hooks'); + var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers'); + var validationHelpers = require('*/cartridge/scripts/helpers/basketValidationHelpers'); + var addressHelpers = require('*/cartridge/scripts/helpers/addressHelpers'); + var currentBasket = BasketMgr.getCurrentBasket(); + if (!currentBasket) { + res.json({ + error: true, + cartError: true, + fieldErrors: [], + serverErrors: [], + redirectUrl: URLUtils.url('Cart-Show').toString() + }); + return next(); + } + + /* ### Custom Adyen cartridge ### */ + if (isNotAdyen(currentBasket)) { + return next(); + } + /* ### Custom Adyen cartridge ### */ + + var validatedProducts = validationHelpers.validateProducts(currentBasket); + if (validatedProducts.error) { + res.json({ + error: true, + cartError: true, + fieldErrors: [], + serverErrors: [], + redirectUrl: URLUtils.url('Cart-Show').toString() + }); + return next(); + } + if (req.session.privacyCache.get('fraudDetectionStatus')) { + res.json({ + error: true, + cartError: true, + redirectUrl: URLUtils.url('Error-ErrorCode', 'err', '01').toString(), + errorMessage: Resource.msg('error.technical', 'checkout', null) + }); + return next(); + } + var validationOrderStatus = hooksHelper('app.validate.order', 'validateOrder', currentBasket, require('*/cartridge/scripts/hooks/validateOrder').validateOrder); + if (validationOrderStatus.error) { + res.json({ + error: true, + errorMessage: validationOrderStatus.message + }); + return next(); + } + + // Check to make sure there is a shipping address + if (currentBasket.defaultShipment.shippingAddress === null) { + res.json({ + error: true, + errorStage: { + stage: 'shipping', + step: 'address' + }, + errorMessage: Resource.msg('error.no.shipping.address', 'checkout', null) + }); + return next(); + } + + // Check to make sure billing address exists + if (!currentBasket.billingAddress) { + res.json({ + error: true, + errorStage: { + stage: 'payment', + step: 'billingAddress' + }, + errorMessage: Resource.msg('error.no.billing.address', 'checkout', null) + }); + return next(); + } + + // Calculate the basket + Transaction.wrap(function () { + basketCalculationHelpers.calculateTotals(currentBasket); + }); + + // Re-calculate the payments. + var calculatedPaymentTransactionTotal = COHelpers.calculatePaymentTransaction(currentBasket); + if (calculatedPaymentTransactionTotal.error) { + res.json({ + error: true, + errorMessage: Resource.msg('error.technical', 'checkout', null) + }); + return next(); + } + + // Check if gift cards were used + var giftCardsAdded = (_currentBasket$custom = currentBasket.custom) !== null && _currentBasket$custom !== void 0 && _currentBasket$custom.adyenGiftCards ? JSON.parse(currentBasket.custom.adyenGiftCards) : null; + + // Creates a new order. + var order; + if (giftCardsAdded) { + var orderNo = currentBasket.custom.adyenGiftCardsOrderNo; + order = OrderMgr.createOrder(currentBasket, orderNo); + } else { + order = COHelpers.createOrder(currentBasket); + } + if (!order) { + session.privacy.orderNo = null; + res.json({ + error: true, + errorMessage: Resource.msg('error.technical', 'checkout', null) + }); + return next(); + } + + /* ### Custom Adyen cartridge start ### */ + // Cache order number in order to be able to restore cart later + req.session.privacyCache.set('currentOrderNumber', order.orderNo); + req.session.privacyCache.set('currentOrderToken', order.orderToken); + session.privacy.orderNo = order.orderNo; + + // Handles payment authorization + var handlePaymentResult = adyenHelpers.handlePayments(order); + var mainPaymentInstrument = order.getPaymentInstruments(AdyenHelper.getOrderMainPaymentInstrumentType(order))[0]; + if (giftCardsAdded) { + giftCardsAdded.forEach(function (giftCard) { + var divideBy = AdyenHelper.getDivisorForCurrency(mainPaymentInstrument.paymentTransaction.getAmount()); + var amount = { + value: giftCard.remainingAmount.value, + currency: giftCard.remainingAmount.currency + }; + var formattedAmount = new Money(amount.value, amount.currency).divide(divideBy); + Transaction.wrap(function () { + mainPaymentInstrument.paymentTransaction.setAmount(formattedAmount); //update amount from order total to PM total + }); + + GiftCardsHelper.createGiftCardPaymentInstrument(giftCard, divideBy, order); + }); + } + /* ### Custom Adyen cartridge end ### */ + + // Handle custom processing post authorization + var options = { + req: req, + res: res + }; + var postAuthCustomizations = hooksHelper('app.post.auth', 'postAuthorization', handlePaymentResult, order, options, require('*/cartridge/scripts/hooks/postAuthorizationHandling').postAuthorization); + if (postAuthCustomizations && Object.prototype.hasOwnProperty.call(postAuthCustomizations, 'error')) { + res.json(postAuthCustomizations); + return next(); + } + if (handlePaymentResult.error) { + res.json({ + error: true, + errorMessage: Resource.msg('error.payment.not.valid', 'checkout', null) + }); + this.emit('route:Complete', req, res); + return; + } + + /* ### Custom Adyen cartridge start ### */ + var cbEmitter = function cbEmitter(route) { + return _this.emit(route, req, res); + }; + if (handlePaymentResult.action && ((_handlePaymentResult$ = handlePaymentResult.action) === null || _handlePaymentResult$ === void 0 ? void 0 : _handlePaymentResult$.type) !== constants.ACTIONTYPES.VOUCHER) { + return processPayment(order, handlePaymentResult, req, res, cbEmitter); + } + /* ### Custom Adyen cartridge end ### */ + + var fraudDetectionStatus = hooksHelper('app.fraud.detection', 'fraudDetection', currentBasket, require('*/cartridge/scripts/hooks/fraudDetection').fraudDetection); + if (fraudDetectionStatus.status === 'fail') { + Transaction.wrap(function () { + OrderMgr.failOrder(order, true); + }); + + // fraud detection failed + req.session.privacyCache.set('fraudDetectionStatus', true); + res.json({ + error: true, + cartError: true, + redirectUrl: URLUtils.url('Error-ErrorCode', 'err', fraudDetectionStatus.errorCode).toString(), + errorMessage: Resource.msg('error.technical', 'checkout', null) + }); + return next(); + } + + // Places the order + var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus); + if (placeOrderResult.error) { + res.json({ + error: true, + errorMessage: Resource.msg('error.technical', 'checkout', null) + }); + return next(); + } + if (req.currentCustomer.addressBook) { + // save all used shipping addresses to address book of the logged in customer + var allAddresses = addressHelpers.gatherShippingAddresses(order); + allAddresses.forEach(function (address) { + if (!addressHelpers.checkIfAddressStored(address, req.currentCustomer.addressBook.addresses)) { + addressHelpers.saveAddress(address, req.currentCustomer, addressHelpers.generateAddressName(address)); + } + }); + } + if (order.getCustomerEmail()) { + COHelpers.sendConfirmationEmail(order, req.locale.id); + } + clearForms.clearForms(); + if (mainPaymentInstrument) { + clearForms.clearPaymentTransactionData(mainPaymentInstrument); + clearForms.clearAdyenData(mainPaymentInstrument); + } + // Reset usingMultiShip after successful Order placement + req.session.privacyCache.set('usingMultiShipping', false); + + // TODO: Exposing a direct route to an Order, without at least encoding the orderID + // is a serious PII violation. It enables looking up every customers orders, one at a + // time. + res.json({ + error: false, + orderID: order.orderNo, + orderToken: order.orderToken, + continueUrl: URLUtils.url('Order-Confirm').toString() + }); + this.emit('route:Complete', req, res); +} +module.exports = placeOrder; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/index.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/index.js new file mode 100644 index 000000000..8925dddcd --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/index.js @@ -0,0 +1,12 @@ +"use strict"; + +var adyen = require('*/cartridge/controllers/middlewares/adyen/index'); +var checkout = require('*/cartridge/controllers/middlewares/checkout/index'); +var order = require('*/cartridge/controllers/middlewares/order/index'); +var paymentInstruments = require('*/cartridge/controllers/middlewares/payment_instruments/index'); +module.exports = { + adyen: adyen, + checkout: checkout, + order: order, + paymentInstruments: paymentInstruments +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/order/confirm.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/order/confirm.js new file mode 100644 index 000000000..fa51fe3df --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/order/confirm.js @@ -0,0 +1,55 @@ +"use strict"; + +var OrderMgr = require('dw/order/OrderMgr'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var AdyenConfigs = require('*/cartridge/scripts/util/adyenConfigs'); + +// order-confirm is POST in SFRA v6.0.0. orderID and orderToken are contained in form. +// This was a GET call with a querystring containing ID & token in earlier versions. +function getOrderId(req) { + return req.form && req.form.orderID ? req.form.orderID : req.querystring.ID; +} +function getOrderToken(req) { + return req.form && req.form.orderToken ? req.form.orderToken : req.querystring.token; +} +function handleAdyenGiving(req, res) { + var clientKey = AdyenConfigs.getAdyenClientKey(); + var environment = AdyenHelper.getCheckoutEnvironment(); + var configuredAmounts = AdyenHelper.getDonationAmounts(); + var charityName = encodeURI(AdyenConfigs.getAdyenGivingCharityName()); + var charityWebsite = AdyenConfigs.getAdyenGivingCharityWebsite(); + var charityDescription = encodeURI(AdyenConfigs.getAdyenGivingCharityDescription()); + var adyenGivingBackgroundUrl = AdyenConfigs.getAdyenGivingBackgroundUrl(); + var adyenGivingLogoUrl = AdyenConfigs.getAdyenGivingLogoUrl(); + var orderToken = getOrderToken(req); + var donationAmounts = { + currency: session.currency.currencyCode, + values: configuredAmounts + }; + var viewData = res.getViewData(); + viewData.adyen = { + clientKey: clientKey, + environment: environment, + adyenGivingAvailable: true, + donationAmounts: JSON.stringify(donationAmounts), + charityName: charityName, + charityDescription: charityDescription, + charityWebsite: charityWebsite, + adyenGivingBackgroundUrl: adyenGivingBackgroundUrl, + adyenGivingLogoUrl: adyenGivingLogoUrl, + orderToken: orderToken + }; + res.setViewData(viewData); +} +function confirm(req, res, next) { + var orderId = getOrderId(req); + var orderToken = getOrderToken(req); + if (orderId && orderToken) { + var order = OrderMgr.getOrder(orderId, orderToken); + if (AdyenHelper.getAdyenGivingConfig(order)) { + handleAdyenGiving(req, res); + } + } + return next(); +} +module.exports = confirm; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/order/index.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/order/index.js new file mode 100644 index 000000000..7dd010b92 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/order/index.js @@ -0,0 +1,6 @@ +"use strict"; + +var confirm = require('*/cartridge/controllers/middlewares/order/confirm'); +module.exports = { + confirm: confirm +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/deletePayment.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/deletePayment.js new file mode 100644 index 000000000..7a8093bc3 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/deletePayment.js @@ -0,0 +1,21 @@ +"use strict"; + +var CustomerMgr = require('dw/customer/CustomerMgr'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var _require = require('*/cartridge/scripts/adyenDeleteRecurringPayment'), + deleteRecurringPayment = _require.deleteRecurringPayment; +function deletePayment(req, res, next) { + var payment = res.getViewData(); + if (payment) { + var customer = CustomerMgr.getCustomerByCustomerNumber(req.currentCustomer.profile.customerNo); + var tokenToDelete = AdyenHelper.getCardToken(payment.UUID, customer); + if (tokenToDelete) { + deleteRecurringPayment({ + Customer: customer, + RecurringDetailReference: tokenToDelete + }); + } + } + return next(); +} +module.exports = deletePayment; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/index.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/index.js new file mode 100644 index 000000000..f17abe7c9 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/index.js @@ -0,0 +1,8 @@ +"use strict"; + +var savePayment = require('*/cartridge/controllers/middlewares/payment_instruments/savePayment'); +var deletePayment = require('*/cartridge/controllers/middlewares/payment_instruments/deletePayment'); +module.exports = { + savePayment: savePayment, + deletePayment: deletePayment +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/paymentProcessorIDs.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/paymentProcessorIDs.js new file mode 100644 index 000000000..84db9298f --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/paymentProcessorIDs.js @@ -0,0 +1,3 @@ +"use strict"; + +module.exports.paymentProcessorIDs = ['Adyen_Component', 'ADYEN_CREDIT']; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/savePayment.js b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/savePayment.js new file mode 100644 index 000000000..c87bdd351 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/middlewares/payment_instruments/savePayment.js @@ -0,0 +1,72 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var server = require('server'); +var Resource = require('dw/web/Resource'); +var CustomerMgr = require('dw/customer/CustomerMgr'); +var Transaction = require('dw/system/Transaction'); +var URLUtils = require('dw/web/URLUtils'); +var PaymentMgr = require('dw/order/PaymentMgr'); +var adyenZeroAuth = require('*/cartridge/scripts/adyenZeroAuth'); +var constants = require('*/cartridge/adyenConstants/constants'); +var accountHelpers = require('*/cartridge/scripts/helpers/accountHelpers'); +var _require = require('*/cartridge/scripts/updateSavedCards'), + updateSavedCards = _require.updateSavedCards; +var _require2 = require('*/cartridge/controllers/middlewares/payment_instruments/paymentProcessorIDs'), + paymentProcessorIDs = _require2.paymentProcessorIDs; +function containsValidResultCode(req) { + return [constants.RESULTCODES.AUTHORISED, constants.RESULTCODES.IDENTIFYSHOPPER, constants.RESULTCODES.CHALLENGESHOPPER, constants.RESULTCODES.REDIRECTSHOPPER].indexOf(req.resultCode) !== -1; +} +function createPaymentInstrument(customer) { + var paymentInstrument; + var paymentForm = server.forms.getForm('creditCard'); + var wallet = customer.getProfile().getWallet(); + Transaction.wrap(function () { + paymentInstrument = wallet.createPaymentInstrument(constants.METHOD_ADYEN_COMPONENT); + paymentInstrument.custom.adyenPaymentData = paymentForm.adyenStateData.value; + }); + return paymentInstrument; +} +function getResponseBody(action) { + return _objectSpread({ + success: true, + redirectUrl: URLUtils.url('PaymentInstruments-List').toString() + }, action && { + redirectAction: action + }); +} +function isAdyen() { + var _PaymentMgr$getPaymen, _PaymentMgr$getPaymen2; + return paymentProcessorIDs.indexOf((_PaymentMgr$getPaymen = PaymentMgr.getPaymentMethod('CREDIT_CARD')) === null || _PaymentMgr$getPaymen === void 0 ? void 0 : (_PaymentMgr$getPaymen2 = _PaymentMgr$getPaymen.getPaymentProcessor()) === null || _PaymentMgr$getPaymen2 === void 0 ? void 0 : _PaymentMgr$getPaymen2.getID()) > -1 || PaymentMgr.getPaymentMethod(constants.METHOD_ADYEN_COMPONENT).isActive(); +} +function savePayment(req, res, next) { + if (!isAdyen()) { + return next(); + } + var customer = CustomerMgr.getCustomerByCustomerNumber(req.currentCustomer.profile.customerNo); + Transaction.begin(); + var zeroAuthResult = adyenZeroAuth.zeroAuthPayment(customer, createPaymentInstrument(customer)); + if (zeroAuthResult.error || !containsValidResultCode(zeroAuthResult)) { + Transaction.rollback(); + res.json({ + success: false, + error: [Resource.msg('error.card.information.error', 'creditCard', null)] + }); + return this.emit('route:Complete', req, res); + } + Transaction.commit(); + updateSavedCards({ + CurrentCustomer: req.currentCustomer.raw + }); + + // Send account edited email + accountHelpers.sendAccountEditedEmail(customer.profile); + res.json(getResponseBody(zeroAuthResult.action)); + return this.emit('route:Complete', req, res); +} +module.exports = savePayment; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/utils/clearForms.js b/cartridges/int_adyen_SFRA/cartridge/controllers/utils/clearForms.js new file mode 100644 index 000000000..72651b08e --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/utils/clearForms.js @@ -0,0 +1,66 @@ +"use strict"; + +var Transaction = require('dw/system/Transaction'); +/** + * Clear custom session data + */ +function clearCustomSessionFields() { + // Clears all fields used in the 3d secure payment. + session.privacy.paymentMethod = null; + session.privacy.brandCode = null; + session.privacy.issuer = null; + session.privacy.adyenPaymentMethod = null; + session.privacy.adyenIssuerName = null; + session.privacy.ratePayFingerprint = null; + session.privacy.giftCardResponse = null; + session.privacy.partialPaymentData = null; + session.privacy.amazonExpressShopperDetail = null; +} + +/** + * Clear system session data + */ +function clearForms() { + // Clears all forms used in the checkout process. + session.forms.billing.clearFormElement(); + clearCustomSessionFields(); +} + +/** + * Clear Adyen payment data + */ +function clearAdyenData(paymentInstrument) { + Transaction.wrap(function () { + paymentInstrument.custom.adyenPaymentData = null; + paymentInstrument.custom.adyenPartialPaymentsOrder = null; + paymentInstrument.custom.adyenMD = null; + }); +} + +/** + * Clear Adyen basket data + */ +function clearAdyenBasketData(basket) { + if (basket) { + Transaction.wrap(function () { + basket.custom.adyenGiftCards = null; + basket.custom.adyenGiftCardsOrderNo = null; + }); + } +} + +/** + * Clear Adyen transaction data + */ +function clearPaymentTransactionData(paymentInstrument) { + Transaction.wrap(function () { + paymentInstrument.paymentTransaction.custom.Adyen_authResult = null; + paymentInstrument.paymentTransaction.custom.Adyen_merchantSig = null; + }); +} +module.exports = { + clearForms: clearForms, + clearAdyenData: clearAdyenData, + clearPaymentTransactionData: clearPaymentTransactionData, + clearAdyenBasketData: clearAdyenBasketData +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/controllers/utils/index.js b/cartridges/int_adyen_SFRA/cartridge/controllers/utils/index.js new file mode 100644 index 000000000..6e96936bc --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/controllers/utils/index.js @@ -0,0 +1,4 @@ +"use strict"; + +module.exports.clearForms = require('*/cartridge/controllers/utils/clearForms'); +module.exports.clearForms = require('*/cartridge/controllers/utils/clearForms'); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/forms/default/address.xml b/cartridges/int_adyen_SFRA/cartridge/forms/default/address.xml new file mode 100644 index 000000000..c44e3826c --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/forms/default/address.xml @@ -0,0 +1,288 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/forms/default/adyenPayment.xml b/cartridges/int_adyen_SFRA/cartridge/forms/default/adyenPayment.xml new file mode 100644 index 000000000..9e7b771f8 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/forms/default/adyenPayment.xml @@ -0,0 +1,13 @@ + +
            + + + + + + + + + + + diff --git a/cartridges/int_adyen_SFRA/cartridge/forms/default/billing.xml b/cartridges/int_adyen_SFRA/cartridge/forms/default/billing.xml new file mode 100644 index 000000000..6ad656382 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/forms/default/billing.xml @@ -0,0 +1,19 @@ + +
            + + + + + + + + + + + + + + + + diff --git a/cartridges/int_adyen_SFRA/cartridge/forms/default/creditCard.xml b/cartridges/int_adyen_SFRA/cartridge/forms/default/creditCard.xml new file mode 100644 index 000000000..47428930e --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/forms/default/creditCard.xml @@ -0,0 +1,55 @@ + +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cartridges/int_adyen_SFRA/cartridge/int_adyen_SFRA.properties b/cartridges/int_adyen_SFRA/cartridge/int_adyen_SFRA.properties new file mode 100755 index 000000000..6d5f84687 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/int_adyen_SFRA.properties @@ -0,0 +1,4 @@ +## cartridge.properties for cartridge LINK_adyen +#Thu Apr 26 2018 13:00:35 GMT+0000 (UTC) +demandware.cartridges.int_adyen_SFRA.multipleLanguageStorefront=true +demandware.cartridges.int_adyen_SFRA.id=int_adyen_SFRA diff --git a/cartridges/int_adyen_SFRA/cartridge/models/createPayment.js b/cartridges/int_adyen_SFRA/cartridge/models/createPayment.js new file mode 100644 index 000000000..7e0256da7 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/models/createPayment.js @@ -0,0 +1,39 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function getField(name, obj) { + return obj && _defineProperty({}, name, obj); +} +function getParsedField(name, str) { + return str && _defineProperty({}, name, JSON.parse(str)); +} +function getOrNull(name, obj) { + return obj ? _defineProperty({}, name, obj) : _defineProperty({}, name, null); +} +module.exports.createSelectedPaymentInstruments = function createSelectedPaymentInstruments(_ref5) { + var paymentMethod = _ref5.paymentMethod, + paymentTransaction = _ref5.paymentTransaction, + custom = _ref5.custom, + creditCardNumberLastDigits = _ref5.creditCardNumberLastDigits, + creditCardExpirationMonth = _ref5.creditCardExpirationMonth, + creditCardExpirationYear = _ref5.creditCardExpirationYear, + creditCardHolder = _ref5.creditCardHolder, + creditCardType = _ref5.creditCardType, + giftCertificateCode = _ref5.giftCertificateCode, + maskedGiftCertificateCode = _ref5.maskedGiftCertificateCode, + maskedCreditCardNumber = _ref5.maskedCreditCardNumber; + var results = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({ + paymentMethod: paymentMethod, + amount: paymentTransaction.amount.value + }, getField('selectedAdyenPM', custom.adyenPaymentMethod)), getField('selectedIssuerName', custom.adyenIssuerName)), getParsedField('adyenAdditionalPaymentData', custom.adyenAdditionalPaymentData)), getField('adyenAction', custom.adyenAction)), getOrNull('lastFour', creditCardNumberLastDigits)), getOrNull('owner', creditCardHolder)), getOrNull('expirationYear', creditCardExpirationYear)), getOrNull('type', creditCardType)), getOrNull('maskedCreditCardNumber', maskedCreditCardNumber)), getOrNull('expirationMonth', creditCardExpirationMonth)); + if (paymentMethod === 'GIFT_CERTIFICATE') { + results.giftCertificateCode = giftCertificateCode; + results.maskedGiftCertificateCode = maskedGiftCertificateCode; + } + return results; +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/models/payment.js b/cartridges/int_adyen_SFRA/cartridge/models/payment.js new file mode 100644 index 000000000..2eabd404b --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/models/payment.js @@ -0,0 +1,30 @@ +"use strict"; + +var collections = require('*/cartridge/scripts/util/collections'); +var _require = require('./createPayment'), + createSelectedPaymentInstruments = _require.createSelectedPaymentInstruments; +var base = module.superModule; + +/** + * Creates an array of objects containing selected payment information + * @param {dw.util.ArrayList} selectedPaymentInstruments - ArrayList + * of payment instruments that the user is using to pay for the current basket + * @returns {Array} Array of objects that contain information about the selected payment instruments + */ +function getSelectedPaymentInstruments(selectedPaymentInstruments) { + return collections.map(selectedPaymentInstruments, createSelectedPaymentInstruments); +} + +/** + * Payment class that represents payment information for the current basket + * @param {dw.order.Basket} currentBasket - the target Basket object + * @param {dw.customer.Customer} currentCustomer - the associated Customer object + * @param {string} countryCode - the associated Site countryCode + * @constructor + */ +function Payment(currentBasket, currentCustomer, countryCode) { + base.call(this, currentBasket, currentCustomer, countryCode); + var paymentInstruments = currentBasket.paymentInstruments; + this.selectedPaymentInstruments = paymentInstruments ? getSelectedPaymentInstruments(paymentInstruments) : null; +} +module.exports = Payment; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/adyenService.js b/cartridges/int_adyen_SFRA/cartridge/scripts/adyenService.js new file mode 100644 index 000000000..abe0acb14 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/adyenService.js @@ -0,0 +1,65 @@ +"use strict"; + +var Site = require('dw/system/Site'); +var Resource = require('dw/web/Resource'); +var HashMap = require('dw/util/HashMap'); +var Mail = require('dw/net/Mail'); +var Template = require('dw/util/Template'); +var Transaction = require('dw/system/Transaction'); +var Order = require('dw/order/Order'); +var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers'); +var OrderModel = require('*/cartridge/models/order'); +function sendEmail(order) { + var confirmationEmail = new Mail(); + var context = new HashMap(); + var orderModel = new OrderModel(order, { + containerView: 'order' + }); + var orderObject = { + order: orderModel + }; + confirmationEmail.addTo(order.customerEmail); + confirmationEmail.setSubject(Resource.msg('subject.order.confirmation.email', 'order', null)); + confirmationEmail.setFrom(Site.current.getCustomPreferenceValue('customerServiceEmail') || 'no-reply@salesforce.com'); + Object.keys(orderObject).forEach(function (key) { + context.put(key, orderObject[key]); + }); + var template = new Template('checkout/confirmation/confirmationEmail'); + var content = template.render(context).text; + confirmationEmail.setContent(content, 'text/html', 'UTF-8'); + confirmationEmail.send(); +} +function submit(order) { + try { + Transaction.begin(); + // Places the order if not placed yet + if (order.status.value === Order.ORDER_STATUS_CREATED) { + // custom fraudDetection + var fraudDetectionStatus = { + status: 'success' + }; + var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus); + if (placeOrderResult.error) { + return placeOrderResult; + } + } + sendEmail(order); + Transaction.commit(); + return { + order_created: true + }; + } catch (e) { + Transaction.rollback(); + return { + error: true + }; + } +} +var EXTERNAL_PLATFORM_VERSION = 'SFRA'; +function getExternalPlatformVersion() { + return EXTERNAL_PLATFORM_VERSION; +} +module.exports = { + submit: submit, + getExternalPlatformVersion: getExternalPlatformVersion +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/adyenHelpers.js b/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/adyenHelpers.js new file mode 100644 index 000000000..0a837acc1 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/adyenHelpers.js @@ -0,0 +1,30 @@ +"use strict"; + +var Transaction = require('dw/system/Transaction'); +var OrderMgr = require('dw/order/OrderMgr'); +var _require = require('*/cartridge/scripts/checkout/utils/index'), + getPayments = _require.getPayments; + +/** + * handles the payment authorization for each payment instrument + * @param {dw.order.Order} order - the order object + * @param {string} orderNumber - The order number for the order + * @returns {Object} an error object + */ +function handlePayments(order) { + if (order.totalNetPrice === 0.0) { + return {}; + } + if (order.paymentInstruments.length) { + return getPayments(order); + } + Transaction.wrap(function () { + OrderMgr.failOrder(order, true); + }); + return { + error: true + }; +} +module.exports = { + handlePayments: handlePayments +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/getPayments.js b/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/getPayments.js new file mode 100644 index 000000000..7be69e578 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/getPayments.js @@ -0,0 +1,35 @@ +"use strict"; + +var Transaction = require('dw/system/Transaction'); +var HookMgr = require('dw/system/HookMgr'); +var PaymentMgr = require('dw/order/PaymentMgr'); +var OrderMgr = require('dw/order/OrderMgr'); +var getAuthorizationResult = function getAuthorizationResult(pProcessor, order, pInstrument) { + var hookName = "app.payment.processor.".concat(pProcessor.ID.toLowerCase()); + var customAuthorizeHook = function customAuthorizeHook() { + return HookMgr.callHook(hookName, 'Authorize', order, pInstrument, pProcessor); + }; + return HookMgr.hasHook(hookName) ? customAuthorizeHook() : HookMgr.callHook('app.payment.processor.default', 'Authorize'); +}; +var getPayments = function getPayments(order) { + return order.paymentInstruments.toArray().reduce(function (acc, paymentInstrument) { + if (!acc.error) { + var _PaymentMgr$getPaymen = PaymentMgr.getPaymentMethod(paymentInstrument.paymentMethod), + paymentProcessor = _PaymentMgr$getPaymen.paymentProcessor; + if (paymentProcessor) { + var authorizationResult = getAuthorizationResult(paymentProcessor, order, paymentInstrument); + if (authorizationResult.error) { + Transaction.wrap(function () { + OrderMgr.failOrder(order, true); + }); + } + return authorizationResult; + } + Transaction.begin(); + paymentInstrument.paymentTransaction.setTransactionID(order.orderNo); + Transaction.commit(); + } + return acc; + }, {}); +}; +module.exports = getPayments; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/index.js b/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/index.js new file mode 100644 index 000000000..d89026dd0 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/index.js @@ -0,0 +1,8 @@ +"use strict"; + +var getPayments = require('*/cartridge/scripts/checkout/utils/getPayments'); +var validatePaymentMethod = require('*/cartridge/scripts/checkout/utils/validatePaymentMethod'); +module.exports = { + getPayments: getPayments, + validatePaymentMethod: validatePaymentMethod +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/validatePaymentMethod.js b/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/validatePaymentMethod.js new file mode 100644 index 000000000..555b521d8 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/checkout/utils/validatePaymentMethod.js @@ -0,0 +1,22 @@ +"use strict"; + +var PaymentInstrument = require('dw/order/PaymentInstrument'); +var PaymentMgr = require('dw/order/PaymentMgr'); +function validatePaymentMethod(applicablePaymentCards, applicablePaymentMethods) { + return function (paymentInstrument) { + var isValidPaymentMethod = function isValidPaymentMethod() { + var isCard = PaymentInstrument.METHOD_CREDIT_CARD.equals(paymentInstrument.paymentMethod); + var card = PaymentMgr.getPaymentCard(paymentInstrument.creditCardType); + var isValidCard = card && applicablePaymentCards.contains(card) || paymentInstrument.getCreditCardToken(); + // Checks whether payment card is still applicable or if there is a credit card token set. + return !isCard || isValidCard; + }; + var paymentMethod = PaymentMgr.getPaymentMethod(paymentInstrument.getPaymentMethod()); + if (paymentMethod && applicablePaymentMethods.contains(paymentMethod)) { + return isValidPaymentMethod(); + } + var isGiftCertificate = PaymentInstrument.METHOD_GIFT_CERTIFICATE.equals(paymentInstrument.paymentMethod); + return isGiftCertificate; + }; +} +module.exports = validatePaymentMethod; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks.json b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks.json new file mode 100644 index 000000000..b7f90c4eb --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks.json @@ -0,0 +1,20 @@ +{ + "hooks": [ + { + "name": "app.payment.processor.adyen_pos", + "script": "./hooks/payment/processor/adyen_pos" + }, + { + "name": "app.payment.form.processor.adyen_pos", + "script": "./hooks/payment/processor/adyen_pos_form_processor" + }, + { + "name": "app.payment.processor.adyen_component", + "script": "./hooks/payment/processor/adyen_component" + }, + { + "name": "app.payment.form.processor.adyen_component", + "script": "./hooks/payment/processor/adyen_component_form_processor" + } + ] +} diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_component.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_component.js new file mode 100644 index 000000000..4cc0bf1da --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_component.js @@ -0,0 +1,24 @@ +"use strict"; + +/** + * + */ +var middlewares = require('*/cartridge/scripts/hooks/payment/processor/middlewares/index'); +function Handle(basket, paymentInformation) { + return middlewares.handle(basket, paymentInformation); +} + +/** + * Authorizes a payment using a credit card. Customizations may use other processors and custom + * logic to authorize credit card payment. + * @param {number} orderNumber - The current order's number + * @param {dw.order.PaymentInstrument} paymentInstrument - The payment instrument to authorize + * @param {dw.order.PaymentProcessor} paymentProcessor - The payment processor of the current + * payment method + * @return {Object} returns an error object + */ +function Authorize(order, paymentInstrument, paymentProcessor) { + return middlewares.authorize(order, paymentInstrument, paymentProcessor); +} +exports.Handle = Handle; +exports.Authorize = Authorize; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_component_form_processor.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_component_form_processor.js new file mode 100644 index 000000000..60c58a05b --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_component_form_processor.js @@ -0,0 +1,26 @@ +"use strict"; + +var middlewares = require('*/cartridge/scripts/hooks/payment/processor/middlewares/index'); + +/** + * Verifies the required information for billing form is provided. + * @param {Object} req - The request object + * @param {Object} paymentForm - the payment form + * @param {Object} viewFormData - object contains billing form data + * @returns {Object} an object that has error information or payment information + */ +function processForm(req, paymentForm, viewFormData) { + return middlewares.processForm(req, paymentForm, viewFormData); +} + +/** + * Save the credit card information to login account if save card option is selected + * @param {Object} req - The request object + * @param {dw.order.Basket} basket - The current basket + * @param {Object} billingData - payment information + */ +function savePaymentInformation(req, basket, billingData) { + return middlewares.savePaymentInformation(req, basket, billingData); +} +exports.processForm = processForm; +exports.savePaymentInformation = savePaymentInformation; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_pos.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_pos.js new file mode 100644 index 000000000..ba5fec931 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_pos.js @@ -0,0 +1,15 @@ +"use strict"; + +var middlewares = require('*/cartridge/scripts/hooks/payment/processor/middlewares/index'); +function Handle(basket) { + return middlewares.posHandle(basket); +} + +/** + * Authorize + */ +function Authorize(order, paymentInstrument, paymentProcessor) { + return middlewares.posAuthorize(order, paymentInstrument, paymentProcessor); +} +exports.Handle = Handle; +exports.Authorize = Authorize; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_pos_form_processor.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_pos_form_processor.js new file mode 100644 index 000000000..3a0cfa50d --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/adyen_pos_form_processor.js @@ -0,0 +1,27 @@ +"use strict"; + +/** + * Verifies the required information for billing form is provided. + * @param {Object} req - The request object + * @param {Object} paymentForm - the payment form + * @param {Object} viewFormData - object contains billing form data + * @returns {Object} an object that has error information or payment information + */ +function processForm(req, paymentForm, viewFormData) { + var viewData = viewFormData; + viewData.paymentMethod = { + value: paymentForm.paymentMethod.value, + htmlName: paymentForm.paymentMethod.value + }; + return { + error: false, + viewData: viewData + }; +} + +/** + * By default no save payment information is supported + */ +function savePaymentInformation() {} +exports.processForm = processForm; +exports.savePaymentInformation = savePaymentInformation; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/authorize.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/authorize.js new file mode 100644 index 000000000..8c5d1775b --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/authorize.js @@ -0,0 +1,60 @@ +"use strict"; + +var Resource = require('dw/web/Resource'); +var Transaction = require('dw/system/Transaction'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var adyenCheckout = require('*/cartridge/scripts/adyenCheckout'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +function errorHandler() { + var serverErrors = [Resource.msg('error.payment.processor.not.supported', 'checkout', null)]; + return { + authorized: false, + fieldErrors: [], + serverErrors: serverErrors, + error: true + }; +} +function paymentErrorHandler(result) { + AdyenLogs.error_log("Payment failed, result: ".concat(JSON.stringify(result))); + Transaction.rollback(); + return { + error: true + }; +} + +/** + * Authorizes a payment using a credit card. Customizations may use other processors and custom + * logic to authorize credit card payment. + * @param {dw.order.Order} order - The current order + * @param {dw.order.PaymentInstrument} paymentInstrument - The payment instrument to authorize + * @param {dw.order.PaymentProcessor} paymentProcessor - The payment processor of the current + * payment method + * @return {Object} returns an error object + */ +function authorize(order, paymentInstrument, paymentProcessor) { + Transaction.wrap(function () { + paymentInstrument.paymentTransaction.paymentProcessor = paymentProcessor; + }); + Transaction.begin(); + var result = adyenCheckout.createPaymentRequest({ + Order: order, + PaymentInstrument: paymentInstrument + }); + if (result.error) { + return errorHandler(); + } + var checkoutResponse = AdyenHelper.createAdyenCheckoutResponse(result); + if (!checkoutResponse.isFinal) { + return checkoutResponse; + } + if (!checkoutResponse.isSuccessful) { + return paymentErrorHandler(result); + } + AdyenHelper.savePaymentDetails(paymentInstrument, order, result.fullResponse); + Transaction.commit(); + return { + authorized: true, + error: false + }; +} +module.exports = authorize; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/handle.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/handle.js new file mode 100644 index 000000000..c96d3378f --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/handle.js @@ -0,0 +1,59 @@ +"use strict"; + +var Transaction = require('dw/system/Transaction'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var collections = require('*/cartridge/scripts/util/collections'); +var constants = require('*/cartridge/adyenConstants/constants'); +function removeAllPaymentInstruments(currentBasket) { + collections.forEach(currentBasket.getPaymentInstruments(), function (item) { + currentBasket.removePaymentInstrument(item); + }); +} +function convertToSfccCardType(paymentInformation, paymentInstrument) { + var _stateData$paymentMet; + var stateData = JSON.parse(paymentInformation.stateData); + var cardType = paymentInformation.cardType || (stateData === null || stateData === void 0 ? void 0 : (_stateData$paymentMet = stateData.paymentMethod) === null || _stateData$paymentMet === void 0 ? void 0 : _stateData$paymentMet.srcScheme); + var sfccCardType = !paymentInformation.creditCardToken ? AdyenHelper.getSfccCardType(cardType) : paymentInformation.cardType; + paymentInstrument.setCreditCardNumber(paymentInformation.cardNumber); + paymentInstrument.setCreditCardType(sfccCardType); + paymentInstrument.custom.adyenPaymentMethod = sfccCardType; + paymentInstrument.custom["".concat(constants.OMS_NAMESPACE, "_Adyen_Payment_Method")] = sfccCardType; + if (paymentInformation.creditCardToken) { + var firstTwoDigitsFromCurrentYear = AdyenHelper.getFirstTwoNumbersFromYear(); + var expirationYear = firstTwoDigitsFromCurrentYear * 100 + paymentInformation.expirationYear; + paymentInstrument.setCreditCardExpirationMonth(paymentInformation.expirationMonth); + paymentInstrument.setCreditCardExpirationYear(expirationYear); + paymentInstrument.setCreditCardToken(paymentInformation.creditCardToken); + } +} +function handle(basket, paymentInformation) { + var currentBasket = basket; + var cardErrors = {}; + var serverErrors = []; + Transaction.wrap(function () { + var _JSON$parse, _JSON$parse$paymentMe, _JSON$parse2, _JSON$parse2$paymentM; + removeAllPaymentInstruments(currentBasket); + var paymentInstrumentType = AdyenHelper.getPaymentInstrumentType(paymentInformation.isCreditCard); + var paymentInstrument = currentBasket.createPaymentInstrument(paymentInstrumentType, currentBasket.totalGrossPrice); + paymentInstrument.custom.adyenPaymentData = paymentInformation.stateData; + paymentInstrument.custom.adyenMainPaymentInstrument = paymentInstrumentType; + paymentInstrument.custom.adyenPaymentMethod = paymentInformation.adyenPaymentMethod; + if (paymentInformation.partialPaymentsOrder) { + paymentInstrument.custom.adyenPartialPaymentsOrder = session.privacy.partialPaymentData; + } + paymentInstrument.custom.Adyen_Payment_Method_Variant = paymentInformation.stateData ? (_JSON$parse = JSON.parse(paymentInformation.stateData)) === null || _JSON$parse === void 0 ? void 0 : (_JSON$parse$paymentMe = _JSON$parse.paymentMethod) === null || _JSON$parse$paymentMe === void 0 ? void 0 : _JSON$parse$paymentMe.type : null; + paymentInstrument.custom["".concat(constants.OMS_NAMESPACE, "__Adyen_Payment_Method_Variant")] = paymentInformation.stateData ? (_JSON$parse2 = JSON.parse(paymentInformation.stateData)) === null || _JSON$parse2 === void 0 ? void 0 : (_JSON$parse2$paymentM = _JSON$parse2.paymentMethod) === null || _JSON$parse2$paymentM === void 0 ? void 0 : _JSON$parse2$paymentM.type : null; + if (paymentInformation.isCreditCard) { + // If the card wasn't a stored card we need to convert sfccCardType + convertToSfccCardType(paymentInformation, paymentInstrument); + } else { + paymentInstrument.custom["".concat(constants.OMS_NAMESPACE, "__Adyen_Payment_Method")] = paymentInformation.adyenPaymentMethod; + } + }); + return { + fieldErrors: cardErrors, + serverErrors: serverErrors, + error: false + }; +} +module.exports = handle; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/index.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/index.js new file mode 100644 index 000000000..0dfb58c09 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/index.js @@ -0,0 +1,16 @@ +"use strict"; + +var authorize = require('*/cartridge/scripts/hooks/payment/processor/middlewares/authorize'); +var handle = require('*/cartridge/scripts/hooks/payment/processor/middlewares/handle'); +var posHandle = require('*/cartridge/scripts/hooks/payment/processor/middlewares/posHandle'); +var posAuthorize = require('*/cartridge/scripts/hooks/payment/processor/middlewares/posAuthorize'); +var processForm = require('*/cartridge/scripts/hooks/payment/processor/middlewares/processForm'); +var savePaymentInformation = require('*/cartridge/scripts/hooks/payment/processor/middlewares/savePaymentInformation'); +module.exports = { + authorize: authorize, + handle: handle, + posHandle: posHandle, + posAuthorize: posAuthorize, + processForm: processForm, + savePaymentInformation: savePaymentInformation +}; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/posAuthorize.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/posAuthorize.js new file mode 100644 index 000000000..744d23918 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/posAuthorize.js @@ -0,0 +1,42 @@ +"use strict"; + +var server = require('server'); +var Resource = require('dw/web/Resource'); +var Transaction = require('dw/system/Transaction'); +var adyenTerminalApi = require('*/cartridge/scripts/adyenTerminalApi'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); + +/** + * Authorize + */ +function posAuthorize(order, paymentInstrument, paymentProcessor) { + Transaction.wrap(function () { + paymentInstrument.paymentTransaction.transactionID = order.orderNo; + paymentInstrument.paymentTransaction.paymentProcessor = paymentProcessor; + }); + var adyenPaymentForm = server.forms.getForm('billing').adyenPaymentFields; + var terminalId = adyenPaymentForm.terminalId.value; + if (!terminalId) { + AdyenLogs.fatal_log('No terminal selected'); + var errors = [Resource.msg('error.payment.processor.not.supported', 'checkout', null)]; + return { + authorized: false, + fieldErrors: [], + serverErrors: errors, + error: true + }; + } + var result = adyenTerminalApi.createTerminalPayment(order, paymentInstrument, terminalId); + if (result.error) { + AdyenLogs.fatal_log("POS Authorise error, result: ".concat(result.response)); + var _errors = [Resource.msg('error.payment.processor.not.supported', 'checkout', null)]; + return { + authorized: false, + fieldErrors: [], + serverErrors: _errors, + error: true + }; + } + return result; +} +module.exports = posAuthorize; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/posHandle.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/posHandle.js new file mode 100644 index 000000000..f2773e8b7 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/posHandle.js @@ -0,0 +1,18 @@ +"use strict"; + +var Transaction = require('dw/system/Transaction'); +var collections = require('*/cartridge/scripts/util/collections'); +var constants = require('*/cartridge/adyenConstants/constants'); +function posHandle(basket) { + Transaction.wrap(function () { + collections.forEach(basket.getPaymentInstruments(), function (item) { + basket.removePaymentInstrument(item); + }); + var paymentInstrument = basket.createPaymentInstrument(constants.METHOD_ADYEN_POS, basket.totalGrossPrice); + paymentInstrument.custom.adyenPaymentMethod = 'POS Terminal'; + }); + return { + error: false + }; +} +module.exports = posHandle; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/processForm.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/processForm.js new file mode 100644 index 000000000..08f8db8a3 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/processForm.js @@ -0,0 +1,114 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers'); +var array = require('*/cartridge/scripts/util/array'); +var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper'); +var AdyenLogs = require('*/cartridge/scripts/adyenCustomLogs'); +function getCreditCardErrors(req, isCreditCard, paymentForm) { + if (!req.form.storedPaymentUUID && isCreditCard) { + // verify credit card form data + return COHelpers.validateCreditCard(paymentForm); + } + return {}; +} +function setSessionPrivacy(_ref) { + var adyenPaymentFields = _ref.adyenPaymentFields; + session.privacy.adyenFingerprint = adyenPaymentFields.adyenFingerprint.value; +} +function getPaymentInstrument(req, storedPaymentMethodId) { + var currentCustomer = req.currentCustomer; + var findById = function findById(item) { + return storedPaymentMethodId === item.getCreditCardToken(); + }; + var paymentInstruments = AdyenHelper.getCustomer(currentCustomer).getProfile().getWallet().getPaymentInstruments(); + return array.find(paymentInstruments, findById); +} + +// process payment information +function getProcessFormResult(paymentMethod, req, viewData) { + var _req$currentCustomer$ = req.currentCustomer.raw, + authenticated = _req$currentCustomer$.authenticated, + registered = _req$currentCustomer$.registered; + if (paymentMethod.storedPaymentMethodId && authenticated && registered) { + var paymentInstrument = getPaymentInstrument(req, paymentMethod.storedPaymentMethodId); + return { + error: false, + viewData: _objectSpread(_objectSpread({}, viewData), {}, { + paymentInformation: _objectSpread(_objectSpread({}, viewData.paymentInformation), {}, { + cardNumber: paymentInstrument.creditCardNumber, + cardType: paymentInstrument.creditCardType, + securityCode: req.form.securityCode, + expirationMonth: paymentInstrument.creditCardExpirationMonth, + expirationYear: paymentInstrument.creditCardExpirationYear, + creditCardToken: paymentInstrument.creditCardToken + }) + }) + }; + } + return { + error: false, + viewData: viewData + }; +} +function getViewData(viewFormData, paymentForm, isCreditCard, adyenPaymentMethod, adyenIssuerName) { + return _objectSpread(_objectSpread({}, viewFormData), {}, { + paymentMethod: { + value: paymentForm.paymentMethod.value, + htmlName: paymentForm.paymentMethod.value + }, + paymentInformation: { + isCreditCard: isCreditCard, + cardType: paymentForm.creditCardFields.cardType.value, + cardNumber: paymentForm.creditCardFields.cardNumber.value, + adyenPaymentMethod: adyenPaymentMethod, + adyenIssuerName: adyenIssuerName, + stateData: paymentForm.adyenPaymentFields.adyenStateData.value, + partialPaymentsOrder: paymentForm.adyenPaymentFields.adyenPartialPaymentsOrder.value + }, + saveCard: paymentForm.creditCardFields.saveCard.checked + }); +} +function getPaymentMethodFromForm(paymentForm) { + try { + var _paymentForm$adyenPay, _paymentForm$adyenPay2; + return JSON.parse((_paymentForm$adyenPay = paymentForm.adyenPaymentFields) === null || _paymentForm$adyenPay === void 0 ? void 0 : (_paymentForm$adyenPay2 = _paymentForm$adyenPay.adyenStateData) === null || _paymentForm$adyenPay2 === void 0 ? void 0 : _paymentForm$adyenPay2.value).paymentMethod; + } catch (error) { + AdyenLogs.error_log('Failed to parse payment form stateData'); + return {}; + } +} + +/** + * Verifies the required information for billing form is provided. + * @param {Object} req - The request object + * @param {Object} paymentForm - the payment form + * @param {Object} viewFormData - object contains billing form data + * @returns {Object} an object that has error information or payment information + */ +function processForm(req, paymentForm, viewFormData) { + var brand = JSON.stringify(req.form.brandCode); + var isCreditCard = req.form.brandCode === 'scheme' || (brand === null || brand === void 0 ? void 0 : brand.indexOf('storedCard')) > -1; + var creditCardErrors = getCreditCardErrors(req, isCreditCard, paymentForm); + if (Object.keys(creditCardErrors).length) { + return { + fieldErrors: creditCardErrors, + error: true + }; + } + setSessionPrivacy(paymentForm); + var _req$form = req.form, + _req$form$adyenPaymen = _req$form.adyenPaymentMethod, + adyenPaymentMethod = _req$form$adyenPaymen === void 0 ? null : _req$form$adyenPaymen, + _req$form$adyenIssuer = _req$form.adyenIssuerName, + adyenIssuerName = _req$form$adyenIssuer === void 0 ? null : _req$form$adyenIssuer; + var paymentMethod = getPaymentMethodFromForm(paymentForm); + var viewData = getViewData(viewFormData, paymentForm, isCreditCard, adyenPaymentMethod, adyenIssuerName); + return getProcessFormResult(paymentMethod, req, viewData); +} +module.exports = processForm; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/savePaymentInformation.js b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/savePaymentInformation.js new file mode 100644 index 000000000..d7dee7580 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/scripts/hooks/payment/processor/middlewares/savePaymentInformation.js @@ -0,0 +1,55 @@ +"use strict"; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var CustomerMgr = require('dw/customer/CustomerMgr'); +var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers'); +function hasValidBillingData(_ref) { + var storedPaymentUUID = _ref.storedPaymentUUID, + saveCard = _ref.saveCard, + paymentMethod = _ref.paymentMethod; + var isCreditCard = paymentMethod.value === 'CREDIT_CARD'; + return !storedPaymentUUID && saveCard && isCreditCard; +} +function isValidCustomer(_ref2) { + var authenticated = _ref2.authenticated, + registered = _ref2.registered; + return authenticated && registered; +} +function isValid(raw, billingData) { + return isValidCustomer(raw) && hasValidBillingData(billingData); +} + +/** + * Save the credit card information to login account if save card option is selected + * @param {Object} req - The request object + * @param {dw.order.Basket} basket - The current basket + * @param {Object} billingData - payment information + */ +function savePaymentInformation(req, basket, billingData) { + var _req$currentCustomer = req.currentCustomer, + raw = _req$currentCustomer.raw, + profile = _req$currentCustomer.profile, + wallet = _req$currentCustomer.wallet; + if (isValid(raw, billingData)) { + var customer = CustomerMgr.getCustomerByCustomerNumber(profile.customerNo); + var saveCardResult = COHelpers.savePaymentInstrumentToWallet(billingData, basket, customer); + wallet.paymentInstruments.push(_objectSpread(_objectSpread({ + creditCardHolder: saveCardResult.creditCardHolder, + maskedCreditCardNumber: saveCardResult.maskedCreditCardNumber, + creditCardType: saveCardResult.creditCardType, + creditCardExpirationMonth: saveCardResult.creditCardExpirationMonth, + creditCardExpirationYear: saveCardResult.creditCardExpirationYear, + UUID: saveCardResult.UUID + }, 'creditCardNumber' in saveCardResult && { + creditCardNumber: saveCardResult.creditCardNumber + }), {}, { + raw: saveCardResult + })); + } +} +module.exports = savePaymentInformation; \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenAccount.js b/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenAccount.js new file mode 100644 index 000000000..88cd10ff5 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenAccount.js @@ -0,0 +1,148 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenAccount.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenAccount.js": +/*!*******************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenAccount.js ***! + \*******************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nvar _require = __webpack_require__(/*! ./commons/index */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js\"),\n onFieldValid = _require.onFieldValid,\n onBrand = _require.onBrand,\n createSession = _require.createSession;\nvar store = __webpack_require__(/*! ../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar checkout;\nvar card;\n\n// Store configuration\nstore.checkoutConfiguration.amount = {\n value: 0,\n currency: 'EUR'\n};\nstore.checkoutConfiguration.paymentMethodsConfiguration = {\n card: {\n enableStoreDetails: false,\n hasHolderName: true,\n holderNameRequired: true,\n installments: [],\n onBrand: onBrand,\n onFieldValid: onFieldValid,\n onChange: function onChange(state) {\n store.isValid = state.isValid;\n store.componentState = state;\n }\n }\n};\n\n// Handle Payment action\nfunction handleAction(action) {\n checkout.createFromAction(action).mount('#action-container');\n $('#action-modal').modal({\n backdrop: 'static',\n keyboard: false\n });\n}\n\n// confirm onAdditionalDetails event and paymentsDetails response\nstore.checkoutConfiguration.onAdditionalDetails = function (state) {\n $.ajax({\n type: 'POST',\n url: 'Adyen-PaymentsDetails',\n data: JSON.stringify({\n data: state.data\n }),\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function success(data) {\n if (data.isSuccessful) {\n window.location.href = window.redirectUrl;\n } else if (!data.isFinal && _typeof(data.action) === 'object') {\n handleAction(data.action);\n } else {\n $('#action-modal').modal('hide');\n document.getElementById('cardError').style.display = 'block';\n }\n }\n });\n};\nfunction initializeCardComponent() {\n return _initializeCardComponent.apply(this, arguments);\n}\nfunction _initializeCardComponent() {\n _initializeCardComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n var session, cardNode;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return createSession();\n case 2:\n session = _context.sent;\n store.checkoutConfiguration.session = {\n id: session.id,\n sessionData: session.sessionData\n };\n cardNode = document.getElementById('card');\n _context.next = 7;\n return AdyenCheckout(store.checkoutConfiguration);\n case 7:\n checkout = _context.sent;\n card = checkout.create('card').mount(cardNode);\n case 9:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return _initializeCardComponent.apply(this, arguments);\n}\nvar formErrorsExist = false;\nfunction submitAddCard() {\n var form = $(document.getElementById('payment-form'));\n $.ajax({\n type: 'POST',\n url: form.attr('action'),\n data: form.serialize(),\n async: false,\n success: function success(data) {\n if (data.redirectAction) {\n handleAction(data.redirectAction);\n } else if (data.redirectUrl) {\n window.location.href = data.redirectUrl;\n } else if (data.error) {\n formErrorsExist = true;\n }\n }\n });\n}\ninitializeCardComponent();\n\n// Add Payment Button event handler\n$('button[value=\"add-new-payment\"]').on('click', function (event) {\n if (store.isValid) {\n document.querySelector('#adyenStateData').value = JSON.stringify(store.componentState.data);\n submitAddCard();\n if (formErrorsExist) {\n return;\n }\n event.preventDefault();\n } else {\n var _card;\n (_card = card) === null || _card === void 0 ? void 0 : _card.showValidation();\n }\n});\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenAccount.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js": +/*!********************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nmodule.exports.onFieldValid = function onFieldValid(data) {\n if (data.endDigits) {\n store.endDigits = data.endDigits;\n document.querySelector('#cardNumber').value = store.maskedCardNumber;\n }\n};\nmodule.exports.onBrand = function onBrand(brandObject) {\n document.querySelector('#cardType').value = brandObject.brand;\n};\n\n/**\n * Makes an ajax call to the controller function CreateSession\n */\nmodule.exports.createSession = /*#__PURE__*/function () {\n var _createSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n return _context.abrupt(\"return\", $.ajax({\n url: window.sessionsUrl,\n type: 'get'\n }));\n case 1:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n function createSession() {\n return _createSession.apply(this, arguments);\n }\n return createSession;\n}();\n\n/**\n * Makes an ajax call to the controller function FetchGiftCards\n */\nmodule.exports.fetchGiftCards = /*#__PURE__*/function () {\n var _fetchGiftCards = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n return _context2.abrupt(\"return\", $.ajax({\n url: window.fetchGiftCardsUrl,\n type: 'get'\n }));\n case 1:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n function fetchGiftCards() {\n return _fetchGiftCards.apply(this, arguments);\n }\n return fetchGiftCards;\n}();\nmodule.exports.checkIfExpressMethodsAreReady = function checkIfExpressMethodsAreReady() {\n var expressMethodsConfig = {\n applepay: window.isApplePayExpressEnabled === 'true',\n amazonpay: window.isAmazonPayExpressEnabled === 'true'\n };\n var enabledExpressMethods = [];\n Object.keys(expressMethodsConfig).forEach(function (key) {\n if (expressMethodsConfig[key]) {\n enabledExpressMethods.push(key);\n }\n });\n enabledExpressMethods = enabledExpressMethods.sort();\n var loadedExpressMethods = window.loadedExpressMethods && window.loadedExpressMethods.length ? window.loadedExpressMethods.sort() : [];\n var areAllMethodsReady = JSON.stringify(enabledExpressMethods) === JSON.stringify(loadedExpressMethods);\n if (!enabledExpressMethods.length || areAllMethodsReady) {\n var _document$getElementB, _document$getElementB2;\n (_document$getElementB = document.getElementById('express-loader-container')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.classList.add('hidden');\n (_document$getElementB2 = document.getElementById('express-container')) === null || _document$getElementB2 === void 0 ? void 0 : _document$getElementB2.classList.remove('hidden');\n }\n};\nmodule.exports.updateLoadedExpressMethods = function updateLoadedExpressMethods(method) {\n if (!window.loadedExpressMethods) {\n window.loadedExpressMethods = [];\n }\n if (!window.loadedExpressMethods.includes(method)) {\n window.loadedExpressMethods.push(method);\n }\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/store/index.js": +/*!************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/store/index.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nvar _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, _descriptor12, _descriptor13;\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }\nfunction _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); }\nvar _require = __webpack_require__(/*! mobx */ \"./node_modules/mobx/dist/mobx.esm.js\"),\n observable = _require.observable,\n computed = _require.computed;\nvar Store = (_class = /*#__PURE__*/function () {\n function Store() {\n _classCallCheck(this, Store);\n _defineProperty(this, \"MASKED_CC_PREFIX\", '************');\n _initializerDefineProperty(this, \"checkout\", _descriptor, this);\n _initializerDefineProperty(this, \"endDigits\", _descriptor2, this);\n _initializerDefineProperty(this, \"selectedMethod\", _descriptor3, this);\n _initializerDefineProperty(this, \"componentsObj\", _descriptor4, this);\n _initializerDefineProperty(this, \"checkoutConfiguration\", _descriptor5, this);\n _initializerDefineProperty(this, \"formErrorsExist\", _descriptor6, this);\n _initializerDefineProperty(this, \"isValid\", _descriptor7, this);\n _initializerDefineProperty(this, \"paypalTerminatedEarly\", _descriptor8, this);\n _initializerDefineProperty(this, \"componentState\", _descriptor9, this);\n _initializerDefineProperty(this, \"brand\", _descriptor10, this);\n _initializerDefineProperty(this, \"partialPaymentsOrderObj\", _descriptor11, this);\n _initializerDefineProperty(this, \"giftCardComponentListenersAdded\", _descriptor12, this);\n _initializerDefineProperty(this, \"addedGiftCards\", _descriptor13, this);\n }\n _createClass(Store, [{\n key: \"maskedCardNumber\",\n get: function get() {\n return \"\".concat(this.MASKED_CC_PREFIX).concat(this.endDigits);\n }\n }, {\n key: \"selectedPayment\",\n get: function get() {\n return this.componentsObj[this.selectedMethod];\n }\n }, {\n key: \"selectedPaymentIsValid\",\n get: function get() {\n var _this$selectedPayment;\n return !!((_this$selectedPayment = this.selectedPayment) !== null && _this$selectedPayment !== void 0 && _this$selectedPayment.isValid);\n }\n }, {\n key: \"stateData\",\n get: function get() {\n var _this$selectedPayment2;\n return ((_this$selectedPayment2 = this.selectedPayment) === null || _this$selectedPayment2 === void 0 ? void 0 : _this$selectedPayment2.stateData) || {\n paymentMethod: _objectSpread({\n type: this.selectedMethod\n }, this.brand ? {\n brand: this.brand\n } : undefined)\n };\n }\n }, {\n key: \"updateSelectedPayment\",\n value: function updateSelectedPayment(method, key, val) {\n this.componentsObj[method][key] = val;\n }\n }]);\n return Store;\n}(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, \"checkout\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, \"endDigits\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, \"selectedMethod\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, \"componentsObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, \"checkoutConfiguration\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return window.Configuration || {};\n }\n}), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, \"formErrorsExist\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, \"isValid\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, \"paypalTerminatedEarly\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor9 = _applyDecoratedDescriptor(_class.prototype, \"componentState\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor10 = _applyDecoratedDescriptor(_class.prototype, \"brand\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor11 = _applyDecoratedDescriptor(_class.prototype, \"partialPaymentsOrderObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor12 = _applyDecoratedDescriptor(_class.prototype, \"giftCardComponentListenersAdded\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor13 = _applyDecoratedDescriptor(_class.prototype, \"addedGiftCards\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _applyDecoratedDescriptor(_class.prototype, \"maskedCardNumber\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"maskedCardNumber\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPayment\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPayment\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPaymentIsValid\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPaymentIsValid\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"stateData\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"stateData\"), _class.prototype)), _class);\nmodule.exports = new Store();\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/store/index.js?"); + +/***/ }), + +/***/ "./node_modules/mobx/dist/mobx.esm.js": +/*!********************************************!*\ + !*** ./node_modules/mobx/dist/mobx.esm.js ***! + \********************************************/ +/*! exports provided: $mobx, FlowCancellationError, ObservableMap, ObservableSet, Reaction, _allowStateChanges, _allowStateChangesInsideComputed, _allowStateReadsEnd, _allowStateReadsStart, _autoAction, _endAction, _getAdministration, _getGlobalState, _interceptReads, _isComputingDerivation, _resetGlobalState, _startAction, action, autorun, comparer, computed, configure, createAtom, defineProperty, entries, extendObservable, flow, flowResult, get, getAtom, getDebugName, getDependencyTree, getObserverTree, has, intercept, isAction, isBoxedObservable, isComputed, isComputedProp, isFlow, isFlowCancellationError, isObservable, isObservableArray, isObservableMap, isObservableObject, isObservableProp, isObservableSet, keys, makeAutoObservable, makeObservable, observable, observe, onBecomeObserved, onBecomeUnobserved, onReactionError, override, ownKeys, reaction, remove, runInAction, set, spy, toJS, trace, transaction, untracked, values, when */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"$mobx\", function() { return $mobx; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"FlowCancellationError\", function() { return FlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableMap\", function() { return ObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableSet\", function() { return ObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Reaction\", function() { return Reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChanges\", function() { return allowStateChanges; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChangesInsideComputed\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsEnd\", function() { return allowStateReadsEnd; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsStart\", function() { return allowStateReadsStart; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_autoAction\", function() { return autoAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_endAction\", function() { return _endAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getAdministration\", function() { return getAdministration; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getGlobalState\", function() { return getGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_interceptReads\", function() { return interceptReads; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_isComputingDerivation\", function() { return isComputingDerivation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_resetGlobalState\", function() { return resetGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_startAction\", function() { return _startAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"action\", function() { return action; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"autorun\", function() { return autorun; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"comparer\", function() { return comparer; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"computed\", function() { return computed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"configure\", function() { return configure; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createAtom\", function() { return createAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"defineProperty\", function() { return apiDefineProperty; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"entries\", function() { return entries; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"extendObservable\", function() { return extendObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flow\", function() { return flow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flowResult\", function() { return flowResult; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"get\", function() { return get; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getAtom\", function() { return getAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDebugName\", function() { return getDebugName; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDependencyTree\", function() { return getDependencyTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getObserverTree\", function() { return getObserverTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"has\", function() { return has; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"intercept\", function() { return intercept; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isAction\", function() { return isAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isBoxedObservable\", function() { return isObservableValue; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputed\", function() { return isComputed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputedProp\", function() { return isComputedProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlow\", function() { return isFlow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlowCancellationError\", function() { return isFlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservable\", function() { return isObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableArray\", function() { return isObservableArray; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableMap\", function() { return isObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableObject\", function() { return isObservableObject; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableProp\", function() { return isObservableProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableSet\", function() { return isObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"keys\", function() { return keys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeAutoObservable\", function() { return makeAutoObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeObservable\", function() { return makeObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observable\", function() { return observable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observe\", function() { return observe; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeObserved\", function() { return onBecomeObserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeUnobserved\", function() { return onBecomeUnobserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onReactionError\", function() { return onReactionError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"override\", function() { return override; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ownKeys\", function() { return apiOwnKeys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"reaction\", function() { return reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"remove\", function() { return remove; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"runInAction\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"set\", function() { return set; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"spy\", function() { return spy; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toJS\", function() { return toJS; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"trace\", function() { return trace; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"transaction\", function() { return transaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"untracked\", function() { return untracked; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"values\", function() { return values; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"when\", function() { return when; });\nvar niceErrors = {\n 0: \"Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'\",\n 1: function _(annotationType, key) {\n return \"Cannot apply '\" + annotationType + \"' to '\" + key.toString() + \"': Field not found.\";\n },\n\n /*\r\n 2(prop) {\r\n return `invalid decorator for '${prop.toString()}'`\r\n },\r\n 3(prop) {\r\n return `Cannot decorate '${prop.toString()}': action can only be used on properties with a function value.`\r\n },\r\n 4(prop) {\r\n return `Cannot decorate '${prop.toString()}': computed can only be used on getter properties.`\r\n },\r\n */\n 5: \"'keys()' can only be used on observable objects, arrays, sets and maps\",\n 6: \"'values()' can only be used on observable objects, arrays, sets and maps\",\n 7: \"'entries()' can only be used on observable objects, arrays and maps\",\n 8: \"'set()' can only be used on observable objects, arrays and maps\",\n 9: \"'remove()' can only be used on observable objects, arrays and maps\",\n 10: \"'has()' can only be used on observable objects, arrays and maps\",\n 11: \"'get()' can only be used on observable objects, arrays and maps\",\n 12: \"Invalid annotation\",\n 13: \"Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 14: \"Intercept handlers should return nothing or a change object\",\n 15: \"Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 16: \"Modification exception: the internal structure of an observable array was changed.\",\n 17: function _(index, length) {\n return \"[mobx.array] Index out of bounds, \" + index + \" is larger than \" + length;\n },\n 18: \"mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js\",\n 19: function _(other) {\n return \"Cannot initialize from classes that inherit from Map: \" + other.constructor.name;\n },\n 20: function _(other) {\n return \"Cannot initialize map from \" + other;\n },\n 21: function _(dataStructure) {\n return \"Cannot convert to map from '\" + dataStructure + \"'\";\n },\n 22: \"mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js\",\n 23: \"It is not possible to get index atoms from arrays\",\n 24: function _(thing) {\n return \"Cannot obtain administration from \" + thing;\n },\n 25: function _(property, name) {\n return \"the entry '\" + property + \"' does not exist in the observable map '\" + name + \"'\";\n },\n 26: \"please specify a property\",\n 27: function _(property, name) {\n return \"no observable property '\" + property.toString() + \"' found on the observable object '\" + name + \"'\";\n },\n 28: function _(thing) {\n return \"Cannot obtain atom from \" + thing;\n },\n 29: \"Expecting some object\",\n 30: \"invalid action stack. did you forget to finish an action?\",\n 31: \"missing option for computed: get\",\n 32: function _(name, derivation) {\n return \"Cycle detected in computation \" + name + \": \" + derivation;\n },\n 33: function _(name) {\n return \"The setter of computed value '\" + name + \"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?\";\n },\n 34: function _(name) {\n return \"[ComputedValue '\" + name + \"'] It is not possible to assign a new value to a computed value.\";\n },\n 35: \"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`\",\n 36: \"isolateGlobalState should be called before MobX is running any reactions\",\n 37: function _(method) {\n return \"[mobx] `observableArray.\" + method + \"()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice().\" + method + \"()` instead\";\n },\n 38: \"'ownKeys()' can only be used on observable objects\",\n 39: \"'defineProperty()' can only be used on observable objects\"\n};\nvar errors = true ? niceErrors : undefined;\nfunction die(error) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n if (true) {\n var e = typeof error === \"string\" ? error : errors[error];\n if (typeof e === \"function\") e = e.apply(null, args);\n throw new Error(\"[MobX] \" + e);\n }\n\n throw new Error(typeof error === \"number\" ? \"[MobX] minified error nr: \" + error + (args.length ? \" \" + args.map(String).join(\",\") : \"\") + \". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts\" : \"[MobX] \" + error);\n}\n\nvar mockGlobal = {};\nfunction getGlobal() {\n if (typeof globalThis !== \"undefined\") {\n return globalThis;\n }\n\n if (typeof window !== \"undefined\") {\n return window;\n }\n\n if (typeof global !== \"undefined\") {\n return global;\n }\n\n if (typeof self !== \"undefined\") {\n return self;\n }\n\n return mockGlobal;\n}\n\nvar assign = Object.assign;\nvar getDescriptor = Object.getOwnPropertyDescriptor;\nvar defineProperty = Object.defineProperty;\nvar objectPrototype = Object.prototype;\nvar EMPTY_ARRAY = [];\nObject.freeze(EMPTY_ARRAY);\nvar EMPTY_OBJECT = {};\nObject.freeze(EMPTY_OBJECT);\nvar hasProxy = typeof Proxy !== \"undefined\";\nvar plainObjectString = /*#__PURE__*/Object.toString();\nfunction assertProxies() {\n if (!hasProxy) {\n die( true ? \"`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`\" : undefined);\n }\n}\nfunction warnAboutProxyRequirement(msg) {\n if ( true && globalState.verifyProxies) {\n die(\"MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to \" + msg);\n }\n}\nfunction getNextId() {\n return ++globalState.mobxGuid;\n}\n/**\r\n * Makes sure that the provided function is invoked at most once.\r\n */\n\nfunction once(func) {\n var invoked = false;\n return function () {\n if (invoked) {\n return;\n }\n\n invoked = true;\n return func.apply(this, arguments);\n };\n}\nvar noop = function noop() {};\nfunction isFunction(fn) {\n return typeof fn === \"function\";\n}\nfunction isStringish(value) {\n var t = typeof value;\n\n switch (t) {\n case \"string\":\n case \"symbol\":\n case \"number\":\n return true;\n }\n\n return false;\n}\nfunction isObject(value) {\n return value !== null && typeof value === \"object\";\n}\nfunction isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n\n var proto = Object.getPrototypeOf(value);\n\n if (proto == null) {\n return true;\n }\n\n var protoConstructor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof protoConstructor === \"function\" && protoConstructor.toString() === plainObjectString;\n} // https://stackoverflow.com/a/37865170\n\nfunction isGenerator(obj) {\n var constructor = obj == null ? void 0 : obj.constructor;\n\n if (!constructor) {\n return false;\n }\n\n if (\"GeneratorFunction\" === constructor.name || \"GeneratorFunction\" === constructor.displayName) {\n return true;\n }\n\n return false;\n}\nfunction addHiddenProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\nfunction addHiddenFinalProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\nfunction createInstanceofPredicate(name, theClass) {\n var propName = \"isMobX\" + name;\n theClass.prototype[propName] = true;\n return function (x) {\n return isObject(x) && x[propName] === true;\n };\n}\nfunction isES6Map(thing) {\n return thing instanceof Map;\n}\nfunction isES6Set(thing) {\n return thing instanceof Set;\n}\nvar hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== \"undefined\";\n/**\r\n * Returns the following: own enumerable keys and symbols.\r\n */\n\nfunction getPlainObjectKeys(object) {\n var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway...\n\n if (!hasGetOwnPropertySymbols) {\n return keys;\n }\n\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (!symbols.length) {\n return keys;\n }\n\n return [].concat(keys, symbols.filter(function (s) {\n return objectPrototype.propertyIsEnumerable.call(object, s);\n }));\n} // From Immer utils\n// Returns all own keys, including non-enumerable and symbolic\n\nvar ownKeys = typeof Reflect !== \"undefined\" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {\n return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));\n} :\n/* istanbul ignore next */\nObject.getOwnPropertyNames;\nfunction stringifyKey(key) {\n if (typeof key === \"string\") {\n return key;\n }\n\n if (typeof key === \"symbol\") {\n return key.toString();\n }\n\n return new String(key).toString();\n}\nfunction toPrimitive(value) {\n return value === null ? null : typeof value === \"object\" ? \"\" + value : value;\n}\nfunction hasProp(target, prop) {\n return objectPrototype.hasOwnProperty.call(target, prop);\n} // From Immer utils\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {\n // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up\n\n ownKeys(target).forEach(function (key) {\n res[key] = getDescriptor(target, key);\n });\n return res;\n};\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n\n _setPrototypeOf(subClass, superClass);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n if (it) return (it = it.call(o)).next.bind(it);\n\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n return function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar storedAnnotationsSymbol = /*#__PURE__*/Symbol(\"mobx-stored-annotations\");\n/**\r\n * Creates a function that acts as\r\n * - decorator\r\n * - annotation object\r\n */\n\nfunction createDecoratorAnnotation(annotation) {\n function decorator(target, property) {\n storeAnnotation(target, property, annotation);\n }\n\n return Object.assign(decorator, annotation);\n}\n/**\r\n * Stores annotation to prototype,\r\n * so it can be inspected later by `makeObservable` called from constructor\r\n */\n\nfunction storeAnnotation(prototype, key, annotation) {\n if (!hasProp(prototype, storedAnnotationsSymbol)) {\n addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));\n } // @override must override something\n\n\n if ( true && isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n die(\"'\" + fieldName + \"' is decorated with 'override', \" + \"but no such decorated member was found on prototype.\");\n } // Cannot re-decorate\n\n\n assertNotDecorated(prototype, annotation, key); // Ignore override\n\n if (!isOverride(annotation)) {\n prototype[storedAnnotationsSymbol][key] = annotation;\n }\n}\n\nfunction assertNotDecorated(prototype, annotation, key) {\n if ( true && !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '@\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already decorated with '@\" + currentAnnotationType + \"'.\") + \"\\nRe-decorating fields is not allowed.\" + \"\\nUse '@override' decorator for methods overridden by subclass.\");\n }\n}\n/**\r\n * Collects annotations from prototypes and stores them on target (instance)\r\n */\n\n\nfunction collectStoredAnnotations(target) {\n if (!hasProp(target, storedAnnotationsSymbol)) {\n if ( true && !target[storedAnnotationsSymbol]) {\n die(\"No annotations were passed to makeObservable, but no decorated members have been found either\");\n } // We need a copy as we will remove annotation from the list once it's applied.\n\n\n addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));\n }\n\n return target[storedAnnotationsSymbol];\n}\n\nvar $mobx = /*#__PURE__*/Symbol(\"mobx administration\");\nvar Atom = /*#__PURE__*/function () {\n // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed\n\n /**\r\n * Create a new atom. For debugging purposes it is recommended to give it a name.\r\n * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.\r\n */\n function Atom(name_) {\n if (name_ === void 0) {\n name_ = true ? \"Atom@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.isPendingUnobservation_ = false;\n this.isBeingObserved_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n this.name_ = name_;\n } // onBecomeObservedListeners\n\n\n var _proto = Atom.prototype;\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Invoke this method to notify mobx that your atom has been used somehow.\r\n * Returns true if there is currently a reactive context.\r\n */\n ;\n\n _proto.reportObserved = function reportObserved$1() {\n return reportObserved(this);\n }\n /**\r\n * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.\r\n */\n ;\n\n _proto.reportChanged = function reportChanged() {\n startBatch();\n propagateChanged(this);\n endBatch();\n };\n\n _proto.toString = function toString() {\n return this.name_;\n };\n\n return Atom;\n}();\nvar isAtom = /*#__PURE__*/createInstanceofPredicate(\"Atom\", Atom);\nfunction createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {\n if (onBecomeObservedHandler === void 0) {\n onBecomeObservedHandler = noop;\n }\n\n if (onBecomeUnobservedHandler === void 0) {\n onBecomeUnobservedHandler = noop;\n }\n\n var atom = new Atom(name); // default `noop` listener will not initialize the hook Set\n\n if (onBecomeObservedHandler !== noop) {\n onBecomeObserved(atom, onBecomeObservedHandler);\n }\n\n if (onBecomeUnobservedHandler !== noop) {\n onBecomeUnobserved(atom, onBecomeUnobservedHandler);\n }\n\n return atom;\n}\n\nfunction identityComparer(a, b) {\n return a === b;\n}\n\nfunction structuralComparer(a, b) {\n return deepEqual(a, b);\n}\n\nfunction shallowComparer(a, b) {\n return deepEqual(a, b, 1);\n}\n\nfunction defaultComparer(a, b) {\n if (Object.is) {\n return Object.is(a, b);\n }\n\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n}\n\nvar comparer = {\n identity: identityComparer,\n structural: structuralComparer,\n \"default\": defaultComparer,\n shallow: shallowComparer\n};\n\nfunction deepEnhancer(v, _, name) {\n // it is an observable already, done\n if (isObservable(v)) {\n return v;\n } // something that can be converted and mutated?\n\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name\n });\n }\n\n if (typeof v === \"function\" && !isAction(v) && !isFlow(v)) {\n if (isGenerator(v)) {\n return flow(v);\n } else {\n return autoAction(name, v);\n }\n }\n\n return v;\n}\nfunction shallowEnhancer(v, _, name) {\n if (v === undefined || v === null) {\n return v;\n }\n\n if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {\n return v;\n }\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name,\n deep: false\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name,\n deep: false\n });\n }\n\n if (true) {\n die(\"The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets\");\n }\n}\nfunction referenceEnhancer(newValue) {\n // never turn into an observable\n return newValue;\n}\nfunction refStructEnhancer(v, oldValue) {\n if ( true && isObservable(v)) {\n die(\"observable.struct should not be used with observable values\");\n }\n\n if (deepEqual(v, oldValue)) {\n return oldValue;\n }\n\n return v;\n}\n\nvar OVERRIDE = \"override\";\nvar override = /*#__PURE__*/createDecoratorAnnotation({\n annotationType_: OVERRIDE,\n make_: make_,\n extend_: extend_\n});\nfunction isOverride(annotation) {\n return annotation.annotationType_ === OVERRIDE;\n}\n\nfunction make_(adm, key) {\n // Must not be plain object\n if ( true && adm.isPlainObject_) {\n die(\"Cannot apply '\" + this.annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + this.annotationType_ + \"' cannot be used on plain objects.\"));\n } // Must override something\n\n\n if ( true && !hasProp(adm.appliedAnnotations_, key)) {\n die(\"'\" + adm.name_ + \".\" + key.toString() + \"' is annotated with '\" + this.annotationType_ + \"', \" + \"but no such annotated member was found on prototype.\");\n }\n\n return 0\n /* Cancel */\n ;\n}\n\nfunction extend_(adm, key, descriptor, proxyTrap) {\n die(\"'\" + this.annotationType_ + \"' can only be used with 'makeObservable'\");\n}\n\nfunction createActionAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$1,\n extend_: extend_$1\n };\n}\n\nfunction make_$1(adm, key, descriptor, source) {\n var _this$options_;\n\n // bound\n if ((_this$options_ = this.options_) != null && _this$options_.bound) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n } // own\n\n\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n\n\n if (isAction(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);\n defineProperty(source, key, actionDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$1(adm, key, descriptor, proxyTrap) {\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);\n return adm.defineProperty_(key, actionDescriptor, proxyTrap);\n}\n\nfunction assertActionDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a function value.\"));\n }\n}\n\nfunction createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;\n\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertActionDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n\n if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {\n var _adm$proxy_;\n\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return {\n value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false, // https://github.com/mobxjs/mobx/discussions/3140\n (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createFlowAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$2,\n extend_: extend_$2\n };\n}\n\nfunction make_$2(adm, key, descriptor, source) {\n var _this$options_;\n\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n // bound - must annotate protos to support super.flow()\n\n\n if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {\n if (this.extend_(adm, key, descriptor, false) === null) {\n return 0\n /* Cancel */\n ;\n }\n }\n\n if (isFlow(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);\n defineProperty(source, key, flowDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$2(adm, key, descriptor, proxyTrap) {\n var _this$options_2;\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);\n return adm.defineProperty_(key, flowDescriptor, proxyTrap);\n}\n\nfunction assertFlowDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a generator function value.\"));\n }\n}\n\nfunction createFlowDescriptor(adm, annotation, key, descriptor, bound, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertFlowDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value; // In case of flow.bound, the descriptor can be from already annotated prototype\n\n if (!isFlow(value)) {\n value = flow(value);\n }\n\n if (bound) {\n var _adm$proxy_;\n\n // We do not keep original function around, so we bind the existing flow\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); // This is normally set by `flow`, but `bind` returns new function...\n\n value.isMobXFlow = true;\n }\n\n return {\n value: value,\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createComputedAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$3,\n extend_: extend_$3\n };\n}\n\nfunction make_$3(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$3(adm, key, descriptor, proxyTrap) {\n assertComputedDescriptor(adm, this, key, descriptor);\n return adm.defineComputedProperty_(key, _extends({}, this.options_, {\n get: descriptor.get,\n set: descriptor.set\n }), proxyTrap);\n}\n\nfunction assertComputedDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var get = _ref2.get;\n\n if ( true && !get) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on getter(+setter) properties.\"));\n }\n}\n\nfunction createObservableAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$4,\n extend_: extend_$4\n };\n}\n\nfunction make_$4(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$4(adm, key, descriptor, proxyTrap) {\n var _this$options_$enhanc, _this$options_;\n\n assertObservableDescriptor(adm, this, key, descriptor);\n return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap);\n}\n\nfunction assertObservableDescriptor(adm, _ref, key, descriptor) {\n var annotationType_ = _ref.annotationType_;\n\n if ( true && !(\"value\" in descriptor)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' cannot be used on getter/setter properties\"));\n }\n}\n\nvar AUTO = \"true\";\nvar autoAnnotation = /*#__PURE__*/createAutoAnnotation();\nfunction createAutoAnnotation(options) {\n return {\n annotationType_: AUTO,\n options_: options,\n make_: make_$5,\n extend_: extend_$5\n };\n}\n\nfunction make_$5(adm, key, descriptor, source) {\n var _this$options_3, _this$options_4;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.make_(adm, key, descriptor, source);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.make_\n var set = createAction(key.toString(), descriptor.set); // own\n\n if (source === adm.target_) {\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: set\n }) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // proto\n\n\n defineProperty(source, key, {\n configurable: true,\n set: set\n });\n return 2\n /* Continue */\n ;\n } // function on proto -> autoAction/flow\n\n\n if (source !== adm.target_ && typeof descriptor.value === \"function\") {\n var _this$options_2;\n\n if (isGenerator(descriptor.value)) {\n var _this$options_;\n\n var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;\n return flowAnnotation.make_(adm, key, descriptor, source);\n }\n\n var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;\n return actionAnnotation.make_(adm, key, descriptor, source);\n } // other -> observable\n // Copy props from proto as well, see test:\n // \"decorate should work with Object.create\"\n\n\n var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable; // if function respect autoBind option\n\n if (typeof descriptor.value === \"function\" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {\n var _adm$proxy_;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return observableAnnotation.make_(adm, key, descriptor, source);\n}\n\nfunction extend_$5(adm, key, descriptor, proxyTrap) {\n var _this$options_5, _this$options_6;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.extend_(adm, key, descriptor, proxyTrap);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.extend_\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: createAction(key.toString(), descriptor.set)\n }, proxyTrap);\n } // other -> observable\n // if function respect autoBind option\n\n\n if (typeof descriptor.value === \"function\" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {\n var _adm$proxy_2;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);\n }\n\n var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;\n return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);\n}\n\nvar OBSERVABLE = \"observable\";\nvar OBSERVABLE_REF = \"observable.ref\";\nvar OBSERVABLE_SHALLOW = \"observable.shallow\";\nvar OBSERVABLE_STRUCT = \"observable.struct\"; // Predefined bags of create observable options, to avoid allocating temporarily option objects\n// in the majority of cases\n\nvar defaultCreateObservableOptions = {\n deep: true,\n name: undefined,\n defaultDecorator: undefined,\n proxy: true\n};\nObject.freeze(defaultCreateObservableOptions);\nfunction asCreateObservableOptions(thing) {\n return thing || defaultCreateObservableOptions;\n}\nvar observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);\nvar observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {\n enhancer: referenceEnhancer\n});\nvar observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {\n enhancer: shallowEnhancer\n});\nvar observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {\n enhancer: refStructEnhancer\n});\nvar observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);\nfunction getEnhancerFromOptions(options) {\n return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);\n}\nfunction getAnnotationFromOptions(options) {\n var _options$defaultDecor;\n\n return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;\n}\nfunction getEnhancerFromAnnotation(annotation) {\n var _annotation$options_$, _annotation$options_;\n\n return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;\n}\n/**\r\n * Turns an object, array or function into a reactive structure.\r\n * @param v the value which should become observable.\r\n */\n\nfunction createObservable(v, arg2, arg3) {\n // @observable someProp;\n if (isStringish(arg2)) {\n storeAnnotation(v, arg2, observableAnnotation);\n return;\n } // already observable - ignore\n\n\n if (isObservable(v)) {\n return v;\n } // plain object\n\n\n if (isPlainObject(v)) {\n return observable.object(v, arg2, arg3);\n } // Array\n\n\n if (Array.isArray(v)) {\n return observable.array(v, arg2);\n } // Map\n\n\n if (isES6Map(v)) {\n return observable.map(v, arg2);\n } // Set\n\n\n if (isES6Set(v)) {\n return observable.set(v, arg2);\n } // other object - ignore\n\n\n if (typeof v === \"object\" && v !== null) {\n return v;\n } // anything else\n\n\n return observable.box(v, arg2);\n}\n\nObject.assign(createObservable, observableDecoratorAnnotation);\nvar observableFactories = {\n box: function box(value, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);\n },\n array: function array(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);\n },\n map: function map(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);\n },\n set: function set(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);\n },\n object: function object(props, decorators, options) {\n return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);\n },\n ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),\n shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),\n deep: observableDecoratorAnnotation,\n struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)\n}; // eslint-disable-next-line\n\nvar observable = /*#__PURE__*/assign(createObservable, observableFactories);\n\nvar COMPUTED = \"computed\";\nvar COMPUTED_STRUCT = \"computed.struct\";\nvar computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);\nvar computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {\n equals: comparer.structural\n});\n/**\r\n * Decorator for class properties: @computed get value() { return expr; }.\r\n * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;\r\n */\n\nvar computed = function computed(arg1, arg2) {\n if (isStringish(arg2)) {\n // @computed\n return storeAnnotation(arg1, arg2, computedAnnotation);\n }\n\n if (isPlainObject(arg1)) {\n // @computed({ options })\n return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));\n } // computed(expr, options?)\n\n\n if (true) {\n if (!isFunction(arg1)) {\n die(\"First argument to `computed` should be an expression.\");\n }\n\n if (isFunction(arg2)) {\n die(\"A setter as second argument is no longer supported, use `{ set: fn }` option instead\");\n }\n }\n\n var opts = isPlainObject(arg2) ? arg2 : {};\n opts.get = arg1;\n opts.name || (opts.name = arg1.name || \"\");\n /* for generated name */\n\n return new ComputedValue(opts);\n};\nObject.assign(computed, computedAnnotation);\ncomputed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);\n\nvar _getDescriptor$config, _getDescriptor;\n// mobx versions\n\nvar currentActionId = 0;\nvar nextActionId = 1;\nvar isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, \"name\")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object\n\nvar tmpNameDescriptor = {\n value: \"action\",\n configurable: true,\n writable: false,\n enumerable: false\n};\nfunction createAction(actionName, fn, autoAction, ref) {\n if (autoAction === void 0) {\n autoAction = false;\n }\n\n if (true) {\n if (!isFunction(fn)) {\n die(\"`action` can only be invoked on functions\");\n }\n\n if (typeof actionName !== \"string\" || !actionName) {\n die(\"actions should have valid names, got: '\" + actionName + \"'\");\n }\n }\n\n function res() {\n return executeAction(actionName, autoAction, fn, ref || this, arguments);\n }\n\n res.isMobxAction = true;\n\n if (isFunctionNameConfigurable) {\n tmpNameDescriptor.value = actionName;\n Object.defineProperty(res, \"name\", tmpNameDescriptor);\n }\n\n return res;\n}\nfunction executeAction(actionName, canRunAsDerivation, fn, scope, args) {\n var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);\n\n try {\n return fn.apply(scope, args);\n } catch (err) {\n runInfo.error_ = err;\n throw err;\n } finally {\n _endAction(runInfo);\n }\n}\nfunction _startAction(actionName, canRunAsDerivation, // true for autoAction\nscope, args) {\n var notifySpy_ = true && isSpyEnabled() && !!actionName;\n var startTime_ = 0;\n\n if ( true && notifySpy_) {\n startTime_ = Date.now();\n var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;\n spyReportStart({\n type: ACTION,\n name: actionName,\n object: scope,\n arguments: flattenedArgs\n });\n }\n\n var prevDerivation_ = globalState.trackingDerivation;\n var runAsAction = !canRunAsDerivation || !prevDerivation_;\n startBatch();\n var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow\n\n if (runAsAction) {\n untrackedStart();\n prevAllowStateChanges_ = allowStateChangesStart(true);\n }\n\n var prevAllowStateReads_ = allowStateReadsStart(true);\n var runInfo = {\n runAsAction_: runAsAction,\n prevDerivation_: prevDerivation_,\n prevAllowStateChanges_: prevAllowStateChanges_,\n prevAllowStateReads_: prevAllowStateReads_,\n notifySpy_: notifySpy_,\n startTime_: startTime_,\n actionId_: nextActionId++,\n parentActionId_: currentActionId\n };\n currentActionId = runInfo.actionId_;\n return runInfo;\n}\nfunction _endAction(runInfo) {\n if (currentActionId !== runInfo.actionId_) {\n die(30);\n }\n\n currentActionId = runInfo.parentActionId_;\n\n if (runInfo.error_ !== undefined) {\n globalState.suppressReactionErrors = true;\n }\n\n allowStateChangesEnd(runInfo.prevAllowStateChanges_);\n allowStateReadsEnd(runInfo.prevAllowStateReads_);\n endBatch();\n\n if (runInfo.runAsAction_) {\n untrackedEnd(runInfo.prevDerivation_);\n }\n\n if ( true && runInfo.notifySpy_) {\n spyReportEnd({\n time: Date.now() - runInfo.startTime_\n });\n }\n\n globalState.suppressReactionErrors = false;\n}\nfunction allowStateChanges(allowStateChanges, func) {\n var prev = allowStateChangesStart(allowStateChanges);\n\n try {\n return func();\n } finally {\n allowStateChangesEnd(prev);\n }\n}\nfunction allowStateChangesStart(allowStateChanges) {\n var prev = globalState.allowStateChanges;\n globalState.allowStateChanges = allowStateChanges;\n return prev;\n}\nfunction allowStateChangesEnd(prev) {\n globalState.allowStateChanges = prev;\n}\n\nvar _Symbol$toPrimitive;\nvar CREATE = \"create\";\n_Symbol$toPrimitive = Symbol.toPrimitive;\nvar ObservableValue = /*#__PURE__*/function (_Atom) {\n _inheritsLoose(ObservableValue, _Atom);\n\n function ObservableValue(value, enhancer, name_, notifySpy, equals) {\n var _this;\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableValue@\" + getNextId() : undefined;\n }\n\n if (notifySpy === void 0) {\n notifySpy = true;\n }\n\n if (equals === void 0) {\n equals = comparer[\"default\"];\n }\n\n _this = _Atom.call(this, name_) || this;\n _this.enhancer = void 0;\n _this.name_ = void 0;\n _this.equals = void 0;\n _this.hasUnreportedChange_ = false;\n _this.interceptors_ = void 0;\n _this.changeListeners_ = void 0;\n _this.value_ = void 0;\n _this.dehancer = void 0;\n _this.enhancer = enhancer;\n _this.name_ = name_;\n _this.equals = equals;\n _this.value_ = enhancer(value, undefined, name_);\n\n if ( true && notifySpy && isSpyEnabled()) {\n // only notify spy if this is a stand-alone observable\n spyReport({\n type: CREATE,\n object: _assertThisInitialized(_this),\n observableKind: \"value\",\n debugObjectName: _this.name_,\n newValue: \"\" + _this.value_\n });\n }\n\n return _this;\n }\n\n var _proto = ObservableValue.prototype;\n\n _proto.dehanceValue = function dehanceValue(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.set = function set(newValue) {\n var oldValue = this.value_;\n newValue = this.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n\n if ( true && notifySpy) {\n spyReportStart({\n type: UPDATE,\n object: this,\n observableKind: \"value\",\n debugObjectName: this.name_,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n\n this.setNewValue_(newValue);\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.prepareNewValue_ = function prepareNewValue_(newValue) {\n checkIfStateModificationsAreAllowed(this);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this,\n type: UPDATE,\n newValue: newValue\n });\n\n if (!change) {\n return globalState.UNCHANGED;\n }\n\n newValue = change.newValue;\n } // apply modifier\n\n\n newValue = this.enhancer(newValue, this.value_, this.name_);\n return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;\n };\n\n _proto.setNewValue_ = function setNewValue_(newValue) {\n var oldValue = this.value_;\n this.value_ = newValue;\n this.reportChanged();\n\n if (hasListeners(this)) {\n notifyListeners(this, {\n type: UPDATE,\n object: this,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n };\n\n _proto.get = function get() {\n this.reportObserved();\n return this.dehanceValue(this.value_);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately) {\n listener({\n observableKind: \"value\",\n debugObjectName: this.name_,\n object: this,\n type: UPDATE,\n newValue: this.value_,\n oldValue: undefined\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.raw = function raw() {\n // used by MST ot get undehanced value\n return this.value_;\n };\n\n _proto.toJSON = function toJSON() {\n return this.get();\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.value_ + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive] = function () {\n return this.valueOf();\n };\n\n return ObservableValue;\n}(Atom);\nvar isObservableValue = /*#__PURE__*/createInstanceofPredicate(\"ObservableValue\", ObservableValue);\n\nvar _Symbol$toPrimitive$1;\n/**\r\n * A node in the state dependency root that observes other nodes, and can be observed itself.\r\n *\r\n * ComputedValue will remember the result of the computation for the duration of the batch, or\r\n * while being observed.\r\n *\r\n * During this time it will recompute only when one of its direct dependencies changed,\r\n * but only when it is being accessed with `ComputedValue.get()`.\r\n *\r\n * Implementation description:\r\n * 1. First time it's being accessed it will compute and remember result\r\n * give back remembered result until 2. happens\r\n * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.\r\n * 3. When it's being accessed, recompute if any shallow dependency changed.\r\n * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.\r\n * go to step 2. either way\r\n *\r\n * If at any point it's outside batch and it isn't observed: reset everything and go to 1.\r\n */\n\n_Symbol$toPrimitive$1 = Symbol.toPrimitive;\nvar ComputedValue = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n // during tracking it's an array with new observed observers\n // to check for cycles\n // N.B: unminified as it is used by MST\n\n /**\r\n * Create a new computed value based on a function expression.\r\n *\r\n * The `name` property is for debug purposes only.\r\n *\r\n * The `equals` property specifies the comparer function to use to determine if a newly produced\r\n * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`\r\n * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.\r\n * Structural comparison can be convenient if you always produce a new aggregated object and\r\n * don't want to notify observers if it is structurally the same.\r\n * This is useful for working with vectors, mouse coordinates etc.\r\n */\n function ComputedValue(options) {\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.observing_ = [];\n this.newObserving_ = null;\n this.isBeingObserved_ = false;\n this.isPendingUnobservation_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n this.unboundDepsCount_ = 0;\n this.value_ = new CaughtException(null);\n this.name_ = void 0;\n this.triggeredBy_ = void 0;\n this.isComputing_ = false;\n this.isRunningSetter_ = false;\n this.derivation = void 0;\n this.setter_ = void 0;\n this.isTracing_ = TraceMode.NONE;\n this.scope_ = void 0;\n this.equals_ = void 0;\n this.requiresReaction_ = void 0;\n this.keepAlive_ = void 0;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n\n if (!options.get) {\n die(31);\n }\n\n this.derivation = options.get;\n this.name_ = options.name || ( true ? \"ComputedValue@\" + getNextId() : undefined);\n\n if (options.set) {\n this.setter_ = createAction( true ? this.name_ + \"-setter\" : undefined, options.set);\n }\n\n this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer[\"default\"]);\n this.scope_ = options.context;\n this.requiresReaction_ = options.requiresReaction;\n this.keepAlive_ = !!options.keepAlive;\n }\n\n var _proto = ComputedValue.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n propagateMaybeChanged(this);\n };\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Returns the current value of this computed value.\r\n * Will evaluate its computation first if needed.\r\n */\n ;\n\n _proto.get = function get() {\n if (this.isComputing_) {\n die(32, this.name_, this.derivation);\n }\n\n if (globalState.inBatch === 0 && // !globalState.trackingDerivatpion &&\n this.observers_.size === 0 && !this.keepAlive_) {\n if (shouldCompute(this)) {\n this.warnAboutUntrackedRead_();\n startBatch(); // See perf test 'computed memoization'\n\n this.value_ = this.computeValue_(false);\n endBatch();\n }\n } else {\n reportObserved(this);\n\n if (shouldCompute(this)) {\n var prevTrackingContext = globalState.trackingContext;\n\n if (this.keepAlive_ && !prevTrackingContext) {\n globalState.trackingContext = this;\n }\n\n if (this.trackAndCompute()) {\n propagateChangeConfirmed(this);\n }\n\n globalState.trackingContext = prevTrackingContext;\n }\n }\n\n var result = this.value_;\n\n if (isCaughtException(result)) {\n throw result.cause;\n }\n\n return result;\n };\n\n _proto.set = function set(value) {\n if (this.setter_) {\n if (this.isRunningSetter_) {\n die(33, this.name_);\n }\n\n this.isRunningSetter_ = true;\n\n try {\n this.setter_.call(this.scope_, value);\n } finally {\n this.isRunningSetter_ = false;\n }\n } else {\n die(34, this.name_);\n }\n };\n\n _proto.trackAndCompute = function trackAndCompute() {\n // N.B: unminified as it is used by MST\n var oldValue = this.value_;\n var wasSuspended =\n /* see #1208 */\n this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;\n var newValue = this.computeValue_(true);\n var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);\n\n if (changed) {\n this.value_ = newValue;\n\n if ( true && isSpyEnabled()) {\n spyReport({\n observableKind: \"computed\",\n debugObjectName: this.name_,\n object: this.scope_,\n type: \"update\",\n oldValue: oldValue,\n newValue: newValue\n });\n }\n }\n\n return changed;\n };\n\n _proto.computeValue_ = function computeValue_(track) {\n this.isComputing_ = true; // don't allow state changes during computation\n\n var prev = allowStateChangesStart(false);\n var res;\n\n if (track) {\n res = trackDerivedFunction(this, this.derivation, this.scope_);\n } else {\n if (globalState.disableErrorBoundaries === true) {\n res = this.derivation.call(this.scope_);\n } else {\n try {\n res = this.derivation.call(this.scope_);\n } catch (e) {\n res = new CaughtException(e);\n }\n }\n }\n\n allowStateChangesEnd(prev);\n this.isComputing_ = false;\n return res;\n };\n\n _proto.suspend_ = function suspend_() {\n if (!this.keepAlive_) {\n clearObserving(this);\n this.value_ = undefined; // don't hold on to computed value!\n\n if ( true && this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' was suspended and it will recompute on the next access.\");\n }\n }\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n var _this = this;\n\n var firstTime = true;\n var prevValue = undefined;\n return autorun(function () {\n // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place\n var newValue = _this.get();\n\n if (!firstTime || fireImmediately) {\n var prevU = untrackedStart();\n listener({\n observableKind: \"computed\",\n debugObjectName: _this.name_,\n type: UPDATE,\n object: _this,\n newValue: newValue,\n oldValue: prevValue\n });\n untrackedEnd(prevU);\n }\n\n firstTime = false;\n prevValue = newValue;\n });\n };\n\n _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {\n if (false) {}\n\n if (this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n\n if (typeof this.requiresReaction_ === \"boolean\" ? this.requiresReaction_ : globalState.computedRequiresReaction) {\n console.warn(\"[mobx] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.derivation.toString() + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive$1] = function () {\n return this.valueOf();\n };\n\n return ComputedValue;\n}();\nvar isComputedValue = /*#__PURE__*/createInstanceofPredicate(\"ComputedValue\", ComputedValue);\n\nvar IDerivationState_;\n\n(function (IDerivationState_) {\n // before being run or (outside batch and not being observed)\n // at this point derivation is not holding any data about dependency tree\n IDerivationState_[IDerivationState_[\"NOT_TRACKING_\"] = -1] = \"NOT_TRACKING_\"; // no shallow dependency changed since last computation\n // won't recalculate derivation\n // this is what makes mobx fast\n\n IDerivationState_[IDerivationState_[\"UP_TO_DATE_\"] = 0] = \"UP_TO_DATE_\"; // some deep dependency changed, but don't know if shallow dependency changed\n // will require to check first if UP_TO_DATE or POSSIBLY_STALE\n // currently only ComputedValue will propagate POSSIBLY_STALE\n //\n // having this state is second big optimization:\n // don't have to recompute on every dependency change, but only when it's needed\n\n IDerivationState_[IDerivationState_[\"POSSIBLY_STALE_\"] = 1] = \"POSSIBLY_STALE_\"; // A shallow dependency has changed since last computation and the derivation\n // will need to recompute when it's needed next.\n\n IDerivationState_[IDerivationState_[\"STALE_\"] = 2] = \"STALE_\";\n})(IDerivationState_ || (IDerivationState_ = {}));\n\nvar TraceMode;\n\n(function (TraceMode) {\n TraceMode[TraceMode[\"NONE\"] = 0] = \"NONE\";\n TraceMode[TraceMode[\"LOG\"] = 1] = \"LOG\";\n TraceMode[TraceMode[\"BREAK\"] = 2] = \"BREAK\";\n})(TraceMode || (TraceMode = {}));\n\nvar CaughtException = function CaughtException(cause) {\n this.cause = void 0;\n this.cause = cause; // Empty\n};\nfunction isCaughtException(e) {\n return e instanceof CaughtException;\n}\n/**\r\n * Finds out whether any dependency of the derivation has actually changed.\r\n * If dependenciesState is 1 then it will recalculate dependencies,\r\n * if any dependency changed it will propagate it by changing dependenciesState to 2.\r\n *\r\n * By iterating over the dependencies in the same order that they were reported and\r\n * stopping on the first change, all the recalculations are only called for ComputedValues\r\n * that will be tracked by derivation. That is because we assume that if the first x\r\n * dependencies of the derivation doesn't change then the derivation should run the same way\r\n * up until accessing x-th dependency.\r\n */\n\nfunction shouldCompute(derivation) {\n switch (derivation.dependenciesState_) {\n case IDerivationState_.UP_TO_DATE_:\n return false;\n\n case IDerivationState_.NOT_TRACKING_:\n case IDerivationState_.STALE_:\n return true;\n\n case IDerivationState_.POSSIBLY_STALE_:\n {\n // state propagation can occur outside of action/reactive context #2195\n var prevAllowStateReads = allowStateReadsStart(true);\n var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.\n\n var obs = derivation.observing_,\n l = obs.length;\n\n for (var i = 0; i < l; i++) {\n var obj = obs[i];\n\n if (isComputedValue(obj)) {\n if (globalState.disableErrorBoundaries) {\n obj.get();\n } else {\n try {\n obj.get();\n } catch (e) {\n // we are not interested in the value *or* exception at this moment, but if there is one, notify all\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.\n // and `derivation` is an observer of `obj`\n // invariantShouldCompute(derivation)\n\n\n if (derivation.dependenciesState_ === IDerivationState_.STALE_) {\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n }\n\n changeDependenciesStateTo0(derivation);\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return false;\n }\n }\n}\nfunction isComputingDerivation() {\n return globalState.trackingDerivation !== null; // filter out actions inside computations\n}\nfunction checkIfStateModificationsAreAllowed(atom) {\n if (false) {}\n\n var hasObservers = atom.observers_.size > 0; // Should not be possible to change observed state outside strict mode, except during initialization, see #563\n\n if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === \"always\")) {\n console.warn(\"[MobX] \" + (globalState.enforceActions ? \"Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: \" : \"Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: \") + atom.name_);\n }\n}\nfunction checkIfStateReadsAreAllowed(observable) {\n if ( true && !globalState.allowStateReads && globalState.observableRequiresReaction) {\n console.warn(\"[mobx] Observable '\" + observable.name_ + \"' being read outside a reactive context.\");\n }\n}\n/**\r\n * Executes the provided function `f` and tracks which observables are being accessed.\r\n * The tracking information is stored on the `derivation` object and the derivation is registered\r\n * as observer of any of the accessed observables.\r\n */\n\nfunction trackDerivedFunction(derivation, f, context) {\n var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps\n // array will be trimmed by bindDependencies\n\n changeDependenciesStateTo0(derivation);\n derivation.newObserving_ = new Array(derivation.observing_.length + 100);\n derivation.unboundDepsCount_ = 0;\n derivation.runId_ = ++globalState.runId;\n var prevTracking = globalState.trackingDerivation;\n globalState.trackingDerivation = derivation;\n globalState.inBatch++;\n var result;\n\n if (globalState.disableErrorBoundaries === true) {\n result = f.call(context);\n } else {\n try {\n result = f.call(context);\n } catch (e) {\n result = new CaughtException(e);\n }\n }\n\n globalState.inBatch--;\n globalState.trackingDerivation = prevTracking;\n bindDependencies(derivation);\n warnAboutDerivationWithoutDependencies(derivation);\n allowStateReadsEnd(prevAllowStateReads);\n return result;\n}\n\nfunction warnAboutDerivationWithoutDependencies(derivation) {\n if (false) {}\n\n if (derivation.observing_.length !== 0) {\n return;\n }\n\n if (typeof derivation.requiresObservable_ === \"boolean\" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {\n console.warn(\"[mobx] Derivation '\" + derivation.name_ + \"' is created/updated without reading any observable value.\");\n }\n}\n/**\r\n * diffs newObserving with observing.\r\n * update observing to be newObserving with unique observables\r\n * notify observers that become observed/unobserved\r\n */\n\n\nfunction bindDependencies(derivation) {\n // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, \"INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1\");\n var prevObserving = derivation.observing_;\n var observing = derivation.observing_ = derivation.newObserving_;\n var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; // Go through all new observables and check diffValue: (this list can contain duplicates):\n // 0: first occurrence, change to 1 and keep it\n // 1: extra occurrence, drop it\n\n var i0 = 0,\n l = derivation.unboundDepsCount_;\n\n for (var i = 0; i < l; i++) {\n var dep = observing[i];\n\n if (dep.diffValue_ === 0) {\n dep.diffValue_ = 1;\n\n if (i0 !== i) {\n observing[i0] = dep;\n }\n\n i0++;\n } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,\n // not hitting the condition\n\n\n if (dep.dependenciesState_ > lowestNewObservingDerivationState) {\n lowestNewObservingDerivationState = dep.dependenciesState_;\n }\n }\n\n observing.length = i0;\n derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)\n // Go through all old observables and check diffValue: (it is unique after last bindDependencies)\n // 0: it's not in new observables, unobserve it\n // 1: it keeps being observed, don't want to notify it. change to 0\n\n l = prevObserving.length;\n\n while (l--) {\n var _dep = prevObserving[l];\n\n if (_dep.diffValue_ === 0) {\n removeObserver(_dep, derivation);\n }\n\n _dep.diffValue_ = 0;\n } // Go through all new observables and check diffValue: (now it should be unique)\n // 0: it was set to 0 in last loop. don't need to do anything.\n // 1: it wasn't observed, let's observe it. set back to 0\n\n\n while (i0--) {\n var _dep2 = observing[i0];\n\n if (_dep2.diffValue_ === 1) {\n _dep2.diffValue_ = 0;\n addObserver(_dep2, derivation);\n }\n } // Some new observed derivations may become stale during this derivation computation\n // so they have had no chance to propagate staleness (#916)\n\n\n if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {\n derivation.dependenciesState_ = lowestNewObservingDerivationState;\n derivation.onBecomeStale_();\n }\n}\n\nfunction clearObserving(derivation) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR clearObserving should be called only inside batch\");\n var obs = derivation.observing_;\n derivation.observing_ = [];\n var i = obs.length;\n\n while (i--) {\n removeObserver(obs[i], derivation);\n }\n\n derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n}\nfunction untracked(action) {\n var prev = untrackedStart();\n\n try {\n return action();\n } finally {\n untrackedEnd(prev);\n }\n}\nfunction untrackedStart() {\n var prev = globalState.trackingDerivation;\n globalState.trackingDerivation = null;\n return prev;\n}\nfunction untrackedEnd(prev) {\n globalState.trackingDerivation = prev;\n}\nfunction allowStateReadsStart(allowStateReads) {\n var prev = globalState.allowStateReads;\n globalState.allowStateReads = allowStateReads;\n return prev;\n}\nfunction allowStateReadsEnd(prev) {\n globalState.allowStateReads = prev;\n}\n/**\r\n * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0\r\n *\r\n */\n\nfunction changeDependenciesStateTo0(derivation) {\n if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;\n var obs = derivation.observing_;\n var i = obs.length;\n\n while (i--) {\n obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n}\n\n/**\r\n * These values will persist if global state is reset\r\n */\n\nvar persistentKeys = [\"mobxGuid\", \"spyListeners\", \"enforceActions\", \"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"allowStateReads\", \"disableErrorBoundaries\", \"runId\", \"UNCHANGED\", \"useProxies\"];\nvar MobXGlobals = function MobXGlobals() {\n this.version = 6;\n this.UNCHANGED = {};\n this.trackingDerivation = null;\n this.trackingContext = null;\n this.runId = 0;\n this.mobxGuid = 0;\n this.inBatch = 0;\n this.pendingUnobservations = [];\n this.pendingReactions = [];\n this.isRunningReactions = false;\n this.allowStateChanges = false;\n this.allowStateReads = true;\n this.enforceActions = true;\n this.spyListeners = [];\n this.globalReactionErrorHandlers = [];\n this.computedRequiresReaction = false;\n this.reactionRequiresObservable = false;\n this.observableRequiresReaction = false;\n this.disableErrorBoundaries = false;\n this.suppressReactionErrors = false;\n this.useProxies = true;\n this.verifyProxies = false;\n this.safeDescriptors = true;\n};\nvar canMergeGlobalState = true;\nvar isolateCalled = false;\nvar globalState = /*#__PURE__*/function () {\n var global = /*#__PURE__*/getGlobal();\n\n if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {\n canMergeGlobalState = false;\n }\n\n if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {\n canMergeGlobalState = false;\n }\n\n if (!canMergeGlobalState) {\n // Because this is a IIFE we need to let isolateCalled a chance to change\n // so we run it after the event loop completed at least 1 iteration\n setTimeout(function () {\n if (!isolateCalled) {\n die(35);\n }\n }, 1);\n return new MobXGlobals();\n } else if (global.__mobxGlobals) {\n global.__mobxInstanceCount += 1;\n\n if (!global.__mobxGlobals.UNCHANGED) {\n global.__mobxGlobals.UNCHANGED = {};\n } // make merge backward compatible\n\n\n return global.__mobxGlobals;\n } else {\n global.__mobxInstanceCount = 1;\n return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();\n }\n}();\nfunction isolateGlobalState() {\n if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {\n die(36);\n }\n\n isolateCalled = true;\n\n if (canMergeGlobalState) {\n var global = getGlobal();\n\n if (--global.__mobxInstanceCount === 0) {\n global.__mobxGlobals = undefined;\n }\n\n globalState = new MobXGlobals();\n }\n}\nfunction getGlobalState() {\n return globalState;\n}\n/**\r\n * For testing purposes only; this will break the internal state of existing observables,\r\n * but can be used to get back at a stable state after throwing errors\r\n */\n\nfunction resetGlobalState() {\n var defaultGlobals = new MobXGlobals();\n\n for (var key in defaultGlobals) {\n if (persistentKeys.indexOf(key) === -1) {\n globalState[key] = defaultGlobals[key];\n }\n }\n\n globalState.allowStateChanges = !globalState.enforceActions;\n}\n\nfunction hasObservers(observable) {\n return observable.observers_ && observable.observers_.size > 0;\n}\nfunction getObservers(observable) {\n return observable.observers_;\n} // function invariantObservers(observable: IObservable) {\n// const list = observable.observers\n// const map = observable.observersIndexes\n// const l = list.length\n// for (let i = 0; i < l; i++) {\n// const id = list[i].__mapid\n// if (i) {\n// invariant(map[id] === i, \"INTERNAL ERROR maps derivation.__mapid to index in list\") // for performance\n// } else {\n// invariant(!(id in map), \"INTERNAL ERROR observer on index 0 shouldn't be held in map.\") // for performance\n// }\n// }\n// invariant(\n// list.length === 0 || Object.keys(map).length === list.length - 1,\n// \"INTERNAL ERROR there is no junk in map\"\n// )\n// }\n\nfunction addObserver(observable, node) {\n // invariant(node.dependenciesState !== -1, \"INTERNAL ERROR, can add only dependenciesState !== -1\");\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR add already added node\");\n // invariantObservers(observable);\n observable.observers_.add(node);\n\n if (observable.lowestObserverState_ > node.dependenciesState_) {\n observable.lowestObserverState_ = node.dependenciesState_;\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR didn't add node\");\n\n}\nfunction removeObserver(observable, node) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR, remove should be called only inside batch\");\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR remove already removed node\");\n // invariantObservers(observable);\n observable.observers_[\"delete\"](node);\n\n if (observable.observers_.size === 0) {\n // deleting last observer\n queueForUnobservation(observable);\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR remove already removed node2\");\n\n}\nfunction queueForUnobservation(observable) {\n if (observable.isPendingUnobservation_ === false) {\n // invariant(observable._observers.length === 0, \"INTERNAL ERROR, should only queue for unobservation unobserved observables\");\n observable.isPendingUnobservation_ = true;\n globalState.pendingUnobservations.push(observable);\n }\n}\n/**\r\n * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.\r\n * During a batch `onBecomeUnobserved` will be called at most once per observable.\r\n * Avoids unnecessary recalculations.\r\n */\n\nfunction startBatch() {\n globalState.inBatch++;\n}\nfunction endBatch() {\n if (--globalState.inBatch === 0) {\n runReactions(); // the batch is actually about to finish, all unobserving should happen here.\n\n var list = globalState.pendingUnobservations;\n\n for (var i = 0; i < list.length; i++) {\n var observable = list[i];\n observable.isPendingUnobservation_ = false;\n\n if (observable.observers_.size === 0) {\n if (observable.isBeingObserved_) {\n // if this observable had reactive observers, trigger the hooks\n observable.isBeingObserved_ = false;\n observable.onBUO();\n }\n\n if (observable instanceof ComputedValue) {\n // computed values are automatically teared down when the last observer leaves\n // this process happens recursively, this computed might be the last observabe of another, etc..\n observable.suspend_();\n }\n }\n }\n\n globalState.pendingUnobservations = [];\n }\n}\nfunction reportObserved(observable) {\n checkIfStateReadsAreAllowed(observable);\n var derivation = globalState.trackingDerivation;\n\n if (derivation !== null) {\n /**\r\n * Simple optimization, give each derivation run an unique id (runId)\r\n * Check if last time this observable was accessed the same runId is used\r\n * if this is the case, the relation is already known\r\n */\n if (derivation.runId_ !== observable.lastAccessedBy_) {\n observable.lastAccessedBy_ = derivation.runId_; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...\n\n derivation.newObserving_[derivation.unboundDepsCount_++] = observable;\n\n if (!observable.isBeingObserved_ && globalState.trackingContext) {\n observable.isBeingObserved_ = true;\n observable.onBO();\n }\n }\n\n return observable.isBeingObserved_;\n } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {\n queueForUnobservation(observable);\n }\n\n return false;\n} // function invariantLOS(observable: IObservable, msg: string) {\n// // it's expensive so better not run it in produciton. but temporarily helpful for testing\n// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)\n// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`\n// throw new Error(\n// \"lowestObserverState is wrong for \" +\n// msg +\n// \" because \" +\n// min +\n// \" < \" +\n// observable.lowestObserverState\n// )\n// }\n\n/**\r\n * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly\r\n * It will propagate changes to observers from previous run\r\n * It's hard or maybe impossible (with reasonable perf) to get it right with current approach\r\n * Hopefully self reruning autoruns aren't a feature people should depend on\r\n * Also most basic use cases should be ok\r\n */\n// Called by Atom when its value changes\n\nfunction propagateChanged(observable) {\n // invariantLOS(observable, \"changed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_; // Ideally we use for..of here, but the downcompiled version is really slow...\n\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n\n d.onBecomeStale_();\n }\n\n d.dependenciesState_ = IDerivationState_.STALE_;\n }); // invariantLOS(observable, \"changed end\");\n} // Called by ComputedValue when it recalculate and its value changed\n\nfunction propagateChangeConfirmed(observable) {\n // invariantLOS(observable, \"confirmed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {\n d.dependenciesState_ = IDerivationState_.STALE_;\n\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.\n ) {\n observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n }); // invariantLOS(observable, \"confirmed end\");\n} // Used by computed when its dependency changed, but we don't wan't to immediately recompute.\n\nfunction propagateMaybeChanged(observable) {\n // invariantLOS(observable, \"maybe start\");\n if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;\n d.onBecomeStale_();\n }\n }); // invariantLOS(observable, \"maybe end\");\n}\n\nfunction logTraceInfo(derivation, observable) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' is invalidated due to a change in: '\" + observable.name_ + \"'\");\n\n if (derivation.isTracing_ === TraceMode.BREAK) {\n var lines = [];\n printDepTree(getDependencyTree(derivation), lines, 1); // prettier-ignore\n\n new Function(\"debugger;\\n/*\\nTracing '\" + derivation.name_ + \"'\\n\\nYou are entering this break point because derivation '\" + derivation.name_ + \"' is being traced and '\" + observable.name_ + \"' is now forcing it to update.\\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\\n\\n\" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\\//g, \"/\") : \"\") + \"\\n\\nThe dependencies for this derivation are:\\n\\n\" + lines.join(\"\\n\") + \"\\n*/\\n \")();\n }\n}\n\nfunction printDepTree(tree, lines, depth) {\n if (lines.length >= 1000) {\n lines.push(\"(and many more)\");\n return;\n }\n\n lines.push(\"\" + \"\\t\".repeat(depth - 1) + tree.name);\n\n if (tree.dependencies) {\n tree.dependencies.forEach(function (child) {\n return printDepTree(child, lines, depth + 1);\n });\n }\n}\n\nvar Reaction = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {\n if (name_ === void 0) {\n name_ = true ? \"Reaction@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.onInvalidate_ = void 0;\n this.errorHandler_ = void 0;\n this.requiresObservable_ = void 0;\n this.observing_ = [];\n this.newObserving_ = [];\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.unboundDepsCount_ = 0;\n this.isDisposed_ = false;\n this.isScheduled_ = false;\n this.isTrackPending_ = false;\n this.isRunning_ = false;\n this.isTracing_ = TraceMode.NONE;\n this.name_ = name_;\n this.onInvalidate_ = onInvalidate_;\n this.errorHandler_ = errorHandler_;\n this.requiresObservable_ = requiresObservable_;\n }\n\n var _proto = Reaction.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n this.schedule_();\n };\n\n _proto.schedule_ = function schedule_() {\n if (!this.isScheduled_) {\n this.isScheduled_ = true;\n globalState.pendingReactions.push(this);\n runReactions();\n }\n };\n\n _proto.isScheduled = function isScheduled() {\n return this.isScheduled_;\n }\n /**\r\n * internal, use schedule() if you intend to kick off a reaction\r\n */\n ;\n\n _proto.runReaction_ = function runReaction_() {\n if (!this.isDisposed_) {\n startBatch();\n this.isScheduled_ = false;\n var prev = globalState.trackingContext;\n globalState.trackingContext = this;\n\n if (shouldCompute(this)) {\n this.isTrackPending_ = true;\n\n try {\n this.onInvalidate_();\n\n if ( true && this.isTrackPending_ && isSpyEnabled()) {\n // onInvalidate didn't trigger track right away..\n spyReport({\n name: this.name_,\n type: \"scheduled-reaction\"\n });\n }\n } catch (e) {\n this.reportExceptionInDerivation_(e);\n }\n }\n\n globalState.trackingContext = prev;\n endBatch();\n }\n };\n\n _proto.track = function track(fn) {\n if (this.isDisposed_) {\n return; // console.warn(\"Reaction already disposed\") // Note: Not a warning / error in mobx 4 either\n }\n\n startBatch();\n var notify = isSpyEnabled();\n var startTime;\n\n if ( true && notify) {\n startTime = Date.now();\n spyReportStart({\n name: this.name_,\n type: \"reaction\"\n });\n }\n\n this.isRunning_ = true;\n var prevReaction = globalState.trackingContext; // reactions could create reactions...\n\n globalState.trackingContext = this;\n var result = trackDerivedFunction(this, fn, undefined);\n globalState.trackingContext = prevReaction;\n this.isRunning_ = false;\n this.isTrackPending_ = false;\n\n if (this.isDisposed_) {\n // disposed during last run. Clean up everything that was bound after the dispose call.\n clearObserving(this);\n }\n\n if (isCaughtException(result)) {\n this.reportExceptionInDerivation_(result.cause);\n }\n\n if ( true && notify) {\n spyReportEnd({\n time: Date.now() - startTime\n });\n }\n\n endBatch();\n };\n\n _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {\n var _this = this;\n\n if (this.errorHandler_) {\n this.errorHandler_(error, this);\n return;\n }\n\n if (globalState.disableErrorBoundaries) {\n throw error;\n }\n\n var message = true ? \"[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '\" + this + \"'\" : undefined;\n\n if (!globalState.suppressReactionErrors) {\n console.error(message, error);\n /** If debugging brought you here, please, read the above message :-). Tnx! */\n } else if (true) {\n console.warn(\"[mobx] (error in reaction '\" + this.name_ + \"' suppressed, fix error of causing action below)\");\n } // prettier-ignore\n\n\n if ( true && isSpyEnabled()) {\n spyReport({\n type: \"error\",\n name: this.name_,\n message: message,\n error: \"\" + error\n });\n }\n\n globalState.globalReactionErrorHandlers.forEach(function (f) {\n return f(error, _this);\n });\n };\n\n _proto.dispose = function dispose() {\n if (!this.isDisposed_) {\n this.isDisposed_ = true;\n\n if (!this.isRunning_) {\n // if disposed while running, clean up later. Maybe not optimal, but rare case\n startBatch();\n clearObserving(this);\n endBatch();\n }\n }\n };\n\n _proto.getDisposer_ = function getDisposer_() {\n var r = this.dispose.bind(this);\n r[$mobx] = this;\n return r;\n };\n\n _proto.toString = function toString() {\n return \"Reaction[\" + this.name_ + \"]\";\n };\n\n _proto.trace = function trace$1(enterBreakPoint) {\n if (enterBreakPoint === void 0) {\n enterBreakPoint = false;\n }\n\n trace(this, enterBreakPoint);\n };\n\n return Reaction;\n}();\nfunction onReactionError(handler) {\n globalState.globalReactionErrorHandlers.push(handler);\n return function () {\n var idx = globalState.globalReactionErrorHandlers.indexOf(handler);\n\n if (idx >= 0) {\n globalState.globalReactionErrorHandlers.splice(idx, 1);\n }\n };\n}\n/**\r\n * Magic number alert!\r\n * Defines within how many times a reaction is allowed to re-trigger itself\r\n * until it is assumed that this is gonna be a never ending loop...\r\n */\n\nvar MAX_REACTION_ITERATIONS = 100;\n\nvar reactionScheduler = function reactionScheduler(f) {\n return f();\n};\n\nfunction runReactions() {\n // Trampolining, if runReactions are already running, new reactions will be picked up\n if (globalState.inBatch > 0 || globalState.isRunningReactions) {\n return;\n }\n\n reactionScheduler(runReactionsHelper);\n}\n\nfunction runReactionsHelper() {\n globalState.isRunningReactions = true;\n var allReactions = globalState.pendingReactions;\n var iterations = 0; // While running reactions, new reactions might be triggered.\n // Hence we work with two variables and check whether\n // we converge to no remaining reactions after a while.\n\n while (allReactions.length > 0) {\n if (++iterations === MAX_REACTION_ITERATIONS) {\n console.error( true ? \"Reaction doesn't converge to a stable state after \" + MAX_REACTION_ITERATIONS + \" iterations.\" + (\" Probably there is a cycle in the reactive function: \" + allReactions[0]) : undefined);\n allReactions.splice(0); // clear reactions\n }\n\n var remainingReactions = allReactions.splice(0);\n\n for (var i = 0, l = remainingReactions.length; i < l; i++) {\n remainingReactions[i].runReaction_();\n }\n }\n\n globalState.isRunningReactions = false;\n}\n\nvar isReaction = /*#__PURE__*/createInstanceofPredicate(\"Reaction\", Reaction);\nfunction setReactionScheduler(fn) {\n var baseScheduler = reactionScheduler;\n\n reactionScheduler = function reactionScheduler(f) {\n return fn(function () {\n return baseScheduler(f);\n });\n };\n}\n\nfunction isSpyEnabled() {\n return true && !!globalState.spyListeners.length;\n}\nfunction spyReport(event) {\n if (false) {} // dead code elimination can do the rest\n\n\n if (!globalState.spyListeners.length) {\n return;\n }\n\n var listeners = globalState.spyListeners;\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](event);\n }\n}\nfunction spyReportStart(event) {\n if (false) {}\n\n var change = _extends({}, event, {\n spyReportStart: true\n });\n\n spyReport(change);\n}\nvar END_EVENT = {\n type: \"report-end\",\n spyReportEnd: true\n};\nfunction spyReportEnd(change) {\n if (false) {}\n\n if (change) {\n spyReport(_extends({}, change, {\n type: \"report-end\",\n spyReportEnd: true\n }));\n } else {\n spyReport(END_EVENT);\n }\n}\nfunction spy(listener) {\n if (false) {} else {\n globalState.spyListeners.push(listener);\n return once(function () {\n globalState.spyListeners = globalState.spyListeners.filter(function (l) {\n return l !== listener;\n });\n });\n }\n}\n\nvar ACTION = \"action\";\nvar ACTION_BOUND = \"action.bound\";\nvar AUTOACTION = \"autoAction\";\nvar AUTOACTION_BOUND = \"autoAction.bound\";\nvar DEFAULT_ACTION_NAME = \"\";\nvar actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);\nvar actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {\n bound: true\n});\nvar autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {\n autoAction: true\n});\nvar autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {\n autoAction: true,\n bound: true\n});\n\nfunction createActionFactory(autoAction) {\n var res = function action(arg1, arg2) {\n // action(fn() {})\n if (isFunction(arg1)) {\n return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);\n } // action(\"name\", fn() {})\n\n\n if (isFunction(arg2)) {\n return createAction(arg1, arg2, autoAction);\n } // @action\n\n\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);\n } // action(\"name\") & @action(\"name\")\n\n\n if (isStringish(arg1)) {\n return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {\n name: arg1,\n autoAction: autoAction\n }));\n }\n\n if (true) {\n die(\"Invalid arguments for `action`\");\n }\n };\n\n return res;\n}\n\nvar action = /*#__PURE__*/createActionFactory(false);\nObject.assign(action, actionAnnotation);\nvar autoAction = /*#__PURE__*/createActionFactory(true);\nObject.assign(autoAction, autoActionAnnotation);\naction.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);\nautoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);\nfunction runInAction(fn) {\n return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);\n}\nfunction isAction(thing) {\n return isFunction(thing) && thing.isMobxAction === true;\n}\n\n/**\r\n * Creates a named reactive view and keeps it alive, so that the view is always\r\n * updated if one of the dependencies changes, even when the view is not further used by something else.\r\n * @param view The reactive view\r\n * @returns disposer function, which can be used to stop the view from being updated in the future.\r\n */\n\nfunction autorun(view, opts) {\n var _opts$name, _opts;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(view)) {\n die(\"Autorun expects a function as first argument\");\n }\n\n if (isAction(view)) {\n die(\"Autorun does not accept actions since actions are untrackable\");\n }\n }\n\n var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : true ? view.name || \"Autorun@\" + getNextId() : undefined;\n var runSync = !opts.scheduler && !opts.delay;\n var reaction;\n\n if (runSync) {\n // normal autorun\n reaction = new Reaction(name, function () {\n this.track(reactionRunner);\n }, opts.onError, opts.requiresObservable);\n } else {\n var scheduler = createSchedulerFromOptions(opts); // debounced autorun\n\n var isScheduled = false;\n reaction = new Reaction(name, function () {\n if (!isScheduled) {\n isScheduled = true;\n scheduler(function () {\n isScheduled = false;\n\n if (!reaction.isDisposed_) {\n reaction.track(reactionRunner);\n }\n });\n }\n }, opts.onError, opts.requiresObservable);\n }\n\n function reactionRunner() {\n view(reaction);\n }\n\n reaction.schedule_();\n return reaction.getDisposer_();\n}\n\nvar run = function run(f) {\n return f();\n};\n\nfunction createSchedulerFromOptions(opts) {\n return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {\n return setTimeout(f, opts.delay);\n } : run;\n}\n\nfunction reaction(expression, effect, opts) {\n var _opts$name2;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(expression) || !isFunction(effect)) {\n die(\"First and second argument to reaction should be functions\");\n }\n\n if (!isPlainObject(opts)) {\n die(\"Third argument of reactions should be an object\");\n }\n }\n\n var name = (_opts$name2 = opts.name) != null ? _opts$name2 : true ? \"Reaction@\" + getNextId() : undefined;\n var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);\n var runSync = !opts.scheduler && !opts.delay;\n var scheduler = createSchedulerFromOptions(opts);\n var firstTime = true;\n var isScheduled = false;\n var value;\n var oldValue;\n var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer[\"default\"];\n var r = new Reaction(name, function () {\n if (firstTime || runSync) {\n reactionRunner();\n } else if (!isScheduled) {\n isScheduled = true;\n scheduler(reactionRunner);\n }\n }, opts.onError, opts.requiresObservable);\n\n function reactionRunner() {\n isScheduled = false;\n\n if (r.isDisposed_) {\n return;\n }\n\n var changed = false;\n r.track(function () {\n var nextValue = allowStateChanges(false, function () {\n return expression(r);\n });\n changed = firstTime || !equals(value, nextValue);\n oldValue = value;\n value = nextValue;\n });\n\n if (firstTime && opts.fireImmediately) {\n effectAction(value, oldValue, r);\n } else if (!firstTime && changed) {\n effectAction(value, oldValue, r);\n }\n\n firstTime = false;\n }\n\n r.schedule_();\n return r.getDisposer_();\n}\n\nfunction wrapErrorHandler(errorHandler, baseFn) {\n return function () {\n try {\n return baseFn.apply(this, arguments);\n } catch (e) {\n errorHandler.call(this, e);\n }\n };\n}\n\nvar ON_BECOME_OBSERVED = \"onBO\";\nvar ON_BECOME_UNOBSERVED = \"onBUO\";\nfunction onBecomeObserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);\n}\nfunction onBecomeUnobserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);\n}\n\nfunction interceptHook(hook, thing, arg2, arg3) {\n var atom = typeof arg3 === \"function\" ? getAtom(thing, arg2) : getAtom(thing);\n var cb = isFunction(arg3) ? arg3 : arg2;\n var listenersKey = hook + \"L\";\n\n if (atom[listenersKey]) {\n atom[listenersKey].add(cb);\n } else {\n atom[listenersKey] = new Set([cb]);\n }\n\n return function () {\n var hookListeners = atom[listenersKey];\n\n if (hookListeners) {\n hookListeners[\"delete\"](cb);\n\n if (hookListeners.size === 0) {\n delete atom[listenersKey];\n }\n }\n };\n}\n\nvar NEVER = \"never\";\nvar ALWAYS = \"always\";\nvar OBSERVED = \"observed\"; // const IF_AVAILABLE = \"ifavailable\"\n\nfunction configure(options) {\n if (options.isolateGlobalState === true) {\n isolateGlobalState();\n }\n\n var useProxies = options.useProxies,\n enforceActions = options.enforceActions;\n\n if (useProxies !== undefined) {\n globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== \"undefined\";\n }\n\n if (useProxies === \"ifavailable\") {\n globalState.verifyProxies = true;\n }\n\n if (enforceActions !== undefined) {\n var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;\n globalState.enforceActions = ea;\n globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;\n }\n [\"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"disableErrorBoundaries\", \"safeDescriptors\"].forEach(function (key) {\n if (key in options) {\n globalState[key] = !!options[key];\n }\n });\n globalState.allowStateReads = !globalState.observableRequiresReaction;\n\n if ( true && globalState.disableErrorBoundaries === true) {\n console.warn(\"WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.\");\n }\n\n if (options.reactionScheduler) {\n setReactionScheduler(options.reactionScheduler);\n }\n}\n\nfunction extendObservable(target, properties, annotations, options) {\n if (true) {\n if (arguments.length > 4) {\n die(\"'extendObservable' expected 2-4 arguments\");\n }\n\n if (typeof target !== \"object\") {\n die(\"'extendObservable' expects an object as first argument\");\n }\n\n if (isObservableMap(target)) {\n die(\"'extendObservable' should not be used on maps, use map.merge instead\");\n }\n\n if (!isPlainObject(properties)) {\n die(\"'extendObservable' only accepts plain objects as second argument\");\n }\n\n if (isObservable(properties) || isObservable(annotations)) {\n die(\"Extending an object with another observable (object) is not supported\");\n }\n } // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)\n\n\n var descriptors = getOwnPropertyDescriptors(properties);\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n ownKeys(descriptors).forEach(function (key) {\n adm.extend_(key, descriptors[key], // must pass \"undefined\" for { key: undefined }\n !annotations ? true : key in annotations ? annotations[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nfunction getDependencyTree(thing, property) {\n return nodeToDependencyTree(getAtom(thing, property));\n}\n\nfunction nodeToDependencyTree(node) {\n var result = {\n name: node.name_\n };\n\n if (node.observing_ && node.observing_.length > 0) {\n result.dependencies = unique(node.observing_).map(nodeToDependencyTree);\n }\n\n return result;\n}\n\nfunction getObserverTree(thing, property) {\n return nodeToObserverTree(getAtom(thing, property));\n}\n\nfunction nodeToObserverTree(node) {\n var result = {\n name: node.name_\n };\n\n if (hasObservers(node)) {\n result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);\n }\n\n return result;\n}\n\nfunction unique(list) {\n return Array.from(new Set(list));\n}\n\nvar generatorId = 0;\nfunction FlowCancellationError() {\n this.message = \"FLOW_CANCELLED\";\n}\nFlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);\nfunction isFlowCancellationError(error) {\n return error instanceof FlowCancellationError;\n}\nvar flowAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow\");\nvar flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow.bound\", {\n bound: true\n});\nvar flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {\n // @flow\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, flowAnnotation);\n } // flow(fn)\n\n\n if ( true && arguments.length !== 1) {\n die(\"Flow expects single argument with generator function\");\n }\n\n var generator = arg1;\n var name = generator.name || \"\"; // Implementation based on https://github.com/tj/co/blob/master/index.js\n\n var res = function res() {\n var ctx = this;\n var args = arguments;\n var runId = ++generatorId;\n var gen = action(name + \" - runid: \" + runId + \" - init\", generator).apply(ctx, args);\n var rejector;\n var pendingPromise = undefined;\n var promise = new Promise(function (resolve, reject) {\n var stepId = 0;\n rejector = reject;\n\n function onFulfilled(res) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen.next).call(gen, res);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function onRejected(err) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen[\"throw\"]).call(gen, err);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function next(ret) {\n if (isFunction(ret == null ? void 0 : ret.then)) {\n // an async iterator\n ret.then(next, reject);\n return;\n }\n\n if (ret.done) {\n return resolve(ret.value);\n }\n\n pendingPromise = Promise.resolve(ret.value);\n return pendingPromise.then(onFulfilled, onRejected);\n }\n\n onFulfilled(undefined); // kick off the process\n });\n promise.cancel = action(name + \" - runid: \" + runId + \" - cancel\", function () {\n try {\n if (pendingPromise) {\n cancelPromise(pendingPromise);\n } // Finally block can return (or yield) stuff..\n\n\n var _res = gen[\"return\"](undefined); // eat anything that promise would do, it's cancelled!\n\n\n var yieldedPromise = Promise.resolve(_res.value);\n yieldedPromise.then(noop, noop);\n cancelPromise(yieldedPromise); // maybe it can be cancelled :)\n // reject our original promise\n\n rejector(new FlowCancellationError());\n } catch (e) {\n rejector(e); // there could be a throwing finally block\n }\n });\n return promise;\n };\n\n res.isMobXFlow = true;\n return res;\n}, flowAnnotation);\nflow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);\n\nfunction cancelPromise(promise) {\n if (isFunction(promise.cancel)) {\n promise.cancel();\n }\n}\n\nfunction flowResult(result) {\n return result; // just tricking TypeScript :)\n}\nfunction isFlow(fn) {\n return (fn == null ? void 0 : fn.isMobXFlow) === true;\n}\n\nfunction interceptReads(thing, propOrHandler, handler) {\n var target;\n\n if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {\n target = getAdministration(thing);\n } else if (isObservableObject(thing)) {\n if ( true && !isStringish(propOrHandler)) {\n return die(\"InterceptReads can only be used with a specific property, not with an object in general\");\n }\n\n target = getAdministration(thing, propOrHandler);\n } else if (true) {\n return die(\"Expected observable map, object or array as first array\");\n }\n\n if ( true && target.dehancer !== undefined) {\n return die(\"An intercept reader was already established\");\n }\n\n target.dehancer = typeof propOrHandler === \"function\" ? propOrHandler : handler;\n return function () {\n target.dehancer = undefined;\n };\n}\n\nfunction intercept(thing, propOrHandler, handler) {\n if (isFunction(handler)) {\n return interceptProperty(thing, propOrHandler, handler);\n } else {\n return interceptInterceptable(thing, propOrHandler);\n }\n}\n\nfunction interceptInterceptable(thing, handler) {\n return getAdministration(thing).intercept_(handler);\n}\n\nfunction interceptProperty(thing, property, handler) {\n return getAdministration(thing, property).intercept_(handler);\n}\n\nfunction _isComputed(value, property) {\n if (property === undefined) {\n return isComputedValue(value);\n }\n\n if (isObservableObject(value) === false) {\n return false;\n }\n\n if (!value[$mobx].values_.has(property)) {\n return false;\n }\n\n var atom = getAtom(value, property);\n return isComputedValue(atom);\n}\nfunction isComputed(value) {\n if ( true && arguments.length > 1) {\n return die(\"isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property\");\n }\n\n return _isComputed(value);\n}\nfunction isComputedProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"isComputed expected a property name as second argument\");\n }\n\n return _isComputed(value, propName);\n}\n\nfunction _isObservable(value, property) {\n if (!value) {\n return false;\n }\n\n if (property !== undefined) {\n if ( true && (isObservableMap(value) || isObservableArray(value))) {\n return die(\"isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.\");\n }\n\n if (isObservableObject(value)) {\n return value[$mobx].values_.has(property);\n }\n\n return false;\n } // For first check, see #701\n\n\n return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);\n}\n\nfunction isObservable(value) {\n if ( true && arguments.length !== 1) {\n die(\"isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property\");\n }\n\n return _isObservable(value);\n}\nfunction isObservableProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"expected a property name as second argument\");\n }\n\n return _isObservable(value, propName);\n}\n\nfunction keys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].keys_();\n }\n\n if (isObservableMap(obj) || isObservableSet(obj)) {\n return Array.from(obj.keys());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (_, index) {\n return index;\n });\n }\n\n die(5);\n}\nfunction values(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return obj[key];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return obj.get(key);\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.values());\n }\n\n if (isObservableArray(obj)) {\n return obj.slice();\n }\n\n die(6);\n}\nfunction entries(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj.get(key)];\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.entries());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (key, index) {\n return [index, key];\n });\n }\n\n die(7);\n}\nfunction set(obj, key, value) {\n if (arguments.length === 2 && !isObservableSet(obj)) {\n startBatch();\n var _values = key;\n\n try {\n for (var _key in _values) {\n set(obj, _key, _values[_key]);\n }\n } finally {\n endBatch();\n }\n\n return;\n }\n\n if (isObservableObject(obj)) {\n obj[$mobx].set_(key, value);\n } else if (isObservableMap(obj)) {\n obj.set(key, value);\n } else if (isObservableSet(obj)) {\n obj.add(key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n if (key < 0) {\n die(\"Invalid index: '\" + key + \"'\");\n }\n\n startBatch();\n\n if (key >= obj.length) {\n obj.length = key + 1;\n }\n\n obj[key] = value;\n endBatch();\n } else {\n die(8);\n }\n}\nfunction remove(obj, key) {\n if (isObservableObject(obj)) {\n obj[$mobx].delete_(key);\n } else if (isObservableMap(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableSet(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n obj.splice(key, 1);\n } else {\n die(9);\n }\n}\nfunction has(obj, key) {\n if (isObservableObject(obj)) {\n return obj[$mobx].has_(key);\n } else if (isObservableMap(obj)) {\n return obj.has(key);\n } else if (isObservableSet(obj)) {\n return obj.has(key);\n } else if (isObservableArray(obj)) {\n return key >= 0 && key < obj.length;\n }\n\n die(10);\n}\nfunction get(obj, key) {\n if (!has(obj, key)) {\n return undefined;\n }\n\n if (isObservableObject(obj)) {\n return obj[$mobx].get_(key);\n } else if (isObservableMap(obj)) {\n return obj.get(key);\n } else if (isObservableArray(obj)) {\n return obj[key];\n }\n\n die(11);\n}\nfunction apiDefineProperty(obj, key, descriptor) {\n if (isObservableObject(obj)) {\n return obj[$mobx].defineProperty_(key, descriptor);\n }\n\n die(39);\n}\nfunction apiOwnKeys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].ownKeys_();\n }\n\n die(38);\n}\n\nfunction observe(thing, propOrCb, cbOrFire, fireImmediately) {\n if (isFunction(cbOrFire)) {\n return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);\n } else {\n return observeObservable(thing, propOrCb, cbOrFire);\n }\n}\n\nfunction observeObservable(thing, listener, fireImmediately) {\n return getAdministration(thing).observe_(listener, fireImmediately);\n}\n\nfunction observeObservableProperty(thing, property, listener, fireImmediately) {\n return getAdministration(thing, property).observe_(listener, fireImmediately);\n}\n\nfunction cache(map, key, value) {\n map.set(key, value);\n return value;\n}\n\nfunction toJSHelper(source, __alreadySeen) {\n if (source == null || typeof source !== \"object\" || source instanceof Date || !isObservable(source)) {\n return source;\n }\n\n if (isObservableValue(source) || isComputedValue(source)) {\n return toJSHelper(source.get(), __alreadySeen);\n }\n\n if (__alreadySeen.has(source)) {\n return __alreadySeen.get(source);\n }\n\n if (isObservableArray(source)) {\n var res = cache(__alreadySeen, source, new Array(source.length));\n source.forEach(function (value, idx) {\n res[idx] = toJSHelper(value, __alreadySeen);\n });\n return res;\n }\n\n if (isObservableSet(source)) {\n var _res = cache(__alreadySeen, source, new Set());\n\n source.forEach(function (value) {\n _res.add(toJSHelper(value, __alreadySeen));\n });\n return _res;\n }\n\n if (isObservableMap(source)) {\n var _res2 = cache(__alreadySeen, source, new Map());\n\n source.forEach(function (value, key) {\n _res2.set(key, toJSHelper(value, __alreadySeen));\n });\n return _res2;\n } else {\n // must be observable object\n var _res3 = cache(__alreadySeen, source, {});\n\n apiOwnKeys(source).forEach(function (key) {\n if (objectPrototype.propertyIsEnumerable.call(source, key)) {\n _res3[key] = toJSHelper(source[key], __alreadySeen);\n }\n });\n return _res3;\n }\n}\n/**\r\n * Recursively converts an observable to it's non-observable native counterpart.\r\n * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.\r\n * Computed and other non-enumerable properties are completely ignored.\r\n * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.\r\n */\n\n\nfunction toJS(source, options) {\n if ( true && options) {\n die(\"toJS no longer supports options\");\n }\n\n return toJSHelper(source, new Map());\n}\n\nfunction trace() {\n if (false) {}\n\n var enterBreakPoint = false;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (typeof args[args.length - 1] === \"boolean\") {\n enterBreakPoint = args.pop();\n }\n\n var derivation = getAtomFromArgs(args);\n\n if (!derivation) {\n return die(\"'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly\");\n }\n\n if (derivation.isTracing_ === TraceMode.NONE) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' tracing enabled\");\n }\n\n derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;\n}\n\nfunction getAtomFromArgs(args) {\n switch (args.length) {\n case 0:\n return globalState.trackingDerivation;\n\n case 1:\n return getAtom(args[0]);\n\n case 2:\n return getAtom(args[0], args[1]);\n }\n}\n\n/**\r\n * During a transaction no views are updated until the end of the transaction.\r\n * The transaction will be run synchronously nonetheless.\r\n *\r\n * @param action a function that updates some reactive state\r\n * @returns any value that was returned by the 'action' parameter.\r\n */\n\nfunction transaction(action, thisArg) {\n if (thisArg === void 0) {\n thisArg = undefined;\n }\n\n startBatch();\n\n try {\n return action.apply(thisArg);\n } finally {\n endBatch();\n }\n}\n\nfunction when(predicate, arg1, arg2) {\n if (arguments.length === 1 || arg1 && typeof arg1 === \"object\") {\n return whenPromise(predicate, arg1);\n }\n\n return _when(predicate, arg1, arg2 || {});\n}\n\nfunction _when(predicate, effect, opts) {\n var timeoutHandle;\n\n if (typeof opts.timeout === \"number\") {\n var error = new Error(\"WHEN_TIMEOUT\");\n timeoutHandle = setTimeout(function () {\n if (!disposer[$mobx].isDisposed_) {\n disposer();\n\n if (opts.onError) {\n opts.onError(error);\n } else {\n throw error;\n }\n }\n }, opts.timeout);\n }\n\n opts.name = true ? opts.name || \"When@\" + getNextId() : undefined;\n var effectAction = createAction( true ? opts.name + \"-effect\" : undefined, effect); // eslint-disable-next-line\n\n var disposer = autorun(function (r) {\n // predicate should not change state\n var cond = allowStateChanges(false, predicate);\n\n if (cond) {\n r.dispose();\n\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n\n effectAction();\n }\n }, opts);\n return disposer;\n}\n\nfunction whenPromise(predicate, opts) {\n var _opts$signal;\n\n if ( true && opts && opts.onError) {\n return die(\"the options 'onError' and 'promise' cannot be combined\");\n }\n\n if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {\n return Object.assign(Promise.reject(new Error(\"WHEN_ABORTED\")), {\n cancel: function cancel() {\n return null;\n }\n });\n }\n\n var cancel;\n var abort;\n var res = new Promise(function (resolve, reject) {\n var _opts$signal2;\n\n var disposer = _when(predicate, resolve, _extends({}, opts, {\n onError: reject\n }));\n\n cancel = function cancel() {\n disposer();\n reject(new Error(\"WHEN_CANCELLED\"));\n };\n\n abort = function abort() {\n disposer();\n reject(new Error(\"WHEN_ABORTED\"));\n };\n\n opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener(\"abort\", abort);\n })[\"finally\"](function () {\n var _opts$signal3;\n\n return opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener(\"abort\", abort);\n });\n res.cancel = cancel;\n return res;\n}\n\nfunction getAdm(target) {\n return target[$mobx];\n} // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,\n// and skip either the internal values map, or the base object with its property descriptors!\n\n\nvar objectProxyTraps = {\n has: function has(target, name) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.\");\n }\n\n return getAdm(target).has_(name);\n },\n get: function get(target, name) {\n return getAdm(target).get_(name);\n },\n set: function set(target, name, value) {\n var _getAdm$set_;\n\n if (!isStringish(name)) {\n return false;\n }\n\n if ( true && !getAdm(target).values_.has(name)) {\n warnAboutProxyRequirement(\"add a new observable property through direct assignment. Use 'set' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;\n },\n deleteProperty: function deleteProperty(target, name) {\n var _getAdm$delete_;\n\n if (true) {\n warnAboutProxyRequirement(\"delete properties from an observable object. Use 'remove' from 'mobx' instead.\");\n }\n\n if (!isStringish(name)) {\n return false;\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;\n },\n defineProperty: function defineProperty(target, name, descriptor) {\n var _getAdm$definePropert;\n\n if (true) {\n warnAboutProxyRequirement(\"define property on an observable object. Use 'defineProperty' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;\n },\n ownKeys: function ownKeys(target) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.\");\n }\n\n return getAdm(target).ownKeys_();\n },\n preventExtensions: function preventExtensions(target) {\n die(13);\n }\n};\nfunction asDynamicObservableObject(target, options) {\n var _target$$mobx, _target$$mobx$proxy_;\n\n assertProxies();\n target = asObservableObject(target, options);\n return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);\n}\n\nfunction hasInterceptors(interceptable) {\n return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;\n}\nfunction registerInterceptor(interceptable, handler) {\n var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);\n interceptors.push(handler);\n return once(function () {\n var idx = interceptors.indexOf(handler);\n\n if (idx !== -1) {\n interceptors.splice(idx, 1);\n }\n });\n}\nfunction interceptChange(interceptable, change) {\n var prevU = untrackedStart();\n\n try {\n // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950\n var interceptors = [].concat(interceptable.interceptors_ || []);\n\n for (var i = 0, l = interceptors.length; i < l; i++) {\n change = interceptors[i](change);\n\n if (change && !change.type) {\n die(14);\n }\n\n if (!change) {\n break;\n }\n }\n\n return change;\n } finally {\n untrackedEnd(prevU);\n }\n}\n\nfunction hasListeners(listenable) {\n return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;\n}\nfunction registerListener(listenable, handler) {\n var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);\n listeners.push(handler);\n return once(function () {\n var idx = listeners.indexOf(handler);\n\n if (idx !== -1) {\n listeners.splice(idx, 1);\n }\n });\n}\nfunction notifyListeners(listenable, change) {\n var prevU = untrackedStart();\n var listeners = listenable.changeListeners_;\n\n if (!listeners) {\n return;\n }\n\n listeners = listeners.slice();\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](change);\n }\n\n untrackedEnd(prevU);\n}\n\nfunction makeObservable(target, annotations, options) {\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n var _annotations;\n\n if ( true && annotations && target[storedAnnotationsSymbol]) {\n die(\"makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.\");\n } // Default to decorators\n\n\n (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target); // Annotate\n\n ownKeys(annotations).forEach(function (key) {\n return adm.make_(key, annotations[key]);\n });\n } finally {\n endBatch();\n }\n\n return target;\n} // proto[keysSymbol] = new Set()\n\nvar keysSymbol = /*#__PURE__*/Symbol(\"mobx-keys\");\nfunction makeAutoObservable(target, overrides, options) {\n if (true) {\n if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {\n die(\"'makeAutoObservable' can only be used for classes that don't have a superclass\");\n }\n\n if (isObservableObject(target)) {\n die(\"makeAutoObservable can only be used on objects not already made observable\");\n }\n } // Optimization: avoid visiting protos\n // Assumes that annotation.make_/.extend_ works the same for plain objects\n\n\n if (isPlainObject(target)) {\n return extendObservable(target, target, overrides, options);\n }\n\n var adm = asObservableObject(target, options)[$mobx]; // Optimization: cache keys on proto\n // Assumes makeAutoObservable can be called only once per object and can't be used in subclass\n\n if (!target[keysSymbol]) {\n var proto = Object.getPrototypeOf(target);\n var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));\n keys[\"delete\"](\"constructor\");\n keys[\"delete\"]($mobx);\n addHiddenProp(proto, keysSymbol, keys);\n }\n\n startBatch();\n\n try {\n target[keysSymbol].forEach(function (key) {\n return adm.make_(key, // must pass \"undefined\" for { key: undefined }\n !overrides ? true : key in overrides ? overrides[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nvar SPLICE = \"splice\";\nvar UPDATE = \"update\";\nvar MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859\n\nvar arrayTraps = {\n get: function get(target, name) {\n var adm = target[$mobx];\n\n if (name === $mobx) {\n return adm;\n }\n\n if (name === \"length\") {\n return adm.getArrayLength_();\n }\n\n if (typeof name === \"string\" && !isNaN(name)) {\n return adm.get_(parseInt(name));\n }\n\n if (hasProp(arrayExtensions, name)) {\n return arrayExtensions[name];\n }\n\n return target[name];\n },\n set: function set(target, name, value) {\n var adm = target[$mobx];\n\n if (name === \"length\") {\n adm.setArrayLength_(value);\n }\n\n if (typeof name === \"symbol\" || isNaN(name)) {\n target[name] = value;\n } else {\n // numeric string\n adm.set_(parseInt(name), value);\n }\n\n return true;\n },\n preventExtensions: function preventExtensions() {\n die(15);\n }\n};\nvar ObservableArrayAdministration = /*#__PURE__*/function () {\n // this is the prop that gets proxied, so can't replace it!\n function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n this.owned_ = void 0;\n this.legacyMode_ = void 0;\n this.atom_ = void 0;\n this.values_ = [];\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.enhancer_ = void 0;\n this.dehancer = void 0;\n this.proxy_ = void 0;\n this.lastKnownLength_ = 0;\n this.owned_ = owned_;\n this.legacyMode_ = legacyMode_;\n this.atom_ = new Atom(name);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, true ? name + \"[..]\" : undefined);\n };\n }\n\n var _proto = ObservableArrayAdministration.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.dehanceValues_ = function dehanceValues_(values) {\n if (this.dehancer !== undefined && values.length > 0) {\n return values.map(this.dehancer);\n }\n\n return values;\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately === void 0) {\n fireImmediately = false;\n }\n\n if (fireImmediately) {\n listener({\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: \"splice\",\n index: 0,\n added: this.values_.slice(),\n addedCount: this.values_.length,\n removed: [],\n removedCount: 0\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.getArrayLength_ = function getArrayLength_() {\n this.atom_.reportObserved();\n return this.values_.length;\n };\n\n _proto.setArrayLength_ = function setArrayLength_(newLength) {\n if (typeof newLength !== \"number\" || isNaN(newLength) || newLength < 0) {\n die(\"Out of range: \" + newLength);\n }\n\n var currentLength = this.values_.length;\n\n if (newLength === currentLength) {\n return;\n } else if (newLength > currentLength) {\n var newItems = new Array(newLength - currentLength);\n\n for (var i = 0; i < newLength - currentLength; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n this.spliceWithArray_(currentLength, 0, newItems);\n } else {\n this.spliceWithArray_(newLength, currentLength - newLength);\n }\n };\n\n _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {\n if (oldLength !== this.lastKnownLength_) {\n die(16);\n }\n\n this.lastKnownLength_ += delta;\n\n if (this.legacyMode_ && delta > 0) {\n reserveArrayBuffer(oldLength + delta + 1);\n }\n };\n\n _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {\n var _this = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n var length = this.values_.length;\n\n if (index === undefined) {\n index = 0;\n } else if (index > length) {\n index = length;\n } else if (index < 0) {\n index = Math.max(0, length + index);\n }\n\n if (arguments.length === 1) {\n deleteCount = length - index;\n } else if (deleteCount === undefined || deleteCount === null) {\n deleteCount = 0;\n } else {\n deleteCount = Math.max(0, Math.min(deleteCount, length - index));\n }\n\n if (newItems === undefined) {\n newItems = EMPTY_ARRAY;\n }\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_,\n type: SPLICE,\n index: index,\n removedCount: deleteCount,\n added: newItems\n });\n\n if (!change) {\n return EMPTY_ARRAY;\n }\n\n deleteCount = change.removedCount;\n newItems = change.added;\n }\n\n newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {\n return _this.enhancer_(v, undefined);\n });\n\n if (this.legacyMode_ || \"development\" !== \"production\") {\n var lengthDelta = newItems.length - deleteCount;\n this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified\n }\n\n var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);\n\n if (deleteCount !== 0 || newItems.length !== 0) {\n this.notifyArraySplice_(index, newItems, res);\n }\n\n return this.dehanceValues_(res);\n };\n\n _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {\n if (newItems.length < MAX_SPLICE_SIZE) {\n var _this$values_;\n\n return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));\n } else {\n // The items removed by the splice\n var res = this.values_.slice(index, index + deleteCount); // The items that that should remain at the end of the array\n\n var oldItems = this.values_.slice(index + deleteCount); // New length is the previous length + addition count - deletion count\n\n this.values_.length += newItems.length - deleteCount;\n\n for (var i = 0; i < newItems.length; i++) {\n this.values_[index + i] = newItems[i];\n }\n\n for (var _i = 0; _i < oldItems.length; _i++) {\n this.values_[index + newItems.length + _i] = oldItems[_i];\n }\n\n return res;\n }\n };\n\n _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n type: UPDATE,\n debugObjectName: this.atom_.name_,\n index: index,\n newValue: newValue,\n oldValue: oldValue\n } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't\n // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged();\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: SPLICE,\n index: index,\n removed: removed,\n added: added,\n removedCount: removed.length,\n addedCount: added.length\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get_ = function get_(index) {\n if (this.legacyMode_ && index >= this.values_.length) {\n console.warn( true ? \"[mobx.array] Attempt to read an array index (\" + index + \") that is out of bounds (\" + this.values_.length + \"). Please check length first. Out of bound indices will not be tracked by MobX\" : undefined);\n return undefined;\n }\n\n this.atom_.reportObserved();\n return this.dehanceValue_(this.values_[index]);\n };\n\n _proto.set_ = function set_(index, newValue) {\n var values = this.values_;\n\n if (this.legacyMode_ && index > values.length) {\n // out of bounds\n die(17, index, values.length);\n }\n\n if (index < values.length) {\n // update at index in range\n checkIfStateModificationsAreAllowed(this.atom_);\n var oldValue = values[index];\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_,\n index: index,\n newValue: newValue\n });\n\n if (!change) {\n return;\n }\n\n newValue = change.newValue;\n }\n\n newValue = this.enhancer_(newValue, oldValue);\n var changed = newValue !== oldValue;\n\n if (changed) {\n values[index] = newValue;\n this.notifyArrayChildUpdate_(index, newValue, oldValue);\n }\n } else {\n // For out of bound index, we don't create an actual sparse array,\n // but rather fill the holes with undefined (same as setArrayLength_).\n // This could be considered a bug.\n var newItems = new Array(index + 1 - values.length);\n\n for (var i = 0; i < newItems.length - 1; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n newItems[newItems.length - 1] = newValue;\n this.spliceWithArray_(values.length, 0, newItems);\n }\n };\n\n return ObservableArrayAdministration;\n}();\nfunction createObservableArray(initialValues, enhancer, name, owned) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n assertProxies();\n var adm = new ObservableArrayAdministration(name, enhancer, owned, false);\n addHiddenFinalProp(adm.values_, $mobx, adm);\n var proxy = new Proxy(adm.values_, arrayTraps);\n adm.proxy_ = proxy;\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true);\n adm.spliceWithArray_(0, 0, initialValues);\n allowStateChangesEnd(prev);\n }\n\n return proxy;\n} // eslint-disable-next-line\n\nvar arrayExtensions = {\n clear: function clear() {\n return this.splice(0);\n },\n replace: function replace(newItems) {\n var adm = this[$mobx];\n return adm.spliceWithArray_(0, adm.values_.length, newItems);\n },\n // Used by JSON.stringify\n toJSON: function toJSON() {\n return this.slice();\n },\n\n /*\r\n * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)\r\n * since these functions alter the inner structure of the array, the have side effects.\r\n * Because the have side effects, they should not be used in computed function,\r\n * and for that reason the do not call dependencyState.notifyObserved\r\n */\n splice: function splice(index, deleteCount) {\n for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n newItems[_key - 2] = arguments[_key];\n }\n\n var adm = this[$mobx];\n\n switch (arguments.length) {\n case 0:\n return [];\n\n case 1:\n return adm.spliceWithArray_(index);\n\n case 2:\n return adm.spliceWithArray_(index, deleteCount);\n }\n\n return adm.spliceWithArray_(index, deleteCount, newItems);\n },\n spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {\n return this[$mobx].spliceWithArray_(index, deleteCount, newItems);\n },\n push: function push() {\n var adm = this[$mobx];\n\n for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n items[_key2] = arguments[_key2];\n }\n\n adm.spliceWithArray_(adm.values_.length, 0, items);\n return adm.values_.length;\n },\n pop: function pop() {\n return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];\n },\n shift: function shift() {\n return this.splice(0, 1)[0];\n },\n unshift: function unshift() {\n var adm = this[$mobx];\n\n for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n items[_key3] = arguments[_key3];\n }\n\n adm.spliceWithArray_(0, 0, items);\n return adm.values_.length;\n },\n reverse: function reverse() {\n // reverse by default mutates in place before returning the result\n // which makes it both a 'derivation' and a 'mutation'.\n if (globalState.trackingDerivation) {\n die(37, \"reverse\");\n }\n\n this.replace(this.slice().reverse());\n return this;\n },\n sort: function sort() {\n // sort by default mutates in place before returning the result\n // which goes against all good practices. Let's not change the array in place!\n if (globalState.trackingDerivation) {\n die(37, \"sort\");\n }\n\n var copy = this.slice();\n copy.sort.apply(copy, arguments);\n this.replace(copy);\n return this;\n },\n remove: function remove(value) {\n var adm = this[$mobx];\n var idx = adm.dehanceValues_(adm.values_).indexOf(value);\n\n if (idx > -1) {\n this.splice(idx, 1);\n return true;\n }\n\n return false;\n }\n};\n/**\r\n * Wrap function from prototype\r\n * Without this, everything works as well, but this works\r\n * faster as everything works on unproxied values\r\n */\n\naddArrayExtension(\"concat\", simpleFunc);\naddArrayExtension(\"flat\", simpleFunc);\naddArrayExtension(\"includes\", simpleFunc);\naddArrayExtension(\"indexOf\", simpleFunc);\naddArrayExtension(\"join\", simpleFunc);\naddArrayExtension(\"lastIndexOf\", simpleFunc);\naddArrayExtension(\"slice\", simpleFunc);\naddArrayExtension(\"toString\", simpleFunc);\naddArrayExtension(\"toLocaleString\", simpleFunc); // map\n\naddArrayExtension(\"every\", mapLikeFunc);\naddArrayExtension(\"filter\", mapLikeFunc);\naddArrayExtension(\"find\", mapLikeFunc);\naddArrayExtension(\"findIndex\", mapLikeFunc);\naddArrayExtension(\"flatMap\", mapLikeFunc);\naddArrayExtension(\"forEach\", mapLikeFunc);\naddArrayExtension(\"map\", mapLikeFunc);\naddArrayExtension(\"some\", mapLikeFunc); // reduce\n\naddArrayExtension(\"reduce\", reduceLikeFunc);\naddArrayExtension(\"reduceRight\", reduceLikeFunc);\n\nfunction addArrayExtension(funcName, funcFactory) {\n if (typeof Array.prototype[funcName] === \"function\") {\n arrayExtensions[funcName] = funcFactory(funcName);\n }\n} // Report and delegate to dehanced array\n\n\nfunction simpleFunc(funcName) {\n return function () {\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction mapLikeFunc(funcName) {\n return function (callback, thisArg) {\n var _this2 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName](function (element, index) {\n return callback.call(thisArg, element, index, _this2);\n });\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction reduceLikeFunc(funcName) {\n return function () {\n var _this3 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_); // #2432 - reduce behavior depends on arguments.length\n\n var callback = arguments[0];\n\n arguments[0] = function (accumulator, currentValue, index) {\n return callback(accumulator, currentValue, index, _this3);\n };\n\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\n\nvar isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableArrayAdministration\", ObservableArrayAdministration);\nfunction isObservableArray(thing) {\n return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);\n}\n\nvar _Symbol$iterator, _Symbol$toStringTag;\nvar ObservableMapMarker = {};\nvar ADD = \"add\";\nvar DELETE = \"delete\"; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54\n// But: https://github.com/mobxjs/mobx/issues/1556\n\n_Symbol$iterator = Symbol.iterator;\n_Symbol$toStringTag = Symbol.toStringTag;\nvar ObservableMap = /*#__PURE__*/function () {\n // hasMap, not hashMap >-).\n function ObservableMap(initialData, enhancer_, name_) {\n var _this = this;\n\n if (enhancer_ === void 0) {\n enhancer_ = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableMap@\" + getNextId() : undefined;\n }\n\n this.enhancer_ = void 0;\n this.name_ = void 0;\n this[$mobx] = ObservableMapMarker;\n this.data_ = void 0;\n this.hasMap_ = void 0;\n this.keysAtom_ = void 0;\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = enhancer_;\n this.name_ = name_;\n\n if (!isFunction(Map)) {\n die(18);\n }\n\n this.keysAtom_ = createAtom( true ? this.name_ + \".keys()\" : undefined);\n this.data_ = new Map();\n this.hasMap_ = new Map();\n allowStateChanges(true, function () {\n _this.merge(initialData);\n });\n }\n\n var _proto = ObservableMap.prototype;\n\n _proto.has_ = function has_(key) {\n return this.data_.has(key);\n };\n\n _proto.has = function has(key) {\n var _this2 = this;\n\n if (!globalState.trackingDerivation) {\n return this.has_(key);\n }\n\n var entry = this.hasMap_.get(key);\n\n if (!entry) {\n var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.hasMap_.set(key, newEntry);\n onBecomeUnobserved(newEntry, function () {\n return _this2.hasMap_[\"delete\"](key);\n });\n }\n\n return entry.get();\n };\n\n _proto.set = function set(key, value) {\n var hasKey = this.has_(key);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: hasKey ? UPDATE : ADD,\n object: this,\n newValue: value,\n name: key\n });\n\n if (!change) {\n return this;\n }\n\n value = change.newValue;\n }\n\n if (hasKey) {\n this.updateValue_(key, value);\n } else {\n this.addValue_(key, value);\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(key) {\n var _this3 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n name: key\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has_(key)) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: this.data_.get(key).value_,\n name: key\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n } // TODO fix type\n\n\n transaction(function () {\n var _this3$hasMap_$get;\n\n _this3.keysAtom_.reportChanged();\n\n (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false);\n\n var observable = _this3.data_.get(key);\n\n observable.setNewValue_(undefined);\n\n _this3.data_[\"delete\"](key);\n });\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.updateValue_ = function updateValue_(key, newValue) {\n var observable = this.data_.get(key);\n newValue = observable.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: UPDATE,\n object: this,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.addValue_ = function addValue_(key, newValue) {\n var _this4 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n transaction(function () {\n var _this4$hasMap_$get;\n\n var observable = new ObservableValue(newValue, _this4.enhancer_, true ? _this4.name_ + \".\" + stringifyKey(key) : undefined, false);\n\n _this4.data_.set(key, observable);\n\n newValue = observable.value_; // value might have been changed\n\n (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true);\n\n _this4.keysAtom_.reportChanged();\n });\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get = function get(key) {\n if (this.has(key)) {\n return this.dehanceValue_(this.data_.get(key).get());\n }\n\n return this.dehanceValue_(undefined);\n };\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.keys = function keys() {\n this.keysAtom_.reportObserved();\n return this.data_.keys();\n };\n\n _proto.values = function values() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next = keys.next(),\n done = _keys$next.done,\n value = _keys$next.value;\n\n return {\n done: done,\n value: done ? undefined : self.get(value)\n };\n }\n });\n };\n\n _proto.entries = function entries() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next2 = keys.next(),\n done = _keys$next2.done,\n value = _keys$next2.value;\n\n return {\n done: done,\n value: done ? undefined : [value, self.get(value)]\n };\n }\n });\n };\n\n _proto[_Symbol$iterator] = function () {\n return this.entries();\n };\n\n _proto.forEach = function forEach(callback, thisArg) {\n for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {\n var _step$value = _step.value,\n key = _step$value[0],\n value = _step$value[1];\n callback.call(thisArg, value, key, this);\n }\n }\n /** Merge another object into this object, returns this. */\n ;\n\n _proto.merge = function merge(other) {\n var _this5 = this;\n\n if (isObservableMap(other)) {\n other = new Map(other);\n }\n\n transaction(function () {\n if (isPlainObject(other)) {\n getPlainObjectKeys(other).forEach(function (key) {\n return _this5.set(key, other[key]);\n });\n } else if (Array.isArray(other)) {\n other.forEach(function (_ref) {\n var key = _ref[0],\n value = _ref[1];\n return _this5.set(key, value);\n });\n } else if (isES6Map(other)) {\n if (other.constructor !== Map) {\n die(19, other);\n }\n\n other.forEach(function (value, key) {\n return _this5.set(key, value);\n });\n } else if (other !== null && other !== undefined) {\n die(20, other);\n }\n });\n return this;\n };\n\n _proto.clear = function clear() {\n var _this6 = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {\n var key = _step2.value;\n\n _this6[\"delete\"](key);\n }\n });\n });\n };\n\n _proto.replace = function replace(values) {\n var _this7 = this;\n\n // Implementation requirements:\n // - respect ordering of replacement map\n // - allow interceptors to run and potentially prevent individual operations\n // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)\n // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)\n // - note that result map may differ from replacement map due to the interceptors\n transaction(function () {\n // Convert to map so we can do quick key lookups\n var replacementMap = convertToMap(values);\n var orderedData = new Map(); // Used for optimization\n\n var keysReportChangedCalled = false; // Delete keys that don't exist in replacement map\n // if the key deletion is prevented by interceptor\n // add entry at the beginning of the result map\n\n for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {\n var key = _step3.value;\n\n // Concurrently iterating/deleting keys\n // iterator should handle this correctly\n if (!replacementMap.has(key)) {\n var deleted = _this7[\"delete\"](key); // Was the key removed?\n\n\n if (deleted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n } else {\n // Delete prevented by interceptor\n var value = _this7.data_.get(key);\n\n orderedData.set(key, value);\n }\n }\n } // Merge entries\n\n\n for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {\n var _step4$value = _step4.value,\n _key = _step4$value[0],\n _value = _step4$value[1];\n\n // We will want to know whether a new key is added\n var keyExisted = _this7.data_.has(_key); // Add or update value\n\n\n _this7.set(_key, _value); // The addition could have been prevent by interceptor\n\n\n if (_this7.data_.has(_key)) {\n // The update could have been prevented by interceptor\n // and also we want to preserve existing values\n // so use value from _data map (instead of replacement map)\n var _value2 = _this7.data_.get(_key);\n\n orderedData.set(_key, _value2); // Was a new key added?\n\n if (!keyExisted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n }\n }\n } // Check for possible key order change\n\n\n if (!keysReportChangedCalled) {\n if (_this7.data_.size !== orderedData.size) {\n // If size differs, keys are definitely modified\n _this7.keysAtom_.reportChanged();\n } else {\n var iter1 = _this7.data_.keys();\n\n var iter2 = orderedData.keys();\n var next1 = iter1.next();\n var next2 = iter2.next();\n\n while (!next1.done) {\n if (next1.value !== next2.value) {\n _this7.keysAtom_.reportChanged();\n\n break;\n }\n\n next1 = iter1.next();\n next2 = iter2.next();\n }\n }\n } // Use correctly ordered map\n\n\n _this7.data_ = orderedData;\n });\n return this;\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableMap]\";\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with maps.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _createClass(ObservableMap, [{\n key: \"size\",\n get: function get() {\n this.keysAtom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Map\";\n }\n }]);\n\n return ObservableMap;\n}(); // eslint-disable-next-line\n\nvar isObservableMap = /*#__PURE__*/createInstanceofPredicate(\"ObservableMap\", ObservableMap);\n\nfunction convertToMap(dataStructure) {\n if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {\n return dataStructure;\n } else if (Array.isArray(dataStructure)) {\n return new Map(dataStructure);\n } else if (isPlainObject(dataStructure)) {\n var map = new Map();\n\n for (var key in dataStructure) {\n map.set(key, dataStructure[key]);\n }\n\n return map;\n } else {\n return die(21, dataStructure);\n }\n}\n\nvar _Symbol$iterator$1, _Symbol$toStringTag$1;\nvar ObservableSetMarker = {};\n_Symbol$iterator$1 = Symbol.iterator;\n_Symbol$toStringTag$1 = Symbol.toStringTag;\nvar ObservableSet = /*#__PURE__*/function () {\n function ObservableSet(initialData, enhancer, name_) {\n if (enhancer === void 0) {\n enhancer = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableSet@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this[$mobx] = ObservableSetMarker;\n this.data_ = new Set();\n this.atom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = void 0;\n this.name_ = name_;\n\n if (!isFunction(Set)) {\n die(22);\n }\n\n this.atom_ = createAtom(this.name_);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, name_);\n };\n\n if (initialData) {\n this.replace(initialData);\n }\n }\n\n var _proto = ObservableSet.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.clear = function clear() {\n var _this = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) {\n var value = _step.value;\n\n _this[\"delete\"](value);\n }\n });\n });\n };\n\n _proto.forEach = function forEach(callbackFn, thisArg) {\n for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {\n var value = _step2.value;\n callbackFn.call(thisArg, value, value, this);\n }\n };\n\n _proto.add = function add(value) {\n var _this2 = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: ADD,\n object: this,\n newValue: value\n });\n\n if (!change) {\n return this;\n } // ideally, value = change.value would be done here, so that values can be\n // changed by interceptor. Same applies for other Set and Map api's.\n\n }\n\n if (!this.has(value)) {\n transaction(function () {\n _this2.data_.add(_this2.enhancer_(value, undefined));\n\n _this2.atom_.reportChanged();\n });\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n newValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change);\n }\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(value) {\n var _this3 = this;\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n oldValue: value\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has(value)) {\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change2 = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change2);\n }\n\n transaction(function () {\n _this3.atom_.reportChanged();\n\n _this3.data_[\"delete\"](value);\n });\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.has = function has(value) {\n this.atom_.reportObserved();\n return this.data_.has(this.dehanceValue_(value));\n };\n\n _proto.entries = function entries() {\n var nextIndex = 0;\n var keys = Array.from(this.keys());\n var values = Array.from(this.values());\n return makeIterable({\n next: function next() {\n var index = nextIndex;\n nextIndex += 1;\n return index < values.length ? {\n value: [keys[index], values[index]],\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.keys = function keys() {\n return this.values();\n };\n\n _proto.values = function values() {\n this.atom_.reportObserved();\n var self = this;\n var nextIndex = 0;\n var observableValues = Array.from(this.data_.values());\n return makeIterable({\n next: function next() {\n return nextIndex < observableValues.length ? {\n value: self.dehanceValue_(observableValues[nextIndex++]),\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.replace = function replace(other) {\n var _this4 = this;\n\n if (isObservableSet(other)) {\n other = new Set(other);\n }\n\n transaction(function () {\n if (Array.isArray(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (isES6Set(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (other !== null && other !== undefined) {\n die(\"Cannot initialize set from \" + other);\n }\n });\n return this;\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n // ... 'fireImmediately' could also be true?\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with sets.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableSet]\";\n };\n\n _proto[_Symbol$iterator$1] = function () {\n return this.values();\n };\n\n _createClass(ObservableSet, [{\n key: \"size\",\n get: function get() {\n this.atom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag$1,\n get: function get() {\n return \"Set\";\n }\n }]);\n\n return ObservableSet;\n}(); // eslint-disable-next-line\n\nvar isObservableSet = /*#__PURE__*/createInstanceofPredicate(\"ObservableSet\", ObservableSet);\n\nvar descriptorCache = /*#__PURE__*/Object.create(null);\nvar REMOVE = \"remove\";\nvar ObservableObjectAdministration = /*#__PURE__*/function () {\n function ObservableObjectAdministration(target_, values_, name_, // Used anytime annotation is not explicitely provided\n defaultAnnotation_) {\n if (values_ === void 0) {\n values_ = new Map();\n }\n\n if (defaultAnnotation_ === void 0) {\n defaultAnnotation_ = autoAnnotation;\n }\n\n this.target_ = void 0;\n this.values_ = void 0;\n this.name_ = void 0;\n this.defaultAnnotation_ = void 0;\n this.keysAtom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.proxy_ = void 0;\n this.isPlainObject_ = void 0;\n this.appliedAnnotations_ = void 0;\n this.pendingKeys_ = void 0;\n this.target_ = target_;\n this.values_ = values_;\n this.name_ = name_;\n this.defaultAnnotation_ = defaultAnnotation_;\n this.keysAtom_ = new Atom( true ? this.name_ + \".keys\" : undefined); // Optimization: we use this frequently\n\n this.isPlainObject_ = isPlainObject(this.target_);\n\n if ( true && !isAnnotation(this.defaultAnnotation_)) {\n die(\"defaultAnnotation must be valid annotation\");\n }\n\n if (true) {\n // Prepare structure for tracking which fields were already annotated\n this.appliedAnnotations_ = {};\n }\n }\n\n var _proto = ObservableObjectAdministration.prototype;\n\n _proto.getObservablePropValue_ = function getObservablePropValue_(key) {\n return this.values_.get(key).get();\n };\n\n _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {\n var observable = this.values_.get(key);\n\n if (observable instanceof ComputedValue) {\n observable.set(newValue);\n return true;\n } // intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: newValue\n });\n\n if (!change) {\n return null;\n }\n\n newValue = change.newValue;\n }\n\n newValue = observable.prepareNewValue_(newValue); // notify spy & observers\n\n if (newValue !== globalState.UNCHANGED) {\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n var _change = notify || notifySpy ? {\n type: UPDATE,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n }\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n return true;\n };\n\n _proto.get_ = function get_(key) {\n if (globalState.trackingDerivation && !hasProp(this.target_, key)) {\n // Key doesn't exist yet, subscribe for it in case it's added later\n this.has_(key);\n }\n\n return this.target_[key];\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {any} value\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.set_ = function set_(key, value, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // Don't use .has(key) - we care about own\n if (hasProp(this.target_, key)) {\n // Existing prop\n if (this.values_.has(key)) {\n // Observable (can be intercepted)\n return this.setObservablePropValue_(key, value);\n } else if (proxyTrap) {\n // Non-observable - proxy\n return Reflect.set(this.target_, key, value);\n } else {\n // Non-observable\n this.target_[key] = value;\n return true;\n }\n } else {\n // New prop\n return this.extend_(key, {\n value: value,\n enumerable: true,\n writable: true,\n configurable: true\n }, this.defaultAnnotation_, proxyTrap);\n }\n } // Trap for \"in\"\n ;\n\n _proto.has_ = function has_(key) {\n if (!globalState.trackingDerivation) {\n // Skip key subscription outside derivation\n return key in this.target_;\n }\n\n this.pendingKeys_ || (this.pendingKeys_ = new Map());\n var entry = this.pendingKeys_.get(key);\n\n if (!entry) {\n entry = new ObservableValue(key in this.target_, referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.pendingKeys_.set(key, entry);\n }\n\n return entry.get();\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop\r\n */\n ;\n\n _proto.make_ = function make_(key, annotation) {\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return;\n }\n\n assertAnnotable(this, annotation, key);\n\n if (!(key in this.target_)) {\n var _this$target_$storedA;\n\n // Throw on missing key, except for decorators:\n // Decorator annotations are collected from whole prototype chain.\n // When called from super() some props may not exist yet.\n // However we don't have to worry about missing prop,\n // because the decorator must have been applied to something.\n if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {\n return; // will be annotated by subclass constructor\n } else {\n die(1, annotation.annotationType_, this.name_ + \".\" + key.toString());\n }\n }\n\n var source = this.target_;\n\n while (source && source !== objectPrototype) {\n var descriptor = getDescriptor(source, key);\n\n if (descriptor) {\n var outcome = annotation.make_(this, key, descriptor, source);\n\n if (outcome === 0\n /* Cancel */\n ) {\n return;\n }\n\n if (outcome === 1\n /* Break */\n ) {\n break;\n }\n }\n\n source = Object.getPrototypeOf(source);\n }\n\n recordAnnotationApplied(this, annotation, key);\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return this.defineProperty_(key, descriptor, proxyTrap);\n }\n\n assertAnnotable(this, annotation, key);\n var outcome = annotation.extend_(this, key, descriptor, proxyTrap);\n\n if (outcome) {\n recordAnnotationApplied(this, annotation, key);\n }\n\n return outcome;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: descriptor.value\n });\n\n if (!change) {\n return null;\n }\n\n var newValue = change.newValue;\n\n if (descriptor.value !== newValue) {\n descriptor = _extends({}, descriptor, {\n value: newValue\n });\n }\n } // Define\n\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n } // Notify\n\n\n this.notifyPropertyAddition_(key, descriptor.value);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: value\n });\n\n if (!change) {\n return null;\n }\n\n value = change.newValue;\n }\n\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: true,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n var observable = new ObservableValue(value, enhancer, true ? this.name_ + \".\" + key.toString() : undefined, false);\n this.values_.set(key, observable); // Notify (value possibly changed by ObservableValue)\n\n this.notifyPropertyAddition_(key, observable.value_);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: undefined\n });\n\n if (!change) {\n return null;\n }\n }\n\n options.name || (options.name = true ? this.name_ + \".\" + key.toString() : undefined);\n options.context = this.proxy_ || this.target_;\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: false,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n this.values_.set(key, new ComputedValue(options)); // Notify\n\n this.notifyPropertyAddition_(key, undefined);\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.delete_ = function delete_(key, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // No such prop\n if (!hasProp(this.target_, key)) {\n return true;\n } // Intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: REMOVE\n }); // Cancelled\n\n if (!change) {\n return null;\n }\n } // Delete\n\n\n try {\n var _this$pendingKeys_, _this$pendingKeys_$ge;\n\n startBatch();\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n var observable = this.values_.get(key); // Value needed for spies/listeners\n\n var value = undefined; // Optimization: don't pull the value unless we will need it\n\n if (!observable && (notify || notifySpy)) {\n var _getDescriptor;\n\n value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;\n } // delete prop (do first, may fail)\n\n\n if (proxyTrap) {\n if (!Reflect.deleteProperty(this.target_, key)) {\n return false;\n }\n } else {\n delete this.target_[key];\n } // Allow re-annotating this field\n\n\n if (true) {\n delete this.appliedAnnotations_[key];\n } // Clear observable\n\n\n if (observable) {\n this.values_[\"delete\"](key); // for computed, value is undefined\n\n if (observable instanceof ObservableValue) {\n value = observable.value_;\n } // Notify: autorun(() => obj[key]), see #1796\n\n\n propagateChanged(observable);\n } // Notify \"keys/entries/values\" observers\n\n\n this.keysAtom_.reportChanged(); // Notify \"has\" observers\n // \"in\" as it may still exist in proto\n\n (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_); // Notify spies/listeners\n\n if (notify || notifySpy) {\n var _change2 = {\n type: REMOVE,\n observableKind: \"object\",\n object: this.proxy_ || this.target_,\n debugObjectName: this.name_,\n oldValue: value,\n name: key\n };\n\n if ( true && notifySpy) {\n spyReportStart(_change2);\n }\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n ;\n\n _proto.observe_ = function observe_(callback, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support the fire immediately property for observable objects.\");\n }\n\n return registerListener(this, callback);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {\n var _this$pendingKeys_2, _this$pendingKeys_2$g;\n\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n if (notify || notifySpy) {\n var change = notify || notifySpy ? {\n type: ADD,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: value\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true); // Notify \"keys/entries/values\" observers\n\n this.keysAtom_.reportChanged();\n };\n\n _proto.ownKeys_ = function ownKeys_() {\n this.keysAtom_.reportObserved();\n return ownKeys(this.target_);\n };\n\n _proto.keys_ = function keys_() {\n // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.\n // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.\n // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)\n // We choose to over-report in Object.keys(object), because:\n // - typically it's used with simple data objects\n // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected\n this.keysAtom_.reportObserved();\n return Object.keys(this.target_);\n };\n\n return ObservableObjectAdministration;\n}();\nfunction asObservableObject(target, options) {\n var _options$name;\n\n if ( true && options && isObservableObject(target)) {\n die(\"Options can't be provided for already observable objects.\");\n }\n\n if (hasProp(target, $mobx)) {\n if ( true && !(getAdministration(target) instanceof ObservableObjectAdministration)) {\n die(\"Cannot convert '\" + getDebugName(target) + \"' into observable object:\" + \"\\nThe target is already observable of different type.\" + \"\\nExtending builtins is not supported.\");\n }\n\n return target;\n }\n\n if ( true && !Object.isExtensible(target)) {\n die(\"Cannot make the designated object observable; it is not extensible\");\n }\n\n var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : true ? (isPlainObject(target) ? \"ObservableObject\" : target.constructor.name) + \"@\" + getNextId() : undefined;\n var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));\n addHiddenProp(target, $mobx, adm);\n return target;\n}\nvar isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableObjectAdministration\", ObservableObjectAdministration);\n\nfunction getCachedObservablePropDescriptor(key) {\n return descriptorCache[key] || (descriptorCache[key] = {\n get: function get() {\n return this[$mobx].getObservablePropValue_(key);\n },\n set: function set(value) {\n return this[$mobx].setObservablePropValue_(key, value);\n }\n });\n}\n\nfunction isObservableObject(thing) {\n if (isObject(thing)) {\n return isObservableObjectAdministration(thing[$mobx]);\n }\n\n return false;\n}\nfunction recordAnnotationApplied(adm, annotation, key) {\n var _adm$target_$storedAn;\n\n if (true) {\n adm.appliedAnnotations_[key] = annotation;\n } // Remove applied decorator annotation so we don't try to apply it again in subclass constructor\n\n\n (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key];\n}\n\nfunction assertAnnotable(adm, annotation, key) {\n // Valid annotation\n if ( true && !isAnnotation(annotation)) {\n die(\"Cannot annotate '\" + adm.name_ + \".\" + key.toString() + \"': Invalid annotation.\");\n }\n /*\r\n // Configurable, not sealed, not frozen\r\n // Possibly not needed, just a little better error then the one thrown by engine.\r\n // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.\r\n if (__DEV__) {\r\n const configurable = getDescriptor(adm.target_, key)?.configurable\r\n const frozen = Object.isFrozen(adm.target_)\r\n const sealed = Object.isSealed(adm.target_)\r\n if (!configurable || frozen || sealed) {\r\n const fieldName = `${adm.name_}.${key.toString()}`\r\n const requestedAnnotationType = annotation.annotationType_\r\n let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`\r\n if (frozen) {\r\n error += `\\nObject is frozen.`\r\n }\r\n if (sealed) {\r\n error += `\\nObject is sealed.`\r\n }\r\n if (!configurable) {\r\n error += `\\nproperty is not configurable.`\r\n // Mention only if caused by us to avoid confusion\r\n if (hasProp(adm.appliedAnnotations!, key)) {\r\n error += `\\nTo prevent accidental re-definition of a field by a subclass, `\r\n error += `all annotated fields of non-plain objects (classes) are not configurable.`\r\n }\r\n }\r\n die(error)\r\n }\r\n }\r\n */\n // Not annotated\n\n\n if ( true && !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {\n var fieldName = adm.name_ + \".\" + key.toString();\n var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already annotated with '\" + currentAnnotationType + \"'.\") + \"\\nRe-annotating fields is not allowed.\" + \"\\nUse 'override' annotation for methods overridden by subclass.\");\n }\n}\n\nvar ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);\n/**\r\n * This array buffer contains two lists of properties, so that all arrays\r\n * can recycle their property definitions, which significantly improves performance of creating\r\n * properties on the fly.\r\n */\n\n\nvar OBSERVABLE_ARRAY_BUFFER_SIZE = 0; // Typescript workaround to make sure ObservableArray extends Array\n\nvar StubArray = function StubArray() {};\n\nfunction inherit(ctor, proto) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(ctor.prototype, proto);\n } else if (ctor.prototype.__proto__ !== undefined) {\n ctor.prototype.__proto__ = proto;\n } else {\n ctor.prototype = proto;\n }\n}\n\ninherit(StubArray, Array.prototype); // Weex proto freeze protection was here,\n// but it is unclear why the hack is need as MobX never changed the prototype\n// anyway, so removed it in V6\n\nvar LegacyObservableArray = /*#__PURE__*/function (_StubArray, _Symbol$toStringTag, _Symbol$iterator) {\n _inheritsLoose(LegacyObservableArray, _StubArray);\n\n function LegacyObservableArray(initialValues, enhancer, name, owned) {\n var _this;\n\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n _this = _StubArray.call(this) || this;\n var adm = new ObservableArrayAdministration(name, enhancer, owned, true);\n adm.proxy_ = _assertThisInitialized(_this);\n addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm);\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true); // @ts-ignore\n\n _this.spliceWithArray(0, 0, initialValues);\n\n allowStateChangesEnd(prev);\n }\n\n {\n // Seems that Safari won't use numeric prototype setter untill any * numeric property is\n // defined on the instance. After that it works fine, even if this property is deleted.\n Object.defineProperty(_assertThisInitialized(_this), \"0\", ENTRY_0);\n }\n\n return _this;\n }\n\n var _proto = LegacyObservableArray.prototype;\n\n _proto.concat = function concat() {\n this[$mobx].atom_.reportObserved();\n\n for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {\n arrays[_key] = arguments[_key];\n }\n\n return Array.prototype.concat.apply(this.slice(), //@ts-ignore\n arrays.map(function (a) {\n return isObservableArray(a) ? a.slice() : a;\n }));\n };\n\n _proto[_Symbol$iterator] = function () {\n var self = this;\n var nextIndex = 0;\n return makeIterable({\n next: function next() {\n return nextIndex < self.length ? {\n value: self[nextIndex++],\n done: false\n } : {\n done: true,\n value: undefined\n };\n }\n });\n };\n\n _createClass(LegacyObservableArray, [{\n key: \"length\",\n get: function get() {\n return this[$mobx].getArrayLength_();\n },\n set: function set(newLength) {\n this[$mobx].setArrayLength_(newLength);\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Array\";\n }\n }]);\n\n return LegacyObservableArray;\n}(StubArray, Symbol.toStringTag, Symbol.iterator);\n\nObject.entries(arrayExtensions).forEach(function (_ref) {\n var prop = _ref[0],\n fn = _ref[1];\n\n if (prop !== \"concat\") {\n addHiddenProp(LegacyObservableArray.prototype, prop, fn);\n }\n});\n\nfunction createArrayEntryDescriptor(index) {\n return {\n enumerable: false,\n configurable: true,\n get: function get() {\n return this[$mobx].get_(index);\n },\n set: function set(value) {\n this[$mobx].set_(index, value);\n }\n };\n}\n\nfunction createArrayBufferItem(index) {\n defineProperty(LegacyObservableArray.prototype, \"\" + index, createArrayEntryDescriptor(index));\n}\n\nfunction reserveArrayBuffer(max) {\n if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {\n for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {\n createArrayBufferItem(index);\n }\n\n OBSERVABLE_ARRAY_BUFFER_SIZE = max;\n }\n}\nreserveArrayBuffer(1000);\nfunction createLegacyArray(initialValues, enhancer, name) {\n return new LegacyObservableArray(initialValues, enhancer, name);\n}\n\nfunction getAtom(thing, property) {\n if (typeof thing === \"object\" && thing !== null) {\n if (isObservableArray(thing)) {\n if (property !== undefined) {\n die(23);\n }\n\n return thing[$mobx].atom_;\n }\n\n if (isObservableSet(thing)) {\n return thing[$mobx];\n }\n\n if (isObservableMap(thing)) {\n if (property === undefined) {\n return thing.keysAtom_;\n }\n\n var observable = thing.data_.get(property) || thing.hasMap_.get(property);\n\n if (!observable) {\n die(25, property, getDebugName(thing));\n }\n\n return observable;\n }\n\n\n if (isObservableObject(thing)) {\n if (!property) {\n return die(26);\n }\n\n var _observable = thing[$mobx].values_.get(property);\n\n if (!_observable) {\n die(27, property, getDebugName(thing));\n }\n\n return _observable;\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n } else if (isFunction(thing)) {\n if (isReaction(thing[$mobx])) {\n // disposer function\n return thing[$mobx];\n }\n }\n\n die(28);\n}\nfunction getAdministration(thing, property) {\n if (!thing) {\n die(29);\n }\n\n if (property !== undefined) {\n return getAdministration(getAtom(thing, property));\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n\n if (isObservableMap(thing) || isObservableSet(thing)) {\n return thing;\n }\n\n if (thing[$mobx]) {\n return thing[$mobx];\n }\n\n die(24, thing);\n}\nfunction getDebugName(thing, property) {\n var named;\n\n if (property !== undefined) {\n named = getAtom(thing, property);\n } else if (isAction(thing)) {\n return thing.name;\n } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {\n named = getAdministration(thing);\n } else {\n // valid for arrays as well\n named = getAtom(thing);\n }\n\n return named.name_;\n}\n\nvar toString = objectPrototype.toString;\nfunction deepEqual(a, b, depth) {\n if (depth === void 0) {\n depth = -1;\n }\n\n return eq(a, b, depth);\n} // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289\n// Internal recursive comparison function for `isEqual`.\n\nfunction eq(a, b, depth, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) {\n return a !== 0 || 1 / a === 1 / b;\n } // `null` or `undefined` only equal to itself (strict comparison).\n\n\n if (a == null || b == null) {\n return false;\n } // `NaN`s are equivalent, but non-reflexive.\n\n\n if (a !== a) {\n return b !== b;\n } // Exhaust primitive checks\n\n\n var type = typeof a;\n\n if (type !== \"function\" && type !== \"object\" && typeof b != \"object\") {\n return false;\n } // Compare `[[Class]]` names.\n\n\n var className = toString.call(a);\n\n if (className !== toString.call(b)) {\n return false;\n }\n\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case \"[object RegExp]\": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n\n case \"[object String]\":\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return \"\" + a === \"\" + b;\n\n case \"[object Number]\":\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN.\n if (+a !== +a) {\n return +b !== +b;\n } // An `egal` comparison is performed for other numeric values.\n\n\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n\n case \"[object Date]\":\n case \"[object Boolean]\":\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n\n case \"[object Symbol]\":\n return typeof Symbol !== \"undefined\" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);\n\n case \"[object Map]\":\n case \"[object Set]\":\n // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.\n // Hide this extra level by increasing the depth.\n if (depth >= 0) {\n depth++;\n }\n\n break;\n } // Unwrap any wrapped objects.\n\n\n a = unwrap(a);\n b = unwrap(b);\n var areArrays = className === \"[object Array]\";\n\n if (!areArrays) {\n if (typeof a != \"object\" || typeof b != \"object\") {\n return false;\n } // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n\n\n var aCtor = a.constructor,\n bCtor = b.constructor;\n\n if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && \"constructor\" in a && \"constructor\" in b) {\n return false;\n }\n }\n\n if (depth === 0) {\n return false;\n } else if (depth < 0) {\n depth = -1;\n } // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n\n\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) {\n return bStack[length] === b;\n }\n } // Add the first object to the stack of traversed objects.\n\n\n aStack.push(a);\n bStack.push(b); // Recursively compare objects and arrays.\n\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n\n if (length !== b.length) {\n return false;\n } // Deep compare the contents, ignoring non-numeric properties.\n\n\n while (length--) {\n if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {\n return false;\n }\n }\n } else {\n // Deep compare objects.\n var keys = Object.keys(a);\n var key;\n length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality.\n\n if (Object.keys(b).length !== length) {\n return false;\n }\n\n while (length--) {\n // Deep compare each member\n key = keys[length];\n\n if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {\n return false;\n }\n }\n } // Remove the first object from the stack of traversed objects.\n\n\n aStack.pop();\n bStack.pop();\n return true;\n}\n\nfunction unwrap(a) {\n if (isObservableArray(a)) {\n return a.slice();\n }\n\n if (isES6Map(a) || isObservableMap(a)) {\n return Array.from(a.entries());\n }\n\n if (isES6Set(a) || isObservableSet(a)) {\n return Array.from(a.entries());\n }\n\n return a;\n}\n\nfunction makeIterable(iterator) {\n iterator[Symbol.iterator] = getSelf;\n return iterator;\n}\n\nfunction getSelf() {\n return this;\n}\n\nfunction isAnnotation(thing) {\n return (// Can be function\n thing instanceof Object && typeof thing.annotationType_ === \"string\" && isFunction(thing.make_) && isFunction(thing.extend_)\n );\n}\n\n/**\r\n * (c) Michel Weststrate 2015 - 2020\r\n * MIT Licensed\r\n *\r\n * Welcome to the mobx sources! To get a global overview of how MobX internally works,\r\n * this is a good place to start:\r\n * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74\r\n *\r\n * Source folders:\r\n * ===============\r\n *\r\n * - api/ Most of the public static methods exposed by the module can be found here.\r\n * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.\r\n * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.\r\n * - utils/ Utility stuff.\r\n *\r\n */\n[\"Symbol\", \"Map\", \"Set\"].forEach(function (m) {\n var g = getGlobal();\n\n if (typeof g[m] === \"undefined\") {\n die(\"MobX requires global '\" + m + \"' to be available or polyfilled\");\n }\n});\n\nif (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === \"object\") {\n // See: https://github.com/andykog/mobx-devtools/\n __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({\n spy: spy,\n extras: {\n getDebugName: getDebugName\n },\n $mobx: $mobx\n });\n}\n\n\n//# sourceMappingURL=mobx.esm.js.map\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../sgmf-scripts/node_modules/webpack/buildin/global.js */ \"./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/mobx/dist/mobx.esm.js?"); + +/***/ }), + +/***/ "./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js": +/*!***********************************!*\ + !*** (webpack)/buildin/global.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +eval("var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n\n\n//# sourceURL=webpack:///(webpack)/buildin/global.js?"); + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenCheckout.js b/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenCheckout.js new file mode 100644 index 000000000..4f1869eb4 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenCheckout.js @@ -0,0 +1,256 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenCheckout.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenCheckout.js": +/*!********************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenCheckout.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nvar store = __webpack_require__(/*! ../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar _require = __webpack_require__(/*! ./adyen_checkout/renderGenericComponent */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js\"),\n renderGenericComponent = _require.renderGenericComponent;\nvar _require2 = __webpack_require__(/*! ./adyen_checkout/checkoutConfiguration */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/checkoutConfiguration.js\"),\n setCheckoutConfiguration = _require2.setCheckoutConfiguration,\n actionHandler = _require2.actionHandler;\nvar _require3 = __webpack_require__(/*! ./adyen_checkout/helpers */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js\"),\n assignPaymentMethodValue = _require3.assignPaymentMethodValue,\n showValidation = _require3.showValidation,\n paymentFromComponent = _require3.paymentFromComponent;\nvar _require4 = __webpack_require__(/*! ./adyen_checkout/validateComponents */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/validateComponents.js\"),\n validateComponents = _require4.validateComponents;\n$('#dwfrm_billing').submit(function apiRequest(e) {\n e.preventDefault();\n var form = $(this);\n var url = form.attr('action');\n $.ajax({\n type: 'POST',\n url: url,\n data: form.serialize(),\n async: false,\n success: function success(data) {\n store.formErrorsExist = 'fieldErrors' in data;\n }\n });\n});\nsetCheckoutConfiguration();\nif (window.cardholderNameBool !== 'null') {\n store.checkoutConfiguration.paymentMethodsConfiguration.card.hasHolderName = true;\n store.checkoutConfiguration.paymentMethodsConfiguration.card.holderNameRequired = true;\n}\nif (window.googleMerchantID !== 'null' && window.Configuration.environment === 'live') {\n var id = 'merchantId';\n store.checkoutConfiguration.paymentMethodsConfiguration.paywithgoogle.configuration[id] = window.googleMerchantID;\n store.checkoutConfiguration.paymentMethodsConfiguration.googlepay.configuration[id] = window.googleMerchantID;\n}\n\n// Submit the payment\n$('button[value=\"submit-payment\"]').on('click', function () {\n if (store.paypalTerminatedEarly) {\n paymentFromComponent({\n cancelTransaction: true,\n merchantReference: document.querySelector('#merchantReference').value\n });\n store.paypalTerminatedEarly = false;\n }\n if (document.querySelector('#selectedPaymentOption').value === 'AdyenPOS') {\n document.querySelector('#terminalId').value = document.querySelector('#terminalList').value;\n }\n if (document.querySelector('#selectedPaymentOption').value === 'AdyenComponent' || document.querySelector('#selectedPaymentOption').value === 'CREDIT_CARD') {\n assignPaymentMethodValue();\n validateComponents();\n return showValidation();\n }\n return true;\n});\nmodule.exports = {\n renderGenericComponent: renderGenericComponent,\n actionHandler: actionHandler\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenCheckout.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/checkoutConfiguration.js": +/*!*******************************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/checkoutConfiguration.js ***! + \*******************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar helpers = __webpack_require__(/*! ./helpers */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js\");\nvar _require = __webpack_require__(/*! ./makePartialPayment */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/makePartialPayment.js\"),\n makePartialPayment = _require.makePartialPayment;\nvar _require2 = __webpack_require__(/*! ../commons */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js\"),\n onBrand = _require2.onBrand,\n onFieldValid = _require2.onFieldValid;\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar constants = __webpack_require__(/*! ../constants */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js\");\nvar _require3 = __webpack_require__(/*! ./renderGiftcardComponent */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGiftcardComponent.js\"),\n createElementsToShowRemainingGiftCardAmount = _require3.createElementsToShowRemainingGiftCardAmount,\n renderAddedGiftCard = _require3.renderAddedGiftCard,\n getGiftCardElements = _require3.getGiftCardElements,\n showGiftCardInfoMessage = _require3.showGiftCardInfoMessage,\n showGiftCardCancelButton = _require3.showGiftCardCancelButton,\n attachGiftCardCancelListener = _require3.attachGiftCardCancelListener;\nfunction getCardConfig() {\n return {\n enableStoreDetails: window.showStoreDetails,\n showBrandsUnderCardNumber: false,\n clickToPayConfiguration: {\n shopperEmail: window.customerEmail,\n merchantDisplayName: window.merchantAccount\n },\n onChange: function onChange(state) {\n store.isValid = state.isValid;\n var method = state.data.paymentMethod.storedPaymentMethodId ? \"storedCard\".concat(state.data.paymentMethod.storedPaymentMethodId) : store.selectedMethod;\n store.updateSelectedPayment(method, 'isValid', store.isValid);\n store.updateSelectedPayment(method, 'stateData', state.data);\n },\n onSubmit: function onSubmit() {\n helpers.assignPaymentMethodValue();\n document.querySelector('button[value=\"submit-payment\"]').disabled = false;\n document.querySelector('button[value=\"submit-payment\"]').click();\n },\n onFieldValid: onFieldValid,\n onBrand: onBrand\n };\n}\nfunction getPaypalConfig() {\n store.paypalTerminatedEarly = false;\n return {\n showPayButton: true,\n environment: window.Configuration.environment,\n onSubmit: function onSubmit(state, component) {\n helpers.assignPaymentMethodValue();\n document.querySelector('#adyenStateData').value = JSON.stringify(store.selectedPayment.stateData);\n helpers.paymentFromComponent(state.data, component);\n },\n onCancel: function onCancel(data, component) {\n store.paypalTerminatedEarly = false;\n helpers.paymentFromComponent({\n cancelTransaction: true,\n merchantReference: document.querySelector('#merchantReference').value,\n orderToken: document.querySelector('#orderToken').value\n }, component);\n },\n onError: function onError(error, component) {\n store.paypalTerminatedEarly = false;\n if (component) {\n component.setStatus('ready');\n }\n document.querySelector('#showConfirmationForm').submit();\n },\n onAdditionalDetails: function onAdditionalDetails(state) {\n store.paypalTerminatedEarly = false;\n document.querySelector('#additionalDetailsHidden').value = JSON.stringify(state.data);\n document.querySelector('#showConfirmationForm').submit();\n },\n onClick: function onClick(data, actions) {\n $('#dwfrm_billing').trigger('submit');\n if (store.formErrorsExist) {\n return actions.reject();\n }\n if (store.paypalTerminatedEarly) {\n helpers.paymentFromComponent({\n cancelTransaction: true,\n merchantReference: document.querySelector('#merchantReference').value\n });\n store.paypalTerminatedEarly = false;\n return actions.resolve();\n }\n store.paypalTerminatedEarly = true;\n return null;\n }\n };\n}\nfunction getGooglePayConfig() {\n return {\n environment: window.Configuration.environment,\n onSubmit: function onSubmit() {\n helpers.assignPaymentMethodValue();\n document.querySelector('button[value=\"submit-payment\"]').disabled = false;\n document.querySelector('button[value=\"submit-payment\"]').click();\n },\n configuration: {\n gatewayMerchantId: window.merchantAccount\n },\n showPayButton: true,\n buttonColor: 'white'\n };\n}\nfunction handlePartialPaymentSuccess() {\n var _store$addedGiftCards;\n var _getGiftCardElements = getGiftCardElements(),\n giftCardSelectContainer = _getGiftCardElements.giftCardSelectContainer,\n giftCardSelect = _getGiftCardElements.giftCardSelect,\n giftCardsList = _getGiftCardElements.giftCardsList,\n cancelMainPaymentGiftCard = _getGiftCardElements.cancelMainPaymentGiftCard,\n giftCardAddButton = _getGiftCardElements.giftCardAddButton;\n giftCardSelectContainer.classList.add('invisible');\n giftCardSelect.value = null;\n giftCardsList.innerHTML = '';\n cancelMainPaymentGiftCard.addEventListener('click', function () {\n store.componentsObj.giftcard.node.unmount('component_giftcard');\n cancelMainPaymentGiftCard.classList.add('invisible');\n giftCardAddButton.style.display = 'block';\n giftCardSelect.value = 'null';\n });\n if (store.componentsObj.giftcard) {\n store.componentsObj.giftcard.node.unmount('component_giftcard');\n }\n store.addedGiftCards.forEach(function (card) {\n renderAddedGiftCard(card);\n });\n if ((_store$addedGiftCards = store.addedGiftCards) !== null && _store$addedGiftCards !== void 0 && _store$addedGiftCards.length) {\n showGiftCardInfoMessage();\n }\n showGiftCardCancelButton(true);\n attachGiftCardCancelListener();\n createElementsToShowRemainingGiftCardAmount();\n}\nfunction makeGiftcardPaymentRequest(giftCardData, giftcardBalance, reject) {\n var brandSelect = document.getElementById('giftCardSelect');\n var selectedBrandIndex = brandSelect.selectedIndex;\n var giftcardBrand = brandSelect.options[selectedBrandIndex].text;\n var partialPaymentRequest = {\n paymentMethod: giftCardData,\n amount: giftcardBalance,\n partialPaymentsOrder: {\n pspReference: store.adyenOrderData.pspReference,\n orderData: store.adyenOrderData.orderData\n },\n giftcardBrand: giftcardBrand\n };\n var partialPaymentResponse = makePartialPayment(partialPaymentRequest);\n if (partialPaymentResponse !== null && partialPaymentResponse !== void 0 && partialPaymentResponse.error) {\n reject();\n } else {\n handlePartialPaymentSuccess();\n }\n}\nfunction getGiftCardConfig() {\n var giftcardBalance;\n return {\n showPayButton: true,\n onChange: function onChange(state) {\n store.updateSelectedPayment(constants.GIFTCARD, 'isValid', state.isValid);\n store.updateSelectedPayment(constants.GIFTCARD, 'stateData', state.data);\n },\n onBalanceCheck: function onBalanceCheck(resolve, reject, requestData) {\n $.ajax({\n type: 'POST',\n url: window.checkBalanceUrl,\n data: JSON.stringify(requestData),\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function success(data) {\n giftcardBalance = data.balance;\n document.querySelector('button[value=\"submit-payment\"]').disabled = false;\n if (data.resultCode === constants.SUCCESS) {\n var _getGiftCardElements2 = getGiftCardElements(),\n giftCardsInfoMessageContainer = _getGiftCardElements2.giftCardsInfoMessageContainer,\n giftCardSelect = _getGiftCardElements2.giftCardSelect,\n cancelMainPaymentGiftCard = _getGiftCardElements2.cancelMainPaymentGiftCard,\n giftCardAddButton = _getGiftCardElements2.giftCardAddButton,\n giftCardSelectWrapper = _getGiftCardElements2.giftCardSelectWrapper;\n if (giftCardSelectWrapper) {\n giftCardSelectWrapper.classList.add('invisible');\n }\n var initialPartialObject = _objectSpread({}, store.partialPaymentsOrderObj);\n cancelMainPaymentGiftCard.classList.remove('invisible');\n cancelMainPaymentGiftCard.addEventListener('click', function () {\n store.componentsObj.giftcard.node.unmount('component_giftcard');\n cancelMainPaymentGiftCard.classList.add('invisible');\n giftCardAddButton.style.display = 'block';\n giftCardSelect.value = 'null';\n store.partialPaymentsOrderObj.remainingAmountFormatted = initialPartialObject.remainingAmountFormatted;\n store.partialPaymentsOrderObj.totalDiscountedAmount = initialPartialObject.totalDiscountedAmount;\n });\n document.querySelector('button[value=\"submit-payment\"]').disabled = true;\n giftCardsInfoMessageContainer.innerHTML = '';\n giftCardsInfoMessageContainer.classList.remove('gift-cards-info-message-container');\n store.partialPaymentsOrderObj.remainingAmountFormatted = data.remainingAmountFormatted;\n store.partialPaymentsOrderObj.totalDiscountedAmount = data.totalAmountFormatted;\n resolve(data);\n } else if (data.resultCode === constants.NOTENOUGHBALANCE) {\n resolve(data);\n } else {\n reject();\n }\n },\n fail: function fail() {\n reject();\n }\n });\n },\n onOrderRequest: function onOrderRequest(resolve, reject, requestData) {\n // Make a POST /orders request\n // Create an order for the total transaction amount\n var giftCardData = requestData.paymentMethod;\n if (store.adyenOrderData) {\n makeGiftcardPaymentRequest(giftCardData, giftcardBalance, reject);\n } else {\n $.ajax({\n type: 'POST',\n url: window.partialPaymentsOrderUrl,\n data: JSON.stringify(requestData),\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function success(data) {\n if (data.resultCode === 'Success') {\n store.adyenOrderData = data;\n // make payments call including giftcard data and order data\n makeGiftcardPaymentRequest(giftCardData, giftcardBalance, reject);\n }\n }\n });\n }\n },\n onSubmit: function onSubmit(state, component) {\n store.selectedMethod = state.data.paymentMethod.type;\n store.brand = component === null || component === void 0 ? void 0 : component.displayName;\n document.querySelector('input[name=\"brandCode\"]').checked = false;\n document.querySelector('button[value=\"submit-payment\"]').disabled = false;\n document.querySelector('button[value=\"submit-payment\"]').click();\n }\n };\n}\nfunction handleOnChange(state) {\n store.isValid = state.isValid;\n if (!store.componentsObj[store.selectedMethod]) {\n store.componentsObj[store.selectedMethod] = {};\n }\n store.componentsObj[store.selectedMethod].isValid = store.isValid;\n store.componentsObj[store.selectedMethod].stateData = state.data;\n}\nvar actionHandler = /*#__PURE__*/function () {\n var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(action) {\n var checkout;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return AdyenCheckout(store.checkoutConfiguration);\n case 2:\n checkout = _context.sent;\n checkout.createFromAction(action).mount('#action-container');\n $('#action-modal').modal({\n backdrop: 'static',\n keyboard: false\n });\n if (action.type === constants.ACTIONTYPE.QRCODE) {\n document.getElementById('cancelQrMethodsButton').classList.remove('invisible');\n }\n case 6:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return function actionHandler(_x) {\n return _ref.apply(this, arguments);\n };\n}();\nfunction handleOnAdditionalDetails(state) {\n $.ajax({\n type: 'POST',\n url: window.paymentsDetailsURL,\n data: JSON.stringify({\n data: state.data,\n orderToken: window.orderToken\n }),\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function success(data) {\n if (!data.isFinal && _typeof(data.action) === 'object') {\n actionHandler(data.action);\n } else {\n window.location.href = data.redirectUrl;\n }\n }\n });\n}\nfunction getAmazonpayConfig() {\n return {\n showPayButton: true,\n productType: 'PayAndShip',\n checkoutMode: 'ProcessOrder',\n locale: window.Configuration.locale,\n returnUrl: window.returnURL,\n onClick: function onClick(resolve, reject) {\n $('#dwfrm_billing').trigger('submit');\n if (store.formErrorsExist) {\n reject();\n } else {\n helpers.assignPaymentMethodValue();\n resolve();\n }\n },\n onError: function onError() {}\n };\n}\nfunction getApplePayConfig() {\n return {\n showPayButton: true,\n onSubmit: function onSubmit(state, component) {\n helpers.assignPaymentMethodValue();\n helpers.paymentFromComponent(state.data, component);\n }\n };\n}\nfunction getCashAppConfig() {\n return {\n showPayButton: true,\n onSubmit: function onSubmit(state, component) {\n $('#dwfrm_billing').trigger('submit');\n helpers.assignPaymentMethodValue();\n helpers.paymentFromComponent(state.data, component);\n }\n };\n}\nfunction getKlarnaConfig() {\n var _window = window,\n klarnaWidgetEnabled = _window.klarnaWidgetEnabled;\n if (klarnaWidgetEnabled) {\n return {\n showPayButton: true,\n useKlarnaWidget: true,\n onSubmit: function onSubmit(state, component) {\n helpers.assignPaymentMethodValue();\n helpers.paymentFromComponent(state.data, component);\n },\n onAdditionalDetails: function onAdditionalDetails(state) {\n document.querySelector('#additionalDetailsHidden').value = JSON.stringify(state.data);\n document.querySelector('#showConfirmationForm').submit();\n }\n };\n }\n return null;\n}\nfunction setCheckoutConfiguration() {\n store.checkoutConfiguration.onChange = handleOnChange;\n store.checkoutConfiguration.onAdditionalDetails = handleOnAdditionalDetails;\n store.checkoutConfiguration.showPayButton = false;\n store.checkoutConfiguration.clientKey = window.adyenClientKey;\n store.checkoutConfiguration.paymentMethodsConfiguration = {\n card: getCardConfig(),\n bcmc: getCardConfig(),\n storedCard: getCardConfig(),\n boletobancario: {\n personalDetailsRequired: true,\n // turn personalDetails section on/off\n billingAddressRequired: false,\n // turn billingAddress section on/off\n showEmailAddress: false // allow shopper to specify their email address\n },\n\n paywithgoogle: getGooglePayConfig(),\n googlepay: getGooglePayConfig(),\n paypal: getPaypalConfig(),\n amazonpay: getAmazonpayConfig(),\n giftcard: getGiftCardConfig(),\n applepay: getApplePayConfig(),\n klarna: getKlarnaConfig(),\n klarna_account: getKlarnaConfig(),\n klarna_paynow: getKlarnaConfig(),\n cashapp: getCashAppConfig()\n };\n}\nmodule.exports = {\n getCardConfig: getCardConfig,\n getPaypalConfig: getPaypalConfig,\n getGooglePayConfig: getGooglePayConfig,\n getAmazonpayConfig: getAmazonpayConfig,\n setCheckoutConfiguration: setCheckoutConfiguration,\n actionHandler: actionHandler\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/checkoutConfiguration.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js": +/*!*****************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js ***! + \*****************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar constants = __webpack_require__(/*! ../constants */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js\");\nfunction assignPaymentMethodValue() {\n var adyenPaymentMethod = document.querySelector('#adyenPaymentMethodName');\n // if currently selected paymentMethod contains a brand it will be part of the label ID\n var paymentMethodlabelId = \"#lb_\".concat(store.selectedMethod);\n if (adyenPaymentMethod) {\n var _document$querySelect;\n adyenPaymentMethod.value = store.brand ? store.brand : (_document$querySelect = document.querySelector(paymentMethodlabelId)) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.innerHTML;\n }\n}\nfunction setOrderFormData(response) {\n if (response.orderNo) {\n document.querySelector('#merchantReference').value = response.orderNo;\n }\n if (response.orderToken) {\n document.querySelector('#orderToken').value = response.orderToken;\n }\n}\n\n/**\n * Makes an ajax call to the controller function PaymentFromComponent.\n * Used by certain payment methods like paypal\n */\nfunction paymentFromComponent(data) {\n var component = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var requestData = store.partialPaymentsOrderObj ? _objectSpread(_objectSpread({}, data), {}, {\n partialPaymentsOrder: store.partialPaymentsOrderObj\n }) : data;\n $.ajax({\n url: window.paymentFromComponentURL,\n type: 'post',\n data: {\n data: JSON.stringify(requestData),\n paymentMethod: document.querySelector('#adyenPaymentMethodName').value\n },\n success: function success(response) {\n var _response$fullRespons;\n setOrderFormData(response);\n if ((_response$fullRespons = response.fullResponse) !== null && _response$fullRespons !== void 0 && _response$fullRespons.action) {\n component.handleAction(response.fullResponse.action);\n } else if (response.skipSummaryPage) {\n document.querySelector('#result').value = JSON.stringify(response);\n document.querySelector('#showConfirmationForm').submit();\n } else if (response.paymentError || response.error) {\n component.handleError();\n }\n }\n });\n}\nfunction resetPaymentMethod() {\n $('#requiredBrandCode').hide();\n $('#selectedIssuer').val('');\n $('#adyenIssuerName').val('');\n $('#dateOfBirth').val('');\n $('#telephoneNumber').val('');\n $('#gender').val('');\n $('#bankAccountOwnerName').val('');\n $('#bankAccountNumber').val('');\n $('#bankLocationId').val('');\n $('.additionalFields').hide();\n}\n\n/**\n * Changes the \"display\" attribute of the selected method from hidden to visible\n */\nfunction displaySelectedMethod(type) {\n var _document$querySelect2;\n // If 'type' input field is present use this as type, otherwise default to function input param\n store.selectedMethod = document.querySelector(\"#component_\".concat(type, \" .type\")) ? document.querySelector(\"#component_\".concat(type, \" .type\")).value : type;\n resetPaymentMethod();\n var disabledSubmitButtonMethods = constants.DISABLED_SUBMIT_BUTTON_METHODS;\n if (window.klarnaWidgetEnabled) {\n disabledSubmitButtonMethods.push('klarna');\n }\n document.querySelector('button[value=\"submit-payment\"]').disabled = disabledSubmitButtonMethods.findIndex(function (pm) {\n return type.includes(pm);\n }) > -1;\n document.querySelector(\"#component_\".concat(type)).setAttribute('style', 'display:block');\n // set brand for giftcards if hidden inputfield is present\n store.brand = (_document$querySelect2 = document.querySelector(\"#component_\".concat(type, \" .brand\"))) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value;\n}\nfunction displayValidationErrors() {\n store.selectedPayment.node.showValidation();\n return false;\n}\nvar selectedMethods = {};\nfunction doCustomValidation() {\n return store.selectedMethod in selectedMethods ? selectedMethods[store.selectedMethod]() : true;\n}\nfunction showValidation() {\n return store.selectedPaymentIsValid ? doCustomValidation() : displayValidationErrors();\n}\nfunction getInstallmentValues(maxValue) {\n var values = [];\n for (var i = 1; i <= maxValue; i += 1) {\n values.push(i);\n }\n return values;\n}\nfunction createShowConfirmationForm(action) {\n if (document.querySelector('#showConfirmationForm')) {\n return;\n }\n var template = document.createElement('template');\n var form = \"
            \\n \\n \\n \\n \\n
            \");\n template.innerHTML = form;\n document.querySelector('body').appendChild(template.content);\n}\nmodule.exports = {\n setOrderFormData: setOrderFormData,\n assignPaymentMethodValue: assignPaymentMethodValue,\n paymentFromComponent: paymentFromComponent,\n resetPaymentMethod: resetPaymentMethod,\n displaySelectedMethod: displaySelectedMethod,\n showValidation: showValidation,\n createShowConfirmationForm: createShowConfirmationForm,\n getInstallmentValues: getInstallmentValues\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/localesUsingInstallments.js": +/*!**********************************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/localesUsingInstallments.js ***! + \**********************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nmodule.exports.installmentLocales = ['pt_BR', 'ja_JP', 'tr_TR', 'es_MX'];\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/localesUsingInstallments.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/makePartialPayment.js": +/*!****************************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/makePartialPayment.js ***! + \****************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nvar _excluded = [\"giftCards\"];\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar _require = __webpack_require__(/*! ./renderGenericComponent */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js\"),\n initializeCheckout = _require.initializeCheckout;\nvar helpers = __webpack_require__(/*! ./helpers */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js\");\nfunction makePartialPayment(requestData) {\n var error;\n $.ajax({\n url: window.partialPaymentUrl,\n type: 'POST',\n data: JSON.stringify(requestData),\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function success(response) {\n if (response.error) {\n error = {\n error: true\n };\n } else {\n var giftCards = response.giftCards,\n rest = _objectWithoutProperties(response, _excluded);\n store.checkout.options.amount = rest.remainingAmount;\n store.adyenOrderData = rest.partialPaymentsOrder;\n store.partialPaymentsOrderObj = rest;\n sessionStorage.setItem('partialPaymentsObj', JSON.stringify(rest));\n store.addedGiftCards = giftCards;\n helpers.setOrderFormData(response);\n initializeCheckout();\n }\n }\n }).fail(function () {});\n return error;\n}\nmodule.exports = {\n makePartialPayment: makePartialPayment\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/makePartialPayment.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js": +/*!********************************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js ***! + \********************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nvar _document$getElementB;\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _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.\"); }\nfunction _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); }\nfunction _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; }\nfunction _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i[\"return\"] && (_r = _i[\"return\"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/* eslint-disable no-unsafe-optional-chaining */\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar _require = __webpack_require__(/*! ./renderPaymentMethod */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderPaymentMethod.js\"),\n renderPaymentMethod = _require.renderPaymentMethod;\nvar helpers = __webpack_require__(/*! ./helpers */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js\");\nvar _require2 = __webpack_require__(/*! ./localesUsingInstallments */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/localesUsingInstallments.js\"),\n installmentLocales = _require2.installmentLocales;\nvar _require3 = __webpack_require__(/*! ../commons */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js\"),\n createSession = _require3.createSession,\n fetchGiftCards = _require3.fetchGiftCards;\nvar constants = __webpack_require__(/*! ../constants */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js\");\nvar _require4 = __webpack_require__(/*! ./renderGiftcardComponent */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGiftcardComponent.js\"),\n createElementsToShowRemainingGiftCardAmount = _require4.createElementsToShowRemainingGiftCardAmount,\n removeGiftCards = _require4.removeGiftCards,\n renderAddedGiftCard = _require4.renderAddedGiftCard,\n showGiftCardWarningMessage = _require4.showGiftCardWarningMessage,\n attachGiftCardAddButtonListener = _require4.attachGiftCardAddButtonListener,\n showGiftCardInfoMessage = _require4.showGiftCardInfoMessage,\n giftCardBrands = _require4.giftCardBrands,\n clearGiftCardsContainer = _require4.clearGiftCardsContainer,\n attachGiftCardCancelListener = _require4.attachGiftCardCancelListener,\n showGiftCardCancelButton = _require4.showGiftCardCancelButton;\nvar INIT_CHECKOUT_EVENT = 'INIT_CHECKOUT_EVENT';\nfunction addPosTerminals(terminals) {\n var ddTerminals = document.createElement('select');\n ddTerminals.id = 'terminalList';\n Object.keys(terminals).forEach(function (t) {\n var option = document.createElement('option');\n option.value = terminals[t];\n option.text = terminals[t];\n ddTerminals.appendChild(option);\n });\n document.querySelector('#adyenPosTerminals').append(ddTerminals);\n}\nfunction setCheckoutConfiguration(checkoutOptions) {\n var setField = function setField(key, val) {\n return val && _defineProperty({}, key, val);\n };\n store.checkoutConfiguration = _objectSpread(_objectSpread(_objectSpread({}, store.checkoutConfiguration), setField('amount', checkoutOptions.amount)), setField('countryCode', checkoutOptions.countryCode));\n}\nfunction resolveUnmount(key, val) {\n try {\n return Promise.resolve(val.node.unmount(\"component_\".concat(key)));\n } catch (e) {\n // try/catch block for val.unmount\n return Promise.resolve(false);\n }\n}\n\n/**\n * To avoid re-rendering components twice, unmounts existing components from payment methods list\n */\nfunction unmountComponents() {\n var promises = Object.entries(store.componentsObj).map(function (_ref2) {\n var _ref3 = _slicedToArray(_ref2, 2),\n key = _ref3[0],\n val = _ref3[1];\n delete store.componentsObj[key];\n return resolveUnmount(key, val);\n });\n return Promise.all(promises);\n}\nfunction isCartModified(amount, orderAmount) {\n return amount.currency !== orderAmount.currency || amount.value !== orderAmount.value;\n}\nfunction renderGiftCardLogo(imagePath) {\n var headingImg = document.querySelector('#headingImg');\n if (headingImg) {\n headingImg.src = \"\".concat(imagePath, \"genericgiftcard.png\");\n }\n}\nfunction applyGiftCards() {\n var now = new Date().toISOString();\n var amount = store.checkoutConfiguration.amount;\n var orderAmount = store.partialPaymentsOrderObj.orderAmount;\n var isPartialPaymentExpired = store.addedGiftCards.some(function (cart) {\n return now > cart.expiresAt;\n });\n var cartModified = isCartModified(amount, orderAmount);\n if (isPartialPaymentExpired) {\n removeGiftCards();\n } else if (cartModified) {\n removeGiftCards();\n showGiftCardWarningMessage();\n } else {\n var _store$addedGiftCards;\n clearGiftCardsContainer();\n store.addedGiftCards.forEach(function (card) {\n renderAddedGiftCard(card);\n });\n if ((_store$addedGiftCards = store.addedGiftCards) !== null && _store$addedGiftCards !== void 0 && _store$addedGiftCards.length) {\n showGiftCardInfoMessage();\n }\n store.checkout.options.amount = store.addedGiftCards[store.addedGiftCards.length - 1].remainingAmount;\n showGiftCardCancelButton(true);\n attachGiftCardCancelListener();\n createElementsToShowRemainingGiftCardAmount();\n }\n}\nfunction renderStoredPaymentMethod(imagePath) {\n return function (pm) {\n if (pm.supportedShopperInteractions.includes('Ecommerce')) {\n renderPaymentMethod(pm, true, imagePath);\n }\n };\n}\nfunction renderStoredPaymentMethods(data, imagePath) {\n if (data.storedPaymentMethods) {\n var storedPaymentMethods = data.storedPaymentMethods;\n storedPaymentMethods.forEach(renderStoredPaymentMethod(imagePath));\n }\n}\nfunction renderPaymentMethods(paymentMethods, imagePath, adyenDescriptions) {\n var promises = [];\n for (var i = 0; i < paymentMethods.length; i += 1) {\n var pm = paymentMethods[i];\n promises.push(renderPaymentMethod(pm, false, imagePath, adyenDescriptions[pm.type]));\n }\n return Promise.all(promises);\n}\nfunction renderPosTerminals(adyenConnectedTerminals) {\n var _adyenConnectedTermin;\n var removeChilds = function removeChilds() {\n var posTerminals = document.querySelector('#adyenPosTerminals');\n while (posTerminals.firstChild) {\n posTerminals.removeChild(posTerminals.firstChild);\n }\n };\n if (adyenConnectedTerminals !== null && adyenConnectedTerminals !== void 0 && (_adyenConnectedTermin = adyenConnectedTerminals.uniqueTerminalIds) !== null && _adyenConnectedTermin !== void 0 && _adyenConnectedTermin.length) {\n removeChilds();\n addPosTerminals(adyenConnectedTerminals.uniqueTerminalIds);\n }\n}\nfunction setAmazonPayConfig(adyenPaymentMethods) {\n var amazonpay = adyenPaymentMethods.paymentMethods.find(function (paymentMethod) {\n return paymentMethod.type === 'amazonpay';\n });\n if (amazonpay) {\n var _document$querySelect, _document$querySelect2, _document$querySelect3, _document$querySelect4, _document$querySelect5, _document$querySelect6, _document$querySelect7, _document$querySelect8;\n store.checkoutConfiguration.paymentMethodsConfiguration.amazonpay.configuration = amazonpay.configuration;\n store.checkoutConfiguration.paymentMethodsConfiguration.amazonpay.addressDetails = {\n name: \"\".concat((_document$querySelect = document.querySelector('#shippingFirstNamedefault')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.value, \" \").concat((_document$querySelect2 = document.querySelector('#shippingLastNamedefault')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value),\n addressLine1: (_document$querySelect3 = document.querySelector('#shippingAddressOnedefault')) === null || _document$querySelect3 === void 0 ? void 0 : _document$querySelect3.value,\n city: (_document$querySelect4 = document.querySelector('#shippingAddressCitydefault')) === null || _document$querySelect4 === void 0 ? void 0 : _document$querySelect4.value,\n stateOrRegion: (_document$querySelect5 = document.querySelector('#shippingAddressCitydefault')) === null || _document$querySelect5 === void 0 ? void 0 : _document$querySelect5.value,\n postalCode: (_document$querySelect6 = document.querySelector('#shippingZipCodedefault')) === null || _document$querySelect6 === void 0 ? void 0 : _document$querySelect6.value,\n countryCode: (_document$querySelect7 = document.querySelector('#shippingCountrydefault')) === null || _document$querySelect7 === void 0 ? void 0 : _document$querySelect7.value,\n phoneNumber: (_document$querySelect8 = document.querySelector('#shippingPhoneNumberdefault')) === null || _document$querySelect8 === void 0 ? void 0 : _document$querySelect8.value\n };\n }\n}\nfunction setInstallments(amount) {\n try {\n var _window$installments;\n if (installmentLocales.indexOf(window.Configuration.locale) < 0) {\n return;\n }\n var _window$installments$ = (_window$installments = window.installments) === null || _window$installments === void 0 ? void 0 : _window$installments.replace(/\\[|]/g, '').split(','),\n _window$installments$2 = _slicedToArray(_window$installments$, 2),\n minAmount = _window$installments$2[0],\n numOfInstallments = _window$installments$2[1];\n if (minAmount <= amount.value) {\n store.checkoutConfiguration.paymentMethodsConfiguration.card.installmentOptions = {\n card: {}\n }; // eslint-disable-next-line max-len\n store.checkoutConfiguration.paymentMethodsConfiguration.card.installmentOptions.card.values = helpers.getInstallmentValues(numOfInstallments);\n store.checkoutConfiguration.paymentMethodsConfiguration.card.showInstallmentAmounts = true;\n }\n } catch (e) {} // eslint-disable-line no-empty\n}\n\nfunction setGiftCardContainerVisibility() {\n var availableGiftCards = giftCardBrands();\n if (availableGiftCards.length === 0) {\n var giftCardContainer = document.querySelector('.gift-card-selection');\n giftCardContainer.style.display = 'none';\n var giftCardSeparator = document.querySelector('.gift-card-separator');\n giftCardSeparator.style.display = 'none';\n }\n}\nfunction initializeCheckout() {\n return _initializeCheckout.apply(this, arguments);\n}\nfunction _initializeCheckout() {\n _initializeCheckout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {\n var session, giftCardsData, totalDiscountedAmount, giftCards, lastGiftCard, paymentMethodsWithoutGiftCards, firstPaymentMethod;\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return createSession();\n case 2:\n session = _context2.sent;\n _context2.next = 5;\n return fetchGiftCards();\n case 5:\n giftCardsData = _context2.sent;\n store.checkoutConfiguration.session = {\n id: session.id,\n sessionData: session.sessionData,\n imagePath: session.imagePath,\n adyenDescriptions: session.adyenDescriptions\n };\n _context2.next = 9;\n return AdyenCheckout(store.checkoutConfiguration);\n case 9:\n store.checkout = _context2.sent;\n setGiftCardContainerVisibility();\n totalDiscountedAmount = giftCardsData.totalDiscountedAmount, giftCards = giftCardsData.giftCards;\n if (giftCards !== null && giftCards !== void 0 && giftCards.length) {\n store.addedGiftCards = giftCards;\n lastGiftCard = store.addedGiftCards[store.addedGiftCards.length - 1];\n store.partialPaymentsOrderObj = _objectSpread(_objectSpread({}, lastGiftCard), {}, {\n totalDiscountedAmount: totalDiscountedAmount\n });\n }\n setCheckoutConfiguration(store.checkout.options);\n setInstallments(store.checkout.options.amount);\n setAmazonPayConfig(store.checkout.paymentMethodsResponse);\n document.querySelector('#paymentMethodsList').innerHTML = '';\n paymentMethodsWithoutGiftCards = store.checkout.paymentMethodsResponse.paymentMethods.filter(function (pm) {\n return pm.type !== constants.GIFTCARD;\n });\n renderStoredPaymentMethods(paymentMethodsWithoutGiftCards, session.imagePath);\n _context2.next = 21;\n return renderPaymentMethods(paymentMethodsWithoutGiftCards, session.imagePath, session.adyenDescriptions);\n case 21:\n renderPosTerminals(session.adyenConnectedTerminals);\n renderGiftCardLogo(session.imagePath);\n firstPaymentMethod = document.querySelector('input[type=radio][name=brandCode]');\n if (firstPaymentMethod) {\n firstPaymentMethod.checked = true;\n helpers.displaySelectedMethod(firstPaymentMethod.value);\n }\n helpers.createShowConfirmationForm(window.ShowConfirmationPaymentFromComponent);\n case 26:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n return _initializeCheckout.apply(this, arguments);\n}\n(_document$getElementB = document.getElementById('email')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.addEventListener('change', function (e) {\n var emailPattern = /^[\\w.%+-]+@[\\w.-]+\\.[\\w]{2,6}$/;\n if (emailPattern.test(e.target.value)) {\n var paymentMethodsConfiguration = store.checkoutConfiguration.paymentMethodsConfiguration;\n paymentMethodsConfiguration.card.clickToPayConfiguration.shopperEmail = e.target.value;\n var event = new Event(INIT_CHECKOUT_EVENT);\n document.dispatchEvent(event);\n }\n});\n\n// used by renderGiftCardComponent.js\ndocument.addEventListener(INIT_CHECKOUT_EVENT, function () {\n var handleCheckoutEvent = /*#__PURE__*/function () {\n var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n if (!(Object.keys(store.componentsObj).length !== 0)) {\n _context.next = 3;\n break;\n }\n _context.next = 3;\n return unmountComponents();\n case 3:\n _context.next = 5;\n return initializeCheckout();\n case 5:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return function handleCheckoutEvent() {\n return _ref4.apply(this, arguments);\n };\n }();\n handleCheckoutEvent();\n});\n\n/**\n * Calls createSession and then renders the retrieved payment methods (including card component)\n */\nfunction renderGenericComponent() {\n return _renderGenericComponent.apply(this, arguments);\n}\nfunction _renderGenericComponent() {\n _renderGenericComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {\n var _store$addedGiftCards2;\n return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n while (1) switch (_context3.prev = _context3.next) {\n case 0:\n if (!(Object.keys(store.componentsObj).length !== 0)) {\n _context3.next = 3;\n break;\n }\n _context3.next = 3;\n return unmountComponents();\n case 3:\n _context3.next = 5;\n return initializeCheckout();\n case 5:\n if ((_store$addedGiftCards2 = store.addedGiftCards) !== null && _store$addedGiftCards2 !== void 0 && _store$addedGiftCards2.length) {\n applyGiftCards();\n }\n attachGiftCardAddButtonListener();\n case 7:\n case \"end\":\n return _context3.stop();\n }\n }, _callee3);\n }));\n return _renderGenericComponent.apply(this, arguments);\n}\nmodule.exports = {\n renderGenericComponent: renderGenericComponent,\n initializeCheckout: initializeCheckout,\n INIT_CHECKOUT_EVENT: INIT_CHECKOUT_EVENT\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGiftcardComponent.js": +/*!*********************************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGiftcardComponent.js ***! + \*********************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar constants = __webpack_require__(/*! ../constants */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js\");\nvar _require = __webpack_require__(/*! ./renderGenericComponent */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js\"),\n INIT_CHECKOUT_EVENT = _require.INIT_CHECKOUT_EVENT;\nfunction getGiftCardElements() {\n var giftCardSelect = document.querySelector('#giftCardSelect');\n var giftCardUl = document.querySelector('#giftCardUl');\n var giftCardContainer = document.querySelector('#giftCardContainer');\n var giftCardAddButton = document.querySelector('#giftCardAddButton');\n var giftCardCancelContainer = document.querySelector('#giftCardsCancelContainer');\n var giftCardCancelButton = document.querySelector('#giftCardCancelButton');\n var giftCardSelectContainer = document.querySelector('#giftCardSelectContainer');\n var giftCardSelectWrapper = document.querySelector('#giftCardSelectWrapper');\n var giftCardsList = document.querySelector('#giftCardsList');\n var giftCardsInfoMessageContainer = document.querySelector('#giftCardsInfoMessage');\n var cancelMainPaymentGiftCard = document.querySelector('#cancelGiftCardButton');\n var giftCardInformation = document.querySelector('#giftCardInformation');\n return {\n giftCardSelect: giftCardSelect,\n giftCardUl: giftCardUl,\n giftCardContainer: giftCardContainer,\n giftCardAddButton: giftCardAddButton,\n giftCardSelectContainer: giftCardSelectContainer,\n giftCardsList: giftCardsList,\n giftCardsInfoMessageContainer: giftCardsInfoMessageContainer,\n giftCardSelectWrapper: giftCardSelectWrapper,\n giftCardCancelContainer: giftCardCancelContainer,\n giftCardCancelButton: giftCardCancelButton,\n cancelMainPaymentGiftCard: cancelMainPaymentGiftCard,\n giftCardInformation: giftCardInformation\n };\n}\nfunction showGiftCardCancelButton(show) {\n var _getGiftCardElements = getGiftCardElements(),\n giftCardCancelContainer = _getGiftCardElements.giftCardCancelContainer;\n if (show) {\n giftCardCancelContainer.classList.remove('invisible');\n } else {\n giftCardCancelContainer.classList.add('invisible');\n }\n}\nfunction removeGiftCards() {\n var _store$addedGiftCards;\n (_store$addedGiftCards = store.addedGiftCards) === null || _store$addedGiftCards === void 0 ? void 0 : _store$addedGiftCards.forEach(function (card) {\n $.ajax({\n type: 'POST',\n url: window.cancelPartialPaymentOrderUrl,\n data: JSON.stringify(card),\n contentType: 'application/json; charset=utf-8',\n async: false,\n success: function success(res) {\n var adyenPartialPaymentsOrder = document.querySelector('#adyenPartialPaymentsOrder');\n var _getGiftCardElements2 = getGiftCardElements(),\n giftCardsList = _getGiftCardElements2.giftCardsList,\n giftCardAddButton = _getGiftCardElements2.giftCardAddButton,\n giftCardSelect = _getGiftCardElements2.giftCardSelect,\n giftCardUl = _getGiftCardElements2.giftCardUl,\n giftCardsInfoMessageContainer = _getGiftCardElements2.giftCardsInfoMessageContainer,\n giftCardSelectContainer = _getGiftCardElements2.giftCardSelectContainer,\n cancelMainPaymentGiftCard = _getGiftCardElements2.cancelMainPaymentGiftCard,\n giftCardInformation = _getGiftCardElements2.giftCardInformation;\n adyenPartialPaymentsOrder.value = null;\n giftCardsList.innerHTML = '';\n giftCardAddButton.style.display = 'block';\n giftCardSelect.value = null;\n giftCardSelectContainer.classList.add('invisible');\n giftCardSelect.classList.remove('invisible');\n giftCardUl.innerHTML = '';\n cancelMainPaymentGiftCard.classList.add('invisible');\n showGiftCardCancelButton(false);\n giftCardInformation === null || giftCardInformation === void 0 ? void 0 : giftCardInformation.remove();\n store.checkout.options.amount = res.amount;\n store.partialPaymentsOrderObj = null;\n store.addedGiftCards = null;\n store.adyenOrderData = null;\n giftCardsInfoMessageContainer.innerHTML = '';\n giftCardsInfoMessageContainer.classList.remove('gift-cards-info-message-container');\n document.querySelector('button[value=\"submit-payment\"]').disabled = false;\n if (res.resultCode === constants.RECEIVED) {\n var _document$querySelect, _store$componentsObj, _store$componentsObj$;\n (_document$querySelect = document.querySelector('#cancelGiftCardContainer')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.parentNode.remove();\n (_store$componentsObj = store.componentsObj) === null || _store$componentsObj === void 0 ? void 0 : (_store$componentsObj$ = _store$componentsObj.giftcard) === null || _store$componentsObj$ === void 0 ? void 0 : _store$componentsObj$.node.unmount('component_giftcard');\n }\n var event = new Event(INIT_CHECKOUT_EVENT);\n document.dispatchEvent(event);\n }\n });\n });\n}\nfunction giftCardBrands() {\n var paymentMethodsResponse = store.checkout.paymentMethodsResponse;\n return paymentMethodsResponse.paymentMethods.filter(function (pm) {\n return pm.type === constants.GIFTCARD;\n });\n}\nfunction renderGiftCardSelectForm() {\n var _getGiftCardElements3 = getGiftCardElements(),\n giftCardUl = _getGiftCardElements3.giftCardUl,\n giftCardSelect = _getGiftCardElements3.giftCardSelect;\n if (giftCardUl !== null && giftCardUl !== void 0 && giftCardUl.innerHTML) {\n giftCardSelect.classList.remove('invisible');\n return;\n }\n var imagePath = store.checkoutConfiguration.session.imagePath;\n giftCardBrands().forEach(function (giftCard) {\n var newListItem = document.createElement('li');\n newListItem.setAttribute('data-brand', giftCard.brand);\n newListItem.setAttribute('data-name', giftCard.name);\n newListItem.setAttribute('data-type', giftCard.type);\n var span = document.createElement('span');\n span.textContent = giftCard.name;\n var img = document.createElement('img');\n img.src = \"\".concat(imagePath).concat(giftCard.brand, \".png\");\n img.width = 40;\n img.height = 26;\n newListItem.appendChild(span);\n newListItem.appendChild(img);\n giftCardUl.appendChild(newListItem);\n });\n}\nfunction attachGiftCardFormListeners() {\n if (store.giftCardComponentListenersAdded) {\n return;\n }\n var _getGiftCardElements4 = getGiftCardElements(),\n giftCardUl = _getGiftCardElements4.giftCardUl,\n giftCardSelect = _getGiftCardElements4.giftCardSelect,\n giftCardContainer = _getGiftCardElements4.giftCardContainer,\n giftCardSelectWrapper = _getGiftCardElements4.giftCardSelectWrapper;\n if (giftCardUl) {\n giftCardUl.addEventListener('click', function (event) {\n var _store$componentsObj2;\n giftCardUl.classList.toggle('invisible');\n var selectedGiftCard = {\n name: event.target.dataset.name,\n brand: event.target.dataset.brand,\n type: event.target.dataset.type\n };\n if ((_store$componentsObj2 = store.componentsObj) !== null && _store$componentsObj2 !== void 0 && _store$componentsObj2.giftcard) {\n store.componentsObj.giftcard.node.unmount('component_giftcard');\n }\n if (!store.partialPaymentsOrderObj) {\n store.partialPaymentsOrderObj = {};\n }\n var newOption = document.createElement('option');\n newOption.textContent = selectedGiftCard.name;\n newOption.value = selectedGiftCard.brand;\n newOption.style.visibility = 'hidden';\n giftCardSelect.appendChild(newOption);\n giftCardSelect.value = selectedGiftCard.brand;\n giftCardContainer.innerHTML = '';\n var giftCardNode = store.checkout.create(constants.GIFTCARD, _objectSpread(_objectSpread({}, store.checkoutConfiguration.giftcard), {}, {\n brand: selectedGiftCard.brand,\n name: selectedGiftCard.name\n })).mount(giftCardContainer);\n store.componentsObj.giftcard = {\n node: giftCardNode\n };\n });\n }\n if (giftCardSelect) {\n giftCardSelectWrapper.addEventListener('mousedown', function () {\n giftCardUl.classList.toggle('invisible');\n });\n }\n store.giftCardComponentListenersAdded = true;\n}\nfunction showGiftCardWarningMessage() {\n var alertContainer = document.createElement('div');\n alertContainer.setAttribute('id', 'giftCardWarningMessage');\n alertContainer.classList.add('alert', 'alert-warning', 'error-message', 'gift-card-warning-msg');\n alertContainer.setAttribute('role', 'alert');\n var alertContainerP = document.createElement('p');\n alertContainerP.classList.add('error-message-text');\n alertContainerP.textContent = window.giftCardWarningMessage;\n alertContainer.appendChild(alertContainerP);\n var orderTotalSummaryEl = document.querySelector('.card-body.order-total-summary');\n orderTotalSummaryEl === null || orderTotalSummaryEl === void 0 ? void 0 : orderTotalSummaryEl.appendChild(alertContainer);\n}\nfunction attachGiftCardAddButtonListener() {\n var _getGiftCardElements5 = getGiftCardElements(),\n giftCardAddButton = _getGiftCardElements5.giftCardAddButton,\n giftCardSelectContainer = _getGiftCardElements5.giftCardSelectContainer,\n giftCardSelectWrapper = _getGiftCardElements5.giftCardSelectWrapper,\n giftCardSelect = _getGiftCardElements5.giftCardSelect;\n if (giftCardAddButton) {\n giftCardAddButton.addEventListener('click', function () {\n renderGiftCardSelectForm();\n attachGiftCardFormListeners();\n var giftCardWarningMessageEl = document.querySelector('#giftCardWarningMessage');\n if (giftCardWarningMessageEl) {\n giftCardWarningMessageEl.style.display = 'none';\n }\n giftCardSelect.value = 'null';\n giftCardAddButton.style.display = 'none';\n giftCardSelectContainer.classList.remove('invisible');\n giftCardSelectWrapper.classList.remove('invisible');\n });\n }\n}\nfunction attachGiftCardCancelListener() {\n var _getGiftCardElements6 = getGiftCardElements(),\n giftCardCancelButton = _getGiftCardElements6.giftCardCancelButton;\n giftCardCancelButton === null || giftCardCancelButton === void 0 ? void 0 : giftCardCancelButton.addEventListener('click', function () {\n removeGiftCards();\n });\n}\nfunction removeGiftCardFormListeners() {\n var _getGiftCardElements7 = getGiftCardElements(),\n giftCardUl = _getGiftCardElements7.giftCardUl,\n giftCardSelect = _getGiftCardElements7.giftCardSelect;\n giftCardUl.replaceWith(giftCardUl.cloneNode(true));\n giftCardSelect.replaceWith(giftCardSelect.cloneNode(true));\n store.giftCardComponentListenersAdded = false;\n}\nfunction clearGiftCardsContainer() {\n var _getGiftCardElements8 = getGiftCardElements(),\n giftCardsList = _getGiftCardElements8.giftCardsList;\n giftCardsList.innerHTML = '';\n}\nfunction renderAddedGiftCard(card) {\n var giftCardData = card.giftCard;\n var imagePath = store.checkoutConfiguration.session.imagePath;\n var _getGiftCardElements9 = getGiftCardElements(),\n giftCardsList = _getGiftCardElements9.giftCardsList,\n giftCardAddButton = _getGiftCardElements9.giftCardAddButton;\n var giftCardDiv = document.createElement('div');\n giftCardDiv.classList.add('gift-card');\n var brandContainer = document.createElement('div');\n brandContainer.classList.add('brand-container');\n var giftCardImg = document.createElement('img');\n var giftCardImgSrc = \"\".concat(imagePath).concat(giftCardData.brand, \".png\");\n giftCardImg.setAttribute('src', giftCardImgSrc);\n giftCardImg.classList.add('gift-card-logo');\n var giftCardNameP = document.createElement('p');\n giftCardNameP.textContent = giftCardData.name;\n brandContainer.appendChild(giftCardImg);\n brandContainer.appendChild(giftCardNameP);\n var giftCardAction = document.createElement('div');\n giftCardAction.classList.add('gift-card-action');\n var brandAndRemoveActionWrapper = document.createElement('div');\n brandAndRemoveActionWrapper.classList.add('wrapper');\n brandAndRemoveActionWrapper.appendChild(brandContainer);\n brandAndRemoveActionWrapper.appendChild(giftCardAction);\n var giftCardAmountDiv = document.createElement('div');\n giftCardAmountDiv.classList.add('wrapper');\n var amountLabel = document.createElement('p');\n amountLabel.textContent = window.deductedBalanceGiftCardResource;\n var amountValue = document.createElement('strong');\n amountValue.textContent = card.discountedAmount ? \"-\".concat(card.discountedAmount) : '';\n giftCardAmountDiv.appendChild(amountLabel);\n giftCardAmountDiv.appendChild(amountValue);\n giftCardDiv.appendChild(brandAndRemoveActionWrapper);\n giftCardDiv.appendChild(giftCardAmountDiv);\n giftCardsList.appendChild(giftCardDiv);\n giftCardAddButton.style.display = 'block';\n removeGiftCardFormListeners();\n}\nfunction createElementsToShowRemainingGiftCardAmount() {\n var renderedRemainingAmountEndSpan = document.getElementById('remainingAmountEndSpan');\n var renderedDiscountedAmountEndSpan = document.getElementById('discountedAmountEndSpan');\n if (renderedRemainingAmountEndSpan && renderedDiscountedAmountEndSpan) {\n renderedRemainingAmountEndSpan.innerText = store.partialPaymentsOrderObj.remainingAmountFormatted;\n renderedDiscountedAmountEndSpan.innerText = store.partialPaymentsOrderObj.totalDiscountedAmount;\n return;\n }\n var mainContainer = document.createElement('div');\n var remainingAmountContainer = document.createElement('div');\n var remainingAmountStart = document.createElement('div');\n var remainingAmountEnd = document.createElement('div');\n var discountedAmountContainer = document.createElement('div');\n var discountedAmountStart = document.createElement('div');\n var discountedAmountEnd = document.createElement('div');\n var remainingAmountStartP = document.createElement('p');\n var remainingAmountEndP = document.createElement('p');\n var discountedAmountStartP = document.createElement('p');\n var discountedAmountEndP = document.createElement('p');\n var remainingAmountStartSpan = document.createElement('span');\n var discountedAmountStartSpan = document.createElement('span');\n var remainingAmountEndSpan = document.createElement('span');\n remainingAmountEndSpan.id = 'remainingAmountEndSpan';\n var discountedAmountEndSpan = document.createElement('span');\n discountedAmountEndSpan.id = 'discountedAmountEndSpan';\n remainingAmountContainer.classList.add('row', 'grand-total', 'leading-lines');\n remainingAmountStart.classList.add('col-6', 'start-lines');\n remainingAmountEnd.classList.add('col-6', 'end-lines');\n remainingAmountStartP.classList.add('order-receipt-label');\n discountedAmountContainer.classList.add('row', 'grand-total', 'leading-lines');\n discountedAmountStart.classList.add('col-6', 'start-lines');\n discountedAmountEnd.classList.add('col-6', 'end-lines');\n discountedAmountStartP.classList.add('order-receipt-label');\n remainingAmountEndP.classList.add('text-right');\n discountedAmountEndP.classList.add('text-right');\n discountedAmountContainer.id = 'discountedAmountContainer';\n remainingAmountContainer.id = 'remainingAmountContainer';\n remainingAmountStartSpan.innerText = window.remainingAmountGiftCardResource;\n discountedAmountStartSpan.innerText = window.discountedAmountGiftCardResource;\n remainingAmountEndSpan.innerText = store.partialPaymentsOrderObj.remainingAmountFormatted;\n discountedAmountEndSpan.innerText = store.partialPaymentsOrderObj.totalDiscountedAmount;\n remainingAmountContainer.appendChild(remainingAmountStart);\n remainingAmountContainer.appendChild(remainingAmountEnd);\n remainingAmountStart.appendChild(remainingAmountStartP);\n discountedAmountContainer.appendChild(discountedAmountStart);\n discountedAmountContainer.appendChild(discountedAmountEnd);\n discountedAmountStart.appendChild(discountedAmountStartP);\n remainingAmountEnd.appendChild(remainingAmountEndP);\n remainingAmountStartP.appendChild(remainingAmountStartSpan);\n discountedAmountEnd.appendChild(discountedAmountEndP);\n discountedAmountStartP.appendChild(discountedAmountStartSpan);\n remainingAmountEndP.appendChild(remainingAmountEndSpan);\n discountedAmountEndP.appendChild(discountedAmountEndSpan);\n var pricingContainer = document.querySelector('.card-body.order-total-summary');\n mainContainer.id = 'giftCardInformation';\n mainContainer.appendChild(discountedAmountContainer);\n mainContainer.appendChild(remainingAmountContainer);\n pricingContainer.appendChild(mainContainer);\n}\nfunction showGiftCardInfoMessage() {\n var messageText = store.partialPaymentsOrderObj.message;\n var _getGiftCardElements10 = getGiftCardElements(),\n giftCardsInfoMessageContainer = _getGiftCardElements10.giftCardsInfoMessageContainer;\n giftCardsInfoMessageContainer.innerHTML = '';\n giftCardsInfoMessageContainer.classList.remove('gift-cards-info-message-container');\n if (!messageText) return;\n var giftCardsInfoMessage = document.createElement('div');\n giftCardsInfoMessage.classList.add('adyen-checkout__alert-message', 'adyen-checkout__alert-message--warning');\n giftCardsInfoMessage.setAttribute('role', 'alert');\n var infoMessage = document.createElement('span');\n infoMessage.textContent = messageText;\n giftCardsInfoMessage.appendChild(infoMessage);\n giftCardsInfoMessageContainer.appendChild(giftCardsInfoMessage);\n giftCardsInfoMessageContainer.classList.add('gift-cards-info-message-container');\n}\nmodule.exports = {\n removeGiftCards: removeGiftCards,\n renderAddedGiftCard: renderAddedGiftCard,\n attachGiftCardAddButtonListener: attachGiftCardAddButtonListener,\n getGiftCardElements: getGiftCardElements,\n showGiftCardWarningMessage: showGiftCardWarningMessage,\n createElementsToShowRemainingGiftCardAmount: createElementsToShowRemainingGiftCardAmount,\n renderGiftCardSelectForm: renderGiftCardSelectForm,\n showGiftCardInfoMessage: showGiftCardInfoMessage,\n giftCardBrands: giftCardBrands,\n clearGiftCardsContainer: clearGiftCardsContainer,\n attachGiftCardCancelListener: attachGiftCardCancelListener,\n showGiftCardCancelButton: showGiftCardCancelButton\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGiftcardComponent.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderPaymentMethod.js": +/*!*****************************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderPaymentMethod.js ***! + \*****************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar helpers = __webpack_require__(/*! ./helpers */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js\");\nvar constants = __webpack_require__(/*! ../constants */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js\");\nfunction getFallback(paymentMethod) {\n var fallback = {};\n if (fallback[paymentMethod.type]) {\n store.componentsObj[paymentMethod.type] = {};\n }\n return fallback[paymentMethod.type];\n}\nfunction getPersonalDetails() {\n var _document$querySelect, _document$querySelect2, _document$querySelect3, _document$querySelect4;\n return {\n firstName: (_document$querySelect = document.querySelector('#shippingFirstNamedefault')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.value,\n lastName: (_document$querySelect2 = document.querySelector('#shippingLastNamedefault')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value,\n telephoneNumber: (_document$querySelect3 = document.querySelector('#shippingPhoneNumberdefault')) === null || _document$querySelect3 === void 0 ? void 0 : _document$querySelect3.value,\n shopperEmail: (_document$querySelect4 = document.querySelector('.customer-summary-email')) === null || _document$querySelect4 === void 0 ? void 0 : _document$querySelect4.textContent\n };\n}\nfunction setNode(paymentMethodID) {\n var createNode = function createNode() {\n if (!store.componentsObj[paymentMethodID]) {\n store.componentsObj[paymentMethodID] = {};\n }\n try {\n var _store$checkout;\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n // ALl nodes created for the checkout component are enriched with shopper personal details\n var node = (_store$checkout = store.checkout).create.apply(_store$checkout, args.concat([{\n data: _objectSpread(_objectSpread({}, getPersonalDetails()), {}, {\n personalDetails: getPersonalDetails()\n }),\n visibility: {\n personalDetails: 'editable',\n billingAddress: 'hidden',\n deliveryAddress: 'hidden'\n }\n }]));\n store.componentsObj[paymentMethodID].node = node;\n store.componentsObj[paymentMethodID].isValid = node.isValid;\n } catch (e) {\n /* No component for payment method */\n }\n };\n return createNode;\n}\nfunction getPaymentMethodID(isStored, paymentMethod) {\n if (isStored) {\n return \"storedCard\".concat(paymentMethod.id);\n }\n if (paymentMethod.type === constants.GIFTCARD) {\n return constants.GIFTCARD;\n }\n if (paymentMethod.brand) {\n return \"\".concat(paymentMethod.type, \"_\").concat(paymentMethod.brand);\n }\n return paymentMethod.type;\n}\nfunction getImage(isStored, paymentMethod) {\n return isStored ? paymentMethod.brand : paymentMethod.type;\n}\nfunction getLabel(isStored, paymentMethod) {\n var label = isStored ? \" \".concat(store.MASKED_CC_PREFIX).concat(paymentMethod.lastFour) : '';\n return \"\".concat(paymentMethod.name).concat(label);\n}\nfunction handleFallbackPayment(_ref) {\n var paymentMethod = _ref.paymentMethod,\n container = _ref.container,\n paymentMethodID = _ref.paymentMethodID;\n var fallback = getFallback(paymentMethod);\n var createTemplate = function createTemplate() {\n var template = document.createElement('template');\n template.innerHTML = fallback;\n container.append(template.content);\n };\n return fallback ? createTemplate() : setNode(paymentMethod.type)(paymentMethodID);\n}\nfunction handlePayment(options) {\n return options.isStored ? setNode(options.paymentMethodID)('card', options.paymentMethod) : handleFallbackPayment(options);\n}\nfunction getListContents(_ref2) {\n var imagePath = _ref2.imagePath,\n isStored = _ref2.isStored,\n paymentMethod = _ref2.paymentMethod,\n description = _ref2.description;\n var paymentMethodID = getPaymentMethodID(isStored, paymentMethod);\n var label = getLabel(isStored, paymentMethod);\n var liContents = \"\\n \\n \\n \\n \");\n return description ? \"\".concat(liContents, \"

            \").concat(description, \"

            \") : liContents;\n}\nfunction getImagePath(_ref3) {\n var isStored = _ref3.isStored,\n paymentMethod = _ref3.paymentMethod,\n path = _ref3.path,\n isSchemeNotStored = _ref3.isSchemeNotStored;\n var paymentMethodImage = \"\".concat(path).concat(getImage(isStored, paymentMethod), \".png\");\n var cardImage = \"\".concat(path, \"card.png\");\n return isSchemeNotStored ? cardImage : paymentMethodImage;\n}\nfunction setValid(_ref4) {\n var isStored = _ref4.isStored,\n paymentMethodID = _ref4.paymentMethodID;\n if (isStored && ['bcmc', 'scheme'].indexOf(paymentMethodID) > -1) {\n store.componentsObj[paymentMethodID].isValid = true;\n }\n}\nfunction configureContainer(_ref5) {\n var paymentMethodID = _ref5.paymentMethodID,\n container = _ref5.container;\n container.classList.add('additionalFields');\n container.setAttribute('id', \"component_\".concat(paymentMethodID));\n container.setAttribute('style', 'display:none');\n}\nfunction handleInput(_ref6) {\n var paymentMethodID = _ref6.paymentMethodID;\n var input = document.querySelector(\"#rb_\".concat(paymentMethodID));\n input.onchange = /*#__PURE__*/function () {\n var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(event) {\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n helpers.displaySelectedMethod(event.target.value);\n case 1:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return function (_x) {\n return _ref7.apply(this, arguments);\n };\n }();\n}\nfunction createListItem(rerender, paymentMethodID, liContents) {\n var li;\n if (rerender) {\n li = document.querySelector(\"#rb_\".concat(paymentMethodID)).closest('li');\n } else {\n li = document.createElement('li');\n li.innerHTML = liContents;\n li.classList.add('paymentMethod');\n }\n return li;\n}\nfunction checkIfNodeIsAvailable(_x2) {\n return _checkIfNodeIsAvailable.apply(this, arguments);\n}\nfunction _checkIfNodeIsAvailable() {\n _checkIfNodeIsAvailable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(node) {\n var isNodeAvailable;\n return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n while (1) switch (_context3.prev = _context3.next) {\n case 0:\n if (!node.isAvailable) {\n _context3.next = 6;\n break;\n }\n _context3.next = 3;\n return node.isAvailable();\n case 3:\n isNodeAvailable = _context3.sent;\n if (isNodeAvailable) {\n _context3.next = 6;\n break;\n }\n return _context3.abrupt(\"return\", false);\n case 6:\n return _context3.abrupt(\"return\", true);\n case 7:\n case \"end\":\n return _context3.stop();\n }\n }, _callee3);\n }));\n return _checkIfNodeIsAvailable.apply(this, arguments);\n}\nfunction appendNodeToContainerIfAvailable(_x3, _x4, _x5, _x6) {\n return _appendNodeToContainerIfAvailable.apply(this, arguments);\n}\nfunction _appendNodeToContainerIfAvailable() {\n _appendNodeToContainerIfAvailable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(paymentMethodsUI, li, node, container) {\n var canBeMounted;\n return _regeneratorRuntime().wrap(function _callee4$(_context4) {\n while (1) switch (_context4.prev = _context4.next) {\n case 0:\n if (!node) {\n _context4.next = 5;\n break;\n }\n _context4.next = 3;\n return checkIfNodeIsAvailable(node);\n case 3:\n canBeMounted = _context4.sent;\n if (canBeMounted) {\n paymentMethodsUI.append(li);\n node.mount(container);\n }\n case 5:\n case \"end\":\n return _context4.stop();\n }\n }, _callee4);\n }));\n return _appendNodeToContainerIfAvailable.apply(this, arguments);\n}\nmodule.exports.renderPaymentMethod = /*#__PURE__*/function () {\n var _renderPaymentMethod = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(paymentMethod, isStored, path) {\n var description,\n rerender,\n _store$componentsObj$,\n paymentMethodsUI,\n paymentMethodID,\n isSchemeNotStored,\n container,\n options,\n imagePath,\n liContents,\n li,\n _args2 = arguments;\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n description = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : null;\n rerender = _args2.length > 4 && _args2[4] !== undefined ? _args2[4] : false;\n _context2.prev = 2;\n paymentMethodsUI = document.querySelector('#paymentMethodsList');\n paymentMethodID = getPaymentMethodID(isStored, paymentMethod);\n if (!(paymentMethodID === constants.GIFTCARD)) {\n _context2.next = 7;\n break;\n }\n return _context2.abrupt(\"return\");\n case 7:\n isSchemeNotStored = paymentMethod.type === 'scheme' && !isStored;\n container = document.createElement('div');\n options = {\n container: container,\n paymentMethod: paymentMethod,\n isStored: isStored,\n path: path,\n description: description,\n paymentMethodID: paymentMethodID,\n isSchemeNotStored: isSchemeNotStored\n };\n imagePath = getImagePath(options);\n liContents = getListContents(_objectSpread(_objectSpread({}, options), {}, {\n imagePath: imagePath,\n description: description\n }));\n li = createListItem(rerender, paymentMethodID, liContents);\n handlePayment(options);\n configureContainer(options);\n li.append(container);\n _context2.next = 18;\n return appendNodeToContainerIfAvailable(paymentMethodsUI, li, (_store$componentsObj$ = store.componentsObj[paymentMethodID]) === null || _store$componentsObj$ === void 0 ? void 0 : _store$componentsObj$.node, container);\n case 18:\n if (paymentMethodID === constants.GIROPAY) {\n container.innerHTML = '';\n }\n handleInput(options);\n setValid(options);\n _context2.next = 25;\n break;\n case 23:\n _context2.prev = 23;\n _context2.t0 = _context2[\"catch\"](2);\n case 25:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2, null, [[2, 23]]);\n }));\n function renderPaymentMethod(_x7, _x8, _x9) {\n return _renderPaymentMethod.apply(this, arguments);\n }\n return renderPaymentMethod;\n}();\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderPaymentMethod.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/validateComponents.js": +/*!****************************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/validateComponents.js ***! + \****************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nmodule.exports.validateComponents = function validateComponents() {\n var customMethods = {};\n if (store.selectedMethod in customMethods) {\n customMethods[store.selectedMethod]();\n }\n document.querySelector('#adyenStateData').value = JSON.stringify(store.stateData);\n if (store.partialPaymentsOrderObj) {\n document.querySelector('#adyenPartialPaymentsOrder').value = JSON.stringify(store.partialPaymentsOrderObj);\n }\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/validateComponents.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js": +/*!********************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nmodule.exports.onFieldValid = function onFieldValid(data) {\n if (data.endDigits) {\n store.endDigits = data.endDigits;\n document.querySelector('#cardNumber').value = store.maskedCardNumber;\n }\n};\nmodule.exports.onBrand = function onBrand(brandObject) {\n document.querySelector('#cardType').value = brandObject.brand;\n};\n\n/**\n * Makes an ajax call to the controller function CreateSession\n */\nmodule.exports.createSession = /*#__PURE__*/function () {\n var _createSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n return _context.abrupt(\"return\", $.ajax({\n url: window.sessionsUrl,\n type: 'get'\n }));\n case 1:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n function createSession() {\n return _createSession.apply(this, arguments);\n }\n return createSession;\n}();\n\n/**\n * Makes an ajax call to the controller function FetchGiftCards\n */\nmodule.exports.fetchGiftCards = /*#__PURE__*/function () {\n var _fetchGiftCards = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n return _context2.abrupt(\"return\", $.ajax({\n url: window.fetchGiftCardsUrl,\n type: 'get'\n }));\n case 1:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n function fetchGiftCards() {\n return _fetchGiftCards.apply(this, arguments);\n }\n return fetchGiftCards;\n}();\nmodule.exports.checkIfExpressMethodsAreReady = function checkIfExpressMethodsAreReady() {\n var expressMethodsConfig = {\n applepay: window.isApplePayExpressEnabled === 'true',\n amazonpay: window.isAmazonPayExpressEnabled === 'true'\n };\n var enabledExpressMethods = [];\n Object.keys(expressMethodsConfig).forEach(function (key) {\n if (expressMethodsConfig[key]) {\n enabledExpressMethods.push(key);\n }\n });\n enabledExpressMethods = enabledExpressMethods.sort();\n var loadedExpressMethods = window.loadedExpressMethods && window.loadedExpressMethods.length ? window.loadedExpressMethods.sort() : [];\n var areAllMethodsReady = JSON.stringify(enabledExpressMethods) === JSON.stringify(loadedExpressMethods);\n if (!enabledExpressMethods.length || areAllMethodsReady) {\n var _document$getElementB, _document$getElementB2;\n (_document$getElementB = document.getElementById('express-loader-container')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.classList.add('hidden');\n (_document$getElementB2 = document.getElementById('express-container')) === null || _document$getElementB2 === void 0 ? void 0 : _document$getElementB2.classList.remove('hidden');\n }\n};\nmodule.exports.updateLoadedExpressMethods = function updateLoadedExpressMethods(method) {\n if (!window.loadedExpressMethods) {\n window.loadedExpressMethods = [];\n }\n if (!window.loadedExpressMethods.includes(method)) {\n window.loadedExpressMethods.push(method);\n }\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js": +/*!****************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js ***! + \****************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\n// Adyen constants\n\nmodule.exports = {\n METHOD_ADYEN: 'Adyen',\n METHOD_ADYEN_POS: 'AdyenPOS',\n METHOD_ADYEN_COMPONENT: 'AdyenComponent',\n RECEIVED: 'Received',\n NOTENOUGHBALANCE: 'NotEnoughBalance',\n SUCCESS: 'Success',\n GIFTCARD: 'giftcard',\n GIROPAY: 'giropay',\n APPLE_PAY: 'applepay',\n ACTIONTYPE: {\n QRCODE: 'qrCode'\n },\n DISABLED_SUBMIT_BUTTON_METHODS: ['paypal', 'paywithgoogle', 'googlepay', 'amazonpay', 'applepay', 'cashapp'],\n APPLE_DOMAIN_URL: '/.well-known/apple-developer-merchantid-domain-association'\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/store/index.js": +/*!************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/store/index.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nvar _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, _descriptor12, _descriptor13;\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }\nfunction _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); }\nvar _require = __webpack_require__(/*! mobx */ \"./node_modules/mobx/dist/mobx.esm.js\"),\n observable = _require.observable,\n computed = _require.computed;\nvar Store = (_class = /*#__PURE__*/function () {\n function Store() {\n _classCallCheck(this, Store);\n _defineProperty(this, \"MASKED_CC_PREFIX\", '************');\n _initializerDefineProperty(this, \"checkout\", _descriptor, this);\n _initializerDefineProperty(this, \"endDigits\", _descriptor2, this);\n _initializerDefineProperty(this, \"selectedMethod\", _descriptor3, this);\n _initializerDefineProperty(this, \"componentsObj\", _descriptor4, this);\n _initializerDefineProperty(this, \"checkoutConfiguration\", _descriptor5, this);\n _initializerDefineProperty(this, \"formErrorsExist\", _descriptor6, this);\n _initializerDefineProperty(this, \"isValid\", _descriptor7, this);\n _initializerDefineProperty(this, \"paypalTerminatedEarly\", _descriptor8, this);\n _initializerDefineProperty(this, \"componentState\", _descriptor9, this);\n _initializerDefineProperty(this, \"brand\", _descriptor10, this);\n _initializerDefineProperty(this, \"partialPaymentsOrderObj\", _descriptor11, this);\n _initializerDefineProperty(this, \"giftCardComponentListenersAdded\", _descriptor12, this);\n _initializerDefineProperty(this, \"addedGiftCards\", _descriptor13, this);\n }\n _createClass(Store, [{\n key: \"maskedCardNumber\",\n get: function get() {\n return \"\".concat(this.MASKED_CC_PREFIX).concat(this.endDigits);\n }\n }, {\n key: \"selectedPayment\",\n get: function get() {\n return this.componentsObj[this.selectedMethod];\n }\n }, {\n key: \"selectedPaymentIsValid\",\n get: function get() {\n var _this$selectedPayment;\n return !!((_this$selectedPayment = this.selectedPayment) !== null && _this$selectedPayment !== void 0 && _this$selectedPayment.isValid);\n }\n }, {\n key: \"stateData\",\n get: function get() {\n var _this$selectedPayment2;\n return ((_this$selectedPayment2 = this.selectedPayment) === null || _this$selectedPayment2 === void 0 ? void 0 : _this$selectedPayment2.stateData) || {\n paymentMethod: _objectSpread({\n type: this.selectedMethod\n }, this.brand ? {\n brand: this.brand\n } : undefined)\n };\n }\n }, {\n key: \"updateSelectedPayment\",\n value: function updateSelectedPayment(method, key, val) {\n this.componentsObj[method][key] = val;\n }\n }]);\n return Store;\n}(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, \"checkout\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, \"endDigits\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, \"selectedMethod\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, \"componentsObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, \"checkoutConfiguration\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return window.Configuration || {};\n }\n}), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, \"formErrorsExist\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, \"isValid\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, \"paypalTerminatedEarly\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor9 = _applyDecoratedDescriptor(_class.prototype, \"componentState\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor10 = _applyDecoratedDescriptor(_class.prototype, \"brand\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor11 = _applyDecoratedDescriptor(_class.prototype, \"partialPaymentsOrderObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor12 = _applyDecoratedDescriptor(_class.prototype, \"giftCardComponentListenersAdded\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor13 = _applyDecoratedDescriptor(_class.prototype, \"addedGiftCards\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _applyDecoratedDescriptor(_class.prototype, \"maskedCardNumber\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"maskedCardNumber\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPayment\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPayment\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPaymentIsValid\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPaymentIsValid\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"stateData\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"stateData\"), _class.prototype)), _class);\nmodule.exports = new Store();\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/store/index.js?"); + +/***/ }), + +/***/ "./node_modules/mobx/dist/mobx.esm.js": +/*!********************************************!*\ + !*** ./node_modules/mobx/dist/mobx.esm.js ***! + \********************************************/ +/*! exports provided: $mobx, FlowCancellationError, ObservableMap, ObservableSet, Reaction, _allowStateChanges, _allowStateChangesInsideComputed, _allowStateReadsEnd, _allowStateReadsStart, _autoAction, _endAction, _getAdministration, _getGlobalState, _interceptReads, _isComputingDerivation, _resetGlobalState, _startAction, action, autorun, comparer, computed, configure, createAtom, defineProperty, entries, extendObservable, flow, flowResult, get, getAtom, getDebugName, getDependencyTree, getObserverTree, has, intercept, isAction, isBoxedObservable, isComputed, isComputedProp, isFlow, isFlowCancellationError, isObservable, isObservableArray, isObservableMap, isObservableObject, isObservableProp, isObservableSet, keys, makeAutoObservable, makeObservable, observable, observe, onBecomeObserved, onBecomeUnobserved, onReactionError, override, ownKeys, reaction, remove, runInAction, set, spy, toJS, trace, transaction, untracked, values, when */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"$mobx\", function() { return $mobx; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"FlowCancellationError\", function() { return FlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableMap\", function() { return ObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableSet\", function() { return ObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Reaction\", function() { return Reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChanges\", function() { return allowStateChanges; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChangesInsideComputed\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsEnd\", function() { return allowStateReadsEnd; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsStart\", function() { return allowStateReadsStart; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_autoAction\", function() { return autoAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_endAction\", function() { return _endAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getAdministration\", function() { return getAdministration; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getGlobalState\", function() { return getGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_interceptReads\", function() { return interceptReads; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_isComputingDerivation\", function() { return isComputingDerivation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_resetGlobalState\", function() { return resetGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_startAction\", function() { return _startAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"action\", function() { return action; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"autorun\", function() { return autorun; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"comparer\", function() { return comparer; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"computed\", function() { return computed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"configure\", function() { return configure; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createAtom\", function() { return createAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"defineProperty\", function() { return apiDefineProperty; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"entries\", function() { return entries; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"extendObservable\", function() { return extendObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flow\", function() { return flow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flowResult\", function() { return flowResult; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"get\", function() { return get; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getAtom\", function() { return getAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDebugName\", function() { return getDebugName; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDependencyTree\", function() { return getDependencyTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getObserverTree\", function() { return getObserverTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"has\", function() { return has; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"intercept\", function() { return intercept; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isAction\", function() { return isAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isBoxedObservable\", function() { return isObservableValue; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputed\", function() { return isComputed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputedProp\", function() { return isComputedProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlow\", function() { return isFlow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlowCancellationError\", function() { return isFlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservable\", function() { return isObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableArray\", function() { return isObservableArray; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableMap\", function() { return isObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableObject\", function() { return isObservableObject; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableProp\", function() { return isObservableProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableSet\", function() { return isObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"keys\", function() { return keys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeAutoObservable\", function() { return makeAutoObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeObservable\", function() { return makeObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observable\", function() { return observable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observe\", function() { return observe; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeObserved\", function() { return onBecomeObserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeUnobserved\", function() { return onBecomeUnobserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onReactionError\", function() { return onReactionError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"override\", function() { return override; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ownKeys\", function() { return apiOwnKeys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"reaction\", function() { return reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"remove\", function() { return remove; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"runInAction\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"set\", function() { return set; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"spy\", function() { return spy; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toJS\", function() { return toJS; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"trace\", function() { return trace; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"transaction\", function() { return transaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"untracked\", function() { return untracked; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"values\", function() { return values; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"when\", function() { return when; });\nvar niceErrors = {\n 0: \"Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'\",\n 1: function _(annotationType, key) {\n return \"Cannot apply '\" + annotationType + \"' to '\" + key.toString() + \"': Field not found.\";\n },\n\n /*\r\n 2(prop) {\r\n return `invalid decorator for '${prop.toString()}'`\r\n },\r\n 3(prop) {\r\n return `Cannot decorate '${prop.toString()}': action can only be used on properties with a function value.`\r\n },\r\n 4(prop) {\r\n return `Cannot decorate '${prop.toString()}': computed can only be used on getter properties.`\r\n },\r\n */\n 5: \"'keys()' can only be used on observable objects, arrays, sets and maps\",\n 6: \"'values()' can only be used on observable objects, arrays, sets and maps\",\n 7: \"'entries()' can only be used on observable objects, arrays and maps\",\n 8: \"'set()' can only be used on observable objects, arrays and maps\",\n 9: \"'remove()' can only be used on observable objects, arrays and maps\",\n 10: \"'has()' can only be used on observable objects, arrays and maps\",\n 11: \"'get()' can only be used on observable objects, arrays and maps\",\n 12: \"Invalid annotation\",\n 13: \"Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 14: \"Intercept handlers should return nothing or a change object\",\n 15: \"Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 16: \"Modification exception: the internal structure of an observable array was changed.\",\n 17: function _(index, length) {\n return \"[mobx.array] Index out of bounds, \" + index + \" is larger than \" + length;\n },\n 18: \"mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js\",\n 19: function _(other) {\n return \"Cannot initialize from classes that inherit from Map: \" + other.constructor.name;\n },\n 20: function _(other) {\n return \"Cannot initialize map from \" + other;\n },\n 21: function _(dataStructure) {\n return \"Cannot convert to map from '\" + dataStructure + \"'\";\n },\n 22: \"mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js\",\n 23: \"It is not possible to get index atoms from arrays\",\n 24: function _(thing) {\n return \"Cannot obtain administration from \" + thing;\n },\n 25: function _(property, name) {\n return \"the entry '\" + property + \"' does not exist in the observable map '\" + name + \"'\";\n },\n 26: \"please specify a property\",\n 27: function _(property, name) {\n return \"no observable property '\" + property.toString() + \"' found on the observable object '\" + name + \"'\";\n },\n 28: function _(thing) {\n return \"Cannot obtain atom from \" + thing;\n },\n 29: \"Expecting some object\",\n 30: \"invalid action stack. did you forget to finish an action?\",\n 31: \"missing option for computed: get\",\n 32: function _(name, derivation) {\n return \"Cycle detected in computation \" + name + \": \" + derivation;\n },\n 33: function _(name) {\n return \"The setter of computed value '\" + name + \"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?\";\n },\n 34: function _(name) {\n return \"[ComputedValue '\" + name + \"'] It is not possible to assign a new value to a computed value.\";\n },\n 35: \"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`\",\n 36: \"isolateGlobalState should be called before MobX is running any reactions\",\n 37: function _(method) {\n return \"[mobx] `observableArray.\" + method + \"()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice().\" + method + \"()` instead\";\n },\n 38: \"'ownKeys()' can only be used on observable objects\",\n 39: \"'defineProperty()' can only be used on observable objects\"\n};\nvar errors = true ? niceErrors : undefined;\nfunction die(error) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n if (true) {\n var e = typeof error === \"string\" ? error : errors[error];\n if (typeof e === \"function\") e = e.apply(null, args);\n throw new Error(\"[MobX] \" + e);\n }\n\n throw new Error(typeof error === \"number\" ? \"[MobX] minified error nr: \" + error + (args.length ? \" \" + args.map(String).join(\",\") : \"\") + \". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts\" : \"[MobX] \" + error);\n}\n\nvar mockGlobal = {};\nfunction getGlobal() {\n if (typeof globalThis !== \"undefined\") {\n return globalThis;\n }\n\n if (typeof window !== \"undefined\") {\n return window;\n }\n\n if (typeof global !== \"undefined\") {\n return global;\n }\n\n if (typeof self !== \"undefined\") {\n return self;\n }\n\n return mockGlobal;\n}\n\nvar assign = Object.assign;\nvar getDescriptor = Object.getOwnPropertyDescriptor;\nvar defineProperty = Object.defineProperty;\nvar objectPrototype = Object.prototype;\nvar EMPTY_ARRAY = [];\nObject.freeze(EMPTY_ARRAY);\nvar EMPTY_OBJECT = {};\nObject.freeze(EMPTY_OBJECT);\nvar hasProxy = typeof Proxy !== \"undefined\";\nvar plainObjectString = /*#__PURE__*/Object.toString();\nfunction assertProxies() {\n if (!hasProxy) {\n die( true ? \"`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`\" : undefined);\n }\n}\nfunction warnAboutProxyRequirement(msg) {\n if ( true && globalState.verifyProxies) {\n die(\"MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to \" + msg);\n }\n}\nfunction getNextId() {\n return ++globalState.mobxGuid;\n}\n/**\r\n * Makes sure that the provided function is invoked at most once.\r\n */\n\nfunction once(func) {\n var invoked = false;\n return function () {\n if (invoked) {\n return;\n }\n\n invoked = true;\n return func.apply(this, arguments);\n };\n}\nvar noop = function noop() {};\nfunction isFunction(fn) {\n return typeof fn === \"function\";\n}\nfunction isStringish(value) {\n var t = typeof value;\n\n switch (t) {\n case \"string\":\n case \"symbol\":\n case \"number\":\n return true;\n }\n\n return false;\n}\nfunction isObject(value) {\n return value !== null && typeof value === \"object\";\n}\nfunction isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n\n var proto = Object.getPrototypeOf(value);\n\n if (proto == null) {\n return true;\n }\n\n var protoConstructor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof protoConstructor === \"function\" && protoConstructor.toString() === plainObjectString;\n} // https://stackoverflow.com/a/37865170\n\nfunction isGenerator(obj) {\n var constructor = obj == null ? void 0 : obj.constructor;\n\n if (!constructor) {\n return false;\n }\n\n if (\"GeneratorFunction\" === constructor.name || \"GeneratorFunction\" === constructor.displayName) {\n return true;\n }\n\n return false;\n}\nfunction addHiddenProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\nfunction addHiddenFinalProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\nfunction createInstanceofPredicate(name, theClass) {\n var propName = \"isMobX\" + name;\n theClass.prototype[propName] = true;\n return function (x) {\n return isObject(x) && x[propName] === true;\n };\n}\nfunction isES6Map(thing) {\n return thing instanceof Map;\n}\nfunction isES6Set(thing) {\n return thing instanceof Set;\n}\nvar hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== \"undefined\";\n/**\r\n * Returns the following: own enumerable keys and symbols.\r\n */\n\nfunction getPlainObjectKeys(object) {\n var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway...\n\n if (!hasGetOwnPropertySymbols) {\n return keys;\n }\n\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (!symbols.length) {\n return keys;\n }\n\n return [].concat(keys, symbols.filter(function (s) {\n return objectPrototype.propertyIsEnumerable.call(object, s);\n }));\n} // From Immer utils\n// Returns all own keys, including non-enumerable and symbolic\n\nvar ownKeys = typeof Reflect !== \"undefined\" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {\n return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));\n} :\n/* istanbul ignore next */\nObject.getOwnPropertyNames;\nfunction stringifyKey(key) {\n if (typeof key === \"string\") {\n return key;\n }\n\n if (typeof key === \"symbol\") {\n return key.toString();\n }\n\n return new String(key).toString();\n}\nfunction toPrimitive(value) {\n return value === null ? null : typeof value === \"object\" ? \"\" + value : value;\n}\nfunction hasProp(target, prop) {\n return objectPrototype.hasOwnProperty.call(target, prop);\n} // From Immer utils\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {\n // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up\n\n ownKeys(target).forEach(function (key) {\n res[key] = getDescriptor(target, key);\n });\n return res;\n};\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n\n _setPrototypeOf(subClass, superClass);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n if (it) return (it = it.call(o)).next.bind(it);\n\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n return function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar storedAnnotationsSymbol = /*#__PURE__*/Symbol(\"mobx-stored-annotations\");\n/**\r\n * Creates a function that acts as\r\n * - decorator\r\n * - annotation object\r\n */\n\nfunction createDecoratorAnnotation(annotation) {\n function decorator(target, property) {\n storeAnnotation(target, property, annotation);\n }\n\n return Object.assign(decorator, annotation);\n}\n/**\r\n * Stores annotation to prototype,\r\n * so it can be inspected later by `makeObservable` called from constructor\r\n */\n\nfunction storeAnnotation(prototype, key, annotation) {\n if (!hasProp(prototype, storedAnnotationsSymbol)) {\n addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));\n } // @override must override something\n\n\n if ( true && isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n die(\"'\" + fieldName + \"' is decorated with 'override', \" + \"but no such decorated member was found on prototype.\");\n } // Cannot re-decorate\n\n\n assertNotDecorated(prototype, annotation, key); // Ignore override\n\n if (!isOverride(annotation)) {\n prototype[storedAnnotationsSymbol][key] = annotation;\n }\n}\n\nfunction assertNotDecorated(prototype, annotation, key) {\n if ( true && !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '@\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already decorated with '@\" + currentAnnotationType + \"'.\") + \"\\nRe-decorating fields is not allowed.\" + \"\\nUse '@override' decorator for methods overridden by subclass.\");\n }\n}\n/**\r\n * Collects annotations from prototypes and stores them on target (instance)\r\n */\n\n\nfunction collectStoredAnnotations(target) {\n if (!hasProp(target, storedAnnotationsSymbol)) {\n if ( true && !target[storedAnnotationsSymbol]) {\n die(\"No annotations were passed to makeObservable, but no decorated members have been found either\");\n } // We need a copy as we will remove annotation from the list once it's applied.\n\n\n addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));\n }\n\n return target[storedAnnotationsSymbol];\n}\n\nvar $mobx = /*#__PURE__*/Symbol(\"mobx administration\");\nvar Atom = /*#__PURE__*/function () {\n // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed\n\n /**\r\n * Create a new atom. For debugging purposes it is recommended to give it a name.\r\n * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.\r\n */\n function Atom(name_) {\n if (name_ === void 0) {\n name_ = true ? \"Atom@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.isPendingUnobservation_ = false;\n this.isBeingObserved_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n this.name_ = name_;\n } // onBecomeObservedListeners\n\n\n var _proto = Atom.prototype;\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Invoke this method to notify mobx that your atom has been used somehow.\r\n * Returns true if there is currently a reactive context.\r\n */\n ;\n\n _proto.reportObserved = function reportObserved$1() {\n return reportObserved(this);\n }\n /**\r\n * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.\r\n */\n ;\n\n _proto.reportChanged = function reportChanged() {\n startBatch();\n propagateChanged(this);\n endBatch();\n };\n\n _proto.toString = function toString() {\n return this.name_;\n };\n\n return Atom;\n}();\nvar isAtom = /*#__PURE__*/createInstanceofPredicate(\"Atom\", Atom);\nfunction createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {\n if (onBecomeObservedHandler === void 0) {\n onBecomeObservedHandler = noop;\n }\n\n if (onBecomeUnobservedHandler === void 0) {\n onBecomeUnobservedHandler = noop;\n }\n\n var atom = new Atom(name); // default `noop` listener will not initialize the hook Set\n\n if (onBecomeObservedHandler !== noop) {\n onBecomeObserved(atom, onBecomeObservedHandler);\n }\n\n if (onBecomeUnobservedHandler !== noop) {\n onBecomeUnobserved(atom, onBecomeUnobservedHandler);\n }\n\n return atom;\n}\n\nfunction identityComparer(a, b) {\n return a === b;\n}\n\nfunction structuralComparer(a, b) {\n return deepEqual(a, b);\n}\n\nfunction shallowComparer(a, b) {\n return deepEqual(a, b, 1);\n}\n\nfunction defaultComparer(a, b) {\n if (Object.is) {\n return Object.is(a, b);\n }\n\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n}\n\nvar comparer = {\n identity: identityComparer,\n structural: structuralComparer,\n \"default\": defaultComparer,\n shallow: shallowComparer\n};\n\nfunction deepEnhancer(v, _, name) {\n // it is an observable already, done\n if (isObservable(v)) {\n return v;\n } // something that can be converted and mutated?\n\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name\n });\n }\n\n if (typeof v === \"function\" && !isAction(v) && !isFlow(v)) {\n if (isGenerator(v)) {\n return flow(v);\n } else {\n return autoAction(name, v);\n }\n }\n\n return v;\n}\nfunction shallowEnhancer(v, _, name) {\n if (v === undefined || v === null) {\n return v;\n }\n\n if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {\n return v;\n }\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name,\n deep: false\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name,\n deep: false\n });\n }\n\n if (true) {\n die(\"The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets\");\n }\n}\nfunction referenceEnhancer(newValue) {\n // never turn into an observable\n return newValue;\n}\nfunction refStructEnhancer(v, oldValue) {\n if ( true && isObservable(v)) {\n die(\"observable.struct should not be used with observable values\");\n }\n\n if (deepEqual(v, oldValue)) {\n return oldValue;\n }\n\n return v;\n}\n\nvar OVERRIDE = \"override\";\nvar override = /*#__PURE__*/createDecoratorAnnotation({\n annotationType_: OVERRIDE,\n make_: make_,\n extend_: extend_\n});\nfunction isOverride(annotation) {\n return annotation.annotationType_ === OVERRIDE;\n}\n\nfunction make_(adm, key) {\n // Must not be plain object\n if ( true && adm.isPlainObject_) {\n die(\"Cannot apply '\" + this.annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + this.annotationType_ + \"' cannot be used on plain objects.\"));\n } // Must override something\n\n\n if ( true && !hasProp(adm.appliedAnnotations_, key)) {\n die(\"'\" + adm.name_ + \".\" + key.toString() + \"' is annotated with '\" + this.annotationType_ + \"', \" + \"but no such annotated member was found on prototype.\");\n }\n\n return 0\n /* Cancel */\n ;\n}\n\nfunction extend_(adm, key, descriptor, proxyTrap) {\n die(\"'\" + this.annotationType_ + \"' can only be used with 'makeObservable'\");\n}\n\nfunction createActionAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$1,\n extend_: extend_$1\n };\n}\n\nfunction make_$1(adm, key, descriptor, source) {\n var _this$options_;\n\n // bound\n if ((_this$options_ = this.options_) != null && _this$options_.bound) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n } // own\n\n\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n\n\n if (isAction(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);\n defineProperty(source, key, actionDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$1(adm, key, descriptor, proxyTrap) {\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);\n return adm.defineProperty_(key, actionDescriptor, proxyTrap);\n}\n\nfunction assertActionDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a function value.\"));\n }\n}\n\nfunction createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;\n\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertActionDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n\n if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {\n var _adm$proxy_;\n\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return {\n value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false, // https://github.com/mobxjs/mobx/discussions/3140\n (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createFlowAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$2,\n extend_: extend_$2\n };\n}\n\nfunction make_$2(adm, key, descriptor, source) {\n var _this$options_;\n\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n // bound - must annotate protos to support super.flow()\n\n\n if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {\n if (this.extend_(adm, key, descriptor, false) === null) {\n return 0\n /* Cancel */\n ;\n }\n }\n\n if (isFlow(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);\n defineProperty(source, key, flowDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$2(adm, key, descriptor, proxyTrap) {\n var _this$options_2;\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);\n return adm.defineProperty_(key, flowDescriptor, proxyTrap);\n}\n\nfunction assertFlowDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a generator function value.\"));\n }\n}\n\nfunction createFlowDescriptor(adm, annotation, key, descriptor, bound, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertFlowDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value; // In case of flow.bound, the descriptor can be from already annotated prototype\n\n if (!isFlow(value)) {\n value = flow(value);\n }\n\n if (bound) {\n var _adm$proxy_;\n\n // We do not keep original function around, so we bind the existing flow\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); // This is normally set by `flow`, but `bind` returns new function...\n\n value.isMobXFlow = true;\n }\n\n return {\n value: value,\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createComputedAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$3,\n extend_: extend_$3\n };\n}\n\nfunction make_$3(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$3(adm, key, descriptor, proxyTrap) {\n assertComputedDescriptor(adm, this, key, descriptor);\n return adm.defineComputedProperty_(key, _extends({}, this.options_, {\n get: descriptor.get,\n set: descriptor.set\n }), proxyTrap);\n}\n\nfunction assertComputedDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var get = _ref2.get;\n\n if ( true && !get) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on getter(+setter) properties.\"));\n }\n}\n\nfunction createObservableAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$4,\n extend_: extend_$4\n };\n}\n\nfunction make_$4(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$4(adm, key, descriptor, proxyTrap) {\n var _this$options_$enhanc, _this$options_;\n\n assertObservableDescriptor(adm, this, key, descriptor);\n return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap);\n}\n\nfunction assertObservableDescriptor(adm, _ref, key, descriptor) {\n var annotationType_ = _ref.annotationType_;\n\n if ( true && !(\"value\" in descriptor)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' cannot be used on getter/setter properties\"));\n }\n}\n\nvar AUTO = \"true\";\nvar autoAnnotation = /*#__PURE__*/createAutoAnnotation();\nfunction createAutoAnnotation(options) {\n return {\n annotationType_: AUTO,\n options_: options,\n make_: make_$5,\n extend_: extend_$5\n };\n}\n\nfunction make_$5(adm, key, descriptor, source) {\n var _this$options_3, _this$options_4;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.make_(adm, key, descriptor, source);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.make_\n var set = createAction(key.toString(), descriptor.set); // own\n\n if (source === adm.target_) {\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: set\n }) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // proto\n\n\n defineProperty(source, key, {\n configurable: true,\n set: set\n });\n return 2\n /* Continue */\n ;\n } // function on proto -> autoAction/flow\n\n\n if (source !== adm.target_ && typeof descriptor.value === \"function\") {\n var _this$options_2;\n\n if (isGenerator(descriptor.value)) {\n var _this$options_;\n\n var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;\n return flowAnnotation.make_(adm, key, descriptor, source);\n }\n\n var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;\n return actionAnnotation.make_(adm, key, descriptor, source);\n } // other -> observable\n // Copy props from proto as well, see test:\n // \"decorate should work with Object.create\"\n\n\n var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable; // if function respect autoBind option\n\n if (typeof descriptor.value === \"function\" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {\n var _adm$proxy_;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return observableAnnotation.make_(adm, key, descriptor, source);\n}\n\nfunction extend_$5(adm, key, descriptor, proxyTrap) {\n var _this$options_5, _this$options_6;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.extend_(adm, key, descriptor, proxyTrap);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.extend_\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: createAction(key.toString(), descriptor.set)\n }, proxyTrap);\n } // other -> observable\n // if function respect autoBind option\n\n\n if (typeof descriptor.value === \"function\" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {\n var _adm$proxy_2;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);\n }\n\n var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;\n return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);\n}\n\nvar OBSERVABLE = \"observable\";\nvar OBSERVABLE_REF = \"observable.ref\";\nvar OBSERVABLE_SHALLOW = \"observable.shallow\";\nvar OBSERVABLE_STRUCT = \"observable.struct\"; // Predefined bags of create observable options, to avoid allocating temporarily option objects\n// in the majority of cases\n\nvar defaultCreateObservableOptions = {\n deep: true,\n name: undefined,\n defaultDecorator: undefined,\n proxy: true\n};\nObject.freeze(defaultCreateObservableOptions);\nfunction asCreateObservableOptions(thing) {\n return thing || defaultCreateObservableOptions;\n}\nvar observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);\nvar observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {\n enhancer: referenceEnhancer\n});\nvar observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {\n enhancer: shallowEnhancer\n});\nvar observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {\n enhancer: refStructEnhancer\n});\nvar observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);\nfunction getEnhancerFromOptions(options) {\n return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);\n}\nfunction getAnnotationFromOptions(options) {\n var _options$defaultDecor;\n\n return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;\n}\nfunction getEnhancerFromAnnotation(annotation) {\n var _annotation$options_$, _annotation$options_;\n\n return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;\n}\n/**\r\n * Turns an object, array or function into a reactive structure.\r\n * @param v the value which should become observable.\r\n */\n\nfunction createObservable(v, arg2, arg3) {\n // @observable someProp;\n if (isStringish(arg2)) {\n storeAnnotation(v, arg2, observableAnnotation);\n return;\n } // already observable - ignore\n\n\n if (isObservable(v)) {\n return v;\n } // plain object\n\n\n if (isPlainObject(v)) {\n return observable.object(v, arg2, arg3);\n } // Array\n\n\n if (Array.isArray(v)) {\n return observable.array(v, arg2);\n } // Map\n\n\n if (isES6Map(v)) {\n return observable.map(v, arg2);\n } // Set\n\n\n if (isES6Set(v)) {\n return observable.set(v, arg2);\n } // other object - ignore\n\n\n if (typeof v === \"object\" && v !== null) {\n return v;\n } // anything else\n\n\n return observable.box(v, arg2);\n}\n\nObject.assign(createObservable, observableDecoratorAnnotation);\nvar observableFactories = {\n box: function box(value, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);\n },\n array: function array(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);\n },\n map: function map(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);\n },\n set: function set(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);\n },\n object: function object(props, decorators, options) {\n return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);\n },\n ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),\n shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),\n deep: observableDecoratorAnnotation,\n struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)\n}; // eslint-disable-next-line\n\nvar observable = /*#__PURE__*/assign(createObservable, observableFactories);\n\nvar COMPUTED = \"computed\";\nvar COMPUTED_STRUCT = \"computed.struct\";\nvar computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);\nvar computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {\n equals: comparer.structural\n});\n/**\r\n * Decorator for class properties: @computed get value() { return expr; }.\r\n * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;\r\n */\n\nvar computed = function computed(arg1, arg2) {\n if (isStringish(arg2)) {\n // @computed\n return storeAnnotation(arg1, arg2, computedAnnotation);\n }\n\n if (isPlainObject(arg1)) {\n // @computed({ options })\n return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));\n } // computed(expr, options?)\n\n\n if (true) {\n if (!isFunction(arg1)) {\n die(\"First argument to `computed` should be an expression.\");\n }\n\n if (isFunction(arg2)) {\n die(\"A setter as second argument is no longer supported, use `{ set: fn }` option instead\");\n }\n }\n\n var opts = isPlainObject(arg2) ? arg2 : {};\n opts.get = arg1;\n opts.name || (opts.name = arg1.name || \"\");\n /* for generated name */\n\n return new ComputedValue(opts);\n};\nObject.assign(computed, computedAnnotation);\ncomputed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);\n\nvar _getDescriptor$config, _getDescriptor;\n// mobx versions\n\nvar currentActionId = 0;\nvar nextActionId = 1;\nvar isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, \"name\")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object\n\nvar tmpNameDescriptor = {\n value: \"action\",\n configurable: true,\n writable: false,\n enumerable: false\n};\nfunction createAction(actionName, fn, autoAction, ref) {\n if (autoAction === void 0) {\n autoAction = false;\n }\n\n if (true) {\n if (!isFunction(fn)) {\n die(\"`action` can only be invoked on functions\");\n }\n\n if (typeof actionName !== \"string\" || !actionName) {\n die(\"actions should have valid names, got: '\" + actionName + \"'\");\n }\n }\n\n function res() {\n return executeAction(actionName, autoAction, fn, ref || this, arguments);\n }\n\n res.isMobxAction = true;\n\n if (isFunctionNameConfigurable) {\n tmpNameDescriptor.value = actionName;\n Object.defineProperty(res, \"name\", tmpNameDescriptor);\n }\n\n return res;\n}\nfunction executeAction(actionName, canRunAsDerivation, fn, scope, args) {\n var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);\n\n try {\n return fn.apply(scope, args);\n } catch (err) {\n runInfo.error_ = err;\n throw err;\n } finally {\n _endAction(runInfo);\n }\n}\nfunction _startAction(actionName, canRunAsDerivation, // true for autoAction\nscope, args) {\n var notifySpy_ = true && isSpyEnabled() && !!actionName;\n var startTime_ = 0;\n\n if ( true && notifySpy_) {\n startTime_ = Date.now();\n var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;\n spyReportStart({\n type: ACTION,\n name: actionName,\n object: scope,\n arguments: flattenedArgs\n });\n }\n\n var prevDerivation_ = globalState.trackingDerivation;\n var runAsAction = !canRunAsDerivation || !prevDerivation_;\n startBatch();\n var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow\n\n if (runAsAction) {\n untrackedStart();\n prevAllowStateChanges_ = allowStateChangesStart(true);\n }\n\n var prevAllowStateReads_ = allowStateReadsStart(true);\n var runInfo = {\n runAsAction_: runAsAction,\n prevDerivation_: prevDerivation_,\n prevAllowStateChanges_: prevAllowStateChanges_,\n prevAllowStateReads_: prevAllowStateReads_,\n notifySpy_: notifySpy_,\n startTime_: startTime_,\n actionId_: nextActionId++,\n parentActionId_: currentActionId\n };\n currentActionId = runInfo.actionId_;\n return runInfo;\n}\nfunction _endAction(runInfo) {\n if (currentActionId !== runInfo.actionId_) {\n die(30);\n }\n\n currentActionId = runInfo.parentActionId_;\n\n if (runInfo.error_ !== undefined) {\n globalState.suppressReactionErrors = true;\n }\n\n allowStateChangesEnd(runInfo.prevAllowStateChanges_);\n allowStateReadsEnd(runInfo.prevAllowStateReads_);\n endBatch();\n\n if (runInfo.runAsAction_) {\n untrackedEnd(runInfo.prevDerivation_);\n }\n\n if ( true && runInfo.notifySpy_) {\n spyReportEnd({\n time: Date.now() - runInfo.startTime_\n });\n }\n\n globalState.suppressReactionErrors = false;\n}\nfunction allowStateChanges(allowStateChanges, func) {\n var prev = allowStateChangesStart(allowStateChanges);\n\n try {\n return func();\n } finally {\n allowStateChangesEnd(prev);\n }\n}\nfunction allowStateChangesStart(allowStateChanges) {\n var prev = globalState.allowStateChanges;\n globalState.allowStateChanges = allowStateChanges;\n return prev;\n}\nfunction allowStateChangesEnd(prev) {\n globalState.allowStateChanges = prev;\n}\n\nvar _Symbol$toPrimitive;\nvar CREATE = \"create\";\n_Symbol$toPrimitive = Symbol.toPrimitive;\nvar ObservableValue = /*#__PURE__*/function (_Atom) {\n _inheritsLoose(ObservableValue, _Atom);\n\n function ObservableValue(value, enhancer, name_, notifySpy, equals) {\n var _this;\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableValue@\" + getNextId() : undefined;\n }\n\n if (notifySpy === void 0) {\n notifySpy = true;\n }\n\n if (equals === void 0) {\n equals = comparer[\"default\"];\n }\n\n _this = _Atom.call(this, name_) || this;\n _this.enhancer = void 0;\n _this.name_ = void 0;\n _this.equals = void 0;\n _this.hasUnreportedChange_ = false;\n _this.interceptors_ = void 0;\n _this.changeListeners_ = void 0;\n _this.value_ = void 0;\n _this.dehancer = void 0;\n _this.enhancer = enhancer;\n _this.name_ = name_;\n _this.equals = equals;\n _this.value_ = enhancer(value, undefined, name_);\n\n if ( true && notifySpy && isSpyEnabled()) {\n // only notify spy if this is a stand-alone observable\n spyReport({\n type: CREATE,\n object: _assertThisInitialized(_this),\n observableKind: \"value\",\n debugObjectName: _this.name_,\n newValue: \"\" + _this.value_\n });\n }\n\n return _this;\n }\n\n var _proto = ObservableValue.prototype;\n\n _proto.dehanceValue = function dehanceValue(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.set = function set(newValue) {\n var oldValue = this.value_;\n newValue = this.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n\n if ( true && notifySpy) {\n spyReportStart({\n type: UPDATE,\n object: this,\n observableKind: \"value\",\n debugObjectName: this.name_,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n\n this.setNewValue_(newValue);\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.prepareNewValue_ = function prepareNewValue_(newValue) {\n checkIfStateModificationsAreAllowed(this);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this,\n type: UPDATE,\n newValue: newValue\n });\n\n if (!change) {\n return globalState.UNCHANGED;\n }\n\n newValue = change.newValue;\n } // apply modifier\n\n\n newValue = this.enhancer(newValue, this.value_, this.name_);\n return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;\n };\n\n _proto.setNewValue_ = function setNewValue_(newValue) {\n var oldValue = this.value_;\n this.value_ = newValue;\n this.reportChanged();\n\n if (hasListeners(this)) {\n notifyListeners(this, {\n type: UPDATE,\n object: this,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n };\n\n _proto.get = function get() {\n this.reportObserved();\n return this.dehanceValue(this.value_);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately) {\n listener({\n observableKind: \"value\",\n debugObjectName: this.name_,\n object: this,\n type: UPDATE,\n newValue: this.value_,\n oldValue: undefined\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.raw = function raw() {\n // used by MST ot get undehanced value\n return this.value_;\n };\n\n _proto.toJSON = function toJSON() {\n return this.get();\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.value_ + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive] = function () {\n return this.valueOf();\n };\n\n return ObservableValue;\n}(Atom);\nvar isObservableValue = /*#__PURE__*/createInstanceofPredicate(\"ObservableValue\", ObservableValue);\n\nvar _Symbol$toPrimitive$1;\n/**\r\n * A node in the state dependency root that observes other nodes, and can be observed itself.\r\n *\r\n * ComputedValue will remember the result of the computation for the duration of the batch, or\r\n * while being observed.\r\n *\r\n * During this time it will recompute only when one of its direct dependencies changed,\r\n * but only when it is being accessed with `ComputedValue.get()`.\r\n *\r\n * Implementation description:\r\n * 1. First time it's being accessed it will compute and remember result\r\n * give back remembered result until 2. happens\r\n * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.\r\n * 3. When it's being accessed, recompute if any shallow dependency changed.\r\n * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.\r\n * go to step 2. either way\r\n *\r\n * If at any point it's outside batch and it isn't observed: reset everything and go to 1.\r\n */\n\n_Symbol$toPrimitive$1 = Symbol.toPrimitive;\nvar ComputedValue = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n // during tracking it's an array with new observed observers\n // to check for cycles\n // N.B: unminified as it is used by MST\n\n /**\r\n * Create a new computed value based on a function expression.\r\n *\r\n * The `name` property is for debug purposes only.\r\n *\r\n * The `equals` property specifies the comparer function to use to determine if a newly produced\r\n * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`\r\n * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.\r\n * Structural comparison can be convenient if you always produce a new aggregated object and\r\n * don't want to notify observers if it is structurally the same.\r\n * This is useful for working with vectors, mouse coordinates etc.\r\n */\n function ComputedValue(options) {\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.observing_ = [];\n this.newObserving_ = null;\n this.isBeingObserved_ = false;\n this.isPendingUnobservation_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n this.unboundDepsCount_ = 0;\n this.value_ = new CaughtException(null);\n this.name_ = void 0;\n this.triggeredBy_ = void 0;\n this.isComputing_ = false;\n this.isRunningSetter_ = false;\n this.derivation = void 0;\n this.setter_ = void 0;\n this.isTracing_ = TraceMode.NONE;\n this.scope_ = void 0;\n this.equals_ = void 0;\n this.requiresReaction_ = void 0;\n this.keepAlive_ = void 0;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n\n if (!options.get) {\n die(31);\n }\n\n this.derivation = options.get;\n this.name_ = options.name || ( true ? \"ComputedValue@\" + getNextId() : undefined);\n\n if (options.set) {\n this.setter_ = createAction( true ? this.name_ + \"-setter\" : undefined, options.set);\n }\n\n this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer[\"default\"]);\n this.scope_ = options.context;\n this.requiresReaction_ = options.requiresReaction;\n this.keepAlive_ = !!options.keepAlive;\n }\n\n var _proto = ComputedValue.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n propagateMaybeChanged(this);\n };\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Returns the current value of this computed value.\r\n * Will evaluate its computation first if needed.\r\n */\n ;\n\n _proto.get = function get() {\n if (this.isComputing_) {\n die(32, this.name_, this.derivation);\n }\n\n if (globalState.inBatch === 0 && // !globalState.trackingDerivatpion &&\n this.observers_.size === 0 && !this.keepAlive_) {\n if (shouldCompute(this)) {\n this.warnAboutUntrackedRead_();\n startBatch(); // See perf test 'computed memoization'\n\n this.value_ = this.computeValue_(false);\n endBatch();\n }\n } else {\n reportObserved(this);\n\n if (shouldCompute(this)) {\n var prevTrackingContext = globalState.trackingContext;\n\n if (this.keepAlive_ && !prevTrackingContext) {\n globalState.trackingContext = this;\n }\n\n if (this.trackAndCompute()) {\n propagateChangeConfirmed(this);\n }\n\n globalState.trackingContext = prevTrackingContext;\n }\n }\n\n var result = this.value_;\n\n if (isCaughtException(result)) {\n throw result.cause;\n }\n\n return result;\n };\n\n _proto.set = function set(value) {\n if (this.setter_) {\n if (this.isRunningSetter_) {\n die(33, this.name_);\n }\n\n this.isRunningSetter_ = true;\n\n try {\n this.setter_.call(this.scope_, value);\n } finally {\n this.isRunningSetter_ = false;\n }\n } else {\n die(34, this.name_);\n }\n };\n\n _proto.trackAndCompute = function trackAndCompute() {\n // N.B: unminified as it is used by MST\n var oldValue = this.value_;\n var wasSuspended =\n /* see #1208 */\n this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;\n var newValue = this.computeValue_(true);\n var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);\n\n if (changed) {\n this.value_ = newValue;\n\n if ( true && isSpyEnabled()) {\n spyReport({\n observableKind: \"computed\",\n debugObjectName: this.name_,\n object: this.scope_,\n type: \"update\",\n oldValue: oldValue,\n newValue: newValue\n });\n }\n }\n\n return changed;\n };\n\n _proto.computeValue_ = function computeValue_(track) {\n this.isComputing_ = true; // don't allow state changes during computation\n\n var prev = allowStateChangesStart(false);\n var res;\n\n if (track) {\n res = trackDerivedFunction(this, this.derivation, this.scope_);\n } else {\n if (globalState.disableErrorBoundaries === true) {\n res = this.derivation.call(this.scope_);\n } else {\n try {\n res = this.derivation.call(this.scope_);\n } catch (e) {\n res = new CaughtException(e);\n }\n }\n }\n\n allowStateChangesEnd(prev);\n this.isComputing_ = false;\n return res;\n };\n\n _proto.suspend_ = function suspend_() {\n if (!this.keepAlive_) {\n clearObserving(this);\n this.value_ = undefined; // don't hold on to computed value!\n\n if ( true && this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' was suspended and it will recompute on the next access.\");\n }\n }\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n var _this = this;\n\n var firstTime = true;\n var prevValue = undefined;\n return autorun(function () {\n // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place\n var newValue = _this.get();\n\n if (!firstTime || fireImmediately) {\n var prevU = untrackedStart();\n listener({\n observableKind: \"computed\",\n debugObjectName: _this.name_,\n type: UPDATE,\n object: _this,\n newValue: newValue,\n oldValue: prevValue\n });\n untrackedEnd(prevU);\n }\n\n firstTime = false;\n prevValue = newValue;\n });\n };\n\n _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {\n if (false) {}\n\n if (this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n\n if (typeof this.requiresReaction_ === \"boolean\" ? this.requiresReaction_ : globalState.computedRequiresReaction) {\n console.warn(\"[mobx] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.derivation.toString() + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive$1] = function () {\n return this.valueOf();\n };\n\n return ComputedValue;\n}();\nvar isComputedValue = /*#__PURE__*/createInstanceofPredicate(\"ComputedValue\", ComputedValue);\n\nvar IDerivationState_;\n\n(function (IDerivationState_) {\n // before being run or (outside batch and not being observed)\n // at this point derivation is not holding any data about dependency tree\n IDerivationState_[IDerivationState_[\"NOT_TRACKING_\"] = -1] = \"NOT_TRACKING_\"; // no shallow dependency changed since last computation\n // won't recalculate derivation\n // this is what makes mobx fast\n\n IDerivationState_[IDerivationState_[\"UP_TO_DATE_\"] = 0] = \"UP_TO_DATE_\"; // some deep dependency changed, but don't know if shallow dependency changed\n // will require to check first if UP_TO_DATE or POSSIBLY_STALE\n // currently only ComputedValue will propagate POSSIBLY_STALE\n //\n // having this state is second big optimization:\n // don't have to recompute on every dependency change, but only when it's needed\n\n IDerivationState_[IDerivationState_[\"POSSIBLY_STALE_\"] = 1] = \"POSSIBLY_STALE_\"; // A shallow dependency has changed since last computation and the derivation\n // will need to recompute when it's needed next.\n\n IDerivationState_[IDerivationState_[\"STALE_\"] = 2] = \"STALE_\";\n})(IDerivationState_ || (IDerivationState_ = {}));\n\nvar TraceMode;\n\n(function (TraceMode) {\n TraceMode[TraceMode[\"NONE\"] = 0] = \"NONE\";\n TraceMode[TraceMode[\"LOG\"] = 1] = \"LOG\";\n TraceMode[TraceMode[\"BREAK\"] = 2] = \"BREAK\";\n})(TraceMode || (TraceMode = {}));\n\nvar CaughtException = function CaughtException(cause) {\n this.cause = void 0;\n this.cause = cause; // Empty\n};\nfunction isCaughtException(e) {\n return e instanceof CaughtException;\n}\n/**\r\n * Finds out whether any dependency of the derivation has actually changed.\r\n * If dependenciesState is 1 then it will recalculate dependencies,\r\n * if any dependency changed it will propagate it by changing dependenciesState to 2.\r\n *\r\n * By iterating over the dependencies in the same order that they were reported and\r\n * stopping on the first change, all the recalculations are only called for ComputedValues\r\n * that will be tracked by derivation. That is because we assume that if the first x\r\n * dependencies of the derivation doesn't change then the derivation should run the same way\r\n * up until accessing x-th dependency.\r\n */\n\nfunction shouldCompute(derivation) {\n switch (derivation.dependenciesState_) {\n case IDerivationState_.UP_TO_DATE_:\n return false;\n\n case IDerivationState_.NOT_TRACKING_:\n case IDerivationState_.STALE_:\n return true;\n\n case IDerivationState_.POSSIBLY_STALE_:\n {\n // state propagation can occur outside of action/reactive context #2195\n var prevAllowStateReads = allowStateReadsStart(true);\n var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.\n\n var obs = derivation.observing_,\n l = obs.length;\n\n for (var i = 0; i < l; i++) {\n var obj = obs[i];\n\n if (isComputedValue(obj)) {\n if (globalState.disableErrorBoundaries) {\n obj.get();\n } else {\n try {\n obj.get();\n } catch (e) {\n // we are not interested in the value *or* exception at this moment, but if there is one, notify all\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.\n // and `derivation` is an observer of `obj`\n // invariantShouldCompute(derivation)\n\n\n if (derivation.dependenciesState_ === IDerivationState_.STALE_) {\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n }\n\n changeDependenciesStateTo0(derivation);\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return false;\n }\n }\n}\nfunction isComputingDerivation() {\n return globalState.trackingDerivation !== null; // filter out actions inside computations\n}\nfunction checkIfStateModificationsAreAllowed(atom) {\n if (false) {}\n\n var hasObservers = atom.observers_.size > 0; // Should not be possible to change observed state outside strict mode, except during initialization, see #563\n\n if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === \"always\")) {\n console.warn(\"[MobX] \" + (globalState.enforceActions ? \"Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: \" : \"Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: \") + atom.name_);\n }\n}\nfunction checkIfStateReadsAreAllowed(observable) {\n if ( true && !globalState.allowStateReads && globalState.observableRequiresReaction) {\n console.warn(\"[mobx] Observable '\" + observable.name_ + \"' being read outside a reactive context.\");\n }\n}\n/**\r\n * Executes the provided function `f` and tracks which observables are being accessed.\r\n * The tracking information is stored on the `derivation` object and the derivation is registered\r\n * as observer of any of the accessed observables.\r\n */\n\nfunction trackDerivedFunction(derivation, f, context) {\n var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps\n // array will be trimmed by bindDependencies\n\n changeDependenciesStateTo0(derivation);\n derivation.newObserving_ = new Array(derivation.observing_.length + 100);\n derivation.unboundDepsCount_ = 0;\n derivation.runId_ = ++globalState.runId;\n var prevTracking = globalState.trackingDerivation;\n globalState.trackingDerivation = derivation;\n globalState.inBatch++;\n var result;\n\n if (globalState.disableErrorBoundaries === true) {\n result = f.call(context);\n } else {\n try {\n result = f.call(context);\n } catch (e) {\n result = new CaughtException(e);\n }\n }\n\n globalState.inBatch--;\n globalState.trackingDerivation = prevTracking;\n bindDependencies(derivation);\n warnAboutDerivationWithoutDependencies(derivation);\n allowStateReadsEnd(prevAllowStateReads);\n return result;\n}\n\nfunction warnAboutDerivationWithoutDependencies(derivation) {\n if (false) {}\n\n if (derivation.observing_.length !== 0) {\n return;\n }\n\n if (typeof derivation.requiresObservable_ === \"boolean\" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {\n console.warn(\"[mobx] Derivation '\" + derivation.name_ + \"' is created/updated without reading any observable value.\");\n }\n}\n/**\r\n * diffs newObserving with observing.\r\n * update observing to be newObserving with unique observables\r\n * notify observers that become observed/unobserved\r\n */\n\n\nfunction bindDependencies(derivation) {\n // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, \"INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1\");\n var prevObserving = derivation.observing_;\n var observing = derivation.observing_ = derivation.newObserving_;\n var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; // Go through all new observables and check diffValue: (this list can contain duplicates):\n // 0: first occurrence, change to 1 and keep it\n // 1: extra occurrence, drop it\n\n var i0 = 0,\n l = derivation.unboundDepsCount_;\n\n for (var i = 0; i < l; i++) {\n var dep = observing[i];\n\n if (dep.diffValue_ === 0) {\n dep.diffValue_ = 1;\n\n if (i0 !== i) {\n observing[i0] = dep;\n }\n\n i0++;\n } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,\n // not hitting the condition\n\n\n if (dep.dependenciesState_ > lowestNewObservingDerivationState) {\n lowestNewObservingDerivationState = dep.dependenciesState_;\n }\n }\n\n observing.length = i0;\n derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)\n // Go through all old observables and check diffValue: (it is unique after last bindDependencies)\n // 0: it's not in new observables, unobserve it\n // 1: it keeps being observed, don't want to notify it. change to 0\n\n l = prevObserving.length;\n\n while (l--) {\n var _dep = prevObserving[l];\n\n if (_dep.diffValue_ === 0) {\n removeObserver(_dep, derivation);\n }\n\n _dep.diffValue_ = 0;\n } // Go through all new observables and check diffValue: (now it should be unique)\n // 0: it was set to 0 in last loop. don't need to do anything.\n // 1: it wasn't observed, let's observe it. set back to 0\n\n\n while (i0--) {\n var _dep2 = observing[i0];\n\n if (_dep2.diffValue_ === 1) {\n _dep2.diffValue_ = 0;\n addObserver(_dep2, derivation);\n }\n } // Some new observed derivations may become stale during this derivation computation\n // so they have had no chance to propagate staleness (#916)\n\n\n if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {\n derivation.dependenciesState_ = lowestNewObservingDerivationState;\n derivation.onBecomeStale_();\n }\n}\n\nfunction clearObserving(derivation) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR clearObserving should be called only inside batch\");\n var obs = derivation.observing_;\n derivation.observing_ = [];\n var i = obs.length;\n\n while (i--) {\n removeObserver(obs[i], derivation);\n }\n\n derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n}\nfunction untracked(action) {\n var prev = untrackedStart();\n\n try {\n return action();\n } finally {\n untrackedEnd(prev);\n }\n}\nfunction untrackedStart() {\n var prev = globalState.trackingDerivation;\n globalState.trackingDerivation = null;\n return prev;\n}\nfunction untrackedEnd(prev) {\n globalState.trackingDerivation = prev;\n}\nfunction allowStateReadsStart(allowStateReads) {\n var prev = globalState.allowStateReads;\n globalState.allowStateReads = allowStateReads;\n return prev;\n}\nfunction allowStateReadsEnd(prev) {\n globalState.allowStateReads = prev;\n}\n/**\r\n * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0\r\n *\r\n */\n\nfunction changeDependenciesStateTo0(derivation) {\n if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;\n var obs = derivation.observing_;\n var i = obs.length;\n\n while (i--) {\n obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n}\n\n/**\r\n * These values will persist if global state is reset\r\n */\n\nvar persistentKeys = [\"mobxGuid\", \"spyListeners\", \"enforceActions\", \"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"allowStateReads\", \"disableErrorBoundaries\", \"runId\", \"UNCHANGED\", \"useProxies\"];\nvar MobXGlobals = function MobXGlobals() {\n this.version = 6;\n this.UNCHANGED = {};\n this.trackingDerivation = null;\n this.trackingContext = null;\n this.runId = 0;\n this.mobxGuid = 0;\n this.inBatch = 0;\n this.pendingUnobservations = [];\n this.pendingReactions = [];\n this.isRunningReactions = false;\n this.allowStateChanges = false;\n this.allowStateReads = true;\n this.enforceActions = true;\n this.spyListeners = [];\n this.globalReactionErrorHandlers = [];\n this.computedRequiresReaction = false;\n this.reactionRequiresObservable = false;\n this.observableRequiresReaction = false;\n this.disableErrorBoundaries = false;\n this.suppressReactionErrors = false;\n this.useProxies = true;\n this.verifyProxies = false;\n this.safeDescriptors = true;\n};\nvar canMergeGlobalState = true;\nvar isolateCalled = false;\nvar globalState = /*#__PURE__*/function () {\n var global = /*#__PURE__*/getGlobal();\n\n if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {\n canMergeGlobalState = false;\n }\n\n if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {\n canMergeGlobalState = false;\n }\n\n if (!canMergeGlobalState) {\n // Because this is a IIFE we need to let isolateCalled a chance to change\n // so we run it after the event loop completed at least 1 iteration\n setTimeout(function () {\n if (!isolateCalled) {\n die(35);\n }\n }, 1);\n return new MobXGlobals();\n } else if (global.__mobxGlobals) {\n global.__mobxInstanceCount += 1;\n\n if (!global.__mobxGlobals.UNCHANGED) {\n global.__mobxGlobals.UNCHANGED = {};\n } // make merge backward compatible\n\n\n return global.__mobxGlobals;\n } else {\n global.__mobxInstanceCount = 1;\n return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();\n }\n}();\nfunction isolateGlobalState() {\n if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {\n die(36);\n }\n\n isolateCalled = true;\n\n if (canMergeGlobalState) {\n var global = getGlobal();\n\n if (--global.__mobxInstanceCount === 0) {\n global.__mobxGlobals = undefined;\n }\n\n globalState = new MobXGlobals();\n }\n}\nfunction getGlobalState() {\n return globalState;\n}\n/**\r\n * For testing purposes only; this will break the internal state of existing observables,\r\n * but can be used to get back at a stable state after throwing errors\r\n */\n\nfunction resetGlobalState() {\n var defaultGlobals = new MobXGlobals();\n\n for (var key in defaultGlobals) {\n if (persistentKeys.indexOf(key) === -1) {\n globalState[key] = defaultGlobals[key];\n }\n }\n\n globalState.allowStateChanges = !globalState.enforceActions;\n}\n\nfunction hasObservers(observable) {\n return observable.observers_ && observable.observers_.size > 0;\n}\nfunction getObservers(observable) {\n return observable.observers_;\n} // function invariantObservers(observable: IObservable) {\n// const list = observable.observers\n// const map = observable.observersIndexes\n// const l = list.length\n// for (let i = 0; i < l; i++) {\n// const id = list[i].__mapid\n// if (i) {\n// invariant(map[id] === i, \"INTERNAL ERROR maps derivation.__mapid to index in list\") // for performance\n// } else {\n// invariant(!(id in map), \"INTERNAL ERROR observer on index 0 shouldn't be held in map.\") // for performance\n// }\n// }\n// invariant(\n// list.length === 0 || Object.keys(map).length === list.length - 1,\n// \"INTERNAL ERROR there is no junk in map\"\n// )\n// }\n\nfunction addObserver(observable, node) {\n // invariant(node.dependenciesState !== -1, \"INTERNAL ERROR, can add only dependenciesState !== -1\");\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR add already added node\");\n // invariantObservers(observable);\n observable.observers_.add(node);\n\n if (observable.lowestObserverState_ > node.dependenciesState_) {\n observable.lowestObserverState_ = node.dependenciesState_;\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR didn't add node\");\n\n}\nfunction removeObserver(observable, node) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR, remove should be called only inside batch\");\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR remove already removed node\");\n // invariantObservers(observable);\n observable.observers_[\"delete\"](node);\n\n if (observable.observers_.size === 0) {\n // deleting last observer\n queueForUnobservation(observable);\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR remove already removed node2\");\n\n}\nfunction queueForUnobservation(observable) {\n if (observable.isPendingUnobservation_ === false) {\n // invariant(observable._observers.length === 0, \"INTERNAL ERROR, should only queue for unobservation unobserved observables\");\n observable.isPendingUnobservation_ = true;\n globalState.pendingUnobservations.push(observable);\n }\n}\n/**\r\n * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.\r\n * During a batch `onBecomeUnobserved` will be called at most once per observable.\r\n * Avoids unnecessary recalculations.\r\n */\n\nfunction startBatch() {\n globalState.inBatch++;\n}\nfunction endBatch() {\n if (--globalState.inBatch === 0) {\n runReactions(); // the batch is actually about to finish, all unobserving should happen here.\n\n var list = globalState.pendingUnobservations;\n\n for (var i = 0; i < list.length; i++) {\n var observable = list[i];\n observable.isPendingUnobservation_ = false;\n\n if (observable.observers_.size === 0) {\n if (observable.isBeingObserved_) {\n // if this observable had reactive observers, trigger the hooks\n observable.isBeingObserved_ = false;\n observable.onBUO();\n }\n\n if (observable instanceof ComputedValue) {\n // computed values are automatically teared down when the last observer leaves\n // this process happens recursively, this computed might be the last observabe of another, etc..\n observable.suspend_();\n }\n }\n }\n\n globalState.pendingUnobservations = [];\n }\n}\nfunction reportObserved(observable) {\n checkIfStateReadsAreAllowed(observable);\n var derivation = globalState.trackingDerivation;\n\n if (derivation !== null) {\n /**\r\n * Simple optimization, give each derivation run an unique id (runId)\r\n * Check if last time this observable was accessed the same runId is used\r\n * if this is the case, the relation is already known\r\n */\n if (derivation.runId_ !== observable.lastAccessedBy_) {\n observable.lastAccessedBy_ = derivation.runId_; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...\n\n derivation.newObserving_[derivation.unboundDepsCount_++] = observable;\n\n if (!observable.isBeingObserved_ && globalState.trackingContext) {\n observable.isBeingObserved_ = true;\n observable.onBO();\n }\n }\n\n return observable.isBeingObserved_;\n } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {\n queueForUnobservation(observable);\n }\n\n return false;\n} // function invariantLOS(observable: IObservable, msg: string) {\n// // it's expensive so better not run it in produciton. but temporarily helpful for testing\n// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)\n// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`\n// throw new Error(\n// \"lowestObserverState is wrong for \" +\n// msg +\n// \" because \" +\n// min +\n// \" < \" +\n// observable.lowestObserverState\n// )\n// }\n\n/**\r\n * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly\r\n * It will propagate changes to observers from previous run\r\n * It's hard or maybe impossible (with reasonable perf) to get it right with current approach\r\n * Hopefully self reruning autoruns aren't a feature people should depend on\r\n * Also most basic use cases should be ok\r\n */\n// Called by Atom when its value changes\n\nfunction propagateChanged(observable) {\n // invariantLOS(observable, \"changed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_; // Ideally we use for..of here, but the downcompiled version is really slow...\n\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n\n d.onBecomeStale_();\n }\n\n d.dependenciesState_ = IDerivationState_.STALE_;\n }); // invariantLOS(observable, \"changed end\");\n} // Called by ComputedValue when it recalculate and its value changed\n\nfunction propagateChangeConfirmed(observable) {\n // invariantLOS(observable, \"confirmed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {\n d.dependenciesState_ = IDerivationState_.STALE_;\n\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.\n ) {\n observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n }); // invariantLOS(observable, \"confirmed end\");\n} // Used by computed when its dependency changed, but we don't wan't to immediately recompute.\n\nfunction propagateMaybeChanged(observable) {\n // invariantLOS(observable, \"maybe start\");\n if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;\n d.onBecomeStale_();\n }\n }); // invariantLOS(observable, \"maybe end\");\n}\n\nfunction logTraceInfo(derivation, observable) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' is invalidated due to a change in: '\" + observable.name_ + \"'\");\n\n if (derivation.isTracing_ === TraceMode.BREAK) {\n var lines = [];\n printDepTree(getDependencyTree(derivation), lines, 1); // prettier-ignore\n\n new Function(\"debugger;\\n/*\\nTracing '\" + derivation.name_ + \"'\\n\\nYou are entering this break point because derivation '\" + derivation.name_ + \"' is being traced and '\" + observable.name_ + \"' is now forcing it to update.\\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\\n\\n\" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\\//g, \"/\") : \"\") + \"\\n\\nThe dependencies for this derivation are:\\n\\n\" + lines.join(\"\\n\") + \"\\n*/\\n \")();\n }\n}\n\nfunction printDepTree(tree, lines, depth) {\n if (lines.length >= 1000) {\n lines.push(\"(and many more)\");\n return;\n }\n\n lines.push(\"\" + \"\\t\".repeat(depth - 1) + tree.name);\n\n if (tree.dependencies) {\n tree.dependencies.forEach(function (child) {\n return printDepTree(child, lines, depth + 1);\n });\n }\n}\n\nvar Reaction = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {\n if (name_ === void 0) {\n name_ = true ? \"Reaction@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.onInvalidate_ = void 0;\n this.errorHandler_ = void 0;\n this.requiresObservable_ = void 0;\n this.observing_ = [];\n this.newObserving_ = [];\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.unboundDepsCount_ = 0;\n this.isDisposed_ = false;\n this.isScheduled_ = false;\n this.isTrackPending_ = false;\n this.isRunning_ = false;\n this.isTracing_ = TraceMode.NONE;\n this.name_ = name_;\n this.onInvalidate_ = onInvalidate_;\n this.errorHandler_ = errorHandler_;\n this.requiresObservable_ = requiresObservable_;\n }\n\n var _proto = Reaction.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n this.schedule_();\n };\n\n _proto.schedule_ = function schedule_() {\n if (!this.isScheduled_) {\n this.isScheduled_ = true;\n globalState.pendingReactions.push(this);\n runReactions();\n }\n };\n\n _proto.isScheduled = function isScheduled() {\n return this.isScheduled_;\n }\n /**\r\n * internal, use schedule() if you intend to kick off a reaction\r\n */\n ;\n\n _proto.runReaction_ = function runReaction_() {\n if (!this.isDisposed_) {\n startBatch();\n this.isScheduled_ = false;\n var prev = globalState.trackingContext;\n globalState.trackingContext = this;\n\n if (shouldCompute(this)) {\n this.isTrackPending_ = true;\n\n try {\n this.onInvalidate_();\n\n if ( true && this.isTrackPending_ && isSpyEnabled()) {\n // onInvalidate didn't trigger track right away..\n spyReport({\n name: this.name_,\n type: \"scheduled-reaction\"\n });\n }\n } catch (e) {\n this.reportExceptionInDerivation_(e);\n }\n }\n\n globalState.trackingContext = prev;\n endBatch();\n }\n };\n\n _proto.track = function track(fn) {\n if (this.isDisposed_) {\n return; // console.warn(\"Reaction already disposed\") // Note: Not a warning / error in mobx 4 either\n }\n\n startBatch();\n var notify = isSpyEnabled();\n var startTime;\n\n if ( true && notify) {\n startTime = Date.now();\n spyReportStart({\n name: this.name_,\n type: \"reaction\"\n });\n }\n\n this.isRunning_ = true;\n var prevReaction = globalState.trackingContext; // reactions could create reactions...\n\n globalState.trackingContext = this;\n var result = trackDerivedFunction(this, fn, undefined);\n globalState.trackingContext = prevReaction;\n this.isRunning_ = false;\n this.isTrackPending_ = false;\n\n if (this.isDisposed_) {\n // disposed during last run. Clean up everything that was bound after the dispose call.\n clearObserving(this);\n }\n\n if (isCaughtException(result)) {\n this.reportExceptionInDerivation_(result.cause);\n }\n\n if ( true && notify) {\n spyReportEnd({\n time: Date.now() - startTime\n });\n }\n\n endBatch();\n };\n\n _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {\n var _this = this;\n\n if (this.errorHandler_) {\n this.errorHandler_(error, this);\n return;\n }\n\n if (globalState.disableErrorBoundaries) {\n throw error;\n }\n\n var message = true ? \"[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '\" + this + \"'\" : undefined;\n\n if (!globalState.suppressReactionErrors) {\n console.error(message, error);\n /** If debugging brought you here, please, read the above message :-). Tnx! */\n } else if (true) {\n console.warn(\"[mobx] (error in reaction '\" + this.name_ + \"' suppressed, fix error of causing action below)\");\n } // prettier-ignore\n\n\n if ( true && isSpyEnabled()) {\n spyReport({\n type: \"error\",\n name: this.name_,\n message: message,\n error: \"\" + error\n });\n }\n\n globalState.globalReactionErrorHandlers.forEach(function (f) {\n return f(error, _this);\n });\n };\n\n _proto.dispose = function dispose() {\n if (!this.isDisposed_) {\n this.isDisposed_ = true;\n\n if (!this.isRunning_) {\n // if disposed while running, clean up later. Maybe not optimal, but rare case\n startBatch();\n clearObserving(this);\n endBatch();\n }\n }\n };\n\n _proto.getDisposer_ = function getDisposer_() {\n var r = this.dispose.bind(this);\n r[$mobx] = this;\n return r;\n };\n\n _proto.toString = function toString() {\n return \"Reaction[\" + this.name_ + \"]\";\n };\n\n _proto.trace = function trace$1(enterBreakPoint) {\n if (enterBreakPoint === void 0) {\n enterBreakPoint = false;\n }\n\n trace(this, enterBreakPoint);\n };\n\n return Reaction;\n}();\nfunction onReactionError(handler) {\n globalState.globalReactionErrorHandlers.push(handler);\n return function () {\n var idx = globalState.globalReactionErrorHandlers.indexOf(handler);\n\n if (idx >= 0) {\n globalState.globalReactionErrorHandlers.splice(idx, 1);\n }\n };\n}\n/**\r\n * Magic number alert!\r\n * Defines within how many times a reaction is allowed to re-trigger itself\r\n * until it is assumed that this is gonna be a never ending loop...\r\n */\n\nvar MAX_REACTION_ITERATIONS = 100;\n\nvar reactionScheduler = function reactionScheduler(f) {\n return f();\n};\n\nfunction runReactions() {\n // Trampolining, if runReactions are already running, new reactions will be picked up\n if (globalState.inBatch > 0 || globalState.isRunningReactions) {\n return;\n }\n\n reactionScheduler(runReactionsHelper);\n}\n\nfunction runReactionsHelper() {\n globalState.isRunningReactions = true;\n var allReactions = globalState.pendingReactions;\n var iterations = 0; // While running reactions, new reactions might be triggered.\n // Hence we work with two variables and check whether\n // we converge to no remaining reactions after a while.\n\n while (allReactions.length > 0) {\n if (++iterations === MAX_REACTION_ITERATIONS) {\n console.error( true ? \"Reaction doesn't converge to a stable state after \" + MAX_REACTION_ITERATIONS + \" iterations.\" + (\" Probably there is a cycle in the reactive function: \" + allReactions[0]) : undefined);\n allReactions.splice(0); // clear reactions\n }\n\n var remainingReactions = allReactions.splice(0);\n\n for (var i = 0, l = remainingReactions.length; i < l; i++) {\n remainingReactions[i].runReaction_();\n }\n }\n\n globalState.isRunningReactions = false;\n}\n\nvar isReaction = /*#__PURE__*/createInstanceofPredicate(\"Reaction\", Reaction);\nfunction setReactionScheduler(fn) {\n var baseScheduler = reactionScheduler;\n\n reactionScheduler = function reactionScheduler(f) {\n return fn(function () {\n return baseScheduler(f);\n });\n };\n}\n\nfunction isSpyEnabled() {\n return true && !!globalState.spyListeners.length;\n}\nfunction spyReport(event) {\n if (false) {} // dead code elimination can do the rest\n\n\n if (!globalState.spyListeners.length) {\n return;\n }\n\n var listeners = globalState.spyListeners;\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](event);\n }\n}\nfunction spyReportStart(event) {\n if (false) {}\n\n var change = _extends({}, event, {\n spyReportStart: true\n });\n\n spyReport(change);\n}\nvar END_EVENT = {\n type: \"report-end\",\n spyReportEnd: true\n};\nfunction spyReportEnd(change) {\n if (false) {}\n\n if (change) {\n spyReport(_extends({}, change, {\n type: \"report-end\",\n spyReportEnd: true\n }));\n } else {\n spyReport(END_EVENT);\n }\n}\nfunction spy(listener) {\n if (false) {} else {\n globalState.spyListeners.push(listener);\n return once(function () {\n globalState.spyListeners = globalState.spyListeners.filter(function (l) {\n return l !== listener;\n });\n });\n }\n}\n\nvar ACTION = \"action\";\nvar ACTION_BOUND = \"action.bound\";\nvar AUTOACTION = \"autoAction\";\nvar AUTOACTION_BOUND = \"autoAction.bound\";\nvar DEFAULT_ACTION_NAME = \"\";\nvar actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);\nvar actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {\n bound: true\n});\nvar autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {\n autoAction: true\n});\nvar autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {\n autoAction: true,\n bound: true\n});\n\nfunction createActionFactory(autoAction) {\n var res = function action(arg1, arg2) {\n // action(fn() {})\n if (isFunction(arg1)) {\n return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);\n } // action(\"name\", fn() {})\n\n\n if (isFunction(arg2)) {\n return createAction(arg1, arg2, autoAction);\n } // @action\n\n\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);\n } // action(\"name\") & @action(\"name\")\n\n\n if (isStringish(arg1)) {\n return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {\n name: arg1,\n autoAction: autoAction\n }));\n }\n\n if (true) {\n die(\"Invalid arguments for `action`\");\n }\n };\n\n return res;\n}\n\nvar action = /*#__PURE__*/createActionFactory(false);\nObject.assign(action, actionAnnotation);\nvar autoAction = /*#__PURE__*/createActionFactory(true);\nObject.assign(autoAction, autoActionAnnotation);\naction.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);\nautoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);\nfunction runInAction(fn) {\n return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);\n}\nfunction isAction(thing) {\n return isFunction(thing) && thing.isMobxAction === true;\n}\n\n/**\r\n * Creates a named reactive view and keeps it alive, so that the view is always\r\n * updated if one of the dependencies changes, even when the view is not further used by something else.\r\n * @param view The reactive view\r\n * @returns disposer function, which can be used to stop the view from being updated in the future.\r\n */\n\nfunction autorun(view, opts) {\n var _opts$name, _opts;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(view)) {\n die(\"Autorun expects a function as first argument\");\n }\n\n if (isAction(view)) {\n die(\"Autorun does not accept actions since actions are untrackable\");\n }\n }\n\n var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : true ? view.name || \"Autorun@\" + getNextId() : undefined;\n var runSync = !opts.scheduler && !opts.delay;\n var reaction;\n\n if (runSync) {\n // normal autorun\n reaction = new Reaction(name, function () {\n this.track(reactionRunner);\n }, opts.onError, opts.requiresObservable);\n } else {\n var scheduler = createSchedulerFromOptions(opts); // debounced autorun\n\n var isScheduled = false;\n reaction = new Reaction(name, function () {\n if (!isScheduled) {\n isScheduled = true;\n scheduler(function () {\n isScheduled = false;\n\n if (!reaction.isDisposed_) {\n reaction.track(reactionRunner);\n }\n });\n }\n }, opts.onError, opts.requiresObservable);\n }\n\n function reactionRunner() {\n view(reaction);\n }\n\n reaction.schedule_();\n return reaction.getDisposer_();\n}\n\nvar run = function run(f) {\n return f();\n};\n\nfunction createSchedulerFromOptions(opts) {\n return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {\n return setTimeout(f, opts.delay);\n } : run;\n}\n\nfunction reaction(expression, effect, opts) {\n var _opts$name2;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(expression) || !isFunction(effect)) {\n die(\"First and second argument to reaction should be functions\");\n }\n\n if (!isPlainObject(opts)) {\n die(\"Third argument of reactions should be an object\");\n }\n }\n\n var name = (_opts$name2 = opts.name) != null ? _opts$name2 : true ? \"Reaction@\" + getNextId() : undefined;\n var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);\n var runSync = !opts.scheduler && !opts.delay;\n var scheduler = createSchedulerFromOptions(opts);\n var firstTime = true;\n var isScheduled = false;\n var value;\n var oldValue;\n var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer[\"default\"];\n var r = new Reaction(name, function () {\n if (firstTime || runSync) {\n reactionRunner();\n } else if (!isScheduled) {\n isScheduled = true;\n scheduler(reactionRunner);\n }\n }, opts.onError, opts.requiresObservable);\n\n function reactionRunner() {\n isScheduled = false;\n\n if (r.isDisposed_) {\n return;\n }\n\n var changed = false;\n r.track(function () {\n var nextValue = allowStateChanges(false, function () {\n return expression(r);\n });\n changed = firstTime || !equals(value, nextValue);\n oldValue = value;\n value = nextValue;\n });\n\n if (firstTime && opts.fireImmediately) {\n effectAction(value, oldValue, r);\n } else if (!firstTime && changed) {\n effectAction(value, oldValue, r);\n }\n\n firstTime = false;\n }\n\n r.schedule_();\n return r.getDisposer_();\n}\n\nfunction wrapErrorHandler(errorHandler, baseFn) {\n return function () {\n try {\n return baseFn.apply(this, arguments);\n } catch (e) {\n errorHandler.call(this, e);\n }\n };\n}\n\nvar ON_BECOME_OBSERVED = \"onBO\";\nvar ON_BECOME_UNOBSERVED = \"onBUO\";\nfunction onBecomeObserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);\n}\nfunction onBecomeUnobserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);\n}\n\nfunction interceptHook(hook, thing, arg2, arg3) {\n var atom = typeof arg3 === \"function\" ? getAtom(thing, arg2) : getAtom(thing);\n var cb = isFunction(arg3) ? arg3 : arg2;\n var listenersKey = hook + \"L\";\n\n if (atom[listenersKey]) {\n atom[listenersKey].add(cb);\n } else {\n atom[listenersKey] = new Set([cb]);\n }\n\n return function () {\n var hookListeners = atom[listenersKey];\n\n if (hookListeners) {\n hookListeners[\"delete\"](cb);\n\n if (hookListeners.size === 0) {\n delete atom[listenersKey];\n }\n }\n };\n}\n\nvar NEVER = \"never\";\nvar ALWAYS = \"always\";\nvar OBSERVED = \"observed\"; // const IF_AVAILABLE = \"ifavailable\"\n\nfunction configure(options) {\n if (options.isolateGlobalState === true) {\n isolateGlobalState();\n }\n\n var useProxies = options.useProxies,\n enforceActions = options.enforceActions;\n\n if (useProxies !== undefined) {\n globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== \"undefined\";\n }\n\n if (useProxies === \"ifavailable\") {\n globalState.verifyProxies = true;\n }\n\n if (enforceActions !== undefined) {\n var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;\n globalState.enforceActions = ea;\n globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;\n }\n [\"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"disableErrorBoundaries\", \"safeDescriptors\"].forEach(function (key) {\n if (key in options) {\n globalState[key] = !!options[key];\n }\n });\n globalState.allowStateReads = !globalState.observableRequiresReaction;\n\n if ( true && globalState.disableErrorBoundaries === true) {\n console.warn(\"WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.\");\n }\n\n if (options.reactionScheduler) {\n setReactionScheduler(options.reactionScheduler);\n }\n}\n\nfunction extendObservable(target, properties, annotations, options) {\n if (true) {\n if (arguments.length > 4) {\n die(\"'extendObservable' expected 2-4 arguments\");\n }\n\n if (typeof target !== \"object\") {\n die(\"'extendObservable' expects an object as first argument\");\n }\n\n if (isObservableMap(target)) {\n die(\"'extendObservable' should not be used on maps, use map.merge instead\");\n }\n\n if (!isPlainObject(properties)) {\n die(\"'extendObservable' only accepts plain objects as second argument\");\n }\n\n if (isObservable(properties) || isObservable(annotations)) {\n die(\"Extending an object with another observable (object) is not supported\");\n }\n } // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)\n\n\n var descriptors = getOwnPropertyDescriptors(properties);\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n ownKeys(descriptors).forEach(function (key) {\n adm.extend_(key, descriptors[key], // must pass \"undefined\" for { key: undefined }\n !annotations ? true : key in annotations ? annotations[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nfunction getDependencyTree(thing, property) {\n return nodeToDependencyTree(getAtom(thing, property));\n}\n\nfunction nodeToDependencyTree(node) {\n var result = {\n name: node.name_\n };\n\n if (node.observing_ && node.observing_.length > 0) {\n result.dependencies = unique(node.observing_).map(nodeToDependencyTree);\n }\n\n return result;\n}\n\nfunction getObserverTree(thing, property) {\n return nodeToObserverTree(getAtom(thing, property));\n}\n\nfunction nodeToObserverTree(node) {\n var result = {\n name: node.name_\n };\n\n if (hasObservers(node)) {\n result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);\n }\n\n return result;\n}\n\nfunction unique(list) {\n return Array.from(new Set(list));\n}\n\nvar generatorId = 0;\nfunction FlowCancellationError() {\n this.message = \"FLOW_CANCELLED\";\n}\nFlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);\nfunction isFlowCancellationError(error) {\n return error instanceof FlowCancellationError;\n}\nvar flowAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow\");\nvar flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow.bound\", {\n bound: true\n});\nvar flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {\n // @flow\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, flowAnnotation);\n } // flow(fn)\n\n\n if ( true && arguments.length !== 1) {\n die(\"Flow expects single argument with generator function\");\n }\n\n var generator = arg1;\n var name = generator.name || \"\"; // Implementation based on https://github.com/tj/co/blob/master/index.js\n\n var res = function res() {\n var ctx = this;\n var args = arguments;\n var runId = ++generatorId;\n var gen = action(name + \" - runid: \" + runId + \" - init\", generator).apply(ctx, args);\n var rejector;\n var pendingPromise = undefined;\n var promise = new Promise(function (resolve, reject) {\n var stepId = 0;\n rejector = reject;\n\n function onFulfilled(res) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen.next).call(gen, res);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function onRejected(err) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen[\"throw\"]).call(gen, err);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function next(ret) {\n if (isFunction(ret == null ? void 0 : ret.then)) {\n // an async iterator\n ret.then(next, reject);\n return;\n }\n\n if (ret.done) {\n return resolve(ret.value);\n }\n\n pendingPromise = Promise.resolve(ret.value);\n return pendingPromise.then(onFulfilled, onRejected);\n }\n\n onFulfilled(undefined); // kick off the process\n });\n promise.cancel = action(name + \" - runid: \" + runId + \" - cancel\", function () {\n try {\n if (pendingPromise) {\n cancelPromise(pendingPromise);\n } // Finally block can return (or yield) stuff..\n\n\n var _res = gen[\"return\"](undefined); // eat anything that promise would do, it's cancelled!\n\n\n var yieldedPromise = Promise.resolve(_res.value);\n yieldedPromise.then(noop, noop);\n cancelPromise(yieldedPromise); // maybe it can be cancelled :)\n // reject our original promise\n\n rejector(new FlowCancellationError());\n } catch (e) {\n rejector(e); // there could be a throwing finally block\n }\n });\n return promise;\n };\n\n res.isMobXFlow = true;\n return res;\n}, flowAnnotation);\nflow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);\n\nfunction cancelPromise(promise) {\n if (isFunction(promise.cancel)) {\n promise.cancel();\n }\n}\n\nfunction flowResult(result) {\n return result; // just tricking TypeScript :)\n}\nfunction isFlow(fn) {\n return (fn == null ? void 0 : fn.isMobXFlow) === true;\n}\n\nfunction interceptReads(thing, propOrHandler, handler) {\n var target;\n\n if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {\n target = getAdministration(thing);\n } else if (isObservableObject(thing)) {\n if ( true && !isStringish(propOrHandler)) {\n return die(\"InterceptReads can only be used with a specific property, not with an object in general\");\n }\n\n target = getAdministration(thing, propOrHandler);\n } else if (true) {\n return die(\"Expected observable map, object or array as first array\");\n }\n\n if ( true && target.dehancer !== undefined) {\n return die(\"An intercept reader was already established\");\n }\n\n target.dehancer = typeof propOrHandler === \"function\" ? propOrHandler : handler;\n return function () {\n target.dehancer = undefined;\n };\n}\n\nfunction intercept(thing, propOrHandler, handler) {\n if (isFunction(handler)) {\n return interceptProperty(thing, propOrHandler, handler);\n } else {\n return interceptInterceptable(thing, propOrHandler);\n }\n}\n\nfunction interceptInterceptable(thing, handler) {\n return getAdministration(thing).intercept_(handler);\n}\n\nfunction interceptProperty(thing, property, handler) {\n return getAdministration(thing, property).intercept_(handler);\n}\n\nfunction _isComputed(value, property) {\n if (property === undefined) {\n return isComputedValue(value);\n }\n\n if (isObservableObject(value) === false) {\n return false;\n }\n\n if (!value[$mobx].values_.has(property)) {\n return false;\n }\n\n var atom = getAtom(value, property);\n return isComputedValue(atom);\n}\nfunction isComputed(value) {\n if ( true && arguments.length > 1) {\n return die(\"isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property\");\n }\n\n return _isComputed(value);\n}\nfunction isComputedProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"isComputed expected a property name as second argument\");\n }\n\n return _isComputed(value, propName);\n}\n\nfunction _isObservable(value, property) {\n if (!value) {\n return false;\n }\n\n if (property !== undefined) {\n if ( true && (isObservableMap(value) || isObservableArray(value))) {\n return die(\"isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.\");\n }\n\n if (isObservableObject(value)) {\n return value[$mobx].values_.has(property);\n }\n\n return false;\n } // For first check, see #701\n\n\n return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);\n}\n\nfunction isObservable(value) {\n if ( true && arguments.length !== 1) {\n die(\"isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property\");\n }\n\n return _isObservable(value);\n}\nfunction isObservableProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"expected a property name as second argument\");\n }\n\n return _isObservable(value, propName);\n}\n\nfunction keys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].keys_();\n }\n\n if (isObservableMap(obj) || isObservableSet(obj)) {\n return Array.from(obj.keys());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (_, index) {\n return index;\n });\n }\n\n die(5);\n}\nfunction values(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return obj[key];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return obj.get(key);\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.values());\n }\n\n if (isObservableArray(obj)) {\n return obj.slice();\n }\n\n die(6);\n}\nfunction entries(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj.get(key)];\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.entries());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (key, index) {\n return [index, key];\n });\n }\n\n die(7);\n}\nfunction set(obj, key, value) {\n if (arguments.length === 2 && !isObservableSet(obj)) {\n startBatch();\n var _values = key;\n\n try {\n for (var _key in _values) {\n set(obj, _key, _values[_key]);\n }\n } finally {\n endBatch();\n }\n\n return;\n }\n\n if (isObservableObject(obj)) {\n obj[$mobx].set_(key, value);\n } else if (isObservableMap(obj)) {\n obj.set(key, value);\n } else if (isObservableSet(obj)) {\n obj.add(key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n if (key < 0) {\n die(\"Invalid index: '\" + key + \"'\");\n }\n\n startBatch();\n\n if (key >= obj.length) {\n obj.length = key + 1;\n }\n\n obj[key] = value;\n endBatch();\n } else {\n die(8);\n }\n}\nfunction remove(obj, key) {\n if (isObservableObject(obj)) {\n obj[$mobx].delete_(key);\n } else if (isObservableMap(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableSet(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n obj.splice(key, 1);\n } else {\n die(9);\n }\n}\nfunction has(obj, key) {\n if (isObservableObject(obj)) {\n return obj[$mobx].has_(key);\n } else if (isObservableMap(obj)) {\n return obj.has(key);\n } else if (isObservableSet(obj)) {\n return obj.has(key);\n } else if (isObservableArray(obj)) {\n return key >= 0 && key < obj.length;\n }\n\n die(10);\n}\nfunction get(obj, key) {\n if (!has(obj, key)) {\n return undefined;\n }\n\n if (isObservableObject(obj)) {\n return obj[$mobx].get_(key);\n } else if (isObservableMap(obj)) {\n return obj.get(key);\n } else if (isObservableArray(obj)) {\n return obj[key];\n }\n\n die(11);\n}\nfunction apiDefineProperty(obj, key, descriptor) {\n if (isObservableObject(obj)) {\n return obj[$mobx].defineProperty_(key, descriptor);\n }\n\n die(39);\n}\nfunction apiOwnKeys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].ownKeys_();\n }\n\n die(38);\n}\n\nfunction observe(thing, propOrCb, cbOrFire, fireImmediately) {\n if (isFunction(cbOrFire)) {\n return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);\n } else {\n return observeObservable(thing, propOrCb, cbOrFire);\n }\n}\n\nfunction observeObservable(thing, listener, fireImmediately) {\n return getAdministration(thing).observe_(listener, fireImmediately);\n}\n\nfunction observeObservableProperty(thing, property, listener, fireImmediately) {\n return getAdministration(thing, property).observe_(listener, fireImmediately);\n}\n\nfunction cache(map, key, value) {\n map.set(key, value);\n return value;\n}\n\nfunction toJSHelper(source, __alreadySeen) {\n if (source == null || typeof source !== \"object\" || source instanceof Date || !isObservable(source)) {\n return source;\n }\n\n if (isObservableValue(source) || isComputedValue(source)) {\n return toJSHelper(source.get(), __alreadySeen);\n }\n\n if (__alreadySeen.has(source)) {\n return __alreadySeen.get(source);\n }\n\n if (isObservableArray(source)) {\n var res = cache(__alreadySeen, source, new Array(source.length));\n source.forEach(function (value, idx) {\n res[idx] = toJSHelper(value, __alreadySeen);\n });\n return res;\n }\n\n if (isObservableSet(source)) {\n var _res = cache(__alreadySeen, source, new Set());\n\n source.forEach(function (value) {\n _res.add(toJSHelper(value, __alreadySeen));\n });\n return _res;\n }\n\n if (isObservableMap(source)) {\n var _res2 = cache(__alreadySeen, source, new Map());\n\n source.forEach(function (value, key) {\n _res2.set(key, toJSHelper(value, __alreadySeen));\n });\n return _res2;\n } else {\n // must be observable object\n var _res3 = cache(__alreadySeen, source, {});\n\n apiOwnKeys(source).forEach(function (key) {\n if (objectPrototype.propertyIsEnumerable.call(source, key)) {\n _res3[key] = toJSHelper(source[key], __alreadySeen);\n }\n });\n return _res3;\n }\n}\n/**\r\n * Recursively converts an observable to it's non-observable native counterpart.\r\n * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.\r\n * Computed and other non-enumerable properties are completely ignored.\r\n * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.\r\n */\n\n\nfunction toJS(source, options) {\n if ( true && options) {\n die(\"toJS no longer supports options\");\n }\n\n return toJSHelper(source, new Map());\n}\n\nfunction trace() {\n if (false) {}\n\n var enterBreakPoint = false;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (typeof args[args.length - 1] === \"boolean\") {\n enterBreakPoint = args.pop();\n }\n\n var derivation = getAtomFromArgs(args);\n\n if (!derivation) {\n return die(\"'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly\");\n }\n\n if (derivation.isTracing_ === TraceMode.NONE) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' tracing enabled\");\n }\n\n derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;\n}\n\nfunction getAtomFromArgs(args) {\n switch (args.length) {\n case 0:\n return globalState.trackingDerivation;\n\n case 1:\n return getAtom(args[0]);\n\n case 2:\n return getAtom(args[0], args[1]);\n }\n}\n\n/**\r\n * During a transaction no views are updated until the end of the transaction.\r\n * The transaction will be run synchronously nonetheless.\r\n *\r\n * @param action a function that updates some reactive state\r\n * @returns any value that was returned by the 'action' parameter.\r\n */\n\nfunction transaction(action, thisArg) {\n if (thisArg === void 0) {\n thisArg = undefined;\n }\n\n startBatch();\n\n try {\n return action.apply(thisArg);\n } finally {\n endBatch();\n }\n}\n\nfunction when(predicate, arg1, arg2) {\n if (arguments.length === 1 || arg1 && typeof arg1 === \"object\") {\n return whenPromise(predicate, arg1);\n }\n\n return _when(predicate, arg1, arg2 || {});\n}\n\nfunction _when(predicate, effect, opts) {\n var timeoutHandle;\n\n if (typeof opts.timeout === \"number\") {\n var error = new Error(\"WHEN_TIMEOUT\");\n timeoutHandle = setTimeout(function () {\n if (!disposer[$mobx].isDisposed_) {\n disposer();\n\n if (opts.onError) {\n opts.onError(error);\n } else {\n throw error;\n }\n }\n }, opts.timeout);\n }\n\n opts.name = true ? opts.name || \"When@\" + getNextId() : undefined;\n var effectAction = createAction( true ? opts.name + \"-effect\" : undefined, effect); // eslint-disable-next-line\n\n var disposer = autorun(function (r) {\n // predicate should not change state\n var cond = allowStateChanges(false, predicate);\n\n if (cond) {\n r.dispose();\n\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n\n effectAction();\n }\n }, opts);\n return disposer;\n}\n\nfunction whenPromise(predicate, opts) {\n var _opts$signal;\n\n if ( true && opts && opts.onError) {\n return die(\"the options 'onError' and 'promise' cannot be combined\");\n }\n\n if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {\n return Object.assign(Promise.reject(new Error(\"WHEN_ABORTED\")), {\n cancel: function cancel() {\n return null;\n }\n });\n }\n\n var cancel;\n var abort;\n var res = new Promise(function (resolve, reject) {\n var _opts$signal2;\n\n var disposer = _when(predicate, resolve, _extends({}, opts, {\n onError: reject\n }));\n\n cancel = function cancel() {\n disposer();\n reject(new Error(\"WHEN_CANCELLED\"));\n };\n\n abort = function abort() {\n disposer();\n reject(new Error(\"WHEN_ABORTED\"));\n };\n\n opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener(\"abort\", abort);\n })[\"finally\"](function () {\n var _opts$signal3;\n\n return opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener(\"abort\", abort);\n });\n res.cancel = cancel;\n return res;\n}\n\nfunction getAdm(target) {\n return target[$mobx];\n} // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,\n// and skip either the internal values map, or the base object with its property descriptors!\n\n\nvar objectProxyTraps = {\n has: function has(target, name) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.\");\n }\n\n return getAdm(target).has_(name);\n },\n get: function get(target, name) {\n return getAdm(target).get_(name);\n },\n set: function set(target, name, value) {\n var _getAdm$set_;\n\n if (!isStringish(name)) {\n return false;\n }\n\n if ( true && !getAdm(target).values_.has(name)) {\n warnAboutProxyRequirement(\"add a new observable property through direct assignment. Use 'set' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;\n },\n deleteProperty: function deleteProperty(target, name) {\n var _getAdm$delete_;\n\n if (true) {\n warnAboutProxyRequirement(\"delete properties from an observable object. Use 'remove' from 'mobx' instead.\");\n }\n\n if (!isStringish(name)) {\n return false;\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;\n },\n defineProperty: function defineProperty(target, name, descriptor) {\n var _getAdm$definePropert;\n\n if (true) {\n warnAboutProxyRequirement(\"define property on an observable object. Use 'defineProperty' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;\n },\n ownKeys: function ownKeys(target) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.\");\n }\n\n return getAdm(target).ownKeys_();\n },\n preventExtensions: function preventExtensions(target) {\n die(13);\n }\n};\nfunction asDynamicObservableObject(target, options) {\n var _target$$mobx, _target$$mobx$proxy_;\n\n assertProxies();\n target = asObservableObject(target, options);\n return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);\n}\n\nfunction hasInterceptors(interceptable) {\n return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;\n}\nfunction registerInterceptor(interceptable, handler) {\n var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);\n interceptors.push(handler);\n return once(function () {\n var idx = interceptors.indexOf(handler);\n\n if (idx !== -1) {\n interceptors.splice(idx, 1);\n }\n });\n}\nfunction interceptChange(interceptable, change) {\n var prevU = untrackedStart();\n\n try {\n // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950\n var interceptors = [].concat(interceptable.interceptors_ || []);\n\n for (var i = 0, l = interceptors.length; i < l; i++) {\n change = interceptors[i](change);\n\n if (change && !change.type) {\n die(14);\n }\n\n if (!change) {\n break;\n }\n }\n\n return change;\n } finally {\n untrackedEnd(prevU);\n }\n}\n\nfunction hasListeners(listenable) {\n return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;\n}\nfunction registerListener(listenable, handler) {\n var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);\n listeners.push(handler);\n return once(function () {\n var idx = listeners.indexOf(handler);\n\n if (idx !== -1) {\n listeners.splice(idx, 1);\n }\n });\n}\nfunction notifyListeners(listenable, change) {\n var prevU = untrackedStart();\n var listeners = listenable.changeListeners_;\n\n if (!listeners) {\n return;\n }\n\n listeners = listeners.slice();\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](change);\n }\n\n untrackedEnd(prevU);\n}\n\nfunction makeObservable(target, annotations, options) {\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n var _annotations;\n\n if ( true && annotations && target[storedAnnotationsSymbol]) {\n die(\"makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.\");\n } // Default to decorators\n\n\n (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target); // Annotate\n\n ownKeys(annotations).forEach(function (key) {\n return adm.make_(key, annotations[key]);\n });\n } finally {\n endBatch();\n }\n\n return target;\n} // proto[keysSymbol] = new Set()\n\nvar keysSymbol = /*#__PURE__*/Symbol(\"mobx-keys\");\nfunction makeAutoObservable(target, overrides, options) {\n if (true) {\n if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {\n die(\"'makeAutoObservable' can only be used for classes that don't have a superclass\");\n }\n\n if (isObservableObject(target)) {\n die(\"makeAutoObservable can only be used on objects not already made observable\");\n }\n } // Optimization: avoid visiting protos\n // Assumes that annotation.make_/.extend_ works the same for plain objects\n\n\n if (isPlainObject(target)) {\n return extendObservable(target, target, overrides, options);\n }\n\n var adm = asObservableObject(target, options)[$mobx]; // Optimization: cache keys on proto\n // Assumes makeAutoObservable can be called only once per object and can't be used in subclass\n\n if (!target[keysSymbol]) {\n var proto = Object.getPrototypeOf(target);\n var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));\n keys[\"delete\"](\"constructor\");\n keys[\"delete\"]($mobx);\n addHiddenProp(proto, keysSymbol, keys);\n }\n\n startBatch();\n\n try {\n target[keysSymbol].forEach(function (key) {\n return adm.make_(key, // must pass \"undefined\" for { key: undefined }\n !overrides ? true : key in overrides ? overrides[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nvar SPLICE = \"splice\";\nvar UPDATE = \"update\";\nvar MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859\n\nvar arrayTraps = {\n get: function get(target, name) {\n var adm = target[$mobx];\n\n if (name === $mobx) {\n return adm;\n }\n\n if (name === \"length\") {\n return adm.getArrayLength_();\n }\n\n if (typeof name === \"string\" && !isNaN(name)) {\n return adm.get_(parseInt(name));\n }\n\n if (hasProp(arrayExtensions, name)) {\n return arrayExtensions[name];\n }\n\n return target[name];\n },\n set: function set(target, name, value) {\n var adm = target[$mobx];\n\n if (name === \"length\") {\n adm.setArrayLength_(value);\n }\n\n if (typeof name === \"symbol\" || isNaN(name)) {\n target[name] = value;\n } else {\n // numeric string\n adm.set_(parseInt(name), value);\n }\n\n return true;\n },\n preventExtensions: function preventExtensions() {\n die(15);\n }\n};\nvar ObservableArrayAdministration = /*#__PURE__*/function () {\n // this is the prop that gets proxied, so can't replace it!\n function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n this.owned_ = void 0;\n this.legacyMode_ = void 0;\n this.atom_ = void 0;\n this.values_ = [];\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.enhancer_ = void 0;\n this.dehancer = void 0;\n this.proxy_ = void 0;\n this.lastKnownLength_ = 0;\n this.owned_ = owned_;\n this.legacyMode_ = legacyMode_;\n this.atom_ = new Atom(name);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, true ? name + \"[..]\" : undefined);\n };\n }\n\n var _proto = ObservableArrayAdministration.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.dehanceValues_ = function dehanceValues_(values) {\n if (this.dehancer !== undefined && values.length > 0) {\n return values.map(this.dehancer);\n }\n\n return values;\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately === void 0) {\n fireImmediately = false;\n }\n\n if (fireImmediately) {\n listener({\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: \"splice\",\n index: 0,\n added: this.values_.slice(),\n addedCount: this.values_.length,\n removed: [],\n removedCount: 0\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.getArrayLength_ = function getArrayLength_() {\n this.atom_.reportObserved();\n return this.values_.length;\n };\n\n _proto.setArrayLength_ = function setArrayLength_(newLength) {\n if (typeof newLength !== \"number\" || isNaN(newLength) || newLength < 0) {\n die(\"Out of range: \" + newLength);\n }\n\n var currentLength = this.values_.length;\n\n if (newLength === currentLength) {\n return;\n } else if (newLength > currentLength) {\n var newItems = new Array(newLength - currentLength);\n\n for (var i = 0; i < newLength - currentLength; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n this.spliceWithArray_(currentLength, 0, newItems);\n } else {\n this.spliceWithArray_(newLength, currentLength - newLength);\n }\n };\n\n _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {\n if (oldLength !== this.lastKnownLength_) {\n die(16);\n }\n\n this.lastKnownLength_ += delta;\n\n if (this.legacyMode_ && delta > 0) {\n reserveArrayBuffer(oldLength + delta + 1);\n }\n };\n\n _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {\n var _this = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n var length = this.values_.length;\n\n if (index === undefined) {\n index = 0;\n } else if (index > length) {\n index = length;\n } else if (index < 0) {\n index = Math.max(0, length + index);\n }\n\n if (arguments.length === 1) {\n deleteCount = length - index;\n } else if (deleteCount === undefined || deleteCount === null) {\n deleteCount = 0;\n } else {\n deleteCount = Math.max(0, Math.min(deleteCount, length - index));\n }\n\n if (newItems === undefined) {\n newItems = EMPTY_ARRAY;\n }\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_,\n type: SPLICE,\n index: index,\n removedCount: deleteCount,\n added: newItems\n });\n\n if (!change) {\n return EMPTY_ARRAY;\n }\n\n deleteCount = change.removedCount;\n newItems = change.added;\n }\n\n newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {\n return _this.enhancer_(v, undefined);\n });\n\n if (this.legacyMode_ || \"development\" !== \"production\") {\n var lengthDelta = newItems.length - deleteCount;\n this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified\n }\n\n var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);\n\n if (deleteCount !== 0 || newItems.length !== 0) {\n this.notifyArraySplice_(index, newItems, res);\n }\n\n return this.dehanceValues_(res);\n };\n\n _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {\n if (newItems.length < MAX_SPLICE_SIZE) {\n var _this$values_;\n\n return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));\n } else {\n // The items removed by the splice\n var res = this.values_.slice(index, index + deleteCount); // The items that that should remain at the end of the array\n\n var oldItems = this.values_.slice(index + deleteCount); // New length is the previous length + addition count - deletion count\n\n this.values_.length += newItems.length - deleteCount;\n\n for (var i = 0; i < newItems.length; i++) {\n this.values_[index + i] = newItems[i];\n }\n\n for (var _i = 0; _i < oldItems.length; _i++) {\n this.values_[index + newItems.length + _i] = oldItems[_i];\n }\n\n return res;\n }\n };\n\n _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n type: UPDATE,\n debugObjectName: this.atom_.name_,\n index: index,\n newValue: newValue,\n oldValue: oldValue\n } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't\n // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged();\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: SPLICE,\n index: index,\n removed: removed,\n added: added,\n removedCount: removed.length,\n addedCount: added.length\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get_ = function get_(index) {\n if (this.legacyMode_ && index >= this.values_.length) {\n console.warn( true ? \"[mobx.array] Attempt to read an array index (\" + index + \") that is out of bounds (\" + this.values_.length + \"). Please check length first. Out of bound indices will not be tracked by MobX\" : undefined);\n return undefined;\n }\n\n this.atom_.reportObserved();\n return this.dehanceValue_(this.values_[index]);\n };\n\n _proto.set_ = function set_(index, newValue) {\n var values = this.values_;\n\n if (this.legacyMode_ && index > values.length) {\n // out of bounds\n die(17, index, values.length);\n }\n\n if (index < values.length) {\n // update at index in range\n checkIfStateModificationsAreAllowed(this.atom_);\n var oldValue = values[index];\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_,\n index: index,\n newValue: newValue\n });\n\n if (!change) {\n return;\n }\n\n newValue = change.newValue;\n }\n\n newValue = this.enhancer_(newValue, oldValue);\n var changed = newValue !== oldValue;\n\n if (changed) {\n values[index] = newValue;\n this.notifyArrayChildUpdate_(index, newValue, oldValue);\n }\n } else {\n // For out of bound index, we don't create an actual sparse array,\n // but rather fill the holes with undefined (same as setArrayLength_).\n // This could be considered a bug.\n var newItems = new Array(index + 1 - values.length);\n\n for (var i = 0; i < newItems.length - 1; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n newItems[newItems.length - 1] = newValue;\n this.spliceWithArray_(values.length, 0, newItems);\n }\n };\n\n return ObservableArrayAdministration;\n}();\nfunction createObservableArray(initialValues, enhancer, name, owned) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n assertProxies();\n var adm = new ObservableArrayAdministration(name, enhancer, owned, false);\n addHiddenFinalProp(adm.values_, $mobx, adm);\n var proxy = new Proxy(adm.values_, arrayTraps);\n adm.proxy_ = proxy;\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true);\n adm.spliceWithArray_(0, 0, initialValues);\n allowStateChangesEnd(prev);\n }\n\n return proxy;\n} // eslint-disable-next-line\n\nvar arrayExtensions = {\n clear: function clear() {\n return this.splice(0);\n },\n replace: function replace(newItems) {\n var adm = this[$mobx];\n return adm.spliceWithArray_(0, adm.values_.length, newItems);\n },\n // Used by JSON.stringify\n toJSON: function toJSON() {\n return this.slice();\n },\n\n /*\r\n * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)\r\n * since these functions alter the inner structure of the array, the have side effects.\r\n * Because the have side effects, they should not be used in computed function,\r\n * and for that reason the do not call dependencyState.notifyObserved\r\n */\n splice: function splice(index, deleteCount) {\n for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n newItems[_key - 2] = arguments[_key];\n }\n\n var adm = this[$mobx];\n\n switch (arguments.length) {\n case 0:\n return [];\n\n case 1:\n return adm.spliceWithArray_(index);\n\n case 2:\n return adm.spliceWithArray_(index, deleteCount);\n }\n\n return adm.spliceWithArray_(index, deleteCount, newItems);\n },\n spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {\n return this[$mobx].spliceWithArray_(index, deleteCount, newItems);\n },\n push: function push() {\n var adm = this[$mobx];\n\n for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n items[_key2] = arguments[_key2];\n }\n\n adm.spliceWithArray_(adm.values_.length, 0, items);\n return adm.values_.length;\n },\n pop: function pop() {\n return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];\n },\n shift: function shift() {\n return this.splice(0, 1)[0];\n },\n unshift: function unshift() {\n var adm = this[$mobx];\n\n for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n items[_key3] = arguments[_key3];\n }\n\n adm.spliceWithArray_(0, 0, items);\n return adm.values_.length;\n },\n reverse: function reverse() {\n // reverse by default mutates in place before returning the result\n // which makes it both a 'derivation' and a 'mutation'.\n if (globalState.trackingDerivation) {\n die(37, \"reverse\");\n }\n\n this.replace(this.slice().reverse());\n return this;\n },\n sort: function sort() {\n // sort by default mutates in place before returning the result\n // which goes against all good practices. Let's not change the array in place!\n if (globalState.trackingDerivation) {\n die(37, \"sort\");\n }\n\n var copy = this.slice();\n copy.sort.apply(copy, arguments);\n this.replace(copy);\n return this;\n },\n remove: function remove(value) {\n var adm = this[$mobx];\n var idx = adm.dehanceValues_(adm.values_).indexOf(value);\n\n if (idx > -1) {\n this.splice(idx, 1);\n return true;\n }\n\n return false;\n }\n};\n/**\r\n * Wrap function from prototype\r\n * Without this, everything works as well, but this works\r\n * faster as everything works on unproxied values\r\n */\n\naddArrayExtension(\"concat\", simpleFunc);\naddArrayExtension(\"flat\", simpleFunc);\naddArrayExtension(\"includes\", simpleFunc);\naddArrayExtension(\"indexOf\", simpleFunc);\naddArrayExtension(\"join\", simpleFunc);\naddArrayExtension(\"lastIndexOf\", simpleFunc);\naddArrayExtension(\"slice\", simpleFunc);\naddArrayExtension(\"toString\", simpleFunc);\naddArrayExtension(\"toLocaleString\", simpleFunc); // map\n\naddArrayExtension(\"every\", mapLikeFunc);\naddArrayExtension(\"filter\", mapLikeFunc);\naddArrayExtension(\"find\", mapLikeFunc);\naddArrayExtension(\"findIndex\", mapLikeFunc);\naddArrayExtension(\"flatMap\", mapLikeFunc);\naddArrayExtension(\"forEach\", mapLikeFunc);\naddArrayExtension(\"map\", mapLikeFunc);\naddArrayExtension(\"some\", mapLikeFunc); // reduce\n\naddArrayExtension(\"reduce\", reduceLikeFunc);\naddArrayExtension(\"reduceRight\", reduceLikeFunc);\n\nfunction addArrayExtension(funcName, funcFactory) {\n if (typeof Array.prototype[funcName] === \"function\") {\n arrayExtensions[funcName] = funcFactory(funcName);\n }\n} // Report and delegate to dehanced array\n\n\nfunction simpleFunc(funcName) {\n return function () {\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction mapLikeFunc(funcName) {\n return function (callback, thisArg) {\n var _this2 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName](function (element, index) {\n return callback.call(thisArg, element, index, _this2);\n });\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction reduceLikeFunc(funcName) {\n return function () {\n var _this3 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_); // #2432 - reduce behavior depends on arguments.length\n\n var callback = arguments[0];\n\n arguments[0] = function (accumulator, currentValue, index) {\n return callback(accumulator, currentValue, index, _this3);\n };\n\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\n\nvar isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableArrayAdministration\", ObservableArrayAdministration);\nfunction isObservableArray(thing) {\n return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);\n}\n\nvar _Symbol$iterator, _Symbol$toStringTag;\nvar ObservableMapMarker = {};\nvar ADD = \"add\";\nvar DELETE = \"delete\"; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54\n// But: https://github.com/mobxjs/mobx/issues/1556\n\n_Symbol$iterator = Symbol.iterator;\n_Symbol$toStringTag = Symbol.toStringTag;\nvar ObservableMap = /*#__PURE__*/function () {\n // hasMap, not hashMap >-).\n function ObservableMap(initialData, enhancer_, name_) {\n var _this = this;\n\n if (enhancer_ === void 0) {\n enhancer_ = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableMap@\" + getNextId() : undefined;\n }\n\n this.enhancer_ = void 0;\n this.name_ = void 0;\n this[$mobx] = ObservableMapMarker;\n this.data_ = void 0;\n this.hasMap_ = void 0;\n this.keysAtom_ = void 0;\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = enhancer_;\n this.name_ = name_;\n\n if (!isFunction(Map)) {\n die(18);\n }\n\n this.keysAtom_ = createAtom( true ? this.name_ + \".keys()\" : undefined);\n this.data_ = new Map();\n this.hasMap_ = new Map();\n allowStateChanges(true, function () {\n _this.merge(initialData);\n });\n }\n\n var _proto = ObservableMap.prototype;\n\n _proto.has_ = function has_(key) {\n return this.data_.has(key);\n };\n\n _proto.has = function has(key) {\n var _this2 = this;\n\n if (!globalState.trackingDerivation) {\n return this.has_(key);\n }\n\n var entry = this.hasMap_.get(key);\n\n if (!entry) {\n var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.hasMap_.set(key, newEntry);\n onBecomeUnobserved(newEntry, function () {\n return _this2.hasMap_[\"delete\"](key);\n });\n }\n\n return entry.get();\n };\n\n _proto.set = function set(key, value) {\n var hasKey = this.has_(key);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: hasKey ? UPDATE : ADD,\n object: this,\n newValue: value,\n name: key\n });\n\n if (!change) {\n return this;\n }\n\n value = change.newValue;\n }\n\n if (hasKey) {\n this.updateValue_(key, value);\n } else {\n this.addValue_(key, value);\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(key) {\n var _this3 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n name: key\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has_(key)) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: this.data_.get(key).value_,\n name: key\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n } // TODO fix type\n\n\n transaction(function () {\n var _this3$hasMap_$get;\n\n _this3.keysAtom_.reportChanged();\n\n (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false);\n\n var observable = _this3.data_.get(key);\n\n observable.setNewValue_(undefined);\n\n _this3.data_[\"delete\"](key);\n });\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.updateValue_ = function updateValue_(key, newValue) {\n var observable = this.data_.get(key);\n newValue = observable.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: UPDATE,\n object: this,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.addValue_ = function addValue_(key, newValue) {\n var _this4 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n transaction(function () {\n var _this4$hasMap_$get;\n\n var observable = new ObservableValue(newValue, _this4.enhancer_, true ? _this4.name_ + \".\" + stringifyKey(key) : undefined, false);\n\n _this4.data_.set(key, observable);\n\n newValue = observable.value_; // value might have been changed\n\n (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true);\n\n _this4.keysAtom_.reportChanged();\n });\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get = function get(key) {\n if (this.has(key)) {\n return this.dehanceValue_(this.data_.get(key).get());\n }\n\n return this.dehanceValue_(undefined);\n };\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.keys = function keys() {\n this.keysAtom_.reportObserved();\n return this.data_.keys();\n };\n\n _proto.values = function values() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next = keys.next(),\n done = _keys$next.done,\n value = _keys$next.value;\n\n return {\n done: done,\n value: done ? undefined : self.get(value)\n };\n }\n });\n };\n\n _proto.entries = function entries() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next2 = keys.next(),\n done = _keys$next2.done,\n value = _keys$next2.value;\n\n return {\n done: done,\n value: done ? undefined : [value, self.get(value)]\n };\n }\n });\n };\n\n _proto[_Symbol$iterator] = function () {\n return this.entries();\n };\n\n _proto.forEach = function forEach(callback, thisArg) {\n for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {\n var _step$value = _step.value,\n key = _step$value[0],\n value = _step$value[1];\n callback.call(thisArg, value, key, this);\n }\n }\n /** Merge another object into this object, returns this. */\n ;\n\n _proto.merge = function merge(other) {\n var _this5 = this;\n\n if (isObservableMap(other)) {\n other = new Map(other);\n }\n\n transaction(function () {\n if (isPlainObject(other)) {\n getPlainObjectKeys(other).forEach(function (key) {\n return _this5.set(key, other[key]);\n });\n } else if (Array.isArray(other)) {\n other.forEach(function (_ref) {\n var key = _ref[0],\n value = _ref[1];\n return _this5.set(key, value);\n });\n } else if (isES6Map(other)) {\n if (other.constructor !== Map) {\n die(19, other);\n }\n\n other.forEach(function (value, key) {\n return _this5.set(key, value);\n });\n } else if (other !== null && other !== undefined) {\n die(20, other);\n }\n });\n return this;\n };\n\n _proto.clear = function clear() {\n var _this6 = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {\n var key = _step2.value;\n\n _this6[\"delete\"](key);\n }\n });\n });\n };\n\n _proto.replace = function replace(values) {\n var _this7 = this;\n\n // Implementation requirements:\n // - respect ordering of replacement map\n // - allow interceptors to run and potentially prevent individual operations\n // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)\n // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)\n // - note that result map may differ from replacement map due to the interceptors\n transaction(function () {\n // Convert to map so we can do quick key lookups\n var replacementMap = convertToMap(values);\n var orderedData = new Map(); // Used for optimization\n\n var keysReportChangedCalled = false; // Delete keys that don't exist in replacement map\n // if the key deletion is prevented by interceptor\n // add entry at the beginning of the result map\n\n for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {\n var key = _step3.value;\n\n // Concurrently iterating/deleting keys\n // iterator should handle this correctly\n if (!replacementMap.has(key)) {\n var deleted = _this7[\"delete\"](key); // Was the key removed?\n\n\n if (deleted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n } else {\n // Delete prevented by interceptor\n var value = _this7.data_.get(key);\n\n orderedData.set(key, value);\n }\n }\n } // Merge entries\n\n\n for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {\n var _step4$value = _step4.value,\n _key = _step4$value[0],\n _value = _step4$value[1];\n\n // We will want to know whether a new key is added\n var keyExisted = _this7.data_.has(_key); // Add or update value\n\n\n _this7.set(_key, _value); // The addition could have been prevent by interceptor\n\n\n if (_this7.data_.has(_key)) {\n // The update could have been prevented by interceptor\n // and also we want to preserve existing values\n // so use value from _data map (instead of replacement map)\n var _value2 = _this7.data_.get(_key);\n\n orderedData.set(_key, _value2); // Was a new key added?\n\n if (!keyExisted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n }\n }\n } // Check for possible key order change\n\n\n if (!keysReportChangedCalled) {\n if (_this7.data_.size !== orderedData.size) {\n // If size differs, keys are definitely modified\n _this7.keysAtom_.reportChanged();\n } else {\n var iter1 = _this7.data_.keys();\n\n var iter2 = orderedData.keys();\n var next1 = iter1.next();\n var next2 = iter2.next();\n\n while (!next1.done) {\n if (next1.value !== next2.value) {\n _this7.keysAtom_.reportChanged();\n\n break;\n }\n\n next1 = iter1.next();\n next2 = iter2.next();\n }\n }\n } // Use correctly ordered map\n\n\n _this7.data_ = orderedData;\n });\n return this;\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableMap]\";\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with maps.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _createClass(ObservableMap, [{\n key: \"size\",\n get: function get() {\n this.keysAtom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Map\";\n }\n }]);\n\n return ObservableMap;\n}(); // eslint-disable-next-line\n\nvar isObservableMap = /*#__PURE__*/createInstanceofPredicate(\"ObservableMap\", ObservableMap);\n\nfunction convertToMap(dataStructure) {\n if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {\n return dataStructure;\n } else if (Array.isArray(dataStructure)) {\n return new Map(dataStructure);\n } else if (isPlainObject(dataStructure)) {\n var map = new Map();\n\n for (var key in dataStructure) {\n map.set(key, dataStructure[key]);\n }\n\n return map;\n } else {\n return die(21, dataStructure);\n }\n}\n\nvar _Symbol$iterator$1, _Symbol$toStringTag$1;\nvar ObservableSetMarker = {};\n_Symbol$iterator$1 = Symbol.iterator;\n_Symbol$toStringTag$1 = Symbol.toStringTag;\nvar ObservableSet = /*#__PURE__*/function () {\n function ObservableSet(initialData, enhancer, name_) {\n if (enhancer === void 0) {\n enhancer = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableSet@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this[$mobx] = ObservableSetMarker;\n this.data_ = new Set();\n this.atom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = void 0;\n this.name_ = name_;\n\n if (!isFunction(Set)) {\n die(22);\n }\n\n this.atom_ = createAtom(this.name_);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, name_);\n };\n\n if (initialData) {\n this.replace(initialData);\n }\n }\n\n var _proto = ObservableSet.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.clear = function clear() {\n var _this = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) {\n var value = _step.value;\n\n _this[\"delete\"](value);\n }\n });\n });\n };\n\n _proto.forEach = function forEach(callbackFn, thisArg) {\n for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {\n var value = _step2.value;\n callbackFn.call(thisArg, value, value, this);\n }\n };\n\n _proto.add = function add(value) {\n var _this2 = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: ADD,\n object: this,\n newValue: value\n });\n\n if (!change) {\n return this;\n } // ideally, value = change.value would be done here, so that values can be\n // changed by interceptor. Same applies for other Set and Map api's.\n\n }\n\n if (!this.has(value)) {\n transaction(function () {\n _this2.data_.add(_this2.enhancer_(value, undefined));\n\n _this2.atom_.reportChanged();\n });\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n newValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change);\n }\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(value) {\n var _this3 = this;\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n oldValue: value\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has(value)) {\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change2 = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change2);\n }\n\n transaction(function () {\n _this3.atom_.reportChanged();\n\n _this3.data_[\"delete\"](value);\n });\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.has = function has(value) {\n this.atom_.reportObserved();\n return this.data_.has(this.dehanceValue_(value));\n };\n\n _proto.entries = function entries() {\n var nextIndex = 0;\n var keys = Array.from(this.keys());\n var values = Array.from(this.values());\n return makeIterable({\n next: function next() {\n var index = nextIndex;\n nextIndex += 1;\n return index < values.length ? {\n value: [keys[index], values[index]],\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.keys = function keys() {\n return this.values();\n };\n\n _proto.values = function values() {\n this.atom_.reportObserved();\n var self = this;\n var nextIndex = 0;\n var observableValues = Array.from(this.data_.values());\n return makeIterable({\n next: function next() {\n return nextIndex < observableValues.length ? {\n value: self.dehanceValue_(observableValues[nextIndex++]),\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.replace = function replace(other) {\n var _this4 = this;\n\n if (isObservableSet(other)) {\n other = new Set(other);\n }\n\n transaction(function () {\n if (Array.isArray(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (isES6Set(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (other !== null && other !== undefined) {\n die(\"Cannot initialize set from \" + other);\n }\n });\n return this;\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n // ... 'fireImmediately' could also be true?\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with sets.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableSet]\";\n };\n\n _proto[_Symbol$iterator$1] = function () {\n return this.values();\n };\n\n _createClass(ObservableSet, [{\n key: \"size\",\n get: function get() {\n this.atom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag$1,\n get: function get() {\n return \"Set\";\n }\n }]);\n\n return ObservableSet;\n}(); // eslint-disable-next-line\n\nvar isObservableSet = /*#__PURE__*/createInstanceofPredicate(\"ObservableSet\", ObservableSet);\n\nvar descriptorCache = /*#__PURE__*/Object.create(null);\nvar REMOVE = \"remove\";\nvar ObservableObjectAdministration = /*#__PURE__*/function () {\n function ObservableObjectAdministration(target_, values_, name_, // Used anytime annotation is not explicitely provided\n defaultAnnotation_) {\n if (values_ === void 0) {\n values_ = new Map();\n }\n\n if (defaultAnnotation_ === void 0) {\n defaultAnnotation_ = autoAnnotation;\n }\n\n this.target_ = void 0;\n this.values_ = void 0;\n this.name_ = void 0;\n this.defaultAnnotation_ = void 0;\n this.keysAtom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.proxy_ = void 0;\n this.isPlainObject_ = void 0;\n this.appliedAnnotations_ = void 0;\n this.pendingKeys_ = void 0;\n this.target_ = target_;\n this.values_ = values_;\n this.name_ = name_;\n this.defaultAnnotation_ = defaultAnnotation_;\n this.keysAtom_ = new Atom( true ? this.name_ + \".keys\" : undefined); // Optimization: we use this frequently\n\n this.isPlainObject_ = isPlainObject(this.target_);\n\n if ( true && !isAnnotation(this.defaultAnnotation_)) {\n die(\"defaultAnnotation must be valid annotation\");\n }\n\n if (true) {\n // Prepare structure for tracking which fields were already annotated\n this.appliedAnnotations_ = {};\n }\n }\n\n var _proto = ObservableObjectAdministration.prototype;\n\n _proto.getObservablePropValue_ = function getObservablePropValue_(key) {\n return this.values_.get(key).get();\n };\n\n _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {\n var observable = this.values_.get(key);\n\n if (observable instanceof ComputedValue) {\n observable.set(newValue);\n return true;\n } // intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: newValue\n });\n\n if (!change) {\n return null;\n }\n\n newValue = change.newValue;\n }\n\n newValue = observable.prepareNewValue_(newValue); // notify spy & observers\n\n if (newValue !== globalState.UNCHANGED) {\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n var _change = notify || notifySpy ? {\n type: UPDATE,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n }\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n return true;\n };\n\n _proto.get_ = function get_(key) {\n if (globalState.trackingDerivation && !hasProp(this.target_, key)) {\n // Key doesn't exist yet, subscribe for it in case it's added later\n this.has_(key);\n }\n\n return this.target_[key];\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {any} value\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.set_ = function set_(key, value, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // Don't use .has(key) - we care about own\n if (hasProp(this.target_, key)) {\n // Existing prop\n if (this.values_.has(key)) {\n // Observable (can be intercepted)\n return this.setObservablePropValue_(key, value);\n } else if (proxyTrap) {\n // Non-observable - proxy\n return Reflect.set(this.target_, key, value);\n } else {\n // Non-observable\n this.target_[key] = value;\n return true;\n }\n } else {\n // New prop\n return this.extend_(key, {\n value: value,\n enumerable: true,\n writable: true,\n configurable: true\n }, this.defaultAnnotation_, proxyTrap);\n }\n } // Trap for \"in\"\n ;\n\n _proto.has_ = function has_(key) {\n if (!globalState.trackingDerivation) {\n // Skip key subscription outside derivation\n return key in this.target_;\n }\n\n this.pendingKeys_ || (this.pendingKeys_ = new Map());\n var entry = this.pendingKeys_.get(key);\n\n if (!entry) {\n entry = new ObservableValue(key in this.target_, referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.pendingKeys_.set(key, entry);\n }\n\n return entry.get();\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop\r\n */\n ;\n\n _proto.make_ = function make_(key, annotation) {\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return;\n }\n\n assertAnnotable(this, annotation, key);\n\n if (!(key in this.target_)) {\n var _this$target_$storedA;\n\n // Throw on missing key, except for decorators:\n // Decorator annotations are collected from whole prototype chain.\n // When called from super() some props may not exist yet.\n // However we don't have to worry about missing prop,\n // because the decorator must have been applied to something.\n if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {\n return; // will be annotated by subclass constructor\n } else {\n die(1, annotation.annotationType_, this.name_ + \".\" + key.toString());\n }\n }\n\n var source = this.target_;\n\n while (source && source !== objectPrototype) {\n var descriptor = getDescriptor(source, key);\n\n if (descriptor) {\n var outcome = annotation.make_(this, key, descriptor, source);\n\n if (outcome === 0\n /* Cancel */\n ) {\n return;\n }\n\n if (outcome === 1\n /* Break */\n ) {\n break;\n }\n }\n\n source = Object.getPrototypeOf(source);\n }\n\n recordAnnotationApplied(this, annotation, key);\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return this.defineProperty_(key, descriptor, proxyTrap);\n }\n\n assertAnnotable(this, annotation, key);\n var outcome = annotation.extend_(this, key, descriptor, proxyTrap);\n\n if (outcome) {\n recordAnnotationApplied(this, annotation, key);\n }\n\n return outcome;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: descriptor.value\n });\n\n if (!change) {\n return null;\n }\n\n var newValue = change.newValue;\n\n if (descriptor.value !== newValue) {\n descriptor = _extends({}, descriptor, {\n value: newValue\n });\n }\n } // Define\n\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n } // Notify\n\n\n this.notifyPropertyAddition_(key, descriptor.value);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: value\n });\n\n if (!change) {\n return null;\n }\n\n value = change.newValue;\n }\n\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: true,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n var observable = new ObservableValue(value, enhancer, true ? this.name_ + \".\" + key.toString() : undefined, false);\n this.values_.set(key, observable); // Notify (value possibly changed by ObservableValue)\n\n this.notifyPropertyAddition_(key, observable.value_);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: undefined\n });\n\n if (!change) {\n return null;\n }\n }\n\n options.name || (options.name = true ? this.name_ + \".\" + key.toString() : undefined);\n options.context = this.proxy_ || this.target_;\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: false,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n this.values_.set(key, new ComputedValue(options)); // Notify\n\n this.notifyPropertyAddition_(key, undefined);\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.delete_ = function delete_(key, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // No such prop\n if (!hasProp(this.target_, key)) {\n return true;\n } // Intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: REMOVE\n }); // Cancelled\n\n if (!change) {\n return null;\n }\n } // Delete\n\n\n try {\n var _this$pendingKeys_, _this$pendingKeys_$ge;\n\n startBatch();\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n var observable = this.values_.get(key); // Value needed for spies/listeners\n\n var value = undefined; // Optimization: don't pull the value unless we will need it\n\n if (!observable && (notify || notifySpy)) {\n var _getDescriptor;\n\n value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;\n } // delete prop (do first, may fail)\n\n\n if (proxyTrap) {\n if (!Reflect.deleteProperty(this.target_, key)) {\n return false;\n }\n } else {\n delete this.target_[key];\n } // Allow re-annotating this field\n\n\n if (true) {\n delete this.appliedAnnotations_[key];\n } // Clear observable\n\n\n if (observable) {\n this.values_[\"delete\"](key); // for computed, value is undefined\n\n if (observable instanceof ObservableValue) {\n value = observable.value_;\n } // Notify: autorun(() => obj[key]), see #1796\n\n\n propagateChanged(observable);\n } // Notify \"keys/entries/values\" observers\n\n\n this.keysAtom_.reportChanged(); // Notify \"has\" observers\n // \"in\" as it may still exist in proto\n\n (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_); // Notify spies/listeners\n\n if (notify || notifySpy) {\n var _change2 = {\n type: REMOVE,\n observableKind: \"object\",\n object: this.proxy_ || this.target_,\n debugObjectName: this.name_,\n oldValue: value,\n name: key\n };\n\n if ( true && notifySpy) {\n spyReportStart(_change2);\n }\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n ;\n\n _proto.observe_ = function observe_(callback, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support the fire immediately property for observable objects.\");\n }\n\n return registerListener(this, callback);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {\n var _this$pendingKeys_2, _this$pendingKeys_2$g;\n\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n if (notify || notifySpy) {\n var change = notify || notifySpy ? {\n type: ADD,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: value\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true); // Notify \"keys/entries/values\" observers\n\n this.keysAtom_.reportChanged();\n };\n\n _proto.ownKeys_ = function ownKeys_() {\n this.keysAtom_.reportObserved();\n return ownKeys(this.target_);\n };\n\n _proto.keys_ = function keys_() {\n // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.\n // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.\n // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)\n // We choose to over-report in Object.keys(object), because:\n // - typically it's used with simple data objects\n // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected\n this.keysAtom_.reportObserved();\n return Object.keys(this.target_);\n };\n\n return ObservableObjectAdministration;\n}();\nfunction asObservableObject(target, options) {\n var _options$name;\n\n if ( true && options && isObservableObject(target)) {\n die(\"Options can't be provided for already observable objects.\");\n }\n\n if (hasProp(target, $mobx)) {\n if ( true && !(getAdministration(target) instanceof ObservableObjectAdministration)) {\n die(\"Cannot convert '\" + getDebugName(target) + \"' into observable object:\" + \"\\nThe target is already observable of different type.\" + \"\\nExtending builtins is not supported.\");\n }\n\n return target;\n }\n\n if ( true && !Object.isExtensible(target)) {\n die(\"Cannot make the designated object observable; it is not extensible\");\n }\n\n var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : true ? (isPlainObject(target) ? \"ObservableObject\" : target.constructor.name) + \"@\" + getNextId() : undefined;\n var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));\n addHiddenProp(target, $mobx, adm);\n return target;\n}\nvar isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableObjectAdministration\", ObservableObjectAdministration);\n\nfunction getCachedObservablePropDescriptor(key) {\n return descriptorCache[key] || (descriptorCache[key] = {\n get: function get() {\n return this[$mobx].getObservablePropValue_(key);\n },\n set: function set(value) {\n return this[$mobx].setObservablePropValue_(key, value);\n }\n });\n}\n\nfunction isObservableObject(thing) {\n if (isObject(thing)) {\n return isObservableObjectAdministration(thing[$mobx]);\n }\n\n return false;\n}\nfunction recordAnnotationApplied(adm, annotation, key) {\n var _adm$target_$storedAn;\n\n if (true) {\n adm.appliedAnnotations_[key] = annotation;\n } // Remove applied decorator annotation so we don't try to apply it again in subclass constructor\n\n\n (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key];\n}\n\nfunction assertAnnotable(adm, annotation, key) {\n // Valid annotation\n if ( true && !isAnnotation(annotation)) {\n die(\"Cannot annotate '\" + adm.name_ + \".\" + key.toString() + \"': Invalid annotation.\");\n }\n /*\r\n // Configurable, not sealed, not frozen\r\n // Possibly not needed, just a little better error then the one thrown by engine.\r\n // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.\r\n if (__DEV__) {\r\n const configurable = getDescriptor(adm.target_, key)?.configurable\r\n const frozen = Object.isFrozen(adm.target_)\r\n const sealed = Object.isSealed(adm.target_)\r\n if (!configurable || frozen || sealed) {\r\n const fieldName = `${adm.name_}.${key.toString()}`\r\n const requestedAnnotationType = annotation.annotationType_\r\n let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`\r\n if (frozen) {\r\n error += `\\nObject is frozen.`\r\n }\r\n if (sealed) {\r\n error += `\\nObject is sealed.`\r\n }\r\n if (!configurable) {\r\n error += `\\nproperty is not configurable.`\r\n // Mention only if caused by us to avoid confusion\r\n if (hasProp(adm.appliedAnnotations!, key)) {\r\n error += `\\nTo prevent accidental re-definition of a field by a subclass, `\r\n error += `all annotated fields of non-plain objects (classes) are not configurable.`\r\n }\r\n }\r\n die(error)\r\n }\r\n }\r\n */\n // Not annotated\n\n\n if ( true && !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {\n var fieldName = adm.name_ + \".\" + key.toString();\n var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already annotated with '\" + currentAnnotationType + \"'.\") + \"\\nRe-annotating fields is not allowed.\" + \"\\nUse 'override' annotation for methods overridden by subclass.\");\n }\n}\n\nvar ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);\n/**\r\n * This array buffer contains two lists of properties, so that all arrays\r\n * can recycle their property definitions, which significantly improves performance of creating\r\n * properties on the fly.\r\n */\n\n\nvar OBSERVABLE_ARRAY_BUFFER_SIZE = 0; // Typescript workaround to make sure ObservableArray extends Array\n\nvar StubArray = function StubArray() {};\n\nfunction inherit(ctor, proto) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(ctor.prototype, proto);\n } else if (ctor.prototype.__proto__ !== undefined) {\n ctor.prototype.__proto__ = proto;\n } else {\n ctor.prototype = proto;\n }\n}\n\ninherit(StubArray, Array.prototype); // Weex proto freeze protection was here,\n// but it is unclear why the hack is need as MobX never changed the prototype\n// anyway, so removed it in V6\n\nvar LegacyObservableArray = /*#__PURE__*/function (_StubArray, _Symbol$toStringTag, _Symbol$iterator) {\n _inheritsLoose(LegacyObservableArray, _StubArray);\n\n function LegacyObservableArray(initialValues, enhancer, name, owned) {\n var _this;\n\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n _this = _StubArray.call(this) || this;\n var adm = new ObservableArrayAdministration(name, enhancer, owned, true);\n adm.proxy_ = _assertThisInitialized(_this);\n addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm);\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true); // @ts-ignore\n\n _this.spliceWithArray(0, 0, initialValues);\n\n allowStateChangesEnd(prev);\n }\n\n {\n // Seems that Safari won't use numeric prototype setter untill any * numeric property is\n // defined on the instance. After that it works fine, even if this property is deleted.\n Object.defineProperty(_assertThisInitialized(_this), \"0\", ENTRY_0);\n }\n\n return _this;\n }\n\n var _proto = LegacyObservableArray.prototype;\n\n _proto.concat = function concat() {\n this[$mobx].atom_.reportObserved();\n\n for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {\n arrays[_key] = arguments[_key];\n }\n\n return Array.prototype.concat.apply(this.slice(), //@ts-ignore\n arrays.map(function (a) {\n return isObservableArray(a) ? a.slice() : a;\n }));\n };\n\n _proto[_Symbol$iterator] = function () {\n var self = this;\n var nextIndex = 0;\n return makeIterable({\n next: function next() {\n return nextIndex < self.length ? {\n value: self[nextIndex++],\n done: false\n } : {\n done: true,\n value: undefined\n };\n }\n });\n };\n\n _createClass(LegacyObservableArray, [{\n key: \"length\",\n get: function get() {\n return this[$mobx].getArrayLength_();\n },\n set: function set(newLength) {\n this[$mobx].setArrayLength_(newLength);\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Array\";\n }\n }]);\n\n return LegacyObservableArray;\n}(StubArray, Symbol.toStringTag, Symbol.iterator);\n\nObject.entries(arrayExtensions).forEach(function (_ref) {\n var prop = _ref[0],\n fn = _ref[1];\n\n if (prop !== \"concat\") {\n addHiddenProp(LegacyObservableArray.prototype, prop, fn);\n }\n});\n\nfunction createArrayEntryDescriptor(index) {\n return {\n enumerable: false,\n configurable: true,\n get: function get() {\n return this[$mobx].get_(index);\n },\n set: function set(value) {\n this[$mobx].set_(index, value);\n }\n };\n}\n\nfunction createArrayBufferItem(index) {\n defineProperty(LegacyObservableArray.prototype, \"\" + index, createArrayEntryDescriptor(index));\n}\n\nfunction reserveArrayBuffer(max) {\n if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {\n for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {\n createArrayBufferItem(index);\n }\n\n OBSERVABLE_ARRAY_BUFFER_SIZE = max;\n }\n}\nreserveArrayBuffer(1000);\nfunction createLegacyArray(initialValues, enhancer, name) {\n return new LegacyObservableArray(initialValues, enhancer, name);\n}\n\nfunction getAtom(thing, property) {\n if (typeof thing === \"object\" && thing !== null) {\n if (isObservableArray(thing)) {\n if (property !== undefined) {\n die(23);\n }\n\n return thing[$mobx].atom_;\n }\n\n if (isObservableSet(thing)) {\n return thing[$mobx];\n }\n\n if (isObservableMap(thing)) {\n if (property === undefined) {\n return thing.keysAtom_;\n }\n\n var observable = thing.data_.get(property) || thing.hasMap_.get(property);\n\n if (!observable) {\n die(25, property, getDebugName(thing));\n }\n\n return observable;\n }\n\n\n if (isObservableObject(thing)) {\n if (!property) {\n return die(26);\n }\n\n var _observable = thing[$mobx].values_.get(property);\n\n if (!_observable) {\n die(27, property, getDebugName(thing));\n }\n\n return _observable;\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n } else if (isFunction(thing)) {\n if (isReaction(thing[$mobx])) {\n // disposer function\n return thing[$mobx];\n }\n }\n\n die(28);\n}\nfunction getAdministration(thing, property) {\n if (!thing) {\n die(29);\n }\n\n if (property !== undefined) {\n return getAdministration(getAtom(thing, property));\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n\n if (isObservableMap(thing) || isObservableSet(thing)) {\n return thing;\n }\n\n if (thing[$mobx]) {\n return thing[$mobx];\n }\n\n die(24, thing);\n}\nfunction getDebugName(thing, property) {\n var named;\n\n if (property !== undefined) {\n named = getAtom(thing, property);\n } else if (isAction(thing)) {\n return thing.name;\n } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {\n named = getAdministration(thing);\n } else {\n // valid for arrays as well\n named = getAtom(thing);\n }\n\n return named.name_;\n}\n\nvar toString = objectPrototype.toString;\nfunction deepEqual(a, b, depth) {\n if (depth === void 0) {\n depth = -1;\n }\n\n return eq(a, b, depth);\n} // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289\n// Internal recursive comparison function for `isEqual`.\n\nfunction eq(a, b, depth, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) {\n return a !== 0 || 1 / a === 1 / b;\n } // `null` or `undefined` only equal to itself (strict comparison).\n\n\n if (a == null || b == null) {\n return false;\n } // `NaN`s are equivalent, but non-reflexive.\n\n\n if (a !== a) {\n return b !== b;\n } // Exhaust primitive checks\n\n\n var type = typeof a;\n\n if (type !== \"function\" && type !== \"object\" && typeof b != \"object\") {\n return false;\n } // Compare `[[Class]]` names.\n\n\n var className = toString.call(a);\n\n if (className !== toString.call(b)) {\n return false;\n }\n\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case \"[object RegExp]\": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n\n case \"[object String]\":\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return \"\" + a === \"\" + b;\n\n case \"[object Number]\":\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN.\n if (+a !== +a) {\n return +b !== +b;\n } // An `egal` comparison is performed for other numeric values.\n\n\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n\n case \"[object Date]\":\n case \"[object Boolean]\":\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n\n case \"[object Symbol]\":\n return typeof Symbol !== \"undefined\" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);\n\n case \"[object Map]\":\n case \"[object Set]\":\n // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.\n // Hide this extra level by increasing the depth.\n if (depth >= 0) {\n depth++;\n }\n\n break;\n } // Unwrap any wrapped objects.\n\n\n a = unwrap(a);\n b = unwrap(b);\n var areArrays = className === \"[object Array]\";\n\n if (!areArrays) {\n if (typeof a != \"object\" || typeof b != \"object\") {\n return false;\n } // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n\n\n var aCtor = a.constructor,\n bCtor = b.constructor;\n\n if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && \"constructor\" in a && \"constructor\" in b) {\n return false;\n }\n }\n\n if (depth === 0) {\n return false;\n } else if (depth < 0) {\n depth = -1;\n } // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n\n\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) {\n return bStack[length] === b;\n }\n } // Add the first object to the stack of traversed objects.\n\n\n aStack.push(a);\n bStack.push(b); // Recursively compare objects and arrays.\n\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n\n if (length !== b.length) {\n return false;\n } // Deep compare the contents, ignoring non-numeric properties.\n\n\n while (length--) {\n if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {\n return false;\n }\n }\n } else {\n // Deep compare objects.\n var keys = Object.keys(a);\n var key;\n length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality.\n\n if (Object.keys(b).length !== length) {\n return false;\n }\n\n while (length--) {\n // Deep compare each member\n key = keys[length];\n\n if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {\n return false;\n }\n }\n } // Remove the first object from the stack of traversed objects.\n\n\n aStack.pop();\n bStack.pop();\n return true;\n}\n\nfunction unwrap(a) {\n if (isObservableArray(a)) {\n return a.slice();\n }\n\n if (isES6Map(a) || isObservableMap(a)) {\n return Array.from(a.entries());\n }\n\n if (isES6Set(a) || isObservableSet(a)) {\n return Array.from(a.entries());\n }\n\n return a;\n}\n\nfunction makeIterable(iterator) {\n iterator[Symbol.iterator] = getSelf;\n return iterator;\n}\n\nfunction getSelf() {\n return this;\n}\n\nfunction isAnnotation(thing) {\n return (// Can be function\n thing instanceof Object && typeof thing.annotationType_ === \"string\" && isFunction(thing.make_) && isFunction(thing.extend_)\n );\n}\n\n/**\r\n * (c) Michel Weststrate 2015 - 2020\r\n * MIT Licensed\r\n *\r\n * Welcome to the mobx sources! To get a global overview of how MobX internally works,\r\n * this is a good place to start:\r\n * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74\r\n *\r\n * Source folders:\r\n * ===============\r\n *\r\n * - api/ Most of the public static methods exposed by the module can be found here.\r\n * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.\r\n * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.\r\n * - utils/ Utility stuff.\r\n *\r\n */\n[\"Symbol\", \"Map\", \"Set\"].forEach(function (m) {\n var g = getGlobal();\n\n if (typeof g[m] === \"undefined\") {\n die(\"MobX requires global '\" + m + \"' to be available or polyfilled\");\n }\n});\n\nif (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === \"object\") {\n // See: https://github.com/andykog/mobx-devtools/\n __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({\n spy: spy,\n extras: {\n getDebugName: getDebugName\n },\n $mobx: $mobx\n });\n}\n\n\n//# sourceMappingURL=mobx.esm.js.map\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../sgmf-scripts/node_modules/webpack/buildin/global.js */ \"./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/mobx/dist/mobx.esm.js?"); + +/***/ }), + +/***/ "./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js": +/*!***********************************!*\ + !*** (webpack)/buildin/global.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +eval("var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n\n\n//# sourceURL=webpack:///(webpack)/buildin/global.js?"); + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenGiving.js b/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenGiving.js new file mode 100644 index 000000000..3f4a8de30 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/static/default/js/adyenGiving.js @@ -0,0 +1,101 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenGiving.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenGiving.js": +/*!******************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenGiving.js ***! + \******************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nvar adyenGivingNode = document.getElementById('donate-container');\nfunction handleOnDonate(state, component) {\n if (!state.isValid) {\n return;\n }\n var selectedAmount = state.data.amount;\n var donationData = {\n amountValue: selectedAmount.value,\n amountCurrency: selectedAmount.currency,\n orderNo: window.orderNo,\n orderToken: window.orderToken\n };\n $.ajax({\n url: window.donateURL,\n type: 'post',\n data: donationData,\n success: function success() {\n component.setStatus('success');\n }\n });\n}\nfunction handleOnCancel(state, component) {\n var adyenGiving = document.getElementById('adyenGiving');\n adyenGiving.style.transition = 'all 3s ease-in-out';\n adyenGiving.style.display = 'none';\n component.unmount();\n}\nfunction getAmounts() {\n try {\n return JSON.parse(donationAmounts);\n } catch (e) {\n return [];\n }\n}\nvar donationConfig = {\n amounts: getAmounts(),\n backgroundUrl: adyenGivingBackgroundUrl,\n description: decodeURI(charityDescription),\n logoUrl: adyenGivingLogoUrl,\n name: decodeURI(charityName),\n url: charityWebsite,\n showCancelButton: true,\n onDonate: handleOnDonate,\n onCancel: handleOnCancel\n};\nAdyenCheckout(window.Configuration).then(function (checkout) {\n checkout.create('donation', donationConfig).mount(adyenGivingNode);\n});\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyenGiving.js?"); + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayCheckout.js b/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayCheckout.js new file mode 100644 index 000000000..3d03cacbe --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayCheckout.js @@ -0,0 +1,160 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayCheckout.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js": +/*!*****************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js ***! + \*****************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar constants = __webpack_require__(/*! ../constants */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js\");\nfunction assignPaymentMethodValue() {\n var adyenPaymentMethod = document.querySelector('#adyenPaymentMethodName');\n // if currently selected paymentMethod contains a brand it will be part of the label ID\n var paymentMethodlabelId = \"#lb_\".concat(store.selectedMethod);\n if (adyenPaymentMethod) {\n var _document$querySelect;\n adyenPaymentMethod.value = store.brand ? store.brand : (_document$querySelect = document.querySelector(paymentMethodlabelId)) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.innerHTML;\n }\n}\nfunction setOrderFormData(response) {\n if (response.orderNo) {\n document.querySelector('#merchantReference').value = response.orderNo;\n }\n if (response.orderToken) {\n document.querySelector('#orderToken').value = response.orderToken;\n }\n}\n\n/**\n * Makes an ajax call to the controller function PaymentFromComponent.\n * Used by certain payment methods like paypal\n */\nfunction paymentFromComponent(data) {\n var component = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var requestData = store.partialPaymentsOrderObj ? _objectSpread(_objectSpread({}, data), {}, {\n partialPaymentsOrder: store.partialPaymentsOrderObj\n }) : data;\n $.ajax({\n url: window.paymentFromComponentURL,\n type: 'post',\n data: {\n data: JSON.stringify(requestData),\n paymentMethod: document.querySelector('#adyenPaymentMethodName').value\n },\n success: function success(response) {\n var _response$fullRespons;\n setOrderFormData(response);\n if ((_response$fullRespons = response.fullResponse) !== null && _response$fullRespons !== void 0 && _response$fullRespons.action) {\n component.handleAction(response.fullResponse.action);\n } else if (response.skipSummaryPage) {\n document.querySelector('#result').value = JSON.stringify(response);\n document.querySelector('#showConfirmationForm').submit();\n } else if (response.paymentError || response.error) {\n component.handleError();\n }\n }\n });\n}\nfunction resetPaymentMethod() {\n $('#requiredBrandCode').hide();\n $('#selectedIssuer').val('');\n $('#adyenIssuerName').val('');\n $('#dateOfBirth').val('');\n $('#telephoneNumber').val('');\n $('#gender').val('');\n $('#bankAccountOwnerName').val('');\n $('#bankAccountNumber').val('');\n $('#bankLocationId').val('');\n $('.additionalFields').hide();\n}\n\n/**\n * Changes the \"display\" attribute of the selected method from hidden to visible\n */\nfunction displaySelectedMethod(type) {\n var _document$querySelect2;\n // If 'type' input field is present use this as type, otherwise default to function input param\n store.selectedMethod = document.querySelector(\"#component_\".concat(type, \" .type\")) ? document.querySelector(\"#component_\".concat(type, \" .type\")).value : type;\n resetPaymentMethod();\n var disabledSubmitButtonMethods = constants.DISABLED_SUBMIT_BUTTON_METHODS;\n if (window.klarnaWidgetEnabled) {\n disabledSubmitButtonMethods.push('klarna');\n }\n document.querySelector('button[value=\"submit-payment\"]').disabled = disabledSubmitButtonMethods.findIndex(function (pm) {\n return type.includes(pm);\n }) > -1;\n document.querySelector(\"#component_\".concat(type)).setAttribute('style', 'display:block');\n // set brand for giftcards if hidden inputfield is present\n store.brand = (_document$querySelect2 = document.querySelector(\"#component_\".concat(type, \" .brand\"))) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value;\n}\nfunction displayValidationErrors() {\n store.selectedPayment.node.showValidation();\n return false;\n}\nvar selectedMethods = {};\nfunction doCustomValidation() {\n return store.selectedMethod in selectedMethods ? selectedMethods[store.selectedMethod]() : true;\n}\nfunction showValidation() {\n return store.selectedPaymentIsValid ? doCustomValidation() : displayValidationErrors();\n}\nfunction getInstallmentValues(maxValue) {\n var values = [];\n for (var i = 1; i <= maxValue; i += 1) {\n values.push(i);\n }\n return values;\n}\nfunction createShowConfirmationForm(action) {\n if (document.querySelector('#showConfirmationForm')) {\n return;\n }\n var template = document.createElement('template');\n var form = \"
            \\n \\n \\n \\n \\n
            \");\n template.innerHTML = form;\n document.querySelector('body').appendChild(template.content);\n}\nmodule.exports = {\n setOrderFormData: setOrderFormData,\n assignPaymentMethodValue: assignPaymentMethodValue,\n paymentFromComponent: paymentFromComponent,\n resetPaymentMethod: resetPaymentMethod,\n displaySelectedMethod: displaySelectedMethod,\n showValidation: showValidation,\n createShowConfirmationForm: createShowConfirmationForm,\n getInstallmentValues: getInstallmentValues\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayCheckout.js": +/*!************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayCheckout.js ***! + \************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction 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); } }\nfunction _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); }); }; }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar store = __webpack_require__(/*! ../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar helpers = __webpack_require__(/*! ./adyen_checkout/helpers */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js\");\nfunction handleAuthorised(response) {\n var _response$fullRespons, _response$fullRespons2, _response$fullRespons3, _response$fullRespons4, _response$fullRespons5;\n document.querySelector('#result').value = JSON.stringify({\n pspReference: (_response$fullRespons = response.fullResponse) === null || _response$fullRespons === void 0 ? void 0 : _response$fullRespons.pspReference,\n resultCode: (_response$fullRespons2 = response.fullResponse) === null || _response$fullRespons2 === void 0 ? void 0 : _response$fullRespons2.resultCode,\n paymentMethod: (_response$fullRespons3 = response.fullResponse) !== null && _response$fullRespons3 !== void 0 && _response$fullRespons3.paymentMethod ? response.fullResponse.paymentMethod : (_response$fullRespons4 = response.fullResponse) === null || _response$fullRespons4 === void 0 ? void 0 : (_response$fullRespons5 = _response$fullRespons4.additionalData) === null || _response$fullRespons5 === void 0 ? void 0 : _response$fullRespons5.paymentMethod\n });\n document.querySelector('#showConfirmationForm').submit();\n}\nfunction handleError() {\n document.querySelector('#result').value = JSON.stringify({\n error: true\n });\n document.querySelector('#showConfirmationForm').submit();\n}\nfunction handleAmazonResponse(response, component) {\n var _response$fullRespons6;\n if ((_response$fullRespons6 = response.fullResponse) !== null && _response$fullRespons6 !== void 0 && _response$fullRespons6.action) {\n component.handleAction(response.fullResponse.action);\n } else if (response.resultCode === window.resultCodeAuthorised) {\n handleAuthorised(response);\n } else {\n // first try the amazon decline flow\n component.handleDeclineFlow();\n // if this does not trigger a redirect, try the regular handleError flow\n handleError();\n }\n}\nfunction paymentFromComponent(data, component) {\n var partialPaymentsOrder = sessionStorage.getItem('partialPaymentsObj');\n var requestData = partialPaymentsOrder ? _objectSpread(_objectSpread({}, data), {}, {\n partialPaymentsOrder: JSON.parse(partialPaymentsOrder)\n }) : data;\n $.ajax({\n url: window.paymentFromComponentURL,\n type: 'post',\n data: {\n data: JSON.stringify(requestData),\n paymentMethod: 'amazonpay',\n merchantReference: document.querySelector('#merchantReference').value,\n orderToken: document.querySelector('#orderToken').value\n },\n success: function success(response) {\n sessionStorage.removeItem('partialPaymentsObj');\n helpers.setOrderFormData(response);\n handleAmazonResponse(response, component);\n }\n });\n}\nfunction mountAmazonPayComponent() {\n return _mountAmazonPayComponent.apply(this, arguments);\n}\nfunction _mountAmazonPayComponent() {\n _mountAmazonPayComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n var amazonPayNode, checkout, amazonConfig, amazonPayComponent;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n amazonPayNode = document.getElementById('amazon-container');\n _context.next = 3;\n return AdyenCheckout(window.Configuration);\n case 3:\n checkout = _context.sent;\n amazonConfig = {\n showOrderButton: false,\n returnUrl: window.returnURL,\n configuration: {\n merchantId: window.amazonMerchantID,\n storeId: window.amazonStoreID,\n publicKeyId: window.amazonPublicKeyID\n },\n amazonCheckoutSessionId: window.amazonCheckoutSessionId,\n onSubmit: function onSubmit(state, component) {\n document.querySelector('#adyenStateData').value = JSON.stringify(state.data);\n document.querySelector('#additionalDetailsHidden').value = JSON.stringify(state.data);\n paymentFromComponent(state.data, component);\n },\n onAdditionalDetails: function onAdditionalDetails(state) {\n state.data.paymentMethod = 'amazonpay';\n $.ajax({\n type: 'post',\n url: window.paymentsDetailsURL,\n data: JSON.stringify({\n data: state.data,\n orderToken: window.orderToken\n }),\n contentType: 'application/json; charset=utf-8',\n success: function success(data) {\n if (data.isSuccessful) {\n handleAuthorised(data);\n } else if (!data.isFinal && _typeof(data.action) === 'object') {\n checkout.createFromAction(data.action).mount('#amazon-container');\n } else {\n $('#action-modal').modal('hide');\n handleError();\n }\n }\n });\n }\n };\n amazonPayComponent = checkout.create('amazonpay', amazonConfig).mount(amazonPayNode);\n helpers.createShowConfirmationForm(window.ShowConfirmationPaymentFromComponent);\n $('#dwfrm_billing').submit(function apiRequest(e) {\n e.preventDefault();\n var form = $(this);\n var url = form.attr('action');\n $.ajax({\n type: 'POST',\n url: url,\n data: form.serialize(),\n async: false,\n success: function success(data) {\n store.formErrorsExist = 'fieldErrors' in data;\n }\n });\n });\n $('#action-modal').modal({\n backdrop: 'static',\n keyboard: false\n });\n amazonPayComponent.submit();\n case 10:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return _mountAmazonPayComponent.apply(this, arguments);\n}\nmountAmazonPayComponent();\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayCheckout.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js": +/*!****************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js ***! + \****************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\n// Adyen constants\n\nmodule.exports = {\n METHOD_ADYEN: 'Adyen',\n METHOD_ADYEN_POS: 'AdyenPOS',\n METHOD_ADYEN_COMPONENT: 'AdyenComponent',\n RECEIVED: 'Received',\n NOTENOUGHBALANCE: 'NotEnoughBalance',\n SUCCESS: 'Success',\n GIFTCARD: 'giftcard',\n GIROPAY: 'giropay',\n APPLE_PAY: 'applepay',\n ACTIONTYPE: {\n QRCODE: 'qrCode'\n },\n DISABLED_SUBMIT_BUTTON_METHODS: ['paypal', 'paywithgoogle', 'googlepay', 'amazonpay', 'applepay', 'cashapp'],\n APPLE_DOMAIN_URL: '/.well-known/apple-developer-merchantid-domain-association'\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/store/index.js": +/*!************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/store/index.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nvar _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, _descriptor12, _descriptor13;\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }\nfunction _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); }\nvar _require = __webpack_require__(/*! mobx */ \"./node_modules/mobx/dist/mobx.esm.js\"),\n observable = _require.observable,\n computed = _require.computed;\nvar Store = (_class = /*#__PURE__*/function () {\n function Store() {\n _classCallCheck(this, Store);\n _defineProperty(this, \"MASKED_CC_PREFIX\", '************');\n _initializerDefineProperty(this, \"checkout\", _descriptor, this);\n _initializerDefineProperty(this, \"endDigits\", _descriptor2, this);\n _initializerDefineProperty(this, \"selectedMethod\", _descriptor3, this);\n _initializerDefineProperty(this, \"componentsObj\", _descriptor4, this);\n _initializerDefineProperty(this, \"checkoutConfiguration\", _descriptor5, this);\n _initializerDefineProperty(this, \"formErrorsExist\", _descriptor6, this);\n _initializerDefineProperty(this, \"isValid\", _descriptor7, this);\n _initializerDefineProperty(this, \"paypalTerminatedEarly\", _descriptor8, this);\n _initializerDefineProperty(this, \"componentState\", _descriptor9, this);\n _initializerDefineProperty(this, \"brand\", _descriptor10, this);\n _initializerDefineProperty(this, \"partialPaymentsOrderObj\", _descriptor11, this);\n _initializerDefineProperty(this, \"giftCardComponentListenersAdded\", _descriptor12, this);\n _initializerDefineProperty(this, \"addedGiftCards\", _descriptor13, this);\n }\n _createClass(Store, [{\n key: \"maskedCardNumber\",\n get: function get() {\n return \"\".concat(this.MASKED_CC_PREFIX).concat(this.endDigits);\n }\n }, {\n key: \"selectedPayment\",\n get: function get() {\n return this.componentsObj[this.selectedMethod];\n }\n }, {\n key: \"selectedPaymentIsValid\",\n get: function get() {\n var _this$selectedPayment;\n return !!((_this$selectedPayment = this.selectedPayment) !== null && _this$selectedPayment !== void 0 && _this$selectedPayment.isValid);\n }\n }, {\n key: \"stateData\",\n get: function get() {\n var _this$selectedPayment2;\n return ((_this$selectedPayment2 = this.selectedPayment) === null || _this$selectedPayment2 === void 0 ? void 0 : _this$selectedPayment2.stateData) || {\n paymentMethod: _objectSpread({\n type: this.selectedMethod\n }, this.brand ? {\n brand: this.brand\n } : undefined)\n };\n }\n }, {\n key: \"updateSelectedPayment\",\n value: function updateSelectedPayment(method, key, val) {\n this.componentsObj[method][key] = val;\n }\n }]);\n return Store;\n}(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, \"checkout\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, \"endDigits\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, \"selectedMethod\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, \"componentsObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, \"checkoutConfiguration\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return window.Configuration || {};\n }\n}), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, \"formErrorsExist\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, \"isValid\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, \"paypalTerminatedEarly\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor9 = _applyDecoratedDescriptor(_class.prototype, \"componentState\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor10 = _applyDecoratedDescriptor(_class.prototype, \"brand\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor11 = _applyDecoratedDescriptor(_class.prototype, \"partialPaymentsOrderObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor12 = _applyDecoratedDescriptor(_class.prototype, \"giftCardComponentListenersAdded\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor13 = _applyDecoratedDescriptor(_class.prototype, \"addedGiftCards\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _applyDecoratedDescriptor(_class.prototype, \"maskedCardNumber\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"maskedCardNumber\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPayment\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPayment\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPaymentIsValid\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPaymentIsValid\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"stateData\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"stateData\"), _class.prototype)), _class);\nmodule.exports = new Store();\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/store/index.js?"); + +/***/ }), + +/***/ "./node_modules/mobx/dist/mobx.esm.js": +/*!********************************************!*\ + !*** ./node_modules/mobx/dist/mobx.esm.js ***! + \********************************************/ +/*! exports provided: $mobx, FlowCancellationError, ObservableMap, ObservableSet, Reaction, _allowStateChanges, _allowStateChangesInsideComputed, _allowStateReadsEnd, _allowStateReadsStart, _autoAction, _endAction, _getAdministration, _getGlobalState, _interceptReads, _isComputingDerivation, _resetGlobalState, _startAction, action, autorun, comparer, computed, configure, createAtom, defineProperty, entries, extendObservable, flow, flowResult, get, getAtom, getDebugName, getDependencyTree, getObserverTree, has, intercept, isAction, isBoxedObservable, isComputed, isComputedProp, isFlow, isFlowCancellationError, isObservable, isObservableArray, isObservableMap, isObservableObject, isObservableProp, isObservableSet, keys, makeAutoObservable, makeObservable, observable, observe, onBecomeObserved, onBecomeUnobserved, onReactionError, override, ownKeys, reaction, remove, runInAction, set, spy, toJS, trace, transaction, untracked, values, when */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"$mobx\", function() { return $mobx; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"FlowCancellationError\", function() { return FlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableMap\", function() { return ObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableSet\", function() { return ObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Reaction\", function() { return Reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChanges\", function() { return allowStateChanges; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChangesInsideComputed\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsEnd\", function() { return allowStateReadsEnd; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsStart\", function() { return allowStateReadsStart; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_autoAction\", function() { return autoAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_endAction\", function() { return _endAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getAdministration\", function() { return getAdministration; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getGlobalState\", function() { return getGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_interceptReads\", function() { return interceptReads; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_isComputingDerivation\", function() { return isComputingDerivation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_resetGlobalState\", function() { return resetGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_startAction\", function() { return _startAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"action\", function() { return action; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"autorun\", function() { return autorun; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"comparer\", function() { return comparer; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"computed\", function() { return computed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"configure\", function() { return configure; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createAtom\", function() { return createAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"defineProperty\", function() { return apiDefineProperty; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"entries\", function() { return entries; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"extendObservable\", function() { return extendObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flow\", function() { return flow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flowResult\", function() { return flowResult; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"get\", function() { return get; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getAtom\", function() { return getAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDebugName\", function() { return getDebugName; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDependencyTree\", function() { return getDependencyTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getObserverTree\", function() { return getObserverTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"has\", function() { return has; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"intercept\", function() { return intercept; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isAction\", function() { return isAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isBoxedObservable\", function() { return isObservableValue; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputed\", function() { return isComputed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputedProp\", function() { return isComputedProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlow\", function() { return isFlow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlowCancellationError\", function() { return isFlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservable\", function() { return isObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableArray\", function() { return isObservableArray; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableMap\", function() { return isObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableObject\", function() { return isObservableObject; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableProp\", function() { return isObservableProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableSet\", function() { return isObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"keys\", function() { return keys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeAutoObservable\", function() { return makeAutoObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeObservable\", function() { return makeObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observable\", function() { return observable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observe\", function() { return observe; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeObserved\", function() { return onBecomeObserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeUnobserved\", function() { return onBecomeUnobserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onReactionError\", function() { return onReactionError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"override\", function() { return override; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ownKeys\", function() { return apiOwnKeys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"reaction\", function() { return reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"remove\", function() { return remove; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"runInAction\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"set\", function() { return set; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"spy\", function() { return spy; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toJS\", function() { return toJS; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"trace\", function() { return trace; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"transaction\", function() { return transaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"untracked\", function() { return untracked; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"values\", function() { return values; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"when\", function() { return when; });\nvar niceErrors = {\n 0: \"Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'\",\n 1: function _(annotationType, key) {\n return \"Cannot apply '\" + annotationType + \"' to '\" + key.toString() + \"': Field not found.\";\n },\n\n /*\r\n 2(prop) {\r\n return `invalid decorator for '${prop.toString()}'`\r\n },\r\n 3(prop) {\r\n return `Cannot decorate '${prop.toString()}': action can only be used on properties with a function value.`\r\n },\r\n 4(prop) {\r\n return `Cannot decorate '${prop.toString()}': computed can only be used on getter properties.`\r\n },\r\n */\n 5: \"'keys()' can only be used on observable objects, arrays, sets and maps\",\n 6: \"'values()' can only be used on observable objects, arrays, sets and maps\",\n 7: \"'entries()' can only be used on observable objects, arrays and maps\",\n 8: \"'set()' can only be used on observable objects, arrays and maps\",\n 9: \"'remove()' can only be used on observable objects, arrays and maps\",\n 10: \"'has()' can only be used on observable objects, arrays and maps\",\n 11: \"'get()' can only be used on observable objects, arrays and maps\",\n 12: \"Invalid annotation\",\n 13: \"Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 14: \"Intercept handlers should return nothing or a change object\",\n 15: \"Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 16: \"Modification exception: the internal structure of an observable array was changed.\",\n 17: function _(index, length) {\n return \"[mobx.array] Index out of bounds, \" + index + \" is larger than \" + length;\n },\n 18: \"mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js\",\n 19: function _(other) {\n return \"Cannot initialize from classes that inherit from Map: \" + other.constructor.name;\n },\n 20: function _(other) {\n return \"Cannot initialize map from \" + other;\n },\n 21: function _(dataStructure) {\n return \"Cannot convert to map from '\" + dataStructure + \"'\";\n },\n 22: \"mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js\",\n 23: \"It is not possible to get index atoms from arrays\",\n 24: function _(thing) {\n return \"Cannot obtain administration from \" + thing;\n },\n 25: function _(property, name) {\n return \"the entry '\" + property + \"' does not exist in the observable map '\" + name + \"'\";\n },\n 26: \"please specify a property\",\n 27: function _(property, name) {\n return \"no observable property '\" + property.toString() + \"' found on the observable object '\" + name + \"'\";\n },\n 28: function _(thing) {\n return \"Cannot obtain atom from \" + thing;\n },\n 29: \"Expecting some object\",\n 30: \"invalid action stack. did you forget to finish an action?\",\n 31: \"missing option for computed: get\",\n 32: function _(name, derivation) {\n return \"Cycle detected in computation \" + name + \": \" + derivation;\n },\n 33: function _(name) {\n return \"The setter of computed value '\" + name + \"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?\";\n },\n 34: function _(name) {\n return \"[ComputedValue '\" + name + \"'] It is not possible to assign a new value to a computed value.\";\n },\n 35: \"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`\",\n 36: \"isolateGlobalState should be called before MobX is running any reactions\",\n 37: function _(method) {\n return \"[mobx] `observableArray.\" + method + \"()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice().\" + method + \"()` instead\";\n },\n 38: \"'ownKeys()' can only be used on observable objects\",\n 39: \"'defineProperty()' can only be used on observable objects\"\n};\nvar errors = true ? niceErrors : undefined;\nfunction die(error) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n if (true) {\n var e = typeof error === \"string\" ? error : errors[error];\n if (typeof e === \"function\") e = e.apply(null, args);\n throw new Error(\"[MobX] \" + e);\n }\n\n throw new Error(typeof error === \"number\" ? \"[MobX] minified error nr: \" + error + (args.length ? \" \" + args.map(String).join(\",\") : \"\") + \". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts\" : \"[MobX] \" + error);\n}\n\nvar mockGlobal = {};\nfunction getGlobal() {\n if (typeof globalThis !== \"undefined\") {\n return globalThis;\n }\n\n if (typeof window !== \"undefined\") {\n return window;\n }\n\n if (typeof global !== \"undefined\") {\n return global;\n }\n\n if (typeof self !== \"undefined\") {\n return self;\n }\n\n return mockGlobal;\n}\n\nvar assign = Object.assign;\nvar getDescriptor = Object.getOwnPropertyDescriptor;\nvar defineProperty = Object.defineProperty;\nvar objectPrototype = Object.prototype;\nvar EMPTY_ARRAY = [];\nObject.freeze(EMPTY_ARRAY);\nvar EMPTY_OBJECT = {};\nObject.freeze(EMPTY_OBJECT);\nvar hasProxy = typeof Proxy !== \"undefined\";\nvar plainObjectString = /*#__PURE__*/Object.toString();\nfunction assertProxies() {\n if (!hasProxy) {\n die( true ? \"`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`\" : undefined);\n }\n}\nfunction warnAboutProxyRequirement(msg) {\n if ( true && globalState.verifyProxies) {\n die(\"MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to \" + msg);\n }\n}\nfunction getNextId() {\n return ++globalState.mobxGuid;\n}\n/**\r\n * Makes sure that the provided function is invoked at most once.\r\n */\n\nfunction once(func) {\n var invoked = false;\n return function () {\n if (invoked) {\n return;\n }\n\n invoked = true;\n return func.apply(this, arguments);\n };\n}\nvar noop = function noop() {};\nfunction isFunction(fn) {\n return typeof fn === \"function\";\n}\nfunction isStringish(value) {\n var t = typeof value;\n\n switch (t) {\n case \"string\":\n case \"symbol\":\n case \"number\":\n return true;\n }\n\n return false;\n}\nfunction isObject(value) {\n return value !== null && typeof value === \"object\";\n}\nfunction isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n\n var proto = Object.getPrototypeOf(value);\n\n if (proto == null) {\n return true;\n }\n\n var protoConstructor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof protoConstructor === \"function\" && protoConstructor.toString() === plainObjectString;\n} // https://stackoverflow.com/a/37865170\n\nfunction isGenerator(obj) {\n var constructor = obj == null ? void 0 : obj.constructor;\n\n if (!constructor) {\n return false;\n }\n\n if (\"GeneratorFunction\" === constructor.name || \"GeneratorFunction\" === constructor.displayName) {\n return true;\n }\n\n return false;\n}\nfunction addHiddenProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\nfunction addHiddenFinalProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\nfunction createInstanceofPredicate(name, theClass) {\n var propName = \"isMobX\" + name;\n theClass.prototype[propName] = true;\n return function (x) {\n return isObject(x) && x[propName] === true;\n };\n}\nfunction isES6Map(thing) {\n return thing instanceof Map;\n}\nfunction isES6Set(thing) {\n return thing instanceof Set;\n}\nvar hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== \"undefined\";\n/**\r\n * Returns the following: own enumerable keys and symbols.\r\n */\n\nfunction getPlainObjectKeys(object) {\n var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway...\n\n if (!hasGetOwnPropertySymbols) {\n return keys;\n }\n\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (!symbols.length) {\n return keys;\n }\n\n return [].concat(keys, symbols.filter(function (s) {\n return objectPrototype.propertyIsEnumerable.call(object, s);\n }));\n} // From Immer utils\n// Returns all own keys, including non-enumerable and symbolic\n\nvar ownKeys = typeof Reflect !== \"undefined\" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {\n return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));\n} :\n/* istanbul ignore next */\nObject.getOwnPropertyNames;\nfunction stringifyKey(key) {\n if (typeof key === \"string\") {\n return key;\n }\n\n if (typeof key === \"symbol\") {\n return key.toString();\n }\n\n return new String(key).toString();\n}\nfunction toPrimitive(value) {\n return value === null ? null : typeof value === \"object\" ? \"\" + value : value;\n}\nfunction hasProp(target, prop) {\n return objectPrototype.hasOwnProperty.call(target, prop);\n} // From Immer utils\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {\n // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up\n\n ownKeys(target).forEach(function (key) {\n res[key] = getDescriptor(target, key);\n });\n return res;\n};\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n\n _setPrototypeOf(subClass, superClass);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n if (it) return (it = it.call(o)).next.bind(it);\n\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n return function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar storedAnnotationsSymbol = /*#__PURE__*/Symbol(\"mobx-stored-annotations\");\n/**\r\n * Creates a function that acts as\r\n * - decorator\r\n * - annotation object\r\n */\n\nfunction createDecoratorAnnotation(annotation) {\n function decorator(target, property) {\n storeAnnotation(target, property, annotation);\n }\n\n return Object.assign(decorator, annotation);\n}\n/**\r\n * Stores annotation to prototype,\r\n * so it can be inspected later by `makeObservable` called from constructor\r\n */\n\nfunction storeAnnotation(prototype, key, annotation) {\n if (!hasProp(prototype, storedAnnotationsSymbol)) {\n addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));\n } // @override must override something\n\n\n if ( true && isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n die(\"'\" + fieldName + \"' is decorated with 'override', \" + \"but no such decorated member was found on prototype.\");\n } // Cannot re-decorate\n\n\n assertNotDecorated(prototype, annotation, key); // Ignore override\n\n if (!isOverride(annotation)) {\n prototype[storedAnnotationsSymbol][key] = annotation;\n }\n}\n\nfunction assertNotDecorated(prototype, annotation, key) {\n if ( true && !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '@\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already decorated with '@\" + currentAnnotationType + \"'.\") + \"\\nRe-decorating fields is not allowed.\" + \"\\nUse '@override' decorator for methods overridden by subclass.\");\n }\n}\n/**\r\n * Collects annotations from prototypes and stores them on target (instance)\r\n */\n\n\nfunction collectStoredAnnotations(target) {\n if (!hasProp(target, storedAnnotationsSymbol)) {\n if ( true && !target[storedAnnotationsSymbol]) {\n die(\"No annotations were passed to makeObservable, but no decorated members have been found either\");\n } // We need a copy as we will remove annotation from the list once it's applied.\n\n\n addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));\n }\n\n return target[storedAnnotationsSymbol];\n}\n\nvar $mobx = /*#__PURE__*/Symbol(\"mobx administration\");\nvar Atom = /*#__PURE__*/function () {\n // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed\n\n /**\r\n * Create a new atom. For debugging purposes it is recommended to give it a name.\r\n * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.\r\n */\n function Atom(name_) {\n if (name_ === void 0) {\n name_ = true ? \"Atom@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.isPendingUnobservation_ = false;\n this.isBeingObserved_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n this.name_ = name_;\n } // onBecomeObservedListeners\n\n\n var _proto = Atom.prototype;\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Invoke this method to notify mobx that your atom has been used somehow.\r\n * Returns true if there is currently a reactive context.\r\n */\n ;\n\n _proto.reportObserved = function reportObserved$1() {\n return reportObserved(this);\n }\n /**\r\n * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.\r\n */\n ;\n\n _proto.reportChanged = function reportChanged() {\n startBatch();\n propagateChanged(this);\n endBatch();\n };\n\n _proto.toString = function toString() {\n return this.name_;\n };\n\n return Atom;\n}();\nvar isAtom = /*#__PURE__*/createInstanceofPredicate(\"Atom\", Atom);\nfunction createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {\n if (onBecomeObservedHandler === void 0) {\n onBecomeObservedHandler = noop;\n }\n\n if (onBecomeUnobservedHandler === void 0) {\n onBecomeUnobservedHandler = noop;\n }\n\n var atom = new Atom(name); // default `noop` listener will not initialize the hook Set\n\n if (onBecomeObservedHandler !== noop) {\n onBecomeObserved(atom, onBecomeObservedHandler);\n }\n\n if (onBecomeUnobservedHandler !== noop) {\n onBecomeUnobserved(atom, onBecomeUnobservedHandler);\n }\n\n return atom;\n}\n\nfunction identityComparer(a, b) {\n return a === b;\n}\n\nfunction structuralComparer(a, b) {\n return deepEqual(a, b);\n}\n\nfunction shallowComparer(a, b) {\n return deepEqual(a, b, 1);\n}\n\nfunction defaultComparer(a, b) {\n if (Object.is) {\n return Object.is(a, b);\n }\n\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n}\n\nvar comparer = {\n identity: identityComparer,\n structural: structuralComparer,\n \"default\": defaultComparer,\n shallow: shallowComparer\n};\n\nfunction deepEnhancer(v, _, name) {\n // it is an observable already, done\n if (isObservable(v)) {\n return v;\n } // something that can be converted and mutated?\n\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name\n });\n }\n\n if (typeof v === \"function\" && !isAction(v) && !isFlow(v)) {\n if (isGenerator(v)) {\n return flow(v);\n } else {\n return autoAction(name, v);\n }\n }\n\n return v;\n}\nfunction shallowEnhancer(v, _, name) {\n if (v === undefined || v === null) {\n return v;\n }\n\n if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {\n return v;\n }\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name,\n deep: false\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name,\n deep: false\n });\n }\n\n if (true) {\n die(\"The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets\");\n }\n}\nfunction referenceEnhancer(newValue) {\n // never turn into an observable\n return newValue;\n}\nfunction refStructEnhancer(v, oldValue) {\n if ( true && isObservable(v)) {\n die(\"observable.struct should not be used with observable values\");\n }\n\n if (deepEqual(v, oldValue)) {\n return oldValue;\n }\n\n return v;\n}\n\nvar OVERRIDE = \"override\";\nvar override = /*#__PURE__*/createDecoratorAnnotation({\n annotationType_: OVERRIDE,\n make_: make_,\n extend_: extend_\n});\nfunction isOverride(annotation) {\n return annotation.annotationType_ === OVERRIDE;\n}\n\nfunction make_(adm, key) {\n // Must not be plain object\n if ( true && adm.isPlainObject_) {\n die(\"Cannot apply '\" + this.annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + this.annotationType_ + \"' cannot be used on plain objects.\"));\n } // Must override something\n\n\n if ( true && !hasProp(adm.appliedAnnotations_, key)) {\n die(\"'\" + adm.name_ + \".\" + key.toString() + \"' is annotated with '\" + this.annotationType_ + \"', \" + \"but no such annotated member was found on prototype.\");\n }\n\n return 0\n /* Cancel */\n ;\n}\n\nfunction extend_(adm, key, descriptor, proxyTrap) {\n die(\"'\" + this.annotationType_ + \"' can only be used with 'makeObservable'\");\n}\n\nfunction createActionAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$1,\n extend_: extend_$1\n };\n}\n\nfunction make_$1(adm, key, descriptor, source) {\n var _this$options_;\n\n // bound\n if ((_this$options_ = this.options_) != null && _this$options_.bound) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n } // own\n\n\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n\n\n if (isAction(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);\n defineProperty(source, key, actionDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$1(adm, key, descriptor, proxyTrap) {\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);\n return adm.defineProperty_(key, actionDescriptor, proxyTrap);\n}\n\nfunction assertActionDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a function value.\"));\n }\n}\n\nfunction createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;\n\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertActionDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n\n if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {\n var _adm$proxy_;\n\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return {\n value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false, // https://github.com/mobxjs/mobx/discussions/3140\n (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createFlowAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$2,\n extend_: extend_$2\n };\n}\n\nfunction make_$2(adm, key, descriptor, source) {\n var _this$options_;\n\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n // bound - must annotate protos to support super.flow()\n\n\n if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {\n if (this.extend_(adm, key, descriptor, false) === null) {\n return 0\n /* Cancel */\n ;\n }\n }\n\n if (isFlow(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);\n defineProperty(source, key, flowDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$2(adm, key, descriptor, proxyTrap) {\n var _this$options_2;\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);\n return adm.defineProperty_(key, flowDescriptor, proxyTrap);\n}\n\nfunction assertFlowDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a generator function value.\"));\n }\n}\n\nfunction createFlowDescriptor(adm, annotation, key, descriptor, bound, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertFlowDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value; // In case of flow.bound, the descriptor can be from already annotated prototype\n\n if (!isFlow(value)) {\n value = flow(value);\n }\n\n if (bound) {\n var _adm$proxy_;\n\n // We do not keep original function around, so we bind the existing flow\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); // This is normally set by `flow`, but `bind` returns new function...\n\n value.isMobXFlow = true;\n }\n\n return {\n value: value,\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createComputedAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$3,\n extend_: extend_$3\n };\n}\n\nfunction make_$3(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$3(adm, key, descriptor, proxyTrap) {\n assertComputedDescriptor(adm, this, key, descriptor);\n return adm.defineComputedProperty_(key, _extends({}, this.options_, {\n get: descriptor.get,\n set: descriptor.set\n }), proxyTrap);\n}\n\nfunction assertComputedDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var get = _ref2.get;\n\n if ( true && !get) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on getter(+setter) properties.\"));\n }\n}\n\nfunction createObservableAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$4,\n extend_: extend_$4\n };\n}\n\nfunction make_$4(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$4(adm, key, descriptor, proxyTrap) {\n var _this$options_$enhanc, _this$options_;\n\n assertObservableDescriptor(adm, this, key, descriptor);\n return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap);\n}\n\nfunction assertObservableDescriptor(adm, _ref, key, descriptor) {\n var annotationType_ = _ref.annotationType_;\n\n if ( true && !(\"value\" in descriptor)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' cannot be used on getter/setter properties\"));\n }\n}\n\nvar AUTO = \"true\";\nvar autoAnnotation = /*#__PURE__*/createAutoAnnotation();\nfunction createAutoAnnotation(options) {\n return {\n annotationType_: AUTO,\n options_: options,\n make_: make_$5,\n extend_: extend_$5\n };\n}\n\nfunction make_$5(adm, key, descriptor, source) {\n var _this$options_3, _this$options_4;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.make_(adm, key, descriptor, source);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.make_\n var set = createAction(key.toString(), descriptor.set); // own\n\n if (source === adm.target_) {\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: set\n }) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // proto\n\n\n defineProperty(source, key, {\n configurable: true,\n set: set\n });\n return 2\n /* Continue */\n ;\n } // function on proto -> autoAction/flow\n\n\n if (source !== adm.target_ && typeof descriptor.value === \"function\") {\n var _this$options_2;\n\n if (isGenerator(descriptor.value)) {\n var _this$options_;\n\n var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;\n return flowAnnotation.make_(adm, key, descriptor, source);\n }\n\n var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;\n return actionAnnotation.make_(adm, key, descriptor, source);\n } // other -> observable\n // Copy props from proto as well, see test:\n // \"decorate should work with Object.create\"\n\n\n var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable; // if function respect autoBind option\n\n if (typeof descriptor.value === \"function\" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {\n var _adm$proxy_;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return observableAnnotation.make_(adm, key, descriptor, source);\n}\n\nfunction extend_$5(adm, key, descriptor, proxyTrap) {\n var _this$options_5, _this$options_6;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.extend_(adm, key, descriptor, proxyTrap);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.extend_\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: createAction(key.toString(), descriptor.set)\n }, proxyTrap);\n } // other -> observable\n // if function respect autoBind option\n\n\n if (typeof descriptor.value === \"function\" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {\n var _adm$proxy_2;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);\n }\n\n var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;\n return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);\n}\n\nvar OBSERVABLE = \"observable\";\nvar OBSERVABLE_REF = \"observable.ref\";\nvar OBSERVABLE_SHALLOW = \"observable.shallow\";\nvar OBSERVABLE_STRUCT = \"observable.struct\"; // Predefined bags of create observable options, to avoid allocating temporarily option objects\n// in the majority of cases\n\nvar defaultCreateObservableOptions = {\n deep: true,\n name: undefined,\n defaultDecorator: undefined,\n proxy: true\n};\nObject.freeze(defaultCreateObservableOptions);\nfunction asCreateObservableOptions(thing) {\n return thing || defaultCreateObservableOptions;\n}\nvar observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);\nvar observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {\n enhancer: referenceEnhancer\n});\nvar observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {\n enhancer: shallowEnhancer\n});\nvar observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {\n enhancer: refStructEnhancer\n});\nvar observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);\nfunction getEnhancerFromOptions(options) {\n return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);\n}\nfunction getAnnotationFromOptions(options) {\n var _options$defaultDecor;\n\n return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;\n}\nfunction getEnhancerFromAnnotation(annotation) {\n var _annotation$options_$, _annotation$options_;\n\n return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;\n}\n/**\r\n * Turns an object, array or function into a reactive structure.\r\n * @param v the value which should become observable.\r\n */\n\nfunction createObservable(v, arg2, arg3) {\n // @observable someProp;\n if (isStringish(arg2)) {\n storeAnnotation(v, arg2, observableAnnotation);\n return;\n } // already observable - ignore\n\n\n if (isObservable(v)) {\n return v;\n } // plain object\n\n\n if (isPlainObject(v)) {\n return observable.object(v, arg2, arg3);\n } // Array\n\n\n if (Array.isArray(v)) {\n return observable.array(v, arg2);\n } // Map\n\n\n if (isES6Map(v)) {\n return observable.map(v, arg2);\n } // Set\n\n\n if (isES6Set(v)) {\n return observable.set(v, arg2);\n } // other object - ignore\n\n\n if (typeof v === \"object\" && v !== null) {\n return v;\n } // anything else\n\n\n return observable.box(v, arg2);\n}\n\nObject.assign(createObservable, observableDecoratorAnnotation);\nvar observableFactories = {\n box: function box(value, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);\n },\n array: function array(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);\n },\n map: function map(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);\n },\n set: function set(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);\n },\n object: function object(props, decorators, options) {\n return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);\n },\n ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),\n shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),\n deep: observableDecoratorAnnotation,\n struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)\n}; // eslint-disable-next-line\n\nvar observable = /*#__PURE__*/assign(createObservable, observableFactories);\n\nvar COMPUTED = \"computed\";\nvar COMPUTED_STRUCT = \"computed.struct\";\nvar computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);\nvar computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {\n equals: comparer.structural\n});\n/**\r\n * Decorator for class properties: @computed get value() { return expr; }.\r\n * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;\r\n */\n\nvar computed = function computed(arg1, arg2) {\n if (isStringish(arg2)) {\n // @computed\n return storeAnnotation(arg1, arg2, computedAnnotation);\n }\n\n if (isPlainObject(arg1)) {\n // @computed({ options })\n return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));\n } // computed(expr, options?)\n\n\n if (true) {\n if (!isFunction(arg1)) {\n die(\"First argument to `computed` should be an expression.\");\n }\n\n if (isFunction(arg2)) {\n die(\"A setter as second argument is no longer supported, use `{ set: fn }` option instead\");\n }\n }\n\n var opts = isPlainObject(arg2) ? arg2 : {};\n opts.get = arg1;\n opts.name || (opts.name = arg1.name || \"\");\n /* for generated name */\n\n return new ComputedValue(opts);\n};\nObject.assign(computed, computedAnnotation);\ncomputed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);\n\nvar _getDescriptor$config, _getDescriptor;\n// mobx versions\n\nvar currentActionId = 0;\nvar nextActionId = 1;\nvar isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, \"name\")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object\n\nvar tmpNameDescriptor = {\n value: \"action\",\n configurable: true,\n writable: false,\n enumerable: false\n};\nfunction createAction(actionName, fn, autoAction, ref) {\n if (autoAction === void 0) {\n autoAction = false;\n }\n\n if (true) {\n if (!isFunction(fn)) {\n die(\"`action` can only be invoked on functions\");\n }\n\n if (typeof actionName !== \"string\" || !actionName) {\n die(\"actions should have valid names, got: '\" + actionName + \"'\");\n }\n }\n\n function res() {\n return executeAction(actionName, autoAction, fn, ref || this, arguments);\n }\n\n res.isMobxAction = true;\n\n if (isFunctionNameConfigurable) {\n tmpNameDescriptor.value = actionName;\n Object.defineProperty(res, \"name\", tmpNameDescriptor);\n }\n\n return res;\n}\nfunction executeAction(actionName, canRunAsDerivation, fn, scope, args) {\n var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);\n\n try {\n return fn.apply(scope, args);\n } catch (err) {\n runInfo.error_ = err;\n throw err;\n } finally {\n _endAction(runInfo);\n }\n}\nfunction _startAction(actionName, canRunAsDerivation, // true for autoAction\nscope, args) {\n var notifySpy_ = true && isSpyEnabled() && !!actionName;\n var startTime_ = 0;\n\n if ( true && notifySpy_) {\n startTime_ = Date.now();\n var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;\n spyReportStart({\n type: ACTION,\n name: actionName,\n object: scope,\n arguments: flattenedArgs\n });\n }\n\n var prevDerivation_ = globalState.trackingDerivation;\n var runAsAction = !canRunAsDerivation || !prevDerivation_;\n startBatch();\n var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow\n\n if (runAsAction) {\n untrackedStart();\n prevAllowStateChanges_ = allowStateChangesStart(true);\n }\n\n var prevAllowStateReads_ = allowStateReadsStart(true);\n var runInfo = {\n runAsAction_: runAsAction,\n prevDerivation_: prevDerivation_,\n prevAllowStateChanges_: prevAllowStateChanges_,\n prevAllowStateReads_: prevAllowStateReads_,\n notifySpy_: notifySpy_,\n startTime_: startTime_,\n actionId_: nextActionId++,\n parentActionId_: currentActionId\n };\n currentActionId = runInfo.actionId_;\n return runInfo;\n}\nfunction _endAction(runInfo) {\n if (currentActionId !== runInfo.actionId_) {\n die(30);\n }\n\n currentActionId = runInfo.parentActionId_;\n\n if (runInfo.error_ !== undefined) {\n globalState.suppressReactionErrors = true;\n }\n\n allowStateChangesEnd(runInfo.prevAllowStateChanges_);\n allowStateReadsEnd(runInfo.prevAllowStateReads_);\n endBatch();\n\n if (runInfo.runAsAction_) {\n untrackedEnd(runInfo.prevDerivation_);\n }\n\n if ( true && runInfo.notifySpy_) {\n spyReportEnd({\n time: Date.now() - runInfo.startTime_\n });\n }\n\n globalState.suppressReactionErrors = false;\n}\nfunction allowStateChanges(allowStateChanges, func) {\n var prev = allowStateChangesStart(allowStateChanges);\n\n try {\n return func();\n } finally {\n allowStateChangesEnd(prev);\n }\n}\nfunction allowStateChangesStart(allowStateChanges) {\n var prev = globalState.allowStateChanges;\n globalState.allowStateChanges = allowStateChanges;\n return prev;\n}\nfunction allowStateChangesEnd(prev) {\n globalState.allowStateChanges = prev;\n}\n\nvar _Symbol$toPrimitive;\nvar CREATE = \"create\";\n_Symbol$toPrimitive = Symbol.toPrimitive;\nvar ObservableValue = /*#__PURE__*/function (_Atom) {\n _inheritsLoose(ObservableValue, _Atom);\n\n function ObservableValue(value, enhancer, name_, notifySpy, equals) {\n var _this;\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableValue@\" + getNextId() : undefined;\n }\n\n if (notifySpy === void 0) {\n notifySpy = true;\n }\n\n if (equals === void 0) {\n equals = comparer[\"default\"];\n }\n\n _this = _Atom.call(this, name_) || this;\n _this.enhancer = void 0;\n _this.name_ = void 0;\n _this.equals = void 0;\n _this.hasUnreportedChange_ = false;\n _this.interceptors_ = void 0;\n _this.changeListeners_ = void 0;\n _this.value_ = void 0;\n _this.dehancer = void 0;\n _this.enhancer = enhancer;\n _this.name_ = name_;\n _this.equals = equals;\n _this.value_ = enhancer(value, undefined, name_);\n\n if ( true && notifySpy && isSpyEnabled()) {\n // only notify spy if this is a stand-alone observable\n spyReport({\n type: CREATE,\n object: _assertThisInitialized(_this),\n observableKind: \"value\",\n debugObjectName: _this.name_,\n newValue: \"\" + _this.value_\n });\n }\n\n return _this;\n }\n\n var _proto = ObservableValue.prototype;\n\n _proto.dehanceValue = function dehanceValue(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.set = function set(newValue) {\n var oldValue = this.value_;\n newValue = this.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n\n if ( true && notifySpy) {\n spyReportStart({\n type: UPDATE,\n object: this,\n observableKind: \"value\",\n debugObjectName: this.name_,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n\n this.setNewValue_(newValue);\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.prepareNewValue_ = function prepareNewValue_(newValue) {\n checkIfStateModificationsAreAllowed(this);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this,\n type: UPDATE,\n newValue: newValue\n });\n\n if (!change) {\n return globalState.UNCHANGED;\n }\n\n newValue = change.newValue;\n } // apply modifier\n\n\n newValue = this.enhancer(newValue, this.value_, this.name_);\n return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;\n };\n\n _proto.setNewValue_ = function setNewValue_(newValue) {\n var oldValue = this.value_;\n this.value_ = newValue;\n this.reportChanged();\n\n if (hasListeners(this)) {\n notifyListeners(this, {\n type: UPDATE,\n object: this,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n };\n\n _proto.get = function get() {\n this.reportObserved();\n return this.dehanceValue(this.value_);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately) {\n listener({\n observableKind: \"value\",\n debugObjectName: this.name_,\n object: this,\n type: UPDATE,\n newValue: this.value_,\n oldValue: undefined\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.raw = function raw() {\n // used by MST ot get undehanced value\n return this.value_;\n };\n\n _proto.toJSON = function toJSON() {\n return this.get();\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.value_ + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive] = function () {\n return this.valueOf();\n };\n\n return ObservableValue;\n}(Atom);\nvar isObservableValue = /*#__PURE__*/createInstanceofPredicate(\"ObservableValue\", ObservableValue);\n\nvar _Symbol$toPrimitive$1;\n/**\r\n * A node in the state dependency root that observes other nodes, and can be observed itself.\r\n *\r\n * ComputedValue will remember the result of the computation for the duration of the batch, or\r\n * while being observed.\r\n *\r\n * During this time it will recompute only when one of its direct dependencies changed,\r\n * but only when it is being accessed with `ComputedValue.get()`.\r\n *\r\n * Implementation description:\r\n * 1. First time it's being accessed it will compute and remember result\r\n * give back remembered result until 2. happens\r\n * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.\r\n * 3. When it's being accessed, recompute if any shallow dependency changed.\r\n * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.\r\n * go to step 2. either way\r\n *\r\n * If at any point it's outside batch and it isn't observed: reset everything and go to 1.\r\n */\n\n_Symbol$toPrimitive$1 = Symbol.toPrimitive;\nvar ComputedValue = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n // during tracking it's an array with new observed observers\n // to check for cycles\n // N.B: unminified as it is used by MST\n\n /**\r\n * Create a new computed value based on a function expression.\r\n *\r\n * The `name` property is for debug purposes only.\r\n *\r\n * The `equals` property specifies the comparer function to use to determine if a newly produced\r\n * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`\r\n * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.\r\n * Structural comparison can be convenient if you always produce a new aggregated object and\r\n * don't want to notify observers if it is structurally the same.\r\n * This is useful for working with vectors, mouse coordinates etc.\r\n */\n function ComputedValue(options) {\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.observing_ = [];\n this.newObserving_ = null;\n this.isBeingObserved_ = false;\n this.isPendingUnobservation_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n this.unboundDepsCount_ = 0;\n this.value_ = new CaughtException(null);\n this.name_ = void 0;\n this.triggeredBy_ = void 0;\n this.isComputing_ = false;\n this.isRunningSetter_ = false;\n this.derivation = void 0;\n this.setter_ = void 0;\n this.isTracing_ = TraceMode.NONE;\n this.scope_ = void 0;\n this.equals_ = void 0;\n this.requiresReaction_ = void 0;\n this.keepAlive_ = void 0;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n\n if (!options.get) {\n die(31);\n }\n\n this.derivation = options.get;\n this.name_ = options.name || ( true ? \"ComputedValue@\" + getNextId() : undefined);\n\n if (options.set) {\n this.setter_ = createAction( true ? this.name_ + \"-setter\" : undefined, options.set);\n }\n\n this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer[\"default\"]);\n this.scope_ = options.context;\n this.requiresReaction_ = options.requiresReaction;\n this.keepAlive_ = !!options.keepAlive;\n }\n\n var _proto = ComputedValue.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n propagateMaybeChanged(this);\n };\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Returns the current value of this computed value.\r\n * Will evaluate its computation first if needed.\r\n */\n ;\n\n _proto.get = function get() {\n if (this.isComputing_) {\n die(32, this.name_, this.derivation);\n }\n\n if (globalState.inBatch === 0 && // !globalState.trackingDerivatpion &&\n this.observers_.size === 0 && !this.keepAlive_) {\n if (shouldCompute(this)) {\n this.warnAboutUntrackedRead_();\n startBatch(); // See perf test 'computed memoization'\n\n this.value_ = this.computeValue_(false);\n endBatch();\n }\n } else {\n reportObserved(this);\n\n if (shouldCompute(this)) {\n var prevTrackingContext = globalState.trackingContext;\n\n if (this.keepAlive_ && !prevTrackingContext) {\n globalState.trackingContext = this;\n }\n\n if (this.trackAndCompute()) {\n propagateChangeConfirmed(this);\n }\n\n globalState.trackingContext = prevTrackingContext;\n }\n }\n\n var result = this.value_;\n\n if (isCaughtException(result)) {\n throw result.cause;\n }\n\n return result;\n };\n\n _proto.set = function set(value) {\n if (this.setter_) {\n if (this.isRunningSetter_) {\n die(33, this.name_);\n }\n\n this.isRunningSetter_ = true;\n\n try {\n this.setter_.call(this.scope_, value);\n } finally {\n this.isRunningSetter_ = false;\n }\n } else {\n die(34, this.name_);\n }\n };\n\n _proto.trackAndCompute = function trackAndCompute() {\n // N.B: unminified as it is used by MST\n var oldValue = this.value_;\n var wasSuspended =\n /* see #1208 */\n this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;\n var newValue = this.computeValue_(true);\n var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);\n\n if (changed) {\n this.value_ = newValue;\n\n if ( true && isSpyEnabled()) {\n spyReport({\n observableKind: \"computed\",\n debugObjectName: this.name_,\n object: this.scope_,\n type: \"update\",\n oldValue: oldValue,\n newValue: newValue\n });\n }\n }\n\n return changed;\n };\n\n _proto.computeValue_ = function computeValue_(track) {\n this.isComputing_ = true; // don't allow state changes during computation\n\n var prev = allowStateChangesStart(false);\n var res;\n\n if (track) {\n res = trackDerivedFunction(this, this.derivation, this.scope_);\n } else {\n if (globalState.disableErrorBoundaries === true) {\n res = this.derivation.call(this.scope_);\n } else {\n try {\n res = this.derivation.call(this.scope_);\n } catch (e) {\n res = new CaughtException(e);\n }\n }\n }\n\n allowStateChangesEnd(prev);\n this.isComputing_ = false;\n return res;\n };\n\n _proto.suspend_ = function suspend_() {\n if (!this.keepAlive_) {\n clearObserving(this);\n this.value_ = undefined; // don't hold on to computed value!\n\n if ( true && this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' was suspended and it will recompute on the next access.\");\n }\n }\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n var _this = this;\n\n var firstTime = true;\n var prevValue = undefined;\n return autorun(function () {\n // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place\n var newValue = _this.get();\n\n if (!firstTime || fireImmediately) {\n var prevU = untrackedStart();\n listener({\n observableKind: \"computed\",\n debugObjectName: _this.name_,\n type: UPDATE,\n object: _this,\n newValue: newValue,\n oldValue: prevValue\n });\n untrackedEnd(prevU);\n }\n\n firstTime = false;\n prevValue = newValue;\n });\n };\n\n _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {\n if (false) {}\n\n if (this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n\n if (typeof this.requiresReaction_ === \"boolean\" ? this.requiresReaction_ : globalState.computedRequiresReaction) {\n console.warn(\"[mobx] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.derivation.toString() + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive$1] = function () {\n return this.valueOf();\n };\n\n return ComputedValue;\n}();\nvar isComputedValue = /*#__PURE__*/createInstanceofPredicate(\"ComputedValue\", ComputedValue);\n\nvar IDerivationState_;\n\n(function (IDerivationState_) {\n // before being run or (outside batch and not being observed)\n // at this point derivation is not holding any data about dependency tree\n IDerivationState_[IDerivationState_[\"NOT_TRACKING_\"] = -1] = \"NOT_TRACKING_\"; // no shallow dependency changed since last computation\n // won't recalculate derivation\n // this is what makes mobx fast\n\n IDerivationState_[IDerivationState_[\"UP_TO_DATE_\"] = 0] = \"UP_TO_DATE_\"; // some deep dependency changed, but don't know if shallow dependency changed\n // will require to check first if UP_TO_DATE or POSSIBLY_STALE\n // currently only ComputedValue will propagate POSSIBLY_STALE\n //\n // having this state is second big optimization:\n // don't have to recompute on every dependency change, but only when it's needed\n\n IDerivationState_[IDerivationState_[\"POSSIBLY_STALE_\"] = 1] = \"POSSIBLY_STALE_\"; // A shallow dependency has changed since last computation and the derivation\n // will need to recompute when it's needed next.\n\n IDerivationState_[IDerivationState_[\"STALE_\"] = 2] = \"STALE_\";\n})(IDerivationState_ || (IDerivationState_ = {}));\n\nvar TraceMode;\n\n(function (TraceMode) {\n TraceMode[TraceMode[\"NONE\"] = 0] = \"NONE\";\n TraceMode[TraceMode[\"LOG\"] = 1] = \"LOG\";\n TraceMode[TraceMode[\"BREAK\"] = 2] = \"BREAK\";\n})(TraceMode || (TraceMode = {}));\n\nvar CaughtException = function CaughtException(cause) {\n this.cause = void 0;\n this.cause = cause; // Empty\n};\nfunction isCaughtException(e) {\n return e instanceof CaughtException;\n}\n/**\r\n * Finds out whether any dependency of the derivation has actually changed.\r\n * If dependenciesState is 1 then it will recalculate dependencies,\r\n * if any dependency changed it will propagate it by changing dependenciesState to 2.\r\n *\r\n * By iterating over the dependencies in the same order that they were reported and\r\n * stopping on the first change, all the recalculations are only called for ComputedValues\r\n * that will be tracked by derivation. That is because we assume that if the first x\r\n * dependencies of the derivation doesn't change then the derivation should run the same way\r\n * up until accessing x-th dependency.\r\n */\n\nfunction shouldCompute(derivation) {\n switch (derivation.dependenciesState_) {\n case IDerivationState_.UP_TO_DATE_:\n return false;\n\n case IDerivationState_.NOT_TRACKING_:\n case IDerivationState_.STALE_:\n return true;\n\n case IDerivationState_.POSSIBLY_STALE_:\n {\n // state propagation can occur outside of action/reactive context #2195\n var prevAllowStateReads = allowStateReadsStart(true);\n var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.\n\n var obs = derivation.observing_,\n l = obs.length;\n\n for (var i = 0; i < l; i++) {\n var obj = obs[i];\n\n if (isComputedValue(obj)) {\n if (globalState.disableErrorBoundaries) {\n obj.get();\n } else {\n try {\n obj.get();\n } catch (e) {\n // we are not interested in the value *or* exception at this moment, but if there is one, notify all\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.\n // and `derivation` is an observer of `obj`\n // invariantShouldCompute(derivation)\n\n\n if (derivation.dependenciesState_ === IDerivationState_.STALE_) {\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n }\n\n changeDependenciesStateTo0(derivation);\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return false;\n }\n }\n}\nfunction isComputingDerivation() {\n return globalState.trackingDerivation !== null; // filter out actions inside computations\n}\nfunction checkIfStateModificationsAreAllowed(atom) {\n if (false) {}\n\n var hasObservers = atom.observers_.size > 0; // Should not be possible to change observed state outside strict mode, except during initialization, see #563\n\n if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === \"always\")) {\n console.warn(\"[MobX] \" + (globalState.enforceActions ? \"Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: \" : \"Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: \") + atom.name_);\n }\n}\nfunction checkIfStateReadsAreAllowed(observable) {\n if ( true && !globalState.allowStateReads && globalState.observableRequiresReaction) {\n console.warn(\"[mobx] Observable '\" + observable.name_ + \"' being read outside a reactive context.\");\n }\n}\n/**\r\n * Executes the provided function `f` and tracks which observables are being accessed.\r\n * The tracking information is stored on the `derivation` object and the derivation is registered\r\n * as observer of any of the accessed observables.\r\n */\n\nfunction trackDerivedFunction(derivation, f, context) {\n var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps\n // array will be trimmed by bindDependencies\n\n changeDependenciesStateTo0(derivation);\n derivation.newObserving_ = new Array(derivation.observing_.length + 100);\n derivation.unboundDepsCount_ = 0;\n derivation.runId_ = ++globalState.runId;\n var prevTracking = globalState.trackingDerivation;\n globalState.trackingDerivation = derivation;\n globalState.inBatch++;\n var result;\n\n if (globalState.disableErrorBoundaries === true) {\n result = f.call(context);\n } else {\n try {\n result = f.call(context);\n } catch (e) {\n result = new CaughtException(e);\n }\n }\n\n globalState.inBatch--;\n globalState.trackingDerivation = prevTracking;\n bindDependencies(derivation);\n warnAboutDerivationWithoutDependencies(derivation);\n allowStateReadsEnd(prevAllowStateReads);\n return result;\n}\n\nfunction warnAboutDerivationWithoutDependencies(derivation) {\n if (false) {}\n\n if (derivation.observing_.length !== 0) {\n return;\n }\n\n if (typeof derivation.requiresObservable_ === \"boolean\" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {\n console.warn(\"[mobx] Derivation '\" + derivation.name_ + \"' is created/updated without reading any observable value.\");\n }\n}\n/**\r\n * diffs newObserving with observing.\r\n * update observing to be newObserving with unique observables\r\n * notify observers that become observed/unobserved\r\n */\n\n\nfunction bindDependencies(derivation) {\n // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, \"INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1\");\n var prevObserving = derivation.observing_;\n var observing = derivation.observing_ = derivation.newObserving_;\n var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; // Go through all new observables and check diffValue: (this list can contain duplicates):\n // 0: first occurrence, change to 1 and keep it\n // 1: extra occurrence, drop it\n\n var i0 = 0,\n l = derivation.unboundDepsCount_;\n\n for (var i = 0; i < l; i++) {\n var dep = observing[i];\n\n if (dep.diffValue_ === 0) {\n dep.diffValue_ = 1;\n\n if (i0 !== i) {\n observing[i0] = dep;\n }\n\n i0++;\n } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,\n // not hitting the condition\n\n\n if (dep.dependenciesState_ > lowestNewObservingDerivationState) {\n lowestNewObservingDerivationState = dep.dependenciesState_;\n }\n }\n\n observing.length = i0;\n derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)\n // Go through all old observables and check diffValue: (it is unique after last bindDependencies)\n // 0: it's not in new observables, unobserve it\n // 1: it keeps being observed, don't want to notify it. change to 0\n\n l = prevObserving.length;\n\n while (l--) {\n var _dep = prevObserving[l];\n\n if (_dep.diffValue_ === 0) {\n removeObserver(_dep, derivation);\n }\n\n _dep.diffValue_ = 0;\n } // Go through all new observables and check diffValue: (now it should be unique)\n // 0: it was set to 0 in last loop. don't need to do anything.\n // 1: it wasn't observed, let's observe it. set back to 0\n\n\n while (i0--) {\n var _dep2 = observing[i0];\n\n if (_dep2.diffValue_ === 1) {\n _dep2.diffValue_ = 0;\n addObserver(_dep2, derivation);\n }\n } // Some new observed derivations may become stale during this derivation computation\n // so they have had no chance to propagate staleness (#916)\n\n\n if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {\n derivation.dependenciesState_ = lowestNewObservingDerivationState;\n derivation.onBecomeStale_();\n }\n}\n\nfunction clearObserving(derivation) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR clearObserving should be called only inside batch\");\n var obs = derivation.observing_;\n derivation.observing_ = [];\n var i = obs.length;\n\n while (i--) {\n removeObserver(obs[i], derivation);\n }\n\n derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n}\nfunction untracked(action) {\n var prev = untrackedStart();\n\n try {\n return action();\n } finally {\n untrackedEnd(prev);\n }\n}\nfunction untrackedStart() {\n var prev = globalState.trackingDerivation;\n globalState.trackingDerivation = null;\n return prev;\n}\nfunction untrackedEnd(prev) {\n globalState.trackingDerivation = prev;\n}\nfunction allowStateReadsStart(allowStateReads) {\n var prev = globalState.allowStateReads;\n globalState.allowStateReads = allowStateReads;\n return prev;\n}\nfunction allowStateReadsEnd(prev) {\n globalState.allowStateReads = prev;\n}\n/**\r\n * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0\r\n *\r\n */\n\nfunction changeDependenciesStateTo0(derivation) {\n if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;\n var obs = derivation.observing_;\n var i = obs.length;\n\n while (i--) {\n obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n}\n\n/**\r\n * These values will persist if global state is reset\r\n */\n\nvar persistentKeys = [\"mobxGuid\", \"spyListeners\", \"enforceActions\", \"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"allowStateReads\", \"disableErrorBoundaries\", \"runId\", \"UNCHANGED\", \"useProxies\"];\nvar MobXGlobals = function MobXGlobals() {\n this.version = 6;\n this.UNCHANGED = {};\n this.trackingDerivation = null;\n this.trackingContext = null;\n this.runId = 0;\n this.mobxGuid = 0;\n this.inBatch = 0;\n this.pendingUnobservations = [];\n this.pendingReactions = [];\n this.isRunningReactions = false;\n this.allowStateChanges = false;\n this.allowStateReads = true;\n this.enforceActions = true;\n this.spyListeners = [];\n this.globalReactionErrorHandlers = [];\n this.computedRequiresReaction = false;\n this.reactionRequiresObservable = false;\n this.observableRequiresReaction = false;\n this.disableErrorBoundaries = false;\n this.suppressReactionErrors = false;\n this.useProxies = true;\n this.verifyProxies = false;\n this.safeDescriptors = true;\n};\nvar canMergeGlobalState = true;\nvar isolateCalled = false;\nvar globalState = /*#__PURE__*/function () {\n var global = /*#__PURE__*/getGlobal();\n\n if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {\n canMergeGlobalState = false;\n }\n\n if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {\n canMergeGlobalState = false;\n }\n\n if (!canMergeGlobalState) {\n // Because this is a IIFE we need to let isolateCalled a chance to change\n // so we run it after the event loop completed at least 1 iteration\n setTimeout(function () {\n if (!isolateCalled) {\n die(35);\n }\n }, 1);\n return new MobXGlobals();\n } else if (global.__mobxGlobals) {\n global.__mobxInstanceCount += 1;\n\n if (!global.__mobxGlobals.UNCHANGED) {\n global.__mobxGlobals.UNCHANGED = {};\n } // make merge backward compatible\n\n\n return global.__mobxGlobals;\n } else {\n global.__mobxInstanceCount = 1;\n return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();\n }\n}();\nfunction isolateGlobalState() {\n if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {\n die(36);\n }\n\n isolateCalled = true;\n\n if (canMergeGlobalState) {\n var global = getGlobal();\n\n if (--global.__mobxInstanceCount === 0) {\n global.__mobxGlobals = undefined;\n }\n\n globalState = new MobXGlobals();\n }\n}\nfunction getGlobalState() {\n return globalState;\n}\n/**\r\n * For testing purposes only; this will break the internal state of existing observables,\r\n * but can be used to get back at a stable state after throwing errors\r\n */\n\nfunction resetGlobalState() {\n var defaultGlobals = new MobXGlobals();\n\n for (var key in defaultGlobals) {\n if (persistentKeys.indexOf(key) === -1) {\n globalState[key] = defaultGlobals[key];\n }\n }\n\n globalState.allowStateChanges = !globalState.enforceActions;\n}\n\nfunction hasObservers(observable) {\n return observable.observers_ && observable.observers_.size > 0;\n}\nfunction getObservers(observable) {\n return observable.observers_;\n} // function invariantObservers(observable: IObservable) {\n// const list = observable.observers\n// const map = observable.observersIndexes\n// const l = list.length\n// for (let i = 0; i < l; i++) {\n// const id = list[i].__mapid\n// if (i) {\n// invariant(map[id] === i, \"INTERNAL ERROR maps derivation.__mapid to index in list\") // for performance\n// } else {\n// invariant(!(id in map), \"INTERNAL ERROR observer on index 0 shouldn't be held in map.\") // for performance\n// }\n// }\n// invariant(\n// list.length === 0 || Object.keys(map).length === list.length - 1,\n// \"INTERNAL ERROR there is no junk in map\"\n// )\n// }\n\nfunction addObserver(observable, node) {\n // invariant(node.dependenciesState !== -1, \"INTERNAL ERROR, can add only dependenciesState !== -1\");\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR add already added node\");\n // invariantObservers(observable);\n observable.observers_.add(node);\n\n if (observable.lowestObserverState_ > node.dependenciesState_) {\n observable.lowestObserverState_ = node.dependenciesState_;\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR didn't add node\");\n\n}\nfunction removeObserver(observable, node) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR, remove should be called only inside batch\");\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR remove already removed node\");\n // invariantObservers(observable);\n observable.observers_[\"delete\"](node);\n\n if (observable.observers_.size === 0) {\n // deleting last observer\n queueForUnobservation(observable);\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR remove already removed node2\");\n\n}\nfunction queueForUnobservation(observable) {\n if (observable.isPendingUnobservation_ === false) {\n // invariant(observable._observers.length === 0, \"INTERNAL ERROR, should only queue for unobservation unobserved observables\");\n observable.isPendingUnobservation_ = true;\n globalState.pendingUnobservations.push(observable);\n }\n}\n/**\r\n * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.\r\n * During a batch `onBecomeUnobserved` will be called at most once per observable.\r\n * Avoids unnecessary recalculations.\r\n */\n\nfunction startBatch() {\n globalState.inBatch++;\n}\nfunction endBatch() {\n if (--globalState.inBatch === 0) {\n runReactions(); // the batch is actually about to finish, all unobserving should happen here.\n\n var list = globalState.pendingUnobservations;\n\n for (var i = 0; i < list.length; i++) {\n var observable = list[i];\n observable.isPendingUnobservation_ = false;\n\n if (observable.observers_.size === 0) {\n if (observable.isBeingObserved_) {\n // if this observable had reactive observers, trigger the hooks\n observable.isBeingObserved_ = false;\n observable.onBUO();\n }\n\n if (observable instanceof ComputedValue) {\n // computed values are automatically teared down when the last observer leaves\n // this process happens recursively, this computed might be the last observabe of another, etc..\n observable.suspend_();\n }\n }\n }\n\n globalState.pendingUnobservations = [];\n }\n}\nfunction reportObserved(observable) {\n checkIfStateReadsAreAllowed(observable);\n var derivation = globalState.trackingDerivation;\n\n if (derivation !== null) {\n /**\r\n * Simple optimization, give each derivation run an unique id (runId)\r\n * Check if last time this observable was accessed the same runId is used\r\n * if this is the case, the relation is already known\r\n */\n if (derivation.runId_ !== observable.lastAccessedBy_) {\n observable.lastAccessedBy_ = derivation.runId_; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...\n\n derivation.newObserving_[derivation.unboundDepsCount_++] = observable;\n\n if (!observable.isBeingObserved_ && globalState.trackingContext) {\n observable.isBeingObserved_ = true;\n observable.onBO();\n }\n }\n\n return observable.isBeingObserved_;\n } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {\n queueForUnobservation(observable);\n }\n\n return false;\n} // function invariantLOS(observable: IObservable, msg: string) {\n// // it's expensive so better not run it in produciton. but temporarily helpful for testing\n// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)\n// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`\n// throw new Error(\n// \"lowestObserverState is wrong for \" +\n// msg +\n// \" because \" +\n// min +\n// \" < \" +\n// observable.lowestObserverState\n// )\n// }\n\n/**\r\n * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly\r\n * It will propagate changes to observers from previous run\r\n * It's hard or maybe impossible (with reasonable perf) to get it right with current approach\r\n * Hopefully self reruning autoruns aren't a feature people should depend on\r\n * Also most basic use cases should be ok\r\n */\n// Called by Atom when its value changes\n\nfunction propagateChanged(observable) {\n // invariantLOS(observable, \"changed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_; // Ideally we use for..of here, but the downcompiled version is really slow...\n\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n\n d.onBecomeStale_();\n }\n\n d.dependenciesState_ = IDerivationState_.STALE_;\n }); // invariantLOS(observable, \"changed end\");\n} // Called by ComputedValue when it recalculate and its value changed\n\nfunction propagateChangeConfirmed(observable) {\n // invariantLOS(observable, \"confirmed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {\n d.dependenciesState_ = IDerivationState_.STALE_;\n\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.\n ) {\n observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n }); // invariantLOS(observable, \"confirmed end\");\n} // Used by computed when its dependency changed, but we don't wan't to immediately recompute.\n\nfunction propagateMaybeChanged(observable) {\n // invariantLOS(observable, \"maybe start\");\n if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;\n d.onBecomeStale_();\n }\n }); // invariantLOS(observable, \"maybe end\");\n}\n\nfunction logTraceInfo(derivation, observable) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' is invalidated due to a change in: '\" + observable.name_ + \"'\");\n\n if (derivation.isTracing_ === TraceMode.BREAK) {\n var lines = [];\n printDepTree(getDependencyTree(derivation), lines, 1); // prettier-ignore\n\n new Function(\"debugger;\\n/*\\nTracing '\" + derivation.name_ + \"'\\n\\nYou are entering this break point because derivation '\" + derivation.name_ + \"' is being traced and '\" + observable.name_ + \"' is now forcing it to update.\\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\\n\\n\" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\\//g, \"/\") : \"\") + \"\\n\\nThe dependencies for this derivation are:\\n\\n\" + lines.join(\"\\n\") + \"\\n*/\\n \")();\n }\n}\n\nfunction printDepTree(tree, lines, depth) {\n if (lines.length >= 1000) {\n lines.push(\"(and many more)\");\n return;\n }\n\n lines.push(\"\" + \"\\t\".repeat(depth - 1) + tree.name);\n\n if (tree.dependencies) {\n tree.dependencies.forEach(function (child) {\n return printDepTree(child, lines, depth + 1);\n });\n }\n}\n\nvar Reaction = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {\n if (name_ === void 0) {\n name_ = true ? \"Reaction@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.onInvalidate_ = void 0;\n this.errorHandler_ = void 0;\n this.requiresObservable_ = void 0;\n this.observing_ = [];\n this.newObserving_ = [];\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.unboundDepsCount_ = 0;\n this.isDisposed_ = false;\n this.isScheduled_ = false;\n this.isTrackPending_ = false;\n this.isRunning_ = false;\n this.isTracing_ = TraceMode.NONE;\n this.name_ = name_;\n this.onInvalidate_ = onInvalidate_;\n this.errorHandler_ = errorHandler_;\n this.requiresObservable_ = requiresObservable_;\n }\n\n var _proto = Reaction.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n this.schedule_();\n };\n\n _proto.schedule_ = function schedule_() {\n if (!this.isScheduled_) {\n this.isScheduled_ = true;\n globalState.pendingReactions.push(this);\n runReactions();\n }\n };\n\n _proto.isScheduled = function isScheduled() {\n return this.isScheduled_;\n }\n /**\r\n * internal, use schedule() if you intend to kick off a reaction\r\n */\n ;\n\n _proto.runReaction_ = function runReaction_() {\n if (!this.isDisposed_) {\n startBatch();\n this.isScheduled_ = false;\n var prev = globalState.trackingContext;\n globalState.trackingContext = this;\n\n if (shouldCompute(this)) {\n this.isTrackPending_ = true;\n\n try {\n this.onInvalidate_();\n\n if ( true && this.isTrackPending_ && isSpyEnabled()) {\n // onInvalidate didn't trigger track right away..\n spyReport({\n name: this.name_,\n type: \"scheduled-reaction\"\n });\n }\n } catch (e) {\n this.reportExceptionInDerivation_(e);\n }\n }\n\n globalState.trackingContext = prev;\n endBatch();\n }\n };\n\n _proto.track = function track(fn) {\n if (this.isDisposed_) {\n return; // console.warn(\"Reaction already disposed\") // Note: Not a warning / error in mobx 4 either\n }\n\n startBatch();\n var notify = isSpyEnabled();\n var startTime;\n\n if ( true && notify) {\n startTime = Date.now();\n spyReportStart({\n name: this.name_,\n type: \"reaction\"\n });\n }\n\n this.isRunning_ = true;\n var prevReaction = globalState.trackingContext; // reactions could create reactions...\n\n globalState.trackingContext = this;\n var result = trackDerivedFunction(this, fn, undefined);\n globalState.trackingContext = prevReaction;\n this.isRunning_ = false;\n this.isTrackPending_ = false;\n\n if (this.isDisposed_) {\n // disposed during last run. Clean up everything that was bound after the dispose call.\n clearObserving(this);\n }\n\n if (isCaughtException(result)) {\n this.reportExceptionInDerivation_(result.cause);\n }\n\n if ( true && notify) {\n spyReportEnd({\n time: Date.now() - startTime\n });\n }\n\n endBatch();\n };\n\n _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {\n var _this = this;\n\n if (this.errorHandler_) {\n this.errorHandler_(error, this);\n return;\n }\n\n if (globalState.disableErrorBoundaries) {\n throw error;\n }\n\n var message = true ? \"[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '\" + this + \"'\" : undefined;\n\n if (!globalState.suppressReactionErrors) {\n console.error(message, error);\n /** If debugging brought you here, please, read the above message :-). Tnx! */\n } else if (true) {\n console.warn(\"[mobx] (error in reaction '\" + this.name_ + \"' suppressed, fix error of causing action below)\");\n } // prettier-ignore\n\n\n if ( true && isSpyEnabled()) {\n spyReport({\n type: \"error\",\n name: this.name_,\n message: message,\n error: \"\" + error\n });\n }\n\n globalState.globalReactionErrorHandlers.forEach(function (f) {\n return f(error, _this);\n });\n };\n\n _proto.dispose = function dispose() {\n if (!this.isDisposed_) {\n this.isDisposed_ = true;\n\n if (!this.isRunning_) {\n // if disposed while running, clean up later. Maybe not optimal, but rare case\n startBatch();\n clearObserving(this);\n endBatch();\n }\n }\n };\n\n _proto.getDisposer_ = function getDisposer_() {\n var r = this.dispose.bind(this);\n r[$mobx] = this;\n return r;\n };\n\n _proto.toString = function toString() {\n return \"Reaction[\" + this.name_ + \"]\";\n };\n\n _proto.trace = function trace$1(enterBreakPoint) {\n if (enterBreakPoint === void 0) {\n enterBreakPoint = false;\n }\n\n trace(this, enterBreakPoint);\n };\n\n return Reaction;\n}();\nfunction onReactionError(handler) {\n globalState.globalReactionErrorHandlers.push(handler);\n return function () {\n var idx = globalState.globalReactionErrorHandlers.indexOf(handler);\n\n if (idx >= 0) {\n globalState.globalReactionErrorHandlers.splice(idx, 1);\n }\n };\n}\n/**\r\n * Magic number alert!\r\n * Defines within how many times a reaction is allowed to re-trigger itself\r\n * until it is assumed that this is gonna be a never ending loop...\r\n */\n\nvar MAX_REACTION_ITERATIONS = 100;\n\nvar reactionScheduler = function reactionScheduler(f) {\n return f();\n};\n\nfunction runReactions() {\n // Trampolining, if runReactions are already running, new reactions will be picked up\n if (globalState.inBatch > 0 || globalState.isRunningReactions) {\n return;\n }\n\n reactionScheduler(runReactionsHelper);\n}\n\nfunction runReactionsHelper() {\n globalState.isRunningReactions = true;\n var allReactions = globalState.pendingReactions;\n var iterations = 0; // While running reactions, new reactions might be triggered.\n // Hence we work with two variables and check whether\n // we converge to no remaining reactions after a while.\n\n while (allReactions.length > 0) {\n if (++iterations === MAX_REACTION_ITERATIONS) {\n console.error( true ? \"Reaction doesn't converge to a stable state after \" + MAX_REACTION_ITERATIONS + \" iterations.\" + (\" Probably there is a cycle in the reactive function: \" + allReactions[0]) : undefined);\n allReactions.splice(0); // clear reactions\n }\n\n var remainingReactions = allReactions.splice(0);\n\n for (var i = 0, l = remainingReactions.length; i < l; i++) {\n remainingReactions[i].runReaction_();\n }\n }\n\n globalState.isRunningReactions = false;\n}\n\nvar isReaction = /*#__PURE__*/createInstanceofPredicate(\"Reaction\", Reaction);\nfunction setReactionScheduler(fn) {\n var baseScheduler = reactionScheduler;\n\n reactionScheduler = function reactionScheduler(f) {\n return fn(function () {\n return baseScheduler(f);\n });\n };\n}\n\nfunction isSpyEnabled() {\n return true && !!globalState.spyListeners.length;\n}\nfunction spyReport(event) {\n if (false) {} // dead code elimination can do the rest\n\n\n if (!globalState.spyListeners.length) {\n return;\n }\n\n var listeners = globalState.spyListeners;\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](event);\n }\n}\nfunction spyReportStart(event) {\n if (false) {}\n\n var change = _extends({}, event, {\n spyReportStart: true\n });\n\n spyReport(change);\n}\nvar END_EVENT = {\n type: \"report-end\",\n spyReportEnd: true\n};\nfunction spyReportEnd(change) {\n if (false) {}\n\n if (change) {\n spyReport(_extends({}, change, {\n type: \"report-end\",\n spyReportEnd: true\n }));\n } else {\n spyReport(END_EVENT);\n }\n}\nfunction spy(listener) {\n if (false) {} else {\n globalState.spyListeners.push(listener);\n return once(function () {\n globalState.spyListeners = globalState.spyListeners.filter(function (l) {\n return l !== listener;\n });\n });\n }\n}\n\nvar ACTION = \"action\";\nvar ACTION_BOUND = \"action.bound\";\nvar AUTOACTION = \"autoAction\";\nvar AUTOACTION_BOUND = \"autoAction.bound\";\nvar DEFAULT_ACTION_NAME = \"\";\nvar actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);\nvar actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {\n bound: true\n});\nvar autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {\n autoAction: true\n});\nvar autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {\n autoAction: true,\n bound: true\n});\n\nfunction createActionFactory(autoAction) {\n var res = function action(arg1, arg2) {\n // action(fn() {})\n if (isFunction(arg1)) {\n return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);\n } // action(\"name\", fn() {})\n\n\n if (isFunction(arg2)) {\n return createAction(arg1, arg2, autoAction);\n } // @action\n\n\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);\n } // action(\"name\") & @action(\"name\")\n\n\n if (isStringish(arg1)) {\n return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {\n name: arg1,\n autoAction: autoAction\n }));\n }\n\n if (true) {\n die(\"Invalid arguments for `action`\");\n }\n };\n\n return res;\n}\n\nvar action = /*#__PURE__*/createActionFactory(false);\nObject.assign(action, actionAnnotation);\nvar autoAction = /*#__PURE__*/createActionFactory(true);\nObject.assign(autoAction, autoActionAnnotation);\naction.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);\nautoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);\nfunction runInAction(fn) {\n return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);\n}\nfunction isAction(thing) {\n return isFunction(thing) && thing.isMobxAction === true;\n}\n\n/**\r\n * Creates a named reactive view and keeps it alive, so that the view is always\r\n * updated if one of the dependencies changes, even when the view is not further used by something else.\r\n * @param view The reactive view\r\n * @returns disposer function, which can be used to stop the view from being updated in the future.\r\n */\n\nfunction autorun(view, opts) {\n var _opts$name, _opts;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(view)) {\n die(\"Autorun expects a function as first argument\");\n }\n\n if (isAction(view)) {\n die(\"Autorun does not accept actions since actions are untrackable\");\n }\n }\n\n var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : true ? view.name || \"Autorun@\" + getNextId() : undefined;\n var runSync = !opts.scheduler && !opts.delay;\n var reaction;\n\n if (runSync) {\n // normal autorun\n reaction = new Reaction(name, function () {\n this.track(reactionRunner);\n }, opts.onError, opts.requiresObservable);\n } else {\n var scheduler = createSchedulerFromOptions(opts); // debounced autorun\n\n var isScheduled = false;\n reaction = new Reaction(name, function () {\n if (!isScheduled) {\n isScheduled = true;\n scheduler(function () {\n isScheduled = false;\n\n if (!reaction.isDisposed_) {\n reaction.track(reactionRunner);\n }\n });\n }\n }, opts.onError, opts.requiresObservable);\n }\n\n function reactionRunner() {\n view(reaction);\n }\n\n reaction.schedule_();\n return reaction.getDisposer_();\n}\n\nvar run = function run(f) {\n return f();\n};\n\nfunction createSchedulerFromOptions(opts) {\n return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {\n return setTimeout(f, opts.delay);\n } : run;\n}\n\nfunction reaction(expression, effect, opts) {\n var _opts$name2;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(expression) || !isFunction(effect)) {\n die(\"First and second argument to reaction should be functions\");\n }\n\n if (!isPlainObject(opts)) {\n die(\"Third argument of reactions should be an object\");\n }\n }\n\n var name = (_opts$name2 = opts.name) != null ? _opts$name2 : true ? \"Reaction@\" + getNextId() : undefined;\n var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);\n var runSync = !opts.scheduler && !opts.delay;\n var scheduler = createSchedulerFromOptions(opts);\n var firstTime = true;\n var isScheduled = false;\n var value;\n var oldValue;\n var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer[\"default\"];\n var r = new Reaction(name, function () {\n if (firstTime || runSync) {\n reactionRunner();\n } else if (!isScheduled) {\n isScheduled = true;\n scheduler(reactionRunner);\n }\n }, opts.onError, opts.requiresObservable);\n\n function reactionRunner() {\n isScheduled = false;\n\n if (r.isDisposed_) {\n return;\n }\n\n var changed = false;\n r.track(function () {\n var nextValue = allowStateChanges(false, function () {\n return expression(r);\n });\n changed = firstTime || !equals(value, nextValue);\n oldValue = value;\n value = nextValue;\n });\n\n if (firstTime && opts.fireImmediately) {\n effectAction(value, oldValue, r);\n } else if (!firstTime && changed) {\n effectAction(value, oldValue, r);\n }\n\n firstTime = false;\n }\n\n r.schedule_();\n return r.getDisposer_();\n}\n\nfunction wrapErrorHandler(errorHandler, baseFn) {\n return function () {\n try {\n return baseFn.apply(this, arguments);\n } catch (e) {\n errorHandler.call(this, e);\n }\n };\n}\n\nvar ON_BECOME_OBSERVED = \"onBO\";\nvar ON_BECOME_UNOBSERVED = \"onBUO\";\nfunction onBecomeObserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);\n}\nfunction onBecomeUnobserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);\n}\n\nfunction interceptHook(hook, thing, arg2, arg3) {\n var atom = typeof arg3 === \"function\" ? getAtom(thing, arg2) : getAtom(thing);\n var cb = isFunction(arg3) ? arg3 : arg2;\n var listenersKey = hook + \"L\";\n\n if (atom[listenersKey]) {\n atom[listenersKey].add(cb);\n } else {\n atom[listenersKey] = new Set([cb]);\n }\n\n return function () {\n var hookListeners = atom[listenersKey];\n\n if (hookListeners) {\n hookListeners[\"delete\"](cb);\n\n if (hookListeners.size === 0) {\n delete atom[listenersKey];\n }\n }\n };\n}\n\nvar NEVER = \"never\";\nvar ALWAYS = \"always\";\nvar OBSERVED = \"observed\"; // const IF_AVAILABLE = \"ifavailable\"\n\nfunction configure(options) {\n if (options.isolateGlobalState === true) {\n isolateGlobalState();\n }\n\n var useProxies = options.useProxies,\n enforceActions = options.enforceActions;\n\n if (useProxies !== undefined) {\n globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== \"undefined\";\n }\n\n if (useProxies === \"ifavailable\") {\n globalState.verifyProxies = true;\n }\n\n if (enforceActions !== undefined) {\n var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;\n globalState.enforceActions = ea;\n globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;\n }\n [\"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"disableErrorBoundaries\", \"safeDescriptors\"].forEach(function (key) {\n if (key in options) {\n globalState[key] = !!options[key];\n }\n });\n globalState.allowStateReads = !globalState.observableRequiresReaction;\n\n if ( true && globalState.disableErrorBoundaries === true) {\n console.warn(\"WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.\");\n }\n\n if (options.reactionScheduler) {\n setReactionScheduler(options.reactionScheduler);\n }\n}\n\nfunction extendObservable(target, properties, annotations, options) {\n if (true) {\n if (arguments.length > 4) {\n die(\"'extendObservable' expected 2-4 arguments\");\n }\n\n if (typeof target !== \"object\") {\n die(\"'extendObservable' expects an object as first argument\");\n }\n\n if (isObservableMap(target)) {\n die(\"'extendObservable' should not be used on maps, use map.merge instead\");\n }\n\n if (!isPlainObject(properties)) {\n die(\"'extendObservable' only accepts plain objects as second argument\");\n }\n\n if (isObservable(properties) || isObservable(annotations)) {\n die(\"Extending an object with another observable (object) is not supported\");\n }\n } // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)\n\n\n var descriptors = getOwnPropertyDescriptors(properties);\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n ownKeys(descriptors).forEach(function (key) {\n adm.extend_(key, descriptors[key], // must pass \"undefined\" for { key: undefined }\n !annotations ? true : key in annotations ? annotations[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nfunction getDependencyTree(thing, property) {\n return nodeToDependencyTree(getAtom(thing, property));\n}\n\nfunction nodeToDependencyTree(node) {\n var result = {\n name: node.name_\n };\n\n if (node.observing_ && node.observing_.length > 0) {\n result.dependencies = unique(node.observing_).map(nodeToDependencyTree);\n }\n\n return result;\n}\n\nfunction getObserverTree(thing, property) {\n return nodeToObserverTree(getAtom(thing, property));\n}\n\nfunction nodeToObserverTree(node) {\n var result = {\n name: node.name_\n };\n\n if (hasObservers(node)) {\n result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);\n }\n\n return result;\n}\n\nfunction unique(list) {\n return Array.from(new Set(list));\n}\n\nvar generatorId = 0;\nfunction FlowCancellationError() {\n this.message = \"FLOW_CANCELLED\";\n}\nFlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);\nfunction isFlowCancellationError(error) {\n return error instanceof FlowCancellationError;\n}\nvar flowAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow\");\nvar flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow.bound\", {\n bound: true\n});\nvar flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {\n // @flow\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, flowAnnotation);\n } // flow(fn)\n\n\n if ( true && arguments.length !== 1) {\n die(\"Flow expects single argument with generator function\");\n }\n\n var generator = arg1;\n var name = generator.name || \"\"; // Implementation based on https://github.com/tj/co/blob/master/index.js\n\n var res = function res() {\n var ctx = this;\n var args = arguments;\n var runId = ++generatorId;\n var gen = action(name + \" - runid: \" + runId + \" - init\", generator).apply(ctx, args);\n var rejector;\n var pendingPromise = undefined;\n var promise = new Promise(function (resolve, reject) {\n var stepId = 0;\n rejector = reject;\n\n function onFulfilled(res) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen.next).call(gen, res);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function onRejected(err) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen[\"throw\"]).call(gen, err);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function next(ret) {\n if (isFunction(ret == null ? void 0 : ret.then)) {\n // an async iterator\n ret.then(next, reject);\n return;\n }\n\n if (ret.done) {\n return resolve(ret.value);\n }\n\n pendingPromise = Promise.resolve(ret.value);\n return pendingPromise.then(onFulfilled, onRejected);\n }\n\n onFulfilled(undefined); // kick off the process\n });\n promise.cancel = action(name + \" - runid: \" + runId + \" - cancel\", function () {\n try {\n if (pendingPromise) {\n cancelPromise(pendingPromise);\n } // Finally block can return (or yield) stuff..\n\n\n var _res = gen[\"return\"](undefined); // eat anything that promise would do, it's cancelled!\n\n\n var yieldedPromise = Promise.resolve(_res.value);\n yieldedPromise.then(noop, noop);\n cancelPromise(yieldedPromise); // maybe it can be cancelled :)\n // reject our original promise\n\n rejector(new FlowCancellationError());\n } catch (e) {\n rejector(e); // there could be a throwing finally block\n }\n });\n return promise;\n };\n\n res.isMobXFlow = true;\n return res;\n}, flowAnnotation);\nflow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);\n\nfunction cancelPromise(promise) {\n if (isFunction(promise.cancel)) {\n promise.cancel();\n }\n}\n\nfunction flowResult(result) {\n return result; // just tricking TypeScript :)\n}\nfunction isFlow(fn) {\n return (fn == null ? void 0 : fn.isMobXFlow) === true;\n}\n\nfunction interceptReads(thing, propOrHandler, handler) {\n var target;\n\n if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {\n target = getAdministration(thing);\n } else if (isObservableObject(thing)) {\n if ( true && !isStringish(propOrHandler)) {\n return die(\"InterceptReads can only be used with a specific property, not with an object in general\");\n }\n\n target = getAdministration(thing, propOrHandler);\n } else if (true) {\n return die(\"Expected observable map, object or array as first array\");\n }\n\n if ( true && target.dehancer !== undefined) {\n return die(\"An intercept reader was already established\");\n }\n\n target.dehancer = typeof propOrHandler === \"function\" ? propOrHandler : handler;\n return function () {\n target.dehancer = undefined;\n };\n}\n\nfunction intercept(thing, propOrHandler, handler) {\n if (isFunction(handler)) {\n return interceptProperty(thing, propOrHandler, handler);\n } else {\n return interceptInterceptable(thing, propOrHandler);\n }\n}\n\nfunction interceptInterceptable(thing, handler) {\n return getAdministration(thing).intercept_(handler);\n}\n\nfunction interceptProperty(thing, property, handler) {\n return getAdministration(thing, property).intercept_(handler);\n}\n\nfunction _isComputed(value, property) {\n if (property === undefined) {\n return isComputedValue(value);\n }\n\n if (isObservableObject(value) === false) {\n return false;\n }\n\n if (!value[$mobx].values_.has(property)) {\n return false;\n }\n\n var atom = getAtom(value, property);\n return isComputedValue(atom);\n}\nfunction isComputed(value) {\n if ( true && arguments.length > 1) {\n return die(\"isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property\");\n }\n\n return _isComputed(value);\n}\nfunction isComputedProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"isComputed expected a property name as second argument\");\n }\n\n return _isComputed(value, propName);\n}\n\nfunction _isObservable(value, property) {\n if (!value) {\n return false;\n }\n\n if (property !== undefined) {\n if ( true && (isObservableMap(value) || isObservableArray(value))) {\n return die(\"isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.\");\n }\n\n if (isObservableObject(value)) {\n return value[$mobx].values_.has(property);\n }\n\n return false;\n } // For first check, see #701\n\n\n return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);\n}\n\nfunction isObservable(value) {\n if ( true && arguments.length !== 1) {\n die(\"isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property\");\n }\n\n return _isObservable(value);\n}\nfunction isObservableProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"expected a property name as second argument\");\n }\n\n return _isObservable(value, propName);\n}\n\nfunction keys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].keys_();\n }\n\n if (isObservableMap(obj) || isObservableSet(obj)) {\n return Array.from(obj.keys());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (_, index) {\n return index;\n });\n }\n\n die(5);\n}\nfunction values(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return obj[key];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return obj.get(key);\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.values());\n }\n\n if (isObservableArray(obj)) {\n return obj.slice();\n }\n\n die(6);\n}\nfunction entries(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj.get(key)];\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.entries());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (key, index) {\n return [index, key];\n });\n }\n\n die(7);\n}\nfunction set(obj, key, value) {\n if (arguments.length === 2 && !isObservableSet(obj)) {\n startBatch();\n var _values = key;\n\n try {\n for (var _key in _values) {\n set(obj, _key, _values[_key]);\n }\n } finally {\n endBatch();\n }\n\n return;\n }\n\n if (isObservableObject(obj)) {\n obj[$mobx].set_(key, value);\n } else if (isObservableMap(obj)) {\n obj.set(key, value);\n } else if (isObservableSet(obj)) {\n obj.add(key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n if (key < 0) {\n die(\"Invalid index: '\" + key + \"'\");\n }\n\n startBatch();\n\n if (key >= obj.length) {\n obj.length = key + 1;\n }\n\n obj[key] = value;\n endBatch();\n } else {\n die(8);\n }\n}\nfunction remove(obj, key) {\n if (isObservableObject(obj)) {\n obj[$mobx].delete_(key);\n } else if (isObservableMap(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableSet(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n obj.splice(key, 1);\n } else {\n die(9);\n }\n}\nfunction has(obj, key) {\n if (isObservableObject(obj)) {\n return obj[$mobx].has_(key);\n } else if (isObservableMap(obj)) {\n return obj.has(key);\n } else if (isObservableSet(obj)) {\n return obj.has(key);\n } else if (isObservableArray(obj)) {\n return key >= 0 && key < obj.length;\n }\n\n die(10);\n}\nfunction get(obj, key) {\n if (!has(obj, key)) {\n return undefined;\n }\n\n if (isObservableObject(obj)) {\n return obj[$mobx].get_(key);\n } else if (isObservableMap(obj)) {\n return obj.get(key);\n } else if (isObservableArray(obj)) {\n return obj[key];\n }\n\n die(11);\n}\nfunction apiDefineProperty(obj, key, descriptor) {\n if (isObservableObject(obj)) {\n return obj[$mobx].defineProperty_(key, descriptor);\n }\n\n die(39);\n}\nfunction apiOwnKeys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].ownKeys_();\n }\n\n die(38);\n}\n\nfunction observe(thing, propOrCb, cbOrFire, fireImmediately) {\n if (isFunction(cbOrFire)) {\n return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);\n } else {\n return observeObservable(thing, propOrCb, cbOrFire);\n }\n}\n\nfunction observeObservable(thing, listener, fireImmediately) {\n return getAdministration(thing).observe_(listener, fireImmediately);\n}\n\nfunction observeObservableProperty(thing, property, listener, fireImmediately) {\n return getAdministration(thing, property).observe_(listener, fireImmediately);\n}\n\nfunction cache(map, key, value) {\n map.set(key, value);\n return value;\n}\n\nfunction toJSHelper(source, __alreadySeen) {\n if (source == null || typeof source !== \"object\" || source instanceof Date || !isObservable(source)) {\n return source;\n }\n\n if (isObservableValue(source) || isComputedValue(source)) {\n return toJSHelper(source.get(), __alreadySeen);\n }\n\n if (__alreadySeen.has(source)) {\n return __alreadySeen.get(source);\n }\n\n if (isObservableArray(source)) {\n var res = cache(__alreadySeen, source, new Array(source.length));\n source.forEach(function (value, idx) {\n res[idx] = toJSHelper(value, __alreadySeen);\n });\n return res;\n }\n\n if (isObservableSet(source)) {\n var _res = cache(__alreadySeen, source, new Set());\n\n source.forEach(function (value) {\n _res.add(toJSHelper(value, __alreadySeen));\n });\n return _res;\n }\n\n if (isObservableMap(source)) {\n var _res2 = cache(__alreadySeen, source, new Map());\n\n source.forEach(function (value, key) {\n _res2.set(key, toJSHelper(value, __alreadySeen));\n });\n return _res2;\n } else {\n // must be observable object\n var _res3 = cache(__alreadySeen, source, {});\n\n apiOwnKeys(source).forEach(function (key) {\n if (objectPrototype.propertyIsEnumerable.call(source, key)) {\n _res3[key] = toJSHelper(source[key], __alreadySeen);\n }\n });\n return _res3;\n }\n}\n/**\r\n * Recursively converts an observable to it's non-observable native counterpart.\r\n * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.\r\n * Computed and other non-enumerable properties are completely ignored.\r\n * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.\r\n */\n\n\nfunction toJS(source, options) {\n if ( true && options) {\n die(\"toJS no longer supports options\");\n }\n\n return toJSHelper(source, new Map());\n}\n\nfunction trace() {\n if (false) {}\n\n var enterBreakPoint = false;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (typeof args[args.length - 1] === \"boolean\") {\n enterBreakPoint = args.pop();\n }\n\n var derivation = getAtomFromArgs(args);\n\n if (!derivation) {\n return die(\"'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly\");\n }\n\n if (derivation.isTracing_ === TraceMode.NONE) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' tracing enabled\");\n }\n\n derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;\n}\n\nfunction getAtomFromArgs(args) {\n switch (args.length) {\n case 0:\n return globalState.trackingDerivation;\n\n case 1:\n return getAtom(args[0]);\n\n case 2:\n return getAtom(args[0], args[1]);\n }\n}\n\n/**\r\n * During a transaction no views are updated until the end of the transaction.\r\n * The transaction will be run synchronously nonetheless.\r\n *\r\n * @param action a function that updates some reactive state\r\n * @returns any value that was returned by the 'action' parameter.\r\n */\n\nfunction transaction(action, thisArg) {\n if (thisArg === void 0) {\n thisArg = undefined;\n }\n\n startBatch();\n\n try {\n return action.apply(thisArg);\n } finally {\n endBatch();\n }\n}\n\nfunction when(predicate, arg1, arg2) {\n if (arguments.length === 1 || arg1 && typeof arg1 === \"object\") {\n return whenPromise(predicate, arg1);\n }\n\n return _when(predicate, arg1, arg2 || {});\n}\n\nfunction _when(predicate, effect, opts) {\n var timeoutHandle;\n\n if (typeof opts.timeout === \"number\") {\n var error = new Error(\"WHEN_TIMEOUT\");\n timeoutHandle = setTimeout(function () {\n if (!disposer[$mobx].isDisposed_) {\n disposer();\n\n if (opts.onError) {\n opts.onError(error);\n } else {\n throw error;\n }\n }\n }, opts.timeout);\n }\n\n opts.name = true ? opts.name || \"When@\" + getNextId() : undefined;\n var effectAction = createAction( true ? opts.name + \"-effect\" : undefined, effect); // eslint-disable-next-line\n\n var disposer = autorun(function (r) {\n // predicate should not change state\n var cond = allowStateChanges(false, predicate);\n\n if (cond) {\n r.dispose();\n\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n\n effectAction();\n }\n }, opts);\n return disposer;\n}\n\nfunction whenPromise(predicate, opts) {\n var _opts$signal;\n\n if ( true && opts && opts.onError) {\n return die(\"the options 'onError' and 'promise' cannot be combined\");\n }\n\n if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {\n return Object.assign(Promise.reject(new Error(\"WHEN_ABORTED\")), {\n cancel: function cancel() {\n return null;\n }\n });\n }\n\n var cancel;\n var abort;\n var res = new Promise(function (resolve, reject) {\n var _opts$signal2;\n\n var disposer = _when(predicate, resolve, _extends({}, opts, {\n onError: reject\n }));\n\n cancel = function cancel() {\n disposer();\n reject(new Error(\"WHEN_CANCELLED\"));\n };\n\n abort = function abort() {\n disposer();\n reject(new Error(\"WHEN_ABORTED\"));\n };\n\n opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener(\"abort\", abort);\n })[\"finally\"](function () {\n var _opts$signal3;\n\n return opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener(\"abort\", abort);\n });\n res.cancel = cancel;\n return res;\n}\n\nfunction getAdm(target) {\n return target[$mobx];\n} // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,\n// and skip either the internal values map, or the base object with its property descriptors!\n\n\nvar objectProxyTraps = {\n has: function has(target, name) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.\");\n }\n\n return getAdm(target).has_(name);\n },\n get: function get(target, name) {\n return getAdm(target).get_(name);\n },\n set: function set(target, name, value) {\n var _getAdm$set_;\n\n if (!isStringish(name)) {\n return false;\n }\n\n if ( true && !getAdm(target).values_.has(name)) {\n warnAboutProxyRequirement(\"add a new observable property through direct assignment. Use 'set' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;\n },\n deleteProperty: function deleteProperty(target, name) {\n var _getAdm$delete_;\n\n if (true) {\n warnAboutProxyRequirement(\"delete properties from an observable object. Use 'remove' from 'mobx' instead.\");\n }\n\n if (!isStringish(name)) {\n return false;\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;\n },\n defineProperty: function defineProperty(target, name, descriptor) {\n var _getAdm$definePropert;\n\n if (true) {\n warnAboutProxyRequirement(\"define property on an observable object. Use 'defineProperty' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;\n },\n ownKeys: function ownKeys(target) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.\");\n }\n\n return getAdm(target).ownKeys_();\n },\n preventExtensions: function preventExtensions(target) {\n die(13);\n }\n};\nfunction asDynamicObservableObject(target, options) {\n var _target$$mobx, _target$$mobx$proxy_;\n\n assertProxies();\n target = asObservableObject(target, options);\n return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);\n}\n\nfunction hasInterceptors(interceptable) {\n return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;\n}\nfunction registerInterceptor(interceptable, handler) {\n var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);\n interceptors.push(handler);\n return once(function () {\n var idx = interceptors.indexOf(handler);\n\n if (idx !== -1) {\n interceptors.splice(idx, 1);\n }\n });\n}\nfunction interceptChange(interceptable, change) {\n var prevU = untrackedStart();\n\n try {\n // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950\n var interceptors = [].concat(interceptable.interceptors_ || []);\n\n for (var i = 0, l = interceptors.length; i < l; i++) {\n change = interceptors[i](change);\n\n if (change && !change.type) {\n die(14);\n }\n\n if (!change) {\n break;\n }\n }\n\n return change;\n } finally {\n untrackedEnd(prevU);\n }\n}\n\nfunction hasListeners(listenable) {\n return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;\n}\nfunction registerListener(listenable, handler) {\n var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);\n listeners.push(handler);\n return once(function () {\n var idx = listeners.indexOf(handler);\n\n if (idx !== -1) {\n listeners.splice(idx, 1);\n }\n });\n}\nfunction notifyListeners(listenable, change) {\n var prevU = untrackedStart();\n var listeners = listenable.changeListeners_;\n\n if (!listeners) {\n return;\n }\n\n listeners = listeners.slice();\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](change);\n }\n\n untrackedEnd(prevU);\n}\n\nfunction makeObservable(target, annotations, options) {\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n var _annotations;\n\n if ( true && annotations && target[storedAnnotationsSymbol]) {\n die(\"makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.\");\n } // Default to decorators\n\n\n (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target); // Annotate\n\n ownKeys(annotations).forEach(function (key) {\n return adm.make_(key, annotations[key]);\n });\n } finally {\n endBatch();\n }\n\n return target;\n} // proto[keysSymbol] = new Set()\n\nvar keysSymbol = /*#__PURE__*/Symbol(\"mobx-keys\");\nfunction makeAutoObservable(target, overrides, options) {\n if (true) {\n if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {\n die(\"'makeAutoObservable' can only be used for classes that don't have a superclass\");\n }\n\n if (isObservableObject(target)) {\n die(\"makeAutoObservable can only be used on objects not already made observable\");\n }\n } // Optimization: avoid visiting protos\n // Assumes that annotation.make_/.extend_ works the same for plain objects\n\n\n if (isPlainObject(target)) {\n return extendObservable(target, target, overrides, options);\n }\n\n var adm = asObservableObject(target, options)[$mobx]; // Optimization: cache keys on proto\n // Assumes makeAutoObservable can be called only once per object and can't be used in subclass\n\n if (!target[keysSymbol]) {\n var proto = Object.getPrototypeOf(target);\n var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));\n keys[\"delete\"](\"constructor\");\n keys[\"delete\"]($mobx);\n addHiddenProp(proto, keysSymbol, keys);\n }\n\n startBatch();\n\n try {\n target[keysSymbol].forEach(function (key) {\n return adm.make_(key, // must pass \"undefined\" for { key: undefined }\n !overrides ? true : key in overrides ? overrides[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nvar SPLICE = \"splice\";\nvar UPDATE = \"update\";\nvar MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859\n\nvar arrayTraps = {\n get: function get(target, name) {\n var adm = target[$mobx];\n\n if (name === $mobx) {\n return adm;\n }\n\n if (name === \"length\") {\n return adm.getArrayLength_();\n }\n\n if (typeof name === \"string\" && !isNaN(name)) {\n return adm.get_(parseInt(name));\n }\n\n if (hasProp(arrayExtensions, name)) {\n return arrayExtensions[name];\n }\n\n return target[name];\n },\n set: function set(target, name, value) {\n var adm = target[$mobx];\n\n if (name === \"length\") {\n adm.setArrayLength_(value);\n }\n\n if (typeof name === \"symbol\" || isNaN(name)) {\n target[name] = value;\n } else {\n // numeric string\n adm.set_(parseInt(name), value);\n }\n\n return true;\n },\n preventExtensions: function preventExtensions() {\n die(15);\n }\n};\nvar ObservableArrayAdministration = /*#__PURE__*/function () {\n // this is the prop that gets proxied, so can't replace it!\n function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n this.owned_ = void 0;\n this.legacyMode_ = void 0;\n this.atom_ = void 0;\n this.values_ = [];\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.enhancer_ = void 0;\n this.dehancer = void 0;\n this.proxy_ = void 0;\n this.lastKnownLength_ = 0;\n this.owned_ = owned_;\n this.legacyMode_ = legacyMode_;\n this.atom_ = new Atom(name);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, true ? name + \"[..]\" : undefined);\n };\n }\n\n var _proto = ObservableArrayAdministration.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.dehanceValues_ = function dehanceValues_(values) {\n if (this.dehancer !== undefined && values.length > 0) {\n return values.map(this.dehancer);\n }\n\n return values;\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately === void 0) {\n fireImmediately = false;\n }\n\n if (fireImmediately) {\n listener({\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: \"splice\",\n index: 0,\n added: this.values_.slice(),\n addedCount: this.values_.length,\n removed: [],\n removedCount: 0\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.getArrayLength_ = function getArrayLength_() {\n this.atom_.reportObserved();\n return this.values_.length;\n };\n\n _proto.setArrayLength_ = function setArrayLength_(newLength) {\n if (typeof newLength !== \"number\" || isNaN(newLength) || newLength < 0) {\n die(\"Out of range: \" + newLength);\n }\n\n var currentLength = this.values_.length;\n\n if (newLength === currentLength) {\n return;\n } else if (newLength > currentLength) {\n var newItems = new Array(newLength - currentLength);\n\n for (var i = 0; i < newLength - currentLength; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n this.spliceWithArray_(currentLength, 0, newItems);\n } else {\n this.spliceWithArray_(newLength, currentLength - newLength);\n }\n };\n\n _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {\n if (oldLength !== this.lastKnownLength_) {\n die(16);\n }\n\n this.lastKnownLength_ += delta;\n\n if (this.legacyMode_ && delta > 0) {\n reserveArrayBuffer(oldLength + delta + 1);\n }\n };\n\n _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {\n var _this = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n var length = this.values_.length;\n\n if (index === undefined) {\n index = 0;\n } else if (index > length) {\n index = length;\n } else if (index < 0) {\n index = Math.max(0, length + index);\n }\n\n if (arguments.length === 1) {\n deleteCount = length - index;\n } else if (deleteCount === undefined || deleteCount === null) {\n deleteCount = 0;\n } else {\n deleteCount = Math.max(0, Math.min(deleteCount, length - index));\n }\n\n if (newItems === undefined) {\n newItems = EMPTY_ARRAY;\n }\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_,\n type: SPLICE,\n index: index,\n removedCount: deleteCount,\n added: newItems\n });\n\n if (!change) {\n return EMPTY_ARRAY;\n }\n\n deleteCount = change.removedCount;\n newItems = change.added;\n }\n\n newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {\n return _this.enhancer_(v, undefined);\n });\n\n if (this.legacyMode_ || \"development\" !== \"production\") {\n var lengthDelta = newItems.length - deleteCount;\n this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified\n }\n\n var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);\n\n if (deleteCount !== 0 || newItems.length !== 0) {\n this.notifyArraySplice_(index, newItems, res);\n }\n\n return this.dehanceValues_(res);\n };\n\n _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {\n if (newItems.length < MAX_SPLICE_SIZE) {\n var _this$values_;\n\n return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));\n } else {\n // The items removed by the splice\n var res = this.values_.slice(index, index + deleteCount); // The items that that should remain at the end of the array\n\n var oldItems = this.values_.slice(index + deleteCount); // New length is the previous length + addition count - deletion count\n\n this.values_.length += newItems.length - deleteCount;\n\n for (var i = 0; i < newItems.length; i++) {\n this.values_[index + i] = newItems[i];\n }\n\n for (var _i = 0; _i < oldItems.length; _i++) {\n this.values_[index + newItems.length + _i] = oldItems[_i];\n }\n\n return res;\n }\n };\n\n _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n type: UPDATE,\n debugObjectName: this.atom_.name_,\n index: index,\n newValue: newValue,\n oldValue: oldValue\n } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't\n // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged();\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: SPLICE,\n index: index,\n removed: removed,\n added: added,\n removedCount: removed.length,\n addedCount: added.length\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get_ = function get_(index) {\n if (this.legacyMode_ && index >= this.values_.length) {\n console.warn( true ? \"[mobx.array] Attempt to read an array index (\" + index + \") that is out of bounds (\" + this.values_.length + \"). Please check length first. Out of bound indices will not be tracked by MobX\" : undefined);\n return undefined;\n }\n\n this.atom_.reportObserved();\n return this.dehanceValue_(this.values_[index]);\n };\n\n _proto.set_ = function set_(index, newValue) {\n var values = this.values_;\n\n if (this.legacyMode_ && index > values.length) {\n // out of bounds\n die(17, index, values.length);\n }\n\n if (index < values.length) {\n // update at index in range\n checkIfStateModificationsAreAllowed(this.atom_);\n var oldValue = values[index];\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_,\n index: index,\n newValue: newValue\n });\n\n if (!change) {\n return;\n }\n\n newValue = change.newValue;\n }\n\n newValue = this.enhancer_(newValue, oldValue);\n var changed = newValue !== oldValue;\n\n if (changed) {\n values[index] = newValue;\n this.notifyArrayChildUpdate_(index, newValue, oldValue);\n }\n } else {\n // For out of bound index, we don't create an actual sparse array,\n // but rather fill the holes with undefined (same as setArrayLength_).\n // This could be considered a bug.\n var newItems = new Array(index + 1 - values.length);\n\n for (var i = 0; i < newItems.length - 1; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n newItems[newItems.length - 1] = newValue;\n this.spliceWithArray_(values.length, 0, newItems);\n }\n };\n\n return ObservableArrayAdministration;\n}();\nfunction createObservableArray(initialValues, enhancer, name, owned) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n assertProxies();\n var adm = new ObservableArrayAdministration(name, enhancer, owned, false);\n addHiddenFinalProp(adm.values_, $mobx, adm);\n var proxy = new Proxy(adm.values_, arrayTraps);\n adm.proxy_ = proxy;\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true);\n adm.spliceWithArray_(0, 0, initialValues);\n allowStateChangesEnd(prev);\n }\n\n return proxy;\n} // eslint-disable-next-line\n\nvar arrayExtensions = {\n clear: function clear() {\n return this.splice(0);\n },\n replace: function replace(newItems) {\n var adm = this[$mobx];\n return adm.spliceWithArray_(0, adm.values_.length, newItems);\n },\n // Used by JSON.stringify\n toJSON: function toJSON() {\n return this.slice();\n },\n\n /*\r\n * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)\r\n * since these functions alter the inner structure of the array, the have side effects.\r\n * Because the have side effects, they should not be used in computed function,\r\n * and for that reason the do not call dependencyState.notifyObserved\r\n */\n splice: function splice(index, deleteCount) {\n for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n newItems[_key - 2] = arguments[_key];\n }\n\n var adm = this[$mobx];\n\n switch (arguments.length) {\n case 0:\n return [];\n\n case 1:\n return adm.spliceWithArray_(index);\n\n case 2:\n return adm.spliceWithArray_(index, deleteCount);\n }\n\n return adm.spliceWithArray_(index, deleteCount, newItems);\n },\n spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {\n return this[$mobx].spliceWithArray_(index, deleteCount, newItems);\n },\n push: function push() {\n var adm = this[$mobx];\n\n for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n items[_key2] = arguments[_key2];\n }\n\n adm.spliceWithArray_(adm.values_.length, 0, items);\n return adm.values_.length;\n },\n pop: function pop() {\n return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];\n },\n shift: function shift() {\n return this.splice(0, 1)[0];\n },\n unshift: function unshift() {\n var adm = this[$mobx];\n\n for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n items[_key3] = arguments[_key3];\n }\n\n adm.spliceWithArray_(0, 0, items);\n return adm.values_.length;\n },\n reverse: function reverse() {\n // reverse by default mutates in place before returning the result\n // which makes it both a 'derivation' and a 'mutation'.\n if (globalState.trackingDerivation) {\n die(37, \"reverse\");\n }\n\n this.replace(this.slice().reverse());\n return this;\n },\n sort: function sort() {\n // sort by default mutates in place before returning the result\n // which goes against all good practices. Let's not change the array in place!\n if (globalState.trackingDerivation) {\n die(37, \"sort\");\n }\n\n var copy = this.slice();\n copy.sort.apply(copy, arguments);\n this.replace(copy);\n return this;\n },\n remove: function remove(value) {\n var adm = this[$mobx];\n var idx = adm.dehanceValues_(adm.values_).indexOf(value);\n\n if (idx > -1) {\n this.splice(idx, 1);\n return true;\n }\n\n return false;\n }\n};\n/**\r\n * Wrap function from prototype\r\n * Without this, everything works as well, but this works\r\n * faster as everything works on unproxied values\r\n */\n\naddArrayExtension(\"concat\", simpleFunc);\naddArrayExtension(\"flat\", simpleFunc);\naddArrayExtension(\"includes\", simpleFunc);\naddArrayExtension(\"indexOf\", simpleFunc);\naddArrayExtension(\"join\", simpleFunc);\naddArrayExtension(\"lastIndexOf\", simpleFunc);\naddArrayExtension(\"slice\", simpleFunc);\naddArrayExtension(\"toString\", simpleFunc);\naddArrayExtension(\"toLocaleString\", simpleFunc); // map\n\naddArrayExtension(\"every\", mapLikeFunc);\naddArrayExtension(\"filter\", mapLikeFunc);\naddArrayExtension(\"find\", mapLikeFunc);\naddArrayExtension(\"findIndex\", mapLikeFunc);\naddArrayExtension(\"flatMap\", mapLikeFunc);\naddArrayExtension(\"forEach\", mapLikeFunc);\naddArrayExtension(\"map\", mapLikeFunc);\naddArrayExtension(\"some\", mapLikeFunc); // reduce\n\naddArrayExtension(\"reduce\", reduceLikeFunc);\naddArrayExtension(\"reduceRight\", reduceLikeFunc);\n\nfunction addArrayExtension(funcName, funcFactory) {\n if (typeof Array.prototype[funcName] === \"function\") {\n arrayExtensions[funcName] = funcFactory(funcName);\n }\n} // Report and delegate to dehanced array\n\n\nfunction simpleFunc(funcName) {\n return function () {\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction mapLikeFunc(funcName) {\n return function (callback, thisArg) {\n var _this2 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName](function (element, index) {\n return callback.call(thisArg, element, index, _this2);\n });\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction reduceLikeFunc(funcName) {\n return function () {\n var _this3 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_); // #2432 - reduce behavior depends on arguments.length\n\n var callback = arguments[0];\n\n arguments[0] = function (accumulator, currentValue, index) {\n return callback(accumulator, currentValue, index, _this3);\n };\n\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\n\nvar isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableArrayAdministration\", ObservableArrayAdministration);\nfunction isObservableArray(thing) {\n return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);\n}\n\nvar _Symbol$iterator, _Symbol$toStringTag;\nvar ObservableMapMarker = {};\nvar ADD = \"add\";\nvar DELETE = \"delete\"; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54\n// But: https://github.com/mobxjs/mobx/issues/1556\n\n_Symbol$iterator = Symbol.iterator;\n_Symbol$toStringTag = Symbol.toStringTag;\nvar ObservableMap = /*#__PURE__*/function () {\n // hasMap, not hashMap >-).\n function ObservableMap(initialData, enhancer_, name_) {\n var _this = this;\n\n if (enhancer_ === void 0) {\n enhancer_ = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableMap@\" + getNextId() : undefined;\n }\n\n this.enhancer_ = void 0;\n this.name_ = void 0;\n this[$mobx] = ObservableMapMarker;\n this.data_ = void 0;\n this.hasMap_ = void 0;\n this.keysAtom_ = void 0;\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = enhancer_;\n this.name_ = name_;\n\n if (!isFunction(Map)) {\n die(18);\n }\n\n this.keysAtom_ = createAtom( true ? this.name_ + \".keys()\" : undefined);\n this.data_ = new Map();\n this.hasMap_ = new Map();\n allowStateChanges(true, function () {\n _this.merge(initialData);\n });\n }\n\n var _proto = ObservableMap.prototype;\n\n _proto.has_ = function has_(key) {\n return this.data_.has(key);\n };\n\n _proto.has = function has(key) {\n var _this2 = this;\n\n if (!globalState.trackingDerivation) {\n return this.has_(key);\n }\n\n var entry = this.hasMap_.get(key);\n\n if (!entry) {\n var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.hasMap_.set(key, newEntry);\n onBecomeUnobserved(newEntry, function () {\n return _this2.hasMap_[\"delete\"](key);\n });\n }\n\n return entry.get();\n };\n\n _proto.set = function set(key, value) {\n var hasKey = this.has_(key);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: hasKey ? UPDATE : ADD,\n object: this,\n newValue: value,\n name: key\n });\n\n if (!change) {\n return this;\n }\n\n value = change.newValue;\n }\n\n if (hasKey) {\n this.updateValue_(key, value);\n } else {\n this.addValue_(key, value);\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(key) {\n var _this3 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n name: key\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has_(key)) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: this.data_.get(key).value_,\n name: key\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n } // TODO fix type\n\n\n transaction(function () {\n var _this3$hasMap_$get;\n\n _this3.keysAtom_.reportChanged();\n\n (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false);\n\n var observable = _this3.data_.get(key);\n\n observable.setNewValue_(undefined);\n\n _this3.data_[\"delete\"](key);\n });\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.updateValue_ = function updateValue_(key, newValue) {\n var observable = this.data_.get(key);\n newValue = observable.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: UPDATE,\n object: this,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.addValue_ = function addValue_(key, newValue) {\n var _this4 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n transaction(function () {\n var _this4$hasMap_$get;\n\n var observable = new ObservableValue(newValue, _this4.enhancer_, true ? _this4.name_ + \".\" + stringifyKey(key) : undefined, false);\n\n _this4.data_.set(key, observable);\n\n newValue = observable.value_; // value might have been changed\n\n (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true);\n\n _this4.keysAtom_.reportChanged();\n });\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get = function get(key) {\n if (this.has(key)) {\n return this.dehanceValue_(this.data_.get(key).get());\n }\n\n return this.dehanceValue_(undefined);\n };\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.keys = function keys() {\n this.keysAtom_.reportObserved();\n return this.data_.keys();\n };\n\n _proto.values = function values() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next = keys.next(),\n done = _keys$next.done,\n value = _keys$next.value;\n\n return {\n done: done,\n value: done ? undefined : self.get(value)\n };\n }\n });\n };\n\n _proto.entries = function entries() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next2 = keys.next(),\n done = _keys$next2.done,\n value = _keys$next2.value;\n\n return {\n done: done,\n value: done ? undefined : [value, self.get(value)]\n };\n }\n });\n };\n\n _proto[_Symbol$iterator] = function () {\n return this.entries();\n };\n\n _proto.forEach = function forEach(callback, thisArg) {\n for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {\n var _step$value = _step.value,\n key = _step$value[0],\n value = _step$value[1];\n callback.call(thisArg, value, key, this);\n }\n }\n /** Merge another object into this object, returns this. */\n ;\n\n _proto.merge = function merge(other) {\n var _this5 = this;\n\n if (isObservableMap(other)) {\n other = new Map(other);\n }\n\n transaction(function () {\n if (isPlainObject(other)) {\n getPlainObjectKeys(other).forEach(function (key) {\n return _this5.set(key, other[key]);\n });\n } else if (Array.isArray(other)) {\n other.forEach(function (_ref) {\n var key = _ref[0],\n value = _ref[1];\n return _this5.set(key, value);\n });\n } else if (isES6Map(other)) {\n if (other.constructor !== Map) {\n die(19, other);\n }\n\n other.forEach(function (value, key) {\n return _this5.set(key, value);\n });\n } else if (other !== null && other !== undefined) {\n die(20, other);\n }\n });\n return this;\n };\n\n _proto.clear = function clear() {\n var _this6 = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {\n var key = _step2.value;\n\n _this6[\"delete\"](key);\n }\n });\n });\n };\n\n _proto.replace = function replace(values) {\n var _this7 = this;\n\n // Implementation requirements:\n // - respect ordering of replacement map\n // - allow interceptors to run and potentially prevent individual operations\n // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)\n // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)\n // - note that result map may differ from replacement map due to the interceptors\n transaction(function () {\n // Convert to map so we can do quick key lookups\n var replacementMap = convertToMap(values);\n var orderedData = new Map(); // Used for optimization\n\n var keysReportChangedCalled = false; // Delete keys that don't exist in replacement map\n // if the key deletion is prevented by interceptor\n // add entry at the beginning of the result map\n\n for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {\n var key = _step3.value;\n\n // Concurrently iterating/deleting keys\n // iterator should handle this correctly\n if (!replacementMap.has(key)) {\n var deleted = _this7[\"delete\"](key); // Was the key removed?\n\n\n if (deleted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n } else {\n // Delete prevented by interceptor\n var value = _this7.data_.get(key);\n\n orderedData.set(key, value);\n }\n }\n } // Merge entries\n\n\n for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {\n var _step4$value = _step4.value,\n _key = _step4$value[0],\n _value = _step4$value[1];\n\n // We will want to know whether a new key is added\n var keyExisted = _this7.data_.has(_key); // Add or update value\n\n\n _this7.set(_key, _value); // The addition could have been prevent by interceptor\n\n\n if (_this7.data_.has(_key)) {\n // The update could have been prevented by interceptor\n // and also we want to preserve existing values\n // so use value from _data map (instead of replacement map)\n var _value2 = _this7.data_.get(_key);\n\n orderedData.set(_key, _value2); // Was a new key added?\n\n if (!keyExisted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n }\n }\n } // Check for possible key order change\n\n\n if (!keysReportChangedCalled) {\n if (_this7.data_.size !== orderedData.size) {\n // If size differs, keys are definitely modified\n _this7.keysAtom_.reportChanged();\n } else {\n var iter1 = _this7.data_.keys();\n\n var iter2 = orderedData.keys();\n var next1 = iter1.next();\n var next2 = iter2.next();\n\n while (!next1.done) {\n if (next1.value !== next2.value) {\n _this7.keysAtom_.reportChanged();\n\n break;\n }\n\n next1 = iter1.next();\n next2 = iter2.next();\n }\n }\n } // Use correctly ordered map\n\n\n _this7.data_ = orderedData;\n });\n return this;\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableMap]\";\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with maps.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _createClass(ObservableMap, [{\n key: \"size\",\n get: function get() {\n this.keysAtom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Map\";\n }\n }]);\n\n return ObservableMap;\n}(); // eslint-disable-next-line\n\nvar isObservableMap = /*#__PURE__*/createInstanceofPredicate(\"ObservableMap\", ObservableMap);\n\nfunction convertToMap(dataStructure) {\n if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {\n return dataStructure;\n } else if (Array.isArray(dataStructure)) {\n return new Map(dataStructure);\n } else if (isPlainObject(dataStructure)) {\n var map = new Map();\n\n for (var key in dataStructure) {\n map.set(key, dataStructure[key]);\n }\n\n return map;\n } else {\n return die(21, dataStructure);\n }\n}\n\nvar _Symbol$iterator$1, _Symbol$toStringTag$1;\nvar ObservableSetMarker = {};\n_Symbol$iterator$1 = Symbol.iterator;\n_Symbol$toStringTag$1 = Symbol.toStringTag;\nvar ObservableSet = /*#__PURE__*/function () {\n function ObservableSet(initialData, enhancer, name_) {\n if (enhancer === void 0) {\n enhancer = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableSet@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this[$mobx] = ObservableSetMarker;\n this.data_ = new Set();\n this.atom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = void 0;\n this.name_ = name_;\n\n if (!isFunction(Set)) {\n die(22);\n }\n\n this.atom_ = createAtom(this.name_);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, name_);\n };\n\n if (initialData) {\n this.replace(initialData);\n }\n }\n\n var _proto = ObservableSet.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.clear = function clear() {\n var _this = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) {\n var value = _step.value;\n\n _this[\"delete\"](value);\n }\n });\n });\n };\n\n _proto.forEach = function forEach(callbackFn, thisArg) {\n for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {\n var value = _step2.value;\n callbackFn.call(thisArg, value, value, this);\n }\n };\n\n _proto.add = function add(value) {\n var _this2 = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: ADD,\n object: this,\n newValue: value\n });\n\n if (!change) {\n return this;\n } // ideally, value = change.value would be done here, so that values can be\n // changed by interceptor. Same applies for other Set and Map api's.\n\n }\n\n if (!this.has(value)) {\n transaction(function () {\n _this2.data_.add(_this2.enhancer_(value, undefined));\n\n _this2.atom_.reportChanged();\n });\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n newValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change);\n }\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(value) {\n var _this3 = this;\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n oldValue: value\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has(value)) {\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change2 = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change2);\n }\n\n transaction(function () {\n _this3.atom_.reportChanged();\n\n _this3.data_[\"delete\"](value);\n });\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.has = function has(value) {\n this.atom_.reportObserved();\n return this.data_.has(this.dehanceValue_(value));\n };\n\n _proto.entries = function entries() {\n var nextIndex = 0;\n var keys = Array.from(this.keys());\n var values = Array.from(this.values());\n return makeIterable({\n next: function next() {\n var index = nextIndex;\n nextIndex += 1;\n return index < values.length ? {\n value: [keys[index], values[index]],\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.keys = function keys() {\n return this.values();\n };\n\n _proto.values = function values() {\n this.atom_.reportObserved();\n var self = this;\n var nextIndex = 0;\n var observableValues = Array.from(this.data_.values());\n return makeIterable({\n next: function next() {\n return nextIndex < observableValues.length ? {\n value: self.dehanceValue_(observableValues[nextIndex++]),\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.replace = function replace(other) {\n var _this4 = this;\n\n if (isObservableSet(other)) {\n other = new Set(other);\n }\n\n transaction(function () {\n if (Array.isArray(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (isES6Set(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (other !== null && other !== undefined) {\n die(\"Cannot initialize set from \" + other);\n }\n });\n return this;\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n // ... 'fireImmediately' could also be true?\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with sets.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableSet]\";\n };\n\n _proto[_Symbol$iterator$1] = function () {\n return this.values();\n };\n\n _createClass(ObservableSet, [{\n key: \"size\",\n get: function get() {\n this.atom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag$1,\n get: function get() {\n return \"Set\";\n }\n }]);\n\n return ObservableSet;\n}(); // eslint-disable-next-line\n\nvar isObservableSet = /*#__PURE__*/createInstanceofPredicate(\"ObservableSet\", ObservableSet);\n\nvar descriptorCache = /*#__PURE__*/Object.create(null);\nvar REMOVE = \"remove\";\nvar ObservableObjectAdministration = /*#__PURE__*/function () {\n function ObservableObjectAdministration(target_, values_, name_, // Used anytime annotation is not explicitely provided\n defaultAnnotation_) {\n if (values_ === void 0) {\n values_ = new Map();\n }\n\n if (defaultAnnotation_ === void 0) {\n defaultAnnotation_ = autoAnnotation;\n }\n\n this.target_ = void 0;\n this.values_ = void 0;\n this.name_ = void 0;\n this.defaultAnnotation_ = void 0;\n this.keysAtom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.proxy_ = void 0;\n this.isPlainObject_ = void 0;\n this.appliedAnnotations_ = void 0;\n this.pendingKeys_ = void 0;\n this.target_ = target_;\n this.values_ = values_;\n this.name_ = name_;\n this.defaultAnnotation_ = defaultAnnotation_;\n this.keysAtom_ = new Atom( true ? this.name_ + \".keys\" : undefined); // Optimization: we use this frequently\n\n this.isPlainObject_ = isPlainObject(this.target_);\n\n if ( true && !isAnnotation(this.defaultAnnotation_)) {\n die(\"defaultAnnotation must be valid annotation\");\n }\n\n if (true) {\n // Prepare structure for tracking which fields were already annotated\n this.appliedAnnotations_ = {};\n }\n }\n\n var _proto = ObservableObjectAdministration.prototype;\n\n _proto.getObservablePropValue_ = function getObservablePropValue_(key) {\n return this.values_.get(key).get();\n };\n\n _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {\n var observable = this.values_.get(key);\n\n if (observable instanceof ComputedValue) {\n observable.set(newValue);\n return true;\n } // intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: newValue\n });\n\n if (!change) {\n return null;\n }\n\n newValue = change.newValue;\n }\n\n newValue = observable.prepareNewValue_(newValue); // notify spy & observers\n\n if (newValue !== globalState.UNCHANGED) {\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n var _change = notify || notifySpy ? {\n type: UPDATE,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n }\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n return true;\n };\n\n _proto.get_ = function get_(key) {\n if (globalState.trackingDerivation && !hasProp(this.target_, key)) {\n // Key doesn't exist yet, subscribe for it in case it's added later\n this.has_(key);\n }\n\n return this.target_[key];\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {any} value\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.set_ = function set_(key, value, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // Don't use .has(key) - we care about own\n if (hasProp(this.target_, key)) {\n // Existing prop\n if (this.values_.has(key)) {\n // Observable (can be intercepted)\n return this.setObservablePropValue_(key, value);\n } else if (proxyTrap) {\n // Non-observable - proxy\n return Reflect.set(this.target_, key, value);\n } else {\n // Non-observable\n this.target_[key] = value;\n return true;\n }\n } else {\n // New prop\n return this.extend_(key, {\n value: value,\n enumerable: true,\n writable: true,\n configurable: true\n }, this.defaultAnnotation_, proxyTrap);\n }\n } // Trap for \"in\"\n ;\n\n _proto.has_ = function has_(key) {\n if (!globalState.trackingDerivation) {\n // Skip key subscription outside derivation\n return key in this.target_;\n }\n\n this.pendingKeys_ || (this.pendingKeys_ = new Map());\n var entry = this.pendingKeys_.get(key);\n\n if (!entry) {\n entry = new ObservableValue(key in this.target_, referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.pendingKeys_.set(key, entry);\n }\n\n return entry.get();\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop\r\n */\n ;\n\n _proto.make_ = function make_(key, annotation) {\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return;\n }\n\n assertAnnotable(this, annotation, key);\n\n if (!(key in this.target_)) {\n var _this$target_$storedA;\n\n // Throw on missing key, except for decorators:\n // Decorator annotations are collected from whole prototype chain.\n // When called from super() some props may not exist yet.\n // However we don't have to worry about missing prop,\n // because the decorator must have been applied to something.\n if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {\n return; // will be annotated by subclass constructor\n } else {\n die(1, annotation.annotationType_, this.name_ + \".\" + key.toString());\n }\n }\n\n var source = this.target_;\n\n while (source && source !== objectPrototype) {\n var descriptor = getDescriptor(source, key);\n\n if (descriptor) {\n var outcome = annotation.make_(this, key, descriptor, source);\n\n if (outcome === 0\n /* Cancel */\n ) {\n return;\n }\n\n if (outcome === 1\n /* Break */\n ) {\n break;\n }\n }\n\n source = Object.getPrototypeOf(source);\n }\n\n recordAnnotationApplied(this, annotation, key);\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return this.defineProperty_(key, descriptor, proxyTrap);\n }\n\n assertAnnotable(this, annotation, key);\n var outcome = annotation.extend_(this, key, descriptor, proxyTrap);\n\n if (outcome) {\n recordAnnotationApplied(this, annotation, key);\n }\n\n return outcome;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: descriptor.value\n });\n\n if (!change) {\n return null;\n }\n\n var newValue = change.newValue;\n\n if (descriptor.value !== newValue) {\n descriptor = _extends({}, descriptor, {\n value: newValue\n });\n }\n } // Define\n\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n } // Notify\n\n\n this.notifyPropertyAddition_(key, descriptor.value);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: value\n });\n\n if (!change) {\n return null;\n }\n\n value = change.newValue;\n }\n\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: true,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n var observable = new ObservableValue(value, enhancer, true ? this.name_ + \".\" + key.toString() : undefined, false);\n this.values_.set(key, observable); // Notify (value possibly changed by ObservableValue)\n\n this.notifyPropertyAddition_(key, observable.value_);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: undefined\n });\n\n if (!change) {\n return null;\n }\n }\n\n options.name || (options.name = true ? this.name_ + \".\" + key.toString() : undefined);\n options.context = this.proxy_ || this.target_;\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: false,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n this.values_.set(key, new ComputedValue(options)); // Notify\n\n this.notifyPropertyAddition_(key, undefined);\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.delete_ = function delete_(key, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // No such prop\n if (!hasProp(this.target_, key)) {\n return true;\n } // Intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: REMOVE\n }); // Cancelled\n\n if (!change) {\n return null;\n }\n } // Delete\n\n\n try {\n var _this$pendingKeys_, _this$pendingKeys_$ge;\n\n startBatch();\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n var observable = this.values_.get(key); // Value needed for spies/listeners\n\n var value = undefined; // Optimization: don't pull the value unless we will need it\n\n if (!observable && (notify || notifySpy)) {\n var _getDescriptor;\n\n value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;\n } // delete prop (do first, may fail)\n\n\n if (proxyTrap) {\n if (!Reflect.deleteProperty(this.target_, key)) {\n return false;\n }\n } else {\n delete this.target_[key];\n } // Allow re-annotating this field\n\n\n if (true) {\n delete this.appliedAnnotations_[key];\n } // Clear observable\n\n\n if (observable) {\n this.values_[\"delete\"](key); // for computed, value is undefined\n\n if (observable instanceof ObservableValue) {\n value = observable.value_;\n } // Notify: autorun(() => obj[key]), see #1796\n\n\n propagateChanged(observable);\n } // Notify \"keys/entries/values\" observers\n\n\n this.keysAtom_.reportChanged(); // Notify \"has\" observers\n // \"in\" as it may still exist in proto\n\n (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_); // Notify spies/listeners\n\n if (notify || notifySpy) {\n var _change2 = {\n type: REMOVE,\n observableKind: \"object\",\n object: this.proxy_ || this.target_,\n debugObjectName: this.name_,\n oldValue: value,\n name: key\n };\n\n if ( true && notifySpy) {\n spyReportStart(_change2);\n }\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n ;\n\n _proto.observe_ = function observe_(callback, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support the fire immediately property for observable objects.\");\n }\n\n return registerListener(this, callback);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {\n var _this$pendingKeys_2, _this$pendingKeys_2$g;\n\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n if (notify || notifySpy) {\n var change = notify || notifySpy ? {\n type: ADD,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: value\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true); // Notify \"keys/entries/values\" observers\n\n this.keysAtom_.reportChanged();\n };\n\n _proto.ownKeys_ = function ownKeys_() {\n this.keysAtom_.reportObserved();\n return ownKeys(this.target_);\n };\n\n _proto.keys_ = function keys_() {\n // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.\n // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.\n // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)\n // We choose to over-report in Object.keys(object), because:\n // - typically it's used with simple data objects\n // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected\n this.keysAtom_.reportObserved();\n return Object.keys(this.target_);\n };\n\n return ObservableObjectAdministration;\n}();\nfunction asObservableObject(target, options) {\n var _options$name;\n\n if ( true && options && isObservableObject(target)) {\n die(\"Options can't be provided for already observable objects.\");\n }\n\n if (hasProp(target, $mobx)) {\n if ( true && !(getAdministration(target) instanceof ObservableObjectAdministration)) {\n die(\"Cannot convert '\" + getDebugName(target) + \"' into observable object:\" + \"\\nThe target is already observable of different type.\" + \"\\nExtending builtins is not supported.\");\n }\n\n return target;\n }\n\n if ( true && !Object.isExtensible(target)) {\n die(\"Cannot make the designated object observable; it is not extensible\");\n }\n\n var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : true ? (isPlainObject(target) ? \"ObservableObject\" : target.constructor.name) + \"@\" + getNextId() : undefined;\n var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));\n addHiddenProp(target, $mobx, adm);\n return target;\n}\nvar isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableObjectAdministration\", ObservableObjectAdministration);\n\nfunction getCachedObservablePropDescriptor(key) {\n return descriptorCache[key] || (descriptorCache[key] = {\n get: function get() {\n return this[$mobx].getObservablePropValue_(key);\n },\n set: function set(value) {\n return this[$mobx].setObservablePropValue_(key, value);\n }\n });\n}\n\nfunction isObservableObject(thing) {\n if (isObject(thing)) {\n return isObservableObjectAdministration(thing[$mobx]);\n }\n\n return false;\n}\nfunction recordAnnotationApplied(adm, annotation, key) {\n var _adm$target_$storedAn;\n\n if (true) {\n adm.appliedAnnotations_[key] = annotation;\n } // Remove applied decorator annotation so we don't try to apply it again in subclass constructor\n\n\n (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key];\n}\n\nfunction assertAnnotable(adm, annotation, key) {\n // Valid annotation\n if ( true && !isAnnotation(annotation)) {\n die(\"Cannot annotate '\" + adm.name_ + \".\" + key.toString() + \"': Invalid annotation.\");\n }\n /*\r\n // Configurable, not sealed, not frozen\r\n // Possibly not needed, just a little better error then the one thrown by engine.\r\n // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.\r\n if (__DEV__) {\r\n const configurable = getDescriptor(adm.target_, key)?.configurable\r\n const frozen = Object.isFrozen(adm.target_)\r\n const sealed = Object.isSealed(adm.target_)\r\n if (!configurable || frozen || sealed) {\r\n const fieldName = `${adm.name_}.${key.toString()}`\r\n const requestedAnnotationType = annotation.annotationType_\r\n let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`\r\n if (frozen) {\r\n error += `\\nObject is frozen.`\r\n }\r\n if (sealed) {\r\n error += `\\nObject is sealed.`\r\n }\r\n if (!configurable) {\r\n error += `\\nproperty is not configurable.`\r\n // Mention only if caused by us to avoid confusion\r\n if (hasProp(adm.appliedAnnotations!, key)) {\r\n error += `\\nTo prevent accidental re-definition of a field by a subclass, `\r\n error += `all annotated fields of non-plain objects (classes) are not configurable.`\r\n }\r\n }\r\n die(error)\r\n }\r\n }\r\n */\n // Not annotated\n\n\n if ( true && !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {\n var fieldName = adm.name_ + \".\" + key.toString();\n var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already annotated with '\" + currentAnnotationType + \"'.\") + \"\\nRe-annotating fields is not allowed.\" + \"\\nUse 'override' annotation for methods overridden by subclass.\");\n }\n}\n\nvar ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);\n/**\r\n * This array buffer contains two lists of properties, so that all arrays\r\n * can recycle their property definitions, which significantly improves performance of creating\r\n * properties on the fly.\r\n */\n\n\nvar OBSERVABLE_ARRAY_BUFFER_SIZE = 0; // Typescript workaround to make sure ObservableArray extends Array\n\nvar StubArray = function StubArray() {};\n\nfunction inherit(ctor, proto) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(ctor.prototype, proto);\n } else if (ctor.prototype.__proto__ !== undefined) {\n ctor.prototype.__proto__ = proto;\n } else {\n ctor.prototype = proto;\n }\n}\n\ninherit(StubArray, Array.prototype); // Weex proto freeze protection was here,\n// but it is unclear why the hack is need as MobX never changed the prototype\n// anyway, so removed it in V6\n\nvar LegacyObservableArray = /*#__PURE__*/function (_StubArray, _Symbol$toStringTag, _Symbol$iterator) {\n _inheritsLoose(LegacyObservableArray, _StubArray);\n\n function LegacyObservableArray(initialValues, enhancer, name, owned) {\n var _this;\n\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n _this = _StubArray.call(this) || this;\n var adm = new ObservableArrayAdministration(name, enhancer, owned, true);\n adm.proxy_ = _assertThisInitialized(_this);\n addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm);\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true); // @ts-ignore\n\n _this.spliceWithArray(0, 0, initialValues);\n\n allowStateChangesEnd(prev);\n }\n\n {\n // Seems that Safari won't use numeric prototype setter untill any * numeric property is\n // defined on the instance. After that it works fine, even if this property is deleted.\n Object.defineProperty(_assertThisInitialized(_this), \"0\", ENTRY_0);\n }\n\n return _this;\n }\n\n var _proto = LegacyObservableArray.prototype;\n\n _proto.concat = function concat() {\n this[$mobx].atom_.reportObserved();\n\n for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {\n arrays[_key] = arguments[_key];\n }\n\n return Array.prototype.concat.apply(this.slice(), //@ts-ignore\n arrays.map(function (a) {\n return isObservableArray(a) ? a.slice() : a;\n }));\n };\n\n _proto[_Symbol$iterator] = function () {\n var self = this;\n var nextIndex = 0;\n return makeIterable({\n next: function next() {\n return nextIndex < self.length ? {\n value: self[nextIndex++],\n done: false\n } : {\n done: true,\n value: undefined\n };\n }\n });\n };\n\n _createClass(LegacyObservableArray, [{\n key: \"length\",\n get: function get() {\n return this[$mobx].getArrayLength_();\n },\n set: function set(newLength) {\n this[$mobx].setArrayLength_(newLength);\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Array\";\n }\n }]);\n\n return LegacyObservableArray;\n}(StubArray, Symbol.toStringTag, Symbol.iterator);\n\nObject.entries(arrayExtensions).forEach(function (_ref) {\n var prop = _ref[0],\n fn = _ref[1];\n\n if (prop !== \"concat\") {\n addHiddenProp(LegacyObservableArray.prototype, prop, fn);\n }\n});\n\nfunction createArrayEntryDescriptor(index) {\n return {\n enumerable: false,\n configurable: true,\n get: function get() {\n return this[$mobx].get_(index);\n },\n set: function set(value) {\n this[$mobx].set_(index, value);\n }\n };\n}\n\nfunction createArrayBufferItem(index) {\n defineProperty(LegacyObservableArray.prototype, \"\" + index, createArrayEntryDescriptor(index));\n}\n\nfunction reserveArrayBuffer(max) {\n if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {\n for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {\n createArrayBufferItem(index);\n }\n\n OBSERVABLE_ARRAY_BUFFER_SIZE = max;\n }\n}\nreserveArrayBuffer(1000);\nfunction createLegacyArray(initialValues, enhancer, name) {\n return new LegacyObservableArray(initialValues, enhancer, name);\n}\n\nfunction getAtom(thing, property) {\n if (typeof thing === \"object\" && thing !== null) {\n if (isObservableArray(thing)) {\n if (property !== undefined) {\n die(23);\n }\n\n return thing[$mobx].atom_;\n }\n\n if (isObservableSet(thing)) {\n return thing[$mobx];\n }\n\n if (isObservableMap(thing)) {\n if (property === undefined) {\n return thing.keysAtom_;\n }\n\n var observable = thing.data_.get(property) || thing.hasMap_.get(property);\n\n if (!observable) {\n die(25, property, getDebugName(thing));\n }\n\n return observable;\n }\n\n\n if (isObservableObject(thing)) {\n if (!property) {\n return die(26);\n }\n\n var _observable = thing[$mobx].values_.get(property);\n\n if (!_observable) {\n die(27, property, getDebugName(thing));\n }\n\n return _observable;\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n } else if (isFunction(thing)) {\n if (isReaction(thing[$mobx])) {\n // disposer function\n return thing[$mobx];\n }\n }\n\n die(28);\n}\nfunction getAdministration(thing, property) {\n if (!thing) {\n die(29);\n }\n\n if (property !== undefined) {\n return getAdministration(getAtom(thing, property));\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n\n if (isObservableMap(thing) || isObservableSet(thing)) {\n return thing;\n }\n\n if (thing[$mobx]) {\n return thing[$mobx];\n }\n\n die(24, thing);\n}\nfunction getDebugName(thing, property) {\n var named;\n\n if (property !== undefined) {\n named = getAtom(thing, property);\n } else if (isAction(thing)) {\n return thing.name;\n } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {\n named = getAdministration(thing);\n } else {\n // valid for arrays as well\n named = getAtom(thing);\n }\n\n return named.name_;\n}\n\nvar toString = objectPrototype.toString;\nfunction deepEqual(a, b, depth) {\n if (depth === void 0) {\n depth = -1;\n }\n\n return eq(a, b, depth);\n} // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289\n// Internal recursive comparison function for `isEqual`.\n\nfunction eq(a, b, depth, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) {\n return a !== 0 || 1 / a === 1 / b;\n } // `null` or `undefined` only equal to itself (strict comparison).\n\n\n if (a == null || b == null) {\n return false;\n } // `NaN`s are equivalent, but non-reflexive.\n\n\n if (a !== a) {\n return b !== b;\n } // Exhaust primitive checks\n\n\n var type = typeof a;\n\n if (type !== \"function\" && type !== \"object\" && typeof b != \"object\") {\n return false;\n } // Compare `[[Class]]` names.\n\n\n var className = toString.call(a);\n\n if (className !== toString.call(b)) {\n return false;\n }\n\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case \"[object RegExp]\": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n\n case \"[object String]\":\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return \"\" + a === \"\" + b;\n\n case \"[object Number]\":\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN.\n if (+a !== +a) {\n return +b !== +b;\n } // An `egal` comparison is performed for other numeric values.\n\n\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n\n case \"[object Date]\":\n case \"[object Boolean]\":\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n\n case \"[object Symbol]\":\n return typeof Symbol !== \"undefined\" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);\n\n case \"[object Map]\":\n case \"[object Set]\":\n // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.\n // Hide this extra level by increasing the depth.\n if (depth >= 0) {\n depth++;\n }\n\n break;\n } // Unwrap any wrapped objects.\n\n\n a = unwrap(a);\n b = unwrap(b);\n var areArrays = className === \"[object Array]\";\n\n if (!areArrays) {\n if (typeof a != \"object\" || typeof b != \"object\") {\n return false;\n } // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n\n\n var aCtor = a.constructor,\n bCtor = b.constructor;\n\n if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && \"constructor\" in a && \"constructor\" in b) {\n return false;\n }\n }\n\n if (depth === 0) {\n return false;\n } else if (depth < 0) {\n depth = -1;\n } // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n\n\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) {\n return bStack[length] === b;\n }\n } // Add the first object to the stack of traversed objects.\n\n\n aStack.push(a);\n bStack.push(b); // Recursively compare objects and arrays.\n\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n\n if (length !== b.length) {\n return false;\n } // Deep compare the contents, ignoring non-numeric properties.\n\n\n while (length--) {\n if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {\n return false;\n }\n }\n } else {\n // Deep compare objects.\n var keys = Object.keys(a);\n var key;\n length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality.\n\n if (Object.keys(b).length !== length) {\n return false;\n }\n\n while (length--) {\n // Deep compare each member\n key = keys[length];\n\n if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {\n return false;\n }\n }\n } // Remove the first object from the stack of traversed objects.\n\n\n aStack.pop();\n bStack.pop();\n return true;\n}\n\nfunction unwrap(a) {\n if (isObservableArray(a)) {\n return a.slice();\n }\n\n if (isES6Map(a) || isObservableMap(a)) {\n return Array.from(a.entries());\n }\n\n if (isES6Set(a) || isObservableSet(a)) {\n return Array.from(a.entries());\n }\n\n return a;\n}\n\nfunction makeIterable(iterator) {\n iterator[Symbol.iterator] = getSelf;\n return iterator;\n}\n\nfunction getSelf() {\n return this;\n}\n\nfunction isAnnotation(thing) {\n return (// Can be function\n thing instanceof Object && typeof thing.annotationType_ === \"string\" && isFunction(thing.make_) && isFunction(thing.extend_)\n );\n}\n\n/**\r\n * (c) Michel Weststrate 2015 - 2020\r\n * MIT Licensed\r\n *\r\n * Welcome to the mobx sources! To get a global overview of how MobX internally works,\r\n * this is a good place to start:\r\n * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74\r\n *\r\n * Source folders:\r\n * ===============\r\n *\r\n * - api/ Most of the public static methods exposed by the module can be found here.\r\n * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.\r\n * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.\r\n * - utils/ Utility stuff.\r\n *\r\n */\n[\"Symbol\", \"Map\", \"Set\"].forEach(function (m) {\n var g = getGlobal();\n\n if (typeof g[m] === \"undefined\") {\n die(\"MobX requires global '\" + m + \"' to be available or polyfilled\");\n }\n});\n\nif (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === \"object\") {\n // See: https://github.com/andykog/mobx-devtools/\n __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({\n spy: spy,\n extras: {\n getDebugName: getDebugName\n },\n $mobx: $mobx\n });\n}\n\n\n//# sourceMappingURL=mobx.esm.js.map\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../sgmf-scripts/node_modules/webpack/buildin/global.js */ \"./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/mobx/dist/mobx.esm.js?"); + +/***/ }), + +/***/ "./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js": +/*!***********************************!*\ + !*** (webpack)/buildin/global.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +eval("var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n\n\n//# sourceURL=webpack:///(webpack)/buildin/global.js?"); + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayExpressPart1.js b/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayExpressPart1.js new file mode 100644 index 000000000..a87df738d --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayExpressPart1.js @@ -0,0 +1,148 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart1.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart1.js": +/*!****************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart1.js ***! + \****************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nvar _require = __webpack_require__(/*! ./commons */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js\"),\n checkIfExpressMethodsAreReady = _require.checkIfExpressMethodsAreReady,\n updateLoadedExpressMethods = _require.updateLoadedExpressMethods;\nvar AMAZON_PAY = 'amazonpay';\nfunction mountAmazonPayComponent() {\n return _mountAmazonPayComponent.apply(this, arguments);\n}\nfunction _mountAmazonPayComponent() {\n _mountAmazonPayComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {\n var getPaymentMethods;\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n getPaymentMethods = function _getPaymentMethods(paymentMethods) {\n $.ajax({\n url: window.getPaymentMethodsURL,\n type: 'get',\n success: function success(data) {\n paymentMethods(data);\n },\n error: function error() {\n updateLoadedExpressMethods(AMAZON_PAY);\n checkIfExpressMethodsAreReady();\n }\n });\n };\n getPaymentMethods( /*#__PURE__*/function () {\n var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(data) {\n var _paymentMethodsRespon;\n var paymentMethodsResponse, checkout, amazonPayConfig, amazonPayButtonConfig, amazonPayButton;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n paymentMethodsResponse = data.AdyenPaymentMethods;\n _context.next = 3;\n return AdyenCheckout({\n environment: window.environment,\n clientKey: window.clientKey,\n locale: window.locale\n });\n case 3:\n checkout = _context.sent;\n amazonPayConfig = (_paymentMethodsRespon = paymentMethodsResponse.find(function (pm) {\n return pm.type === AMAZON_PAY;\n })) === null || _paymentMethodsRespon === void 0 ? void 0 : _paymentMethodsRespon.configuration;\n if (amazonPayConfig) {\n _context.next = 7;\n break;\n }\n return _context.abrupt(\"return\");\n case 7:\n amazonPayButtonConfig = {\n showPayButton: true,\n productType: 'PayAndShip',\n configuration: amazonPayConfig,\n returnUrl: window.returnUrl\n };\n amazonPayButton = checkout.create(AMAZON_PAY, amazonPayButtonConfig);\n amazonPayButton.mount('#amazonpay-container');\n updateLoadedExpressMethods(AMAZON_PAY);\n checkIfExpressMethodsAreReady();\n case 12:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return function (_x) {\n return _ref.apply(this, arguments);\n };\n }());\n case 2:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n return _mountAmazonPayComponent.apply(this, arguments);\n}\nmountAmazonPayComponent();\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart1.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js": +/*!********************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nmodule.exports.onFieldValid = function onFieldValid(data) {\n if (data.endDigits) {\n store.endDigits = data.endDigits;\n document.querySelector('#cardNumber').value = store.maskedCardNumber;\n }\n};\nmodule.exports.onBrand = function onBrand(brandObject) {\n document.querySelector('#cardType').value = brandObject.brand;\n};\n\n/**\n * Makes an ajax call to the controller function CreateSession\n */\nmodule.exports.createSession = /*#__PURE__*/function () {\n var _createSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n return _context.abrupt(\"return\", $.ajax({\n url: window.sessionsUrl,\n type: 'get'\n }));\n case 1:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n function createSession() {\n return _createSession.apply(this, arguments);\n }\n return createSession;\n}();\n\n/**\n * Makes an ajax call to the controller function FetchGiftCards\n */\nmodule.exports.fetchGiftCards = /*#__PURE__*/function () {\n var _fetchGiftCards = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n return _context2.abrupt(\"return\", $.ajax({\n url: window.fetchGiftCardsUrl,\n type: 'get'\n }));\n case 1:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n function fetchGiftCards() {\n return _fetchGiftCards.apply(this, arguments);\n }\n return fetchGiftCards;\n}();\nmodule.exports.checkIfExpressMethodsAreReady = function checkIfExpressMethodsAreReady() {\n var expressMethodsConfig = {\n applepay: window.isApplePayExpressEnabled === 'true',\n amazonpay: window.isAmazonPayExpressEnabled === 'true'\n };\n var enabledExpressMethods = [];\n Object.keys(expressMethodsConfig).forEach(function (key) {\n if (expressMethodsConfig[key]) {\n enabledExpressMethods.push(key);\n }\n });\n enabledExpressMethods = enabledExpressMethods.sort();\n var loadedExpressMethods = window.loadedExpressMethods && window.loadedExpressMethods.length ? window.loadedExpressMethods.sort() : [];\n var areAllMethodsReady = JSON.stringify(enabledExpressMethods) === JSON.stringify(loadedExpressMethods);\n if (!enabledExpressMethods.length || areAllMethodsReady) {\n var _document$getElementB, _document$getElementB2;\n (_document$getElementB = document.getElementById('express-loader-container')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.classList.add('hidden');\n (_document$getElementB2 = document.getElementById('express-container')) === null || _document$getElementB2 === void 0 ? void 0 : _document$getElementB2.classList.remove('hidden');\n }\n};\nmodule.exports.updateLoadedExpressMethods = function updateLoadedExpressMethods(method) {\n if (!window.loadedExpressMethods) {\n window.loadedExpressMethods = [];\n }\n if (!window.loadedExpressMethods.includes(method)) {\n window.loadedExpressMethods.push(method);\n }\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/store/index.js": +/*!************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/store/index.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nvar _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, _descriptor12, _descriptor13;\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }\nfunction _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); }\nvar _require = __webpack_require__(/*! mobx */ \"./node_modules/mobx/dist/mobx.esm.js\"),\n observable = _require.observable,\n computed = _require.computed;\nvar Store = (_class = /*#__PURE__*/function () {\n function Store() {\n _classCallCheck(this, Store);\n _defineProperty(this, \"MASKED_CC_PREFIX\", '************');\n _initializerDefineProperty(this, \"checkout\", _descriptor, this);\n _initializerDefineProperty(this, \"endDigits\", _descriptor2, this);\n _initializerDefineProperty(this, \"selectedMethod\", _descriptor3, this);\n _initializerDefineProperty(this, \"componentsObj\", _descriptor4, this);\n _initializerDefineProperty(this, \"checkoutConfiguration\", _descriptor5, this);\n _initializerDefineProperty(this, \"formErrorsExist\", _descriptor6, this);\n _initializerDefineProperty(this, \"isValid\", _descriptor7, this);\n _initializerDefineProperty(this, \"paypalTerminatedEarly\", _descriptor8, this);\n _initializerDefineProperty(this, \"componentState\", _descriptor9, this);\n _initializerDefineProperty(this, \"brand\", _descriptor10, this);\n _initializerDefineProperty(this, \"partialPaymentsOrderObj\", _descriptor11, this);\n _initializerDefineProperty(this, \"giftCardComponentListenersAdded\", _descriptor12, this);\n _initializerDefineProperty(this, \"addedGiftCards\", _descriptor13, this);\n }\n _createClass(Store, [{\n key: \"maskedCardNumber\",\n get: function get() {\n return \"\".concat(this.MASKED_CC_PREFIX).concat(this.endDigits);\n }\n }, {\n key: \"selectedPayment\",\n get: function get() {\n return this.componentsObj[this.selectedMethod];\n }\n }, {\n key: \"selectedPaymentIsValid\",\n get: function get() {\n var _this$selectedPayment;\n return !!((_this$selectedPayment = this.selectedPayment) !== null && _this$selectedPayment !== void 0 && _this$selectedPayment.isValid);\n }\n }, {\n key: \"stateData\",\n get: function get() {\n var _this$selectedPayment2;\n return ((_this$selectedPayment2 = this.selectedPayment) === null || _this$selectedPayment2 === void 0 ? void 0 : _this$selectedPayment2.stateData) || {\n paymentMethod: _objectSpread({\n type: this.selectedMethod\n }, this.brand ? {\n brand: this.brand\n } : undefined)\n };\n }\n }, {\n key: \"updateSelectedPayment\",\n value: function updateSelectedPayment(method, key, val) {\n this.componentsObj[method][key] = val;\n }\n }]);\n return Store;\n}(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, \"checkout\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, \"endDigits\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, \"selectedMethod\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, \"componentsObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, \"checkoutConfiguration\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return window.Configuration || {};\n }\n}), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, \"formErrorsExist\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, \"isValid\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, \"paypalTerminatedEarly\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor9 = _applyDecoratedDescriptor(_class.prototype, \"componentState\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor10 = _applyDecoratedDescriptor(_class.prototype, \"brand\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor11 = _applyDecoratedDescriptor(_class.prototype, \"partialPaymentsOrderObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor12 = _applyDecoratedDescriptor(_class.prototype, \"giftCardComponentListenersAdded\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor13 = _applyDecoratedDescriptor(_class.prototype, \"addedGiftCards\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _applyDecoratedDescriptor(_class.prototype, \"maskedCardNumber\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"maskedCardNumber\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPayment\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPayment\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPaymentIsValid\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPaymentIsValid\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"stateData\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"stateData\"), _class.prototype)), _class);\nmodule.exports = new Store();\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/store/index.js?"); + +/***/ }), + +/***/ "./node_modules/mobx/dist/mobx.esm.js": +/*!********************************************!*\ + !*** ./node_modules/mobx/dist/mobx.esm.js ***! + \********************************************/ +/*! exports provided: $mobx, FlowCancellationError, ObservableMap, ObservableSet, Reaction, _allowStateChanges, _allowStateChangesInsideComputed, _allowStateReadsEnd, _allowStateReadsStart, _autoAction, _endAction, _getAdministration, _getGlobalState, _interceptReads, _isComputingDerivation, _resetGlobalState, _startAction, action, autorun, comparer, computed, configure, createAtom, defineProperty, entries, extendObservable, flow, flowResult, get, getAtom, getDebugName, getDependencyTree, getObserverTree, has, intercept, isAction, isBoxedObservable, isComputed, isComputedProp, isFlow, isFlowCancellationError, isObservable, isObservableArray, isObservableMap, isObservableObject, isObservableProp, isObservableSet, keys, makeAutoObservable, makeObservable, observable, observe, onBecomeObserved, onBecomeUnobserved, onReactionError, override, ownKeys, reaction, remove, runInAction, set, spy, toJS, trace, transaction, untracked, values, when */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"$mobx\", function() { return $mobx; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"FlowCancellationError\", function() { return FlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableMap\", function() { return ObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableSet\", function() { return ObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Reaction\", function() { return Reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChanges\", function() { return allowStateChanges; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChangesInsideComputed\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsEnd\", function() { return allowStateReadsEnd; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsStart\", function() { return allowStateReadsStart; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_autoAction\", function() { return autoAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_endAction\", function() { return _endAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getAdministration\", function() { return getAdministration; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getGlobalState\", function() { return getGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_interceptReads\", function() { return interceptReads; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_isComputingDerivation\", function() { return isComputingDerivation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_resetGlobalState\", function() { return resetGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_startAction\", function() { return _startAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"action\", function() { return action; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"autorun\", function() { return autorun; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"comparer\", function() { return comparer; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"computed\", function() { return computed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"configure\", function() { return configure; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createAtom\", function() { return createAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"defineProperty\", function() { return apiDefineProperty; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"entries\", function() { return entries; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"extendObservable\", function() { return extendObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flow\", function() { return flow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flowResult\", function() { return flowResult; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"get\", function() { return get; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getAtom\", function() { return getAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDebugName\", function() { return getDebugName; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDependencyTree\", function() { return getDependencyTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getObserverTree\", function() { return getObserverTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"has\", function() { return has; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"intercept\", function() { return intercept; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isAction\", function() { return isAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isBoxedObservable\", function() { return isObservableValue; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputed\", function() { return isComputed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputedProp\", function() { return isComputedProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlow\", function() { return isFlow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlowCancellationError\", function() { return isFlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservable\", function() { return isObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableArray\", function() { return isObservableArray; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableMap\", function() { return isObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableObject\", function() { return isObservableObject; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableProp\", function() { return isObservableProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableSet\", function() { return isObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"keys\", function() { return keys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeAutoObservable\", function() { return makeAutoObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeObservable\", function() { return makeObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observable\", function() { return observable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observe\", function() { return observe; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeObserved\", function() { return onBecomeObserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeUnobserved\", function() { return onBecomeUnobserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onReactionError\", function() { return onReactionError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"override\", function() { return override; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ownKeys\", function() { return apiOwnKeys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"reaction\", function() { return reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"remove\", function() { return remove; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"runInAction\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"set\", function() { return set; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"spy\", function() { return spy; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toJS\", function() { return toJS; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"trace\", function() { return trace; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"transaction\", function() { return transaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"untracked\", function() { return untracked; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"values\", function() { return values; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"when\", function() { return when; });\nvar niceErrors = {\n 0: \"Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'\",\n 1: function _(annotationType, key) {\n return \"Cannot apply '\" + annotationType + \"' to '\" + key.toString() + \"': Field not found.\";\n },\n\n /*\r\n 2(prop) {\r\n return `invalid decorator for '${prop.toString()}'`\r\n },\r\n 3(prop) {\r\n return `Cannot decorate '${prop.toString()}': action can only be used on properties with a function value.`\r\n },\r\n 4(prop) {\r\n return `Cannot decorate '${prop.toString()}': computed can only be used on getter properties.`\r\n },\r\n */\n 5: \"'keys()' can only be used on observable objects, arrays, sets and maps\",\n 6: \"'values()' can only be used on observable objects, arrays, sets and maps\",\n 7: \"'entries()' can only be used on observable objects, arrays and maps\",\n 8: \"'set()' can only be used on observable objects, arrays and maps\",\n 9: \"'remove()' can only be used on observable objects, arrays and maps\",\n 10: \"'has()' can only be used on observable objects, arrays and maps\",\n 11: \"'get()' can only be used on observable objects, arrays and maps\",\n 12: \"Invalid annotation\",\n 13: \"Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 14: \"Intercept handlers should return nothing or a change object\",\n 15: \"Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 16: \"Modification exception: the internal structure of an observable array was changed.\",\n 17: function _(index, length) {\n return \"[mobx.array] Index out of bounds, \" + index + \" is larger than \" + length;\n },\n 18: \"mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js\",\n 19: function _(other) {\n return \"Cannot initialize from classes that inherit from Map: \" + other.constructor.name;\n },\n 20: function _(other) {\n return \"Cannot initialize map from \" + other;\n },\n 21: function _(dataStructure) {\n return \"Cannot convert to map from '\" + dataStructure + \"'\";\n },\n 22: \"mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js\",\n 23: \"It is not possible to get index atoms from arrays\",\n 24: function _(thing) {\n return \"Cannot obtain administration from \" + thing;\n },\n 25: function _(property, name) {\n return \"the entry '\" + property + \"' does not exist in the observable map '\" + name + \"'\";\n },\n 26: \"please specify a property\",\n 27: function _(property, name) {\n return \"no observable property '\" + property.toString() + \"' found on the observable object '\" + name + \"'\";\n },\n 28: function _(thing) {\n return \"Cannot obtain atom from \" + thing;\n },\n 29: \"Expecting some object\",\n 30: \"invalid action stack. did you forget to finish an action?\",\n 31: \"missing option for computed: get\",\n 32: function _(name, derivation) {\n return \"Cycle detected in computation \" + name + \": \" + derivation;\n },\n 33: function _(name) {\n return \"The setter of computed value '\" + name + \"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?\";\n },\n 34: function _(name) {\n return \"[ComputedValue '\" + name + \"'] It is not possible to assign a new value to a computed value.\";\n },\n 35: \"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`\",\n 36: \"isolateGlobalState should be called before MobX is running any reactions\",\n 37: function _(method) {\n return \"[mobx] `observableArray.\" + method + \"()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice().\" + method + \"()` instead\";\n },\n 38: \"'ownKeys()' can only be used on observable objects\",\n 39: \"'defineProperty()' can only be used on observable objects\"\n};\nvar errors = true ? niceErrors : undefined;\nfunction die(error) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n if (true) {\n var e = typeof error === \"string\" ? error : errors[error];\n if (typeof e === \"function\") e = e.apply(null, args);\n throw new Error(\"[MobX] \" + e);\n }\n\n throw new Error(typeof error === \"number\" ? \"[MobX] minified error nr: \" + error + (args.length ? \" \" + args.map(String).join(\",\") : \"\") + \". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts\" : \"[MobX] \" + error);\n}\n\nvar mockGlobal = {};\nfunction getGlobal() {\n if (typeof globalThis !== \"undefined\") {\n return globalThis;\n }\n\n if (typeof window !== \"undefined\") {\n return window;\n }\n\n if (typeof global !== \"undefined\") {\n return global;\n }\n\n if (typeof self !== \"undefined\") {\n return self;\n }\n\n return mockGlobal;\n}\n\nvar assign = Object.assign;\nvar getDescriptor = Object.getOwnPropertyDescriptor;\nvar defineProperty = Object.defineProperty;\nvar objectPrototype = Object.prototype;\nvar EMPTY_ARRAY = [];\nObject.freeze(EMPTY_ARRAY);\nvar EMPTY_OBJECT = {};\nObject.freeze(EMPTY_OBJECT);\nvar hasProxy = typeof Proxy !== \"undefined\";\nvar plainObjectString = /*#__PURE__*/Object.toString();\nfunction assertProxies() {\n if (!hasProxy) {\n die( true ? \"`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`\" : undefined);\n }\n}\nfunction warnAboutProxyRequirement(msg) {\n if ( true && globalState.verifyProxies) {\n die(\"MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to \" + msg);\n }\n}\nfunction getNextId() {\n return ++globalState.mobxGuid;\n}\n/**\r\n * Makes sure that the provided function is invoked at most once.\r\n */\n\nfunction once(func) {\n var invoked = false;\n return function () {\n if (invoked) {\n return;\n }\n\n invoked = true;\n return func.apply(this, arguments);\n };\n}\nvar noop = function noop() {};\nfunction isFunction(fn) {\n return typeof fn === \"function\";\n}\nfunction isStringish(value) {\n var t = typeof value;\n\n switch (t) {\n case \"string\":\n case \"symbol\":\n case \"number\":\n return true;\n }\n\n return false;\n}\nfunction isObject(value) {\n return value !== null && typeof value === \"object\";\n}\nfunction isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n\n var proto = Object.getPrototypeOf(value);\n\n if (proto == null) {\n return true;\n }\n\n var protoConstructor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof protoConstructor === \"function\" && protoConstructor.toString() === plainObjectString;\n} // https://stackoverflow.com/a/37865170\n\nfunction isGenerator(obj) {\n var constructor = obj == null ? void 0 : obj.constructor;\n\n if (!constructor) {\n return false;\n }\n\n if (\"GeneratorFunction\" === constructor.name || \"GeneratorFunction\" === constructor.displayName) {\n return true;\n }\n\n return false;\n}\nfunction addHiddenProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\nfunction addHiddenFinalProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\nfunction createInstanceofPredicate(name, theClass) {\n var propName = \"isMobX\" + name;\n theClass.prototype[propName] = true;\n return function (x) {\n return isObject(x) && x[propName] === true;\n };\n}\nfunction isES6Map(thing) {\n return thing instanceof Map;\n}\nfunction isES6Set(thing) {\n return thing instanceof Set;\n}\nvar hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== \"undefined\";\n/**\r\n * Returns the following: own enumerable keys and symbols.\r\n */\n\nfunction getPlainObjectKeys(object) {\n var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway...\n\n if (!hasGetOwnPropertySymbols) {\n return keys;\n }\n\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (!symbols.length) {\n return keys;\n }\n\n return [].concat(keys, symbols.filter(function (s) {\n return objectPrototype.propertyIsEnumerable.call(object, s);\n }));\n} // From Immer utils\n// Returns all own keys, including non-enumerable and symbolic\n\nvar ownKeys = typeof Reflect !== \"undefined\" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {\n return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));\n} :\n/* istanbul ignore next */\nObject.getOwnPropertyNames;\nfunction stringifyKey(key) {\n if (typeof key === \"string\") {\n return key;\n }\n\n if (typeof key === \"symbol\") {\n return key.toString();\n }\n\n return new String(key).toString();\n}\nfunction toPrimitive(value) {\n return value === null ? null : typeof value === \"object\" ? \"\" + value : value;\n}\nfunction hasProp(target, prop) {\n return objectPrototype.hasOwnProperty.call(target, prop);\n} // From Immer utils\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {\n // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up\n\n ownKeys(target).forEach(function (key) {\n res[key] = getDescriptor(target, key);\n });\n return res;\n};\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n\n _setPrototypeOf(subClass, superClass);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n if (it) return (it = it.call(o)).next.bind(it);\n\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n return function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar storedAnnotationsSymbol = /*#__PURE__*/Symbol(\"mobx-stored-annotations\");\n/**\r\n * Creates a function that acts as\r\n * - decorator\r\n * - annotation object\r\n */\n\nfunction createDecoratorAnnotation(annotation) {\n function decorator(target, property) {\n storeAnnotation(target, property, annotation);\n }\n\n return Object.assign(decorator, annotation);\n}\n/**\r\n * Stores annotation to prototype,\r\n * so it can be inspected later by `makeObservable` called from constructor\r\n */\n\nfunction storeAnnotation(prototype, key, annotation) {\n if (!hasProp(prototype, storedAnnotationsSymbol)) {\n addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));\n } // @override must override something\n\n\n if ( true && isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n die(\"'\" + fieldName + \"' is decorated with 'override', \" + \"but no such decorated member was found on prototype.\");\n } // Cannot re-decorate\n\n\n assertNotDecorated(prototype, annotation, key); // Ignore override\n\n if (!isOverride(annotation)) {\n prototype[storedAnnotationsSymbol][key] = annotation;\n }\n}\n\nfunction assertNotDecorated(prototype, annotation, key) {\n if ( true && !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '@\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already decorated with '@\" + currentAnnotationType + \"'.\") + \"\\nRe-decorating fields is not allowed.\" + \"\\nUse '@override' decorator for methods overridden by subclass.\");\n }\n}\n/**\r\n * Collects annotations from prototypes and stores them on target (instance)\r\n */\n\n\nfunction collectStoredAnnotations(target) {\n if (!hasProp(target, storedAnnotationsSymbol)) {\n if ( true && !target[storedAnnotationsSymbol]) {\n die(\"No annotations were passed to makeObservable, but no decorated members have been found either\");\n } // We need a copy as we will remove annotation from the list once it's applied.\n\n\n addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));\n }\n\n return target[storedAnnotationsSymbol];\n}\n\nvar $mobx = /*#__PURE__*/Symbol(\"mobx administration\");\nvar Atom = /*#__PURE__*/function () {\n // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed\n\n /**\r\n * Create a new atom. For debugging purposes it is recommended to give it a name.\r\n * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.\r\n */\n function Atom(name_) {\n if (name_ === void 0) {\n name_ = true ? \"Atom@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.isPendingUnobservation_ = false;\n this.isBeingObserved_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n this.name_ = name_;\n } // onBecomeObservedListeners\n\n\n var _proto = Atom.prototype;\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Invoke this method to notify mobx that your atom has been used somehow.\r\n * Returns true if there is currently a reactive context.\r\n */\n ;\n\n _proto.reportObserved = function reportObserved$1() {\n return reportObserved(this);\n }\n /**\r\n * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.\r\n */\n ;\n\n _proto.reportChanged = function reportChanged() {\n startBatch();\n propagateChanged(this);\n endBatch();\n };\n\n _proto.toString = function toString() {\n return this.name_;\n };\n\n return Atom;\n}();\nvar isAtom = /*#__PURE__*/createInstanceofPredicate(\"Atom\", Atom);\nfunction createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {\n if (onBecomeObservedHandler === void 0) {\n onBecomeObservedHandler = noop;\n }\n\n if (onBecomeUnobservedHandler === void 0) {\n onBecomeUnobservedHandler = noop;\n }\n\n var atom = new Atom(name); // default `noop` listener will not initialize the hook Set\n\n if (onBecomeObservedHandler !== noop) {\n onBecomeObserved(atom, onBecomeObservedHandler);\n }\n\n if (onBecomeUnobservedHandler !== noop) {\n onBecomeUnobserved(atom, onBecomeUnobservedHandler);\n }\n\n return atom;\n}\n\nfunction identityComparer(a, b) {\n return a === b;\n}\n\nfunction structuralComparer(a, b) {\n return deepEqual(a, b);\n}\n\nfunction shallowComparer(a, b) {\n return deepEqual(a, b, 1);\n}\n\nfunction defaultComparer(a, b) {\n if (Object.is) {\n return Object.is(a, b);\n }\n\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n}\n\nvar comparer = {\n identity: identityComparer,\n structural: structuralComparer,\n \"default\": defaultComparer,\n shallow: shallowComparer\n};\n\nfunction deepEnhancer(v, _, name) {\n // it is an observable already, done\n if (isObservable(v)) {\n return v;\n } // something that can be converted and mutated?\n\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name\n });\n }\n\n if (typeof v === \"function\" && !isAction(v) && !isFlow(v)) {\n if (isGenerator(v)) {\n return flow(v);\n } else {\n return autoAction(name, v);\n }\n }\n\n return v;\n}\nfunction shallowEnhancer(v, _, name) {\n if (v === undefined || v === null) {\n return v;\n }\n\n if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {\n return v;\n }\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name,\n deep: false\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name,\n deep: false\n });\n }\n\n if (true) {\n die(\"The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets\");\n }\n}\nfunction referenceEnhancer(newValue) {\n // never turn into an observable\n return newValue;\n}\nfunction refStructEnhancer(v, oldValue) {\n if ( true && isObservable(v)) {\n die(\"observable.struct should not be used with observable values\");\n }\n\n if (deepEqual(v, oldValue)) {\n return oldValue;\n }\n\n return v;\n}\n\nvar OVERRIDE = \"override\";\nvar override = /*#__PURE__*/createDecoratorAnnotation({\n annotationType_: OVERRIDE,\n make_: make_,\n extend_: extend_\n});\nfunction isOverride(annotation) {\n return annotation.annotationType_ === OVERRIDE;\n}\n\nfunction make_(adm, key) {\n // Must not be plain object\n if ( true && adm.isPlainObject_) {\n die(\"Cannot apply '\" + this.annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + this.annotationType_ + \"' cannot be used on plain objects.\"));\n } // Must override something\n\n\n if ( true && !hasProp(adm.appliedAnnotations_, key)) {\n die(\"'\" + adm.name_ + \".\" + key.toString() + \"' is annotated with '\" + this.annotationType_ + \"', \" + \"but no such annotated member was found on prototype.\");\n }\n\n return 0\n /* Cancel */\n ;\n}\n\nfunction extend_(adm, key, descriptor, proxyTrap) {\n die(\"'\" + this.annotationType_ + \"' can only be used with 'makeObservable'\");\n}\n\nfunction createActionAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$1,\n extend_: extend_$1\n };\n}\n\nfunction make_$1(adm, key, descriptor, source) {\n var _this$options_;\n\n // bound\n if ((_this$options_ = this.options_) != null && _this$options_.bound) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n } // own\n\n\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n\n\n if (isAction(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);\n defineProperty(source, key, actionDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$1(adm, key, descriptor, proxyTrap) {\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);\n return adm.defineProperty_(key, actionDescriptor, proxyTrap);\n}\n\nfunction assertActionDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a function value.\"));\n }\n}\n\nfunction createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;\n\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertActionDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n\n if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {\n var _adm$proxy_;\n\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return {\n value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false, // https://github.com/mobxjs/mobx/discussions/3140\n (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createFlowAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$2,\n extend_: extend_$2\n };\n}\n\nfunction make_$2(adm, key, descriptor, source) {\n var _this$options_;\n\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n // bound - must annotate protos to support super.flow()\n\n\n if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {\n if (this.extend_(adm, key, descriptor, false) === null) {\n return 0\n /* Cancel */\n ;\n }\n }\n\n if (isFlow(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);\n defineProperty(source, key, flowDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$2(adm, key, descriptor, proxyTrap) {\n var _this$options_2;\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);\n return adm.defineProperty_(key, flowDescriptor, proxyTrap);\n}\n\nfunction assertFlowDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a generator function value.\"));\n }\n}\n\nfunction createFlowDescriptor(adm, annotation, key, descriptor, bound, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertFlowDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value; // In case of flow.bound, the descriptor can be from already annotated prototype\n\n if (!isFlow(value)) {\n value = flow(value);\n }\n\n if (bound) {\n var _adm$proxy_;\n\n // We do not keep original function around, so we bind the existing flow\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); // This is normally set by `flow`, but `bind` returns new function...\n\n value.isMobXFlow = true;\n }\n\n return {\n value: value,\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createComputedAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$3,\n extend_: extend_$3\n };\n}\n\nfunction make_$3(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$3(adm, key, descriptor, proxyTrap) {\n assertComputedDescriptor(adm, this, key, descriptor);\n return adm.defineComputedProperty_(key, _extends({}, this.options_, {\n get: descriptor.get,\n set: descriptor.set\n }), proxyTrap);\n}\n\nfunction assertComputedDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var get = _ref2.get;\n\n if ( true && !get) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on getter(+setter) properties.\"));\n }\n}\n\nfunction createObservableAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$4,\n extend_: extend_$4\n };\n}\n\nfunction make_$4(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$4(adm, key, descriptor, proxyTrap) {\n var _this$options_$enhanc, _this$options_;\n\n assertObservableDescriptor(adm, this, key, descriptor);\n return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap);\n}\n\nfunction assertObservableDescriptor(adm, _ref, key, descriptor) {\n var annotationType_ = _ref.annotationType_;\n\n if ( true && !(\"value\" in descriptor)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' cannot be used on getter/setter properties\"));\n }\n}\n\nvar AUTO = \"true\";\nvar autoAnnotation = /*#__PURE__*/createAutoAnnotation();\nfunction createAutoAnnotation(options) {\n return {\n annotationType_: AUTO,\n options_: options,\n make_: make_$5,\n extend_: extend_$5\n };\n}\n\nfunction make_$5(adm, key, descriptor, source) {\n var _this$options_3, _this$options_4;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.make_(adm, key, descriptor, source);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.make_\n var set = createAction(key.toString(), descriptor.set); // own\n\n if (source === adm.target_) {\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: set\n }) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // proto\n\n\n defineProperty(source, key, {\n configurable: true,\n set: set\n });\n return 2\n /* Continue */\n ;\n } // function on proto -> autoAction/flow\n\n\n if (source !== adm.target_ && typeof descriptor.value === \"function\") {\n var _this$options_2;\n\n if (isGenerator(descriptor.value)) {\n var _this$options_;\n\n var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;\n return flowAnnotation.make_(adm, key, descriptor, source);\n }\n\n var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;\n return actionAnnotation.make_(adm, key, descriptor, source);\n } // other -> observable\n // Copy props from proto as well, see test:\n // \"decorate should work with Object.create\"\n\n\n var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable; // if function respect autoBind option\n\n if (typeof descriptor.value === \"function\" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {\n var _adm$proxy_;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return observableAnnotation.make_(adm, key, descriptor, source);\n}\n\nfunction extend_$5(adm, key, descriptor, proxyTrap) {\n var _this$options_5, _this$options_6;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.extend_(adm, key, descriptor, proxyTrap);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.extend_\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: createAction(key.toString(), descriptor.set)\n }, proxyTrap);\n } // other -> observable\n // if function respect autoBind option\n\n\n if (typeof descriptor.value === \"function\" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {\n var _adm$proxy_2;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);\n }\n\n var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;\n return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);\n}\n\nvar OBSERVABLE = \"observable\";\nvar OBSERVABLE_REF = \"observable.ref\";\nvar OBSERVABLE_SHALLOW = \"observable.shallow\";\nvar OBSERVABLE_STRUCT = \"observable.struct\"; // Predefined bags of create observable options, to avoid allocating temporarily option objects\n// in the majority of cases\n\nvar defaultCreateObservableOptions = {\n deep: true,\n name: undefined,\n defaultDecorator: undefined,\n proxy: true\n};\nObject.freeze(defaultCreateObservableOptions);\nfunction asCreateObservableOptions(thing) {\n return thing || defaultCreateObservableOptions;\n}\nvar observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);\nvar observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {\n enhancer: referenceEnhancer\n});\nvar observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {\n enhancer: shallowEnhancer\n});\nvar observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {\n enhancer: refStructEnhancer\n});\nvar observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);\nfunction getEnhancerFromOptions(options) {\n return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);\n}\nfunction getAnnotationFromOptions(options) {\n var _options$defaultDecor;\n\n return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;\n}\nfunction getEnhancerFromAnnotation(annotation) {\n var _annotation$options_$, _annotation$options_;\n\n return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;\n}\n/**\r\n * Turns an object, array or function into a reactive structure.\r\n * @param v the value which should become observable.\r\n */\n\nfunction createObservable(v, arg2, arg3) {\n // @observable someProp;\n if (isStringish(arg2)) {\n storeAnnotation(v, arg2, observableAnnotation);\n return;\n } // already observable - ignore\n\n\n if (isObservable(v)) {\n return v;\n } // plain object\n\n\n if (isPlainObject(v)) {\n return observable.object(v, arg2, arg3);\n } // Array\n\n\n if (Array.isArray(v)) {\n return observable.array(v, arg2);\n } // Map\n\n\n if (isES6Map(v)) {\n return observable.map(v, arg2);\n } // Set\n\n\n if (isES6Set(v)) {\n return observable.set(v, arg2);\n } // other object - ignore\n\n\n if (typeof v === \"object\" && v !== null) {\n return v;\n } // anything else\n\n\n return observable.box(v, arg2);\n}\n\nObject.assign(createObservable, observableDecoratorAnnotation);\nvar observableFactories = {\n box: function box(value, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);\n },\n array: function array(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);\n },\n map: function map(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);\n },\n set: function set(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);\n },\n object: function object(props, decorators, options) {\n return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);\n },\n ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),\n shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),\n deep: observableDecoratorAnnotation,\n struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)\n}; // eslint-disable-next-line\n\nvar observable = /*#__PURE__*/assign(createObservable, observableFactories);\n\nvar COMPUTED = \"computed\";\nvar COMPUTED_STRUCT = \"computed.struct\";\nvar computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);\nvar computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {\n equals: comparer.structural\n});\n/**\r\n * Decorator for class properties: @computed get value() { return expr; }.\r\n * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;\r\n */\n\nvar computed = function computed(arg1, arg2) {\n if (isStringish(arg2)) {\n // @computed\n return storeAnnotation(arg1, arg2, computedAnnotation);\n }\n\n if (isPlainObject(arg1)) {\n // @computed({ options })\n return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));\n } // computed(expr, options?)\n\n\n if (true) {\n if (!isFunction(arg1)) {\n die(\"First argument to `computed` should be an expression.\");\n }\n\n if (isFunction(arg2)) {\n die(\"A setter as second argument is no longer supported, use `{ set: fn }` option instead\");\n }\n }\n\n var opts = isPlainObject(arg2) ? arg2 : {};\n opts.get = arg1;\n opts.name || (opts.name = arg1.name || \"\");\n /* for generated name */\n\n return new ComputedValue(opts);\n};\nObject.assign(computed, computedAnnotation);\ncomputed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);\n\nvar _getDescriptor$config, _getDescriptor;\n// mobx versions\n\nvar currentActionId = 0;\nvar nextActionId = 1;\nvar isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, \"name\")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object\n\nvar tmpNameDescriptor = {\n value: \"action\",\n configurable: true,\n writable: false,\n enumerable: false\n};\nfunction createAction(actionName, fn, autoAction, ref) {\n if (autoAction === void 0) {\n autoAction = false;\n }\n\n if (true) {\n if (!isFunction(fn)) {\n die(\"`action` can only be invoked on functions\");\n }\n\n if (typeof actionName !== \"string\" || !actionName) {\n die(\"actions should have valid names, got: '\" + actionName + \"'\");\n }\n }\n\n function res() {\n return executeAction(actionName, autoAction, fn, ref || this, arguments);\n }\n\n res.isMobxAction = true;\n\n if (isFunctionNameConfigurable) {\n tmpNameDescriptor.value = actionName;\n Object.defineProperty(res, \"name\", tmpNameDescriptor);\n }\n\n return res;\n}\nfunction executeAction(actionName, canRunAsDerivation, fn, scope, args) {\n var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);\n\n try {\n return fn.apply(scope, args);\n } catch (err) {\n runInfo.error_ = err;\n throw err;\n } finally {\n _endAction(runInfo);\n }\n}\nfunction _startAction(actionName, canRunAsDerivation, // true for autoAction\nscope, args) {\n var notifySpy_ = true && isSpyEnabled() && !!actionName;\n var startTime_ = 0;\n\n if ( true && notifySpy_) {\n startTime_ = Date.now();\n var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;\n spyReportStart({\n type: ACTION,\n name: actionName,\n object: scope,\n arguments: flattenedArgs\n });\n }\n\n var prevDerivation_ = globalState.trackingDerivation;\n var runAsAction = !canRunAsDerivation || !prevDerivation_;\n startBatch();\n var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow\n\n if (runAsAction) {\n untrackedStart();\n prevAllowStateChanges_ = allowStateChangesStart(true);\n }\n\n var prevAllowStateReads_ = allowStateReadsStart(true);\n var runInfo = {\n runAsAction_: runAsAction,\n prevDerivation_: prevDerivation_,\n prevAllowStateChanges_: prevAllowStateChanges_,\n prevAllowStateReads_: prevAllowStateReads_,\n notifySpy_: notifySpy_,\n startTime_: startTime_,\n actionId_: nextActionId++,\n parentActionId_: currentActionId\n };\n currentActionId = runInfo.actionId_;\n return runInfo;\n}\nfunction _endAction(runInfo) {\n if (currentActionId !== runInfo.actionId_) {\n die(30);\n }\n\n currentActionId = runInfo.parentActionId_;\n\n if (runInfo.error_ !== undefined) {\n globalState.suppressReactionErrors = true;\n }\n\n allowStateChangesEnd(runInfo.prevAllowStateChanges_);\n allowStateReadsEnd(runInfo.prevAllowStateReads_);\n endBatch();\n\n if (runInfo.runAsAction_) {\n untrackedEnd(runInfo.prevDerivation_);\n }\n\n if ( true && runInfo.notifySpy_) {\n spyReportEnd({\n time: Date.now() - runInfo.startTime_\n });\n }\n\n globalState.suppressReactionErrors = false;\n}\nfunction allowStateChanges(allowStateChanges, func) {\n var prev = allowStateChangesStart(allowStateChanges);\n\n try {\n return func();\n } finally {\n allowStateChangesEnd(prev);\n }\n}\nfunction allowStateChangesStart(allowStateChanges) {\n var prev = globalState.allowStateChanges;\n globalState.allowStateChanges = allowStateChanges;\n return prev;\n}\nfunction allowStateChangesEnd(prev) {\n globalState.allowStateChanges = prev;\n}\n\nvar _Symbol$toPrimitive;\nvar CREATE = \"create\";\n_Symbol$toPrimitive = Symbol.toPrimitive;\nvar ObservableValue = /*#__PURE__*/function (_Atom) {\n _inheritsLoose(ObservableValue, _Atom);\n\n function ObservableValue(value, enhancer, name_, notifySpy, equals) {\n var _this;\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableValue@\" + getNextId() : undefined;\n }\n\n if (notifySpy === void 0) {\n notifySpy = true;\n }\n\n if (equals === void 0) {\n equals = comparer[\"default\"];\n }\n\n _this = _Atom.call(this, name_) || this;\n _this.enhancer = void 0;\n _this.name_ = void 0;\n _this.equals = void 0;\n _this.hasUnreportedChange_ = false;\n _this.interceptors_ = void 0;\n _this.changeListeners_ = void 0;\n _this.value_ = void 0;\n _this.dehancer = void 0;\n _this.enhancer = enhancer;\n _this.name_ = name_;\n _this.equals = equals;\n _this.value_ = enhancer(value, undefined, name_);\n\n if ( true && notifySpy && isSpyEnabled()) {\n // only notify spy if this is a stand-alone observable\n spyReport({\n type: CREATE,\n object: _assertThisInitialized(_this),\n observableKind: \"value\",\n debugObjectName: _this.name_,\n newValue: \"\" + _this.value_\n });\n }\n\n return _this;\n }\n\n var _proto = ObservableValue.prototype;\n\n _proto.dehanceValue = function dehanceValue(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.set = function set(newValue) {\n var oldValue = this.value_;\n newValue = this.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n\n if ( true && notifySpy) {\n spyReportStart({\n type: UPDATE,\n object: this,\n observableKind: \"value\",\n debugObjectName: this.name_,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n\n this.setNewValue_(newValue);\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.prepareNewValue_ = function prepareNewValue_(newValue) {\n checkIfStateModificationsAreAllowed(this);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this,\n type: UPDATE,\n newValue: newValue\n });\n\n if (!change) {\n return globalState.UNCHANGED;\n }\n\n newValue = change.newValue;\n } // apply modifier\n\n\n newValue = this.enhancer(newValue, this.value_, this.name_);\n return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;\n };\n\n _proto.setNewValue_ = function setNewValue_(newValue) {\n var oldValue = this.value_;\n this.value_ = newValue;\n this.reportChanged();\n\n if (hasListeners(this)) {\n notifyListeners(this, {\n type: UPDATE,\n object: this,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n };\n\n _proto.get = function get() {\n this.reportObserved();\n return this.dehanceValue(this.value_);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately) {\n listener({\n observableKind: \"value\",\n debugObjectName: this.name_,\n object: this,\n type: UPDATE,\n newValue: this.value_,\n oldValue: undefined\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.raw = function raw() {\n // used by MST ot get undehanced value\n return this.value_;\n };\n\n _proto.toJSON = function toJSON() {\n return this.get();\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.value_ + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive] = function () {\n return this.valueOf();\n };\n\n return ObservableValue;\n}(Atom);\nvar isObservableValue = /*#__PURE__*/createInstanceofPredicate(\"ObservableValue\", ObservableValue);\n\nvar _Symbol$toPrimitive$1;\n/**\r\n * A node in the state dependency root that observes other nodes, and can be observed itself.\r\n *\r\n * ComputedValue will remember the result of the computation for the duration of the batch, or\r\n * while being observed.\r\n *\r\n * During this time it will recompute only when one of its direct dependencies changed,\r\n * but only when it is being accessed with `ComputedValue.get()`.\r\n *\r\n * Implementation description:\r\n * 1. First time it's being accessed it will compute and remember result\r\n * give back remembered result until 2. happens\r\n * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.\r\n * 3. When it's being accessed, recompute if any shallow dependency changed.\r\n * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.\r\n * go to step 2. either way\r\n *\r\n * If at any point it's outside batch and it isn't observed: reset everything and go to 1.\r\n */\n\n_Symbol$toPrimitive$1 = Symbol.toPrimitive;\nvar ComputedValue = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n // during tracking it's an array with new observed observers\n // to check for cycles\n // N.B: unminified as it is used by MST\n\n /**\r\n * Create a new computed value based on a function expression.\r\n *\r\n * The `name` property is for debug purposes only.\r\n *\r\n * The `equals` property specifies the comparer function to use to determine if a newly produced\r\n * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`\r\n * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.\r\n * Structural comparison can be convenient if you always produce a new aggregated object and\r\n * don't want to notify observers if it is structurally the same.\r\n * This is useful for working with vectors, mouse coordinates etc.\r\n */\n function ComputedValue(options) {\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.observing_ = [];\n this.newObserving_ = null;\n this.isBeingObserved_ = false;\n this.isPendingUnobservation_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n this.unboundDepsCount_ = 0;\n this.value_ = new CaughtException(null);\n this.name_ = void 0;\n this.triggeredBy_ = void 0;\n this.isComputing_ = false;\n this.isRunningSetter_ = false;\n this.derivation = void 0;\n this.setter_ = void 0;\n this.isTracing_ = TraceMode.NONE;\n this.scope_ = void 0;\n this.equals_ = void 0;\n this.requiresReaction_ = void 0;\n this.keepAlive_ = void 0;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n\n if (!options.get) {\n die(31);\n }\n\n this.derivation = options.get;\n this.name_ = options.name || ( true ? \"ComputedValue@\" + getNextId() : undefined);\n\n if (options.set) {\n this.setter_ = createAction( true ? this.name_ + \"-setter\" : undefined, options.set);\n }\n\n this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer[\"default\"]);\n this.scope_ = options.context;\n this.requiresReaction_ = options.requiresReaction;\n this.keepAlive_ = !!options.keepAlive;\n }\n\n var _proto = ComputedValue.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n propagateMaybeChanged(this);\n };\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Returns the current value of this computed value.\r\n * Will evaluate its computation first if needed.\r\n */\n ;\n\n _proto.get = function get() {\n if (this.isComputing_) {\n die(32, this.name_, this.derivation);\n }\n\n if (globalState.inBatch === 0 && // !globalState.trackingDerivatpion &&\n this.observers_.size === 0 && !this.keepAlive_) {\n if (shouldCompute(this)) {\n this.warnAboutUntrackedRead_();\n startBatch(); // See perf test 'computed memoization'\n\n this.value_ = this.computeValue_(false);\n endBatch();\n }\n } else {\n reportObserved(this);\n\n if (shouldCompute(this)) {\n var prevTrackingContext = globalState.trackingContext;\n\n if (this.keepAlive_ && !prevTrackingContext) {\n globalState.trackingContext = this;\n }\n\n if (this.trackAndCompute()) {\n propagateChangeConfirmed(this);\n }\n\n globalState.trackingContext = prevTrackingContext;\n }\n }\n\n var result = this.value_;\n\n if (isCaughtException(result)) {\n throw result.cause;\n }\n\n return result;\n };\n\n _proto.set = function set(value) {\n if (this.setter_) {\n if (this.isRunningSetter_) {\n die(33, this.name_);\n }\n\n this.isRunningSetter_ = true;\n\n try {\n this.setter_.call(this.scope_, value);\n } finally {\n this.isRunningSetter_ = false;\n }\n } else {\n die(34, this.name_);\n }\n };\n\n _proto.trackAndCompute = function trackAndCompute() {\n // N.B: unminified as it is used by MST\n var oldValue = this.value_;\n var wasSuspended =\n /* see #1208 */\n this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;\n var newValue = this.computeValue_(true);\n var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);\n\n if (changed) {\n this.value_ = newValue;\n\n if ( true && isSpyEnabled()) {\n spyReport({\n observableKind: \"computed\",\n debugObjectName: this.name_,\n object: this.scope_,\n type: \"update\",\n oldValue: oldValue,\n newValue: newValue\n });\n }\n }\n\n return changed;\n };\n\n _proto.computeValue_ = function computeValue_(track) {\n this.isComputing_ = true; // don't allow state changes during computation\n\n var prev = allowStateChangesStart(false);\n var res;\n\n if (track) {\n res = trackDerivedFunction(this, this.derivation, this.scope_);\n } else {\n if (globalState.disableErrorBoundaries === true) {\n res = this.derivation.call(this.scope_);\n } else {\n try {\n res = this.derivation.call(this.scope_);\n } catch (e) {\n res = new CaughtException(e);\n }\n }\n }\n\n allowStateChangesEnd(prev);\n this.isComputing_ = false;\n return res;\n };\n\n _proto.suspend_ = function suspend_() {\n if (!this.keepAlive_) {\n clearObserving(this);\n this.value_ = undefined; // don't hold on to computed value!\n\n if ( true && this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' was suspended and it will recompute on the next access.\");\n }\n }\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n var _this = this;\n\n var firstTime = true;\n var prevValue = undefined;\n return autorun(function () {\n // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place\n var newValue = _this.get();\n\n if (!firstTime || fireImmediately) {\n var prevU = untrackedStart();\n listener({\n observableKind: \"computed\",\n debugObjectName: _this.name_,\n type: UPDATE,\n object: _this,\n newValue: newValue,\n oldValue: prevValue\n });\n untrackedEnd(prevU);\n }\n\n firstTime = false;\n prevValue = newValue;\n });\n };\n\n _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {\n if (false) {}\n\n if (this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n\n if (typeof this.requiresReaction_ === \"boolean\" ? this.requiresReaction_ : globalState.computedRequiresReaction) {\n console.warn(\"[mobx] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.derivation.toString() + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive$1] = function () {\n return this.valueOf();\n };\n\n return ComputedValue;\n}();\nvar isComputedValue = /*#__PURE__*/createInstanceofPredicate(\"ComputedValue\", ComputedValue);\n\nvar IDerivationState_;\n\n(function (IDerivationState_) {\n // before being run or (outside batch and not being observed)\n // at this point derivation is not holding any data about dependency tree\n IDerivationState_[IDerivationState_[\"NOT_TRACKING_\"] = -1] = \"NOT_TRACKING_\"; // no shallow dependency changed since last computation\n // won't recalculate derivation\n // this is what makes mobx fast\n\n IDerivationState_[IDerivationState_[\"UP_TO_DATE_\"] = 0] = \"UP_TO_DATE_\"; // some deep dependency changed, but don't know if shallow dependency changed\n // will require to check first if UP_TO_DATE or POSSIBLY_STALE\n // currently only ComputedValue will propagate POSSIBLY_STALE\n //\n // having this state is second big optimization:\n // don't have to recompute on every dependency change, but only when it's needed\n\n IDerivationState_[IDerivationState_[\"POSSIBLY_STALE_\"] = 1] = \"POSSIBLY_STALE_\"; // A shallow dependency has changed since last computation and the derivation\n // will need to recompute when it's needed next.\n\n IDerivationState_[IDerivationState_[\"STALE_\"] = 2] = \"STALE_\";\n})(IDerivationState_ || (IDerivationState_ = {}));\n\nvar TraceMode;\n\n(function (TraceMode) {\n TraceMode[TraceMode[\"NONE\"] = 0] = \"NONE\";\n TraceMode[TraceMode[\"LOG\"] = 1] = \"LOG\";\n TraceMode[TraceMode[\"BREAK\"] = 2] = \"BREAK\";\n})(TraceMode || (TraceMode = {}));\n\nvar CaughtException = function CaughtException(cause) {\n this.cause = void 0;\n this.cause = cause; // Empty\n};\nfunction isCaughtException(e) {\n return e instanceof CaughtException;\n}\n/**\r\n * Finds out whether any dependency of the derivation has actually changed.\r\n * If dependenciesState is 1 then it will recalculate dependencies,\r\n * if any dependency changed it will propagate it by changing dependenciesState to 2.\r\n *\r\n * By iterating over the dependencies in the same order that they were reported and\r\n * stopping on the first change, all the recalculations are only called for ComputedValues\r\n * that will be tracked by derivation. That is because we assume that if the first x\r\n * dependencies of the derivation doesn't change then the derivation should run the same way\r\n * up until accessing x-th dependency.\r\n */\n\nfunction shouldCompute(derivation) {\n switch (derivation.dependenciesState_) {\n case IDerivationState_.UP_TO_DATE_:\n return false;\n\n case IDerivationState_.NOT_TRACKING_:\n case IDerivationState_.STALE_:\n return true;\n\n case IDerivationState_.POSSIBLY_STALE_:\n {\n // state propagation can occur outside of action/reactive context #2195\n var prevAllowStateReads = allowStateReadsStart(true);\n var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.\n\n var obs = derivation.observing_,\n l = obs.length;\n\n for (var i = 0; i < l; i++) {\n var obj = obs[i];\n\n if (isComputedValue(obj)) {\n if (globalState.disableErrorBoundaries) {\n obj.get();\n } else {\n try {\n obj.get();\n } catch (e) {\n // we are not interested in the value *or* exception at this moment, but if there is one, notify all\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.\n // and `derivation` is an observer of `obj`\n // invariantShouldCompute(derivation)\n\n\n if (derivation.dependenciesState_ === IDerivationState_.STALE_) {\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n }\n\n changeDependenciesStateTo0(derivation);\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return false;\n }\n }\n}\nfunction isComputingDerivation() {\n return globalState.trackingDerivation !== null; // filter out actions inside computations\n}\nfunction checkIfStateModificationsAreAllowed(atom) {\n if (false) {}\n\n var hasObservers = atom.observers_.size > 0; // Should not be possible to change observed state outside strict mode, except during initialization, see #563\n\n if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === \"always\")) {\n console.warn(\"[MobX] \" + (globalState.enforceActions ? \"Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: \" : \"Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: \") + atom.name_);\n }\n}\nfunction checkIfStateReadsAreAllowed(observable) {\n if ( true && !globalState.allowStateReads && globalState.observableRequiresReaction) {\n console.warn(\"[mobx] Observable '\" + observable.name_ + \"' being read outside a reactive context.\");\n }\n}\n/**\r\n * Executes the provided function `f` and tracks which observables are being accessed.\r\n * The tracking information is stored on the `derivation` object and the derivation is registered\r\n * as observer of any of the accessed observables.\r\n */\n\nfunction trackDerivedFunction(derivation, f, context) {\n var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps\n // array will be trimmed by bindDependencies\n\n changeDependenciesStateTo0(derivation);\n derivation.newObserving_ = new Array(derivation.observing_.length + 100);\n derivation.unboundDepsCount_ = 0;\n derivation.runId_ = ++globalState.runId;\n var prevTracking = globalState.trackingDerivation;\n globalState.trackingDerivation = derivation;\n globalState.inBatch++;\n var result;\n\n if (globalState.disableErrorBoundaries === true) {\n result = f.call(context);\n } else {\n try {\n result = f.call(context);\n } catch (e) {\n result = new CaughtException(e);\n }\n }\n\n globalState.inBatch--;\n globalState.trackingDerivation = prevTracking;\n bindDependencies(derivation);\n warnAboutDerivationWithoutDependencies(derivation);\n allowStateReadsEnd(prevAllowStateReads);\n return result;\n}\n\nfunction warnAboutDerivationWithoutDependencies(derivation) {\n if (false) {}\n\n if (derivation.observing_.length !== 0) {\n return;\n }\n\n if (typeof derivation.requiresObservable_ === \"boolean\" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {\n console.warn(\"[mobx] Derivation '\" + derivation.name_ + \"' is created/updated without reading any observable value.\");\n }\n}\n/**\r\n * diffs newObserving with observing.\r\n * update observing to be newObserving with unique observables\r\n * notify observers that become observed/unobserved\r\n */\n\n\nfunction bindDependencies(derivation) {\n // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, \"INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1\");\n var prevObserving = derivation.observing_;\n var observing = derivation.observing_ = derivation.newObserving_;\n var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; // Go through all new observables and check diffValue: (this list can contain duplicates):\n // 0: first occurrence, change to 1 and keep it\n // 1: extra occurrence, drop it\n\n var i0 = 0,\n l = derivation.unboundDepsCount_;\n\n for (var i = 0; i < l; i++) {\n var dep = observing[i];\n\n if (dep.diffValue_ === 0) {\n dep.diffValue_ = 1;\n\n if (i0 !== i) {\n observing[i0] = dep;\n }\n\n i0++;\n } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,\n // not hitting the condition\n\n\n if (dep.dependenciesState_ > lowestNewObservingDerivationState) {\n lowestNewObservingDerivationState = dep.dependenciesState_;\n }\n }\n\n observing.length = i0;\n derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)\n // Go through all old observables and check diffValue: (it is unique after last bindDependencies)\n // 0: it's not in new observables, unobserve it\n // 1: it keeps being observed, don't want to notify it. change to 0\n\n l = prevObserving.length;\n\n while (l--) {\n var _dep = prevObserving[l];\n\n if (_dep.diffValue_ === 0) {\n removeObserver(_dep, derivation);\n }\n\n _dep.diffValue_ = 0;\n } // Go through all new observables and check diffValue: (now it should be unique)\n // 0: it was set to 0 in last loop. don't need to do anything.\n // 1: it wasn't observed, let's observe it. set back to 0\n\n\n while (i0--) {\n var _dep2 = observing[i0];\n\n if (_dep2.diffValue_ === 1) {\n _dep2.diffValue_ = 0;\n addObserver(_dep2, derivation);\n }\n } // Some new observed derivations may become stale during this derivation computation\n // so they have had no chance to propagate staleness (#916)\n\n\n if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {\n derivation.dependenciesState_ = lowestNewObservingDerivationState;\n derivation.onBecomeStale_();\n }\n}\n\nfunction clearObserving(derivation) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR clearObserving should be called only inside batch\");\n var obs = derivation.observing_;\n derivation.observing_ = [];\n var i = obs.length;\n\n while (i--) {\n removeObserver(obs[i], derivation);\n }\n\n derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n}\nfunction untracked(action) {\n var prev = untrackedStart();\n\n try {\n return action();\n } finally {\n untrackedEnd(prev);\n }\n}\nfunction untrackedStart() {\n var prev = globalState.trackingDerivation;\n globalState.trackingDerivation = null;\n return prev;\n}\nfunction untrackedEnd(prev) {\n globalState.trackingDerivation = prev;\n}\nfunction allowStateReadsStart(allowStateReads) {\n var prev = globalState.allowStateReads;\n globalState.allowStateReads = allowStateReads;\n return prev;\n}\nfunction allowStateReadsEnd(prev) {\n globalState.allowStateReads = prev;\n}\n/**\r\n * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0\r\n *\r\n */\n\nfunction changeDependenciesStateTo0(derivation) {\n if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;\n var obs = derivation.observing_;\n var i = obs.length;\n\n while (i--) {\n obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n}\n\n/**\r\n * These values will persist if global state is reset\r\n */\n\nvar persistentKeys = [\"mobxGuid\", \"spyListeners\", \"enforceActions\", \"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"allowStateReads\", \"disableErrorBoundaries\", \"runId\", \"UNCHANGED\", \"useProxies\"];\nvar MobXGlobals = function MobXGlobals() {\n this.version = 6;\n this.UNCHANGED = {};\n this.trackingDerivation = null;\n this.trackingContext = null;\n this.runId = 0;\n this.mobxGuid = 0;\n this.inBatch = 0;\n this.pendingUnobservations = [];\n this.pendingReactions = [];\n this.isRunningReactions = false;\n this.allowStateChanges = false;\n this.allowStateReads = true;\n this.enforceActions = true;\n this.spyListeners = [];\n this.globalReactionErrorHandlers = [];\n this.computedRequiresReaction = false;\n this.reactionRequiresObservable = false;\n this.observableRequiresReaction = false;\n this.disableErrorBoundaries = false;\n this.suppressReactionErrors = false;\n this.useProxies = true;\n this.verifyProxies = false;\n this.safeDescriptors = true;\n};\nvar canMergeGlobalState = true;\nvar isolateCalled = false;\nvar globalState = /*#__PURE__*/function () {\n var global = /*#__PURE__*/getGlobal();\n\n if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {\n canMergeGlobalState = false;\n }\n\n if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {\n canMergeGlobalState = false;\n }\n\n if (!canMergeGlobalState) {\n // Because this is a IIFE we need to let isolateCalled a chance to change\n // so we run it after the event loop completed at least 1 iteration\n setTimeout(function () {\n if (!isolateCalled) {\n die(35);\n }\n }, 1);\n return new MobXGlobals();\n } else if (global.__mobxGlobals) {\n global.__mobxInstanceCount += 1;\n\n if (!global.__mobxGlobals.UNCHANGED) {\n global.__mobxGlobals.UNCHANGED = {};\n } // make merge backward compatible\n\n\n return global.__mobxGlobals;\n } else {\n global.__mobxInstanceCount = 1;\n return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();\n }\n}();\nfunction isolateGlobalState() {\n if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {\n die(36);\n }\n\n isolateCalled = true;\n\n if (canMergeGlobalState) {\n var global = getGlobal();\n\n if (--global.__mobxInstanceCount === 0) {\n global.__mobxGlobals = undefined;\n }\n\n globalState = new MobXGlobals();\n }\n}\nfunction getGlobalState() {\n return globalState;\n}\n/**\r\n * For testing purposes only; this will break the internal state of existing observables,\r\n * but can be used to get back at a stable state after throwing errors\r\n */\n\nfunction resetGlobalState() {\n var defaultGlobals = new MobXGlobals();\n\n for (var key in defaultGlobals) {\n if (persistentKeys.indexOf(key) === -1) {\n globalState[key] = defaultGlobals[key];\n }\n }\n\n globalState.allowStateChanges = !globalState.enforceActions;\n}\n\nfunction hasObservers(observable) {\n return observable.observers_ && observable.observers_.size > 0;\n}\nfunction getObservers(observable) {\n return observable.observers_;\n} // function invariantObservers(observable: IObservable) {\n// const list = observable.observers\n// const map = observable.observersIndexes\n// const l = list.length\n// for (let i = 0; i < l; i++) {\n// const id = list[i].__mapid\n// if (i) {\n// invariant(map[id] === i, \"INTERNAL ERROR maps derivation.__mapid to index in list\") // for performance\n// } else {\n// invariant(!(id in map), \"INTERNAL ERROR observer on index 0 shouldn't be held in map.\") // for performance\n// }\n// }\n// invariant(\n// list.length === 0 || Object.keys(map).length === list.length - 1,\n// \"INTERNAL ERROR there is no junk in map\"\n// )\n// }\n\nfunction addObserver(observable, node) {\n // invariant(node.dependenciesState !== -1, \"INTERNAL ERROR, can add only dependenciesState !== -1\");\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR add already added node\");\n // invariantObservers(observable);\n observable.observers_.add(node);\n\n if (observable.lowestObserverState_ > node.dependenciesState_) {\n observable.lowestObserverState_ = node.dependenciesState_;\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR didn't add node\");\n\n}\nfunction removeObserver(observable, node) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR, remove should be called only inside batch\");\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR remove already removed node\");\n // invariantObservers(observable);\n observable.observers_[\"delete\"](node);\n\n if (observable.observers_.size === 0) {\n // deleting last observer\n queueForUnobservation(observable);\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR remove already removed node2\");\n\n}\nfunction queueForUnobservation(observable) {\n if (observable.isPendingUnobservation_ === false) {\n // invariant(observable._observers.length === 0, \"INTERNAL ERROR, should only queue for unobservation unobserved observables\");\n observable.isPendingUnobservation_ = true;\n globalState.pendingUnobservations.push(observable);\n }\n}\n/**\r\n * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.\r\n * During a batch `onBecomeUnobserved` will be called at most once per observable.\r\n * Avoids unnecessary recalculations.\r\n */\n\nfunction startBatch() {\n globalState.inBatch++;\n}\nfunction endBatch() {\n if (--globalState.inBatch === 0) {\n runReactions(); // the batch is actually about to finish, all unobserving should happen here.\n\n var list = globalState.pendingUnobservations;\n\n for (var i = 0; i < list.length; i++) {\n var observable = list[i];\n observable.isPendingUnobservation_ = false;\n\n if (observable.observers_.size === 0) {\n if (observable.isBeingObserved_) {\n // if this observable had reactive observers, trigger the hooks\n observable.isBeingObserved_ = false;\n observable.onBUO();\n }\n\n if (observable instanceof ComputedValue) {\n // computed values are automatically teared down when the last observer leaves\n // this process happens recursively, this computed might be the last observabe of another, etc..\n observable.suspend_();\n }\n }\n }\n\n globalState.pendingUnobservations = [];\n }\n}\nfunction reportObserved(observable) {\n checkIfStateReadsAreAllowed(observable);\n var derivation = globalState.trackingDerivation;\n\n if (derivation !== null) {\n /**\r\n * Simple optimization, give each derivation run an unique id (runId)\r\n * Check if last time this observable was accessed the same runId is used\r\n * if this is the case, the relation is already known\r\n */\n if (derivation.runId_ !== observable.lastAccessedBy_) {\n observable.lastAccessedBy_ = derivation.runId_; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...\n\n derivation.newObserving_[derivation.unboundDepsCount_++] = observable;\n\n if (!observable.isBeingObserved_ && globalState.trackingContext) {\n observable.isBeingObserved_ = true;\n observable.onBO();\n }\n }\n\n return observable.isBeingObserved_;\n } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {\n queueForUnobservation(observable);\n }\n\n return false;\n} // function invariantLOS(observable: IObservable, msg: string) {\n// // it's expensive so better not run it in produciton. but temporarily helpful for testing\n// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)\n// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`\n// throw new Error(\n// \"lowestObserverState is wrong for \" +\n// msg +\n// \" because \" +\n// min +\n// \" < \" +\n// observable.lowestObserverState\n// )\n// }\n\n/**\r\n * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly\r\n * It will propagate changes to observers from previous run\r\n * It's hard or maybe impossible (with reasonable perf) to get it right with current approach\r\n * Hopefully self reruning autoruns aren't a feature people should depend on\r\n * Also most basic use cases should be ok\r\n */\n// Called by Atom when its value changes\n\nfunction propagateChanged(observable) {\n // invariantLOS(observable, \"changed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_; // Ideally we use for..of here, but the downcompiled version is really slow...\n\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n\n d.onBecomeStale_();\n }\n\n d.dependenciesState_ = IDerivationState_.STALE_;\n }); // invariantLOS(observable, \"changed end\");\n} // Called by ComputedValue when it recalculate and its value changed\n\nfunction propagateChangeConfirmed(observable) {\n // invariantLOS(observable, \"confirmed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {\n d.dependenciesState_ = IDerivationState_.STALE_;\n\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.\n ) {\n observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n }); // invariantLOS(observable, \"confirmed end\");\n} // Used by computed when its dependency changed, but we don't wan't to immediately recompute.\n\nfunction propagateMaybeChanged(observable) {\n // invariantLOS(observable, \"maybe start\");\n if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;\n d.onBecomeStale_();\n }\n }); // invariantLOS(observable, \"maybe end\");\n}\n\nfunction logTraceInfo(derivation, observable) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' is invalidated due to a change in: '\" + observable.name_ + \"'\");\n\n if (derivation.isTracing_ === TraceMode.BREAK) {\n var lines = [];\n printDepTree(getDependencyTree(derivation), lines, 1); // prettier-ignore\n\n new Function(\"debugger;\\n/*\\nTracing '\" + derivation.name_ + \"'\\n\\nYou are entering this break point because derivation '\" + derivation.name_ + \"' is being traced and '\" + observable.name_ + \"' is now forcing it to update.\\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\\n\\n\" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\\//g, \"/\") : \"\") + \"\\n\\nThe dependencies for this derivation are:\\n\\n\" + lines.join(\"\\n\") + \"\\n*/\\n \")();\n }\n}\n\nfunction printDepTree(tree, lines, depth) {\n if (lines.length >= 1000) {\n lines.push(\"(and many more)\");\n return;\n }\n\n lines.push(\"\" + \"\\t\".repeat(depth - 1) + tree.name);\n\n if (tree.dependencies) {\n tree.dependencies.forEach(function (child) {\n return printDepTree(child, lines, depth + 1);\n });\n }\n}\n\nvar Reaction = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {\n if (name_ === void 0) {\n name_ = true ? \"Reaction@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.onInvalidate_ = void 0;\n this.errorHandler_ = void 0;\n this.requiresObservable_ = void 0;\n this.observing_ = [];\n this.newObserving_ = [];\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.unboundDepsCount_ = 0;\n this.isDisposed_ = false;\n this.isScheduled_ = false;\n this.isTrackPending_ = false;\n this.isRunning_ = false;\n this.isTracing_ = TraceMode.NONE;\n this.name_ = name_;\n this.onInvalidate_ = onInvalidate_;\n this.errorHandler_ = errorHandler_;\n this.requiresObservable_ = requiresObservable_;\n }\n\n var _proto = Reaction.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n this.schedule_();\n };\n\n _proto.schedule_ = function schedule_() {\n if (!this.isScheduled_) {\n this.isScheduled_ = true;\n globalState.pendingReactions.push(this);\n runReactions();\n }\n };\n\n _proto.isScheduled = function isScheduled() {\n return this.isScheduled_;\n }\n /**\r\n * internal, use schedule() if you intend to kick off a reaction\r\n */\n ;\n\n _proto.runReaction_ = function runReaction_() {\n if (!this.isDisposed_) {\n startBatch();\n this.isScheduled_ = false;\n var prev = globalState.trackingContext;\n globalState.trackingContext = this;\n\n if (shouldCompute(this)) {\n this.isTrackPending_ = true;\n\n try {\n this.onInvalidate_();\n\n if ( true && this.isTrackPending_ && isSpyEnabled()) {\n // onInvalidate didn't trigger track right away..\n spyReport({\n name: this.name_,\n type: \"scheduled-reaction\"\n });\n }\n } catch (e) {\n this.reportExceptionInDerivation_(e);\n }\n }\n\n globalState.trackingContext = prev;\n endBatch();\n }\n };\n\n _proto.track = function track(fn) {\n if (this.isDisposed_) {\n return; // console.warn(\"Reaction already disposed\") // Note: Not a warning / error in mobx 4 either\n }\n\n startBatch();\n var notify = isSpyEnabled();\n var startTime;\n\n if ( true && notify) {\n startTime = Date.now();\n spyReportStart({\n name: this.name_,\n type: \"reaction\"\n });\n }\n\n this.isRunning_ = true;\n var prevReaction = globalState.trackingContext; // reactions could create reactions...\n\n globalState.trackingContext = this;\n var result = trackDerivedFunction(this, fn, undefined);\n globalState.trackingContext = prevReaction;\n this.isRunning_ = false;\n this.isTrackPending_ = false;\n\n if (this.isDisposed_) {\n // disposed during last run. Clean up everything that was bound after the dispose call.\n clearObserving(this);\n }\n\n if (isCaughtException(result)) {\n this.reportExceptionInDerivation_(result.cause);\n }\n\n if ( true && notify) {\n spyReportEnd({\n time: Date.now() - startTime\n });\n }\n\n endBatch();\n };\n\n _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {\n var _this = this;\n\n if (this.errorHandler_) {\n this.errorHandler_(error, this);\n return;\n }\n\n if (globalState.disableErrorBoundaries) {\n throw error;\n }\n\n var message = true ? \"[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '\" + this + \"'\" : undefined;\n\n if (!globalState.suppressReactionErrors) {\n console.error(message, error);\n /** If debugging brought you here, please, read the above message :-). Tnx! */\n } else if (true) {\n console.warn(\"[mobx] (error in reaction '\" + this.name_ + \"' suppressed, fix error of causing action below)\");\n } // prettier-ignore\n\n\n if ( true && isSpyEnabled()) {\n spyReport({\n type: \"error\",\n name: this.name_,\n message: message,\n error: \"\" + error\n });\n }\n\n globalState.globalReactionErrorHandlers.forEach(function (f) {\n return f(error, _this);\n });\n };\n\n _proto.dispose = function dispose() {\n if (!this.isDisposed_) {\n this.isDisposed_ = true;\n\n if (!this.isRunning_) {\n // if disposed while running, clean up later. Maybe not optimal, but rare case\n startBatch();\n clearObserving(this);\n endBatch();\n }\n }\n };\n\n _proto.getDisposer_ = function getDisposer_() {\n var r = this.dispose.bind(this);\n r[$mobx] = this;\n return r;\n };\n\n _proto.toString = function toString() {\n return \"Reaction[\" + this.name_ + \"]\";\n };\n\n _proto.trace = function trace$1(enterBreakPoint) {\n if (enterBreakPoint === void 0) {\n enterBreakPoint = false;\n }\n\n trace(this, enterBreakPoint);\n };\n\n return Reaction;\n}();\nfunction onReactionError(handler) {\n globalState.globalReactionErrorHandlers.push(handler);\n return function () {\n var idx = globalState.globalReactionErrorHandlers.indexOf(handler);\n\n if (idx >= 0) {\n globalState.globalReactionErrorHandlers.splice(idx, 1);\n }\n };\n}\n/**\r\n * Magic number alert!\r\n * Defines within how many times a reaction is allowed to re-trigger itself\r\n * until it is assumed that this is gonna be a never ending loop...\r\n */\n\nvar MAX_REACTION_ITERATIONS = 100;\n\nvar reactionScheduler = function reactionScheduler(f) {\n return f();\n};\n\nfunction runReactions() {\n // Trampolining, if runReactions are already running, new reactions will be picked up\n if (globalState.inBatch > 0 || globalState.isRunningReactions) {\n return;\n }\n\n reactionScheduler(runReactionsHelper);\n}\n\nfunction runReactionsHelper() {\n globalState.isRunningReactions = true;\n var allReactions = globalState.pendingReactions;\n var iterations = 0; // While running reactions, new reactions might be triggered.\n // Hence we work with two variables and check whether\n // we converge to no remaining reactions after a while.\n\n while (allReactions.length > 0) {\n if (++iterations === MAX_REACTION_ITERATIONS) {\n console.error( true ? \"Reaction doesn't converge to a stable state after \" + MAX_REACTION_ITERATIONS + \" iterations.\" + (\" Probably there is a cycle in the reactive function: \" + allReactions[0]) : undefined);\n allReactions.splice(0); // clear reactions\n }\n\n var remainingReactions = allReactions.splice(0);\n\n for (var i = 0, l = remainingReactions.length; i < l; i++) {\n remainingReactions[i].runReaction_();\n }\n }\n\n globalState.isRunningReactions = false;\n}\n\nvar isReaction = /*#__PURE__*/createInstanceofPredicate(\"Reaction\", Reaction);\nfunction setReactionScheduler(fn) {\n var baseScheduler = reactionScheduler;\n\n reactionScheduler = function reactionScheduler(f) {\n return fn(function () {\n return baseScheduler(f);\n });\n };\n}\n\nfunction isSpyEnabled() {\n return true && !!globalState.spyListeners.length;\n}\nfunction spyReport(event) {\n if (false) {} // dead code elimination can do the rest\n\n\n if (!globalState.spyListeners.length) {\n return;\n }\n\n var listeners = globalState.spyListeners;\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](event);\n }\n}\nfunction spyReportStart(event) {\n if (false) {}\n\n var change = _extends({}, event, {\n spyReportStart: true\n });\n\n spyReport(change);\n}\nvar END_EVENT = {\n type: \"report-end\",\n spyReportEnd: true\n};\nfunction spyReportEnd(change) {\n if (false) {}\n\n if (change) {\n spyReport(_extends({}, change, {\n type: \"report-end\",\n spyReportEnd: true\n }));\n } else {\n spyReport(END_EVENT);\n }\n}\nfunction spy(listener) {\n if (false) {} else {\n globalState.spyListeners.push(listener);\n return once(function () {\n globalState.spyListeners = globalState.spyListeners.filter(function (l) {\n return l !== listener;\n });\n });\n }\n}\n\nvar ACTION = \"action\";\nvar ACTION_BOUND = \"action.bound\";\nvar AUTOACTION = \"autoAction\";\nvar AUTOACTION_BOUND = \"autoAction.bound\";\nvar DEFAULT_ACTION_NAME = \"\";\nvar actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);\nvar actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {\n bound: true\n});\nvar autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {\n autoAction: true\n});\nvar autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {\n autoAction: true,\n bound: true\n});\n\nfunction createActionFactory(autoAction) {\n var res = function action(arg1, arg2) {\n // action(fn() {})\n if (isFunction(arg1)) {\n return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);\n } // action(\"name\", fn() {})\n\n\n if (isFunction(arg2)) {\n return createAction(arg1, arg2, autoAction);\n } // @action\n\n\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);\n } // action(\"name\") & @action(\"name\")\n\n\n if (isStringish(arg1)) {\n return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {\n name: arg1,\n autoAction: autoAction\n }));\n }\n\n if (true) {\n die(\"Invalid arguments for `action`\");\n }\n };\n\n return res;\n}\n\nvar action = /*#__PURE__*/createActionFactory(false);\nObject.assign(action, actionAnnotation);\nvar autoAction = /*#__PURE__*/createActionFactory(true);\nObject.assign(autoAction, autoActionAnnotation);\naction.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);\nautoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);\nfunction runInAction(fn) {\n return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);\n}\nfunction isAction(thing) {\n return isFunction(thing) && thing.isMobxAction === true;\n}\n\n/**\r\n * Creates a named reactive view and keeps it alive, so that the view is always\r\n * updated if one of the dependencies changes, even when the view is not further used by something else.\r\n * @param view The reactive view\r\n * @returns disposer function, which can be used to stop the view from being updated in the future.\r\n */\n\nfunction autorun(view, opts) {\n var _opts$name, _opts;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(view)) {\n die(\"Autorun expects a function as first argument\");\n }\n\n if (isAction(view)) {\n die(\"Autorun does not accept actions since actions are untrackable\");\n }\n }\n\n var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : true ? view.name || \"Autorun@\" + getNextId() : undefined;\n var runSync = !opts.scheduler && !opts.delay;\n var reaction;\n\n if (runSync) {\n // normal autorun\n reaction = new Reaction(name, function () {\n this.track(reactionRunner);\n }, opts.onError, opts.requiresObservable);\n } else {\n var scheduler = createSchedulerFromOptions(opts); // debounced autorun\n\n var isScheduled = false;\n reaction = new Reaction(name, function () {\n if (!isScheduled) {\n isScheduled = true;\n scheduler(function () {\n isScheduled = false;\n\n if (!reaction.isDisposed_) {\n reaction.track(reactionRunner);\n }\n });\n }\n }, opts.onError, opts.requiresObservable);\n }\n\n function reactionRunner() {\n view(reaction);\n }\n\n reaction.schedule_();\n return reaction.getDisposer_();\n}\n\nvar run = function run(f) {\n return f();\n};\n\nfunction createSchedulerFromOptions(opts) {\n return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {\n return setTimeout(f, opts.delay);\n } : run;\n}\n\nfunction reaction(expression, effect, opts) {\n var _opts$name2;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(expression) || !isFunction(effect)) {\n die(\"First and second argument to reaction should be functions\");\n }\n\n if (!isPlainObject(opts)) {\n die(\"Third argument of reactions should be an object\");\n }\n }\n\n var name = (_opts$name2 = opts.name) != null ? _opts$name2 : true ? \"Reaction@\" + getNextId() : undefined;\n var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);\n var runSync = !opts.scheduler && !opts.delay;\n var scheduler = createSchedulerFromOptions(opts);\n var firstTime = true;\n var isScheduled = false;\n var value;\n var oldValue;\n var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer[\"default\"];\n var r = new Reaction(name, function () {\n if (firstTime || runSync) {\n reactionRunner();\n } else if (!isScheduled) {\n isScheduled = true;\n scheduler(reactionRunner);\n }\n }, opts.onError, opts.requiresObservable);\n\n function reactionRunner() {\n isScheduled = false;\n\n if (r.isDisposed_) {\n return;\n }\n\n var changed = false;\n r.track(function () {\n var nextValue = allowStateChanges(false, function () {\n return expression(r);\n });\n changed = firstTime || !equals(value, nextValue);\n oldValue = value;\n value = nextValue;\n });\n\n if (firstTime && opts.fireImmediately) {\n effectAction(value, oldValue, r);\n } else if (!firstTime && changed) {\n effectAction(value, oldValue, r);\n }\n\n firstTime = false;\n }\n\n r.schedule_();\n return r.getDisposer_();\n}\n\nfunction wrapErrorHandler(errorHandler, baseFn) {\n return function () {\n try {\n return baseFn.apply(this, arguments);\n } catch (e) {\n errorHandler.call(this, e);\n }\n };\n}\n\nvar ON_BECOME_OBSERVED = \"onBO\";\nvar ON_BECOME_UNOBSERVED = \"onBUO\";\nfunction onBecomeObserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);\n}\nfunction onBecomeUnobserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);\n}\n\nfunction interceptHook(hook, thing, arg2, arg3) {\n var atom = typeof arg3 === \"function\" ? getAtom(thing, arg2) : getAtom(thing);\n var cb = isFunction(arg3) ? arg3 : arg2;\n var listenersKey = hook + \"L\";\n\n if (atom[listenersKey]) {\n atom[listenersKey].add(cb);\n } else {\n atom[listenersKey] = new Set([cb]);\n }\n\n return function () {\n var hookListeners = atom[listenersKey];\n\n if (hookListeners) {\n hookListeners[\"delete\"](cb);\n\n if (hookListeners.size === 0) {\n delete atom[listenersKey];\n }\n }\n };\n}\n\nvar NEVER = \"never\";\nvar ALWAYS = \"always\";\nvar OBSERVED = \"observed\"; // const IF_AVAILABLE = \"ifavailable\"\n\nfunction configure(options) {\n if (options.isolateGlobalState === true) {\n isolateGlobalState();\n }\n\n var useProxies = options.useProxies,\n enforceActions = options.enforceActions;\n\n if (useProxies !== undefined) {\n globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== \"undefined\";\n }\n\n if (useProxies === \"ifavailable\") {\n globalState.verifyProxies = true;\n }\n\n if (enforceActions !== undefined) {\n var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;\n globalState.enforceActions = ea;\n globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;\n }\n [\"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"disableErrorBoundaries\", \"safeDescriptors\"].forEach(function (key) {\n if (key in options) {\n globalState[key] = !!options[key];\n }\n });\n globalState.allowStateReads = !globalState.observableRequiresReaction;\n\n if ( true && globalState.disableErrorBoundaries === true) {\n console.warn(\"WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.\");\n }\n\n if (options.reactionScheduler) {\n setReactionScheduler(options.reactionScheduler);\n }\n}\n\nfunction extendObservable(target, properties, annotations, options) {\n if (true) {\n if (arguments.length > 4) {\n die(\"'extendObservable' expected 2-4 arguments\");\n }\n\n if (typeof target !== \"object\") {\n die(\"'extendObservable' expects an object as first argument\");\n }\n\n if (isObservableMap(target)) {\n die(\"'extendObservable' should not be used on maps, use map.merge instead\");\n }\n\n if (!isPlainObject(properties)) {\n die(\"'extendObservable' only accepts plain objects as second argument\");\n }\n\n if (isObservable(properties) || isObservable(annotations)) {\n die(\"Extending an object with another observable (object) is not supported\");\n }\n } // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)\n\n\n var descriptors = getOwnPropertyDescriptors(properties);\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n ownKeys(descriptors).forEach(function (key) {\n adm.extend_(key, descriptors[key], // must pass \"undefined\" for { key: undefined }\n !annotations ? true : key in annotations ? annotations[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nfunction getDependencyTree(thing, property) {\n return nodeToDependencyTree(getAtom(thing, property));\n}\n\nfunction nodeToDependencyTree(node) {\n var result = {\n name: node.name_\n };\n\n if (node.observing_ && node.observing_.length > 0) {\n result.dependencies = unique(node.observing_).map(nodeToDependencyTree);\n }\n\n return result;\n}\n\nfunction getObserverTree(thing, property) {\n return nodeToObserverTree(getAtom(thing, property));\n}\n\nfunction nodeToObserverTree(node) {\n var result = {\n name: node.name_\n };\n\n if (hasObservers(node)) {\n result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);\n }\n\n return result;\n}\n\nfunction unique(list) {\n return Array.from(new Set(list));\n}\n\nvar generatorId = 0;\nfunction FlowCancellationError() {\n this.message = \"FLOW_CANCELLED\";\n}\nFlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);\nfunction isFlowCancellationError(error) {\n return error instanceof FlowCancellationError;\n}\nvar flowAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow\");\nvar flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow.bound\", {\n bound: true\n});\nvar flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {\n // @flow\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, flowAnnotation);\n } // flow(fn)\n\n\n if ( true && arguments.length !== 1) {\n die(\"Flow expects single argument with generator function\");\n }\n\n var generator = arg1;\n var name = generator.name || \"\"; // Implementation based on https://github.com/tj/co/blob/master/index.js\n\n var res = function res() {\n var ctx = this;\n var args = arguments;\n var runId = ++generatorId;\n var gen = action(name + \" - runid: \" + runId + \" - init\", generator).apply(ctx, args);\n var rejector;\n var pendingPromise = undefined;\n var promise = new Promise(function (resolve, reject) {\n var stepId = 0;\n rejector = reject;\n\n function onFulfilled(res) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen.next).call(gen, res);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function onRejected(err) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen[\"throw\"]).call(gen, err);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function next(ret) {\n if (isFunction(ret == null ? void 0 : ret.then)) {\n // an async iterator\n ret.then(next, reject);\n return;\n }\n\n if (ret.done) {\n return resolve(ret.value);\n }\n\n pendingPromise = Promise.resolve(ret.value);\n return pendingPromise.then(onFulfilled, onRejected);\n }\n\n onFulfilled(undefined); // kick off the process\n });\n promise.cancel = action(name + \" - runid: \" + runId + \" - cancel\", function () {\n try {\n if (pendingPromise) {\n cancelPromise(pendingPromise);\n } // Finally block can return (or yield) stuff..\n\n\n var _res = gen[\"return\"](undefined); // eat anything that promise would do, it's cancelled!\n\n\n var yieldedPromise = Promise.resolve(_res.value);\n yieldedPromise.then(noop, noop);\n cancelPromise(yieldedPromise); // maybe it can be cancelled :)\n // reject our original promise\n\n rejector(new FlowCancellationError());\n } catch (e) {\n rejector(e); // there could be a throwing finally block\n }\n });\n return promise;\n };\n\n res.isMobXFlow = true;\n return res;\n}, flowAnnotation);\nflow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);\n\nfunction cancelPromise(promise) {\n if (isFunction(promise.cancel)) {\n promise.cancel();\n }\n}\n\nfunction flowResult(result) {\n return result; // just tricking TypeScript :)\n}\nfunction isFlow(fn) {\n return (fn == null ? void 0 : fn.isMobXFlow) === true;\n}\n\nfunction interceptReads(thing, propOrHandler, handler) {\n var target;\n\n if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {\n target = getAdministration(thing);\n } else if (isObservableObject(thing)) {\n if ( true && !isStringish(propOrHandler)) {\n return die(\"InterceptReads can only be used with a specific property, not with an object in general\");\n }\n\n target = getAdministration(thing, propOrHandler);\n } else if (true) {\n return die(\"Expected observable map, object or array as first array\");\n }\n\n if ( true && target.dehancer !== undefined) {\n return die(\"An intercept reader was already established\");\n }\n\n target.dehancer = typeof propOrHandler === \"function\" ? propOrHandler : handler;\n return function () {\n target.dehancer = undefined;\n };\n}\n\nfunction intercept(thing, propOrHandler, handler) {\n if (isFunction(handler)) {\n return interceptProperty(thing, propOrHandler, handler);\n } else {\n return interceptInterceptable(thing, propOrHandler);\n }\n}\n\nfunction interceptInterceptable(thing, handler) {\n return getAdministration(thing).intercept_(handler);\n}\n\nfunction interceptProperty(thing, property, handler) {\n return getAdministration(thing, property).intercept_(handler);\n}\n\nfunction _isComputed(value, property) {\n if (property === undefined) {\n return isComputedValue(value);\n }\n\n if (isObservableObject(value) === false) {\n return false;\n }\n\n if (!value[$mobx].values_.has(property)) {\n return false;\n }\n\n var atom = getAtom(value, property);\n return isComputedValue(atom);\n}\nfunction isComputed(value) {\n if ( true && arguments.length > 1) {\n return die(\"isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property\");\n }\n\n return _isComputed(value);\n}\nfunction isComputedProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"isComputed expected a property name as second argument\");\n }\n\n return _isComputed(value, propName);\n}\n\nfunction _isObservable(value, property) {\n if (!value) {\n return false;\n }\n\n if (property !== undefined) {\n if ( true && (isObservableMap(value) || isObservableArray(value))) {\n return die(\"isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.\");\n }\n\n if (isObservableObject(value)) {\n return value[$mobx].values_.has(property);\n }\n\n return false;\n } // For first check, see #701\n\n\n return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);\n}\n\nfunction isObservable(value) {\n if ( true && arguments.length !== 1) {\n die(\"isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property\");\n }\n\n return _isObservable(value);\n}\nfunction isObservableProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"expected a property name as second argument\");\n }\n\n return _isObservable(value, propName);\n}\n\nfunction keys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].keys_();\n }\n\n if (isObservableMap(obj) || isObservableSet(obj)) {\n return Array.from(obj.keys());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (_, index) {\n return index;\n });\n }\n\n die(5);\n}\nfunction values(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return obj[key];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return obj.get(key);\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.values());\n }\n\n if (isObservableArray(obj)) {\n return obj.slice();\n }\n\n die(6);\n}\nfunction entries(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj.get(key)];\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.entries());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (key, index) {\n return [index, key];\n });\n }\n\n die(7);\n}\nfunction set(obj, key, value) {\n if (arguments.length === 2 && !isObservableSet(obj)) {\n startBatch();\n var _values = key;\n\n try {\n for (var _key in _values) {\n set(obj, _key, _values[_key]);\n }\n } finally {\n endBatch();\n }\n\n return;\n }\n\n if (isObservableObject(obj)) {\n obj[$mobx].set_(key, value);\n } else if (isObservableMap(obj)) {\n obj.set(key, value);\n } else if (isObservableSet(obj)) {\n obj.add(key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n if (key < 0) {\n die(\"Invalid index: '\" + key + \"'\");\n }\n\n startBatch();\n\n if (key >= obj.length) {\n obj.length = key + 1;\n }\n\n obj[key] = value;\n endBatch();\n } else {\n die(8);\n }\n}\nfunction remove(obj, key) {\n if (isObservableObject(obj)) {\n obj[$mobx].delete_(key);\n } else if (isObservableMap(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableSet(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n obj.splice(key, 1);\n } else {\n die(9);\n }\n}\nfunction has(obj, key) {\n if (isObservableObject(obj)) {\n return obj[$mobx].has_(key);\n } else if (isObservableMap(obj)) {\n return obj.has(key);\n } else if (isObservableSet(obj)) {\n return obj.has(key);\n } else if (isObservableArray(obj)) {\n return key >= 0 && key < obj.length;\n }\n\n die(10);\n}\nfunction get(obj, key) {\n if (!has(obj, key)) {\n return undefined;\n }\n\n if (isObservableObject(obj)) {\n return obj[$mobx].get_(key);\n } else if (isObservableMap(obj)) {\n return obj.get(key);\n } else if (isObservableArray(obj)) {\n return obj[key];\n }\n\n die(11);\n}\nfunction apiDefineProperty(obj, key, descriptor) {\n if (isObservableObject(obj)) {\n return obj[$mobx].defineProperty_(key, descriptor);\n }\n\n die(39);\n}\nfunction apiOwnKeys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].ownKeys_();\n }\n\n die(38);\n}\n\nfunction observe(thing, propOrCb, cbOrFire, fireImmediately) {\n if (isFunction(cbOrFire)) {\n return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);\n } else {\n return observeObservable(thing, propOrCb, cbOrFire);\n }\n}\n\nfunction observeObservable(thing, listener, fireImmediately) {\n return getAdministration(thing).observe_(listener, fireImmediately);\n}\n\nfunction observeObservableProperty(thing, property, listener, fireImmediately) {\n return getAdministration(thing, property).observe_(listener, fireImmediately);\n}\n\nfunction cache(map, key, value) {\n map.set(key, value);\n return value;\n}\n\nfunction toJSHelper(source, __alreadySeen) {\n if (source == null || typeof source !== \"object\" || source instanceof Date || !isObservable(source)) {\n return source;\n }\n\n if (isObservableValue(source) || isComputedValue(source)) {\n return toJSHelper(source.get(), __alreadySeen);\n }\n\n if (__alreadySeen.has(source)) {\n return __alreadySeen.get(source);\n }\n\n if (isObservableArray(source)) {\n var res = cache(__alreadySeen, source, new Array(source.length));\n source.forEach(function (value, idx) {\n res[idx] = toJSHelper(value, __alreadySeen);\n });\n return res;\n }\n\n if (isObservableSet(source)) {\n var _res = cache(__alreadySeen, source, new Set());\n\n source.forEach(function (value) {\n _res.add(toJSHelper(value, __alreadySeen));\n });\n return _res;\n }\n\n if (isObservableMap(source)) {\n var _res2 = cache(__alreadySeen, source, new Map());\n\n source.forEach(function (value, key) {\n _res2.set(key, toJSHelper(value, __alreadySeen));\n });\n return _res2;\n } else {\n // must be observable object\n var _res3 = cache(__alreadySeen, source, {});\n\n apiOwnKeys(source).forEach(function (key) {\n if (objectPrototype.propertyIsEnumerable.call(source, key)) {\n _res3[key] = toJSHelper(source[key], __alreadySeen);\n }\n });\n return _res3;\n }\n}\n/**\r\n * Recursively converts an observable to it's non-observable native counterpart.\r\n * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.\r\n * Computed and other non-enumerable properties are completely ignored.\r\n * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.\r\n */\n\n\nfunction toJS(source, options) {\n if ( true && options) {\n die(\"toJS no longer supports options\");\n }\n\n return toJSHelper(source, new Map());\n}\n\nfunction trace() {\n if (false) {}\n\n var enterBreakPoint = false;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (typeof args[args.length - 1] === \"boolean\") {\n enterBreakPoint = args.pop();\n }\n\n var derivation = getAtomFromArgs(args);\n\n if (!derivation) {\n return die(\"'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly\");\n }\n\n if (derivation.isTracing_ === TraceMode.NONE) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' tracing enabled\");\n }\n\n derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;\n}\n\nfunction getAtomFromArgs(args) {\n switch (args.length) {\n case 0:\n return globalState.trackingDerivation;\n\n case 1:\n return getAtom(args[0]);\n\n case 2:\n return getAtom(args[0], args[1]);\n }\n}\n\n/**\r\n * During a transaction no views are updated until the end of the transaction.\r\n * The transaction will be run synchronously nonetheless.\r\n *\r\n * @param action a function that updates some reactive state\r\n * @returns any value that was returned by the 'action' parameter.\r\n */\n\nfunction transaction(action, thisArg) {\n if (thisArg === void 0) {\n thisArg = undefined;\n }\n\n startBatch();\n\n try {\n return action.apply(thisArg);\n } finally {\n endBatch();\n }\n}\n\nfunction when(predicate, arg1, arg2) {\n if (arguments.length === 1 || arg1 && typeof arg1 === \"object\") {\n return whenPromise(predicate, arg1);\n }\n\n return _when(predicate, arg1, arg2 || {});\n}\n\nfunction _when(predicate, effect, opts) {\n var timeoutHandle;\n\n if (typeof opts.timeout === \"number\") {\n var error = new Error(\"WHEN_TIMEOUT\");\n timeoutHandle = setTimeout(function () {\n if (!disposer[$mobx].isDisposed_) {\n disposer();\n\n if (opts.onError) {\n opts.onError(error);\n } else {\n throw error;\n }\n }\n }, opts.timeout);\n }\n\n opts.name = true ? opts.name || \"When@\" + getNextId() : undefined;\n var effectAction = createAction( true ? opts.name + \"-effect\" : undefined, effect); // eslint-disable-next-line\n\n var disposer = autorun(function (r) {\n // predicate should not change state\n var cond = allowStateChanges(false, predicate);\n\n if (cond) {\n r.dispose();\n\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n\n effectAction();\n }\n }, opts);\n return disposer;\n}\n\nfunction whenPromise(predicate, opts) {\n var _opts$signal;\n\n if ( true && opts && opts.onError) {\n return die(\"the options 'onError' and 'promise' cannot be combined\");\n }\n\n if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {\n return Object.assign(Promise.reject(new Error(\"WHEN_ABORTED\")), {\n cancel: function cancel() {\n return null;\n }\n });\n }\n\n var cancel;\n var abort;\n var res = new Promise(function (resolve, reject) {\n var _opts$signal2;\n\n var disposer = _when(predicate, resolve, _extends({}, opts, {\n onError: reject\n }));\n\n cancel = function cancel() {\n disposer();\n reject(new Error(\"WHEN_CANCELLED\"));\n };\n\n abort = function abort() {\n disposer();\n reject(new Error(\"WHEN_ABORTED\"));\n };\n\n opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener(\"abort\", abort);\n })[\"finally\"](function () {\n var _opts$signal3;\n\n return opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener(\"abort\", abort);\n });\n res.cancel = cancel;\n return res;\n}\n\nfunction getAdm(target) {\n return target[$mobx];\n} // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,\n// and skip either the internal values map, or the base object with its property descriptors!\n\n\nvar objectProxyTraps = {\n has: function has(target, name) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.\");\n }\n\n return getAdm(target).has_(name);\n },\n get: function get(target, name) {\n return getAdm(target).get_(name);\n },\n set: function set(target, name, value) {\n var _getAdm$set_;\n\n if (!isStringish(name)) {\n return false;\n }\n\n if ( true && !getAdm(target).values_.has(name)) {\n warnAboutProxyRequirement(\"add a new observable property through direct assignment. Use 'set' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;\n },\n deleteProperty: function deleteProperty(target, name) {\n var _getAdm$delete_;\n\n if (true) {\n warnAboutProxyRequirement(\"delete properties from an observable object. Use 'remove' from 'mobx' instead.\");\n }\n\n if (!isStringish(name)) {\n return false;\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;\n },\n defineProperty: function defineProperty(target, name, descriptor) {\n var _getAdm$definePropert;\n\n if (true) {\n warnAboutProxyRequirement(\"define property on an observable object. Use 'defineProperty' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;\n },\n ownKeys: function ownKeys(target) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.\");\n }\n\n return getAdm(target).ownKeys_();\n },\n preventExtensions: function preventExtensions(target) {\n die(13);\n }\n};\nfunction asDynamicObservableObject(target, options) {\n var _target$$mobx, _target$$mobx$proxy_;\n\n assertProxies();\n target = asObservableObject(target, options);\n return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);\n}\n\nfunction hasInterceptors(interceptable) {\n return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;\n}\nfunction registerInterceptor(interceptable, handler) {\n var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);\n interceptors.push(handler);\n return once(function () {\n var idx = interceptors.indexOf(handler);\n\n if (idx !== -1) {\n interceptors.splice(idx, 1);\n }\n });\n}\nfunction interceptChange(interceptable, change) {\n var prevU = untrackedStart();\n\n try {\n // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950\n var interceptors = [].concat(interceptable.interceptors_ || []);\n\n for (var i = 0, l = interceptors.length; i < l; i++) {\n change = interceptors[i](change);\n\n if (change && !change.type) {\n die(14);\n }\n\n if (!change) {\n break;\n }\n }\n\n return change;\n } finally {\n untrackedEnd(prevU);\n }\n}\n\nfunction hasListeners(listenable) {\n return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;\n}\nfunction registerListener(listenable, handler) {\n var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);\n listeners.push(handler);\n return once(function () {\n var idx = listeners.indexOf(handler);\n\n if (idx !== -1) {\n listeners.splice(idx, 1);\n }\n });\n}\nfunction notifyListeners(listenable, change) {\n var prevU = untrackedStart();\n var listeners = listenable.changeListeners_;\n\n if (!listeners) {\n return;\n }\n\n listeners = listeners.slice();\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](change);\n }\n\n untrackedEnd(prevU);\n}\n\nfunction makeObservable(target, annotations, options) {\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n var _annotations;\n\n if ( true && annotations && target[storedAnnotationsSymbol]) {\n die(\"makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.\");\n } // Default to decorators\n\n\n (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target); // Annotate\n\n ownKeys(annotations).forEach(function (key) {\n return adm.make_(key, annotations[key]);\n });\n } finally {\n endBatch();\n }\n\n return target;\n} // proto[keysSymbol] = new Set()\n\nvar keysSymbol = /*#__PURE__*/Symbol(\"mobx-keys\");\nfunction makeAutoObservable(target, overrides, options) {\n if (true) {\n if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {\n die(\"'makeAutoObservable' can only be used for classes that don't have a superclass\");\n }\n\n if (isObservableObject(target)) {\n die(\"makeAutoObservable can only be used on objects not already made observable\");\n }\n } // Optimization: avoid visiting protos\n // Assumes that annotation.make_/.extend_ works the same for plain objects\n\n\n if (isPlainObject(target)) {\n return extendObservable(target, target, overrides, options);\n }\n\n var adm = asObservableObject(target, options)[$mobx]; // Optimization: cache keys on proto\n // Assumes makeAutoObservable can be called only once per object and can't be used in subclass\n\n if (!target[keysSymbol]) {\n var proto = Object.getPrototypeOf(target);\n var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));\n keys[\"delete\"](\"constructor\");\n keys[\"delete\"]($mobx);\n addHiddenProp(proto, keysSymbol, keys);\n }\n\n startBatch();\n\n try {\n target[keysSymbol].forEach(function (key) {\n return adm.make_(key, // must pass \"undefined\" for { key: undefined }\n !overrides ? true : key in overrides ? overrides[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nvar SPLICE = \"splice\";\nvar UPDATE = \"update\";\nvar MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859\n\nvar arrayTraps = {\n get: function get(target, name) {\n var adm = target[$mobx];\n\n if (name === $mobx) {\n return adm;\n }\n\n if (name === \"length\") {\n return adm.getArrayLength_();\n }\n\n if (typeof name === \"string\" && !isNaN(name)) {\n return adm.get_(parseInt(name));\n }\n\n if (hasProp(arrayExtensions, name)) {\n return arrayExtensions[name];\n }\n\n return target[name];\n },\n set: function set(target, name, value) {\n var adm = target[$mobx];\n\n if (name === \"length\") {\n adm.setArrayLength_(value);\n }\n\n if (typeof name === \"symbol\" || isNaN(name)) {\n target[name] = value;\n } else {\n // numeric string\n adm.set_(parseInt(name), value);\n }\n\n return true;\n },\n preventExtensions: function preventExtensions() {\n die(15);\n }\n};\nvar ObservableArrayAdministration = /*#__PURE__*/function () {\n // this is the prop that gets proxied, so can't replace it!\n function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n this.owned_ = void 0;\n this.legacyMode_ = void 0;\n this.atom_ = void 0;\n this.values_ = [];\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.enhancer_ = void 0;\n this.dehancer = void 0;\n this.proxy_ = void 0;\n this.lastKnownLength_ = 0;\n this.owned_ = owned_;\n this.legacyMode_ = legacyMode_;\n this.atom_ = new Atom(name);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, true ? name + \"[..]\" : undefined);\n };\n }\n\n var _proto = ObservableArrayAdministration.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.dehanceValues_ = function dehanceValues_(values) {\n if (this.dehancer !== undefined && values.length > 0) {\n return values.map(this.dehancer);\n }\n\n return values;\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately === void 0) {\n fireImmediately = false;\n }\n\n if (fireImmediately) {\n listener({\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: \"splice\",\n index: 0,\n added: this.values_.slice(),\n addedCount: this.values_.length,\n removed: [],\n removedCount: 0\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.getArrayLength_ = function getArrayLength_() {\n this.atom_.reportObserved();\n return this.values_.length;\n };\n\n _proto.setArrayLength_ = function setArrayLength_(newLength) {\n if (typeof newLength !== \"number\" || isNaN(newLength) || newLength < 0) {\n die(\"Out of range: \" + newLength);\n }\n\n var currentLength = this.values_.length;\n\n if (newLength === currentLength) {\n return;\n } else if (newLength > currentLength) {\n var newItems = new Array(newLength - currentLength);\n\n for (var i = 0; i < newLength - currentLength; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n this.spliceWithArray_(currentLength, 0, newItems);\n } else {\n this.spliceWithArray_(newLength, currentLength - newLength);\n }\n };\n\n _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {\n if (oldLength !== this.lastKnownLength_) {\n die(16);\n }\n\n this.lastKnownLength_ += delta;\n\n if (this.legacyMode_ && delta > 0) {\n reserveArrayBuffer(oldLength + delta + 1);\n }\n };\n\n _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {\n var _this = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n var length = this.values_.length;\n\n if (index === undefined) {\n index = 0;\n } else if (index > length) {\n index = length;\n } else if (index < 0) {\n index = Math.max(0, length + index);\n }\n\n if (arguments.length === 1) {\n deleteCount = length - index;\n } else if (deleteCount === undefined || deleteCount === null) {\n deleteCount = 0;\n } else {\n deleteCount = Math.max(0, Math.min(deleteCount, length - index));\n }\n\n if (newItems === undefined) {\n newItems = EMPTY_ARRAY;\n }\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_,\n type: SPLICE,\n index: index,\n removedCount: deleteCount,\n added: newItems\n });\n\n if (!change) {\n return EMPTY_ARRAY;\n }\n\n deleteCount = change.removedCount;\n newItems = change.added;\n }\n\n newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {\n return _this.enhancer_(v, undefined);\n });\n\n if (this.legacyMode_ || \"development\" !== \"production\") {\n var lengthDelta = newItems.length - deleteCount;\n this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified\n }\n\n var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);\n\n if (deleteCount !== 0 || newItems.length !== 0) {\n this.notifyArraySplice_(index, newItems, res);\n }\n\n return this.dehanceValues_(res);\n };\n\n _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {\n if (newItems.length < MAX_SPLICE_SIZE) {\n var _this$values_;\n\n return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));\n } else {\n // The items removed by the splice\n var res = this.values_.slice(index, index + deleteCount); // The items that that should remain at the end of the array\n\n var oldItems = this.values_.slice(index + deleteCount); // New length is the previous length + addition count - deletion count\n\n this.values_.length += newItems.length - deleteCount;\n\n for (var i = 0; i < newItems.length; i++) {\n this.values_[index + i] = newItems[i];\n }\n\n for (var _i = 0; _i < oldItems.length; _i++) {\n this.values_[index + newItems.length + _i] = oldItems[_i];\n }\n\n return res;\n }\n };\n\n _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n type: UPDATE,\n debugObjectName: this.atom_.name_,\n index: index,\n newValue: newValue,\n oldValue: oldValue\n } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't\n // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged();\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: SPLICE,\n index: index,\n removed: removed,\n added: added,\n removedCount: removed.length,\n addedCount: added.length\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get_ = function get_(index) {\n if (this.legacyMode_ && index >= this.values_.length) {\n console.warn( true ? \"[mobx.array] Attempt to read an array index (\" + index + \") that is out of bounds (\" + this.values_.length + \"). Please check length first. Out of bound indices will not be tracked by MobX\" : undefined);\n return undefined;\n }\n\n this.atom_.reportObserved();\n return this.dehanceValue_(this.values_[index]);\n };\n\n _proto.set_ = function set_(index, newValue) {\n var values = this.values_;\n\n if (this.legacyMode_ && index > values.length) {\n // out of bounds\n die(17, index, values.length);\n }\n\n if (index < values.length) {\n // update at index in range\n checkIfStateModificationsAreAllowed(this.atom_);\n var oldValue = values[index];\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_,\n index: index,\n newValue: newValue\n });\n\n if (!change) {\n return;\n }\n\n newValue = change.newValue;\n }\n\n newValue = this.enhancer_(newValue, oldValue);\n var changed = newValue !== oldValue;\n\n if (changed) {\n values[index] = newValue;\n this.notifyArrayChildUpdate_(index, newValue, oldValue);\n }\n } else {\n // For out of bound index, we don't create an actual sparse array,\n // but rather fill the holes with undefined (same as setArrayLength_).\n // This could be considered a bug.\n var newItems = new Array(index + 1 - values.length);\n\n for (var i = 0; i < newItems.length - 1; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n newItems[newItems.length - 1] = newValue;\n this.spliceWithArray_(values.length, 0, newItems);\n }\n };\n\n return ObservableArrayAdministration;\n}();\nfunction createObservableArray(initialValues, enhancer, name, owned) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n assertProxies();\n var adm = new ObservableArrayAdministration(name, enhancer, owned, false);\n addHiddenFinalProp(adm.values_, $mobx, adm);\n var proxy = new Proxy(adm.values_, arrayTraps);\n adm.proxy_ = proxy;\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true);\n adm.spliceWithArray_(0, 0, initialValues);\n allowStateChangesEnd(prev);\n }\n\n return proxy;\n} // eslint-disable-next-line\n\nvar arrayExtensions = {\n clear: function clear() {\n return this.splice(0);\n },\n replace: function replace(newItems) {\n var adm = this[$mobx];\n return adm.spliceWithArray_(0, adm.values_.length, newItems);\n },\n // Used by JSON.stringify\n toJSON: function toJSON() {\n return this.slice();\n },\n\n /*\r\n * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)\r\n * since these functions alter the inner structure of the array, the have side effects.\r\n * Because the have side effects, they should not be used in computed function,\r\n * and for that reason the do not call dependencyState.notifyObserved\r\n */\n splice: function splice(index, deleteCount) {\n for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n newItems[_key - 2] = arguments[_key];\n }\n\n var adm = this[$mobx];\n\n switch (arguments.length) {\n case 0:\n return [];\n\n case 1:\n return adm.spliceWithArray_(index);\n\n case 2:\n return adm.spliceWithArray_(index, deleteCount);\n }\n\n return adm.spliceWithArray_(index, deleteCount, newItems);\n },\n spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {\n return this[$mobx].spliceWithArray_(index, deleteCount, newItems);\n },\n push: function push() {\n var adm = this[$mobx];\n\n for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n items[_key2] = arguments[_key2];\n }\n\n adm.spliceWithArray_(adm.values_.length, 0, items);\n return adm.values_.length;\n },\n pop: function pop() {\n return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];\n },\n shift: function shift() {\n return this.splice(0, 1)[0];\n },\n unshift: function unshift() {\n var adm = this[$mobx];\n\n for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n items[_key3] = arguments[_key3];\n }\n\n adm.spliceWithArray_(0, 0, items);\n return adm.values_.length;\n },\n reverse: function reverse() {\n // reverse by default mutates in place before returning the result\n // which makes it both a 'derivation' and a 'mutation'.\n if (globalState.trackingDerivation) {\n die(37, \"reverse\");\n }\n\n this.replace(this.slice().reverse());\n return this;\n },\n sort: function sort() {\n // sort by default mutates in place before returning the result\n // which goes against all good practices. Let's not change the array in place!\n if (globalState.trackingDerivation) {\n die(37, \"sort\");\n }\n\n var copy = this.slice();\n copy.sort.apply(copy, arguments);\n this.replace(copy);\n return this;\n },\n remove: function remove(value) {\n var adm = this[$mobx];\n var idx = adm.dehanceValues_(adm.values_).indexOf(value);\n\n if (idx > -1) {\n this.splice(idx, 1);\n return true;\n }\n\n return false;\n }\n};\n/**\r\n * Wrap function from prototype\r\n * Without this, everything works as well, but this works\r\n * faster as everything works on unproxied values\r\n */\n\naddArrayExtension(\"concat\", simpleFunc);\naddArrayExtension(\"flat\", simpleFunc);\naddArrayExtension(\"includes\", simpleFunc);\naddArrayExtension(\"indexOf\", simpleFunc);\naddArrayExtension(\"join\", simpleFunc);\naddArrayExtension(\"lastIndexOf\", simpleFunc);\naddArrayExtension(\"slice\", simpleFunc);\naddArrayExtension(\"toString\", simpleFunc);\naddArrayExtension(\"toLocaleString\", simpleFunc); // map\n\naddArrayExtension(\"every\", mapLikeFunc);\naddArrayExtension(\"filter\", mapLikeFunc);\naddArrayExtension(\"find\", mapLikeFunc);\naddArrayExtension(\"findIndex\", mapLikeFunc);\naddArrayExtension(\"flatMap\", mapLikeFunc);\naddArrayExtension(\"forEach\", mapLikeFunc);\naddArrayExtension(\"map\", mapLikeFunc);\naddArrayExtension(\"some\", mapLikeFunc); // reduce\n\naddArrayExtension(\"reduce\", reduceLikeFunc);\naddArrayExtension(\"reduceRight\", reduceLikeFunc);\n\nfunction addArrayExtension(funcName, funcFactory) {\n if (typeof Array.prototype[funcName] === \"function\") {\n arrayExtensions[funcName] = funcFactory(funcName);\n }\n} // Report and delegate to dehanced array\n\n\nfunction simpleFunc(funcName) {\n return function () {\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction mapLikeFunc(funcName) {\n return function (callback, thisArg) {\n var _this2 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName](function (element, index) {\n return callback.call(thisArg, element, index, _this2);\n });\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction reduceLikeFunc(funcName) {\n return function () {\n var _this3 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_); // #2432 - reduce behavior depends on arguments.length\n\n var callback = arguments[0];\n\n arguments[0] = function (accumulator, currentValue, index) {\n return callback(accumulator, currentValue, index, _this3);\n };\n\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\n\nvar isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableArrayAdministration\", ObservableArrayAdministration);\nfunction isObservableArray(thing) {\n return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);\n}\n\nvar _Symbol$iterator, _Symbol$toStringTag;\nvar ObservableMapMarker = {};\nvar ADD = \"add\";\nvar DELETE = \"delete\"; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54\n// But: https://github.com/mobxjs/mobx/issues/1556\n\n_Symbol$iterator = Symbol.iterator;\n_Symbol$toStringTag = Symbol.toStringTag;\nvar ObservableMap = /*#__PURE__*/function () {\n // hasMap, not hashMap >-).\n function ObservableMap(initialData, enhancer_, name_) {\n var _this = this;\n\n if (enhancer_ === void 0) {\n enhancer_ = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableMap@\" + getNextId() : undefined;\n }\n\n this.enhancer_ = void 0;\n this.name_ = void 0;\n this[$mobx] = ObservableMapMarker;\n this.data_ = void 0;\n this.hasMap_ = void 0;\n this.keysAtom_ = void 0;\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = enhancer_;\n this.name_ = name_;\n\n if (!isFunction(Map)) {\n die(18);\n }\n\n this.keysAtom_ = createAtom( true ? this.name_ + \".keys()\" : undefined);\n this.data_ = new Map();\n this.hasMap_ = new Map();\n allowStateChanges(true, function () {\n _this.merge(initialData);\n });\n }\n\n var _proto = ObservableMap.prototype;\n\n _proto.has_ = function has_(key) {\n return this.data_.has(key);\n };\n\n _proto.has = function has(key) {\n var _this2 = this;\n\n if (!globalState.trackingDerivation) {\n return this.has_(key);\n }\n\n var entry = this.hasMap_.get(key);\n\n if (!entry) {\n var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.hasMap_.set(key, newEntry);\n onBecomeUnobserved(newEntry, function () {\n return _this2.hasMap_[\"delete\"](key);\n });\n }\n\n return entry.get();\n };\n\n _proto.set = function set(key, value) {\n var hasKey = this.has_(key);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: hasKey ? UPDATE : ADD,\n object: this,\n newValue: value,\n name: key\n });\n\n if (!change) {\n return this;\n }\n\n value = change.newValue;\n }\n\n if (hasKey) {\n this.updateValue_(key, value);\n } else {\n this.addValue_(key, value);\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(key) {\n var _this3 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n name: key\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has_(key)) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: this.data_.get(key).value_,\n name: key\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n } // TODO fix type\n\n\n transaction(function () {\n var _this3$hasMap_$get;\n\n _this3.keysAtom_.reportChanged();\n\n (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false);\n\n var observable = _this3.data_.get(key);\n\n observable.setNewValue_(undefined);\n\n _this3.data_[\"delete\"](key);\n });\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.updateValue_ = function updateValue_(key, newValue) {\n var observable = this.data_.get(key);\n newValue = observable.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: UPDATE,\n object: this,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.addValue_ = function addValue_(key, newValue) {\n var _this4 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n transaction(function () {\n var _this4$hasMap_$get;\n\n var observable = new ObservableValue(newValue, _this4.enhancer_, true ? _this4.name_ + \".\" + stringifyKey(key) : undefined, false);\n\n _this4.data_.set(key, observable);\n\n newValue = observable.value_; // value might have been changed\n\n (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true);\n\n _this4.keysAtom_.reportChanged();\n });\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get = function get(key) {\n if (this.has(key)) {\n return this.dehanceValue_(this.data_.get(key).get());\n }\n\n return this.dehanceValue_(undefined);\n };\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.keys = function keys() {\n this.keysAtom_.reportObserved();\n return this.data_.keys();\n };\n\n _proto.values = function values() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next = keys.next(),\n done = _keys$next.done,\n value = _keys$next.value;\n\n return {\n done: done,\n value: done ? undefined : self.get(value)\n };\n }\n });\n };\n\n _proto.entries = function entries() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next2 = keys.next(),\n done = _keys$next2.done,\n value = _keys$next2.value;\n\n return {\n done: done,\n value: done ? undefined : [value, self.get(value)]\n };\n }\n });\n };\n\n _proto[_Symbol$iterator] = function () {\n return this.entries();\n };\n\n _proto.forEach = function forEach(callback, thisArg) {\n for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {\n var _step$value = _step.value,\n key = _step$value[0],\n value = _step$value[1];\n callback.call(thisArg, value, key, this);\n }\n }\n /** Merge another object into this object, returns this. */\n ;\n\n _proto.merge = function merge(other) {\n var _this5 = this;\n\n if (isObservableMap(other)) {\n other = new Map(other);\n }\n\n transaction(function () {\n if (isPlainObject(other)) {\n getPlainObjectKeys(other).forEach(function (key) {\n return _this5.set(key, other[key]);\n });\n } else if (Array.isArray(other)) {\n other.forEach(function (_ref) {\n var key = _ref[0],\n value = _ref[1];\n return _this5.set(key, value);\n });\n } else if (isES6Map(other)) {\n if (other.constructor !== Map) {\n die(19, other);\n }\n\n other.forEach(function (value, key) {\n return _this5.set(key, value);\n });\n } else if (other !== null && other !== undefined) {\n die(20, other);\n }\n });\n return this;\n };\n\n _proto.clear = function clear() {\n var _this6 = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {\n var key = _step2.value;\n\n _this6[\"delete\"](key);\n }\n });\n });\n };\n\n _proto.replace = function replace(values) {\n var _this7 = this;\n\n // Implementation requirements:\n // - respect ordering of replacement map\n // - allow interceptors to run and potentially prevent individual operations\n // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)\n // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)\n // - note that result map may differ from replacement map due to the interceptors\n transaction(function () {\n // Convert to map so we can do quick key lookups\n var replacementMap = convertToMap(values);\n var orderedData = new Map(); // Used for optimization\n\n var keysReportChangedCalled = false; // Delete keys that don't exist in replacement map\n // if the key deletion is prevented by interceptor\n // add entry at the beginning of the result map\n\n for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {\n var key = _step3.value;\n\n // Concurrently iterating/deleting keys\n // iterator should handle this correctly\n if (!replacementMap.has(key)) {\n var deleted = _this7[\"delete\"](key); // Was the key removed?\n\n\n if (deleted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n } else {\n // Delete prevented by interceptor\n var value = _this7.data_.get(key);\n\n orderedData.set(key, value);\n }\n }\n } // Merge entries\n\n\n for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {\n var _step4$value = _step4.value,\n _key = _step4$value[0],\n _value = _step4$value[1];\n\n // We will want to know whether a new key is added\n var keyExisted = _this7.data_.has(_key); // Add or update value\n\n\n _this7.set(_key, _value); // The addition could have been prevent by interceptor\n\n\n if (_this7.data_.has(_key)) {\n // The update could have been prevented by interceptor\n // and also we want to preserve existing values\n // so use value from _data map (instead of replacement map)\n var _value2 = _this7.data_.get(_key);\n\n orderedData.set(_key, _value2); // Was a new key added?\n\n if (!keyExisted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n }\n }\n } // Check for possible key order change\n\n\n if (!keysReportChangedCalled) {\n if (_this7.data_.size !== orderedData.size) {\n // If size differs, keys are definitely modified\n _this7.keysAtom_.reportChanged();\n } else {\n var iter1 = _this7.data_.keys();\n\n var iter2 = orderedData.keys();\n var next1 = iter1.next();\n var next2 = iter2.next();\n\n while (!next1.done) {\n if (next1.value !== next2.value) {\n _this7.keysAtom_.reportChanged();\n\n break;\n }\n\n next1 = iter1.next();\n next2 = iter2.next();\n }\n }\n } // Use correctly ordered map\n\n\n _this7.data_ = orderedData;\n });\n return this;\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableMap]\";\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with maps.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _createClass(ObservableMap, [{\n key: \"size\",\n get: function get() {\n this.keysAtom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Map\";\n }\n }]);\n\n return ObservableMap;\n}(); // eslint-disable-next-line\n\nvar isObservableMap = /*#__PURE__*/createInstanceofPredicate(\"ObservableMap\", ObservableMap);\n\nfunction convertToMap(dataStructure) {\n if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {\n return dataStructure;\n } else if (Array.isArray(dataStructure)) {\n return new Map(dataStructure);\n } else if (isPlainObject(dataStructure)) {\n var map = new Map();\n\n for (var key in dataStructure) {\n map.set(key, dataStructure[key]);\n }\n\n return map;\n } else {\n return die(21, dataStructure);\n }\n}\n\nvar _Symbol$iterator$1, _Symbol$toStringTag$1;\nvar ObservableSetMarker = {};\n_Symbol$iterator$1 = Symbol.iterator;\n_Symbol$toStringTag$1 = Symbol.toStringTag;\nvar ObservableSet = /*#__PURE__*/function () {\n function ObservableSet(initialData, enhancer, name_) {\n if (enhancer === void 0) {\n enhancer = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableSet@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this[$mobx] = ObservableSetMarker;\n this.data_ = new Set();\n this.atom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = void 0;\n this.name_ = name_;\n\n if (!isFunction(Set)) {\n die(22);\n }\n\n this.atom_ = createAtom(this.name_);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, name_);\n };\n\n if (initialData) {\n this.replace(initialData);\n }\n }\n\n var _proto = ObservableSet.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.clear = function clear() {\n var _this = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) {\n var value = _step.value;\n\n _this[\"delete\"](value);\n }\n });\n });\n };\n\n _proto.forEach = function forEach(callbackFn, thisArg) {\n for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {\n var value = _step2.value;\n callbackFn.call(thisArg, value, value, this);\n }\n };\n\n _proto.add = function add(value) {\n var _this2 = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: ADD,\n object: this,\n newValue: value\n });\n\n if (!change) {\n return this;\n } // ideally, value = change.value would be done here, so that values can be\n // changed by interceptor. Same applies for other Set and Map api's.\n\n }\n\n if (!this.has(value)) {\n transaction(function () {\n _this2.data_.add(_this2.enhancer_(value, undefined));\n\n _this2.atom_.reportChanged();\n });\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n newValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change);\n }\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(value) {\n var _this3 = this;\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n oldValue: value\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has(value)) {\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change2 = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change2);\n }\n\n transaction(function () {\n _this3.atom_.reportChanged();\n\n _this3.data_[\"delete\"](value);\n });\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.has = function has(value) {\n this.atom_.reportObserved();\n return this.data_.has(this.dehanceValue_(value));\n };\n\n _proto.entries = function entries() {\n var nextIndex = 0;\n var keys = Array.from(this.keys());\n var values = Array.from(this.values());\n return makeIterable({\n next: function next() {\n var index = nextIndex;\n nextIndex += 1;\n return index < values.length ? {\n value: [keys[index], values[index]],\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.keys = function keys() {\n return this.values();\n };\n\n _proto.values = function values() {\n this.atom_.reportObserved();\n var self = this;\n var nextIndex = 0;\n var observableValues = Array.from(this.data_.values());\n return makeIterable({\n next: function next() {\n return nextIndex < observableValues.length ? {\n value: self.dehanceValue_(observableValues[nextIndex++]),\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.replace = function replace(other) {\n var _this4 = this;\n\n if (isObservableSet(other)) {\n other = new Set(other);\n }\n\n transaction(function () {\n if (Array.isArray(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (isES6Set(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (other !== null && other !== undefined) {\n die(\"Cannot initialize set from \" + other);\n }\n });\n return this;\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n // ... 'fireImmediately' could also be true?\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with sets.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableSet]\";\n };\n\n _proto[_Symbol$iterator$1] = function () {\n return this.values();\n };\n\n _createClass(ObservableSet, [{\n key: \"size\",\n get: function get() {\n this.atom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag$1,\n get: function get() {\n return \"Set\";\n }\n }]);\n\n return ObservableSet;\n}(); // eslint-disable-next-line\n\nvar isObservableSet = /*#__PURE__*/createInstanceofPredicate(\"ObservableSet\", ObservableSet);\n\nvar descriptorCache = /*#__PURE__*/Object.create(null);\nvar REMOVE = \"remove\";\nvar ObservableObjectAdministration = /*#__PURE__*/function () {\n function ObservableObjectAdministration(target_, values_, name_, // Used anytime annotation is not explicitely provided\n defaultAnnotation_) {\n if (values_ === void 0) {\n values_ = new Map();\n }\n\n if (defaultAnnotation_ === void 0) {\n defaultAnnotation_ = autoAnnotation;\n }\n\n this.target_ = void 0;\n this.values_ = void 0;\n this.name_ = void 0;\n this.defaultAnnotation_ = void 0;\n this.keysAtom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.proxy_ = void 0;\n this.isPlainObject_ = void 0;\n this.appliedAnnotations_ = void 0;\n this.pendingKeys_ = void 0;\n this.target_ = target_;\n this.values_ = values_;\n this.name_ = name_;\n this.defaultAnnotation_ = defaultAnnotation_;\n this.keysAtom_ = new Atom( true ? this.name_ + \".keys\" : undefined); // Optimization: we use this frequently\n\n this.isPlainObject_ = isPlainObject(this.target_);\n\n if ( true && !isAnnotation(this.defaultAnnotation_)) {\n die(\"defaultAnnotation must be valid annotation\");\n }\n\n if (true) {\n // Prepare structure for tracking which fields were already annotated\n this.appliedAnnotations_ = {};\n }\n }\n\n var _proto = ObservableObjectAdministration.prototype;\n\n _proto.getObservablePropValue_ = function getObservablePropValue_(key) {\n return this.values_.get(key).get();\n };\n\n _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {\n var observable = this.values_.get(key);\n\n if (observable instanceof ComputedValue) {\n observable.set(newValue);\n return true;\n } // intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: newValue\n });\n\n if (!change) {\n return null;\n }\n\n newValue = change.newValue;\n }\n\n newValue = observable.prepareNewValue_(newValue); // notify spy & observers\n\n if (newValue !== globalState.UNCHANGED) {\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n var _change = notify || notifySpy ? {\n type: UPDATE,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n }\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n return true;\n };\n\n _proto.get_ = function get_(key) {\n if (globalState.trackingDerivation && !hasProp(this.target_, key)) {\n // Key doesn't exist yet, subscribe for it in case it's added later\n this.has_(key);\n }\n\n return this.target_[key];\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {any} value\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.set_ = function set_(key, value, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // Don't use .has(key) - we care about own\n if (hasProp(this.target_, key)) {\n // Existing prop\n if (this.values_.has(key)) {\n // Observable (can be intercepted)\n return this.setObservablePropValue_(key, value);\n } else if (proxyTrap) {\n // Non-observable - proxy\n return Reflect.set(this.target_, key, value);\n } else {\n // Non-observable\n this.target_[key] = value;\n return true;\n }\n } else {\n // New prop\n return this.extend_(key, {\n value: value,\n enumerable: true,\n writable: true,\n configurable: true\n }, this.defaultAnnotation_, proxyTrap);\n }\n } // Trap for \"in\"\n ;\n\n _proto.has_ = function has_(key) {\n if (!globalState.trackingDerivation) {\n // Skip key subscription outside derivation\n return key in this.target_;\n }\n\n this.pendingKeys_ || (this.pendingKeys_ = new Map());\n var entry = this.pendingKeys_.get(key);\n\n if (!entry) {\n entry = new ObservableValue(key in this.target_, referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.pendingKeys_.set(key, entry);\n }\n\n return entry.get();\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop\r\n */\n ;\n\n _proto.make_ = function make_(key, annotation) {\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return;\n }\n\n assertAnnotable(this, annotation, key);\n\n if (!(key in this.target_)) {\n var _this$target_$storedA;\n\n // Throw on missing key, except for decorators:\n // Decorator annotations are collected from whole prototype chain.\n // When called from super() some props may not exist yet.\n // However we don't have to worry about missing prop,\n // because the decorator must have been applied to something.\n if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {\n return; // will be annotated by subclass constructor\n } else {\n die(1, annotation.annotationType_, this.name_ + \".\" + key.toString());\n }\n }\n\n var source = this.target_;\n\n while (source && source !== objectPrototype) {\n var descriptor = getDescriptor(source, key);\n\n if (descriptor) {\n var outcome = annotation.make_(this, key, descriptor, source);\n\n if (outcome === 0\n /* Cancel */\n ) {\n return;\n }\n\n if (outcome === 1\n /* Break */\n ) {\n break;\n }\n }\n\n source = Object.getPrototypeOf(source);\n }\n\n recordAnnotationApplied(this, annotation, key);\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return this.defineProperty_(key, descriptor, proxyTrap);\n }\n\n assertAnnotable(this, annotation, key);\n var outcome = annotation.extend_(this, key, descriptor, proxyTrap);\n\n if (outcome) {\n recordAnnotationApplied(this, annotation, key);\n }\n\n return outcome;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: descriptor.value\n });\n\n if (!change) {\n return null;\n }\n\n var newValue = change.newValue;\n\n if (descriptor.value !== newValue) {\n descriptor = _extends({}, descriptor, {\n value: newValue\n });\n }\n } // Define\n\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n } // Notify\n\n\n this.notifyPropertyAddition_(key, descriptor.value);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: value\n });\n\n if (!change) {\n return null;\n }\n\n value = change.newValue;\n }\n\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: true,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n var observable = new ObservableValue(value, enhancer, true ? this.name_ + \".\" + key.toString() : undefined, false);\n this.values_.set(key, observable); // Notify (value possibly changed by ObservableValue)\n\n this.notifyPropertyAddition_(key, observable.value_);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: undefined\n });\n\n if (!change) {\n return null;\n }\n }\n\n options.name || (options.name = true ? this.name_ + \".\" + key.toString() : undefined);\n options.context = this.proxy_ || this.target_;\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: false,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n this.values_.set(key, new ComputedValue(options)); // Notify\n\n this.notifyPropertyAddition_(key, undefined);\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.delete_ = function delete_(key, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // No such prop\n if (!hasProp(this.target_, key)) {\n return true;\n } // Intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: REMOVE\n }); // Cancelled\n\n if (!change) {\n return null;\n }\n } // Delete\n\n\n try {\n var _this$pendingKeys_, _this$pendingKeys_$ge;\n\n startBatch();\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n var observable = this.values_.get(key); // Value needed for spies/listeners\n\n var value = undefined; // Optimization: don't pull the value unless we will need it\n\n if (!observable && (notify || notifySpy)) {\n var _getDescriptor;\n\n value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;\n } // delete prop (do first, may fail)\n\n\n if (proxyTrap) {\n if (!Reflect.deleteProperty(this.target_, key)) {\n return false;\n }\n } else {\n delete this.target_[key];\n } // Allow re-annotating this field\n\n\n if (true) {\n delete this.appliedAnnotations_[key];\n } // Clear observable\n\n\n if (observable) {\n this.values_[\"delete\"](key); // for computed, value is undefined\n\n if (observable instanceof ObservableValue) {\n value = observable.value_;\n } // Notify: autorun(() => obj[key]), see #1796\n\n\n propagateChanged(observable);\n } // Notify \"keys/entries/values\" observers\n\n\n this.keysAtom_.reportChanged(); // Notify \"has\" observers\n // \"in\" as it may still exist in proto\n\n (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_); // Notify spies/listeners\n\n if (notify || notifySpy) {\n var _change2 = {\n type: REMOVE,\n observableKind: \"object\",\n object: this.proxy_ || this.target_,\n debugObjectName: this.name_,\n oldValue: value,\n name: key\n };\n\n if ( true && notifySpy) {\n spyReportStart(_change2);\n }\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n ;\n\n _proto.observe_ = function observe_(callback, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support the fire immediately property for observable objects.\");\n }\n\n return registerListener(this, callback);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {\n var _this$pendingKeys_2, _this$pendingKeys_2$g;\n\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n if (notify || notifySpy) {\n var change = notify || notifySpy ? {\n type: ADD,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: value\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true); // Notify \"keys/entries/values\" observers\n\n this.keysAtom_.reportChanged();\n };\n\n _proto.ownKeys_ = function ownKeys_() {\n this.keysAtom_.reportObserved();\n return ownKeys(this.target_);\n };\n\n _proto.keys_ = function keys_() {\n // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.\n // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.\n // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)\n // We choose to over-report in Object.keys(object), because:\n // - typically it's used with simple data objects\n // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected\n this.keysAtom_.reportObserved();\n return Object.keys(this.target_);\n };\n\n return ObservableObjectAdministration;\n}();\nfunction asObservableObject(target, options) {\n var _options$name;\n\n if ( true && options && isObservableObject(target)) {\n die(\"Options can't be provided for already observable objects.\");\n }\n\n if (hasProp(target, $mobx)) {\n if ( true && !(getAdministration(target) instanceof ObservableObjectAdministration)) {\n die(\"Cannot convert '\" + getDebugName(target) + \"' into observable object:\" + \"\\nThe target is already observable of different type.\" + \"\\nExtending builtins is not supported.\");\n }\n\n return target;\n }\n\n if ( true && !Object.isExtensible(target)) {\n die(\"Cannot make the designated object observable; it is not extensible\");\n }\n\n var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : true ? (isPlainObject(target) ? \"ObservableObject\" : target.constructor.name) + \"@\" + getNextId() : undefined;\n var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));\n addHiddenProp(target, $mobx, adm);\n return target;\n}\nvar isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableObjectAdministration\", ObservableObjectAdministration);\n\nfunction getCachedObservablePropDescriptor(key) {\n return descriptorCache[key] || (descriptorCache[key] = {\n get: function get() {\n return this[$mobx].getObservablePropValue_(key);\n },\n set: function set(value) {\n return this[$mobx].setObservablePropValue_(key, value);\n }\n });\n}\n\nfunction isObservableObject(thing) {\n if (isObject(thing)) {\n return isObservableObjectAdministration(thing[$mobx]);\n }\n\n return false;\n}\nfunction recordAnnotationApplied(adm, annotation, key) {\n var _adm$target_$storedAn;\n\n if (true) {\n adm.appliedAnnotations_[key] = annotation;\n } // Remove applied decorator annotation so we don't try to apply it again in subclass constructor\n\n\n (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key];\n}\n\nfunction assertAnnotable(adm, annotation, key) {\n // Valid annotation\n if ( true && !isAnnotation(annotation)) {\n die(\"Cannot annotate '\" + adm.name_ + \".\" + key.toString() + \"': Invalid annotation.\");\n }\n /*\r\n // Configurable, not sealed, not frozen\r\n // Possibly not needed, just a little better error then the one thrown by engine.\r\n // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.\r\n if (__DEV__) {\r\n const configurable = getDescriptor(adm.target_, key)?.configurable\r\n const frozen = Object.isFrozen(adm.target_)\r\n const sealed = Object.isSealed(adm.target_)\r\n if (!configurable || frozen || sealed) {\r\n const fieldName = `${adm.name_}.${key.toString()}`\r\n const requestedAnnotationType = annotation.annotationType_\r\n let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`\r\n if (frozen) {\r\n error += `\\nObject is frozen.`\r\n }\r\n if (sealed) {\r\n error += `\\nObject is sealed.`\r\n }\r\n if (!configurable) {\r\n error += `\\nproperty is not configurable.`\r\n // Mention only if caused by us to avoid confusion\r\n if (hasProp(adm.appliedAnnotations!, key)) {\r\n error += `\\nTo prevent accidental re-definition of a field by a subclass, `\r\n error += `all annotated fields of non-plain objects (classes) are not configurable.`\r\n }\r\n }\r\n die(error)\r\n }\r\n }\r\n */\n // Not annotated\n\n\n if ( true && !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {\n var fieldName = adm.name_ + \".\" + key.toString();\n var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already annotated with '\" + currentAnnotationType + \"'.\") + \"\\nRe-annotating fields is not allowed.\" + \"\\nUse 'override' annotation for methods overridden by subclass.\");\n }\n}\n\nvar ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);\n/**\r\n * This array buffer contains two lists of properties, so that all arrays\r\n * can recycle their property definitions, which significantly improves performance of creating\r\n * properties on the fly.\r\n */\n\n\nvar OBSERVABLE_ARRAY_BUFFER_SIZE = 0; // Typescript workaround to make sure ObservableArray extends Array\n\nvar StubArray = function StubArray() {};\n\nfunction inherit(ctor, proto) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(ctor.prototype, proto);\n } else if (ctor.prototype.__proto__ !== undefined) {\n ctor.prototype.__proto__ = proto;\n } else {\n ctor.prototype = proto;\n }\n}\n\ninherit(StubArray, Array.prototype); // Weex proto freeze protection was here,\n// but it is unclear why the hack is need as MobX never changed the prototype\n// anyway, so removed it in V6\n\nvar LegacyObservableArray = /*#__PURE__*/function (_StubArray, _Symbol$toStringTag, _Symbol$iterator) {\n _inheritsLoose(LegacyObservableArray, _StubArray);\n\n function LegacyObservableArray(initialValues, enhancer, name, owned) {\n var _this;\n\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n _this = _StubArray.call(this) || this;\n var adm = new ObservableArrayAdministration(name, enhancer, owned, true);\n adm.proxy_ = _assertThisInitialized(_this);\n addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm);\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true); // @ts-ignore\n\n _this.spliceWithArray(0, 0, initialValues);\n\n allowStateChangesEnd(prev);\n }\n\n {\n // Seems that Safari won't use numeric prototype setter untill any * numeric property is\n // defined on the instance. After that it works fine, even if this property is deleted.\n Object.defineProperty(_assertThisInitialized(_this), \"0\", ENTRY_0);\n }\n\n return _this;\n }\n\n var _proto = LegacyObservableArray.prototype;\n\n _proto.concat = function concat() {\n this[$mobx].atom_.reportObserved();\n\n for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {\n arrays[_key] = arguments[_key];\n }\n\n return Array.prototype.concat.apply(this.slice(), //@ts-ignore\n arrays.map(function (a) {\n return isObservableArray(a) ? a.slice() : a;\n }));\n };\n\n _proto[_Symbol$iterator] = function () {\n var self = this;\n var nextIndex = 0;\n return makeIterable({\n next: function next() {\n return nextIndex < self.length ? {\n value: self[nextIndex++],\n done: false\n } : {\n done: true,\n value: undefined\n };\n }\n });\n };\n\n _createClass(LegacyObservableArray, [{\n key: \"length\",\n get: function get() {\n return this[$mobx].getArrayLength_();\n },\n set: function set(newLength) {\n this[$mobx].setArrayLength_(newLength);\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Array\";\n }\n }]);\n\n return LegacyObservableArray;\n}(StubArray, Symbol.toStringTag, Symbol.iterator);\n\nObject.entries(arrayExtensions).forEach(function (_ref) {\n var prop = _ref[0],\n fn = _ref[1];\n\n if (prop !== \"concat\") {\n addHiddenProp(LegacyObservableArray.prototype, prop, fn);\n }\n});\n\nfunction createArrayEntryDescriptor(index) {\n return {\n enumerable: false,\n configurable: true,\n get: function get() {\n return this[$mobx].get_(index);\n },\n set: function set(value) {\n this[$mobx].set_(index, value);\n }\n };\n}\n\nfunction createArrayBufferItem(index) {\n defineProperty(LegacyObservableArray.prototype, \"\" + index, createArrayEntryDescriptor(index));\n}\n\nfunction reserveArrayBuffer(max) {\n if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {\n for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {\n createArrayBufferItem(index);\n }\n\n OBSERVABLE_ARRAY_BUFFER_SIZE = max;\n }\n}\nreserveArrayBuffer(1000);\nfunction createLegacyArray(initialValues, enhancer, name) {\n return new LegacyObservableArray(initialValues, enhancer, name);\n}\n\nfunction getAtom(thing, property) {\n if (typeof thing === \"object\" && thing !== null) {\n if (isObservableArray(thing)) {\n if (property !== undefined) {\n die(23);\n }\n\n return thing[$mobx].atom_;\n }\n\n if (isObservableSet(thing)) {\n return thing[$mobx];\n }\n\n if (isObservableMap(thing)) {\n if (property === undefined) {\n return thing.keysAtom_;\n }\n\n var observable = thing.data_.get(property) || thing.hasMap_.get(property);\n\n if (!observable) {\n die(25, property, getDebugName(thing));\n }\n\n return observable;\n }\n\n\n if (isObservableObject(thing)) {\n if (!property) {\n return die(26);\n }\n\n var _observable = thing[$mobx].values_.get(property);\n\n if (!_observable) {\n die(27, property, getDebugName(thing));\n }\n\n return _observable;\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n } else if (isFunction(thing)) {\n if (isReaction(thing[$mobx])) {\n // disposer function\n return thing[$mobx];\n }\n }\n\n die(28);\n}\nfunction getAdministration(thing, property) {\n if (!thing) {\n die(29);\n }\n\n if (property !== undefined) {\n return getAdministration(getAtom(thing, property));\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n\n if (isObservableMap(thing) || isObservableSet(thing)) {\n return thing;\n }\n\n if (thing[$mobx]) {\n return thing[$mobx];\n }\n\n die(24, thing);\n}\nfunction getDebugName(thing, property) {\n var named;\n\n if (property !== undefined) {\n named = getAtom(thing, property);\n } else if (isAction(thing)) {\n return thing.name;\n } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {\n named = getAdministration(thing);\n } else {\n // valid for arrays as well\n named = getAtom(thing);\n }\n\n return named.name_;\n}\n\nvar toString = objectPrototype.toString;\nfunction deepEqual(a, b, depth) {\n if (depth === void 0) {\n depth = -1;\n }\n\n return eq(a, b, depth);\n} // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289\n// Internal recursive comparison function for `isEqual`.\n\nfunction eq(a, b, depth, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) {\n return a !== 0 || 1 / a === 1 / b;\n } // `null` or `undefined` only equal to itself (strict comparison).\n\n\n if (a == null || b == null) {\n return false;\n } // `NaN`s are equivalent, but non-reflexive.\n\n\n if (a !== a) {\n return b !== b;\n } // Exhaust primitive checks\n\n\n var type = typeof a;\n\n if (type !== \"function\" && type !== \"object\" && typeof b != \"object\") {\n return false;\n } // Compare `[[Class]]` names.\n\n\n var className = toString.call(a);\n\n if (className !== toString.call(b)) {\n return false;\n }\n\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case \"[object RegExp]\": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n\n case \"[object String]\":\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return \"\" + a === \"\" + b;\n\n case \"[object Number]\":\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN.\n if (+a !== +a) {\n return +b !== +b;\n } // An `egal` comparison is performed for other numeric values.\n\n\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n\n case \"[object Date]\":\n case \"[object Boolean]\":\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n\n case \"[object Symbol]\":\n return typeof Symbol !== \"undefined\" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);\n\n case \"[object Map]\":\n case \"[object Set]\":\n // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.\n // Hide this extra level by increasing the depth.\n if (depth >= 0) {\n depth++;\n }\n\n break;\n } // Unwrap any wrapped objects.\n\n\n a = unwrap(a);\n b = unwrap(b);\n var areArrays = className === \"[object Array]\";\n\n if (!areArrays) {\n if (typeof a != \"object\" || typeof b != \"object\") {\n return false;\n } // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n\n\n var aCtor = a.constructor,\n bCtor = b.constructor;\n\n if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && \"constructor\" in a && \"constructor\" in b) {\n return false;\n }\n }\n\n if (depth === 0) {\n return false;\n } else if (depth < 0) {\n depth = -1;\n } // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n\n\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) {\n return bStack[length] === b;\n }\n } // Add the first object to the stack of traversed objects.\n\n\n aStack.push(a);\n bStack.push(b); // Recursively compare objects and arrays.\n\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n\n if (length !== b.length) {\n return false;\n } // Deep compare the contents, ignoring non-numeric properties.\n\n\n while (length--) {\n if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {\n return false;\n }\n }\n } else {\n // Deep compare objects.\n var keys = Object.keys(a);\n var key;\n length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality.\n\n if (Object.keys(b).length !== length) {\n return false;\n }\n\n while (length--) {\n // Deep compare each member\n key = keys[length];\n\n if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {\n return false;\n }\n }\n } // Remove the first object from the stack of traversed objects.\n\n\n aStack.pop();\n bStack.pop();\n return true;\n}\n\nfunction unwrap(a) {\n if (isObservableArray(a)) {\n return a.slice();\n }\n\n if (isES6Map(a) || isObservableMap(a)) {\n return Array.from(a.entries());\n }\n\n if (isES6Set(a) || isObservableSet(a)) {\n return Array.from(a.entries());\n }\n\n return a;\n}\n\nfunction makeIterable(iterator) {\n iterator[Symbol.iterator] = getSelf;\n return iterator;\n}\n\nfunction getSelf() {\n return this;\n}\n\nfunction isAnnotation(thing) {\n return (// Can be function\n thing instanceof Object && typeof thing.annotationType_ === \"string\" && isFunction(thing.make_) && isFunction(thing.extend_)\n );\n}\n\n/**\r\n * (c) Michel Weststrate 2015 - 2020\r\n * MIT Licensed\r\n *\r\n * Welcome to the mobx sources! To get a global overview of how MobX internally works,\r\n * this is a good place to start:\r\n * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74\r\n *\r\n * Source folders:\r\n * ===============\r\n *\r\n * - api/ Most of the public static methods exposed by the module can be found here.\r\n * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.\r\n * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.\r\n * - utils/ Utility stuff.\r\n *\r\n */\n[\"Symbol\", \"Map\", \"Set\"].forEach(function (m) {\n var g = getGlobal();\n\n if (typeof g[m] === \"undefined\") {\n die(\"MobX requires global '\" + m + \"' to be available or polyfilled\");\n }\n});\n\nif (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === \"object\") {\n // See: https://github.com/andykog/mobx-devtools/\n __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({\n spy: spy,\n extras: {\n getDebugName: getDebugName\n },\n $mobx: $mobx\n });\n}\n\n\n//# sourceMappingURL=mobx.esm.js.map\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../sgmf-scripts/node_modules/webpack/buildin/global.js */ \"./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/mobx/dist/mobx.esm.js?"); + +/***/ }), + +/***/ "./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js": +/*!***********************************!*\ + !*** (webpack)/buildin/global.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +eval("var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n\n\n//# sourceURL=webpack:///(webpack)/buildin/global.js?"); + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayExpressPart2.js b/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayExpressPart2.js new file mode 100644 index 000000000..722e99c3d --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/static/default/js/amazonPayExpressPart2.js @@ -0,0 +1,101 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js": +/*!****************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js ***! + \****************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nfunction saveShopperDetails(details) {\n $.ajax({\n url: window.saveShopperDetailsURL,\n type: 'post',\n data: {\n shopperDetails: JSON.stringify(details),\n paymentMethod: 'amazonpay'\n },\n success: function success(data) {\n var select = document.querySelector('#shippingMethods');\n select.innerHTML = '';\n data.shippingMethods.forEach(function (shippingMethod) {\n var option = document.createElement('option');\n option.setAttribute('data-shipping-id', shippingMethod.ID);\n option.innerText = \"\".concat(shippingMethod.displayName, \" (\").concat(shippingMethod.estimatedArrivalTime, \")\");\n select.appendChild(option);\n });\n select.options[0].selected = true;\n select.dispatchEvent(new Event('change'));\n }\n });\n}\nfunction constructAddress(shopperDetails) {\n var addressKeys = Object.keys(shopperDetails.shippingAddress);\n var addressValues = Object.values(shopperDetails.shippingAddress);\n var addressStr = \"\".concat(shopperDetails.shippingAddress.name, \"\\n\");\n for (var i = 0; i < addressKeys.length; i += 1) {\n if (addressValues[i] && addressKeys[i] !== 'name') {\n addressStr += \"\".concat(addressValues[i], \" \");\n }\n }\n return addressStr;\n}\nfunction positionElementBefore(elm) {\n var addressDetails = document.querySelector('#amazonPayAddressDetails');\n var containerNode = addressDetails.parentNode.parentNode.parentNode;\n containerNode.insertBefore(addressDetails, document.querySelector(elm));\n}\nfunction wrapChangeAddressButton() {\n // hide component button and use custom \"Edit\" buttons instead\n var changeDetailsBtn = document.getElementsByClassName('adyen-checkout__button adyen-checkout__button--ghost adyen-checkout__amazonpay__button--changeAddress')[0];\n changeDetailsBtn.classList.add('invisible');\n var editAddressBtns = document.querySelectorAll('.editAddressBtn');\n editAddressBtns.forEach(function (btn) {\n btn.addEventListener('click', function () {\n changeDetailsBtn.click();\n });\n });\n}\nfunction showAddressDetails(shopperDetails) {\n var addressText = constructAddress(shopperDetails);\n var addressElement = document.querySelector('#address');\n var paymentDiscriptorElement = document.querySelector('#paymentStr');\n addressElement.innerText = addressText;\n paymentDiscriptorElement.innerText = shopperDetails.paymentDescriptor;\n positionElementBefore('.coupons-and-promos');\n wrapChangeAddressButton();\n var payBtn = document.getElementsByClassName('adyen-checkout__button adyen-checkout__button--standalone adyen-checkout__button--pay')[0];\n payBtn.style.background = '#00a1e0';\n}\nfunction mountAmazonPayComponent() {\n return _mountAmazonPayComponent.apply(this, arguments);\n}\nfunction _mountAmazonPayComponent() {\n _mountAmazonPayComponent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n var amazonPayNode, checkout, amazonConfig, amazonPayComponent, shopperDetails;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n amazonPayNode = document.getElementById('amazon-container');\n _context.next = 3;\n return AdyenCheckout(window.Configuration);\n case 3:\n checkout = _context.sent;\n _context.prev = 4;\n amazonConfig = {\n showOrderButton: true,\n returnUrl: window.returnUrl,\n showChangePaymentDetailsButton: true,\n amount: JSON.parse(window.basketAmount),\n amazonCheckoutSessionId: window.amazonCheckoutSessionId\n };\n amazonPayComponent = checkout.create('amazonpay', amazonConfig).mount(amazonPayNode);\n _context.next = 9;\n return amazonPayComponent.getShopperDetails();\n case 9:\n shopperDetails = _context.sent;\n saveShopperDetails(shopperDetails);\n showAddressDetails(shopperDetails);\n _context.next = 16;\n break;\n case 14:\n _context.prev = 14;\n _context.t0 = _context[\"catch\"](4);\n case 16:\n case \"end\":\n return _context.stop();\n }\n }, _callee, null, [[4, 14]]);\n }));\n return _mountAmazonPayComponent.apply(this, arguments);\n}\nmountAmazonPayComponent();\nmodule.exports = saveShopperDetails;\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js?"); + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/static/default/js/applePayExpress.js b/cartridges/int_adyen_SFRA/cartridge/static/default/js/applePayExpress.js new file mode 100644 index 000000000..7447fd87e --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/static/default/js/applePayExpress.js @@ -0,0 +1,172 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./cartridges/int_adyen_SFRA/cartridge/client/default/js/applePayExpress.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js": +/*!*****************************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js ***! + \*****************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nvar constants = __webpack_require__(/*! ../constants */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js\");\nfunction assignPaymentMethodValue() {\n var adyenPaymentMethod = document.querySelector('#adyenPaymentMethodName');\n // if currently selected paymentMethod contains a brand it will be part of the label ID\n var paymentMethodlabelId = \"#lb_\".concat(store.selectedMethod);\n if (adyenPaymentMethod) {\n var _document$querySelect;\n adyenPaymentMethod.value = store.brand ? store.brand : (_document$querySelect = document.querySelector(paymentMethodlabelId)) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.innerHTML;\n }\n}\nfunction setOrderFormData(response) {\n if (response.orderNo) {\n document.querySelector('#merchantReference').value = response.orderNo;\n }\n if (response.orderToken) {\n document.querySelector('#orderToken').value = response.orderToken;\n }\n}\n\n/**\n * Makes an ajax call to the controller function PaymentFromComponent.\n * Used by certain payment methods like paypal\n */\nfunction paymentFromComponent(data) {\n var component = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var requestData = store.partialPaymentsOrderObj ? _objectSpread(_objectSpread({}, data), {}, {\n partialPaymentsOrder: store.partialPaymentsOrderObj\n }) : data;\n $.ajax({\n url: window.paymentFromComponentURL,\n type: 'post',\n data: {\n data: JSON.stringify(requestData),\n paymentMethod: document.querySelector('#adyenPaymentMethodName').value\n },\n success: function success(response) {\n var _response$fullRespons;\n setOrderFormData(response);\n if ((_response$fullRespons = response.fullResponse) !== null && _response$fullRespons !== void 0 && _response$fullRespons.action) {\n component.handleAction(response.fullResponse.action);\n } else if (response.skipSummaryPage) {\n document.querySelector('#result').value = JSON.stringify(response);\n document.querySelector('#showConfirmationForm').submit();\n } else if (response.paymentError || response.error) {\n component.handleError();\n }\n }\n });\n}\nfunction resetPaymentMethod() {\n $('#requiredBrandCode').hide();\n $('#selectedIssuer').val('');\n $('#adyenIssuerName').val('');\n $('#dateOfBirth').val('');\n $('#telephoneNumber').val('');\n $('#gender').val('');\n $('#bankAccountOwnerName').val('');\n $('#bankAccountNumber').val('');\n $('#bankLocationId').val('');\n $('.additionalFields').hide();\n}\n\n/**\n * Changes the \"display\" attribute of the selected method from hidden to visible\n */\nfunction displaySelectedMethod(type) {\n var _document$querySelect2;\n // If 'type' input field is present use this as type, otherwise default to function input param\n store.selectedMethod = document.querySelector(\"#component_\".concat(type, \" .type\")) ? document.querySelector(\"#component_\".concat(type, \" .type\")).value : type;\n resetPaymentMethod();\n var disabledSubmitButtonMethods = constants.DISABLED_SUBMIT_BUTTON_METHODS;\n if (window.klarnaWidgetEnabled) {\n disabledSubmitButtonMethods.push('klarna');\n }\n document.querySelector('button[value=\"submit-payment\"]').disabled = disabledSubmitButtonMethods.findIndex(function (pm) {\n return type.includes(pm);\n }) > -1;\n document.querySelector(\"#component_\".concat(type)).setAttribute('style', 'display:block');\n // set brand for giftcards if hidden inputfield is present\n store.brand = (_document$querySelect2 = document.querySelector(\"#component_\".concat(type, \" .brand\"))) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value;\n}\nfunction displayValidationErrors() {\n store.selectedPayment.node.showValidation();\n return false;\n}\nvar selectedMethods = {};\nfunction doCustomValidation() {\n return store.selectedMethod in selectedMethods ? selectedMethods[store.selectedMethod]() : true;\n}\nfunction showValidation() {\n return store.selectedPaymentIsValid ? doCustomValidation() : displayValidationErrors();\n}\nfunction getInstallmentValues(maxValue) {\n var values = [];\n for (var i = 1; i <= maxValue; i += 1) {\n values.push(i);\n }\n return values;\n}\nfunction createShowConfirmationForm(action) {\n if (document.querySelector('#showConfirmationForm')) {\n return;\n }\n var template = document.createElement('template');\n var form = \"
            \\n \\n \\n \\n \\n
            \");\n template.innerHTML = form;\n document.querySelector('body').appendChild(template.content);\n}\nmodule.exports = {\n setOrderFormData: setOrderFormData,\n assignPaymentMethodValue: assignPaymentMethodValue,\n paymentFromComponent: paymentFromComponent,\n resetPaymentMethod: resetPaymentMethod,\n displaySelectedMethod: displaySelectedMethod,\n showValidation: showValidation,\n createShowConfirmationForm: createShowConfirmationForm,\n getInstallmentValues: getInstallmentValues\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/applePayExpress.js": +/*!**********************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/applePayExpress.js ***! + \**********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction 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); } }\nfunction _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); }); }; }\nvar helpers = __webpack_require__(/*! ./adyen_checkout/helpers */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/adyen_checkout/helpers.js\");\nvar _require = __webpack_require__(/*! ./commons/index */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js\"),\n checkIfExpressMethodsAreReady = _require.checkIfExpressMethodsAreReady;\nvar _require2 = __webpack_require__(/*! ./commons */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js\"),\n updateLoadedExpressMethods = _require2.updateLoadedExpressMethods;\nvar _require3 = __webpack_require__(/*! ./constants */ \"./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js\"),\n APPLE_PAY = _require3.APPLE_PAY;\nvar checkout;\nvar shippingMethodsData;\nfunction initializeCheckout() {\n return _initializeCheckout.apply(this, arguments);\n}\nfunction _initializeCheckout() {\n _initializeCheckout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {\n var session, sessionData, shippingMethods;\n return _regeneratorRuntime().wrap(function _callee5$(_context5) {\n while (1) switch (_context5.prev = _context5.next) {\n case 0:\n _context5.next = 2;\n return fetch(window.sessionsUrl);\n case 2:\n session = _context5.sent;\n _context5.next = 5;\n return session.json();\n case 5:\n sessionData = _context5.sent;\n _context5.next = 8;\n return fetch(window.shippingMethodsUrl);\n case 8:\n shippingMethods = _context5.sent;\n _context5.next = 11;\n return shippingMethods.json();\n case 11:\n shippingMethodsData = _context5.sent;\n _context5.next = 14;\n return AdyenCheckout({\n environment: window.environment,\n clientKey: window.clientKey,\n locale: window.locale,\n session: sessionData\n });\n case 14:\n checkout = _context5.sent;\n case 15:\n case \"end\":\n return _context5.stop();\n }\n }, _callee5);\n }));\n return _initializeCheckout.apply(this, arguments);\n}\nfunction createApplePayButton(_x) {\n return _createApplePayButton.apply(this, arguments);\n}\nfunction _createApplePayButton() {\n _createApplePayButton = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(applePayButtonConfig) {\n return _regeneratorRuntime().wrap(function _callee6$(_context6) {\n while (1) switch (_context6.prev = _context6.next) {\n case 0:\n return _context6.abrupt(\"return\", checkout.create(APPLE_PAY, applePayButtonConfig));\n case 1:\n case \"end\":\n return _context6.stop();\n }\n }, _callee6);\n }));\n return _createApplePayButton.apply(this, arguments);\n}\nfunction formatCustomerObject(customerData, billingData) {\n return {\n addressBook: {\n addresses: {},\n preferredAddress: {\n address1: customerData.addressLines[0],\n address2: customerData.addressLines.length > 1 ? customerData.addressLines[1] : null,\n city: customerData.locality,\n countryCode: {\n displayValue: customerData.country,\n value: customerData.countryCode\n },\n firstName: customerData.givenName,\n lastName: customerData.familyName,\n ID: customerData.emailAddress,\n postalCode: customerData.postalCode,\n stateCode: customerData.administrativeArea\n }\n },\n billingAddressDetails: {\n address1: billingData.addressLines[0],\n address2: billingData.addressLines.length > 1 ? billingData.addressLines[1] : null,\n city: billingData.locality,\n countryCode: {\n displayValue: billingData.country,\n value: billingData.countryCode\n },\n firstName: billingData.givenName,\n lastName: billingData.familyName,\n postalCode: billingData.postalCode,\n stateCode: billingData.administrativeArea\n },\n customer: {},\n profile: {\n firstName: customerData.givenName,\n lastName: customerData.familyName,\n email: customerData.emailAddress,\n phone: customerData.phoneNumber\n }\n };\n}\nfunction handleAuthorised(response, resolveApplePay) {\n var _response$fullRespons, _response$fullRespons2, _response$fullRespons3, _response$fullRespons4, _response$fullRespons5;\n resolveApplePay();\n document.querySelector('#result').value = JSON.stringify({\n pspReference: (_response$fullRespons = response.fullResponse) === null || _response$fullRespons === void 0 ? void 0 : _response$fullRespons.pspReference,\n resultCode: (_response$fullRespons2 = response.fullResponse) === null || _response$fullRespons2 === void 0 ? void 0 : _response$fullRespons2.resultCode,\n paymentMethod: (_response$fullRespons3 = response.fullResponse) !== null && _response$fullRespons3 !== void 0 && _response$fullRespons3.paymentMethod ? response.fullResponse.paymentMethod : (_response$fullRespons4 = response.fullResponse) === null || _response$fullRespons4 === void 0 ? void 0 : (_response$fullRespons5 = _response$fullRespons4.additionalData) === null || _response$fullRespons5 === void 0 ? void 0 : _response$fullRespons5.paymentMethod\n });\n document.querySelector('#showConfirmationForm').submit();\n}\nfunction handleError(rejectApplePay) {\n rejectApplePay();\n document.querySelector('#result').value = JSON.stringify({\n error: true\n });\n document.querySelector('#showConfirmationForm').submit();\n}\nfunction handleApplePayResponse(response, resolveApplePay, rejectApplePay) {\n if (response.resultCode === 'Authorised') {\n handleAuthorised(response, resolveApplePay);\n } else {\n handleError(rejectApplePay);\n }\n}\nfunction callPaymentFromComponent(data, resolveApplePay, rejectApplePay) {\n return $.ajax({\n url: window.paymentFromComponentURL,\n type: 'post',\n data: {\n data: JSON.stringify(data),\n paymentMethod: APPLE_PAY\n },\n success: function success(response) {\n helpers.createShowConfirmationForm(window.showConfirmationAction);\n helpers.setOrderFormData(response);\n document.querySelector('#additionalDetailsHidden').value = JSON.stringify(data);\n handleApplePayResponse(response, resolveApplePay, rejectApplePay);\n }\n }).fail(function () {\n rejectApplePay();\n });\n}\ninitializeCheckout().then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {\n var applePayPaymentMethod, applePayConfig, applePayButtonConfig, cartContainer, applePayButton, isApplePayButtonAvailable, expressCheckoutNodesIndex;\n return _regeneratorRuntime().wrap(function _callee4$(_context4) {\n while (1) switch (_context4.prev = _context4.next) {\n case 0:\n applePayPaymentMethod = checkout.paymentMethodsResponse.paymentMethods.find(function (pm) {\n return pm.type === APPLE_PAY;\n });\n if (applePayPaymentMethod) {\n _context4.next = 5;\n break;\n }\n updateLoadedExpressMethods(APPLE_PAY);\n checkIfExpressMethodsAreReady();\n return _context4.abrupt(\"return\");\n case 5:\n applePayConfig = applePayPaymentMethod.configuration;\n applePayButtonConfig = {\n showPayButton: true,\n configuration: applePayConfig,\n amount: checkout.options.amount,\n requiredShippingContactFields: ['postalAddress', 'email', 'phone'],\n requiredBillingContactFields: ['postalAddress', 'phone'],\n shippingMethods: shippingMethodsData.shippingMethods.map(function (sm) {\n return {\n label: sm.displayName,\n detail: sm.description,\n identifier: sm.ID,\n amount: \"\".concat(sm.shippingCost.value)\n };\n }),\n onAuthorized: function () {\n var _onAuthorized = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(resolve, reject, event) {\n var customerData, billingData, customer, stateData, resolveApplePay;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n _context.prev = 0;\n customerData = event.payment.shippingContact;\n billingData = event.payment.billingContact;\n customer = formatCustomerObject(customerData, billingData);\n stateData = {\n paymentMethod: {\n type: APPLE_PAY,\n applePayToken: event.payment.token.paymentData\n },\n paymentType: 'express'\n };\n resolveApplePay = function resolveApplePay() {\n // ** is used instead of Math.pow\n var value = applePayButtonConfig.amount.value * Math.pow(10, parseInt(window.digitsNumber, 10));\n var finalPriceUpdate = {\n newTotal: {\n type: 'final',\n label: applePayConfig.merchantName,\n amount: \"\".concat(Math.round(value))\n }\n };\n resolve(finalPriceUpdate);\n };\n _context.next = 8;\n return callPaymentFromComponent(_objectSpread(_objectSpread({}, stateData), {}, {\n customer: customer\n }), resolveApplePay, reject);\n case 8:\n _context.next = 13;\n break;\n case 10:\n _context.prev = 10;\n _context.t0 = _context[\"catch\"](0);\n reject(_context.t0);\n case 13:\n case \"end\":\n return _context.stop();\n }\n }, _callee, null, [[0, 10]]);\n }));\n function onAuthorized(_x2, _x3, _x4) {\n return _onAuthorized.apply(this, arguments);\n }\n return onAuthorized;\n }(),\n onSubmit: function onSubmit() {\n // This handler is empty to prevent sending a second payment request\n // We already do the payment in paymentFromComponent\n },\n onShippingMethodSelected: function () {\n var _onShippingMethodSelected = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(resolve, reject, event) {\n var shippingMethod, matchingShippingMethod, calculationResponse, newCalculation, applePayShippingMethodUpdate;\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n shippingMethod = event.shippingMethod;\n matchingShippingMethod = shippingMethodsData.shippingMethods.find(function (sm) {\n return sm.ID === shippingMethod.identifier;\n });\n _context2.next = 4;\n return fetch(\"\".concat(window.calculateAmountUrl, \"?\").concat(new URLSearchParams({\n shipmentUUID: matchingShippingMethod.shipmentUUID,\n methodID: matchingShippingMethod.ID\n })), {\n method: 'POST'\n });\n case 4:\n calculationResponse = _context2.sent;\n if (!calculationResponse.ok) {\n _context2.next = 14;\n break;\n }\n _context2.next = 8;\n return calculationResponse.json();\n case 8:\n newCalculation = _context2.sent;\n applePayButtonConfig.amount = {\n value: newCalculation.grandTotalAmount.value,\n currency: newCalculation.grandTotalAmount.currency\n };\n applePayShippingMethodUpdate = {\n newTotal: {\n type: 'final',\n label: applePayConfig.merchantName,\n amount: newCalculation.grandTotalAmount.value\n }\n };\n resolve(applePayShippingMethodUpdate);\n _context2.next = 15;\n break;\n case 14:\n reject();\n case 15:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n function onShippingMethodSelected(_x5, _x6, _x7) {\n return _onShippingMethodSelected.apply(this, arguments);\n }\n return onShippingMethodSelected;\n }(),\n onShippingContactSelected: function () {\n var _onShippingContactSelected = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(resolve, reject, event) {\n var shippingContact, shippingMethods, _shippingMethodsData$, selectedShippingMethod, calculationResponse, shippingMethodsStructured, newCalculation, applePayShippingContactUpdate;\n return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n while (1) switch (_context3.prev = _context3.next) {\n case 0:\n shippingContact = event.shippingContact;\n _context3.next = 3;\n return fetch(\"\".concat(window.shippingMethodsUrl, \"?\").concat(new URLSearchParams({\n city: shippingContact.locality,\n country: shippingContact.country,\n countryCode: shippingContact.countryCode,\n stateCode: shippingContact.administrativeArea\n })));\n case 3:\n shippingMethods = _context3.sent;\n if (!shippingMethods.ok) {\n _context3.next = 28;\n break;\n }\n _context3.next = 7;\n return shippingMethods.json();\n case 7:\n shippingMethodsData = _context3.sent;\n if (!((_shippingMethodsData$ = shippingMethodsData.shippingMethods) !== null && _shippingMethodsData$ !== void 0 && _shippingMethodsData$.length)) {\n _context3.next = 25;\n break;\n }\n selectedShippingMethod = shippingMethodsData.shippingMethods[0];\n _context3.next = 12;\n return fetch(\"\".concat(window.calculateAmountUrl, \"?\").concat(new URLSearchParams({\n shipmentUUID: selectedShippingMethod.shipmentUUID,\n methodID: selectedShippingMethod.ID\n })), {\n method: 'POST'\n });\n case 12:\n calculationResponse = _context3.sent;\n if (!calculationResponse.ok) {\n _context3.next = 22;\n break;\n }\n shippingMethodsStructured = shippingMethodsData.shippingMethods.map(function (sm) {\n return {\n label: sm.displayName,\n detail: sm.description,\n identifier: sm.ID,\n amount: \"\".concat(sm.shippingCost.value)\n };\n });\n _context3.next = 17;\n return calculationResponse.json();\n case 17:\n newCalculation = _context3.sent;\n applePayShippingContactUpdate = {\n newShippingMethods: shippingMethodsStructured,\n newTotal: {\n type: 'final',\n label: applePayConfig.merchantName,\n amount: newCalculation.grandTotalAmount.value\n }\n };\n resolve(applePayShippingContactUpdate);\n _context3.next = 23;\n break;\n case 22:\n reject();\n case 23:\n _context3.next = 26;\n break;\n case 25:\n reject();\n case 26:\n _context3.next = 29;\n break;\n case 28:\n reject();\n case 29:\n case \"end\":\n return _context3.stop();\n }\n }, _callee3);\n }));\n function onShippingContactSelected(_x8, _x9, _x10) {\n return _onShippingContactSelected.apply(this, arguments);\n }\n return onShippingContactSelected;\n }()\n };\n cartContainer = document.getElementsByClassName(APPLE_PAY);\n _context4.next = 10;\n return createApplePayButton(applePayButtonConfig);\n case 10:\n applePayButton = _context4.sent;\n _context4.next = 13;\n return applePayButton.isAvailable();\n case 13:\n isApplePayButtonAvailable = _context4.sent;\n if (isApplePayButtonAvailable) {\n for (expressCheckoutNodesIndex = 0; expressCheckoutNodesIndex < cartContainer.length; expressCheckoutNodesIndex += 1) {\n applePayButton.mount(cartContainer[expressCheckoutNodesIndex]);\n }\n }\n updateLoadedExpressMethods(APPLE_PAY);\n checkIfExpressMethodsAreReady();\n case 17:\n case \"end\":\n return _context4.stop();\n }\n }, _callee4);\n})))[\"catch\"](function () {\n updateLoadedExpressMethods(APPLE_PAY);\n checkIfExpressMethodsAreReady();\n});\nmodule.exports = {\n handleAuthorised: handleAuthorised,\n handleError: handleError,\n handleApplePayResponse: handleApplePayResponse,\n callPaymentFromComponent: callPaymentFromComponent\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/applePayExpress.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js": +/*!********************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, \"_invoke\", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 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) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, 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; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), 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 (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\nfunction 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); } }\nfunction _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); }); }; }\nvar store = __webpack_require__(/*! ../../../../store */ \"./cartridges/int_adyen_SFRA/cartridge/store/index.js\");\nmodule.exports.onFieldValid = function onFieldValid(data) {\n if (data.endDigits) {\n store.endDigits = data.endDigits;\n document.querySelector('#cardNumber').value = store.maskedCardNumber;\n }\n};\nmodule.exports.onBrand = function onBrand(brandObject) {\n document.querySelector('#cardType').value = brandObject.brand;\n};\n\n/**\n * Makes an ajax call to the controller function CreateSession\n */\nmodule.exports.createSession = /*#__PURE__*/function () {\n var _createSession = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n return _context.abrupt(\"return\", $.ajax({\n url: window.sessionsUrl,\n type: 'get'\n }));\n case 1:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n function createSession() {\n return _createSession.apply(this, arguments);\n }\n return createSession;\n}();\n\n/**\n * Makes an ajax call to the controller function FetchGiftCards\n */\nmodule.exports.fetchGiftCards = /*#__PURE__*/function () {\n var _fetchGiftCards = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n return _context2.abrupt(\"return\", $.ajax({\n url: window.fetchGiftCardsUrl,\n type: 'get'\n }));\n case 1:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2);\n }));\n function fetchGiftCards() {\n return _fetchGiftCards.apply(this, arguments);\n }\n return fetchGiftCards;\n}();\nmodule.exports.checkIfExpressMethodsAreReady = function checkIfExpressMethodsAreReady() {\n var expressMethodsConfig = {\n applepay: window.isApplePayExpressEnabled === 'true',\n amazonpay: window.isAmazonPayExpressEnabled === 'true'\n };\n var enabledExpressMethods = [];\n Object.keys(expressMethodsConfig).forEach(function (key) {\n if (expressMethodsConfig[key]) {\n enabledExpressMethods.push(key);\n }\n });\n enabledExpressMethods = enabledExpressMethods.sort();\n var loadedExpressMethods = window.loadedExpressMethods && window.loadedExpressMethods.length ? window.loadedExpressMethods.sort() : [];\n var areAllMethodsReady = JSON.stringify(enabledExpressMethods) === JSON.stringify(loadedExpressMethods);\n if (!enabledExpressMethods.length || areAllMethodsReady) {\n var _document$getElementB, _document$getElementB2;\n (_document$getElementB = document.getElementById('express-loader-container')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.classList.add('hidden');\n (_document$getElementB2 = document.getElementById('express-container')) === null || _document$getElementB2 === void 0 ? void 0 : _document$getElementB2.classList.remove('hidden');\n }\n};\nmodule.exports.updateLoadedExpressMethods = function updateLoadedExpressMethods(method) {\n if (!window.loadedExpressMethods) {\n window.loadedExpressMethods = [];\n }\n if (!window.loadedExpressMethods.includes(method)) {\n window.loadedExpressMethods.push(method);\n }\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/commons/index.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js": +/*!****************************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js ***! + \****************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\n// Adyen constants\n\nmodule.exports = {\n METHOD_ADYEN: 'Adyen',\n METHOD_ADYEN_POS: 'AdyenPOS',\n METHOD_ADYEN_COMPONENT: 'AdyenComponent',\n RECEIVED: 'Received',\n NOTENOUGHBALANCE: 'NotEnoughBalance',\n SUCCESS: 'Success',\n GIFTCARD: 'giftcard',\n GIROPAY: 'giropay',\n APPLE_PAY: 'applepay',\n ACTIONTYPE: {\n QRCODE: 'qrCode'\n },\n DISABLED_SUBMIT_BUTTON_METHODS: ['paypal', 'paywithgoogle', 'googlepay', 'amazonpay', 'applepay', 'cashapp'],\n APPLE_DOMAIN_URL: '/.well-known/apple-developer-merchantid-domain-association'\n};\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/client/default/js/constants.js?"); + +/***/ }), + +/***/ "./cartridges/int_adyen_SFRA/cartridge/store/index.js": +/*!************************************************************!*\ + !*** ./cartridges/int_adyen_SFRA/cartridge/store/index.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\nvar _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, _descriptor10, _descriptor11, _descriptor12, _descriptor13;\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }\nfunction _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); }\nvar _require = __webpack_require__(/*! mobx */ \"./node_modules/mobx/dist/mobx.esm.js\"),\n observable = _require.observable,\n computed = _require.computed;\nvar Store = (_class = /*#__PURE__*/function () {\n function Store() {\n _classCallCheck(this, Store);\n _defineProperty(this, \"MASKED_CC_PREFIX\", '************');\n _initializerDefineProperty(this, \"checkout\", _descriptor, this);\n _initializerDefineProperty(this, \"endDigits\", _descriptor2, this);\n _initializerDefineProperty(this, \"selectedMethod\", _descriptor3, this);\n _initializerDefineProperty(this, \"componentsObj\", _descriptor4, this);\n _initializerDefineProperty(this, \"checkoutConfiguration\", _descriptor5, this);\n _initializerDefineProperty(this, \"formErrorsExist\", _descriptor6, this);\n _initializerDefineProperty(this, \"isValid\", _descriptor7, this);\n _initializerDefineProperty(this, \"paypalTerminatedEarly\", _descriptor8, this);\n _initializerDefineProperty(this, \"componentState\", _descriptor9, this);\n _initializerDefineProperty(this, \"brand\", _descriptor10, this);\n _initializerDefineProperty(this, \"partialPaymentsOrderObj\", _descriptor11, this);\n _initializerDefineProperty(this, \"giftCardComponentListenersAdded\", _descriptor12, this);\n _initializerDefineProperty(this, \"addedGiftCards\", _descriptor13, this);\n }\n _createClass(Store, [{\n key: \"maskedCardNumber\",\n get: function get() {\n return \"\".concat(this.MASKED_CC_PREFIX).concat(this.endDigits);\n }\n }, {\n key: \"selectedPayment\",\n get: function get() {\n return this.componentsObj[this.selectedMethod];\n }\n }, {\n key: \"selectedPaymentIsValid\",\n get: function get() {\n var _this$selectedPayment;\n return !!((_this$selectedPayment = this.selectedPayment) !== null && _this$selectedPayment !== void 0 && _this$selectedPayment.isValid);\n }\n }, {\n key: \"stateData\",\n get: function get() {\n var _this$selectedPayment2;\n return ((_this$selectedPayment2 = this.selectedPayment) === null || _this$selectedPayment2 === void 0 ? void 0 : _this$selectedPayment2.stateData) || {\n paymentMethod: _objectSpread({\n type: this.selectedMethod\n }, this.brand ? {\n brand: this.brand\n } : undefined)\n };\n }\n }, {\n key: \"updateSelectedPayment\",\n value: function updateSelectedPayment(method, key, val) {\n this.componentsObj[method][key] = val;\n }\n }]);\n return Store;\n}(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, \"checkout\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, \"endDigits\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, \"selectedMethod\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, \"componentsObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, \"checkoutConfiguration\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return window.Configuration || {};\n }\n}), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, \"formErrorsExist\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, \"isValid\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, \"paypalTerminatedEarly\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return false;\n }\n}), _descriptor9 = _applyDecoratedDescriptor(_class.prototype, \"componentState\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: function initializer() {\n return {};\n }\n}), _descriptor10 = _applyDecoratedDescriptor(_class.prototype, \"brand\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor11 = _applyDecoratedDescriptor(_class.prototype, \"partialPaymentsOrderObj\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor12 = _applyDecoratedDescriptor(_class.prototype, \"giftCardComponentListenersAdded\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor13 = _applyDecoratedDescriptor(_class.prototype, \"addedGiftCards\", [observable], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _applyDecoratedDescriptor(_class.prototype, \"maskedCardNumber\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"maskedCardNumber\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPayment\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPayment\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"selectedPaymentIsValid\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"selectedPaymentIsValid\"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, \"stateData\", [computed], Object.getOwnPropertyDescriptor(_class.prototype, \"stateData\"), _class.prototype)), _class);\nmodule.exports = new Store();\n\n//# sourceURL=webpack:///./cartridges/int_adyen_SFRA/cartridge/store/index.js?"); + +/***/ }), + +/***/ "./node_modules/mobx/dist/mobx.esm.js": +/*!********************************************!*\ + !*** ./node_modules/mobx/dist/mobx.esm.js ***! + \********************************************/ +/*! exports provided: $mobx, FlowCancellationError, ObservableMap, ObservableSet, Reaction, _allowStateChanges, _allowStateChangesInsideComputed, _allowStateReadsEnd, _allowStateReadsStart, _autoAction, _endAction, _getAdministration, _getGlobalState, _interceptReads, _isComputingDerivation, _resetGlobalState, _startAction, action, autorun, comparer, computed, configure, createAtom, defineProperty, entries, extendObservable, flow, flowResult, get, getAtom, getDebugName, getDependencyTree, getObserverTree, has, intercept, isAction, isBoxedObservable, isComputed, isComputedProp, isFlow, isFlowCancellationError, isObservable, isObservableArray, isObservableMap, isObservableObject, isObservableProp, isObservableSet, keys, makeAutoObservable, makeObservable, observable, observe, onBecomeObserved, onBecomeUnobserved, onReactionError, override, ownKeys, reaction, remove, runInAction, set, spy, toJS, trace, transaction, untracked, values, when */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"$mobx\", function() { return $mobx; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"FlowCancellationError\", function() { return FlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableMap\", function() { return ObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ObservableSet\", function() { return ObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Reaction\", function() { return Reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChanges\", function() { return allowStateChanges; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateChangesInsideComputed\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsEnd\", function() { return allowStateReadsEnd; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_allowStateReadsStart\", function() { return allowStateReadsStart; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_autoAction\", function() { return autoAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_endAction\", function() { return _endAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getAdministration\", function() { return getAdministration; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_getGlobalState\", function() { return getGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_interceptReads\", function() { return interceptReads; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_isComputingDerivation\", function() { return isComputingDerivation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_resetGlobalState\", function() { return resetGlobalState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"_startAction\", function() { return _startAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"action\", function() { return action; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"autorun\", function() { return autorun; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"comparer\", function() { return comparer; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"computed\", function() { return computed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"configure\", function() { return configure; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createAtom\", function() { return createAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"defineProperty\", function() { return apiDefineProperty; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"entries\", function() { return entries; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"extendObservable\", function() { return extendObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flow\", function() { return flow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"flowResult\", function() { return flowResult; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"get\", function() { return get; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getAtom\", function() { return getAtom; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDebugName\", function() { return getDebugName; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getDependencyTree\", function() { return getDependencyTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"getObserverTree\", function() { return getObserverTree; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"has\", function() { return has; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"intercept\", function() { return intercept; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isAction\", function() { return isAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isBoxedObservable\", function() { return isObservableValue; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputed\", function() { return isComputed; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isComputedProp\", function() { return isComputedProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlow\", function() { return isFlow; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isFlowCancellationError\", function() { return isFlowCancellationError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservable\", function() { return isObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableArray\", function() { return isObservableArray; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableMap\", function() { return isObservableMap; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableObject\", function() { return isObservableObject; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableProp\", function() { return isObservableProp; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isObservableSet\", function() { return isObservableSet; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"keys\", function() { return keys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeAutoObservable\", function() { return makeAutoObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"makeObservable\", function() { return makeObservable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observable\", function() { return observable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"observe\", function() { return observe; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeObserved\", function() { return onBecomeObserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onBecomeUnobserved\", function() { return onBecomeUnobserved; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"onReactionError\", function() { return onReactionError; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"override\", function() { return override; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ownKeys\", function() { return apiOwnKeys; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"reaction\", function() { return reaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"remove\", function() { return remove; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"runInAction\", function() { return runInAction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"set\", function() { return set; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"spy\", function() { return spy; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"toJS\", function() { return toJS; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"trace\", function() { return trace; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"transaction\", function() { return transaction; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"untracked\", function() { return untracked; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"values\", function() { return values; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"when\", function() { return when; });\nvar niceErrors = {\n 0: \"Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'\",\n 1: function _(annotationType, key) {\n return \"Cannot apply '\" + annotationType + \"' to '\" + key.toString() + \"': Field not found.\";\n },\n\n /*\r\n 2(prop) {\r\n return `invalid decorator for '${prop.toString()}'`\r\n },\r\n 3(prop) {\r\n return `Cannot decorate '${prop.toString()}': action can only be used on properties with a function value.`\r\n },\r\n 4(prop) {\r\n return `Cannot decorate '${prop.toString()}': computed can only be used on getter properties.`\r\n },\r\n */\n 5: \"'keys()' can only be used on observable objects, arrays, sets and maps\",\n 6: \"'values()' can only be used on observable objects, arrays, sets and maps\",\n 7: \"'entries()' can only be used on observable objects, arrays and maps\",\n 8: \"'set()' can only be used on observable objects, arrays and maps\",\n 9: \"'remove()' can only be used on observable objects, arrays and maps\",\n 10: \"'has()' can only be used on observable objects, arrays and maps\",\n 11: \"'get()' can only be used on observable objects, arrays and maps\",\n 12: \"Invalid annotation\",\n 13: \"Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 14: \"Intercept handlers should return nothing or a change object\",\n 15: \"Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)\",\n 16: \"Modification exception: the internal structure of an observable array was changed.\",\n 17: function _(index, length) {\n return \"[mobx.array] Index out of bounds, \" + index + \" is larger than \" + length;\n },\n 18: \"mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js\",\n 19: function _(other) {\n return \"Cannot initialize from classes that inherit from Map: \" + other.constructor.name;\n },\n 20: function _(other) {\n return \"Cannot initialize map from \" + other;\n },\n 21: function _(dataStructure) {\n return \"Cannot convert to map from '\" + dataStructure + \"'\";\n },\n 22: \"mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js\",\n 23: \"It is not possible to get index atoms from arrays\",\n 24: function _(thing) {\n return \"Cannot obtain administration from \" + thing;\n },\n 25: function _(property, name) {\n return \"the entry '\" + property + \"' does not exist in the observable map '\" + name + \"'\";\n },\n 26: \"please specify a property\",\n 27: function _(property, name) {\n return \"no observable property '\" + property.toString() + \"' found on the observable object '\" + name + \"'\";\n },\n 28: function _(thing) {\n return \"Cannot obtain atom from \" + thing;\n },\n 29: \"Expecting some object\",\n 30: \"invalid action stack. did you forget to finish an action?\",\n 31: \"missing option for computed: get\",\n 32: function _(name, derivation) {\n return \"Cycle detected in computation \" + name + \": \" + derivation;\n },\n 33: function _(name) {\n return \"The setter of computed value '\" + name + \"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?\";\n },\n 34: function _(name) {\n return \"[ComputedValue '\" + name + \"'] It is not possible to assign a new value to a computed value.\";\n },\n 35: \"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`\",\n 36: \"isolateGlobalState should be called before MobX is running any reactions\",\n 37: function _(method) {\n return \"[mobx] `observableArray.\" + method + \"()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice().\" + method + \"()` instead\";\n },\n 38: \"'ownKeys()' can only be used on observable objects\",\n 39: \"'defineProperty()' can only be used on observable objects\"\n};\nvar errors = true ? niceErrors : undefined;\nfunction die(error) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n if (true) {\n var e = typeof error === \"string\" ? error : errors[error];\n if (typeof e === \"function\") e = e.apply(null, args);\n throw new Error(\"[MobX] \" + e);\n }\n\n throw new Error(typeof error === \"number\" ? \"[MobX] minified error nr: \" + error + (args.length ? \" \" + args.map(String).join(\",\") : \"\") + \". Find the full error at: https://github.com/mobxjs/mobx/blob/main/packages/mobx/src/errors.ts\" : \"[MobX] \" + error);\n}\n\nvar mockGlobal = {};\nfunction getGlobal() {\n if (typeof globalThis !== \"undefined\") {\n return globalThis;\n }\n\n if (typeof window !== \"undefined\") {\n return window;\n }\n\n if (typeof global !== \"undefined\") {\n return global;\n }\n\n if (typeof self !== \"undefined\") {\n return self;\n }\n\n return mockGlobal;\n}\n\nvar assign = Object.assign;\nvar getDescriptor = Object.getOwnPropertyDescriptor;\nvar defineProperty = Object.defineProperty;\nvar objectPrototype = Object.prototype;\nvar EMPTY_ARRAY = [];\nObject.freeze(EMPTY_ARRAY);\nvar EMPTY_OBJECT = {};\nObject.freeze(EMPTY_OBJECT);\nvar hasProxy = typeof Proxy !== \"undefined\";\nvar plainObjectString = /*#__PURE__*/Object.toString();\nfunction assertProxies() {\n if (!hasProxy) {\n die( true ? \"`Proxy` objects are not available in the current environment. Please configure MobX to enable a fallback implementation.`\" : undefined);\n }\n}\nfunction warnAboutProxyRequirement(msg) {\n if ( true && globalState.verifyProxies) {\n die(\"MobX is currently configured to be able to run in ES5 mode, but in ES5 MobX won't be able to \" + msg);\n }\n}\nfunction getNextId() {\n return ++globalState.mobxGuid;\n}\n/**\r\n * Makes sure that the provided function is invoked at most once.\r\n */\n\nfunction once(func) {\n var invoked = false;\n return function () {\n if (invoked) {\n return;\n }\n\n invoked = true;\n return func.apply(this, arguments);\n };\n}\nvar noop = function noop() {};\nfunction isFunction(fn) {\n return typeof fn === \"function\";\n}\nfunction isStringish(value) {\n var t = typeof value;\n\n switch (t) {\n case \"string\":\n case \"symbol\":\n case \"number\":\n return true;\n }\n\n return false;\n}\nfunction isObject(value) {\n return value !== null && typeof value === \"object\";\n}\nfunction isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n\n var proto = Object.getPrototypeOf(value);\n\n if (proto == null) {\n return true;\n }\n\n var protoConstructor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof protoConstructor === \"function\" && protoConstructor.toString() === plainObjectString;\n} // https://stackoverflow.com/a/37865170\n\nfunction isGenerator(obj) {\n var constructor = obj == null ? void 0 : obj.constructor;\n\n if (!constructor) {\n return false;\n }\n\n if (\"GeneratorFunction\" === constructor.name || \"GeneratorFunction\" === constructor.displayName) {\n return true;\n }\n\n return false;\n}\nfunction addHiddenProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: true,\n configurable: true,\n value: value\n });\n}\nfunction addHiddenFinalProp(object, propName, value) {\n defineProperty(object, propName, {\n enumerable: false,\n writable: false,\n configurable: true,\n value: value\n });\n}\nfunction createInstanceofPredicate(name, theClass) {\n var propName = \"isMobX\" + name;\n theClass.prototype[propName] = true;\n return function (x) {\n return isObject(x) && x[propName] === true;\n };\n}\nfunction isES6Map(thing) {\n return thing instanceof Map;\n}\nfunction isES6Set(thing) {\n return thing instanceof Set;\n}\nvar hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== \"undefined\";\n/**\r\n * Returns the following: own enumerable keys and symbols.\r\n */\n\nfunction getPlainObjectKeys(object) {\n var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway...\n\n if (!hasGetOwnPropertySymbols) {\n return keys;\n }\n\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (!symbols.length) {\n return keys;\n }\n\n return [].concat(keys, symbols.filter(function (s) {\n return objectPrototype.propertyIsEnumerable.call(object, s);\n }));\n} // From Immer utils\n// Returns all own keys, including non-enumerable and symbolic\n\nvar ownKeys = typeof Reflect !== \"undefined\" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) {\n return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));\n} :\n/* istanbul ignore next */\nObject.getOwnPropertyNames;\nfunction stringifyKey(key) {\n if (typeof key === \"string\") {\n return key;\n }\n\n if (typeof key === \"symbol\") {\n return key.toString();\n }\n\n return new String(key).toString();\n}\nfunction toPrimitive(value) {\n return value === null ? null : typeof value === \"object\" ? \"\" + value : value;\n}\nfunction hasProp(target, prop) {\n return objectPrototype.hasOwnProperty.call(target, prop);\n} // From Immer utils\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {\n // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up\n\n ownKeys(target).forEach(function (key) {\n res[key] = getDescriptor(target, key);\n });\n return res;\n};\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nfunction _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n\n _setPrototypeOf(subClass, superClass);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _createForOfIteratorHelperLoose(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n if (it) return (it = it.call(o)).next.bind(it);\n\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n return function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar storedAnnotationsSymbol = /*#__PURE__*/Symbol(\"mobx-stored-annotations\");\n/**\r\n * Creates a function that acts as\r\n * - decorator\r\n * - annotation object\r\n */\n\nfunction createDecoratorAnnotation(annotation) {\n function decorator(target, property) {\n storeAnnotation(target, property, annotation);\n }\n\n return Object.assign(decorator, annotation);\n}\n/**\r\n * Stores annotation to prototype,\r\n * so it can be inspected later by `makeObservable` called from constructor\r\n */\n\nfunction storeAnnotation(prototype, key, annotation) {\n if (!hasProp(prototype, storedAnnotationsSymbol)) {\n addHiddenProp(prototype, storedAnnotationsSymbol, _extends({}, prototype[storedAnnotationsSymbol]));\n } // @override must override something\n\n\n if ( true && isOverride(annotation) && !hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n die(\"'\" + fieldName + \"' is decorated with 'override', \" + \"but no such decorated member was found on prototype.\");\n } // Cannot re-decorate\n\n\n assertNotDecorated(prototype, annotation, key); // Ignore override\n\n if (!isOverride(annotation)) {\n prototype[storedAnnotationsSymbol][key] = annotation;\n }\n}\n\nfunction assertNotDecorated(prototype, annotation, key) {\n if ( true && !isOverride(annotation) && hasProp(prototype[storedAnnotationsSymbol], key)) {\n var fieldName = prototype.constructor.name + \".prototype.\" + key.toString();\n var currentAnnotationType = prototype[storedAnnotationsSymbol][key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '@\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already decorated with '@\" + currentAnnotationType + \"'.\") + \"\\nRe-decorating fields is not allowed.\" + \"\\nUse '@override' decorator for methods overridden by subclass.\");\n }\n}\n/**\r\n * Collects annotations from prototypes and stores them on target (instance)\r\n */\n\n\nfunction collectStoredAnnotations(target) {\n if (!hasProp(target, storedAnnotationsSymbol)) {\n if ( true && !target[storedAnnotationsSymbol]) {\n die(\"No annotations were passed to makeObservable, but no decorated members have been found either\");\n } // We need a copy as we will remove annotation from the list once it's applied.\n\n\n addHiddenProp(target, storedAnnotationsSymbol, _extends({}, target[storedAnnotationsSymbol]));\n }\n\n return target[storedAnnotationsSymbol];\n}\n\nvar $mobx = /*#__PURE__*/Symbol(\"mobx administration\");\nvar Atom = /*#__PURE__*/function () {\n // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed\n\n /**\r\n * Create a new atom. For debugging purposes it is recommended to give it a name.\r\n * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management.\r\n */\n function Atom(name_) {\n if (name_ === void 0) {\n name_ = true ? \"Atom@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.isPendingUnobservation_ = false;\n this.isBeingObserved_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n this.name_ = name_;\n } // onBecomeObservedListeners\n\n\n var _proto = Atom.prototype;\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Invoke this method to notify mobx that your atom has been used somehow.\r\n * Returns true if there is currently a reactive context.\r\n */\n ;\n\n _proto.reportObserved = function reportObserved$1() {\n return reportObserved(this);\n }\n /**\r\n * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.\r\n */\n ;\n\n _proto.reportChanged = function reportChanged() {\n startBatch();\n propagateChanged(this);\n endBatch();\n };\n\n _proto.toString = function toString() {\n return this.name_;\n };\n\n return Atom;\n}();\nvar isAtom = /*#__PURE__*/createInstanceofPredicate(\"Atom\", Atom);\nfunction createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) {\n if (onBecomeObservedHandler === void 0) {\n onBecomeObservedHandler = noop;\n }\n\n if (onBecomeUnobservedHandler === void 0) {\n onBecomeUnobservedHandler = noop;\n }\n\n var atom = new Atom(name); // default `noop` listener will not initialize the hook Set\n\n if (onBecomeObservedHandler !== noop) {\n onBecomeObserved(atom, onBecomeObservedHandler);\n }\n\n if (onBecomeUnobservedHandler !== noop) {\n onBecomeUnobserved(atom, onBecomeUnobservedHandler);\n }\n\n return atom;\n}\n\nfunction identityComparer(a, b) {\n return a === b;\n}\n\nfunction structuralComparer(a, b) {\n return deepEqual(a, b);\n}\n\nfunction shallowComparer(a, b) {\n return deepEqual(a, b, 1);\n}\n\nfunction defaultComparer(a, b) {\n if (Object.is) {\n return Object.is(a, b);\n }\n\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n}\n\nvar comparer = {\n identity: identityComparer,\n structural: structuralComparer,\n \"default\": defaultComparer,\n shallow: shallowComparer\n};\n\nfunction deepEnhancer(v, _, name) {\n // it is an observable already, done\n if (isObservable(v)) {\n return v;\n } // something that can be converted and mutated?\n\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name\n });\n }\n\n if (typeof v === \"function\" && !isAction(v) && !isFlow(v)) {\n if (isGenerator(v)) {\n return flow(v);\n } else {\n return autoAction(name, v);\n }\n }\n\n return v;\n}\nfunction shallowEnhancer(v, _, name) {\n if (v === undefined || v === null) {\n return v;\n }\n\n if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) {\n return v;\n }\n\n if (Array.isArray(v)) {\n return observable.array(v, {\n name: name,\n deep: false\n });\n }\n\n if (isPlainObject(v)) {\n return observable.object(v, undefined, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Map(v)) {\n return observable.map(v, {\n name: name,\n deep: false\n });\n }\n\n if (isES6Set(v)) {\n return observable.set(v, {\n name: name,\n deep: false\n });\n }\n\n if (true) {\n die(\"The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets\");\n }\n}\nfunction referenceEnhancer(newValue) {\n // never turn into an observable\n return newValue;\n}\nfunction refStructEnhancer(v, oldValue) {\n if ( true && isObservable(v)) {\n die(\"observable.struct should not be used with observable values\");\n }\n\n if (deepEqual(v, oldValue)) {\n return oldValue;\n }\n\n return v;\n}\n\nvar OVERRIDE = \"override\";\nvar override = /*#__PURE__*/createDecoratorAnnotation({\n annotationType_: OVERRIDE,\n make_: make_,\n extend_: extend_\n});\nfunction isOverride(annotation) {\n return annotation.annotationType_ === OVERRIDE;\n}\n\nfunction make_(adm, key) {\n // Must not be plain object\n if ( true && adm.isPlainObject_) {\n die(\"Cannot apply '\" + this.annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + this.annotationType_ + \"' cannot be used on plain objects.\"));\n } // Must override something\n\n\n if ( true && !hasProp(adm.appliedAnnotations_, key)) {\n die(\"'\" + adm.name_ + \".\" + key.toString() + \"' is annotated with '\" + this.annotationType_ + \"', \" + \"but no such annotated member was found on prototype.\");\n }\n\n return 0\n /* Cancel */\n ;\n}\n\nfunction extend_(adm, key, descriptor, proxyTrap) {\n die(\"'\" + this.annotationType_ + \"' can only be used with 'makeObservable'\");\n}\n\nfunction createActionAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$1,\n extend_: extend_$1\n };\n}\n\nfunction make_$1(adm, key, descriptor, source) {\n var _this$options_;\n\n // bound\n if ((_this$options_ = this.options_) != null && _this$options_.bound) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n } // own\n\n\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n\n\n if (isAction(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor, false);\n defineProperty(source, key, actionDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$1(adm, key, descriptor, proxyTrap) {\n var actionDescriptor = createActionDescriptor(adm, this, key, descriptor);\n return adm.defineProperty_(key, actionDescriptor, proxyTrap);\n}\n\nfunction assertActionDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a function value.\"));\n }\n}\n\nfunction createActionDescriptor(adm, annotation, key, descriptor, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n var _annotation$options_, _annotation$options_$, _annotation$options_2, _annotation$options_$2, _annotation$options_3, _annotation$options_4, _adm$proxy_2;\n\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertActionDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value;\n\n if ((_annotation$options_ = annotation.options_) != null && _annotation$options_.bound) {\n var _adm$proxy_;\n\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return {\n value: createAction((_annotation$options_$ = (_annotation$options_2 = annotation.options_) == null ? void 0 : _annotation$options_2.name) != null ? _annotation$options_$ : key.toString(), value, (_annotation$options_$2 = (_annotation$options_3 = annotation.options_) == null ? void 0 : _annotation$options_3.autoAction) != null ? _annotation$options_$2 : false, // https://github.com/mobxjs/mobx/discussions/3140\n (_annotation$options_4 = annotation.options_) != null && _annotation$options_4.bound ? (_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_ : undefined),\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createFlowAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$2,\n extend_: extend_$2\n };\n}\n\nfunction make_$2(adm, key, descriptor, source) {\n var _this$options_;\n\n // own\n if (source === adm.target_) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // prototype\n // bound - must annotate protos to support super.flow()\n\n\n if ((_this$options_ = this.options_) != null && _this$options_.bound && (!hasProp(adm.target_, key) || !isFlow(adm.target_[key]))) {\n if (this.extend_(adm, key, descriptor, false) === null) {\n return 0\n /* Cancel */\n ;\n }\n }\n\n if (isFlow(descriptor.value)) {\n // A prototype could have been annotated already by other constructor,\n // rest of the proto chain must be annotated already\n return 1\n /* Break */\n ;\n }\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, false, false);\n defineProperty(source, key, flowDescriptor);\n return 2\n /* Continue */\n ;\n}\n\nfunction extend_$2(adm, key, descriptor, proxyTrap) {\n var _this$options_2;\n\n var flowDescriptor = createFlowDescriptor(adm, this, key, descriptor, (_this$options_2 = this.options_) == null ? void 0 : _this$options_2.bound);\n return adm.defineProperty_(key, flowDescriptor, proxyTrap);\n}\n\nfunction assertFlowDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var value = _ref2.value;\n\n if ( true && !isFunction(value)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on properties with a generator function value.\"));\n }\n}\n\nfunction createFlowDescriptor(adm, annotation, key, descriptor, bound, // provides ability to disable safeDescriptors for prototypes\nsafeDescriptors) {\n if (safeDescriptors === void 0) {\n safeDescriptors = globalState.safeDescriptors;\n }\n\n assertFlowDescriptor(adm, annotation, key, descriptor);\n var value = descriptor.value; // In case of flow.bound, the descriptor can be from already annotated prototype\n\n if (!isFlow(value)) {\n value = flow(value);\n }\n\n if (bound) {\n var _adm$proxy_;\n\n // We do not keep original function around, so we bind the existing flow\n value = value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_); // This is normally set by `flow`, but `bind` returns new function...\n\n value.isMobXFlow = true;\n }\n\n return {\n value: value,\n // Non-configurable for classes\n // prevents accidental field redefinition in subclass\n configurable: safeDescriptors ? adm.isPlainObject_ : true,\n // https://github.com/mobxjs/mobx/pull/2641#issuecomment-737292058\n enumerable: false,\n // Non-obsevable, therefore non-writable\n // Also prevents rewriting in subclass constructor\n writable: safeDescriptors ? false : true\n };\n}\n\nfunction createComputedAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$3,\n extend_: extend_$3\n };\n}\n\nfunction make_$3(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$3(adm, key, descriptor, proxyTrap) {\n assertComputedDescriptor(adm, this, key, descriptor);\n return adm.defineComputedProperty_(key, _extends({}, this.options_, {\n get: descriptor.get,\n set: descriptor.set\n }), proxyTrap);\n}\n\nfunction assertComputedDescriptor(adm, _ref, key, _ref2) {\n var annotationType_ = _ref.annotationType_;\n var get = _ref2.get;\n\n if ( true && !get) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' can only be used on getter(+setter) properties.\"));\n }\n}\n\nfunction createObservableAnnotation(name, options) {\n return {\n annotationType_: name,\n options_: options,\n make_: make_$4,\n extend_: extend_$4\n };\n}\n\nfunction make_$4(adm, key, descriptor) {\n return this.extend_(adm, key, descriptor, false) === null ? 0\n /* Cancel */\n : 1\n /* Break */\n ;\n}\n\nfunction extend_$4(adm, key, descriptor, proxyTrap) {\n var _this$options_$enhanc, _this$options_;\n\n assertObservableDescriptor(adm, this, key, descriptor);\n return adm.defineObservableProperty_(key, descriptor.value, (_this$options_$enhanc = (_this$options_ = this.options_) == null ? void 0 : _this$options_.enhancer) != null ? _this$options_$enhanc : deepEnhancer, proxyTrap);\n}\n\nfunction assertObservableDescriptor(adm, _ref, key, descriptor) {\n var annotationType_ = _ref.annotationType_;\n\n if ( true && !(\"value\" in descriptor)) {\n die(\"Cannot apply '\" + annotationType_ + \"' to '\" + adm.name_ + \".\" + key.toString() + \"':\" + (\"\\n'\" + annotationType_ + \"' cannot be used on getter/setter properties\"));\n }\n}\n\nvar AUTO = \"true\";\nvar autoAnnotation = /*#__PURE__*/createAutoAnnotation();\nfunction createAutoAnnotation(options) {\n return {\n annotationType_: AUTO,\n options_: options,\n make_: make_$5,\n extend_: extend_$5\n };\n}\n\nfunction make_$5(adm, key, descriptor, source) {\n var _this$options_3, _this$options_4;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.make_(adm, key, descriptor, source);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.make_\n var set = createAction(key.toString(), descriptor.set); // own\n\n if (source === adm.target_) {\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: set\n }) === null ? 0\n /* Cancel */\n : 2\n /* Continue */\n ;\n } // proto\n\n\n defineProperty(source, key, {\n configurable: true,\n set: set\n });\n return 2\n /* Continue */\n ;\n } // function on proto -> autoAction/flow\n\n\n if (source !== adm.target_ && typeof descriptor.value === \"function\") {\n var _this$options_2;\n\n if (isGenerator(descriptor.value)) {\n var _this$options_;\n\n var flowAnnotation = (_this$options_ = this.options_) != null && _this$options_.autoBind ? flow.bound : flow;\n return flowAnnotation.make_(adm, key, descriptor, source);\n }\n\n var actionAnnotation = (_this$options_2 = this.options_) != null && _this$options_2.autoBind ? autoAction.bound : autoAction;\n return actionAnnotation.make_(adm, key, descriptor, source);\n } // other -> observable\n // Copy props from proto as well, see test:\n // \"decorate should work with Object.create\"\n\n\n var observableAnnotation = ((_this$options_3 = this.options_) == null ? void 0 : _this$options_3.deep) === false ? observable.ref : observable; // if function respect autoBind option\n\n if (typeof descriptor.value === \"function\" && (_this$options_4 = this.options_) != null && _this$options_4.autoBind) {\n var _adm$proxy_;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_ = adm.proxy_) != null ? _adm$proxy_ : adm.target_);\n }\n\n return observableAnnotation.make_(adm, key, descriptor, source);\n}\n\nfunction extend_$5(adm, key, descriptor, proxyTrap) {\n var _this$options_5, _this$options_6;\n\n // getter -> computed\n if (descriptor.get) {\n return computed.extend_(adm, key, descriptor, proxyTrap);\n } // lone setter -> action setter\n\n\n if (descriptor.set) {\n // TODO make action applicable to setter and delegate to action.extend_\n return adm.defineProperty_(key, {\n configurable: globalState.safeDescriptors ? adm.isPlainObject_ : true,\n set: createAction(key.toString(), descriptor.set)\n }, proxyTrap);\n } // other -> observable\n // if function respect autoBind option\n\n\n if (typeof descriptor.value === \"function\" && (_this$options_5 = this.options_) != null && _this$options_5.autoBind) {\n var _adm$proxy_2;\n\n descriptor.value = descriptor.value.bind((_adm$proxy_2 = adm.proxy_) != null ? _adm$proxy_2 : adm.target_);\n }\n\n var observableAnnotation = ((_this$options_6 = this.options_) == null ? void 0 : _this$options_6.deep) === false ? observable.ref : observable;\n return observableAnnotation.extend_(adm, key, descriptor, proxyTrap);\n}\n\nvar OBSERVABLE = \"observable\";\nvar OBSERVABLE_REF = \"observable.ref\";\nvar OBSERVABLE_SHALLOW = \"observable.shallow\";\nvar OBSERVABLE_STRUCT = \"observable.struct\"; // Predefined bags of create observable options, to avoid allocating temporarily option objects\n// in the majority of cases\n\nvar defaultCreateObservableOptions = {\n deep: true,\n name: undefined,\n defaultDecorator: undefined,\n proxy: true\n};\nObject.freeze(defaultCreateObservableOptions);\nfunction asCreateObservableOptions(thing) {\n return thing || defaultCreateObservableOptions;\n}\nvar observableAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE);\nvar observableRefAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_REF, {\n enhancer: referenceEnhancer\n});\nvar observableShallowAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_SHALLOW, {\n enhancer: shallowEnhancer\n});\nvar observableStructAnnotation = /*#__PURE__*/createObservableAnnotation(OBSERVABLE_STRUCT, {\n enhancer: refStructEnhancer\n});\nvar observableDecoratorAnnotation = /*#__PURE__*/createDecoratorAnnotation(observableAnnotation);\nfunction getEnhancerFromOptions(options) {\n return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator);\n}\nfunction getAnnotationFromOptions(options) {\n var _options$defaultDecor;\n\n return options ? (_options$defaultDecor = options.defaultDecorator) != null ? _options$defaultDecor : createAutoAnnotation(options) : undefined;\n}\nfunction getEnhancerFromAnnotation(annotation) {\n var _annotation$options_$, _annotation$options_;\n\n return !annotation ? deepEnhancer : (_annotation$options_$ = (_annotation$options_ = annotation.options_) == null ? void 0 : _annotation$options_.enhancer) != null ? _annotation$options_$ : deepEnhancer;\n}\n/**\r\n * Turns an object, array or function into a reactive structure.\r\n * @param v the value which should become observable.\r\n */\n\nfunction createObservable(v, arg2, arg3) {\n // @observable someProp;\n if (isStringish(arg2)) {\n storeAnnotation(v, arg2, observableAnnotation);\n return;\n } // already observable - ignore\n\n\n if (isObservable(v)) {\n return v;\n } // plain object\n\n\n if (isPlainObject(v)) {\n return observable.object(v, arg2, arg3);\n } // Array\n\n\n if (Array.isArray(v)) {\n return observable.array(v, arg2);\n } // Map\n\n\n if (isES6Map(v)) {\n return observable.map(v, arg2);\n } // Set\n\n\n if (isES6Set(v)) {\n return observable.set(v, arg2);\n } // other object - ignore\n\n\n if (typeof v === \"object\" && v !== null) {\n return v;\n } // anything else\n\n\n return observable.box(v, arg2);\n}\n\nObject.assign(createObservable, observableDecoratorAnnotation);\nvar observableFactories = {\n box: function box(value, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals);\n },\n array: function array(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOptions(o), o.name);\n },\n map: function map(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name);\n },\n set: function set(initialValues, options) {\n var o = asCreateObservableOptions(options);\n return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name);\n },\n object: function object(props, decorators, options) {\n return extendObservable(globalState.useProxies === false || (options == null ? void 0 : options.proxy) === false ? asObservableObject({}, options) : asDynamicObservableObject({}, options), props, decorators);\n },\n ref: /*#__PURE__*/createDecoratorAnnotation(observableRefAnnotation),\n shallow: /*#__PURE__*/createDecoratorAnnotation(observableShallowAnnotation),\n deep: observableDecoratorAnnotation,\n struct: /*#__PURE__*/createDecoratorAnnotation(observableStructAnnotation)\n}; // eslint-disable-next-line\n\nvar observable = /*#__PURE__*/assign(createObservable, observableFactories);\n\nvar COMPUTED = \"computed\";\nvar COMPUTED_STRUCT = \"computed.struct\";\nvar computedAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED);\nvar computedStructAnnotation = /*#__PURE__*/createComputedAnnotation(COMPUTED_STRUCT, {\n equals: comparer.structural\n});\n/**\r\n * Decorator for class properties: @computed get value() { return expr; }.\r\n * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`;\r\n */\n\nvar computed = function computed(arg1, arg2) {\n if (isStringish(arg2)) {\n // @computed\n return storeAnnotation(arg1, arg2, computedAnnotation);\n }\n\n if (isPlainObject(arg1)) {\n // @computed({ options })\n return createDecoratorAnnotation(createComputedAnnotation(COMPUTED, arg1));\n } // computed(expr, options?)\n\n\n if (true) {\n if (!isFunction(arg1)) {\n die(\"First argument to `computed` should be an expression.\");\n }\n\n if (isFunction(arg2)) {\n die(\"A setter as second argument is no longer supported, use `{ set: fn }` option instead\");\n }\n }\n\n var opts = isPlainObject(arg2) ? arg2 : {};\n opts.get = arg1;\n opts.name || (opts.name = arg1.name || \"\");\n /* for generated name */\n\n return new ComputedValue(opts);\n};\nObject.assign(computed, computedAnnotation);\ncomputed.struct = /*#__PURE__*/createDecoratorAnnotation(computedStructAnnotation);\n\nvar _getDescriptor$config, _getDescriptor;\n// mobx versions\n\nvar currentActionId = 0;\nvar nextActionId = 1;\nvar isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, \"name\")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object\n\nvar tmpNameDescriptor = {\n value: \"action\",\n configurable: true,\n writable: false,\n enumerable: false\n};\nfunction createAction(actionName, fn, autoAction, ref) {\n if (autoAction === void 0) {\n autoAction = false;\n }\n\n if (true) {\n if (!isFunction(fn)) {\n die(\"`action` can only be invoked on functions\");\n }\n\n if (typeof actionName !== \"string\" || !actionName) {\n die(\"actions should have valid names, got: '\" + actionName + \"'\");\n }\n }\n\n function res() {\n return executeAction(actionName, autoAction, fn, ref || this, arguments);\n }\n\n res.isMobxAction = true;\n\n if (isFunctionNameConfigurable) {\n tmpNameDescriptor.value = actionName;\n Object.defineProperty(res, \"name\", tmpNameDescriptor);\n }\n\n return res;\n}\nfunction executeAction(actionName, canRunAsDerivation, fn, scope, args) {\n var runInfo = _startAction(actionName, canRunAsDerivation, scope, args);\n\n try {\n return fn.apply(scope, args);\n } catch (err) {\n runInfo.error_ = err;\n throw err;\n } finally {\n _endAction(runInfo);\n }\n}\nfunction _startAction(actionName, canRunAsDerivation, // true for autoAction\nscope, args) {\n var notifySpy_ = true && isSpyEnabled() && !!actionName;\n var startTime_ = 0;\n\n if ( true && notifySpy_) {\n startTime_ = Date.now();\n var flattenedArgs = args ? Array.from(args) : EMPTY_ARRAY;\n spyReportStart({\n type: ACTION,\n name: actionName,\n object: scope,\n arguments: flattenedArgs\n });\n }\n\n var prevDerivation_ = globalState.trackingDerivation;\n var runAsAction = !canRunAsDerivation || !prevDerivation_;\n startBatch();\n var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow\n\n if (runAsAction) {\n untrackedStart();\n prevAllowStateChanges_ = allowStateChangesStart(true);\n }\n\n var prevAllowStateReads_ = allowStateReadsStart(true);\n var runInfo = {\n runAsAction_: runAsAction,\n prevDerivation_: prevDerivation_,\n prevAllowStateChanges_: prevAllowStateChanges_,\n prevAllowStateReads_: prevAllowStateReads_,\n notifySpy_: notifySpy_,\n startTime_: startTime_,\n actionId_: nextActionId++,\n parentActionId_: currentActionId\n };\n currentActionId = runInfo.actionId_;\n return runInfo;\n}\nfunction _endAction(runInfo) {\n if (currentActionId !== runInfo.actionId_) {\n die(30);\n }\n\n currentActionId = runInfo.parentActionId_;\n\n if (runInfo.error_ !== undefined) {\n globalState.suppressReactionErrors = true;\n }\n\n allowStateChangesEnd(runInfo.prevAllowStateChanges_);\n allowStateReadsEnd(runInfo.prevAllowStateReads_);\n endBatch();\n\n if (runInfo.runAsAction_) {\n untrackedEnd(runInfo.prevDerivation_);\n }\n\n if ( true && runInfo.notifySpy_) {\n spyReportEnd({\n time: Date.now() - runInfo.startTime_\n });\n }\n\n globalState.suppressReactionErrors = false;\n}\nfunction allowStateChanges(allowStateChanges, func) {\n var prev = allowStateChangesStart(allowStateChanges);\n\n try {\n return func();\n } finally {\n allowStateChangesEnd(prev);\n }\n}\nfunction allowStateChangesStart(allowStateChanges) {\n var prev = globalState.allowStateChanges;\n globalState.allowStateChanges = allowStateChanges;\n return prev;\n}\nfunction allowStateChangesEnd(prev) {\n globalState.allowStateChanges = prev;\n}\n\nvar _Symbol$toPrimitive;\nvar CREATE = \"create\";\n_Symbol$toPrimitive = Symbol.toPrimitive;\nvar ObservableValue = /*#__PURE__*/function (_Atom) {\n _inheritsLoose(ObservableValue, _Atom);\n\n function ObservableValue(value, enhancer, name_, notifySpy, equals) {\n var _this;\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableValue@\" + getNextId() : undefined;\n }\n\n if (notifySpy === void 0) {\n notifySpy = true;\n }\n\n if (equals === void 0) {\n equals = comparer[\"default\"];\n }\n\n _this = _Atom.call(this, name_) || this;\n _this.enhancer = void 0;\n _this.name_ = void 0;\n _this.equals = void 0;\n _this.hasUnreportedChange_ = false;\n _this.interceptors_ = void 0;\n _this.changeListeners_ = void 0;\n _this.value_ = void 0;\n _this.dehancer = void 0;\n _this.enhancer = enhancer;\n _this.name_ = name_;\n _this.equals = equals;\n _this.value_ = enhancer(value, undefined, name_);\n\n if ( true && notifySpy && isSpyEnabled()) {\n // only notify spy if this is a stand-alone observable\n spyReport({\n type: CREATE,\n object: _assertThisInitialized(_this),\n observableKind: \"value\",\n debugObjectName: _this.name_,\n newValue: \"\" + _this.value_\n });\n }\n\n return _this;\n }\n\n var _proto = ObservableValue.prototype;\n\n _proto.dehanceValue = function dehanceValue(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.set = function set(newValue) {\n var oldValue = this.value_;\n newValue = this.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n\n if ( true && notifySpy) {\n spyReportStart({\n type: UPDATE,\n object: this,\n observableKind: \"value\",\n debugObjectName: this.name_,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n\n this.setNewValue_(newValue);\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.prepareNewValue_ = function prepareNewValue_(newValue) {\n checkIfStateModificationsAreAllowed(this);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this,\n type: UPDATE,\n newValue: newValue\n });\n\n if (!change) {\n return globalState.UNCHANGED;\n }\n\n newValue = change.newValue;\n } // apply modifier\n\n\n newValue = this.enhancer(newValue, this.value_, this.name_);\n return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue;\n };\n\n _proto.setNewValue_ = function setNewValue_(newValue) {\n var oldValue = this.value_;\n this.value_ = newValue;\n this.reportChanged();\n\n if (hasListeners(this)) {\n notifyListeners(this, {\n type: UPDATE,\n object: this,\n newValue: newValue,\n oldValue: oldValue\n });\n }\n };\n\n _proto.get = function get() {\n this.reportObserved();\n return this.dehanceValue(this.value_);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately) {\n listener({\n observableKind: \"value\",\n debugObjectName: this.name_,\n object: this,\n type: UPDATE,\n newValue: this.value_,\n oldValue: undefined\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.raw = function raw() {\n // used by MST ot get undehanced value\n return this.value_;\n };\n\n _proto.toJSON = function toJSON() {\n return this.get();\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.value_ + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive] = function () {\n return this.valueOf();\n };\n\n return ObservableValue;\n}(Atom);\nvar isObservableValue = /*#__PURE__*/createInstanceofPredicate(\"ObservableValue\", ObservableValue);\n\nvar _Symbol$toPrimitive$1;\n/**\r\n * A node in the state dependency root that observes other nodes, and can be observed itself.\r\n *\r\n * ComputedValue will remember the result of the computation for the duration of the batch, or\r\n * while being observed.\r\n *\r\n * During this time it will recompute only when one of its direct dependencies changed,\r\n * but only when it is being accessed with `ComputedValue.get()`.\r\n *\r\n * Implementation description:\r\n * 1. First time it's being accessed it will compute and remember result\r\n * give back remembered result until 2. happens\r\n * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.\r\n * 3. When it's being accessed, recompute if any shallow dependency changed.\r\n * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.\r\n * go to step 2. either way\r\n *\r\n * If at any point it's outside batch and it isn't observed: reset everything and go to 1.\r\n */\n\n_Symbol$toPrimitive$1 = Symbol.toPrimitive;\nvar ComputedValue = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n // during tracking it's an array with new observed observers\n // to check for cycles\n // N.B: unminified as it is used by MST\n\n /**\r\n * Create a new computed value based on a function expression.\r\n *\r\n * The `name` property is for debug purposes only.\r\n *\r\n * The `equals` property specifies the comparer function to use to determine if a newly produced\r\n * value differs from the previous value. Two comparers are provided in the library; `defaultComparer`\r\n * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure.\r\n * Structural comparison can be convenient if you always produce a new aggregated object and\r\n * don't want to notify observers if it is structurally the same.\r\n * This is useful for working with vectors, mouse coordinates etc.\r\n */\n function ComputedValue(options) {\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.observing_ = [];\n this.newObserving_ = null;\n this.isBeingObserved_ = false;\n this.isPendingUnobservation_ = false;\n this.observers_ = new Set();\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.lastAccessedBy_ = 0;\n this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n this.unboundDepsCount_ = 0;\n this.value_ = new CaughtException(null);\n this.name_ = void 0;\n this.triggeredBy_ = void 0;\n this.isComputing_ = false;\n this.isRunningSetter_ = false;\n this.derivation = void 0;\n this.setter_ = void 0;\n this.isTracing_ = TraceMode.NONE;\n this.scope_ = void 0;\n this.equals_ = void 0;\n this.requiresReaction_ = void 0;\n this.keepAlive_ = void 0;\n this.onBOL = void 0;\n this.onBUOL = void 0;\n\n if (!options.get) {\n die(31);\n }\n\n this.derivation = options.get;\n this.name_ = options.name || ( true ? \"ComputedValue@\" + getNextId() : undefined);\n\n if (options.set) {\n this.setter_ = createAction( true ? this.name_ + \"-setter\" : undefined, options.set);\n }\n\n this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer[\"default\"]);\n this.scope_ = options.context;\n this.requiresReaction_ = options.requiresReaction;\n this.keepAlive_ = !!options.keepAlive;\n }\n\n var _proto = ComputedValue.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n propagateMaybeChanged(this);\n };\n\n _proto.onBO = function onBO() {\n if (this.onBOL) {\n this.onBOL.forEach(function (listener) {\n return listener();\n });\n }\n };\n\n _proto.onBUO = function onBUO() {\n if (this.onBUOL) {\n this.onBUOL.forEach(function (listener) {\n return listener();\n });\n }\n }\n /**\r\n * Returns the current value of this computed value.\r\n * Will evaluate its computation first if needed.\r\n */\n ;\n\n _proto.get = function get() {\n if (this.isComputing_) {\n die(32, this.name_, this.derivation);\n }\n\n if (globalState.inBatch === 0 && // !globalState.trackingDerivatpion &&\n this.observers_.size === 0 && !this.keepAlive_) {\n if (shouldCompute(this)) {\n this.warnAboutUntrackedRead_();\n startBatch(); // See perf test 'computed memoization'\n\n this.value_ = this.computeValue_(false);\n endBatch();\n }\n } else {\n reportObserved(this);\n\n if (shouldCompute(this)) {\n var prevTrackingContext = globalState.trackingContext;\n\n if (this.keepAlive_ && !prevTrackingContext) {\n globalState.trackingContext = this;\n }\n\n if (this.trackAndCompute()) {\n propagateChangeConfirmed(this);\n }\n\n globalState.trackingContext = prevTrackingContext;\n }\n }\n\n var result = this.value_;\n\n if (isCaughtException(result)) {\n throw result.cause;\n }\n\n return result;\n };\n\n _proto.set = function set(value) {\n if (this.setter_) {\n if (this.isRunningSetter_) {\n die(33, this.name_);\n }\n\n this.isRunningSetter_ = true;\n\n try {\n this.setter_.call(this.scope_, value);\n } finally {\n this.isRunningSetter_ = false;\n }\n } else {\n die(34, this.name_);\n }\n };\n\n _proto.trackAndCompute = function trackAndCompute() {\n // N.B: unminified as it is used by MST\n var oldValue = this.value_;\n var wasSuspended =\n /* see #1208 */\n this.dependenciesState_ === IDerivationState_.NOT_TRACKING_;\n var newValue = this.computeValue_(true);\n var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue);\n\n if (changed) {\n this.value_ = newValue;\n\n if ( true && isSpyEnabled()) {\n spyReport({\n observableKind: \"computed\",\n debugObjectName: this.name_,\n object: this.scope_,\n type: \"update\",\n oldValue: oldValue,\n newValue: newValue\n });\n }\n }\n\n return changed;\n };\n\n _proto.computeValue_ = function computeValue_(track) {\n this.isComputing_ = true; // don't allow state changes during computation\n\n var prev = allowStateChangesStart(false);\n var res;\n\n if (track) {\n res = trackDerivedFunction(this, this.derivation, this.scope_);\n } else {\n if (globalState.disableErrorBoundaries === true) {\n res = this.derivation.call(this.scope_);\n } else {\n try {\n res = this.derivation.call(this.scope_);\n } catch (e) {\n res = new CaughtException(e);\n }\n }\n }\n\n allowStateChangesEnd(prev);\n this.isComputing_ = false;\n return res;\n };\n\n _proto.suspend_ = function suspend_() {\n if (!this.keepAlive_) {\n clearObserving(this);\n this.value_ = undefined; // don't hold on to computed value!\n\n if ( true && this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' was suspended and it will recompute on the next access.\");\n }\n }\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n var _this = this;\n\n var firstTime = true;\n var prevValue = undefined;\n return autorun(function () {\n // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place\n var newValue = _this.get();\n\n if (!firstTime || fireImmediately) {\n var prevU = untrackedStart();\n listener({\n observableKind: \"computed\",\n debugObjectName: _this.name_,\n type: UPDATE,\n object: _this,\n newValue: newValue,\n oldValue: prevValue\n });\n untrackedEnd(prevU);\n }\n\n firstTime = false;\n prevValue = newValue;\n });\n };\n\n _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() {\n if (false) {}\n\n if (this.isTracing_ !== TraceMode.NONE) {\n console.log(\"[mobx.trace] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n\n if (typeof this.requiresReaction_ === \"boolean\" ? this.requiresReaction_ : globalState.computedRequiresReaction) {\n console.warn(\"[mobx] Computed value '\" + this.name_ + \"' is being read outside a reactive context. Doing a full recompute.\");\n }\n };\n\n _proto.toString = function toString() {\n return this.name_ + \"[\" + this.derivation.toString() + \"]\";\n };\n\n _proto.valueOf = function valueOf() {\n return toPrimitive(this.get());\n };\n\n _proto[_Symbol$toPrimitive$1] = function () {\n return this.valueOf();\n };\n\n return ComputedValue;\n}();\nvar isComputedValue = /*#__PURE__*/createInstanceofPredicate(\"ComputedValue\", ComputedValue);\n\nvar IDerivationState_;\n\n(function (IDerivationState_) {\n // before being run or (outside batch and not being observed)\n // at this point derivation is not holding any data about dependency tree\n IDerivationState_[IDerivationState_[\"NOT_TRACKING_\"] = -1] = \"NOT_TRACKING_\"; // no shallow dependency changed since last computation\n // won't recalculate derivation\n // this is what makes mobx fast\n\n IDerivationState_[IDerivationState_[\"UP_TO_DATE_\"] = 0] = \"UP_TO_DATE_\"; // some deep dependency changed, but don't know if shallow dependency changed\n // will require to check first if UP_TO_DATE or POSSIBLY_STALE\n // currently only ComputedValue will propagate POSSIBLY_STALE\n //\n // having this state is second big optimization:\n // don't have to recompute on every dependency change, but only when it's needed\n\n IDerivationState_[IDerivationState_[\"POSSIBLY_STALE_\"] = 1] = \"POSSIBLY_STALE_\"; // A shallow dependency has changed since last computation and the derivation\n // will need to recompute when it's needed next.\n\n IDerivationState_[IDerivationState_[\"STALE_\"] = 2] = \"STALE_\";\n})(IDerivationState_ || (IDerivationState_ = {}));\n\nvar TraceMode;\n\n(function (TraceMode) {\n TraceMode[TraceMode[\"NONE\"] = 0] = \"NONE\";\n TraceMode[TraceMode[\"LOG\"] = 1] = \"LOG\";\n TraceMode[TraceMode[\"BREAK\"] = 2] = \"BREAK\";\n})(TraceMode || (TraceMode = {}));\n\nvar CaughtException = function CaughtException(cause) {\n this.cause = void 0;\n this.cause = cause; // Empty\n};\nfunction isCaughtException(e) {\n return e instanceof CaughtException;\n}\n/**\r\n * Finds out whether any dependency of the derivation has actually changed.\r\n * If dependenciesState is 1 then it will recalculate dependencies,\r\n * if any dependency changed it will propagate it by changing dependenciesState to 2.\r\n *\r\n * By iterating over the dependencies in the same order that they were reported and\r\n * stopping on the first change, all the recalculations are only called for ComputedValues\r\n * that will be tracked by derivation. That is because we assume that if the first x\r\n * dependencies of the derivation doesn't change then the derivation should run the same way\r\n * up until accessing x-th dependency.\r\n */\n\nfunction shouldCompute(derivation) {\n switch (derivation.dependenciesState_) {\n case IDerivationState_.UP_TO_DATE_:\n return false;\n\n case IDerivationState_.NOT_TRACKING_:\n case IDerivationState_.STALE_:\n return true;\n\n case IDerivationState_.POSSIBLY_STALE_:\n {\n // state propagation can occur outside of action/reactive context #2195\n var prevAllowStateReads = allowStateReadsStart(true);\n var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction.\n\n var obs = derivation.observing_,\n l = obs.length;\n\n for (var i = 0; i < l; i++) {\n var obj = obs[i];\n\n if (isComputedValue(obj)) {\n if (globalState.disableErrorBoundaries) {\n obj.get();\n } else {\n try {\n obj.get();\n } catch (e) {\n // we are not interested in the value *or* exception at this moment, but if there is one, notify all\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers.\n // and `derivation` is an observer of `obj`\n // invariantShouldCompute(derivation)\n\n\n if (derivation.dependenciesState_ === IDerivationState_.STALE_) {\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return true;\n }\n }\n }\n\n changeDependenciesStateTo0(derivation);\n untrackedEnd(prevUntracked);\n allowStateReadsEnd(prevAllowStateReads);\n return false;\n }\n }\n}\nfunction isComputingDerivation() {\n return globalState.trackingDerivation !== null; // filter out actions inside computations\n}\nfunction checkIfStateModificationsAreAllowed(atom) {\n if (false) {}\n\n var hasObservers = atom.observers_.size > 0; // Should not be possible to change observed state outside strict mode, except during initialization, see #563\n\n if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === \"always\")) {\n console.warn(\"[MobX] \" + (globalState.enforceActions ? \"Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: \" : \"Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: \") + atom.name_);\n }\n}\nfunction checkIfStateReadsAreAllowed(observable) {\n if ( true && !globalState.allowStateReads && globalState.observableRequiresReaction) {\n console.warn(\"[mobx] Observable '\" + observable.name_ + \"' being read outside a reactive context.\");\n }\n}\n/**\r\n * Executes the provided function `f` and tracks which observables are being accessed.\r\n * The tracking information is stored on the `derivation` object and the derivation is registered\r\n * as observer of any of the accessed observables.\r\n */\n\nfunction trackDerivedFunction(derivation, f, context) {\n var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps\n // array will be trimmed by bindDependencies\n\n changeDependenciesStateTo0(derivation);\n derivation.newObserving_ = new Array(derivation.observing_.length + 100);\n derivation.unboundDepsCount_ = 0;\n derivation.runId_ = ++globalState.runId;\n var prevTracking = globalState.trackingDerivation;\n globalState.trackingDerivation = derivation;\n globalState.inBatch++;\n var result;\n\n if (globalState.disableErrorBoundaries === true) {\n result = f.call(context);\n } else {\n try {\n result = f.call(context);\n } catch (e) {\n result = new CaughtException(e);\n }\n }\n\n globalState.inBatch--;\n globalState.trackingDerivation = prevTracking;\n bindDependencies(derivation);\n warnAboutDerivationWithoutDependencies(derivation);\n allowStateReadsEnd(prevAllowStateReads);\n return result;\n}\n\nfunction warnAboutDerivationWithoutDependencies(derivation) {\n if (false) {}\n\n if (derivation.observing_.length !== 0) {\n return;\n }\n\n if (typeof derivation.requiresObservable_ === \"boolean\" ? derivation.requiresObservable_ : globalState.reactionRequiresObservable) {\n console.warn(\"[mobx] Derivation '\" + derivation.name_ + \"' is created/updated without reading any observable value.\");\n }\n}\n/**\r\n * diffs newObserving with observing.\r\n * update observing to be newObserving with unique observables\r\n * notify observers that become observed/unobserved\r\n */\n\n\nfunction bindDependencies(derivation) {\n // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, \"INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1\");\n var prevObserving = derivation.observing_;\n var observing = derivation.observing_ = derivation.newObserving_;\n var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; // Go through all new observables and check diffValue: (this list can contain duplicates):\n // 0: first occurrence, change to 1 and keep it\n // 1: extra occurrence, drop it\n\n var i0 = 0,\n l = derivation.unboundDepsCount_;\n\n for (var i = 0; i < l; i++) {\n var dep = observing[i];\n\n if (dep.diffValue_ === 0) {\n dep.diffValue_ = 1;\n\n if (i0 !== i) {\n observing[i0] = dep;\n }\n\n i0++;\n } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined,\n // not hitting the condition\n\n\n if (dep.dependenciesState_ > lowestNewObservingDerivationState) {\n lowestNewObservingDerivationState = dep.dependenciesState_;\n }\n }\n\n observing.length = i0;\n derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614)\n // Go through all old observables and check diffValue: (it is unique after last bindDependencies)\n // 0: it's not in new observables, unobserve it\n // 1: it keeps being observed, don't want to notify it. change to 0\n\n l = prevObserving.length;\n\n while (l--) {\n var _dep = prevObserving[l];\n\n if (_dep.diffValue_ === 0) {\n removeObserver(_dep, derivation);\n }\n\n _dep.diffValue_ = 0;\n } // Go through all new observables and check diffValue: (now it should be unique)\n // 0: it was set to 0 in last loop. don't need to do anything.\n // 1: it wasn't observed, let's observe it. set back to 0\n\n\n while (i0--) {\n var _dep2 = observing[i0];\n\n if (_dep2.diffValue_ === 1) {\n _dep2.diffValue_ = 0;\n addObserver(_dep2, derivation);\n }\n } // Some new observed derivations may become stale during this derivation computation\n // so they have had no chance to propagate staleness (#916)\n\n\n if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) {\n derivation.dependenciesState_ = lowestNewObservingDerivationState;\n derivation.onBecomeStale_();\n }\n}\n\nfunction clearObserving(derivation) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR clearObserving should be called only inside batch\");\n var obs = derivation.observing_;\n derivation.observing_ = [];\n var i = obs.length;\n\n while (i--) {\n removeObserver(obs[i], derivation);\n }\n\n derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n}\nfunction untracked(action) {\n var prev = untrackedStart();\n\n try {\n return action();\n } finally {\n untrackedEnd(prev);\n }\n}\nfunction untrackedStart() {\n var prev = globalState.trackingDerivation;\n globalState.trackingDerivation = null;\n return prev;\n}\nfunction untrackedEnd(prev) {\n globalState.trackingDerivation = prev;\n}\nfunction allowStateReadsStart(allowStateReads) {\n var prev = globalState.allowStateReads;\n globalState.allowStateReads = allowStateReads;\n return prev;\n}\nfunction allowStateReadsEnd(prev) {\n globalState.allowStateReads = prev;\n}\n/**\r\n * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0\r\n *\r\n */\n\nfunction changeDependenciesStateTo0(derivation) {\n if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_;\n var obs = derivation.observing_;\n var i = obs.length;\n\n while (i--) {\n obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n}\n\n/**\r\n * These values will persist if global state is reset\r\n */\n\nvar persistentKeys = [\"mobxGuid\", \"spyListeners\", \"enforceActions\", \"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"allowStateReads\", \"disableErrorBoundaries\", \"runId\", \"UNCHANGED\", \"useProxies\"];\nvar MobXGlobals = function MobXGlobals() {\n this.version = 6;\n this.UNCHANGED = {};\n this.trackingDerivation = null;\n this.trackingContext = null;\n this.runId = 0;\n this.mobxGuid = 0;\n this.inBatch = 0;\n this.pendingUnobservations = [];\n this.pendingReactions = [];\n this.isRunningReactions = false;\n this.allowStateChanges = false;\n this.allowStateReads = true;\n this.enforceActions = true;\n this.spyListeners = [];\n this.globalReactionErrorHandlers = [];\n this.computedRequiresReaction = false;\n this.reactionRequiresObservable = false;\n this.observableRequiresReaction = false;\n this.disableErrorBoundaries = false;\n this.suppressReactionErrors = false;\n this.useProxies = true;\n this.verifyProxies = false;\n this.safeDescriptors = true;\n};\nvar canMergeGlobalState = true;\nvar isolateCalled = false;\nvar globalState = /*#__PURE__*/function () {\n var global = /*#__PURE__*/getGlobal();\n\n if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) {\n canMergeGlobalState = false;\n }\n\n if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) {\n canMergeGlobalState = false;\n }\n\n if (!canMergeGlobalState) {\n // Because this is a IIFE we need to let isolateCalled a chance to change\n // so we run it after the event loop completed at least 1 iteration\n setTimeout(function () {\n if (!isolateCalled) {\n die(35);\n }\n }, 1);\n return new MobXGlobals();\n } else if (global.__mobxGlobals) {\n global.__mobxInstanceCount += 1;\n\n if (!global.__mobxGlobals.UNCHANGED) {\n global.__mobxGlobals.UNCHANGED = {};\n } // make merge backward compatible\n\n\n return global.__mobxGlobals;\n } else {\n global.__mobxInstanceCount = 1;\n return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals();\n }\n}();\nfunction isolateGlobalState() {\n if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) {\n die(36);\n }\n\n isolateCalled = true;\n\n if (canMergeGlobalState) {\n var global = getGlobal();\n\n if (--global.__mobxInstanceCount === 0) {\n global.__mobxGlobals = undefined;\n }\n\n globalState = new MobXGlobals();\n }\n}\nfunction getGlobalState() {\n return globalState;\n}\n/**\r\n * For testing purposes only; this will break the internal state of existing observables,\r\n * but can be used to get back at a stable state after throwing errors\r\n */\n\nfunction resetGlobalState() {\n var defaultGlobals = new MobXGlobals();\n\n for (var key in defaultGlobals) {\n if (persistentKeys.indexOf(key) === -1) {\n globalState[key] = defaultGlobals[key];\n }\n }\n\n globalState.allowStateChanges = !globalState.enforceActions;\n}\n\nfunction hasObservers(observable) {\n return observable.observers_ && observable.observers_.size > 0;\n}\nfunction getObservers(observable) {\n return observable.observers_;\n} // function invariantObservers(observable: IObservable) {\n// const list = observable.observers\n// const map = observable.observersIndexes\n// const l = list.length\n// for (let i = 0; i < l; i++) {\n// const id = list[i].__mapid\n// if (i) {\n// invariant(map[id] === i, \"INTERNAL ERROR maps derivation.__mapid to index in list\") // for performance\n// } else {\n// invariant(!(id in map), \"INTERNAL ERROR observer on index 0 shouldn't be held in map.\") // for performance\n// }\n// }\n// invariant(\n// list.length === 0 || Object.keys(map).length === list.length - 1,\n// \"INTERNAL ERROR there is no junk in map\"\n// )\n// }\n\nfunction addObserver(observable, node) {\n // invariant(node.dependenciesState !== -1, \"INTERNAL ERROR, can add only dependenciesState !== -1\");\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR add already added node\");\n // invariantObservers(observable);\n observable.observers_.add(node);\n\n if (observable.lowestObserverState_ > node.dependenciesState_) {\n observable.lowestObserverState_ = node.dependenciesState_;\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR didn't add node\");\n\n}\nfunction removeObserver(observable, node) {\n // invariant(globalState.inBatch > 0, \"INTERNAL ERROR, remove should be called only inside batch\");\n // invariant(observable._observers.indexOf(node) !== -1, \"INTERNAL ERROR remove already removed node\");\n // invariantObservers(observable);\n observable.observers_[\"delete\"](node);\n\n if (observable.observers_.size === 0) {\n // deleting last observer\n queueForUnobservation(observable);\n } // invariantObservers(observable);\n // invariant(observable._observers.indexOf(node) === -1, \"INTERNAL ERROR remove already removed node2\");\n\n}\nfunction queueForUnobservation(observable) {\n if (observable.isPendingUnobservation_ === false) {\n // invariant(observable._observers.length === 0, \"INTERNAL ERROR, should only queue for unobservation unobserved observables\");\n observable.isPendingUnobservation_ = true;\n globalState.pendingUnobservations.push(observable);\n }\n}\n/**\r\n * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does.\r\n * During a batch `onBecomeUnobserved` will be called at most once per observable.\r\n * Avoids unnecessary recalculations.\r\n */\n\nfunction startBatch() {\n globalState.inBatch++;\n}\nfunction endBatch() {\n if (--globalState.inBatch === 0) {\n runReactions(); // the batch is actually about to finish, all unobserving should happen here.\n\n var list = globalState.pendingUnobservations;\n\n for (var i = 0; i < list.length; i++) {\n var observable = list[i];\n observable.isPendingUnobservation_ = false;\n\n if (observable.observers_.size === 0) {\n if (observable.isBeingObserved_) {\n // if this observable had reactive observers, trigger the hooks\n observable.isBeingObserved_ = false;\n observable.onBUO();\n }\n\n if (observable instanceof ComputedValue) {\n // computed values are automatically teared down when the last observer leaves\n // this process happens recursively, this computed might be the last observabe of another, etc..\n observable.suspend_();\n }\n }\n }\n\n globalState.pendingUnobservations = [];\n }\n}\nfunction reportObserved(observable) {\n checkIfStateReadsAreAllowed(observable);\n var derivation = globalState.trackingDerivation;\n\n if (derivation !== null) {\n /**\r\n * Simple optimization, give each derivation run an unique id (runId)\r\n * Check if last time this observable was accessed the same runId is used\r\n * if this is the case, the relation is already known\r\n */\n if (derivation.runId_ !== observable.lastAccessedBy_) {\n observable.lastAccessedBy_ = derivation.runId_; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close...\n\n derivation.newObserving_[derivation.unboundDepsCount_++] = observable;\n\n if (!observable.isBeingObserved_ && globalState.trackingContext) {\n observable.isBeingObserved_ = true;\n observable.onBO();\n }\n }\n\n return observable.isBeingObserved_;\n } else if (observable.observers_.size === 0 && globalState.inBatch > 0) {\n queueForUnobservation(observable);\n }\n\n return false;\n} // function invariantLOS(observable: IObservable, msg: string) {\n// // it's expensive so better not run it in produciton. but temporarily helpful for testing\n// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2)\n// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState`\n// throw new Error(\n// \"lowestObserverState is wrong for \" +\n// msg +\n// \" because \" +\n// min +\n// \" < \" +\n// observable.lowestObserverState\n// )\n// }\n\n/**\r\n * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly\r\n * It will propagate changes to observers from previous run\r\n * It's hard or maybe impossible (with reasonable perf) to get it right with current approach\r\n * Hopefully self reruning autoruns aren't a feature people should depend on\r\n * Also most basic use cases should be ok\r\n */\n// Called by Atom when its value changes\n\nfunction propagateChanged(observable) {\n // invariantLOS(observable, \"changed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_; // Ideally we use for..of here, but the downcompiled version is really slow...\n\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n\n d.onBecomeStale_();\n }\n\n d.dependenciesState_ = IDerivationState_.STALE_;\n }); // invariantLOS(observable, \"changed end\");\n} // Called by ComputedValue when it recalculate and its value changed\n\nfunction propagateChangeConfirmed(observable) {\n // invariantLOS(observable, \"confirmed start\");\n if (observable.lowestObserverState_ === IDerivationState_.STALE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) {\n d.dependenciesState_ = IDerivationState_.STALE_;\n\n if ( true && d.isTracing_ !== TraceMode.NONE) {\n logTraceInfo(d, observable);\n }\n } else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date.\n ) {\n observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_;\n }\n }); // invariantLOS(observable, \"confirmed end\");\n} // Used by computed when its dependency changed, but we don't wan't to immediately recompute.\n\nfunction propagateMaybeChanged(observable) {\n // invariantLOS(observable, \"maybe start\");\n if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) {\n return;\n }\n\n observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_;\n observable.observers_.forEach(function (d) {\n if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) {\n d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_;\n d.onBecomeStale_();\n }\n }); // invariantLOS(observable, \"maybe end\");\n}\n\nfunction logTraceInfo(derivation, observable) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' is invalidated due to a change in: '\" + observable.name_ + \"'\");\n\n if (derivation.isTracing_ === TraceMode.BREAK) {\n var lines = [];\n printDepTree(getDependencyTree(derivation), lines, 1); // prettier-ignore\n\n new Function(\"debugger;\\n/*\\nTracing '\" + derivation.name_ + \"'\\n\\nYou are entering this break point because derivation '\" + derivation.name_ + \"' is being traced and '\" + observable.name_ + \"' is now forcing it to update.\\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\\n\\n\" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\\//g, \"/\") : \"\") + \"\\n\\nThe dependencies for this derivation are:\\n\\n\" + lines.join(\"\\n\") + \"\\n*/\\n \")();\n }\n}\n\nfunction printDepTree(tree, lines, depth) {\n if (lines.length >= 1000) {\n lines.push(\"(and many more)\");\n return;\n }\n\n lines.push(\"\" + \"\\t\".repeat(depth - 1) + tree.name);\n\n if (tree.dependencies) {\n tree.dependencies.forEach(function (child) {\n return printDepTree(child, lines, depth + 1);\n });\n }\n}\n\nvar Reaction = /*#__PURE__*/function () {\n // nodes we are looking at. Our value depends on these nodes\n function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) {\n if (name_ === void 0) {\n name_ = true ? \"Reaction@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this.onInvalidate_ = void 0;\n this.errorHandler_ = void 0;\n this.requiresObservable_ = void 0;\n this.observing_ = [];\n this.newObserving_ = [];\n this.dependenciesState_ = IDerivationState_.NOT_TRACKING_;\n this.diffValue_ = 0;\n this.runId_ = 0;\n this.unboundDepsCount_ = 0;\n this.isDisposed_ = false;\n this.isScheduled_ = false;\n this.isTrackPending_ = false;\n this.isRunning_ = false;\n this.isTracing_ = TraceMode.NONE;\n this.name_ = name_;\n this.onInvalidate_ = onInvalidate_;\n this.errorHandler_ = errorHandler_;\n this.requiresObservable_ = requiresObservable_;\n }\n\n var _proto = Reaction.prototype;\n\n _proto.onBecomeStale_ = function onBecomeStale_() {\n this.schedule_();\n };\n\n _proto.schedule_ = function schedule_() {\n if (!this.isScheduled_) {\n this.isScheduled_ = true;\n globalState.pendingReactions.push(this);\n runReactions();\n }\n };\n\n _proto.isScheduled = function isScheduled() {\n return this.isScheduled_;\n }\n /**\r\n * internal, use schedule() if you intend to kick off a reaction\r\n */\n ;\n\n _proto.runReaction_ = function runReaction_() {\n if (!this.isDisposed_) {\n startBatch();\n this.isScheduled_ = false;\n var prev = globalState.trackingContext;\n globalState.trackingContext = this;\n\n if (shouldCompute(this)) {\n this.isTrackPending_ = true;\n\n try {\n this.onInvalidate_();\n\n if ( true && this.isTrackPending_ && isSpyEnabled()) {\n // onInvalidate didn't trigger track right away..\n spyReport({\n name: this.name_,\n type: \"scheduled-reaction\"\n });\n }\n } catch (e) {\n this.reportExceptionInDerivation_(e);\n }\n }\n\n globalState.trackingContext = prev;\n endBatch();\n }\n };\n\n _proto.track = function track(fn) {\n if (this.isDisposed_) {\n return; // console.warn(\"Reaction already disposed\") // Note: Not a warning / error in mobx 4 either\n }\n\n startBatch();\n var notify = isSpyEnabled();\n var startTime;\n\n if ( true && notify) {\n startTime = Date.now();\n spyReportStart({\n name: this.name_,\n type: \"reaction\"\n });\n }\n\n this.isRunning_ = true;\n var prevReaction = globalState.trackingContext; // reactions could create reactions...\n\n globalState.trackingContext = this;\n var result = trackDerivedFunction(this, fn, undefined);\n globalState.trackingContext = prevReaction;\n this.isRunning_ = false;\n this.isTrackPending_ = false;\n\n if (this.isDisposed_) {\n // disposed during last run. Clean up everything that was bound after the dispose call.\n clearObserving(this);\n }\n\n if (isCaughtException(result)) {\n this.reportExceptionInDerivation_(result.cause);\n }\n\n if ( true && notify) {\n spyReportEnd({\n time: Date.now() - startTime\n });\n }\n\n endBatch();\n };\n\n _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) {\n var _this = this;\n\n if (this.errorHandler_) {\n this.errorHandler_(error, this);\n return;\n }\n\n if (globalState.disableErrorBoundaries) {\n throw error;\n }\n\n var message = true ? \"[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '\" + this + \"'\" : undefined;\n\n if (!globalState.suppressReactionErrors) {\n console.error(message, error);\n /** If debugging brought you here, please, read the above message :-). Tnx! */\n } else if (true) {\n console.warn(\"[mobx] (error in reaction '\" + this.name_ + \"' suppressed, fix error of causing action below)\");\n } // prettier-ignore\n\n\n if ( true && isSpyEnabled()) {\n spyReport({\n type: \"error\",\n name: this.name_,\n message: message,\n error: \"\" + error\n });\n }\n\n globalState.globalReactionErrorHandlers.forEach(function (f) {\n return f(error, _this);\n });\n };\n\n _proto.dispose = function dispose() {\n if (!this.isDisposed_) {\n this.isDisposed_ = true;\n\n if (!this.isRunning_) {\n // if disposed while running, clean up later. Maybe not optimal, but rare case\n startBatch();\n clearObserving(this);\n endBatch();\n }\n }\n };\n\n _proto.getDisposer_ = function getDisposer_() {\n var r = this.dispose.bind(this);\n r[$mobx] = this;\n return r;\n };\n\n _proto.toString = function toString() {\n return \"Reaction[\" + this.name_ + \"]\";\n };\n\n _proto.trace = function trace$1(enterBreakPoint) {\n if (enterBreakPoint === void 0) {\n enterBreakPoint = false;\n }\n\n trace(this, enterBreakPoint);\n };\n\n return Reaction;\n}();\nfunction onReactionError(handler) {\n globalState.globalReactionErrorHandlers.push(handler);\n return function () {\n var idx = globalState.globalReactionErrorHandlers.indexOf(handler);\n\n if (idx >= 0) {\n globalState.globalReactionErrorHandlers.splice(idx, 1);\n }\n };\n}\n/**\r\n * Magic number alert!\r\n * Defines within how many times a reaction is allowed to re-trigger itself\r\n * until it is assumed that this is gonna be a never ending loop...\r\n */\n\nvar MAX_REACTION_ITERATIONS = 100;\n\nvar reactionScheduler = function reactionScheduler(f) {\n return f();\n};\n\nfunction runReactions() {\n // Trampolining, if runReactions are already running, new reactions will be picked up\n if (globalState.inBatch > 0 || globalState.isRunningReactions) {\n return;\n }\n\n reactionScheduler(runReactionsHelper);\n}\n\nfunction runReactionsHelper() {\n globalState.isRunningReactions = true;\n var allReactions = globalState.pendingReactions;\n var iterations = 0; // While running reactions, new reactions might be triggered.\n // Hence we work with two variables and check whether\n // we converge to no remaining reactions after a while.\n\n while (allReactions.length > 0) {\n if (++iterations === MAX_REACTION_ITERATIONS) {\n console.error( true ? \"Reaction doesn't converge to a stable state after \" + MAX_REACTION_ITERATIONS + \" iterations.\" + (\" Probably there is a cycle in the reactive function: \" + allReactions[0]) : undefined);\n allReactions.splice(0); // clear reactions\n }\n\n var remainingReactions = allReactions.splice(0);\n\n for (var i = 0, l = remainingReactions.length; i < l; i++) {\n remainingReactions[i].runReaction_();\n }\n }\n\n globalState.isRunningReactions = false;\n}\n\nvar isReaction = /*#__PURE__*/createInstanceofPredicate(\"Reaction\", Reaction);\nfunction setReactionScheduler(fn) {\n var baseScheduler = reactionScheduler;\n\n reactionScheduler = function reactionScheduler(f) {\n return fn(function () {\n return baseScheduler(f);\n });\n };\n}\n\nfunction isSpyEnabled() {\n return true && !!globalState.spyListeners.length;\n}\nfunction spyReport(event) {\n if (false) {} // dead code elimination can do the rest\n\n\n if (!globalState.spyListeners.length) {\n return;\n }\n\n var listeners = globalState.spyListeners;\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](event);\n }\n}\nfunction spyReportStart(event) {\n if (false) {}\n\n var change = _extends({}, event, {\n spyReportStart: true\n });\n\n spyReport(change);\n}\nvar END_EVENT = {\n type: \"report-end\",\n spyReportEnd: true\n};\nfunction spyReportEnd(change) {\n if (false) {}\n\n if (change) {\n spyReport(_extends({}, change, {\n type: \"report-end\",\n spyReportEnd: true\n }));\n } else {\n spyReport(END_EVENT);\n }\n}\nfunction spy(listener) {\n if (false) {} else {\n globalState.spyListeners.push(listener);\n return once(function () {\n globalState.spyListeners = globalState.spyListeners.filter(function (l) {\n return l !== listener;\n });\n });\n }\n}\n\nvar ACTION = \"action\";\nvar ACTION_BOUND = \"action.bound\";\nvar AUTOACTION = \"autoAction\";\nvar AUTOACTION_BOUND = \"autoAction.bound\";\nvar DEFAULT_ACTION_NAME = \"\";\nvar actionAnnotation = /*#__PURE__*/createActionAnnotation(ACTION);\nvar actionBoundAnnotation = /*#__PURE__*/createActionAnnotation(ACTION_BOUND, {\n bound: true\n});\nvar autoActionAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION, {\n autoAction: true\n});\nvar autoActionBoundAnnotation = /*#__PURE__*/createActionAnnotation(AUTOACTION_BOUND, {\n autoAction: true,\n bound: true\n});\n\nfunction createActionFactory(autoAction) {\n var res = function action(arg1, arg2) {\n // action(fn() {})\n if (isFunction(arg1)) {\n return createAction(arg1.name || DEFAULT_ACTION_NAME, arg1, autoAction);\n } // action(\"name\", fn() {})\n\n\n if (isFunction(arg2)) {\n return createAction(arg1, arg2, autoAction);\n } // @action\n\n\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, autoAction ? autoActionAnnotation : actionAnnotation);\n } // action(\"name\") & @action(\"name\")\n\n\n if (isStringish(arg1)) {\n return createDecoratorAnnotation(createActionAnnotation(autoAction ? AUTOACTION : ACTION, {\n name: arg1,\n autoAction: autoAction\n }));\n }\n\n if (true) {\n die(\"Invalid arguments for `action`\");\n }\n };\n\n return res;\n}\n\nvar action = /*#__PURE__*/createActionFactory(false);\nObject.assign(action, actionAnnotation);\nvar autoAction = /*#__PURE__*/createActionFactory(true);\nObject.assign(autoAction, autoActionAnnotation);\naction.bound = /*#__PURE__*/createDecoratorAnnotation(actionBoundAnnotation);\nautoAction.bound = /*#__PURE__*/createDecoratorAnnotation(autoActionBoundAnnotation);\nfunction runInAction(fn) {\n return executeAction(fn.name || DEFAULT_ACTION_NAME, false, fn, this, undefined);\n}\nfunction isAction(thing) {\n return isFunction(thing) && thing.isMobxAction === true;\n}\n\n/**\r\n * Creates a named reactive view and keeps it alive, so that the view is always\r\n * updated if one of the dependencies changes, even when the view is not further used by something else.\r\n * @param view The reactive view\r\n * @returns disposer function, which can be used to stop the view from being updated in the future.\r\n */\n\nfunction autorun(view, opts) {\n var _opts$name, _opts;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(view)) {\n die(\"Autorun expects a function as first argument\");\n }\n\n if (isAction(view)) {\n die(\"Autorun does not accept actions since actions are untrackable\");\n }\n }\n\n var name = (_opts$name = (_opts = opts) == null ? void 0 : _opts.name) != null ? _opts$name : true ? view.name || \"Autorun@\" + getNextId() : undefined;\n var runSync = !opts.scheduler && !opts.delay;\n var reaction;\n\n if (runSync) {\n // normal autorun\n reaction = new Reaction(name, function () {\n this.track(reactionRunner);\n }, opts.onError, opts.requiresObservable);\n } else {\n var scheduler = createSchedulerFromOptions(opts); // debounced autorun\n\n var isScheduled = false;\n reaction = new Reaction(name, function () {\n if (!isScheduled) {\n isScheduled = true;\n scheduler(function () {\n isScheduled = false;\n\n if (!reaction.isDisposed_) {\n reaction.track(reactionRunner);\n }\n });\n }\n }, opts.onError, opts.requiresObservable);\n }\n\n function reactionRunner() {\n view(reaction);\n }\n\n reaction.schedule_();\n return reaction.getDisposer_();\n}\n\nvar run = function run(f) {\n return f();\n};\n\nfunction createSchedulerFromOptions(opts) {\n return opts.scheduler ? opts.scheduler : opts.delay ? function (f) {\n return setTimeout(f, opts.delay);\n } : run;\n}\n\nfunction reaction(expression, effect, opts) {\n var _opts$name2;\n\n if (opts === void 0) {\n opts = EMPTY_OBJECT;\n }\n\n if (true) {\n if (!isFunction(expression) || !isFunction(effect)) {\n die(\"First and second argument to reaction should be functions\");\n }\n\n if (!isPlainObject(opts)) {\n die(\"Third argument of reactions should be an object\");\n }\n }\n\n var name = (_opts$name2 = opts.name) != null ? _opts$name2 : true ? \"Reaction@\" + getNextId() : undefined;\n var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect);\n var runSync = !opts.scheduler && !opts.delay;\n var scheduler = createSchedulerFromOptions(opts);\n var firstTime = true;\n var isScheduled = false;\n var value;\n var oldValue;\n var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer[\"default\"];\n var r = new Reaction(name, function () {\n if (firstTime || runSync) {\n reactionRunner();\n } else if (!isScheduled) {\n isScheduled = true;\n scheduler(reactionRunner);\n }\n }, opts.onError, opts.requiresObservable);\n\n function reactionRunner() {\n isScheduled = false;\n\n if (r.isDisposed_) {\n return;\n }\n\n var changed = false;\n r.track(function () {\n var nextValue = allowStateChanges(false, function () {\n return expression(r);\n });\n changed = firstTime || !equals(value, nextValue);\n oldValue = value;\n value = nextValue;\n });\n\n if (firstTime && opts.fireImmediately) {\n effectAction(value, oldValue, r);\n } else if (!firstTime && changed) {\n effectAction(value, oldValue, r);\n }\n\n firstTime = false;\n }\n\n r.schedule_();\n return r.getDisposer_();\n}\n\nfunction wrapErrorHandler(errorHandler, baseFn) {\n return function () {\n try {\n return baseFn.apply(this, arguments);\n } catch (e) {\n errorHandler.call(this, e);\n }\n };\n}\n\nvar ON_BECOME_OBSERVED = \"onBO\";\nvar ON_BECOME_UNOBSERVED = \"onBUO\";\nfunction onBecomeObserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3);\n}\nfunction onBecomeUnobserved(thing, arg2, arg3) {\n return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3);\n}\n\nfunction interceptHook(hook, thing, arg2, arg3) {\n var atom = typeof arg3 === \"function\" ? getAtom(thing, arg2) : getAtom(thing);\n var cb = isFunction(arg3) ? arg3 : arg2;\n var listenersKey = hook + \"L\";\n\n if (atom[listenersKey]) {\n atom[listenersKey].add(cb);\n } else {\n atom[listenersKey] = new Set([cb]);\n }\n\n return function () {\n var hookListeners = atom[listenersKey];\n\n if (hookListeners) {\n hookListeners[\"delete\"](cb);\n\n if (hookListeners.size === 0) {\n delete atom[listenersKey];\n }\n }\n };\n}\n\nvar NEVER = \"never\";\nvar ALWAYS = \"always\";\nvar OBSERVED = \"observed\"; // const IF_AVAILABLE = \"ifavailable\"\n\nfunction configure(options) {\n if (options.isolateGlobalState === true) {\n isolateGlobalState();\n }\n\n var useProxies = options.useProxies,\n enforceActions = options.enforceActions;\n\n if (useProxies !== undefined) {\n globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== \"undefined\";\n }\n\n if (useProxies === \"ifavailable\") {\n globalState.verifyProxies = true;\n }\n\n if (enforceActions !== undefined) {\n var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED;\n globalState.enforceActions = ea;\n globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true;\n }\n [\"computedRequiresReaction\", \"reactionRequiresObservable\", \"observableRequiresReaction\", \"disableErrorBoundaries\", \"safeDescriptors\"].forEach(function (key) {\n if (key in options) {\n globalState[key] = !!options[key];\n }\n });\n globalState.allowStateReads = !globalState.observableRequiresReaction;\n\n if ( true && globalState.disableErrorBoundaries === true) {\n console.warn(\"WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled.\");\n }\n\n if (options.reactionScheduler) {\n setReactionScheduler(options.reactionScheduler);\n }\n}\n\nfunction extendObservable(target, properties, annotations, options) {\n if (true) {\n if (arguments.length > 4) {\n die(\"'extendObservable' expected 2-4 arguments\");\n }\n\n if (typeof target !== \"object\") {\n die(\"'extendObservable' expects an object as first argument\");\n }\n\n if (isObservableMap(target)) {\n die(\"'extendObservable' should not be used on maps, use map.merge instead\");\n }\n\n if (!isPlainObject(properties)) {\n die(\"'extendObservable' only accepts plain objects as second argument\");\n }\n\n if (isObservable(properties) || isObservable(annotations)) {\n die(\"Extending an object with another observable (object) is not supported\");\n }\n } // Pull descriptors first, so we don't have to deal with props added by administration ($mobx)\n\n\n var descriptors = getOwnPropertyDescriptors(properties);\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n ownKeys(descriptors).forEach(function (key) {\n adm.extend_(key, descriptors[key], // must pass \"undefined\" for { key: undefined }\n !annotations ? true : key in annotations ? annotations[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nfunction getDependencyTree(thing, property) {\n return nodeToDependencyTree(getAtom(thing, property));\n}\n\nfunction nodeToDependencyTree(node) {\n var result = {\n name: node.name_\n };\n\n if (node.observing_ && node.observing_.length > 0) {\n result.dependencies = unique(node.observing_).map(nodeToDependencyTree);\n }\n\n return result;\n}\n\nfunction getObserverTree(thing, property) {\n return nodeToObserverTree(getAtom(thing, property));\n}\n\nfunction nodeToObserverTree(node) {\n var result = {\n name: node.name_\n };\n\n if (hasObservers(node)) {\n result.observers = Array.from(getObservers(node)).map(nodeToObserverTree);\n }\n\n return result;\n}\n\nfunction unique(list) {\n return Array.from(new Set(list));\n}\n\nvar generatorId = 0;\nfunction FlowCancellationError() {\n this.message = \"FLOW_CANCELLED\";\n}\nFlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype);\nfunction isFlowCancellationError(error) {\n return error instanceof FlowCancellationError;\n}\nvar flowAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow\");\nvar flowBoundAnnotation = /*#__PURE__*/createFlowAnnotation(\"flow.bound\", {\n bound: true\n});\nvar flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) {\n // @flow\n if (isStringish(arg2)) {\n return storeAnnotation(arg1, arg2, flowAnnotation);\n } // flow(fn)\n\n\n if ( true && arguments.length !== 1) {\n die(\"Flow expects single argument with generator function\");\n }\n\n var generator = arg1;\n var name = generator.name || \"\"; // Implementation based on https://github.com/tj/co/blob/master/index.js\n\n var res = function res() {\n var ctx = this;\n var args = arguments;\n var runId = ++generatorId;\n var gen = action(name + \" - runid: \" + runId + \" - init\", generator).apply(ctx, args);\n var rejector;\n var pendingPromise = undefined;\n var promise = new Promise(function (resolve, reject) {\n var stepId = 0;\n rejector = reject;\n\n function onFulfilled(res) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen.next).call(gen, res);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function onRejected(err) {\n pendingPromise = undefined;\n var ret;\n\n try {\n ret = action(name + \" - runid: \" + runId + \" - yield \" + stepId++, gen[\"throw\"]).call(gen, err);\n } catch (e) {\n return reject(e);\n }\n\n next(ret);\n }\n\n function next(ret) {\n if (isFunction(ret == null ? void 0 : ret.then)) {\n // an async iterator\n ret.then(next, reject);\n return;\n }\n\n if (ret.done) {\n return resolve(ret.value);\n }\n\n pendingPromise = Promise.resolve(ret.value);\n return pendingPromise.then(onFulfilled, onRejected);\n }\n\n onFulfilled(undefined); // kick off the process\n });\n promise.cancel = action(name + \" - runid: \" + runId + \" - cancel\", function () {\n try {\n if (pendingPromise) {\n cancelPromise(pendingPromise);\n } // Finally block can return (or yield) stuff..\n\n\n var _res = gen[\"return\"](undefined); // eat anything that promise would do, it's cancelled!\n\n\n var yieldedPromise = Promise.resolve(_res.value);\n yieldedPromise.then(noop, noop);\n cancelPromise(yieldedPromise); // maybe it can be cancelled :)\n // reject our original promise\n\n rejector(new FlowCancellationError());\n } catch (e) {\n rejector(e); // there could be a throwing finally block\n }\n });\n return promise;\n };\n\n res.isMobXFlow = true;\n return res;\n}, flowAnnotation);\nflow.bound = /*#__PURE__*/createDecoratorAnnotation(flowBoundAnnotation);\n\nfunction cancelPromise(promise) {\n if (isFunction(promise.cancel)) {\n promise.cancel();\n }\n}\n\nfunction flowResult(result) {\n return result; // just tricking TypeScript :)\n}\nfunction isFlow(fn) {\n return (fn == null ? void 0 : fn.isMobXFlow) === true;\n}\n\nfunction interceptReads(thing, propOrHandler, handler) {\n var target;\n\n if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) {\n target = getAdministration(thing);\n } else if (isObservableObject(thing)) {\n if ( true && !isStringish(propOrHandler)) {\n return die(\"InterceptReads can only be used with a specific property, not with an object in general\");\n }\n\n target = getAdministration(thing, propOrHandler);\n } else if (true) {\n return die(\"Expected observable map, object or array as first array\");\n }\n\n if ( true && target.dehancer !== undefined) {\n return die(\"An intercept reader was already established\");\n }\n\n target.dehancer = typeof propOrHandler === \"function\" ? propOrHandler : handler;\n return function () {\n target.dehancer = undefined;\n };\n}\n\nfunction intercept(thing, propOrHandler, handler) {\n if (isFunction(handler)) {\n return interceptProperty(thing, propOrHandler, handler);\n } else {\n return interceptInterceptable(thing, propOrHandler);\n }\n}\n\nfunction interceptInterceptable(thing, handler) {\n return getAdministration(thing).intercept_(handler);\n}\n\nfunction interceptProperty(thing, property, handler) {\n return getAdministration(thing, property).intercept_(handler);\n}\n\nfunction _isComputed(value, property) {\n if (property === undefined) {\n return isComputedValue(value);\n }\n\n if (isObservableObject(value) === false) {\n return false;\n }\n\n if (!value[$mobx].values_.has(property)) {\n return false;\n }\n\n var atom = getAtom(value, property);\n return isComputedValue(atom);\n}\nfunction isComputed(value) {\n if ( true && arguments.length > 1) {\n return die(\"isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property\");\n }\n\n return _isComputed(value);\n}\nfunction isComputedProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"isComputed expected a property name as second argument\");\n }\n\n return _isComputed(value, propName);\n}\n\nfunction _isObservable(value, property) {\n if (!value) {\n return false;\n }\n\n if (property !== undefined) {\n if ( true && (isObservableMap(value) || isObservableArray(value))) {\n return die(\"isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.\");\n }\n\n if (isObservableObject(value)) {\n return value[$mobx].values_.has(property);\n }\n\n return false;\n } // For first check, see #701\n\n\n return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value);\n}\n\nfunction isObservable(value) {\n if ( true && arguments.length !== 1) {\n die(\"isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property\");\n }\n\n return _isObservable(value);\n}\nfunction isObservableProp(value, propName) {\n if ( true && !isStringish(propName)) {\n return die(\"expected a property name as second argument\");\n }\n\n return _isObservable(value, propName);\n}\n\nfunction keys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].keys_();\n }\n\n if (isObservableMap(obj) || isObservableSet(obj)) {\n return Array.from(obj.keys());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (_, index) {\n return index;\n });\n }\n\n die(5);\n}\nfunction values(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return obj[key];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return obj.get(key);\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.values());\n }\n\n if (isObservableArray(obj)) {\n return obj.slice();\n }\n\n die(6);\n}\nfunction entries(obj) {\n if (isObservableObject(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj[key]];\n });\n }\n\n if (isObservableMap(obj)) {\n return keys(obj).map(function (key) {\n return [key, obj.get(key)];\n });\n }\n\n if (isObservableSet(obj)) {\n return Array.from(obj.entries());\n }\n\n if (isObservableArray(obj)) {\n return obj.map(function (key, index) {\n return [index, key];\n });\n }\n\n die(7);\n}\nfunction set(obj, key, value) {\n if (arguments.length === 2 && !isObservableSet(obj)) {\n startBatch();\n var _values = key;\n\n try {\n for (var _key in _values) {\n set(obj, _key, _values[_key]);\n }\n } finally {\n endBatch();\n }\n\n return;\n }\n\n if (isObservableObject(obj)) {\n obj[$mobx].set_(key, value);\n } else if (isObservableMap(obj)) {\n obj.set(key, value);\n } else if (isObservableSet(obj)) {\n obj.add(key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n if (key < 0) {\n die(\"Invalid index: '\" + key + \"'\");\n }\n\n startBatch();\n\n if (key >= obj.length) {\n obj.length = key + 1;\n }\n\n obj[key] = value;\n endBatch();\n } else {\n die(8);\n }\n}\nfunction remove(obj, key) {\n if (isObservableObject(obj)) {\n obj[$mobx].delete_(key);\n } else if (isObservableMap(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableSet(obj)) {\n obj[\"delete\"](key);\n } else if (isObservableArray(obj)) {\n if (typeof key !== \"number\") {\n key = parseInt(key, 10);\n }\n\n obj.splice(key, 1);\n } else {\n die(9);\n }\n}\nfunction has(obj, key) {\n if (isObservableObject(obj)) {\n return obj[$mobx].has_(key);\n } else if (isObservableMap(obj)) {\n return obj.has(key);\n } else if (isObservableSet(obj)) {\n return obj.has(key);\n } else if (isObservableArray(obj)) {\n return key >= 0 && key < obj.length;\n }\n\n die(10);\n}\nfunction get(obj, key) {\n if (!has(obj, key)) {\n return undefined;\n }\n\n if (isObservableObject(obj)) {\n return obj[$mobx].get_(key);\n } else if (isObservableMap(obj)) {\n return obj.get(key);\n } else if (isObservableArray(obj)) {\n return obj[key];\n }\n\n die(11);\n}\nfunction apiDefineProperty(obj, key, descriptor) {\n if (isObservableObject(obj)) {\n return obj[$mobx].defineProperty_(key, descriptor);\n }\n\n die(39);\n}\nfunction apiOwnKeys(obj) {\n if (isObservableObject(obj)) {\n return obj[$mobx].ownKeys_();\n }\n\n die(38);\n}\n\nfunction observe(thing, propOrCb, cbOrFire, fireImmediately) {\n if (isFunction(cbOrFire)) {\n return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);\n } else {\n return observeObservable(thing, propOrCb, cbOrFire);\n }\n}\n\nfunction observeObservable(thing, listener, fireImmediately) {\n return getAdministration(thing).observe_(listener, fireImmediately);\n}\n\nfunction observeObservableProperty(thing, property, listener, fireImmediately) {\n return getAdministration(thing, property).observe_(listener, fireImmediately);\n}\n\nfunction cache(map, key, value) {\n map.set(key, value);\n return value;\n}\n\nfunction toJSHelper(source, __alreadySeen) {\n if (source == null || typeof source !== \"object\" || source instanceof Date || !isObservable(source)) {\n return source;\n }\n\n if (isObservableValue(source) || isComputedValue(source)) {\n return toJSHelper(source.get(), __alreadySeen);\n }\n\n if (__alreadySeen.has(source)) {\n return __alreadySeen.get(source);\n }\n\n if (isObservableArray(source)) {\n var res = cache(__alreadySeen, source, new Array(source.length));\n source.forEach(function (value, idx) {\n res[idx] = toJSHelper(value, __alreadySeen);\n });\n return res;\n }\n\n if (isObservableSet(source)) {\n var _res = cache(__alreadySeen, source, new Set());\n\n source.forEach(function (value) {\n _res.add(toJSHelper(value, __alreadySeen));\n });\n return _res;\n }\n\n if (isObservableMap(source)) {\n var _res2 = cache(__alreadySeen, source, new Map());\n\n source.forEach(function (value, key) {\n _res2.set(key, toJSHelper(value, __alreadySeen));\n });\n return _res2;\n } else {\n // must be observable object\n var _res3 = cache(__alreadySeen, source, {});\n\n apiOwnKeys(source).forEach(function (key) {\n if (objectPrototype.propertyIsEnumerable.call(source, key)) {\n _res3[key] = toJSHelper(source[key], __alreadySeen);\n }\n });\n return _res3;\n }\n}\n/**\r\n * Recursively converts an observable to it's non-observable native counterpart.\r\n * It does NOT recurse into non-observables, these are left as they are, even if they contain observables.\r\n * Computed and other non-enumerable properties are completely ignored.\r\n * Complex scenarios require custom solution, eg implementing `toJSON` or using `serializr` lib.\r\n */\n\n\nfunction toJS(source, options) {\n if ( true && options) {\n die(\"toJS no longer supports options\");\n }\n\n return toJSHelper(source, new Map());\n}\n\nfunction trace() {\n if (false) {}\n\n var enterBreakPoint = false;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (typeof args[args.length - 1] === \"boolean\") {\n enterBreakPoint = args.pop();\n }\n\n var derivation = getAtomFromArgs(args);\n\n if (!derivation) {\n return die(\"'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly\");\n }\n\n if (derivation.isTracing_ === TraceMode.NONE) {\n console.log(\"[mobx.trace] '\" + derivation.name_ + \"' tracing enabled\");\n }\n\n derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG;\n}\n\nfunction getAtomFromArgs(args) {\n switch (args.length) {\n case 0:\n return globalState.trackingDerivation;\n\n case 1:\n return getAtom(args[0]);\n\n case 2:\n return getAtom(args[0], args[1]);\n }\n}\n\n/**\r\n * During a transaction no views are updated until the end of the transaction.\r\n * The transaction will be run synchronously nonetheless.\r\n *\r\n * @param action a function that updates some reactive state\r\n * @returns any value that was returned by the 'action' parameter.\r\n */\n\nfunction transaction(action, thisArg) {\n if (thisArg === void 0) {\n thisArg = undefined;\n }\n\n startBatch();\n\n try {\n return action.apply(thisArg);\n } finally {\n endBatch();\n }\n}\n\nfunction when(predicate, arg1, arg2) {\n if (arguments.length === 1 || arg1 && typeof arg1 === \"object\") {\n return whenPromise(predicate, arg1);\n }\n\n return _when(predicate, arg1, arg2 || {});\n}\n\nfunction _when(predicate, effect, opts) {\n var timeoutHandle;\n\n if (typeof opts.timeout === \"number\") {\n var error = new Error(\"WHEN_TIMEOUT\");\n timeoutHandle = setTimeout(function () {\n if (!disposer[$mobx].isDisposed_) {\n disposer();\n\n if (opts.onError) {\n opts.onError(error);\n } else {\n throw error;\n }\n }\n }, opts.timeout);\n }\n\n opts.name = true ? opts.name || \"When@\" + getNextId() : undefined;\n var effectAction = createAction( true ? opts.name + \"-effect\" : undefined, effect); // eslint-disable-next-line\n\n var disposer = autorun(function (r) {\n // predicate should not change state\n var cond = allowStateChanges(false, predicate);\n\n if (cond) {\n r.dispose();\n\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n\n effectAction();\n }\n }, opts);\n return disposer;\n}\n\nfunction whenPromise(predicate, opts) {\n var _opts$signal;\n\n if ( true && opts && opts.onError) {\n return die(\"the options 'onError' and 'promise' cannot be combined\");\n }\n\n if (opts != null && (_opts$signal = opts.signal) != null && _opts$signal.aborted) {\n return Object.assign(Promise.reject(new Error(\"WHEN_ABORTED\")), {\n cancel: function cancel() {\n return null;\n }\n });\n }\n\n var cancel;\n var abort;\n var res = new Promise(function (resolve, reject) {\n var _opts$signal2;\n\n var disposer = _when(predicate, resolve, _extends({}, opts, {\n onError: reject\n }));\n\n cancel = function cancel() {\n disposer();\n reject(new Error(\"WHEN_CANCELLED\"));\n };\n\n abort = function abort() {\n disposer();\n reject(new Error(\"WHEN_ABORTED\"));\n };\n\n opts == null ? void 0 : (_opts$signal2 = opts.signal) == null ? void 0 : _opts$signal2.addEventListener(\"abort\", abort);\n })[\"finally\"](function () {\n var _opts$signal3;\n\n return opts == null ? void 0 : (_opts$signal3 = opts.signal) == null ? void 0 : _opts$signal3.removeEventListener(\"abort\", abort);\n });\n res.cancel = cancel;\n return res;\n}\n\nfunction getAdm(target) {\n return target[$mobx];\n} // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects,\n// and skip either the internal values map, or the base object with its property descriptors!\n\n\nvar objectProxyTraps = {\n has: function has(target, name) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"detect new properties using the 'in' operator. Use 'has' from 'mobx' instead.\");\n }\n\n return getAdm(target).has_(name);\n },\n get: function get(target, name) {\n return getAdm(target).get_(name);\n },\n set: function set(target, name, value) {\n var _getAdm$set_;\n\n if (!isStringish(name)) {\n return false;\n }\n\n if ( true && !getAdm(target).values_.has(name)) {\n warnAboutProxyRequirement(\"add a new observable property through direct assignment. Use 'set' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$set_ = getAdm(target).set_(name, value, true)) != null ? _getAdm$set_ : true;\n },\n deleteProperty: function deleteProperty(target, name) {\n var _getAdm$delete_;\n\n if (true) {\n warnAboutProxyRequirement(\"delete properties from an observable object. Use 'remove' from 'mobx' instead.\");\n }\n\n if (!isStringish(name)) {\n return false;\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$delete_ = getAdm(target).delete_(name, true)) != null ? _getAdm$delete_ : true;\n },\n defineProperty: function defineProperty(target, name, descriptor) {\n var _getAdm$definePropert;\n\n if (true) {\n warnAboutProxyRequirement(\"define property on an observable object. Use 'defineProperty' from 'mobx' instead.\");\n } // null (intercepted) -> true (success)\n\n\n return (_getAdm$definePropert = getAdm(target).defineProperty_(name, descriptor)) != null ? _getAdm$definePropert : true;\n },\n ownKeys: function ownKeys(target) {\n if ( true && globalState.trackingDerivation) {\n warnAboutProxyRequirement(\"iterate keys to detect added / removed properties. Use 'keys' from 'mobx' instead.\");\n }\n\n return getAdm(target).ownKeys_();\n },\n preventExtensions: function preventExtensions(target) {\n die(13);\n }\n};\nfunction asDynamicObservableObject(target, options) {\n var _target$$mobx, _target$$mobx$proxy_;\n\n assertProxies();\n target = asObservableObject(target, options);\n return (_target$$mobx$proxy_ = (_target$$mobx = target[$mobx]).proxy_) != null ? _target$$mobx$proxy_ : _target$$mobx.proxy_ = new Proxy(target, objectProxyTraps);\n}\n\nfunction hasInterceptors(interceptable) {\n return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0;\n}\nfunction registerInterceptor(interceptable, handler) {\n var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []);\n interceptors.push(handler);\n return once(function () {\n var idx = interceptors.indexOf(handler);\n\n if (idx !== -1) {\n interceptors.splice(idx, 1);\n }\n });\n}\nfunction interceptChange(interceptable, change) {\n var prevU = untrackedStart();\n\n try {\n // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950\n var interceptors = [].concat(interceptable.interceptors_ || []);\n\n for (var i = 0, l = interceptors.length; i < l; i++) {\n change = interceptors[i](change);\n\n if (change && !change.type) {\n die(14);\n }\n\n if (!change) {\n break;\n }\n }\n\n return change;\n } finally {\n untrackedEnd(prevU);\n }\n}\n\nfunction hasListeners(listenable) {\n return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0;\n}\nfunction registerListener(listenable, handler) {\n var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []);\n listeners.push(handler);\n return once(function () {\n var idx = listeners.indexOf(handler);\n\n if (idx !== -1) {\n listeners.splice(idx, 1);\n }\n });\n}\nfunction notifyListeners(listenable, change) {\n var prevU = untrackedStart();\n var listeners = listenable.changeListeners_;\n\n if (!listeners) {\n return;\n }\n\n listeners = listeners.slice();\n\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i](change);\n }\n\n untrackedEnd(prevU);\n}\n\nfunction makeObservable(target, annotations, options) {\n var adm = asObservableObject(target, options)[$mobx];\n startBatch();\n\n try {\n var _annotations;\n\n if ( true && annotations && target[storedAnnotationsSymbol]) {\n die(\"makeObservable second arg must be nullish when using decorators. Mixing @decorator syntax with annotations is not supported.\");\n } // Default to decorators\n\n\n (_annotations = annotations) != null ? _annotations : annotations = collectStoredAnnotations(target); // Annotate\n\n ownKeys(annotations).forEach(function (key) {\n return adm.make_(key, annotations[key]);\n });\n } finally {\n endBatch();\n }\n\n return target;\n} // proto[keysSymbol] = new Set()\n\nvar keysSymbol = /*#__PURE__*/Symbol(\"mobx-keys\");\nfunction makeAutoObservable(target, overrides, options) {\n if (true) {\n if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {\n die(\"'makeAutoObservable' can only be used for classes that don't have a superclass\");\n }\n\n if (isObservableObject(target)) {\n die(\"makeAutoObservable can only be used on objects not already made observable\");\n }\n } // Optimization: avoid visiting protos\n // Assumes that annotation.make_/.extend_ works the same for plain objects\n\n\n if (isPlainObject(target)) {\n return extendObservable(target, target, overrides, options);\n }\n\n var adm = asObservableObject(target, options)[$mobx]; // Optimization: cache keys on proto\n // Assumes makeAutoObservable can be called only once per object and can't be used in subclass\n\n if (!target[keysSymbol]) {\n var proto = Object.getPrototypeOf(target);\n var keys = new Set([].concat(ownKeys(target), ownKeys(proto)));\n keys[\"delete\"](\"constructor\");\n keys[\"delete\"]($mobx);\n addHiddenProp(proto, keysSymbol, keys);\n }\n\n startBatch();\n\n try {\n target[keysSymbol].forEach(function (key) {\n return adm.make_(key, // must pass \"undefined\" for { key: undefined }\n !overrides ? true : key in overrides ? overrides[key] : true);\n });\n } finally {\n endBatch();\n }\n\n return target;\n}\n\nvar SPLICE = \"splice\";\nvar UPDATE = \"update\";\nvar MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859\n\nvar arrayTraps = {\n get: function get(target, name) {\n var adm = target[$mobx];\n\n if (name === $mobx) {\n return adm;\n }\n\n if (name === \"length\") {\n return adm.getArrayLength_();\n }\n\n if (typeof name === \"string\" && !isNaN(name)) {\n return adm.get_(parseInt(name));\n }\n\n if (hasProp(arrayExtensions, name)) {\n return arrayExtensions[name];\n }\n\n return target[name];\n },\n set: function set(target, name, value) {\n var adm = target[$mobx];\n\n if (name === \"length\") {\n adm.setArrayLength_(value);\n }\n\n if (typeof name === \"symbol\" || isNaN(name)) {\n target[name] = value;\n } else {\n // numeric string\n adm.set_(parseInt(name), value);\n }\n\n return true;\n },\n preventExtensions: function preventExtensions() {\n die(15);\n }\n};\nvar ObservableArrayAdministration = /*#__PURE__*/function () {\n // this is the prop that gets proxied, so can't replace it!\n function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n this.owned_ = void 0;\n this.legacyMode_ = void 0;\n this.atom_ = void 0;\n this.values_ = [];\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.enhancer_ = void 0;\n this.dehancer = void 0;\n this.proxy_ = void 0;\n this.lastKnownLength_ = 0;\n this.owned_ = owned_;\n this.legacyMode_ = legacyMode_;\n this.atom_ = new Atom(name);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, true ? name + \"[..]\" : undefined);\n };\n }\n\n var _proto = ObservableArrayAdministration.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.dehanceValues_ = function dehanceValues_(values) {\n if (this.dehancer !== undefined && values.length > 0) {\n return values.map(this.dehancer);\n }\n\n return values;\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if (fireImmediately === void 0) {\n fireImmediately = false;\n }\n\n if (fireImmediately) {\n listener({\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: \"splice\",\n index: 0,\n added: this.values_.slice(),\n addedCount: this.values_.length,\n removed: [],\n removedCount: 0\n });\n }\n\n return registerListener(this, listener);\n };\n\n _proto.getArrayLength_ = function getArrayLength_() {\n this.atom_.reportObserved();\n return this.values_.length;\n };\n\n _proto.setArrayLength_ = function setArrayLength_(newLength) {\n if (typeof newLength !== \"number\" || isNaN(newLength) || newLength < 0) {\n die(\"Out of range: \" + newLength);\n }\n\n var currentLength = this.values_.length;\n\n if (newLength === currentLength) {\n return;\n } else if (newLength > currentLength) {\n var newItems = new Array(newLength - currentLength);\n\n for (var i = 0; i < newLength - currentLength; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n this.spliceWithArray_(currentLength, 0, newItems);\n } else {\n this.spliceWithArray_(newLength, currentLength - newLength);\n }\n };\n\n _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) {\n if (oldLength !== this.lastKnownLength_) {\n die(16);\n }\n\n this.lastKnownLength_ += delta;\n\n if (this.legacyMode_ && delta > 0) {\n reserveArrayBuffer(oldLength + delta + 1);\n }\n };\n\n _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) {\n var _this = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n var length = this.values_.length;\n\n if (index === undefined) {\n index = 0;\n } else if (index > length) {\n index = length;\n } else if (index < 0) {\n index = Math.max(0, length + index);\n }\n\n if (arguments.length === 1) {\n deleteCount = length - index;\n } else if (deleteCount === undefined || deleteCount === null) {\n deleteCount = 0;\n } else {\n deleteCount = Math.max(0, Math.min(deleteCount, length - index));\n }\n\n if (newItems === undefined) {\n newItems = EMPTY_ARRAY;\n }\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_,\n type: SPLICE,\n index: index,\n removedCount: deleteCount,\n added: newItems\n });\n\n if (!change) {\n return EMPTY_ARRAY;\n }\n\n deleteCount = change.removedCount;\n newItems = change.added;\n }\n\n newItems = newItems.length === 0 ? newItems : newItems.map(function (v) {\n return _this.enhancer_(v, undefined);\n });\n\n if (this.legacyMode_ || \"development\" !== \"production\") {\n var lengthDelta = newItems.length - deleteCount;\n this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified\n }\n\n var res = this.spliceItemsIntoValues_(index, deleteCount, newItems);\n\n if (deleteCount !== 0 || newItems.length !== 0) {\n this.notifyArraySplice_(index, newItems, res);\n }\n\n return this.dehanceValues_(res);\n };\n\n _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) {\n if (newItems.length < MAX_SPLICE_SIZE) {\n var _this$values_;\n\n return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems));\n } else {\n // The items removed by the splice\n var res = this.values_.slice(index, index + deleteCount); // The items that that should remain at the end of the array\n\n var oldItems = this.values_.slice(index + deleteCount); // New length is the previous length + addition count - deletion count\n\n this.values_.length += newItems.length - deleteCount;\n\n for (var i = 0; i < newItems.length; i++) {\n this.values_[index + i] = newItems[i];\n }\n\n for (var _i = 0; _i < oldItems.length; _i++) {\n this.values_[index + newItems.length + _i] = oldItems[_i];\n }\n\n return res;\n }\n };\n\n _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n type: UPDATE,\n debugObjectName: this.atom_.name_,\n index: index,\n newValue: newValue,\n oldValue: oldValue\n } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't\n // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged();\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) {\n var notifySpy = !this.owned_ && isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"array\",\n object: this.proxy_,\n debugObjectName: this.atom_.name_,\n type: SPLICE,\n index: index,\n removed: removed,\n added: added,\n removedCount: removed.length,\n addedCount: added.length\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n this.atom_.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get_ = function get_(index) {\n if (this.legacyMode_ && index >= this.values_.length) {\n console.warn( true ? \"[mobx.array] Attempt to read an array index (\" + index + \") that is out of bounds (\" + this.values_.length + \"). Please check length first. Out of bound indices will not be tracked by MobX\" : undefined);\n return undefined;\n }\n\n this.atom_.reportObserved();\n return this.dehanceValue_(this.values_[index]);\n };\n\n _proto.set_ = function set_(index, newValue) {\n var values = this.values_;\n\n if (this.legacyMode_ && index > values.length) {\n // out of bounds\n die(17, index, values.length);\n }\n\n if (index < values.length) {\n // update at index in range\n checkIfStateModificationsAreAllowed(this.atom_);\n var oldValue = values[index];\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_,\n index: index,\n newValue: newValue\n });\n\n if (!change) {\n return;\n }\n\n newValue = change.newValue;\n }\n\n newValue = this.enhancer_(newValue, oldValue);\n var changed = newValue !== oldValue;\n\n if (changed) {\n values[index] = newValue;\n this.notifyArrayChildUpdate_(index, newValue, oldValue);\n }\n } else {\n // For out of bound index, we don't create an actual sparse array,\n // but rather fill the holes with undefined (same as setArrayLength_).\n // This could be considered a bug.\n var newItems = new Array(index + 1 - values.length);\n\n for (var i = 0; i < newItems.length - 1; i++) {\n newItems[i] = undefined;\n } // No Array.fill everywhere...\n\n\n newItems[newItems.length - 1] = newValue;\n this.spliceWithArray_(values.length, 0, newItems);\n }\n };\n\n return ObservableArrayAdministration;\n}();\nfunction createObservableArray(initialValues, enhancer, name, owned) {\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n assertProxies();\n var adm = new ObservableArrayAdministration(name, enhancer, owned, false);\n addHiddenFinalProp(adm.values_, $mobx, adm);\n var proxy = new Proxy(adm.values_, arrayTraps);\n adm.proxy_ = proxy;\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true);\n adm.spliceWithArray_(0, 0, initialValues);\n allowStateChangesEnd(prev);\n }\n\n return proxy;\n} // eslint-disable-next-line\n\nvar arrayExtensions = {\n clear: function clear() {\n return this.splice(0);\n },\n replace: function replace(newItems) {\n var adm = this[$mobx];\n return adm.spliceWithArray_(0, adm.values_.length, newItems);\n },\n // Used by JSON.stringify\n toJSON: function toJSON() {\n return this.slice();\n },\n\n /*\r\n * functions that do alter the internal structure of the array, (based on lib.es6.d.ts)\r\n * since these functions alter the inner structure of the array, the have side effects.\r\n * Because the have side effects, they should not be used in computed function,\r\n * and for that reason the do not call dependencyState.notifyObserved\r\n */\n splice: function splice(index, deleteCount) {\n for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n newItems[_key - 2] = arguments[_key];\n }\n\n var adm = this[$mobx];\n\n switch (arguments.length) {\n case 0:\n return [];\n\n case 1:\n return adm.spliceWithArray_(index);\n\n case 2:\n return adm.spliceWithArray_(index, deleteCount);\n }\n\n return adm.spliceWithArray_(index, deleteCount, newItems);\n },\n spliceWithArray: function spliceWithArray(index, deleteCount, newItems) {\n return this[$mobx].spliceWithArray_(index, deleteCount, newItems);\n },\n push: function push() {\n var adm = this[$mobx];\n\n for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n items[_key2] = arguments[_key2];\n }\n\n adm.spliceWithArray_(adm.values_.length, 0, items);\n return adm.values_.length;\n },\n pop: function pop() {\n return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0];\n },\n shift: function shift() {\n return this.splice(0, 1)[0];\n },\n unshift: function unshift() {\n var adm = this[$mobx];\n\n for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n items[_key3] = arguments[_key3];\n }\n\n adm.spliceWithArray_(0, 0, items);\n return adm.values_.length;\n },\n reverse: function reverse() {\n // reverse by default mutates in place before returning the result\n // which makes it both a 'derivation' and a 'mutation'.\n if (globalState.trackingDerivation) {\n die(37, \"reverse\");\n }\n\n this.replace(this.slice().reverse());\n return this;\n },\n sort: function sort() {\n // sort by default mutates in place before returning the result\n // which goes against all good practices. Let's not change the array in place!\n if (globalState.trackingDerivation) {\n die(37, \"sort\");\n }\n\n var copy = this.slice();\n copy.sort.apply(copy, arguments);\n this.replace(copy);\n return this;\n },\n remove: function remove(value) {\n var adm = this[$mobx];\n var idx = adm.dehanceValues_(adm.values_).indexOf(value);\n\n if (idx > -1) {\n this.splice(idx, 1);\n return true;\n }\n\n return false;\n }\n};\n/**\r\n * Wrap function from prototype\r\n * Without this, everything works as well, but this works\r\n * faster as everything works on unproxied values\r\n */\n\naddArrayExtension(\"concat\", simpleFunc);\naddArrayExtension(\"flat\", simpleFunc);\naddArrayExtension(\"includes\", simpleFunc);\naddArrayExtension(\"indexOf\", simpleFunc);\naddArrayExtension(\"join\", simpleFunc);\naddArrayExtension(\"lastIndexOf\", simpleFunc);\naddArrayExtension(\"slice\", simpleFunc);\naddArrayExtension(\"toString\", simpleFunc);\naddArrayExtension(\"toLocaleString\", simpleFunc); // map\n\naddArrayExtension(\"every\", mapLikeFunc);\naddArrayExtension(\"filter\", mapLikeFunc);\naddArrayExtension(\"find\", mapLikeFunc);\naddArrayExtension(\"findIndex\", mapLikeFunc);\naddArrayExtension(\"flatMap\", mapLikeFunc);\naddArrayExtension(\"forEach\", mapLikeFunc);\naddArrayExtension(\"map\", mapLikeFunc);\naddArrayExtension(\"some\", mapLikeFunc); // reduce\n\naddArrayExtension(\"reduce\", reduceLikeFunc);\naddArrayExtension(\"reduceRight\", reduceLikeFunc);\n\nfunction addArrayExtension(funcName, funcFactory) {\n if (typeof Array.prototype[funcName] === \"function\") {\n arrayExtensions[funcName] = funcFactory(funcName);\n }\n} // Report and delegate to dehanced array\n\n\nfunction simpleFunc(funcName) {\n return function () {\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction mapLikeFunc(funcName) {\n return function (callback, thisArg) {\n var _this2 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_);\n return dehancedValues[funcName](function (element, index) {\n return callback.call(thisArg, element, index, _this2);\n });\n };\n} // Make sure callbacks recieve correct array arg #2326\n\n\nfunction reduceLikeFunc(funcName) {\n return function () {\n var _this3 = this;\n\n var adm = this[$mobx];\n adm.atom_.reportObserved();\n var dehancedValues = adm.dehanceValues_(adm.values_); // #2432 - reduce behavior depends on arguments.length\n\n var callback = arguments[0];\n\n arguments[0] = function (accumulator, currentValue, index) {\n return callback(accumulator, currentValue, index, _this3);\n };\n\n return dehancedValues[funcName].apply(dehancedValues, arguments);\n };\n}\n\nvar isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableArrayAdministration\", ObservableArrayAdministration);\nfunction isObservableArray(thing) {\n return isObject(thing) && isObservableArrayAdministration(thing[$mobx]);\n}\n\nvar _Symbol$iterator, _Symbol$toStringTag;\nvar ObservableMapMarker = {};\nvar ADD = \"add\";\nvar DELETE = \"delete\"; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54\n// But: https://github.com/mobxjs/mobx/issues/1556\n\n_Symbol$iterator = Symbol.iterator;\n_Symbol$toStringTag = Symbol.toStringTag;\nvar ObservableMap = /*#__PURE__*/function () {\n // hasMap, not hashMap >-).\n function ObservableMap(initialData, enhancer_, name_) {\n var _this = this;\n\n if (enhancer_ === void 0) {\n enhancer_ = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableMap@\" + getNextId() : undefined;\n }\n\n this.enhancer_ = void 0;\n this.name_ = void 0;\n this[$mobx] = ObservableMapMarker;\n this.data_ = void 0;\n this.hasMap_ = void 0;\n this.keysAtom_ = void 0;\n this.interceptors_ = void 0;\n this.changeListeners_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = enhancer_;\n this.name_ = name_;\n\n if (!isFunction(Map)) {\n die(18);\n }\n\n this.keysAtom_ = createAtom( true ? this.name_ + \".keys()\" : undefined);\n this.data_ = new Map();\n this.hasMap_ = new Map();\n allowStateChanges(true, function () {\n _this.merge(initialData);\n });\n }\n\n var _proto = ObservableMap.prototype;\n\n _proto.has_ = function has_(key) {\n return this.data_.has(key);\n };\n\n _proto.has = function has(key) {\n var _this2 = this;\n\n if (!globalState.trackingDerivation) {\n return this.has_(key);\n }\n\n var entry = this.hasMap_.get(key);\n\n if (!entry) {\n var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.hasMap_.set(key, newEntry);\n onBecomeUnobserved(newEntry, function () {\n return _this2.hasMap_[\"delete\"](key);\n });\n }\n\n return entry.get();\n };\n\n _proto.set = function set(key, value) {\n var hasKey = this.has_(key);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: hasKey ? UPDATE : ADD,\n object: this,\n newValue: value,\n name: key\n });\n\n if (!change) {\n return this;\n }\n\n value = change.newValue;\n }\n\n if (hasKey) {\n this.updateValue_(key, value);\n } else {\n this.addValue_(key, value);\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(key) {\n var _this3 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n name: key\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has_(key)) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: this.data_.get(key).value_,\n name: key\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n } // TODO fix type\n\n\n transaction(function () {\n var _this3$hasMap_$get;\n\n _this3.keysAtom_.reportChanged();\n\n (_this3$hasMap_$get = _this3.hasMap_.get(key)) == null ? void 0 : _this3$hasMap_$get.setNewValue_(false);\n\n var observable = _this3.data_.get(key);\n\n observable.setNewValue_(undefined);\n\n _this3.data_[\"delete\"](key);\n });\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.updateValue_ = function updateValue_(key, newValue) {\n var observable = this.data_.get(key);\n newValue = observable.prepareNewValue_(newValue);\n\n if (newValue !== globalState.UNCHANGED) {\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: UPDATE,\n object: this,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n };\n\n _proto.addValue_ = function addValue_(key, newValue) {\n var _this4 = this;\n\n checkIfStateModificationsAreAllowed(this.keysAtom_);\n transaction(function () {\n var _this4$hasMap_$get;\n\n var observable = new ObservableValue(newValue, _this4.enhancer_, true ? _this4.name_ + \".\" + stringifyKey(key) : undefined, false);\n\n _this4.data_.set(key, observable);\n\n newValue = observable.value_; // value might have been changed\n\n (_this4$hasMap_$get = _this4.hasMap_.get(key)) == null ? void 0 : _this4$hasMap_$get.setNewValue_(true);\n\n _this4.keysAtom_.reportChanged();\n });\n var notifySpy = isSpyEnabled();\n var notify = hasListeners(this);\n var change = notify || notifySpy ? {\n observableKind: \"map\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n } // TODO fix type\n\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n };\n\n _proto.get = function get(key) {\n if (this.has(key)) {\n return this.dehanceValue_(this.data_.get(key).get());\n }\n\n return this.dehanceValue_(undefined);\n };\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.keys = function keys() {\n this.keysAtom_.reportObserved();\n return this.data_.keys();\n };\n\n _proto.values = function values() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next = keys.next(),\n done = _keys$next.done,\n value = _keys$next.value;\n\n return {\n done: done,\n value: done ? undefined : self.get(value)\n };\n }\n });\n };\n\n _proto.entries = function entries() {\n var self = this;\n var keys = this.keys();\n return makeIterable({\n next: function next() {\n var _keys$next2 = keys.next(),\n done = _keys$next2.done,\n value = _keys$next2.value;\n\n return {\n done: done,\n value: done ? undefined : [value, self.get(value)]\n };\n }\n });\n };\n\n _proto[_Symbol$iterator] = function () {\n return this.entries();\n };\n\n _proto.forEach = function forEach(callback, thisArg) {\n for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) {\n var _step$value = _step.value,\n key = _step$value[0],\n value = _step$value[1];\n callback.call(thisArg, value, key, this);\n }\n }\n /** Merge another object into this object, returns this. */\n ;\n\n _proto.merge = function merge(other) {\n var _this5 = this;\n\n if (isObservableMap(other)) {\n other = new Map(other);\n }\n\n transaction(function () {\n if (isPlainObject(other)) {\n getPlainObjectKeys(other).forEach(function (key) {\n return _this5.set(key, other[key]);\n });\n } else if (Array.isArray(other)) {\n other.forEach(function (_ref) {\n var key = _ref[0],\n value = _ref[1];\n return _this5.set(key, value);\n });\n } else if (isES6Map(other)) {\n if (other.constructor !== Map) {\n die(19, other);\n }\n\n other.forEach(function (value, key) {\n return _this5.set(key, value);\n });\n } else if (other !== null && other !== undefined) {\n die(20, other);\n }\n });\n return this;\n };\n\n _proto.clear = function clear() {\n var _this6 = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator2 = _createForOfIteratorHelperLoose(_this6.keys()), _step2; !(_step2 = _iterator2()).done;) {\n var key = _step2.value;\n\n _this6[\"delete\"](key);\n }\n });\n });\n };\n\n _proto.replace = function replace(values) {\n var _this7 = this;\n\n // Implementation requirements:\n // - respect ordering of replacement map\n // - allow interceptors to run and potentially prevent individual operations\n // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions)\n // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!)\n // - note that result map may differ from replacement map due to the interceptors\n transaction(function () {\n // Convert to map so we can do quick key lookups\n var replacementMap = convertToMap(values);\n var orderedData = new Map(); // Used for optimization\n\n var keysReportChangedCalled = false; // Delete keys that don't exist in replacement map\n // if the key deletion is prevented by interceptor\n // add entry at the beginning of the result map\n\n for (var _iterator3 = _createForOfIteratorHelperLoose(_this7.data_.keys()), _step3; !(_step3 = _iterator3()).done;) {\n var key = _step3.value;\n\n // Concurrently iterating/deleting keys\n // iterator should handle this correctly\n if (!replacementMap.has(key)) {\n var deleted = _this7[\"delete\"](key); // Was the key removed?\n\n\n if (deleted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n } else {\n // Delete prevented by interceptor\n var value = _this7.data_.get(key);\n\n orderedData.set(key, value);\n }\n }\n } // Merge entries\n\n\n for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) {\n var _step4$value = _step4.value,\n _key = _step4$value[0],\n _value = _step4$value[1];\n\n // We will want to know whether a new key is added\n var keyExisted = _this7.data_.has(_key); // Add or update value\n\n\n _this7.set(_key, _value); // The addition could have been prevent by interceptor\n\n\n if (_this7.data_.has(_key)) {\n // The update could have been prevented by interceptor\n // and also we want to preserve existing values\n // so use value from _data map (instead of replacement map)\n var _value2 = _this7.data_.get(_key);\n\n orderedData.set(_key, _value2); // Was a new key added?\n\n if (!keyExisted) {\n // _keysAtom.reportChanged() was already called\n keysReportChangedCalled = true;\n }\n }\n } // Check for possible key order change\n\n\n if (!keysReportChangedCalled) {\n if (_this7.data_.size !== orderedData.size) {\n // If size differs, keys are definitely modified\n _this7.keysAtom_.reportChanged();\n } else {\n var iter1 = _this7.data_.keys();\n\n var iter2 = orderedData.keys();\n var next1 = iter1.next();\n var next2 = iter2.next();\n\n while (!next1.done) {\n if (next1.value !== next2.value) {\n _this7.keysAtom_.reportChanged();\n\n break;\n }\n\n next1 = iter1.next();\n next2 = iter2.next();\n }\n }\n } // Use correctly ordered map\n\n\n _this7.data_ = orderedData;\n });\n return this;\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableMap]\";\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n _proto.observe_ = function observe_(listener, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with maps.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _createClass(ObservableMap, [{\n key: \"size\",\n get: function get() {\n this.keysAtom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Map\";\n }\n }]);\n\n return ObservableMap;\n}(); // eslint-disable-next-line\n\nvar isObservableMap = /*#__PURE__*/createInstanceofPredicate(\"ObservableMap\", ObservableMap);\n\nfunction convertToMap(dataStructure) {\n if (isES6Map(dataStructure) || isObservableMap(dataStructure)) {\n return dataStructure;\n } else if (Array.isArray(dataStructure)) {\n return new Map(dataStructure);\n } else if (isPlainObject(dataStructure)) {\n var map = new Map();\n\n for (var key in dataStructure) {\n map.set(key, dataStructure[key]);\n }\n\n return map;\n } else {\n return die(21, dataStructure);\n }\n}\n\nvar _Symbol$iterator$1, _Symbol$toStringTag$1;\nvar ObservableSetMarker = {};\n_Symbol$iterator$1 = Symbol.iterator;\n_Symbol$toStringTag$1 = Symbol.toStringTag;\nvar ObservableSet = /*#__PURE__*/function () {\n function ObservableSet(initialData, enhancer, name_) {\n if (enhancer === void 0) {\n enhancer = deepEnhancer;\n }\n\n if (name_ === void 0) {\n name_ = true ? \"ObservableSet@\" + getNextId() : undefined;\n }\n\n this.name_ = void 0;\n this[$mobx] = ObservableSetMarker;\n this.data_ = new Set();\n this.atom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.dehancer = void 0;\n this.enhancer_ = void 0;\n this.name_ = name_;\n\n if (!isFunction(Set)) {\n die(22);\n }\n\n this.atom_ = createAtom(this.name_);\n\n this.enhancer_ = function (newV, oldV) {\n return enhancer(newV, oldV, name_);\n };\n\n if (initialData) {\n this.replace(initialData);\n }\n }\n\n var _proto = ObservableSet.prototype;\n\n _proto.dehanceValue_ = function dehanceValue_(value) {\n if (this.dehancer !== undefined) {\n return this.dehancer(value);\n }\n\n return value;\n };\n\n _proto.clear = function clear() {\n var _this = this;\n\n transaction(function () {\n untracked(function () {\n for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) {\n var value = _step.value;\n\n _this[\"delete\"](value);\n }\n });\n });\n };\n\n _proto.forEach = function forEach(callbackFn, thisArg) {\n for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) {\n var value = _step2.value;\n callbackFn.call(thisArg, value, value, this);\n }\n };\n\n _proto.add = function add(value) {\n var _this2 = this;\n\n checkIfStateModificationsAreAllowed(this.atom_);\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: ADD,\n object: this,\n newValue: value\n });\n\n if (!change) {\n return this;\n } // ideally, value = change.value would be done here, so that values can be\n // changed by interceptor. Same applies for other Set and Map api's.\n\n }\n\n if (!this.has(value)) {\n transaction(function () {\n _this2.data_.add(_this2.enhancer_(value, undefined));\n\n _this2.atom_.reportChanged();\n });\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: ADD,\n object: this,\n newValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change);\n }\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n }\n\n return this;\n };\n\n _proto[\"delete\"] = function _delete(value) {\n var _this3 = this;\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: DELETE,\n object: this,\n oldValue: value\n });\n\n if (!change) {\n return false;\n }\n }\n\n if (this.has(value)) {\n var notifySpy = true && isSpyEnabled();\n var notify = hasListeners(this);\n\n var _change2 = notify || notifySpy ? {\n observableKind: \"set\",\n debugObjectName: this.name_,\n type: DELETE,\n object: this,\n oldValue: value\n } : null;\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportStart(_change2);\n }\n\n transaction(function () {\n _this3.atom_.reportChanged();\n\n _this3.data_[\"delete\"](value);\n });\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if (notifySpy && \"development\" !== \"production\") {\n spyReportEnd();\n }\n\n return true;\n }\n\n return false;\n };\n\n _proto.has = function has(value) {\n this.atom_.reportObserved();\n return this.data_.has(this.dehanceValue_(value));\n };\n\n _proto.entries = function entries() {\n var nextIndex = 0;\n var keys = Array.from(this.keys());\n var values = Array.from(this.values());\n return makeIterable({\n next: function next() {\n var index = nextIndex;\n nextIndex += 1;\n return index < values.length ? {\n value: [keys[index], values[index]],\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.keys = function keys() {\n return this.values();\n };\n\n _proto.values = function values() {\n this.atom_.reportObserved();\n var self = this;\n var nextIndex = 0;\n var observableValues = Array.from(this.data_.values());\n return makeIterable({\n next: function next() {\n return nextIndex < observableValues.length ? {\n value: self.dehanceValue_(observableValues[nextIndex++]),\n done: false\n } : {\n done: true\n };\n }\n });\n };\n\n _proto.replace = function replace(other) {\n var _this4 = this;\n\n if (isObservableSet(other)) {\n other = new Set(other);\n }\n\n transaction(function () {\n if (Array.isArray(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (isES6Set(other)) {\n _this4.clear();\n\n other.forEach(function (value) {\n return _this4.add(value);\n });\n } else if (other !== null && other !== undefined) {\n die(\"Cannot initialize set from \" + other);\n }\n });\n return this;\n };\n\n _proto.observe_ = function observe_(listener, fireImmediately) {\n // ... 'fireImmediately' could also be true?\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support fireImmediately=true in combination with sets.\");\n }\n\n return registerListener(this, listener);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.toJSON = function toJSON() {\n return Array.from(this);\n };\n\n _proto.toString = function toString() {\n return \"[object ObservableSet]\";\n };\n\n _proto[_Symbol$iterator$1] = function () {\n return this.values();\n };\n\n _createClass(ObservableSet, [{\n key: \"size\",\n get: function get() {\n this.atom_.reportObserved();\n return this.data_.size;\n }\n }, {\n key: _Symbol$toStringTag$1,\n get: function get() {\n return \"Set\";\n }\n }]);\n\n return ObservableSet;\n}(); // eslint-disable-next-line\n\nvar isObservableSet = /*#__PURE__*/createInstanceofPredicate(\"ObservableSet\", ObservableSet);\n\nvar descriptorCache = /*#__PURE__*/Object.create(null);\nvar REMOVE = \"remove\";\nvar ObservableObjectAdministration = /*#__PURE__*/function () {\n function ObservableObjectAdministration(target_, values_, name_, // Used anytime annotation is not explicitely provided\n defaultAnnotation_) {\n if (values_ === void 0) {\n values_ = new Map();\n }\n\n if (defaultAnnotation_ === void 0) {\n defaultAnnotation_ = autoAnnotation;\n }\n\n this.target_ = void 0;\n this.values_ = void 0;\n this.name_ = void 0;\n this.defaultAnnotation_ = void 0;\n this.keysAtom_ = void 0;\n this.changeListeners_ = void 0;\n this.interceptors_ = void 0;\n this.proxy_ = void 0;\n this.isPlainObject_ = void 0;\n this.appliedAnnotations_ = void 0;\n this.pendingKeys_ = void 0;\n this.target_ = target_;\n this.values_ = values_;\n this.name_ = name_;\n this.defaultAnnotation_ = defaultAnnotation_;\n this.keysAtom_ = new Atom( true ? this.name_ + \".keys\" : undefined); // Optimization: we use this frequently\n\n this.isPlainObject_ = isPlainObject(this.target_);\n\n if ( true && !isAnnotation(this.defaultAnnotation_)) {\n die(\"defaultAnnotation must be valid annotation\");\n }\n\n if (true) {\n // Prepare structure for tracking which fields were already annotated\n this.appliedAnnotations_ = {};\n }\n }\n\n var _proto = ObservableObjectAdministration.prototype;\n\n _proto.getObservablePropValue_ = function getObservablePropValue_(key) {\n return this.values_.get(key).get();\n };\n\n _proto.setObservablePropValue_ = function setObservablePropValue_(key, newValue) {\n var observable = this.values_.get(key);\n\n if (observable instanceof ComputedValue) {\n observable.set(newValue);\n return true;\n } // intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n type: UPDATE,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: newValue\n });\n\n if (!change) {\n return null;\n }\n\n newValue = change.newValue;\n }\n\n newValue = observable.prepareNewValue_(newValue); // notify spy & observers\n\n if (newValue !== globalState.UNCHANGED) {\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n var _change = notify || notifySpy ? {\n type: UPDATE,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n oldValue: observable.value_,\n name: key,\n newValue: newValue\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(_change);\n }\n observable.setNewValue_(newValue);\n\n if (notify) {\n notifyListeners(this, _change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n return true;\n };\n\n _proto.get_ = function get_(key) {\n if (globalState.trackingDerivation && !hasProp(this.target_, key)) {\n // Key doesn't exist yet, subscribe for it in case it's added later\n this.has_(key);\n }\n\n return this.target_[key];\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {any} value\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.set_ = function set_(key, value, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // Don't use .has(key) - we care about own\n if (hasProp(this.target_, key)) {\n // Existing prop\n if (this.values_.has(key)) {\n // Observable (can be intercepted)\n return this.setObservablePropValue_(key, value);\n } else if (proxyTrap) {\n // Non-observable - proxy\n return Reflect.set(this.target_, key, value);\n } else {\n // Non-observable\n this.target_[key] = value;\n return true;\n }\n } else {\n // New prop\n return this.extend_(key, {\n value: value,\n enumerable: true,\n writable: true,\n configurable: true\n }, this.defaultAnnotation_, proxyTrap);\n }\n } // Trap for \"in\"\n ;\n\n _proto.has_ = function has_(key) {\n if (!globalState.trackingDerivation) {\n // Skip key subscription outside derivation\n return key in this.target_;\n }\n\n this.pendingKeys_ || (this.pendingKeys_ = new Map());\n var entry = this.pendingKeys_.get(key);\n\n if (!entry) {\n entry = new ObservableValue(key in this.target_, referenceEnhancer, true ? this.name_ + \".\" + stringifyKey(key) + \"?\" : undefined, false);\n this.pendingKeys_.set(key, entry);\n }\n\n return entry.get();\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - ignore prop\r\n */\n ;\n\n _proto.make_ = function make_(key, annotation) {\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return;\n }\n\n assertAnnotable(this, annotation, key);\n\n if (!(key in this.target_)) {\n var _this$target_$storedA;\n\n // Throw on missing key, except for decorators:\n // Decorator annotations are collected from whole prototype chain.\n // When called from super() some props may not exist yet.\n // However we don't have to worry about missing prop,\n // because the decorator must have been applied to something.\n if ((_this$target_$storedA = this.target_[storedAnnotationsSymbol]) != null && _this$target_$storedA[key]) {\n return; // will be annotated by subclass constructor\n } else {\n die(1, annotation.annotationType_, this.name_ + \".\" + key.toString());\n }\n }\n\n var source = this.target_;\n\n while (source && source !== objectPrototype) {\n var descriptor = getDescriptor(source, key);\n\n if (descriptor) {\n var outcome = annotation.make_(this, key, descriptor, source);\n\n if (outcome === 0\n /* Cancel */\n ) {\n return;\n }\n\n if (outcome === 1\n /* Break */\n ) {\n break;\n }\n }\n\n source = Object.getPrototypeOf(source);\n }\n\n recordAnnotationApplied(this, annotation, key);\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {Annotation|boolean} annotation true - use default annotation, false - copy as is\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.extend_ = function extend_(key, descriptor, annotation, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n if (annotation === true) {\n annotation = this.defaultAnnotation_;\n }\n\n if (annotation === false) {\n return this.defineProperty_(key, descriptor, proxyTrap);\n }\n\n assertAnnotable(this, annotation, key);\n var outcome = annotation.extend_(this, key, descriptor, proxyTrap);\n\n if (outcome) {\n recordAnnotationApplied(this, annotation, key);\n }\n\n return outcome;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.defineProperty_ = function defineProperty_(key, descriptor, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: descriptor.value\n });\n\n if (!change) {\n return null;\n }\n\n var newValue = change.newValue;\n\n if (descriptor.value !== newValue) {\n descriptor = _extends({}, descriptor, {\n value: newValue\n });\n }\n } // Define\n\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n } // Notify\n\n\n this.notifyPropertyAddition_(key, descriptor.value);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineObservableProperty_ = function defineObservableProperty_(key, value, enhancer, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: value\n });\n\n if (!change) {\n return null;\n }\n\n value = change.newValue;\n }\n\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: true,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n var observable = new ObservableValue(value, enhancer, true ? this.name_ + \".\" + key.toString() : undefined, false);\n this.values_.set(key, observable); // Notify (value possibly changed by ObservableValue)\n\n this.notifyPropertyAddition_(key, observable.value_);\n } finally {\n endBatch();\n }\n\n return true;\n } // If original descriptor becomes relevant, move this to annotation directly\n ;\n\n _proto.defineComputedProperty_ = function defineComputedProperty_(key, options, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n try {\n startBatch(); // Delete\n\n var deleteOutcome = this.delete_(key);\n\n if (!deleteOutcome) {\n // Failure or intercepted\n return deleteOutcome;\n } // ADD interceptor\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: ADD,\n newValue: undefined\n });\n\n if (!change) {\n return null;\n }\n }\n\n options.name || (options.name = true ? this.name_ + \".\" + key.toString() : undefined);\n options.context = this.proxy_ || this.target_;\n var cachedDescriptor = getCachedObservablePropDescriptor(key);\n var descriptor = {\n configurable: globalState.safeDescriptors ? this.isPlainObject_ : true,\n enumerable: false,\n get: cachedDescriptor.get,\n set: cachedDescriptor.set\n }; // Define\n\n if (proxyTrap) {\n if (!Reflect.defineProperty(this.target_, key, descriptor)) {\n return false;\n }\n } else {\n defineProperty(this.target_, key, descriptor);\n }\n\n this.values_.set(key, new ComputedValue(options)); // Notify\n\n this.notifyPropertyAddition_(key, undefined);\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * @param {PropertyKey} key\r\n * @param {PropertyDescriptor} descriptor\r\n * @param {boolean} proxyTrap whether it's called from proxy trap\r\n * @returns {boolean|null} true on success, false on failure (proxyTrap + non-configurable), null when cancelled by interceptor\r\n */\n ;\n\n _proto.delete_ = function delete_(key, proxyTrap) {\n if (proxyTrap === void 0) {\n proxyTrap = false;\n }\n\n // No such prop\n if (!hasProp(this.target_, key)) {\n return true;\n } // Intercept\n\n\n if (hasInterceptors(this)) {\n var change = interceptChange(this, {\n object: this.proxy_ || this.target_,\n name: key,\n type: REMOVE\n }); // Cancelled\n\n if (!change) {\n return null;\n }\n } // Delete\n\n\n try {\n var _this$pendingKeys_, _this$pendingKeys_$ge;\n\n startBatch();\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n var observable = this.values_.get(key); // Value needed for spies/listeners\n\n var value = undefined; // Optimization: don't pull the value unless we will need it\n\n if (!observable && (notify || notifySpy)) {\n var _getDescriptor;\n\n value = (_getDescriptor = getDescriptor(this.target_, key)) == null ? void 0 : _getDescriptor.value;\n } // delete prop (do first, may fail)\n\n\n if (proxyTrap) {\n if (!Reflect.deleteProperty(this.target_, key)) {\n return false;\n }\n } else {\n delete this.target_[key];\n } // Allow re-annotating this field\n\n\n if (true) {\n delete this.appliedAnnotations_[key];\n } // Clear observable\n\n\n if (observable) {\n this.values_[\"delete\"](key); // for computed, value is undefined\n\n if (observable instanceof ObservableValue) {\n value = observable.value_;\n } // Notify: autorun(() => obj[key]), see #1796\n\n\n propagateChanged(observable);\n } // Notify \"keys/entries/values\" observers\n\n\n this.keysAtom_.reportChanged(); // Notify \"has\" observers\n // \"in\" as it may still exist in proto\n\n (_this$pendingKeys_ = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_$ge = _this$pendingKeys_.get(key)) == null ? void 0 : _this$pendingKeys_$ge.set(key in this.target_); // Notify spies/listeners\n\n if (notify || notifySpy) {\n var _change2 = {\n type: REMOVE,\n observableKind: \"object\",\n object: this.proxy_ || this.target_,\n debugObjectName: this.name_,\n oldValue: value,\n name: key\n };\n\n if ( true && notifySpy) {\n spyReportStart(_change2);\n }\n\n if (notify) {\n notifyListeners(this, _change2);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n } finally {\n endBatch();\n }\n\n return true;\n }\n /**\r\n * Observes this object. Triggers for the events 'add', 'update' and 'delete'.\r\n * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe\r\n * for callback details\r\n */\n ;\n\n _proto.observe_ = function observe_(callback, fireImmediately) {\n if ( true && fireImmediately === true) {\n die(\"`observe` doesn't support the fire immediately property for observable objects.\");\n }\n\n return registerListener(this, callback);\n };\n\n _proto.intercept_ = function intercept_(handler) {\n return registerInterceptor(this, handler);\n };\n\n _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, value) {\n var _this$pendingKeys_2, _this$pendingKeys_2$g;\n\n var notify = hasListeners(this);\n var notifySpy = true && isSpyEnabled();\n\n if (notify || notifySpy) {\n var change = notify || notifySpy ? {\n type: ADD,\n observableKind: \"object\",\n debugObjectName: this.name_,\n object: this.proxy_ || this.target_,\n name: key,\n newValue: value\n } : null;\n\n if ( true && notifySpy) {\n spyReportStart(change);\n }\n\n if (notify) {\n notifyListeners(this, change);\n }\n\n if ( true && notifySpy) {\n spyReportEnd();\n }\n }\n\n (_this$pendingKeys_2 = this.pendingKeys_) == null ? void 0 : (_this$pendingKeys_2$g = _this$pendingKeys_2.get(key)) == null ? void 0 : _this$pendingKeys_2$g.set(true); // Notify \"keys/entries/values\" observers\n\n this.keysAtom_.reportChanged();\n };\n\n _proto.ownKeys_ = function ownKeys_() {\n this.keysAtom_.reportObserved();\n return ownKeys(this.target_);\n };\n\n _proto.keys_ = function keys_() {\n // Returns enumerable && own, but unfortunately keysAtom will report on ANY key change.\n // There is no way to distinguish between Object.keys(object) and Reflect.ownKeys(object) - both are handled by ownKeys trap.\n // We can either over-report in Object.keys(object) or under-report in Reflect.ownKeys(object)\n // We choose to over-report in Object.keys(object), because:\n // - typically it's used with simple data objects\n // - when symbolic/non-enumerable keys are relevant Reflect.ownKeys works as expected\n this.keysAtom_.reportObserved();\n return Object.keys(this.target_);\n };\n\n return ObservableObjectAdministration;\n}();\nfunction asObservableObject(target, options) {\n var _options$name;\n\n if ( true && options && isObservableObject(target)) {\n die(\"Options can't be provided for already observable objects.\");\n }\n\n if (hasProp(target, $mobx)) {\n if ( true && !(getAdministration(target) instanceof ObservableObjectAdministration)) {\n die(\"Cannot convert '\" + getDebugName(target) + \"' into observable object:\" + \"\\nThe target is already observable of different type.\" + \"\\nExtending builtins is not supported.\");\n }\n\n return target;\n }\n\n if ( true && !Object.isExtensible(target)) {\n die(\"Cannot make the designated object observable; it is not extensible\");\n }\n\n var name = (_options$name = options == null ? void 0 : options.name) != null ? _options$name : true ? (isPlainObject(target) ? \"ObservableObject\" : target.constructor.name) + \"@\" + getNextId() : undefined;\n var adm = new ObservableObjectAdministration(target, new Map(), String(name), getAnnotationFromOptions(options));\n addHiddenProp(target, $mobx, adm);\n return target;\n}\nvar isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate(\"ObservableObjectAdministration\", ObservableObjectAdministration);\n\nfunction getCachedObservablePropDescriptor(key) {\n return descriptorCache[key] || (descriptorCache[key] = {\n get: function get() {\n return this[$mobx].getObservablePropValue_(key);\n },\n set: function set(value) {\n return this[$mobx].setObservablePropValue_(key, value);\n }\n });\n}\n\nfunction isObservableObject(thing) {\n if (isObject(thing)) {\n return isObservableObjectAdministration(thing[$mobx]);\n }\n\n return false;\n}\nfunction recordAnnotationApplied(adm, annotation, key) {\n var _adm$target_$storedAn;\n\n if (true) {\n adm.appliedAnnotations_[key] = annotation;\n } // Remove applied decorator annotation so we don't try to apply it again in subclass constructor\n\n\n (_adm$target_$storedAn = adm.target_[storedAnnotationsSymbol]) == null ? true : delete _adm$target_$storedAn[key];\n}\n\nfunction assertAnnotable(adm, annotation, key) {\n // Valid annotation\n if ( true && !isAnnotation(annotation)) {\n die(\"Cannot annotate '\" + adm.name_ + \".\" + key.toString() + \"': Invalid annotation.\");\n }\n /*\r\n // Configurable, not sealed, not frozen\r\n // Possibly not needed, just a little better error then the one thrown by engine.\r\n // Cases where this would be useful the most (subclass field initializer) are not interceptable by this.\r\n if (__DEV__) {\r\n const configurable = getDescriptor(adm.target_, key)?.configurable\r\n const frozen = Object.isFrozen(adm.target_)\r\n const sealed = Object.isSealed(adm.target_)\r\n if (!configurable || frozen || sealed) {\r\n const fieldName = `${adm.name_}.${key.toString()}`\r\n const requestedAnnotationType = annotation.annotationType_\r\n let error = `Cannot apply '${requestedAnnotationType}' to '${fieldName}':`\r\n if (frozen) {\r\n error += `\\nObject is frozen.`\r\n }\r\n if (sealed) {\r\n error += `\\nObject is sealed.`\r\n }\r\n if (!configurable) {\r\n error += `\\nproperty is not configurable.`\r\n // Mention only if caused by us to avoid confusion\r\n if (hasProp(adm.appliedAnnotations!, key)) {\r\n error += `\\nTo prevent accidental re-definition of a field by a subclass, `\r\n error += `all annotated fields of non-plain objects (classes) are not configurable.`\r\n }\r\n }\r\n die(error)\r\n }\r\n }\r\n */\n // Not annotated\n\n\n if ( true && !isOverride(annotation) && hasProp(adm.appliedAnnotations_, key)) {\n var fieldName = adm.name_ + \".\" + key.toString();\n var currentAnnotationType = adm.appliedAnnotations_[key].annotationType_;\n var requestedAnnotationType = annotation.annotationType_;\n die(\"Cannot apply '\" + requestedAnnotationType + \"' to '\" + fieldName + \"':\" + (\"\\nThe field is already annotated with '\" + currentAnnotationType + \"'.\") + \"\\nRe-annotating fields is not allowed.\" + \"\\nUse 'override' annotation for methods overridden by subclass.\");\n }\n}\n\nvar ENTRY_0 = /*#__PURE__*/createArrayEntryDescriptor(0);\n/**\r\n * This array buffer contains two lists of properties, so that all arrays\r\n * can recycle their property definitions, which significantly improves performance of creating\r\n * properties on the fly.\r\n */\n\n\nvar OBSERVABLE_ARRAY_BUFFER_SIZE = 0; // Typescript workaround to make sure ObservableArray extends Array\n\nvar StubArray = function StubArray() {};\n\nfunction inherit(ctor, proto) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(ctor.prototype, proto);\n } else if (ctor.prototype.__proto__ !== undefined) {\n ctor.prototype.__proto__ = proto;\n } else {\n ctor.prototype = proto;\n }\n}\n\ninherit(StubArray, Array.prototype); // Weex proto freeze protection was here,\n// but it is unclear why the hack is need as MobX never changed the prototype\n// anyway, so removed it in V6\n\nvar LegacyObservableArray = /*#__PURE__*/function (_StubArray, _Symbol$toStringTag, _Symbol$iterator) {\n _inheritsLoose(LegacyObservableArray, _StubArray);\n\n function LegacyObservableArray(initialValues, enhancer, name, owned) {\n var _this;\n\n if (name === void 0) {\n name = true ? \"ObservableArray@\" + getNextId() : undefined;\n }\n\n if (owned === void 0) {\n owned = false;\n }\n\n _this = _StubArray.call(this) || this;\n var adm = new ObservableArrayAdministration(name, enhancer, owned, true);\n adm.proxy_ = _assertThisInitialized(_this);\n addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm);\n\n if (initialValues && initialValues.length) {\n var prev = allowStateChangesStart(true); // @ts-ignore\n\n _this.spliceWithArray(0, 0, initialValues);\n\n allowStateChangesEnd(prev);\n }\n\n {\n // Seems that Safari won't use numeric prototype setter untill any * numeric property is\n // defined on the instance. After that it works fine, even if this property is deleted.\n Object.defineProperty(_assertThisInitialized(_this), \"0\", ENTRY_0);\n }\n\n return _this;\n }\n\n var _proto = LegacyObservableArray.prototype;\n\n _proto.concat = function concat() {\n this[$mobx].atom_.reportObserved();\n\n for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) {\n arrays[_key] = arguments[_key];\n }\n\n return Array.prototype.concat.apply(this.slice(), //@ts-ignore\n arrays.map(function (a) {\n return isObservableArray(a) ? a.slice() : a;\n }));\n };\n\n _proto[_Symbol$iterator] = function () {\n var self = this;\n var nextIndex = 0;\n return makeIterable({\n next: function next() {\n return nextIndex < self.length ? {\n value: self[nextIndex++],\n done: false\n } : {\n done: true,\n value: undefined\n };\n }\n });\n };\n\n _createClass(LegacyObservableArray, [{\n key: \"length\",\n get: function get() {\n return this[$mobx].getArrayLength_();\n },\n set: function set(newLength) {\n this[$mobx].setArrayLength_(newLength);\n }\n }, {\n key: _Symbol$toStringTag,\n get: function get() {\n return \"Array\";\n }\n }]);\n\n return LegacyObservableArray;\n}(StubArray, Symbol.toStringTag, Symbol.iterator);\n\nObject.entries(arrayExtensions).forEach(function (_ref) {\n var prop = _ref[0],\n fn = _ref[1];\n\n if (prop !== \"concat\") {\n addHiddenProp(LegacyObservableArray.prototype, prop, fn);\n }\n});\n\nfunction createArrayEntryDescriptor(index) {\n return {\n enumerable: false,\n configurable: true,\n get: function get() {\n return this[$mobx].get_(index);\n },\n set: function set(value) {\n this[$mobx].set_(index, value);\n }\n };\n}\n\nfunction createArrayBufferItem(index) {\n defineProperty(LegacyObservableArray.prototype, \"\" + index, createArrayEntryDescriptor(index));\n}\n\nfunction reserveArrayBuffer(max) {\n if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) {\n for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) {\n createArrayBufferItem(index);\n }\n\n OBSERVABLE_ARRAY_BUFFER_SIZE = max;\n }\n}\nreserveArrayBuffer(1000);\nfunction createLegacyArray(initialValues, enhancer, name) {\n return new LegacyObservableArray(initialValues, enhancer, name);\n}\n\nfunction getAtom(thing, property) {\n if (typeof thing === \"object\" && thing !== null) {\n if (isObservableArray(thing)) {\n if (property !== undefined) {\n die(23);\n }\n\n return thing[$mobx].atom_;\n }\n\n if (isObservableSet(thing)) {\n return thing[$mobx];\n }\n\n if (isObservableMap(thing)) {\n if (property === undefined) {\n return thing.keysAtom_;\n }\n\n var observable = thing.data_.get(property) || thing.hasMap_.get(property);\n\n if (!observable) {\n die(25, property, getDebugName(thing));\n }\n\n return observable;\n }\n\n\n if (isObservableObject(thing)) {\n if (!property) {\n return die(26);\n }\n\n var _observable = thing[$mobx].values_.get(property);\n\n if (!_observable) {\n die(27, property, getDebugName(thing));\n }\n\n return _observable;\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n } else if (isFunction(thing)) {\n if (isReaction(thing[$mobx])) {\n // disposer function\n return thing[$mobx];\n }\n }\n\n die(28);\n}\nfunction getAdministration(thing, property) {\n if (!thing) {\n die(29);\n }\n\n if (property !== undefined) {\n return getAdministration(getAtom(thing, property));\n }\n\n if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) {\n return thing;\n }\n\n if (isObservableMap(thing) || isObservableSet(thing)) {\n return thing;\n }\n\n if (thing[$mobx]) {\n return thing[$mobx];\n }\n\n die(24, thing);\n}\nfunction getDebugName(thing, property) {\n var named;\n\n if (property !== undefined) {\n named = getAtom(thing, property);\n } else if (isAction(thing)) {\n return thing.name;\n } else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) {\n named = getAdministration(thing);\n } else {\n // valid for arrays as well\n named = getAtom(thing);\n }\n\n return named.name_;\n}\n\nvar toString = objectPrototype.toString;\nfunction deepEqual(a, b, depth) {\n if (depth === void 0) {\n depth = -1;\n }\n\n return eq(a, b, depth);\n} // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289\n// Internal recursive comparison function for `isEqual`.\n\nfunction eq(a, b, depth, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) {\n return a !== 0 || 1 / a === 1 / b;\n } // `null` or `undefined` only equal to itself (strict comparison).\n\n\n if (a == null || b == null) {\n return false;\n } // `NaN`s are equivalent, but non-reflexive.\n\n\n if (a !== a) {\n return b !== b;\n } // Exhaust primitive checks\n\n\n var type = typeof a;\n\n if (type !== \"function\" && type !== \"object\" && typeof b != \"object\") {\n return false;\n } // Compare `[[Class]]` names.\n\n\n var className = toString.call(a);\n\n if (className !== toString.call(b)) {\n return false;\n }\n\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case \"[object RegExp]\": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n\n case \"[object String]\":\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return \"\" + a === \"\" + b;\n\n case \"[object Number]\":\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN.\n if (+a !== +a) {\n return +b !== +b;\n } // An `egal` comparison is performed for other numeric values.\n\n\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n\n case \"[object Date]\":\n case \"[object Boolean]\":\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n\n case \"[object Symbol]\":\n return typeof Symbol !== \"undefined\" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b);\n\n case \"[object Map]\":\n case \"[object Set]\":\n // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level.\n // Hide this extra level by increasing the depth.\n if (depth >= 0) {\n depth++;\n }\n\n break;\n } // Unwrap any wrapped objects.\n\n\n a = unwrap(a);\n b = unwrap(b);\n var areArrays = className === \"[object Array]\";\n\n if (!areArrays) {\n if (typeof a != \"object\" || typeof b != \"object\") {\n return false;\n } // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n\n\n var aCtor = a.constructor,\n bCtor = b.constructor;\n\n if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && \"constructor\" in a && \"constructor\" in b) {\n return false;\n }\n }\n\n if (depth === 0) {\n return false;\n } else if (depth < 0) {\n depth = -1;\n } // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n\n\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) {\n return bStack[length] === b;\n }\n } // Add the first object to the stack of traversed objects.\n\n\n aStack.push(a);\n bStack.push(b); // Recursively compare objects and arrays.\n\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n\n if (length !== b.length) {\n return false;\n } // Deep compare the contents, ignoring non-numeric properties.\n\n\n while (length--) {\n if (!eq(a[length], b[length], depth - 1, aStack, bStack)) {\n return false;\n }\n }\n } else {\n // Deep compare objects.\n var keys = Object.keys(a);\n var key;\n length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality.\n\n if (Object.keys(b).length !== length) {\n return false;\n }\n\n while (length--) {\n // Deep compare each member\n key = keys[length];\n\n if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) {\n return false;\n }\n }\n } // Remove the first object from the stack of traversed objects.\n\n\n aStack.pop();\n bStack.pop();\n return true;\n}\n\nfunction unwrap(a) {\n if (isObservableArray(a)) {\n return a.slice();\n }\n\n if (isES6Map(a) || isObservableMap(a)) {\n return Array.from(a.entries());\n }\n\n if (isES6Set(a) || isObservableSet(a)) {\n return Array.from(a.entries());\n }\n\n return a;\n}\n\nfunction makeIterable(iterator) {\n iterator[Symbol.iterator] = getSelf;\n return iterator;\n}\n\nfunction getSelf() {\n return this;\n}\n\nfunction isAnnotation(thing) {\n return (// Can be function\n thing instanceof Object && typeof thing.annotationType_ === \"string\" && isFunction(thing.make_) && isFunction(thing.extend_)\n );\n}\n\n/**\r\n * (c) Michel Weststrate 2015 - 2020\r\n * MIT Licensed\r\n *\r\n * Welcome to the mobx sources! To get a global overview of how MobX internally works,\r\n * this is a good place to start:\r\n * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74\r\n *\r\n * Source folders:\r\n * ===============\r\n *\r\n * - api/ Most of the public static methods exposed by the module can be found here.\r\n * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here.\r\n * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`.\r\n * - utils/ Utility stuff.\r\n *\r\n */\n[\"Symbol\", \"Map\", \"Set\"].forEach(function (m) {\n var g = getGlobal();\n\n if (typeof g[m] === \"undefined\") {\n die(\"MobX requires global '\" + m + \"' to be available or polyfilled\");\n }\n});\n\nif (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === \"object\") {\n // See: https://github.com/andykog/mobx-devtools/\n __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({\n spy: spy,\n extras: {\n getDebugName: getDebugName\n },\n $mobx: $mobx\n });\n}\n\n\n//# sourceMappingURL=mobx.esm.js.map\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../sgmf-scripts/node_modules/webpack/buildin/global.js */ \"./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/mobx/dist/mobx.esm.js?"); + +/***/ }), + +/***/ "./node_modules/sgmf-scripts/node_modules/webpack/buildin/global.js": +/*!***********************************!*\ + !*** (webpack)/buildin/global.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +eval("var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n\n\n//# sourceURL=webpack:///(webpack)/buildin/global.js?"); + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/cartridges/int_adyen_SFRA/cartridge/static/default/js/checkout.js b/cartridges/int_adyen_SFRA/cartridge/static/default/js/checkout.js new file mode 100644 index 000000000..f35686395 --- /dev/null +++ b/cartridges/int_adyen_SFRA/cartridge/static/default/js/checkout.js @@ -0,0 +1,448 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./cartridges/int_adyen_SFRA/cartridge/client/default/js/checkout.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "../storefront-reference-architecture/cartridges/app_storefront_base/cartridge/client/default/js/checkout/address.js": +/*!***************************************************************************************************************************!*\ + !*** ../storefront-reference-architecture/cartridges/app_storefront_base/cartridge/client/default/js/checkout/address.js ***! + \***************************************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +eval("\n\n/**\n * Populate the Billing Address Summary View\n * @param {string} parentSelector - the top level DOM selector for a unique address summary\n * @param {Object} address - the address data\n */\nfunction populateAddressSummary(parentSelector, address) {\n $.each(address, function (attr) {\n var val = address[attr];\n $('.' + attr, parentSelector).text(val || '');\n });\n}\n\n/**\n * returns a formed ');\n }\n var safeShipping = shipping || {};\n var shippingAddress = safeShipping.shippingAddress || {};\n\n if (isBilling && isNew && !order.billing.matchingAddressId) {\n shippingAddress = order.billing.billingAddress.address || {};\n isNew = false;\n isSelected = true;\n safeShipping.UUID = 'manual-entry';\n }\n\n var uuid = safeShipping.UUID ? safeShipping.UUID : 'new';\n var optionEl = $('