diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..5fbd95c2e1 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# Howto with your editor: http://editorconfig.org/#download +# Sublime: https://github.com/sindresorhus/editorconfig-sublime + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[**] +charset = utf-8 +end_of_line = lf +indent_size = 2 +indent_style = space +insert_final_newline = true +max_line_length = 80 +trim_trailing_whitespace = true \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js index 52c9759483..a2a2d2502d 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -2,32 +2,34 @@ // eslint-disable-next-line import/no-commonjs module.exports = { - 'extends': '@krakenjs/eslint-config-grumbler/eslintrc-browser', + extends: ["@krakenjs/eslint-config-grumbler/eslintrc-browser", "prettier"], - 'rules': { - 'react/display-name': 'off', - 'prefer-regex-literals': 'off', - 'require-atomic-updates': 'off', - 'max-lines': 'off', - 'react/require-default-props': 'off', - 'react/prop-types': 'off' - }, + rules: { + "react/display-name": "off", + "prefer-regex-literals": "off", + "require-atomic-updates": "off", + "max-lines": "off", + "react/require-default-props": "off", + "react/prop-types": "off", + }, - 'globals': { - '__SMART_BUTTONS__': true, - 'paypal': true, - '$Shape': true, - 'afterAll': true, - 'jest': true + globals: { + __SMART_BUTTONS__: true, + paypal: true, + $Shape: true, + afterAll: true, + jest: true, + }, + overrides: [ + { + files: ["**/*.test.js"], + env: { + jest: true, + }, + globals: { + JestMockFn: false, + }, }, - 'overrides': [{ - 'files': ['**/*.test.js'], - 'env': { - 'jest': true - }, - 'globals': { - 'JestMockFn': false - } - }], - 'ignorePatterns': ['node-qrcode.js'] + ], + ignorePatterns: ["node-qrcode.js"], }; diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index bf754395f6..49f3bcb718 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -13,7 +13,9 @@ + ### Groups who should review (if applicable) + -❤️ Thank you! +❤️ Thank you! diff --git a/.github/renovate.json b/.github/renovate.json index e0e2f74c66..c433a8a59f 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -1,8 +1,5 @@ { - "extends": [ - "config:base", - ":preserveSemverRanges" - ], + "extends": ["config:base", ":preserveSemverRanges"], "prCreation": "immediate", "prHourlyLimit": 0, "rangeStrategy": "status-success", @@ -10,9 +7,7 @@ "semanticCommits": true, "timezone": "America/Los_Angeles", "rebaseStalePrs": true, - "labels": [ - ":christmas_tree: dependencies" - ], + "labels": [":christmas_tree: dependencies"], "packageRules": [ { "packagePatterns": "^babel", diff --git a/.github/workflows/dry-run.yml b/.github/workflows/dry-run.yml index 23389ccda6..288f12612e 100644 --- a/.github/workflows/dry-run.yml +++ b/.github/workflows/dry-run.yml @@ -15,8 +15,8 @@ jobs: # sets up the .npmrc file to publish to npm uses: actions/setup-node@v3 with: - node-version: '16' - registry-url: 'https://registry.npmjs.org' + node-version: "16" + registry-url: "https://registry.npmjs.org" - name: 📥 Download deps uses: bahmutov/npm-install@v1 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index ff9a964618..e436f4f341 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -40,3 +40,5 @@ jobs: - name: ⬆️ Upload coverage report uses: codecov/codecov-action@v3 + with: + files: coverage/lcov.info, coverage-vitest/clover.xml diff --git a/.gitignore b/.gitignore index 0abc71cabb..ff83e09129 100644 --- a/.gitignore +++ b/.gitignore @@ -1,30 +1,31 @@ -node_modules +*.log +*.orig +.DS_Store .build .configcache .idea +.nyc_output .rebooted .settings -.nyc_output -logs -log -*.orig -*.log -.DS_Store -coverage -cdbs -protected -tmp -ext -temp -tools/tmp +.vscode bower_modules +cdbs config/production.json -test/functional/datadriven/report +coverage +coverage-vitest +ext +flow-typed +log +logs +node_modules +package-lock.json +protected server.crt server.csr server.key server.key.org slipper-cache.json -flow-typed -package-lock.json -.vscode +temp +test/functional/datadriven/report +tmp +tools/tmp diff --git a/.nvmrc b/.nvmrc index b6a7d89c68..6e8e83a5fc 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -16 +16.18 diff --git a/.prettierignore b/.prettierignore index 9d1be21c74..f4409fef0d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,10 +1,36 @@ -.husky/ +*.log +*.orig +.DS_Store +.build +.configcache +.idea .npm .nvm -.vscode/ +.nyc_output +.rebooted +.settings +.vscode +bower_modules +cdbs cdn/ config/ -coverage/ +config/production.json +coverage +coverage-vitest dist/ -flow-typed/ -node_modules/ +ext +flow-typed +log +logs +node_modules +package-lock.json +protected +server.crt +server.csr +server.key +server.key.org +slipper-cache.json +temp +test/functional/datadriven/report +tmp +tools/tmp \ No newline at end of file diff --git a/babel.config.js b/babel.config.js index e5a2b3cba7..66bc35cb70 100644 --- a/babel.config.js +++ b/babel.config.js @@ -2,5 +2,5 @@ /* eslint import/no-commonjs: off */ module.exports = { - extends: "@krakenjs/babel-config-grumbler/babelrc-node", + extends: "@krakenjs/babel-config-grumbler/babelrc-node", }; diff --git a/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.150-alpha-50c2984d.0.tgz b/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.150-alpha-50c2984d.0.tgz deleted file mode 100644 index 0aac4d444e..0000000000 Binary files a/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.150-alpha-50c2984d.0.tgz and /dev/null differ diff --git a/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.151.tgz b/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.151.tgz deleted file mode 100644 index 4724228326..0000000000 Binary files a/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.151.tgz and /dev/null differ diff --git a/cdn/5.0.151/paypal/smart-payment-buttons/info.json b/cdn/5.0.164/paypal/smart-payment-buttons/info.json similarity index 87% rename from cdn/5.0.151/paypal/smart-payment-buttons/info.json rename to cdn/5.0.164/paypal/smart-payment-buttons/info.json index 68b754914e..282c302bdf 100644 --- a/cdn/5.0.151/paypal/smart-payment-buttons/info.json +++ b/cdn/5.0.164/paypal/smart-payment-buttons/info.json @@ -1,14 +1,14 @@ { "name": "@paypal/smart-payment-buttons", "dist-tags": { - "latest": "5.0.151", + "latest": "5.0.164", "noop": "2.0.290", - "active-test": "5.0.151", - "active-local": "5.0.151", - "active-stage": "5.0.151", + "active-test": "5.0.164", + "active-local": "5.0.164", + "active-stage": "5.0.164", "active-sandbox": "5.0.108", "active-production": "5.0.108", - "alpha": "5.0.150-alpha-50c2984d.0", + "alpha": "5.0.164-alpha-66eac557.0", "beta": "5.0.139-beta.0" }, "versions": { @@ -32,7 +32,7 @@ "zalgo-promise": "^1.0.28" }, "dist": { - "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.151/paypal/smart-payment-buttons/tarballs/2.0.290.tgz" + "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.164/paypal/smart-payment-buttons/tarballs/2.0.290.tgz" }, "repository": { "url": "https://github.paypal.com/Checkout/smart-buttons" @@ -65,7 +65,7 @@ "typed-graphqlify": "^2.2.3" }, "dist": { - "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.108.tgz" + "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.108.tgz" }, "repository": { "url": "git+https://github.com/paypal/paypal-smart-payment-buttons.git" @@ -97,17 +97,17 @@ "typed-graphqlify": "^2.2.3" }, "dist": { - "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.139-beta.0.tgz" + "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.139-beta.0.tgz" }, "repository": { "url": "git+https://github.com/paypal/paypal-smart-payment-buttons.git" }, "gitHead": "d67be2b7a38697bdcdd44c7d3637464cc668c51e" }, - "5.0.150-alpha-50c2984d.0": { + "5.0.164-alpha-66eac557.0": { "dependencies": { - "@krakenjs/beaver-logger": "^5.0.1", - "@krakenjs/belter": "^2.1.0", + "@krakenjs/beaver-logger": "^5.5.0", + "@krakenjs/belter": "^2.3.0", "@krakenjs/cross-domain-utils": "^3.0.0", "@krakenjs/grabthar": "^6.2.0", "@krakenjs/jsx-pragmatic": "^3.0.0", @@ -116,7 +116,6 @@ "@paypal/checkout-components": "^5.0.256", "@paypal/common-components": "^1.0.35", "@paypal/installments": "^1.0.0", - "@paypal/sdk-client": "^4.0.175", "@paypal/sdk-constants": "^1.0.128", "@paypal/sdk-logos": "^2.1.0", "@paypal/sdk-release": "^5.0.138", @@ -129,17 +128,17 @@ "typed-graphqlify": "^2.2.3" }, "dist": { - "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.150-alpha-50c2984d.0.tgz" + "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.164-alpha-66eac557.0.tgz" }, "repository": { "url": "git+https://github.com/paypal/paypal-smart-payment-buttons.git" }, - "gitHead": "372d501099ed2245438889bf4047bff7a2ee3cfb" + "gitHead": "2b50f74f3f9ea832f8e9be49060e544d19c67c1c" }, - "5.0.151": { + "5.0.164": { "dependencies": { "@krakenjs/beaver-logger": "^5.5.0", - "@krakenjs/belter": "^2.1.0", + "@krakenjs/belter": "^2.3.0", "@krakenjs/cross-domain-utils": "^3.0.0", "@krakenjs/grabthar": "^6.2.0", "@krakenjs/jsx-pragmatic": "^3.0.0", @@ -148,7 +147,6 @@ "@paypal/checkout-components": "^5.0.256", "@paypal/common-components": "^1.0.35", "@paypal/installments": "^1.0.0", - "@paypal/sdk-client": "^4.0.175", "@paypal/sdk-constants": "^1.0.128", "@paypal/sdk-logos": "^2.1.0", "@paypal/sdk-release": "^5.0.138", @@ -161,12 +159,12 @@ "typed-graphqlify": "^2.2.3" }, "dist": { - "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.151.tgz" + "tarball": "https://www.paypalobjects.com/smart-payment-buttons/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.164.tgz" }, "repository": { "url": "git+https://github.com/paypal/paypal-smart-payment-buttons.git" }, - "gitHead": "ae08c9d3f7e1a2f447237e313c7eb8c159a50d30" + "gitHead": "0c84511018fcdb327c2a41e655a76fc01971ea48" } } } \ No newline at end of file diff --git a/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/2.0.290.tgz b/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/2.0.290.tgz similarity index 100% rename from cdn/5.0.151/paypal/smart-payment-buttons/tarballs/2.0.290.tgz rename to cdn/5.0.164/paypal/smart-payment-buttons/tarballs/2.0.290.tgz diff --git a/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.108.tgz b/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.108.tgz similarity index 100% rename from cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.108.tgz rename to cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.108.tgz diff --git a/cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.139-beta.0.tgz b/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.139-beta.0.tgz similarity index 100% rename from cdn/5.0.151/paypal/smart-payment-buttons/tarballs/5.0.139-beta.0.tgz rename to cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.139-beta.0.tgz diff --git a/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.164-alpha-66eac557.0.tgz b/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.164-alpha-66eac557.0.tgz new file mode 100644 index 0000000000..687d6fb1ac Binary files /dev/null and b/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.164-alpha-66eac557.0.tgz differ diff --git a/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.164.tgz b/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.164.tgz new file mode 100644 index 0000000000..0234226b75 Binary files /dev/null and b/cdn/5.0.164/paypal/smart-payment-buttons/tarballs/5.0.164.tgz differ diff --git a/dist/smart-card.js b/dist/smart-card.js index 2b0e3a6542..d28e5fc4e3 100644 --- a/dist/smart-card.js +++ b/dist/smart-card.js @@ -55,7 +55,7 @@ window.smartCard = function(modules) { return {}.hasOwnProperty.call(object, property); }; __webpack_require__.p = ""; - return __webpack_require__(__webpack_require__.s = 82); + return __webpack_require__(__webpack_require__.s = 83); }([ function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.d(__webpack_exports__, "b", (function() { @@ -367,7 +367,8 @@ window.smartCard = function(modules) { BUTTON_SESSION_ID: "button_session_id", WALLET_SESSION_ID: "wallet_session_id", ORDER_ID: "EC-Token", - PAYMENT_ID: "Pay-ID" + PAYMENT_ID: "Pay-ID", + VAULT_SETUP_TOKEN: "vault_setup_token" }; var FPTI_STATE = { BUTTON: "smart_button", @@ -390,6 +391,7 @@ window.smartCard = function(modules) { CREATE_ORDER: "process_create_order", CONFIRM_ORDER: "process_confirm_order", RECEIVE_ORDER: "process_receive_order", + RECEIVE_VAULT_SETUP_TOKEN: "process_receive_vault_setup_token", CREATE_PAYMENT: "process_create_payment", CAPTURE_AUTHORIZATION: "process_capture_authorization", CHECKOUT_SHIPPING_CHANGE: "process_checkout_shipping_change", @@ -544,8 +546,8 @@ window.smartCard = function(modules) { __webpack_require__.d(__webpack_exports__, "d", (function() { return getPostRobot; })); - var util = __webpack_require__(16); - var logger = __webpack_require__(13); + var util = __webpack_require__(17); + var logger = __webpack_require__(9); __webpack_require__(1); __webpack_require__(10); var belter_src = __webpack_require__(3); @@ -1205,7 +1207,7 @@ window.smartCard = function(modules) { return uid; })); function getStorage(_ref) { - var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime; + var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime, stickySessionId = _ref.stickySessionId; return inlineMemoize(getStorage, (function() { var STORAGE_KEY = "__" + name + "_storage__"; var newStateID = uniqueID(); @@ -1240,7 +1242,7 @@ window.smartCard = function(modules) { var now = Date.now(); session && now - session.created > lifetime && (session = null); session || (session = { - guid: uniqueID(), + guid: stickySessionId || uniqueID(), created: now }); storage.__session__ = session; @@ -1760,7 +1762,7 @@ window.smartCard = function(modules) { var _lib__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(2); function callRestAPI(_ref) { var _extends2; - var accessToken = _ref.accessToken, method = _ref.method, url = _ref.url, data = _ref.data, headers = _ref.headers, eventName = _ref.eventName; + var accessToken = _ref.accessToken, method = _ref.method, url = _ref.url, data = _ref.data, headers = _ref.headers, eventName = _ref.eventName, _ref$metricDimensions = _ref.metricDimensions, metricDimensions = void 0 === _ref$metricDimensions ? {} : _ref$metricDimensions; if (!accessToken) throw new Error("No access token passed to " + url); var requestHeaders = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.a)(((_extends2 = {})[_constants__WEBPACK_IMPORTED_MODULE_5__.i.AUTHORIZATION] = "Bearer " + accessToken, _extends2[_constants__WEBPACK_IMPORTED_MODULE_5__.i.CONTENT_TYPE] = "application/json", @@ -1786,14 +1788,22 @@ window.smartCard = function(modules) { _getLogger$track[_constants__WEBPACK_IMPORTED_MODULE_5__.e.INFO_MSG] = "URL: " + url, _getLogger$track)); } - eventName && Object(_lib__WEBPACK_IMPORTED_MODULE_6__.c)().warn("rest_api_" + eventName + "_status_" + status + "_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.c)().warn("rest_api_" + eventName + "_status_" + status + "_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.i)({ + name: "pp.app.paypal_sdk.buttons.rest_api_" + eventName + ".error.count", + dimensions: metricDimensions + }); throw error; } + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.i)({ + name: "pp.app.paypal_sdk.buttons.rest_api_" + eventName + ".success.count", + dimensions: metricDimensions + }); return body; })); } function callSmartAPI(_ref3) { - var accessToken = _ref3.accessToken, url = _ref3.url, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? "get" : _ref3$method, _ref3$headers = _ref3.headers, reqHeaders = void 0 === _ref3$headers ? {} : _ref3$headers, json = _ref3.json, _ref3$authenticated = _ref3.authenticated, authenticated = void 0 === _ref3$authenticated || _ref3$authenticated, eventName = _ref3.eventName; + var accessToken = _ref3.accessToken, url = _ref3.url, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? "get" : _ref3$method, _ref3$headers = _ref3.headers, reqHeaders = void 0 === _ref3$headers ? {} : _ref3$headers, json = _ref3.json, _ref3$authenticated = _ref3.authenticated, authenticated = void 0 === _ref3$authenticated || _ref3$authenticated, eventName = _ref3.eventName, _ref3$metricDimension = _ref3.metricDimensions, metricDimensions = void 0 === _ref3$metricDimension ? {} : _ref3$metricDimension; reqHeaders[_constants__WEBPACK_IMPORTED_MODULE_5__.i.REQUESTED_BY] = _constants__WEBPACK_IMPORTED_MODULE_5__.p; if (authenticated && !accessToken) throw new Error("Buyer access token not present - can not call smart api: " + url); accessToken && (reqHeaders[_constants__WEBPACK_IMPORTED_MODULE_5__.i.ACCESS_TOKEN] = accessToken); @@ -1825,12 +1835,26 @@ window.smartCard = function(modules) { } if (status > 400) { Object(_lib__WEBPACK_IMPORTED_MODULE_6__.c)().warn("smart_api_" + eventName + "_status_" + status + "_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.i)({ + name: "pp.app.paypal_sdk.buttons.smart_api_" + eventName + ".error.count", + dimensions: Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.a)({ + status: status + }, metricDimensions) + }); throw new Error("Api: " + url + " returned status code: " + status + " (Corr ID: " + headers[_constants__WEBPACK_IMPORTED_MODULE_5__.i.PAYPAL_DEBUG_ID] + ")\n\n" + JSON.stringify(body)); } if ("success" !== body.ack) { Object(_lib__WEBPACK_IMPORTED_MODULE_6__.c)().warn("smart_api_" + eventName + "_ack_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.i)({ + name: "pp.app.paypal_sdk.buttons.smart_api_" + eventName + ".error.count", + dimensions: metricDimensions + }); throw new Error("Api: " + url + " returned ack: " + body.ack + " (Corr ID: " + headers[_constants__WEBPACK_IMPORTED_MODULE_5__.i.PAYPAL_DEBUG_ID] + ")\n\n" + JSON.stringify(body)); } + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.i)({ + name: "pp.app.paypal_sdk.buttons.smart_api_" + eventName + ".success.count", + dimensions: metricDimensions + }); return { data: body.data, headers: headers @@ -1858,12 +1882,26 @@ window.smartCard = function(modules) { err: message }); if (returnErrorObject) throw errors[0]; + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.i)({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".error.count", + dimensions: {} + }); throw new Error(message); } if (200 !== status) { Object(_lib__WEBPACK_IMPORTED_MODULE_6__.c)().warn("graphql_" + name + "_status_" + status + "_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.i)({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".error.count", + dimensions: { + status: status + } + }); throw new Error(_config__WEBPACK_IMPORTED_MODULE_4__.e + " returned status " + status + "\n\n" + JSON.stringify(body)); } + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.i)({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".success.count", + dimensions: {} + }); return body.data; })); } @@ -1941,8 +1979,8 @@ window.smartCard = function(modules) { __webpack_require__.d(__webpack_exports__, "f", (function() { return createAccessToken; })); - __webpack_require__.d(__webpack_exports__, "w", (function() { - return upgradeFacilitatorAccessToken; + __webpack_require__.d(__webpack_exports__, "x", (function() { + return upgradeFacilitatorAccessTokenWithIgnoreCache; })); __webpack_require__.d(__webpack_exports__, "g", (function() { return createOrderID; @@ -1962,10 +2000,10 @@ window.smartCard = function(modules) { __webpack_require__.d(__webpack_exports__, "b", (function() { return authorizeOrder; })); - __webpack_require__.d(__webpack_exports__, "r", (function() { + __webpack_require__.d(__webpack_exports__, "s", (function() { return patchOrder; })); - __webpack_require__.d(__webpack_exports__, "t", (function() { + __webpack_require__.d(__webpack_exports__, "u", (function() { return patchShipping; })); __webpack_require__.d(__webpack_exports__, "e", (function() { @@ -1974,7 +2012,7 @@ window.smartCard = function(modules) { __webpack_require__.d(__webpack_exports__, "c", (function() { return billingTokenToOrderID; })); - __webpack_require__.d(__webpack_exports__, "v", (function() { + __webpack_require__.d(__webpack_exports__, "w", (function() { return subscriptionIdToCartId; })); __webpack_require__.d(__webpack_exports__, "o", (function() { @@ -1992,13 +2030,13 @@ window.smartCard = function(modules) { __webpack_require__.d(__webpack_exports__, "j", (function() { return executePayment; })); - __webpack_require__.d(__webpack_exports__, "s", (function() { + __webpack_require__.d(__webpack_exports__, "t", (function() { return patchPayment; })); __webpack_require__.d(__webpack_exports__, "i", (function() { return createSubscription; })); - __webpack_require__.d(__webpack_exports__, "u", (function() { + __webpack_require__.d(__webpack_exports__, "v", (function() { return reviseSubscription; })); __webpack_require__.d(__webpack_exports__, "a", (function() { @@ -2007,6 +2045,9 @@ window.smartCard = function(modules) { __webpack_require__.d(__webpack_exports__, "n", (function() { return getSubscription; })); + __webpack_require__.d(__webpack_exports__, "r", (function() { + return loadFraudnet; + })); var src = __webpack_require__(4); var belter_src = __webpack_require__(3); var sdk_constants_src = __webpack_require__(0); @@ -2046,38 +2087,53 @@ window.smartCard = function(modules) { })); }), [ clientID, targetSubject ]); } - var lsatUpgradeCalled = !1; - var lsatUpgradeError; + var auth_lsatUpgradeCalled = !1; + var auth_lsatUpgradeError; + var lsatUpgradeWithIgnoreCache = !1; + var getLsatUpgradeWithIgnoreCache = function() { + return lsatUpgradeWithIgnoreCache; + }; var getLsatUpgradeCalled = function() { - return lsatUpgradeCalled; + return auth_lsatUpgradeCalled; }; var getLsatUpgradeError = function() { - return lsatUpgradeError; + return auth_lsatUpgradeError; }; - function upgradeFacilitatorAccessToken(facilitatorAccessToken, _ref3) { - var _headers; - var buyerAccessToken = _ref3.buyerAccessToken, orderID = _ref3.orderID; - !function() { - lsatUpgradeCalled = !1; - lsatUpgradeError = null; - }(); - lsatUpgradeCalled = !0; - return Object(api.a)({ - name: "UpgradeFacilitatorAccessToken", - headers: (_headers = {}, _headers[constants.i.ACCESS_TOKEN] = buyerAccessToken, - _headers[constants.i.CLIENT_CONTEXT] = orderID, _headers), - query: "\n mutation UpgradeFacilitatorAccessToken(\n $orderID: String!\n $buyerAccessToken: String!\n $facilitatorAccessToken: String!\n ) {\n upgradeLowScopeAccessToken(\n token: $orderID\n buyerAccessToken: $buyerAccessToken\n merchantLSAT: $facilitatorAccessToken\n )\n }\n ", - variables: { - facilitatorAccessToken: facilitatorAccessToken, - buyerAccessToken: buyerAccessToken, - orderID: orderID - } - }).then(belter_src.p).catch((function(err) { - !function(err) { - lsatUpgradeError = err; - }(err); - throw err; - })); + function upgradeFacilitatorAccessTokenWithIgnoreCache(facilitatorAccessToken, buyerAccessToken, orderID) { + return Object(belter_src.i)(upgradeFacilitatorAccessTokenWithIgnoreCache, (function() { + var _headers2; + !function() { + auth_lsatUpgradeCalled = !1; + auth_lsatUpgradeError = null; + lsatUpgradeWithIgnoreCache = !1; + }(); + auth_lsatUpgradeCalled = !0; + lsatUpgradeWithIgnoreCache = !0; + return Object(api.a)({ + name: "CreateUpgradedLowScopeAccessToken", + headers: (_headers2 = {}, _headers2[constants.i.ACCESS_TOKEN] = buyerAccessToken, + _headers2[constants.i.CLIENT_CONTEXT] = orderID, _headers2), + query: "\n mutation CreateUpgradedLowScopeAccessToken(\n $orderID: String!\n $buyerAccessToken: String!\n $facilitatorAccessToken: String!\n ) {\n createUpgradedLowScopeAccessToken(\n token: $orderID\n buyerAccessToken: $buyerAccessToken\n merchantLSAT: $facilitatorAccessToken\n )\n }\n ", + variables: { + facilitatorAccessToken: facilitatorAccessToken, + buyerAccessToken: buyerAccessToken, + orderID: orderID + } + }).then((function(res) { + Object(lib.c)().info("create_upgraded_low_scope_access_token_success", { + orderID: orderID + }); + return null == res ? void 0 : res.createUpgradedLowScopeAccessToken; + })).catch((function(err) { + Object(lib.c)().warn("create_upgraded_low_scope_access_token_error", { + orderID: orderID + }); + !function(err) { + auth_lsatUpgradeError = err; + }(err); + return facilitatorAccessToken; + })); + }), [ facilitatorAccessToken, buyerAccessToken, orderID ]); } var esm_extends = __webpack_require__(5); function createOrderID(order, _ref) { @@ -2108,13 +2164,43 @@ window.smartCard = function(modules) { return detail.issue === constants.k.INVALID_RESOURCE_ID; }))); } + function lsatUpgradeType() { + return getLsatUpgradeWithIgnoreCache() ? "with_ignore_cache_lsat_upgrade" : "without_ignore_cache_lsat_upgrade"; + } + function lsatUpgradeMetricValue() { + var lsatUpgradeCalled = Boolean(getLsatUpgradeCalled()); + var lsatUpgradeIgnoreCache = Boolean(getLsatUpgradeWithIgnoreCache()); + var lsatUpgradeError = Boolean(getLsatUpgradeError()); + var cacheType = lsatUpgradeIgnoreCache ? "with_ignore_cache" : "without_ignore_cache"; + return lsatUpgradeCalled ? lsatUpgradeError ? cacheType + "_error" : cacheType + "_success" : cacheType + "_not_called"; + } + function logPayeeInfoForClientSideHelpers(orderID, method) { + getSupplementalOrderInfo(orderID).then((function(order) { + var merchantIds = (order.checkoutSession.payees || []).map((function(p) { + return p.merchantId; + })); + Object(lib.c)().info("using_client_side_helper_" + method, { + payee: merchantIds.join(), + orderID: orderID + }); + })).catch((function(err) { + Object(lib.c)().warn("err_getting_payee_client_side_helper_" + method, { + orderID: orderID, + err: Object(belter_src.v)(err) + }); + })); + } function getOrder(orderID, _ref2) { var _headers4; - var facilitatorAccessToken = _ref2.facilitatorAccessToken, buyerAccessToken = _ref2.buyerAccessToken, partnerAttributionID = _ref2.partnerAttributionID, _ref2$forceRestAPI = _ref2.forceRestAPI, forceRestAPI = void 0 !== _ref2$forceRestAPI && _ref2$forceRestAPI; - Object(lib.c)().info("get_order_lsat_upgrade_" + (getLsatUpgradeCalled() ? "called" : "not_called")); - Object(lib.c)().info("get_order_lsat_upgrade_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + var facilitatorAccessToken = _ref2.facilitatorAccessToken, buyerAccessToken = _ref2.buyerAccessToken, partnerAttributionID = _ref2.partnerAttributionID, _ref2$forceRestAPI = _ref2.forceRestAPI, forceRestAPI = void 0 !== _ref2$forceRestAPI && _ref2$forceRestAPI, experiments = _ref2.experiments; + Object(lib.c)().info("get_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeCalled() ? "called" : "not_called"), { + orderID: orderID + }); + Object(lib.c)().info("get_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + orderID: orderID, err: Object(belter_src.v)(getLsatUpgradeError()) }); + logPayeeInfoForClientSideHelpers(orderID, "get"); if (forceRestAPI && !getLsatUpgradeError()) { var _headers2; return Object(api.b)({ @@ -2122,28 +2208,36 @@ window.smartCard = function(modules) { url: src_config.g + "/" + orderID, eventName: "v2_checkout_orders_get", headers: (_headers2 = {}, _headers2[constants.i.PARTNER_ATTRIBUTION_ID] = partnerAttributionID || "", - _headers2[constants.i.PREFER] = constants.m.REPRESENTATION, _headers2) + _headers2[constants.i.PREFER] = constants.m.REPRESENTATION, _headers2), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue() + } }).catch((function(err) { var _headers3; var restCorrID = Object(api.d)(err); - Object(lib.c)().warn("get_order_call_rest_api_error", { + Object(lib.c)().warn("get_order_" + lsatUpgradeType() + "_call_rest_api_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.v)(err) }); - isInvalidResourceIDError(err) && Object(lib.c)().warn("get_order_invalid_resource_id_error", { + isInvalidResourceIDError(err) && Object(lib.c)().warn("get_order_" + lsatUpgradeType() + "_invalid_resource_id_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.v)(err) }); + if (experiments.disableSmartAPI) throw err; return Object(api.c)({ accessToken: buyerAccessToken, url: src_config.i.ORDER + "/" + orderID, eventName: "order_get", - headers: (_headers3 = {}, _headers3[constants.i.CLIENT_CONTEXT] = orderID, _headers3) + headers: (_headers3 = {}, _headers3[constants.i.CLIENT_CONTEXT] = orderID, _headers3), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback" + } }).then((function(res) { var smartCorrID = Object(api.e)(res); - Object(lib.c)().info("get_order_smart_fallback_success", { + Object(lib.c)().info("get_order_" + lsatUpgradeType() + "_smart_fallback_success", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID @@ -2151,7 +2245,7 @@ window.smartCard = function(modules) { return res.data; })).catch((function(smartErr) { var smartCorrID = Object(api.d)(err); - Object(lib.c)().error("get_order_smart_fallback_error", { + Object(lib.c)().error("get_order_" + lsatUpgradeType() + "_smart_fallback_error", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID, @@ -2159,15 +2253,23 @@ window.smartCard = function(modules) { }); throw smartErr; })); + })).finally((function() { + Object(lib.c)().flush(); })); } return Object(api.c)({ accessToken: buyerAccessToken, url: src_config.i.ORDER + "/" + orderID, eventName: "order_get", - headers: (_headers4 = {}, _headers4[constants.i.CLIENT_CONTEXT] = orderID, _headers4) + headers: (_headers4 = {}, _headers4[constants.i.CLIENT_CONTEXT] = orderID, _headers4), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default" + } }).then((function(_ref3) { return _ref3.data; + })).finally((function() { + Object(lib.c)().flush(); })); } function isProcessorDeclineError(err) { @@ -2185,11 +2287,15 @@ window.smartCard = function(modules) { } function captureOrder(orderID, _ref4) { var _headers7; - var facilitatorAccessToken = _ref4.facilitatorAccessToken, buyerAccessToken = _ref4.buyerAccessToken, partnerAttributionID = _ref4.partnerAttributionID, _ref4$forceRestAPI = _ref4.forceRestAPI, forceRestAPI = void 0 !== _ref4$forceRestAPI && _ref4$forceRestAPI; - Object(lib.c)().info("capture_order_lsat_upgrade_" + (getLsatUpgradeCalled() ? "called" : "not_called")); - Object(lib.c)().info("capture_order_lsat_upgrade_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + var facilitatorAccessToken = _ref4.facilitatorAccessToken, buyerAccessToken = _ref4.buyerAccessToken, partnerAttributionID = _ref4.partnerAttributionID, _ref4$forceRestAPI = _ref4.forceRestAPI, forceRestAPI = void 0 !== _ref4$forceRestAPI && _ref4$forceRestAPI, experiments = _ref4.experiments; + Object(lib.c)().info("capture_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeCalled() ? "called" : "not_called"), { + orderID: orderID + }); + Object(lib.c)().info("capture_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + orderID: orderID, err: Object(belter_src.v)(getLsatUpgradeError()) }); + logPayeeInfoForClientSideHelpers(orderID, "capture"); if (forceRestAPI && !getLsatUpgradeError()) { var _headers5; return Object(api.b)({ @@ -2199,21 +2305,25 @@ window.smartCard = function(modules) { url: src_config.g + "/" + orderID + "/capture", headers: (_headers5 = {}, _headers5[constants.i.PARTNER_ATTRIBUTION_ID] = partnerAttributionID || "", _headers5[constants.i.PREFER] = constants.m.REPRESENTATION, _headers5[constants.i.PAYPAL_REQUEST_ID] = orderID, - _headers5) + _headers5), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue() + } }).catch((function(err) { var _headers6; var restCorrID = Object(api.d)(err); - Object(lib.c)().warn("capture_order_call_rest_api_error", { + Object(lib.c)().warn("capture_order_" + lsatUpgradeType() + "_call_rest_api_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.v)(err) }); - isInvalidResourceIDError(err) && Object(lib.c)().warn("capture_order_invalid_resource_id_error", { + isInvalidResourceIDError(err) && Object(lib.c)().warn("capture_order_" + lsatUpgradeType() + "_invalid_resource_id_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.v)(err) }); if (isProcessorDeclineError(err) || isUnprocessableEntityError(err)) throw err; + if (experiments.disableSmartAPI) throw err; return Object(api.c)({ accessToken: buyerAccessToken, method: "post", @@ -2224,10 +2334,14 @@ window.smartCard = function(modules) { facilitatorAccessToken: facilitatorAccessToken } }, - headers: (_headers6 = {}, _headers6[constants.i.CLIENT_CONTEXT] = orderID, _headers6) + headers: (_headers6 = {}, _headers6[constants.i.CLIENT_CONTEXT] = orderID, _headers6), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback" + } }).then((function(res) { var smartCorrID = Object(api.e)(res); - Object(lib.c)().info("capture_order_smart_fallback_success", { + Object(lib.c)().info("capture_order_" + lsatUpgradeType() + "_smart_fallback_success", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID @@ -2235,7 +2349,7 @@ window.smartCard = function(modules) { return res.data; })).catch((function(smartErr) { var smartCorrID = Object(api.d)(err); - Object(lib.c)().info("capture_order_smart_fallback_error", { + Object(lib.c)().info("capture_order_" + lsatUpgradeType() + "_smart_fallback_error", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID, @@ -2243,6 +2357,8 @@ window.smartCard = function(modules) { }); throw smartErr; })); + })).finally((function() { + Object(lib.c)().flush(); })); } return Object(api.c)({ @@ -2255,18 +2371,28 @@ window.smartCard = function(modules) { facilitatorAccessToken: facilitatorAccessToken } }, - headers: (_headers7 = {}, _headers7[constants.i.CLIENT_CONTEXT] = orderID, _headers7) + headers: (_headers7 = {}, _headers7[constants.i.CLIENT_CONTEXT] = orderID, _headers7), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default" + } }).then((function(_ref5) { return _ref5.data; + })).finally((function() { + Object(lib.c)().flush(); })); } function authorizeOrder(orderID, _ref6) { var _headers10; - var facilitatorAccessToken = _ref6.facilitatorAccessToken, buyerAccessToken = _ref6.buyerAccessToken, partnerAttributionID = _ref6.partnerAttributionID, _ref6$forceRestAPI = _ref6.forceRestAPI, forceRestAPI = void 0 !== _ref6$forceRestAPI && _ref6$forceRestAPI; - Object(lib.c)().info("authorize_order_lsat_upgrade_" + (getLsatUpgradeCalled() ? "called" : "not_called")); - Object(lib.c)().info("authorize_order_lsat_upgrade_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + var facilitatorAccessToken = _ref6.facilitatorAccessToken, buyerAccessToken = _ref6.buyerAccessToken, partnerAttributionID = _ref6.partnerAttributionID, _ref6$forceRestAPI = _ref6.forceRestAPI, forceRestAPI = void 0 !== _ref6$forceRestAPI && _ref6$forceRestAPI, experiments = _ref6.experiments; + Object(lib.c)().info("authorize_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeCalled() ? "called" : "not_called"), { + orderID: orderID + }); + Object(lib.c)().info("authorize_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + orderID: orderID, err: Object(belter_src.v)(getLsatUpgradeError()) }); + logPayeeInfoForClientSideHelpers(orderID, "authorize"); if (forceRestAPI && !getLsatUpgradeError()) { var _headers8; return Object(api.b)({ @@ -2275,21 +2401,25 @@ window.smartCard = function(modules) { eventName: "v2_checkout_orders_authorize", url: src_config.g + "/" + orderID + "/authorize", headers: (_headers8 = {}, _headers8[constants.i.PARTNER_ATTRIBUTION_ID] = partnerAttributionID || "", - _headers8[constants.i.PREFER] = constants.m.REPRESENTATION, _headers8) + _headers8[constants.i.PREFER] = constants.m.REPRESENTATION, _headers8), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue() + } }).catch((function(err) { var _headers9; var restCorrID = Object(api.d)(err); - Object(lib.c)().warn("authorize_order_call_rest_api_error", { + Object(lib.c)().warn("authorize_order_" + lsatUpgradeType() + "_call_rest_api_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.v)(err) }); - isInvalidResourceIDError(err) && Object(lib.c)().warn("authorize_order_invalid_resource_id_error", { + isInvalidResourceIDError(err) && Object(lib.c)().warn("authorize_order_" + lsatUpgradeType() + "_invalid_resource_id_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.v)(err) }); if (isProcessorDeclineError(err)) throw err; + if (experiments.disableSmartAPI) throw err; return Object(api.c)({ accessToken: buyerAccessToken, method: "post", @@ -2300,10 +2430,14 @@ window.smartCard = function(modules) { facilitatorAccessToken: facilitatorAccessToken } }, - headers: (_headers9 = {}, _headers9[constants.i.CLIENT_CONTEXT] = orderID, _headers9) + headers: (_headers9 = {}, _headers9[constants.i.CLIENT_CONTEXT] = orderID, _headers9), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback" + } }).then((function(res) { var smartCorrID = Object(api.e)(res); - Object(lib.c)().info("authorize_order_smart_fallback_success", { + Object(lib.c)().info("authorize_order_" + lsatUpgradeType() + "_smart_fallback_success", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID @@ -2311,7 +2445,7 @@ window.smartCard = function(modules) { return res.data; })).catch((function(smartErr) { var smartCorrID = Object(api.d)(err); - Object(lib.c)().info("authorize_order_smart_fallback_error", { + Object(lib.c)().info("authorize_order_" + lsatUpgradeType() + "_smart_fallback_error", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID, @@ -2319,6 +2453,8 @@ window.smartCard = function(modules) { }); throw smartErr; })); + })).finally((function() { + Object(lib.c)().flush(); })); } Object(lib.c)().info("lsat_upgrade_false"); @@ -2332,18 +2468,28 @@ window.smartCard = function(modules) { facilitatorAccessToken: facilitatorAccessToken } }, - headers: (_headers10 = {}, _headers10[constants.i.CLIENT_CONTEXT] = orderID, _headers10) + headers: (_headers10 = {}, _headers10[constants.i.CLIENT_CONTEXT] = orderID, _headers10), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default" + } }).then((function(_ref7) { return _ref7.data; + })).finally((function() { + Object(lib.c)().flush(); })); } function patchOrder(orderID, data, _ref8) { var _headers13; - var facilitatorAccessToken = _ref8.facilitatorAccessToken, buyerAccessToken = _ref8.buyerAccessToken, partnerAttributionID = _ref8.partnerAttributionID, _ref8$forceRestAPI = _ref8.forceRestAPI, forceRestAPI = void 0 !== _ref8$forceRestAPI && _ref8$forceRestAPI; - Object(lib.c)().info("patch_order_lsat_upgrade_" + (getLsatUpgradeCalled() ? "called" : "not_called")); - Object(lib.c)().info("patch_order_lsat_upgrade_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + var facilitatorAccessToken = _ref8.facilitatorAccessToken, buyerAccessToken = _ref8.buyerAccessToken, partnerAttributionID = _ref8.partnerAttributionID, _ref8$forceRestAPI = _ref8.forceRestAPI, forceRestAPI = void 0 !== _ref8$forceRestAPI && _ref8$forceRestAPI, experiments = _ref8.experiments; + Object(lib.c)().info("patch_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeCalled() ? "called" : "not_called"), { + orderID: orderID + }); + Object(lib.c)().info("patch_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + orderID: orderID, err: Object(belter_src.v)(getLsatUpgradeError()) }); + logPayeeInfoForClientSideHelpers(orderID, "patch"); if (forceRestAPI && !getLsatUpgradeError()) { var _headers11; return Object(api.b)({ @@ -2353,20 +2499,24 @@ window.smartCard = function(modules) { url: src_config.g + "/" + orderID, data: data, headers: (_headers11 = {}, _headers11[constants.i.PARTNER_ATTRIBUTION_ID] = partnerAttributionID || "", - _headers11[constants.i.PREFER] = constants.m.REPRESENTATION, _headers11) + _headers11[constants.i.PREFER] = constants.m.REPRESENTATION, _headers11), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue() + } }).catch((function(err) { var _headers12; var restCorrID = Object(api.d)(err); - Object(lib.c)().warn("patch_order_call_rest_api_error", { + Object(lib.c)().warn("patch_order_" + lsatUpgradeType() + "_call_rest_api_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.v)(err) }); - isInvalidResourceIDError(err) && Object(lib.c)().warn("patch_order_invalid_resource_id_error", { + isInvalidResourceIDError(err) && Object(lib.c)().warn("patch_order_" + lsatUpgradeType() + "_invalid_resource_id_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.v)(err) }); + if (experiments.disableSmartAPI) throw err; var requestData; requestData = Array.isArray(data) ? { patch: data, @@ -2382,10 +2532,14 @@ window.smartCard = function(modules) { json: { data: requestData }, - headers: (_headers12 = {}, _headers12[constants.i.CLIENT_CONTEXT] = orderID, _headers12) + headers: (_headers12 = {}, _headers12[constants.i.CLIENT_CONTEXT] = orderID, _headers12), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback" + } }).then((function(res) { var smartCorrID = Object(api.e)(res); - Object(lib.c)().info("patch_order_smart_fallback_success", { + Object(lib.c)().info("patch_order_" + lsatUpgradeType() + "_smart_fallback_success", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID @@ -2393,7 +2547,7 @@ window.smartCard = function(modules) { return res.data; })).catch((function(smartErr) { var smartCorrID = Object(api.d)(err); - Object(lib.c)().info("patch_order_smart_fallback_error", { + Object(lib.c)().info("patch_order_" + lsatUpgradeType() + "_smart_fallback_error", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID, @@ -2401,6 +2555,8 @@ window.smartCard = function(modules) { }); throw smartErr; })); + })).finally((function() { + Object(lib.c)().flush(); })); } Object(lib.c)().info("lsat_upgrade_false"); @@ -2419,9 +2575,15 @@ window.smartCard = function(modules) { json: { data: requestData }, - headers: (_headers13 = {}, _headers13[constants.i.CLIENT_CONTEXT] = orderID, _headers13) + headers: (_headers13 = {}, _headers13[constants.i.CLIENT_CONTEXT] = orderID, _headers13), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default" + } }).then((function(_ref9) { return _ref9.data; + })).finally((function() { + Object(lib.c)().flush(); })); } function patchShipping(_ref10) { @@ -2455,8 +2617,8 @@ window.smartCard = function(modules) { method: "post", eventName: "payment_ectoken", url: src_config.i.PAYMENT + "/" + billingToken + "/ectoken" - }).then((function(_ref13) { - return _ref13.data.token; + }).then((function(_ref15) { + return _ref15.data.token; })); } function subscriptionIdToCartId(subscriptionID) { @@ -2465,8 +2627,8 @@ window.smartCard = function(modules) { method: "post", eventName: "billagmt_subscriptions_cartid", url: src_config.i.SUBSCRIPTION + "/" + subscriptionID + "/cartid" - }).then((function(_ref14) { - return _ref14.data.token; + }).then((function(_ref16) { + return _ref16.data.token; })); } var getSupplementalOrderInfo = Object(belter_src.o)((function(orderID) { @@ -2656,7 +2818,7 @@ window.smartCard = function(modules) { return _ref8.data; })); } - var util = __webpack_require__(16); + var util = __webpack_require__(17); Object(belter_src.o)((function(config) { return src.a.try((function() { if (!window.firebase || !window.firebase.auth || !window.firebase.database) return Object(util.d)(src_config.d.APP).then((function() { @@ -2670,12 +2832,12 @@ window.smartCard = function(modules) { })); })); var _FRAUDNET_URL; - var FRAUDNET_URL = ((_FRAUDNET_URL = {})[sdk_constants_src.b.LOCAL] = "https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js", - _FRAUDNET_URL[sdk_constants_src.b.STAGE] = "https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js", + var FRAUDNET_URL = ((_FRAUDNET_URL = {})[sdk_constants_src.b.LOCAL] = "https://www.msmaster.qa.paypal.com/en_US/m/fb-raw.js", + _FRAUDNET_URL[sdk_constants_src.b.STAGE] = "https://stage2mb044.qa.paypal.com/fraudnetjsnodeweb/automate/develop/stage_raw.js", _FRAUDNET_URL[sdk_constants_src.b.SANDBOX] = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL[sdk_constants_src.b.PRODUCTION] = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL[sdk_constants_src.b.TEST] = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL); - Object(belter_src.o)((function(_ref) { + var loadFraudnet = Object(belter_src.o)((function(_ref) { var env = _ref.env, clientMetadataID = _ref.clientMetadataID, cspNonce = _ref.cspNonce, _ref$timeout = _ref.timeout, timeout = void 0 === _ref$timeout ? 1e3 : _ref$timeout, _ref$queryStringParam = _ref.queryStringParams, queryStringParams = void 0 === _ref$queryStringParam ? {} : _ref$queryStringParam; return new src.a((function(resolve) { var config = { @@ -2709,7 +2871,7 @@ window.smartCard = function(modules) { })); })); Object(belter_src.o)((function(_ref) { - var clientID = _ref.clientID, merchantID = _ref.merchantID, currency = _ref.currency, _ref$amount = _ref.amount, amount = void 0 === _ref$amount ? "0.00" : _ref$amount, clientMetadataID = _ref.clientMetadataID, userIDToken = _ref.userIDToken, _ref$vetted = _ref.vetted, vetted = void 0 === _ref$vetted || _ref$vetted, paymentMethodToken = _ref.paymentMethodToken, branded = _ref.branded, _ref$allowBillingPaym = _ref.allowBillingPayments, allowBillingPayments = void 0 === _ref$allowBillingPaym || _ref$allowBillingPaym, _ref$headers = _ref.headers, headers = void 0 === _ref$headers ? {} : _ref$headers; + var clientID = _ref.clientID, merchantID = _ref.merchantID, currency = _ref.currency, _ref$amount = _ref.amount, amount = void 0 === _ref$amount ? "0" : _ref$amount, clientMetadataID = _ref.clientMetadataID, userIDToken = _ref.userIDToken, _ref$vetted = _ref.vetted, vetted = void 0 === _ref$vetted || _ref$vetted, paymentMethodToken = _ref.paymentMethodToken, branded = _ref.branded, _ref$allowBillingPaym = _ref.allowBillingPayments, allowBillingPayments = void 0 === _ref$allowBillingPaym || _ref$allowBillingPaym, _ref$headers = _ref.headers, headers = void 0 === _ref$headers ? {} : _ref$headers; clientMetadataID && (headers[constants.i.CLIENT_METADATA_ID] = String(clientMetadataID)); return Object(api.a)({ name: "GetSmartWallet", @@ -2732,199 +2894,444 @@ window.smartCard = function(modules) { })); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; - __webpack_require__.d(__webpack_exports__, "b", (function() { - return ON_SHIPPING_CHANGE_PATHS; - })); - __webpack_require__.d(__webpack_exports__, "c", (function() { - return SHIPPING_ADDRESS_ERROR_MESSAGES; - })); - __webpack_require__.d(__webpack_exports__, "d", (function() { - return SHIPPING_OPTIONS_ERROR_MESSAGES; - })); - __webpack_require__.d(__webpack_exports__, "a", (function() { - return GENERIC_REJECT_ADDRESS_MESSAGE; - })); - __webpack_require__(17); - __webpack_require__(4); - __webpack_require__(0); - __webpack_require__(8); - __webpack_require__(1); - __webpack_require__(2); - var ON_SHIPPING_CHANGE_PATHS = { - AMOUNT: "/purchase_units/@reference_id=='default'/amount", - OPTIONS: "/purchase_units/@reference_id=='default'/shipping/options" - }; - var SHIPPING_ADDRESS_ERROR_MESSAGES = { - ADDRESS_ERROR: "Your order can't be shipped to this address.", - COUNTRY_ERROR: "Your order can't be shipped to this country.", - STATE_ERROR: "Your order can't be shipped to this state.", - ZIP_ERROR: "Your order can't be shipped to this zip." - }; - var SHIPPING_OPTIONS_ERROR_MESSAGES = { - METHOD_UNAVAILABLE: "The shipping method you chose is unavailable. To continue, choose another way to get your order.", - STORE_UNAVAILABLE: "Part of your order isn't available at this store." - }; - var GENERIC_REJECT_ADDRESS_MESSAGE = "Unable to update address. Please try again."; -}, function(module, __webpack_exports__, __webpack_require__) { - "use strict"; - __webpack_require__.d(__webpack_exports__, "c", (function() { - return getDomain; - })); - __webpack_require__.d(__webpack_exports__, "d", (function() { - return isSameDomain; - })); __webpack_require__.d(__webpack_exports__, "a", (function() { - return assertSameDomain; + return getLogger; })); __webpack_require__.d(__webpack_exports__, "b", (function() { - return getAllFramesInWindow; - })); - __webpack_require__.d(__webpack_exports__, "f", (function() { - return isWindowClosed; - })); - __webpack_require__.d(__webpack_exports__, "g", (function() { - return linkFrameWindow; - })); - __webpack_require__.d(__webpack_exports__, "h", (function() { - return onCloseWindow; + return sendCountMetric; })); - __webpack_require__.d(__webpack_exports__, "e", (function() { - return isWindow; + __webpack_require__.d(__webpack_exports__, "c", (function() { + return setupLogger; })); - var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; - function getActualProtocol(win) { - void 0 === win && (win = window); - return win.location.protocol; - } - function getProtocol(win) { - void 0 === win && (win = window); - if (win.mockDomain) { - var protocol = win.mockDomain.split("//")[0]; - if (protocol) return protocol; - } - return getActualProtocol(win); - } - function isAboutProtocol(win) { - void 0 === win && (win = window); - return "about:" === getProtocol(win); - } - function getParent(win) { - void 0 === win && (win = window); - if (win) try { - if (win.parent && win.parent !== win) return win.parent; - } catch (err) {} - } - function canReadFromWindow(win) { - try { - return !0; - } catch (err) {} - return !1; - } - function getActualDomain(win) { - void 0 === win && (win = window); - var location = win.location; - if (!location) throw new Error("Can not read window location"); - var protocol = getActualProtocol(win); - if (!protocol) throw new Error("Can not read window protocol"); - if ("file:" === protocol) return "file://"; - if ("about:" === protocol) { - var parent = getParent(win); - return parent && canReadFromWindow() ? getActualDomain(parent) : "about://"; - } - var host = location.host; - if (!host) throw new Error("Can not read window host"); - return protocol + "//" + host; - } - function getDomain(win) { - void 0 === win && (win = window); - var domain = getActualDomain(win); - return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; - } - function isSameDomain(win) { - if (!function(win) { - try { - if (win === window) return !0; - } catch (err) {} - try { - var desc = Object.getOwnPropertyDescriptor(win, "location"); - if (desc && !1 === desc.enumerable) return !1; - } catch (err) {} - try { - if (isAboutProtocol(win) && canReadFromWindow()) return !0; - } catch (err) {} - try { - if (function(win) { - void 0 === win && (win = window); - return "mock:" === getProtocol(win); - }(win) && canReadFromWindow()) return !0; - } catch (err) {} - try { - if (getActualDomain(win) === getActualDomain(window)) return !0; - } catch (err) {} - return !1; - }(win)) return !1; - try { - if (win === window) return !0; - if (isAboutProtocol(win) && canReadFromWindow()) return !0; - if (getDomain(window) === getDomain(win)) return !0; - } catch (err) {} - return !1; - } - function assertSameDomain(win) { - if (!isSameDomain(win)) throw new Error("Expected window to be same domain"); - return win; - } - function isAncestorParent(parent, child) { - if (!parent || !child) return !1; - var childParent = getParent(child); - return childParent ? childParent === parent : -1 !== function(win) { - var result = []; - try { - for (;win.parent !== win; ) { - result.push(win.parent); - win = win.parent; - } - } catch (err) {} - return result; - }(child).indexOf(parent); - } - function getAllChildFrames(win) { - var result = []; - for (var _i3 = 0, _getFrames2 = function(win) { - var result = []; - var frames; - try { - frames = win.frames; - } catch (err) { - frames = win; - } - var len; - try { - len = frames.length; - } catch (err) {} - if (0 === len) return result; - if (len) { - for (var i = 0; i < len; i++) { - var frame = void 0; - try { - frame = frames[i]; - } catch (err) { - continue; - } - result.push(frame); - } - return result; - } - for (var _i = 0; _i < 100; _i++) { - var _frame = void 0; - try { - _frame = frames[_i]; - } catch (err) { - return result; - } - if (!_frame) return result; - result.push(_frame); - } + var esm_extends = __webpack_require__(5); + var src = __webpack_require__(4); + var belter_src = __webpack_require__(3); + var AUTO_FLUSH_LEVEL = [ "warn", "error" ]; + var LOG_LEVEL_PRIORITY = [ "error", "warn", "info", "debug" ]; + var extendIfDefined = function(target, source) { + for (var key in source) source.hasOwnProperty(key) && (target[key] = source[key]); + }; + var cross_domain_utils_src = __webpack_require__(10); + var sdk_constants_src = __webpack_require__(0); + var config = __webpack_require__(7); + function getLogger() { + var loggerUrl = window && "object" == typeof window.xprops && window.xprops.disableSetCookie ? config.f + "?disableSetCookie=true" : config.f; + return Object(belter_src.i)(getLogger, (function() { + return function(_ref) { + var url = _ref.url, prefix = _ref.prefix, _ref$logLevel = _ref.logLevel, logLevel = void 0 === _ref$logLevel ? "warn" : _ref$logLevel, _ref$transport = _ref.transport, transport = void 0 === _ref$transport ? function(_ref) { + var url = _ref.url, method = _ref.method, headers = _ref.headers, json = _ref.json, _ref$enableSendBeacon = _ref.enableSendBeacon, enableSendBeacon = void 0 !== _ref$enableSendBeacon && _ref$enableSendBeacon; + return src.a.try((function() { + var httpWindow = window; + var win = Object(cross_domain_utils_src.d)(httpWindow) ? Object(cross_domain_utils_src.a)(httpWindow) : window; + var beaconResult = !1; + (function(_ref) { + var headers = _ref.headers, enableSendBeacon = _ref.enableSendBeacon; + var hasHeaders = headers && Object.keys(headers).length; + return !!(window && window.navigator.sendBeacon && !hasHeaders && enableSendBeacon && window.Blob); + })({ + headers: headers, + enableSendBeacon: enableSendBeacon + }) && (beaconResult = function(_ref2) { + var _ref2$win = _ref2.win, win = void 0 === _ref2$win ? window : _ref2$win, url = _ref2.url, data = _ref2.data, _ref2$useBlob = _ref2.useBlob, useBlob = void 0 === _ref2$useBlob || _ref2$useBlob; + try { + var json = JSON.stringify(data); + if (!win.navigator.sendBeacon) throw new Error("No sendBeacon available"); + if (useBlob) { + var blob = new Blob([ json ], { + type: "application/json" + }); + return win.navigator.sendBeacon(url, blob); + } + return win.navigator.sendBeacon(url, json); + } catch (e) { + return !1; + } + }({ + win: win, + url: url, + data: json, + useBlob: !0 + })); + return beaconResult || Object(belter_src.t)({ + win: win, + url: url, + method: method, + headers: headers, + json: json + }); + })).then(belter_src.p); + } : _ref$transport, _ref$flushInterval = _ref.flushInterval, flushInterval = void 0 === _ref$flushInterval ? 6e4 : _ref$flushInterval, _ref$enableSendBeacon = _ref.enableSendBeacon, enableSendBeacon = void 0 !== _ref$enableSendBeacon && _ref$enableSendBeacon; + var events = []; + var tracking = []; + var metrics = []; + var payloadBuilders = []; + var metaBuilders = []; + var trackingBuilders = []; + var headerBuilders = []; + function print(level, event, payload) { + if (Object(belter_src.k)() && window.console && window.console.log && !(LOG_LEVEL_PRIORITY.indexOf(level) > LOG_LEVEL_PRIORITY.indexOf(logLevel))) { + var args = [ event ]; + args.push(payload); + (payload.error || payload.warning) && args.push("\n\n", payload.error || payload.warning); + try { + window.console[level] && window.console[level].apply ? window.console[level].apply(window.console, args) : window.console.log && window.console.log.apply && window.console.log.apply(window.console, args); + } catch (err) {} + } + } + function immediateFlush() { + return src.a.try((function() { + if (Object(belter_src.k)() && "file:" !== window.location.protocol && (events.length || tracking.length || metrics.length)) { + var meta = {}; + for (var _i2 = 0; _i2 < metaBuilders.length; _i2++) extendIfDefined(meta, (0, metaBuilders[_i2])(meta)); + var headers = {}; + for (var _i4 = 0; _i4 < headerBuilders.length; _i4++) extendIfDefined(headers, (0, + headerBuilders[_i4])(headers)); + var res; + url && (res = transport({ + method: "POST", + url: url, + headers: headers, + json: { + events: events, + meta: meta, + tracking: tracking, + metrics: metrics + }, + enableSendBeacon: enableSendBeacon + }).catch(belter_src.p)); + events = []; + tracking = []; + metrics = []; + return src.a.resolve(res).then(belter_src.p); + } + })); + } + var flush = Object(belter_src.r)(immediateFlush); + function log(level, event, payload) { + void 0 === payload && (payload = {}); + if (!Object(belter_src.k)()) return logger; + prefix && (event = prefix + "_" + event); + var logPayload = Object(esm_extends.a)({}, Object(belter_src.q)(payload), { + timestamp: Date.now().toString() + }); + for (var _i6 = 0; _i6 < payloadBuilders.length; _i6++) extendIfDefined(logPayload, (0, + payloadBuilders[_i6])(logPayload)); + !function(level, event, payload) { + events.push({ + level: level, + event: event, + payload: payload + }); + -1 !== AUTO_FLUSH_LEVEL.indexOf(level) && flush(); + }(level, event, logPayload); + print(level, event, logPayload); + return logger; + } + function addBuilder(builders, builder) { + builders.push(builder); + return logger; + } + Object(belter_src.k)() && Object(belter_src.u)(flush, flushInterval); + if ("object" == typeof window) { + window.addEventListener("beforeunload", (function() { + immediateFlush(); + })); + window.addEventListener("unload", (function() { + immediateFlush(); + })); + window.addEventListener("pagehide", (function() { + immediateFlush(); + })); + } + var logger = { + debug: function(event, payload) { + return log("debug", event, payload); + }, + info: function(event, payload) { + return log("info", event, payload); + }, + warn: function(event, payload) { + return log("warn", event, payload); + }, + error: function(event, payload) { + return log("error", event, payload); + }, + track: function(payload) { + void 0 === payload && (payload = {}); + if (!Object(belter_src.k)()) return logger; + var trackingPayload = Object(belter_src.q)(payload); + for (var _i8 = 0; _i8 < trackingBuilders.length; _i8++) extendIfDefined(trackingPayload, (0, + trackingBuilders[_i8])(trackingPayload)); + print("debug", "track", trackingPayload); + tracking.push(trackingPayload); + return logger; + }, + metric: function(metricPayload) { + if (!Object(belter_src.k)()) return logger; + print("debug", "metric." + metricPayload.metricNamespace, metricPayload.dimensions || {}); + metrics.push(metricPayload); + return logger; + }, + flush: flush, + immediateFlush: immediateFlush, + addPayloadBuilder: function(builder) { + return addBuilder(payloadBuilders, builder); + }, + addMetaBuilder: function(builder) { + return addBuilder(metaBuilders, builder); + }, + addTrackingBuilder: function(builder) { + return addBuilder(trackingBuilders, builder); + }, + addHeaderBuilder: function(builder) { + return addBuilder(headerBuilders, builder); + }, + setTransport: function(newTransport) { + transport = newTransport; + return logger; + }, + configure: function(opts) { + opts.url && (url = opts.url); + opts.prefix && (prefix = opts.prefix); + opts.logLevel && (logLevel = opts.logLevel); + opts.transport && (transport = opts.transport); + opts.flushInterval && (flushInterval = opts.flushInterval); + opts.enableSendBeacon && (enableSendBeacon = opts.enableSendBeacon); + return logger; + }, + __buffer__: { + get events() { + return events; + }, + get tracking() { + return tracking; + }, + get metrics() { + return metrics; + } + } + }; + Object.defineProperty(logger, "__buffer__", { + writable: !1 + }); + return logger; + }({ + url: loggerUrl, + enableSendBeacon: !0 + }); + })); + } + var sendCountMetric = function(_ref) { + var dimensions = _ref.dimensions, _ref$event = _ref.event, event = void 0 === _ref$event ? "unused" : _ref$event, name = _ref.name, _ref$value = _ref.value, value = void 0 === _ref$value ? 1 : _ref$value; + return getLogger().metric({ + dimensions: dimensions, + metricEventName: event, + metricNamespace: name, + metricValue: value, + metricType: "counter" + }); + }; + function setupLogger(_ref3) { + var env = _ref3.env, sessionID = _ref3.sessionID, clientID = _ref3.clientID, sdkCorrelationID = _ref3.sdkCorrelationID, buyerCountry = _ref3.buyerCountry, locale = _ref3.locale, _ref3$sdkVersion = _ref3.sdkVersion, sdkVersion = void 0 === _ref3$sdkVersion ? window.paypal.version : _ref3$sdkVersion; + var logger = getLogger(); + logger.addPayloadBuilder((function() { + return { + referer: window.location.host, + sdkCorrelationID: sdkCorrelationID, + sessionID: sessionID, + clientID: clientID, + env: env + }; + })); + logger.addTrackingBuilder((function() { + var _ref4; + return (_ref4 = {})[sdk_constants_src.e.FEED] = sdk_constants_src.d.PAYMENTS_SDK, + _ref4[sdk_constants_src.e.DATA_SOURCE] = sdk_constants_src.c.PAYMENTS_SDK, _ref4[sdk_constants_src.e.CLIENT_ID] = clientID, + _ref4[sdk_constants_src.e.SESSION_UID] = sessionID, _ref4[sdk_constants_src.e.REFERER] = window.location.host, + _ref4[sdk_constants_src.e.BUYER_COUNTRY] = buyerCountry, _ref4[sdk_constants_src.e.LOCALE] = locale.lang + "_" + locale.country, + _ref4[sdk_constants_src.e.INTEGRATION_IDENTIFIER] = clientID, _ref4[sdk_constants_src.e.SDK_ENVIRONMENT] = Object(belter_src.m)() ? sdk_constants_src.i.IOS : Object(belter_src.j)() ? sdk_constants_src.i.ANDROID : null, + _ref4[sdk_constants_src.e.SDK_NAME] = sdk_constants_src.f.PAYMENTS_SDK, _ref4[sdk_constants_src.e.SDK_VERSION] = sdkVersion, + _ref4[sdk_constants_src.e.USER_AGENT] = window.navigator && window.navigator.userAgent, + _ref4[sdk_constants_src.e.CONTEXT_CORRID] = sdkCorrelationID, _ref4[sdk_constants_src.e.TIMESTAMP] = Date.now().toString(), + _ref4; + })); + src.a.onPossiblyUnhandledException((function(err) { + var _logger$track; + logger.track(((_logger$track = {})[sdk_constants_src.e.ERROR_CODE] = "payments_sdk_error", + _logger$track[sdk_constants_src.e.ERROR_DESC] = Object(belter_src.w)(err), _logger$track)); + logger.error("unhandled_error", { + err: Object(belter_src.v)(err) + }); + sendCountMetric({ + event: "error", + name: "pp.app.paypal_sdk.buttons.unhandled_exception.count", + dimensions: { + errorType: "payments_sdk_error" + } + }); + logger.flush().catch(belter_src.p); + })); + } +}, function(module, __webpack_exports__, __webpack_require__) { + "use strict"; + __webpack_require__.d(__webpack_exports__, "c", (function() { + return getDomain; + })); + __webpack_require__.d(__webpack_exports__, "d", (function() { + return isSameDomain; + })); + __webpack_require__.d(__webpack_exports__, "a", (function() { + return assertSameDomain; + })); + __webpack_require__.d(__webpack_exports__, "b", (function() { + return getAllFramesInWindow; + })); + __webpack_require__.d(__webpack_exports__, "f", (function() { + return isWindowClosed; + })); + __webpack_require__.d(__webpack_exports__, "g", (function() { + return linkFrameWindow; + })); + __webpack_require__.d(__webpack_exports__, "h", (function() { + return onCloseWindow; + })); + __webpack_require__.d(__webpack_exports__, "e", (function() { + return isWindow; + })); + var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; + function getActualProtocol(win) { + void 0 === win && (win = window); + return win.location.protocol; + } + function getProtocol(win) { + void 0 === win && (win = window); + if (win.mockDomain) { + var protocol = win.mockDomain.split("//")[0]; + if (protocol) return protocol; + } + return getActualProtocol(win); + } + function isAboutProtocol(win) { + void 0 === win && (win = window); + return "about:" === getProtocol(win); + } + function getParent(win) { + void 0 === win && (win = window); + if (win) try { + if (win.parent && win.parent !== win) return win.parent; + } catch (err) {} + } + function canReadFromWindow(win) { + try { + return !0; + } catch (err) {} + return !1; + } + function getActualDomain(win) { + void 0 === win && (win = window); + var location = win.location; + if (!location) throw new Error("Can not read window location"); + var protocol = getActualProtocol(win); + if (!protocol) throw new Error("Can not read window protocol"); + if ("file:" === protocol) return "file://"; + if ("about:" === protocol) { + var parent = getParent(win); + return parent && canReadFromWindow() ? getActualDomain(parent) : "about://"; + } + var host = location.host; + if (!host) throw new Error("Can not read window host"); + return protocol + "//" + host; + } + function getDomain(win) { + void 0 === win && (win = window); + var domain = getActualDomain(win); + return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; + } + function isSameDomain(win) { + if (!function(win) { + try { + if (win === window) return !0; + } catch (err) {} + try { + var desc = Object.getOwnPropertyDescriptor(win, "location"); + if (desc && !1 === desc.enumerable) return !1; + } catch (err) {} + try { + if (isAboutProtocol(win) && canReadFromWindow()) return !0; + } catch (err) {} + try { + if (function(win) { + void 0 === win && (win = window); + return "mock:" === getProtocol(win); + }(win) && canReadFromWindow()) return !0; + } catch (err) {} + try { + if (getActualDomain(win) === getActualDomain(window)) return !0; + } catch (err) {} + return !1; + }(win)) return !1; + try { + if (win === window) return !0; + if (isAboutProtocol(win) && canReadFromWindow()) return !0; + if (getDomain(window) === getDomain(win)) return !0; + } catch (err) {} + return !1; + } + function assertSameDomain(win) { + if (!isSameDomain(win)) throw new Error("Expected window to be same domain"); + return win; + } + function isAncestorParent(parent, child) { + if (!parent || !child) return !1; + var childParent = getParent(child); + return childParent ? childParent === parent : -1 !== function(win) { + var result = []; + try { + for (;win.parent !== win; ) { + result.push(win.parent); + win = win.parent; + } + } catch (err) {} + return result; + }(child).indexOf(parent); + } + function getAllChildFrames(win) { + var result = []; + for (var _i3 = 0, _getFrames2 = function(win) { + var result = []; + var frames; + try { + frames = win.frames; + } catch (err) { + frames = win; + } + var len; + try { + len = frames.length; + } catch (err) {} + if (0 === len) return result; + if (len) { + for (var i = 0; i < len; i++) { + var frame = void 0; + try { + frame = frames[i]; + } catch (err) { + continue; + } + result.push(frame); + } + return result; + } + for (var _i = 0; _i < 100; _i++) { + var _frame = void 0; + try { + _frame = frames[_i]; + } catch (err) { + return result; + } + if (!_frame) return result; + result.push(_frame); + } return result; }(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; @@ -3071,422 +3478,274 @@ window.smartCard = function(modules) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { - if (obj && obj.top === obj) return !0; - } catch (err) { - if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; - } - try { - if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; - } catch (err) { - return !0; - } - try { - if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; - } catch (err) {} - return !1; - } -}, function(module, __webpack_exports__, __webpack_require__) { - "use strict"; - __webpack_require__.d(__webpack_exports__, "b", (function() { - return calculateTotalFromShippingBreakdownAmounts; - })); - __webpack_require__.d(__webpack_exports__, "a", (function() { - return buildBreakdown; - })); - __webpack_require__.d(__webpack_exports__, "c", (function() { - return convertQueriesToArray; - })); - __webpack_require__.d(__webpack_exports__, "e", (function() { - return updateShippingOptions; - })); - __webpack_require__.d(__webpack_exports__, "d", (function() { - return updateOperationForShippingOptions; - })); - var _onShippingChange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); - var calculateTotalFromShippingBreakdownAmounts = function(_ref) { - var breakdown = _ref.breakdown, updatedAmounts = _ref.updatedAmounts; - var newAmount = 0; - var updatedAmountKeys = Object.keys(updatedAmounts) || []; - var discountKeys = [ "shipping_discount", "discount" ]; - Object.keys(breakdown).forEach((function(item) { - if (-1 !== updatedAmountKeys.indexOf(item)) discountKeys.includes(item) ? newAmount -= Math.abs(parseFloat(updatedAmounts[item])) : newAmount += parseFloat(updatedAmounts[item]); else if (discountKeys.includes(item)) { - var _breakdown$item; - newAmount -= Math.abs(parseFloat(null == (_breakdown$item = breakdown[item]) ? void 0 : _breakdown$item.value)); - } else { - var _breakdown$item2; - newAmount += parseFloat(null == (_breakdown$item2 = breakdown[item]) ? void 0 : _breakdown$item2.value); - } - })); - updatedAmountKeys.forEach((function(key) { - breakdown[key] || updatedAmounts[key] && (discountKeys.includes(key) ? newAmount -= Math.abs(parseFloat(updatedAmounts[key])) : newAmount += parseFloat(updatedAmounts[key])); - })); - return newAmount.toFixed(2); - }; - var buildBreakdown = function(_ref2) { - var _Object$values$; - var _ref2$breakdown = _ref2.breakdown, breakdown = void 0 === _ref2$breakdown ? {} : _ref2$breakdown, _ref2$updatedAmounts = _ref2.updatedAmounts, updatedAmounts = void 0 === _ref2$updatedAmounts ? {} : _ref2$updatedAmounts; - var discountKeys = [ "shipping_discount", "discount" ]; - var updatedAmountKeys = Object.keys(updatedAmounts); - var currency_code = null == (_Object$values$ = Object.values(breakdown)[0]) ? void 0 : _Object$values$.currency_code; - updatedAmountKeys.forEach((function(key) { - breakdown[key] ? breakdown[key].value = updatedAmounts[key] : updatedAmounts[key] && (breakdown[key] = { - currency_code: currency_code, - value: updatedAmounts[key] && discountKeys.includes(key) ? Math.abs(parseFloat(updatedAmounts[key])).toFixed(2) : updatedAmounts[key] - }); - })); - return breakdown; - }; - var convertQueriesToArray = function(_ref3) { - return Object.values(_ref3.queries) || []; - }; - var updateShippingOptions = function(_ref4) { - var option = _ref4.option; - var updatedOptions = []; - _ref4.options.forEach((function(opt) { - if (!opt.id) throw new Error("Must provide an id with each shipping option."); - if (opt.id === option.id) { - opt.selected = !0; - updatedOptions.push(opt); - } else { - opt.selected = !1; - updatedOptions.push(opt); - } - })); - return updatedOptions; - }; - var updateOperationForShippingOptions = function(_ref5) { - var queries = _ref5.queries; - queries[_onShippingChange__WEBPACK_IMPORTED_MODULE_0__.b.OPTIONS] && (queries[_onShippingChange__WEBPACK_IMPORTED_MODULE_0__.b.OPTIONS].op = "replace"); - return convertQueriesToArray({ - queries: queries - }); - }; -}, function(module, exports, __webpack_require__) { - "use strict"; - var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) { - void 0 === k2 && (k2 = k); - Object.defineProperty(o, k2, { - enumerable: !0, - get: function() { - return m[k]; - } - }); - } : function(o, m, k, k2) { - void 0 === k2 && (k2 = k); - o[k2] = m[k]; - }); - var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function(o, v) { - Object.defineProperty(o, "default", { - enumerable: !0, - value: v - }); - } : function(o, v) { - o.default = v; - }); - var creditCardType = (this && this.__importStar || function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (null != mod) for (var k in mod) "default" !== k && {}.hasOwnProperty.call(mod, k) && __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - })(__webpack_require__(26)); - var cardholder_name_1 = __webpack_require__(56); - var card_number_1 = __webpack_require__(57); - var expiration_date_1 = __webpack_require__(59); - var expiration_month_1 = __webpack_require__(28); - var expiration_year_1 = __webpack_require__(25); - var cvv_1 = __webpack_require__(62); - var postal_code_1 = __webpack_require__(63); - module.exports = { - creditCardType: creditCardType, - cardholderName: cardholder_name_1.cardholderName, - number: card_number_1.cardNumber, - expirationDate: expiration_date_1.expirationDate, - expirationMonth: expiration_month_1.expirationMonth, - expirationYear: expiration_year_1.expirationYear, - cvv: cvv_1.cvv, - postalCode: postal_code_1.postalCode - }; + if (obj && obj.top === obj) return !0; + } catch (err) { + if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; + } + try { + if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; + } catch (err) { + return !0; + } + try { + if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; + } catch (err) {} + return !1; + } }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; - __webpack_require__.d(__webpack_exports__, "a", (function() { - return getLogger; - })); __webpack_require__.d(__webpack_exports__, "b", (function() { - return sendCountMetric; + return ON_SHIPPING_CHANGE_PATHS; })); __webpack_require__.d(__webpack_exports__, "c", (function() { - return setupLogger; + return SHIPPING_ADDRESS_ERROR_MESSAGES; })); - var esm_extends = __webpack_require__(5); - var src = __webpack_require__(4); - var belter_src = __webpack_require__(3); - var AUTO_FLUSH_LEVEL = [ "warn", "error" ]; - var LOG_LEVEL_PRIORITY = [ "error", "warn", "info", "debug" ]; - var extendIfDefined = function(target, source) { - for (var key in source) source.hasOwnProperty(key) && (target[key] = source[key]); - }; - var cross_domain_utils_src = __webpack_require__(10); - var sdk_constants_src = __webpack_require__(0); - var config = __webpack_require__(7); - function getLogger() { - var loggerUrl = window && "object" == typeof window.xprops && window.xprops.disableSetCookie ? config.f + "?disableSetCookie=true" : config.f; - return Object(belter_src.i)(getLogger, (function() { - return function(_ref) { - var url = _ref.url, prefix = _ref.prefix, _ref$logLevel = _ref.logLevel, logLevel = void 0 === _ref$logLevel ? "warn" : _ref$logLevel, _ref$transport = _ref.transport, transport = void 0 === _ref$transport ? function(_ref) { - var url = _ref.url, method = _ref.method, headers = _ref.headers, json = _ref.json, _ref$enableSendBeacon = _ref.enableSendBeacon, enableSendBeacon = void 0 !== _ref$enableSendBeacon && _ref$enableSendBeacon; - return src.a.try((function() { - var httpWindow = window; - var win = Object(cross_domain_utils_src.d)(httpWindow) ? Object(cross_domain_utils_src.a)(httpWindow) : window; - var beaconResult = !1; - (function(_ref) { - var headers = _ref.headers, enableSendBeacon = _ref.enableSendBeacon; - var hasHeaders = headers && Object.keys(headers).length; - return !!(window && window.navigator.sendBeacon && !hasHeaders && enableSendBeacon && window.Blob); - })({ - headers: headers, - enableSendBeacon: enableSendBeacon - }) && (beaconResult = function(_ref2) { - var _ref2$win = _ref2.win, win = void 0 === _ref2$win ? window : _ref2$win, url = _ref2.url, data = _ref2.data, _ref2$useBlob = _ref2.useBlob, useBlob = void 0 === _ref2$useBlob || _ref2$useBlob; - try { - var json = JSON.stringify(data); - if (!win.navigator.sendBeacon) throw new Error("No sendBeacon available"); - if (useBlob) { - var blob = new Blob([ json ], { - type: "application/json" - }); - return win.navigator.sendBeacon(url, blob); - } - return win.navigator.sendBeacon(url, json); - } catch (e) { - return !1; - } - }({ - win: win, - url: url, - data: json, - useBlob: !0 - })); - return beaconResult || Object(belter_src.t)({ - win: win, - url: url, - method: method, - headers: headers, - json: json - }); - })).then(belter_src.p); - } : _ref$transport, _ref$flushInterval = _ref.flushInterval, flushInterval = void 0 === _ref$flushInterval ? 6e4 : _ref$flushInterval, _ref$enableSendBeacon = _ref.enableSendBeacon, enableSendBeacon = void 0 !== _ref$enableSendBeacon && _ref$enableSendBeacon; - var events = []; - var tracking = []; - var metrics = []; - var payloadBuilders = []; - var metaBuilders = []; - var trackingBuilders = []; - var headerBuilders = []; - function print(level, event, payload) { - if (Object(belter_src.k)() && window.console && window.console.log && !(LOG_LEVEL_PRIORITY.indexOf(level) > LOG_LEVEL_PRIORITY.indexOf(logLevel))) { - var args = [ event ]; - args.push(payload); - (payload.error || payload.warning) && args.push("\n\n", payload.error || payload.warning); - try { - window.console[level] && window.console[level].apply ? window.console[level].apply(window.console, args) : window.console.log && window.console.log.apply && window.console.log.apply(window.console, args); - } catch (err) {} - } - } - function immediateFlush() { - return src.a.try((function() { - if (Object(belter_src.k)() && "file:" !== window.location.protocol && (events.length || tracking.length || metrics.length)) { - var meta = {}; - for (var _i2 = 0; _i2 < metaBuilders.length; _i2++) extendIfDefined(meta, (0, metaBuilders[_i2])(meta)); - var headers = {}; - for (var _i4 = 0; _i4 < headerBuilders.length; _i4++) extendIfDefined(headers, (0, - headerBuilders[_i4])(headers)); - var res; - url && (res = transport({ - method: "POST", - url: url, - headers: headers, - json: { - events: events, - meta: meta, - tracking: tracking, - metrics: metrics - }, - enableSendBeacon: enableSendBeacon - }).catch(belter_src.p)); - events = []; - tracking = []; - metrics = []; - return src.a.resolve(res).then(belter_src.p); - } - })); - } - var flush = Object(belter_src.r)(immediateFlush); - function log(level, event, payload) { - void 0 === payload && (payload = {}); - if (!Object(belter_src.k)()) return logger; - prefix && (event = prefix + "_" + event); - var logPayload = Object(esm_extends.a)({}, Object(belter_src.q)(payload), { - timestamp: Date.now().toString() - }); - for (var _i6 = 0; _i6 < payloadBuilders.length; _i6++) extendIfDefined(logPayload, (0, - payloadBuilders[_i6])(logPayload)); - !function(level, event, payload) { - events.push({ - level: level, - event: event, - payload: payload - }); - -1 !== AUTO_FLUSH_LEVEL.indexOf(level) && flush(); - }(level, event, logPayload); - print(level, event, logPayload); - return logger; - } - function addBuilder(builders, builder) { - builders.push(builder); - return logger; - } - Object(belter_src.k)() && Object(belter_src.u)(flush, flushInterval); - if ("object" == typeof window) { - window.addEventListener("beforeunload", (function() { - immediateFlush(); - })); - window.addEventListener("unload", (function() { - immediateFlush(); - })); - window.addEventListener("pagehide", (function() { - immediateFlush(); - })); - } - var logger = { - debug: function(event, payload) { - return log("debug", event, payload); - }, - info: function(event, payload) { - return log("info", event, payload); - }, - warn: function(event, payload) { - return log("warn", event, payload); - }, - error: function(event, payload) { - return log("error", event, payload); - }, - track: function(payload) { - void 0 === payload && (payload = {}); - if (!Object(belter_src.k)()) return logger; - var trackingPayload = Object(belter_src.q)(payload); - for (var _i8 = 0; _i8 < trackingBuilders.length; _i8++) extendIfDefined(trackingPayload, (0, - trackingBuilders[_i8])(trackingPayload)); - print("debug", "track", trackingPayload); - tracking.push(trackingPayload); - return logger; - }, - metric: function(metricPayload) { - if (!Object(belter_src.k)()) return logger; - print("debug", "metric." + metricPayload.metricNamespace, metricPayload.dimensions || {}); - metrics.push(metricPayload); - return logger; - }, - flush: flush, - immediateFlush: immediateFlush, - addPayloadBuilder: function(builder) { - return addBuilder(payloadBuilders, builder); - }, - addMetaBuilder: function(builder) { - return addBuilder(metaBuilders, builder); - }, - addTrackingBuilder: function(builder) { - return addBuilder(trackingBuilders, builder); - }, - addHeaderBuilder: function(builder) { - return addBuilder(headerBuilders, builder); - }, - setTransport: function(newTransport) { - transport = newTransport; - return logger; - }, - configure: function(opts) { - opts.url && (url = opts.url); - opts.prefix && (prefix = opts.prefix); - opts.logLevel && (logLevel = opts.logLevel); - opts.transport && (transport = opts.transport); - opts.flushInterval && (flushInterval = opts.flushInterval); - opts.enableSendBeacon && (enableSendBeacon = opts.enableSendBeacon); - return logger; - }, - __buffer__: { - get events() { - return events; - }, - get tracking() { - return tracking; - }, - get metrics() { - return metrics; - } - } - }; - Object.defineProperty(logger, "__buffer__", { - writable: !1 - }); - return logger; - }({ - url: loggerUrl, - enableSendBeacon: !0 - }); - })); - } - var sendCountMetric = function(_ref) { - var dimensions = _ref.dimensions, _ref$event = _ref.event, event = void 0 === _ref$event ? "unused" : _ref$event, name = _ref.name, _ref$value = _ref.value, value = void 0 === _ref$value ? 1 : _ref$value; - return getLogger().metric({ - dimensions: dimensions, - metricEventName: event, - metricNamespace: name, - metricValue: value, - metricType: "counter" + __webpack_require__.d(__webpack_exports__, "d", (function() { + return SHIPPING_OPTIONS_ERROR_MESSAGES; + })); + __webpack_require__.d(__webpack_exports__, "a", (function() { + return GENERIC_REJECT_ADDRESS_MESSAGE; + })); + __webpack_require__(18); + __webpack_require__(5); + __webpack_require__(4); + __webpack_require__(0); + __webpack_require__(8); + __webpack_require__(1); + __webpack_require__(2); + __webpack_require__(13); + var ON_SHIPPING_CHANGE_PATHS = { + AMOUNT: "/purchase_units/@reference_id=='default'/amount", + OPTIONS: "/purchase_units/@reference_id=='default'/shipping/options" + }; + var SHIPPING_ADDRESS_ERROR_MESSAGES = { + ADDRESS_ERROR: "Your order can't be shipped to this address.", + COUNTRY_ERROR: "Your order can't be shipped to this country.", + STATE_ERROR: "Your order can't be shipped to this state.", + ZIP_ERROR: "Your order can't be shipped to this zip." + }; + var SHIPPING_OPTIONS_ERROR_MESSAGES = { + METHOD_UNAVAILABLE: "The shipping method you chose is unavailable. To continue, choose another way to get your order.", + STORE_UNAVAILABLE: "Part of your order isn't available at this store." + }; + var GENERIC_REJECT_ADDRESS_MESSAGE = "Unable to update address. Please try again."; + new RegExp(/^\/purchase_units\/@reference_id=='(?:\w|-)*'\/(?:amount|shipping\/(?:options|address|name))$/); +}, function(module, exports, __webpack_require__) { + "use strict"; + var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) { + void 0 === k2 && (k2 = k); + Object.defineProperty(o, k2, { + enumerable: !0, + get: function() { + return m[k]; + } + }); + } : function(o, m, k, k2) { + void 0 === k2 && (k2 = k); + o[k2] = m[k]; + }); + var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { + enumerable: !0, + value: v }); + } : function(o, v) { + o.default = v; + }); + var creditCardType = (this && this.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (null != mod) for (var k in mod) "default" !== k && {}.hasOwnProperty.call(mod, k) && __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + })(__webpack_require__(27)); + var cardholder_name_1 = __webpack_require__(57); + var card_number_1 = __webpack_require__(58); + var expiration_date_1 = __webpack_require__(60); + var expiration_month_1 = __webpack_require__(29); + var expiration_year_1 = __webpack_require__(26); + var cvv_1 = __webpack_require__(63); + var postal_code_1 = __webpack_require__(64); + module.exports = { + creditCardType: creditCardType, + cardholderName: cardholder_name_1.cardholderName, + number: card_number_1.cardNumber, + expirationDate: expiration_date_1.expirationDate, + expirationMonth: expiration_month_1.expirationMonth, + expirationYear: expiration_year_1.expirationYear, + cvv: cvv_1.cvv, + postalCode: postal_code_1.postalCode }; - function setupLogger(_ref3) { - var env = _ref3.env, sessionID = _ref3.sessionID, clientID = _ref3.clientID, sdkCorrelationID = _ref3.sdkCorrelationID, buyerCountry = _ref3.buyerCountry, locale = _ref3.locale, _ref3$sdkVersion = _ref3.sdkVersion, sdkVersion = void 0 === _ref3$sdkVersion ? window.paypal.version : _ref3$sdkVersion; - var logger = getLogger(); - logger.addPayloadBuilder((function() { - return { - referer: window.location.host, - sdkCorrelationID: sdkCorrelationID, - sessionID: sessionID, - clientID: clientID, - env: env - }; +}, function(module, __webpack_exports__, __webpack_require__) { + "use strict"; + __webpack_require__.d(__webpack_exports__, "a", (function() { + return checkUlsatNotRequired; + })); + __webpack_require__.d(__webpack_exports__, "b", (function() { + return redirect; + })); + var _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); + var _krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); + __webpack_require__(4); + var _lib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2); + var checkUlsatNotRequired = function(paymentSource, buyerAccessToken) { + return paymentSource === _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_0__.g.VENMO && !buyerAccessToken; + }; + var redirect = function(url) { + if (!url) throw new Error("Expected redirect url"); + if (-1 === url.indexOf("://")) { + Object(_lib__WEBPACK_IMPORTED_MODULE_3__.c)().warn("redir_url_non_scheme", { + url: url + }).flush(); + throw new Error("Invalid redirect url: " + url + " - must be fully qualified url"); + } + if (!url.match(/^https:\/\//)) { + Object(_lib__WEBPACK_IMPORTED_MODULE_3__.c)().warn("redir_url_non_http", { + url: url + }).flush(); + if (url.toLowerCase().replace(/[^a-z:]+/g, "").match(/^javascript:/)) { + Object(_lib__WEBPACK_IMPORTED_MODULE_3__.c)().warn("redir_url_has_javascript", { + url: url + }).flush(); + throw new Error("Invalid redirect url: " + url + " - must be fully qualified url"); + } + } + return Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__.s)(url, window.top); + }; +}, function(module, __webpack_exports__, __webpack_require__) { + "use strict"; + __webpack_require__.d(__webpack_exports__, "c", (function() { + return calculateTotalFromShippingBreakdownAmounts; + })); + __webpack_require__.d(__webpack_exports__, "e", (function() { + return optionsKeyChanges; + })); + __webpack_require__.d(__webpack_exports__, "a", (function() { + return breakdownKeyChanges; + })); + __webpack_require__.d(__webpack_exports__, "b", (function() { + return buildBreakdown; + })); + __webpack_require__.d(__webpack_exports__, "d", (function() { + return convertQueriesToArray; + })); + __webpack_require__.d(__webpack_exports__, "g", (function() { + return updateShippingOptions; + })); + __webpack_require__.d(__webpack_exports__, "f", (function() { + return updateOperationForShippingOptions; + })); + var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5); + var _onShippingChange__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11); + var calculateTotalFromShippingBreakdownAmounts = function(_ref) { + var breakdown = _ref.breakdown, updatedAmounts = _ref.updatedAmounts; + var newAmount = 0; + var updatedAmountKeys = Object.keys(updatedAmounts) || []; + var discountKeys = [ "shipping_discount", "discount" ]; + Object.keys(breakdown).forEach((function(item) { + if (-1 !== updatedAmountKeys.indexOf(item)) discountKeys.includes(item) ? newAmount -= Math.abs(parseFloat(updatedAmounts[item])) : newAmount += parseFloat(updatedAmounts[item]); else if (discountKeys.includes(item)) { + var _breakdown$item; + newAmount -= Math.abs(parseFloat(null == (_breakdown$item = breakdown[item]) ? void 0 : _breakdown$item.value)); + } else { + var _breakdown$item2; + newAmount += parseFloat(null == (_breakdown$item2 = breakdown[item]) ? void 0 : _breakdown$item2.value); + } })); - logger.addTrackingBuilder((function() { - var _ref4; - return (_ref4 = {})[sdk_constants_src.e.FEED] = sdk_constants_src.d.PAYMENTS_SDK, - _ref4[sdk_constants_src.e.DATA_SOURCE] = sdk_constants_src.c.PAYMENTS_SDK, _ref4[sdk_constants_src.e.CLIENT_ID] = clientID, - _ref4[sdk_constants_src.e.SESSION_UID] = sessionID, _ref4[sdk_constants_src.e.REFERER] = window.location.host, - _ref4[sdk_constants_src.e.BUYER_COUNTRY] = buyerCountry, _ref4[sdk_constants_src.e.LOCALE] = locale.lang + "_" + locale.country, - _ref4[sdk_constants_src.e.INTEGRATION_IDENTIFIER] = clientID, _ref4[sdk_constants_src.e.SDK_ENVIRONMENT] = Object(belter_src.m)() ? sdk_constants_src.i.IOS : Object(belter_src.j)() ? sdk_constants_src.i.ANDROID : null, - _ref4[sdk_constants_src.e.SDK_NAME] = sdk_constants_src.f.PAYMENTS_SDK, _ref4[sdk_constants_src.e.SDK_VERSION] = sdkVersion, - _ref4[sdk_constants_src.e.USER_AGENT] = window.navigator && window.navigator.userAgent, - _ref4[sdk_constants_src.e.CONTEXT_CORRID] = sdkCorrelationID, _ref4[sdk_constants_src.e.TIMESTAMP] = Date.now().toString(), - _ref4; + updatedAmountKeys.forEach((function(key) { + breakdown[key] || updatedAmounts[key] && (discountKeys.includes(key) ? newAmount -= Math.abs(parseFloat(updatedAmounts[key])) : newAmount += parseFloat(updatedAmounts[key])); })); - src.a.onPossiblyUnhandledException((function(err) { - var _logger$track; - logger.track(((_logger$track = {})[sdk_constants_src.e.ERROR_CODE] = "payments_sdk_error", - _logger$track[sdk_constants_src.e.ERROR_DESC] = Object(belter_src.w)(err), _logger$track)); - logger.error("unhandled_error", { - err: Object(belter_src.v)(err) - }); - sendCountMetric({ - event: "error", - name: "pp.app.paypal_sdk.buttons.unhandled_exception.count", - dimensions: { - errorType: "payments_sdk_error" + return newAmount.toFixed(2); + }; + var optionsKeyChanges = function(options) { + var ordersV2Options = []; + options.forEach((function(element) { + var shippingOption = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.a)({}, element, { + amount: { + value: element.amount.value, + currency_code: element.amount.currencyCode } }); - logger.flush().catch(belter_src.p); + ordersV2Options.push(shippingOption); })); - } + return ordersV2Options; + }; + var breakdownKeyChanges = function(breakdown) { + return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.a)({}, breakdown.discount ? { + discount: { + value: breakdown.discount.value, + currency_code: breakdown.discount.currencyCode + } + } : void 0, breakdown.handling ? { + handling: { + value: breakdown.handling.value, + currency_code: breakdown.handling.currencyCode + } + } : void 0, breakdown.insurance ? { + insurance: { + value: breakdown.insurance.value, + currency_code: breakdown.insurance.currencyCode + } + } : void 0, breakdown.itemTotal ? { + item_total: { + value: breakdown.itemTotal.value, + currency_code: breakdown.itemTotal.currencyCode + } + } : void 0, breakdown.shipping ? { + shipping: { + value: breakdown.shipping.value, + currency_code: breakdown.shipping.currencyCode + } + } : void 0, breakdown.shippingDiscount ? { + shipping_discount: { + value: breakdown.shippingDiscount.value, + currency_code: breakdown.shippingDiscount.currencyCode + } + } : void 0, breakdown.taxTotal ? { + tax_total: { + value: breakdown.taxTotal.value, + currency_code: breakdown.taxTotal.currencyCode + } + } : void 0); + }; + var buildBreakdown = function(_ref2) { + var _Object$values$; + var _ref2$breakdown = _ref2.breakdown, breakdown = void 0 === _ref2$breakdown ? {} : _ref2$breakdown, _ref2$updatedAmounts = _ref2.updatedAmounts, updatedAmounts = void 0 === _ref2$updatedAmounts ? {} : _ref2$updatedAmounts; + var discountKeys = [ "shipping_discount", "discount" ]; + var updatedAmountKeys = Object.keys(updatedAmounts); + var currency_code = null == (_Object$values$ = Object.values(breakdown)[0]) ? void 0 : _Object$values$.currency_code; + updatedAmountKeys.forEach((function(key) { + breakdown[key] ? breakdown[key].value = updatedAmounts[key] : updatedAmounts[key] && (breakdown[key] = { + currency_code: currency_code, + value: updatedAmounts[key] && discountKeys.includes(key) ? Math.abs(parseFloat(updatedAmounts[key])).toFixed(2) : updatedAmounts[key] + }); + })); + return breakdown; + }; + var convertQueriesToArray = function(_ref3) { + return Object.values(_ref3.queries) || []; + }; + var updateShippingOptions = function(_ref4) { + var option = _ref4.option; + var updatedOptions = []; + _ref4.options.forEach((function(opt) { + if (!opt.id) throw new Error("Must provide an id with each shipping option."); + if (opt.id === option.id) { + option.selected = !0; + updatedOptions.push(option); + } else { + opt.selected = !1; + updatedOptions.push(opt); + } + })); + return updatedOptions; + }; + var updateOperationForShippingOptions = function(_ref5) { + var queries = _ref5.queries; + queries[_onShippingChange__WEBPACK_IMPORTED_MODULE_1__.b.OPTIONS] && (queries[_onShippingChange__WEBPACK_IMPORTED_MODULE_1__.b.OPTIONS].op = "replace"); + return convertQueriesToArray({ + queries: queries + }); + }; }, function(module, exports, __webpack_require__) { "use strict"; module.exports = { @@ -3503,7 +3762,7 @@ window.smartCard = function(modules) { } }; }, function(module, exports, __webpack_require__) { - module.exports = __webpack_require__(64); + module.exports = __webpack_require__(65); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.d(__webpack_exports__, "f", (function() { @@ -3530,7 +3789,7 @@ window.smartCard = function(modules) { __webpack_require__(0); __webpack_require__(10); __webpack_require__(1); - __webpack_require__(13); + __webpack_require__(9); function unresolvedPromise() { return new _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__.a(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.p); } @@ -3582,12 +3841,12 @@ window.smartCard = function(modules) { } }, function(module, exports, __webpack_require__) { "use strict"; - var keyCannotMutateValue = __webpack_require__(19); - var getSelection = __webpack_require__(14).get; - var setSelection = __webpack_require__(14).set; - var isBackspace = __webpack_require__(47); - var isDelete = __webpack_require__(76); - var Formatter = __webpack_require__(77); + var keyCannotMutateValue = __webpack_require__(20); + var getSelection = __webpack_require__(15).get; + var setSelection = __webpack_require__(15).set; + var isBackspace = __webpack_require__(48); + var isDelete = __webpack_require__(77); + var Formatter = __webpack_require__(78); function BaseStrategy(options) { this.isFormatted = !1; this.inputElement = options.element; @@ -3703,7 +3962,7 @@ window.smartCard = function(modules) { module.exports = BaseStrategy; }, function(module, exports, __webpack_require__) { "use strict"; - var getCurrentSelection = __webpack_require__(14).get; + var getCurrentSelection = __webpack_require__(15).get; module.exports = function(event) { var input = event.currentTarget || event.srcElement; var selection = getCurrentSelection(input); @@ -3848,14 +4107,15 @@ window.smartCard = function(modules) { var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); var _api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); var updateVaultSetupToken = function(_ref2) { - var clientID = _ref2.clientID, vaultSetupToken = _ref2.vaultSetupToken, paymentSource = _ref2.paymentSource; + var clientID = _ref2.clientID, vaultSetupToken = _ref2.vaultSetupToken, paymentSource = _ref2.paymentSource, idToken = _ref2.idToken; return Object(_api__WEBPACK_IMPORTED_MODULE_2__.a)({ name: "UpdateVaultSetupToken", - query: "\n mutation UpdateVaultSetupToken(\n $clientID: String!\n $vaultSetupToken: String!\n $paymentSource: PaymentSource\n ) {\n updateVaultSetupToken(\n clientId: $clientID\n vaultSetupToken: $vaultSetupToken\n paymentSource: $paymentSource\n ) {\n id,\n status,\n links {\n rel, href\n }\n }\n }", + query: "\n mutation UpdateVaultSetupToken(\n $clientID: String!\n $vaultSetupToken: String!\n $paymentSource: PaymentSource\n $idToken: String\n ) {\n updateVaultSetupToken(\n clientId: $clientID\n vaultSetupToken: $vaultSetupToken\n paymentSource: $paymentSource\n idToken: $idToken\n ) {\n id,\n status,\n links {\n rel, href\n }\n }\n }", variables: { clientID: clientID, vaultSetupToken: vaultSetupToken, - paymentSource: paymentSource + paymentSource: paymentSource, + idToken: idToken } }); }; @@ -3925,11 +4185,11 @@ window.smartCard = function(modules) { return t; }).apply(this, arguments); }; - var cardTypes = __webpack_require__(51); - var add_matching_cards_to_results_1 = __webpack_require__(52); - var is_valid_input_type_1 = __webpack_require__(54); - var find_best_match_1 = __webpack_require__(55); - var clone_1 = __webpack_require__(27); + var cardTypes = __webpack_require__(52); + var add_matching_cards_to_results_1 = __webpack_require__(53); + var is_valid_input_type_1 = __webpack_require__(55); + var find_best_match_1 = __webpack_require__(56); + var clone_1 = __webpack_require__(28); var customCards = {}; var cardNames = { VISA: "visa", @@ -4040,11 +4300,11 @@ window.smartCard = function(modules) { __webpack_require__(0); var _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); var _lib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2); - var _onInit__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20); - var _onClick__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(21); - var _onError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(22); + var _onInit__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(21); + var _onClick__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(22); + var _onError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(23); function getProps(_ref) { - var branded = _ref.branded, enableOrdersApprovalSmartWallet = _ref.enableOrdersApprovalSmartWallet, smartWalletOrderID = _ref.smartWalletOrderID; + var branded = _ref.branded; var xprops = window.xprops; var uid = xprops.uid, env = xprops.env, _xprops$vault = xprops.vault, vault = void 0 !== _xprops$vault && _xprops$vault, commit = xprops.commit, locale = xprops.locale, platform = xprops.platform, sessionID = xprops.sessionID, clientID = xprops.clientID, partnerAttributionID = xprops.partnerAttributionID, merchantRequestedPopupsDisabled = xprops.merchantRequestedPopupsDisabled, clientMetadataID = xprops.clientMetadataID, sdkCorrelationID = xprops.sdkCorrelationID, getParentDomain = xprops.getParentDomain, clientAccessToken = xprops.clientAccessToken, getPopupBridge = xprops.getPopupBridge, getPrerenderDetails = xprops.getPrerenderDetails, getPageUrl = xprops.getPageUrl, enableThreeDomainSecure = xprops.enableThreeDomainSecure, enableVaultInstallments = xprops.enableVaultInstallments, _xprops$enableNativeC = xprops.enableNativeCheckout, enableNativeCheckout = void 0 !== _xprops$enableNativeC && _xprops$enableNativeC, rememberFunding = xprops.remember, stageHost = xprops.stageHost, apiStageHost = xprops.apiStageHost, getParent = xprops.getParent, fundingSource = xprops.fundingSource, currency = xprops.currency, connect = xprops.connect, intent = xprops.intent, merchantID = xprops.merchantID, amount = xprops.amount, userIDToken = xprops.userIDToken, enableFunding = xprops.enableFunding, disableFunding = xprops.disableFunding, disableCard = xprops.disableCard, disableAutocomplete = xprops.disableAutocomplete, wallet = xprops.wallet, _xprops$paymentMethod = xprops.paymentMethodToken, paymentMethodToken = void 0 === _xprops$paymentMethod ? xprops.paymentMethodNonce : _xprops$paymentMethod, _xprops$getQueriedEli = xprops.getQueriedEligibleFunding, getQueriedEligibleFunding = void 0 === _xprops$getQueriedEli ? function() { return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__.a.resolve([]); @@ -4110,8 +4370,6 @@ window.smartCard = function(modules) { allowBillingPayments: allowBillingPayments, paymentRequest: paymentRequest, merchantID: merchantID, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, - smartWalletOrderID: smartWalletOrderID, disableSetCookie: disableSetCookie }; } @@ -4126,7 +4384,7 @@ window.smartCard = function(modules) { __webpack_require__(1); __webpack_require__(2); __webpack_require__(7); - __webpack_require__(23); + __webpack_require__(24); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__(4); @@ -4148,6 +4406,8 @@ window.smartCard = function(modules) { __webpack_require__(3); __webpack_require__(4); __webpack_require__(0); + __webpack_require__(1); + __webpack_require__(2); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__(5); @@ -4158,6 +4418,7 @@ window.smartCard = function(modules) { __webpack_require__(1); __webpack_require__(2); __webpack_require__(7); + __webpack_require__(13); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__(4); @@ -4166,6 +4427,7 @@ window.smartCard = function(modules) { __webpack_require__(2); __webpack_require__(1); __webpack_require__(8); + __webpack_require__(13); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__(3); @@ -4173,30 +4435,31 @@ window.smartCard = function(modules) { __webpack_require__(0); __webpack_require__(2); __webpack_require__(1); + __webpack_require__(13); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; - __webpack_require__(24); + __webpack_require__(25); __webpack_require__(5); - __webpack_require__(17); + __webpack_require__(18); __webpack_require__(4); __webpack_require__(0); __webpack_require__(8); __webpack_require__(1); __webpack_require__(2); - __webpack_require__(9); __webpack_require__(11); + __webpack_require__(14); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; - __webpack_require__(24); + __webpack_require__(25); __webpack_require__(5); - __webpack_require__(17); + __webpack_require__(18); __webpack_require__(4); __webpack_require__(0); __webpack_require__(8); __webpack_require__(1); __webpack_require__(2); - __webpack_require__(9); __webpack_require__(11); + __webpack_require__(14); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__(4); @@ -4210,8 +4473,6 @@ window.smartCard = function(modules) { }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__(4); - __webpack_require__(3); - __webpack_require__(8); __webpack_require__(2); }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -4220,10 +4481,10 @@ window.smartCard = function(modules) { }, function(module, exports) {}, function(module, exports, __webpack_require__) { "use strict"; var UA = window.navigator && window.navigator.userAgent; - var isAndroid = __webpack_require__(66); - var isChrome = __webpack_require__(67); - var isIos = __webpack_require__(70); - var isIE9 = __webpack_require__(71); + var isAndroid = __webpack_require__(67); + var isChrome = __webpack_require__(68); + var isIos = __webpack_require__(71); + var isIE9 = __webpack_require__(72); var KITKAT_WEBVIEW_REGEX = /Version\/\d\.\d* Chrome\/\d*\.0\.0\.0/; module.exports = { isIE9: isIE9, @@ -4249,9 +4510,9 @@ window.smartCard = function(modules) { }; }, function(module, exports, __webpack_require__) { "use strict"; - var keyCannotMutateValue = __webpack_require__(19); - var BaseStrategy = __webpack_require__(18); - var setSelection = __webpack_require__(14).set; + var keyCannotMutateValue = __webpack_require__(20); + var BaseStrategy = __webpack_require__(19); + var setSelection = __webpack_require__(15).set; function AndroidChromeStrategy(options) { BaseStrategy.call(this, options); } @@ -4286,32 +4547,32 @@ window.smartCard = function(modules) { module.exports = AndroidChromeStrategy; }, function(module, __webpack_exports__, __webpack_require__) { "use strict"; - var _props__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(29); + var _props__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30); __webpack_require__.d(__webpack_exports__, "getProps", (function() { return _props__WEBPACK_IMPORTED_MODULE_0__.a; })); - __webpack_require__(30); __webpack_require__(31); __webpack_require__(32); __webpack_require__(33); __webpack_require__(34); __webpack_require__(35); __webpack_require__(36); - __webpack_require__(20); __webpack_require__(37); - __webpack_require__(9); + __webpack_require__(21); __webpack_require__(38); + __webpack_require__(11); __webpack_require__(39); - __webpack_require__(21); - __webpack_require__(22); __webpack_require__(40); + __webpack_require__(22); + __webpack_require__(23); __webpack_require__(41); __webpack_require__(42); __webpack_require__(43); __webpack_require__(44); __webpack_require__(45); + __webpack_require__(46); }, function(module, exports, __webpack_require__) { - module.exports = __webpack_require__(65); + module.exports = __webpack_require__(66); }, function(module, exports, __webpack_require__) { "use strict"; module.exports = { @@ -4454,8 +4715,8 @@ window.smartCard = function(modules) { value: !0 }); exports.addMatchingCardsToResults = void 0; - var clone_1 = __webpack_require__(27); - var matches_1 = __webpack_require__(53); + var clone_1 = __webpack_require__(28); + var matches_1 = __webpack_require__(54); exports.addMatchingCardsToResults = function(cardNumber, cardConfiguration, results) { var i, patternLength; for (i = 0; i < cardConfiguration.patterns.length; i++) { @@ -4534,8 +4795,8 @@ window.smartCard = function(modules) { value: !0 }); exports.cardNumber = void 0; - var luhn10 = __webpack_require__(58); - var getCardTypes = __webpack_require__(26); + var luhn10 = __webpack_require__(59); + var getCardTypes = __webpack_require__(27); function verification(card, isPotentiallyValid, isValid) { return { card: card, @@ -4591,9 +4852,9 @@ window.smartCard = function(modules) { value: !0 }); exports.expirationDate = void 0; - var parse_date_1 = __webpack_require__(60); - var expiration_month_1 = __webpack_require__(28); - var expiration_year_1 = __webpack_require__(25); + var parse_date_1 = __webpack_require__(61); + var expiration_month_1 = __webpack_require__(29); + var expiration_year_1 = __webpack_require__(26); function verification(isValid, isPotentiallyValid, month, year) { return { isValid: isValid, @@ -4632,8 +4893,8 @@ window.smartCard = function(modules) { value: !0 }); exports.parseDate = void 0; - var expiration_year_1 = __webpack_require__(25); - var is_array_1 = __webpack_require__(61); + var expiration_year_1 = __webpack_require__(26); + var is_array_1 = __webpack_require__(62); exports.parseDate = function(datestring) { var date; /^\d{4}-\d{1,2}$/.test(datestring) ? date = datestring.split("-").reverse() : /\//.test(datestring) ? date = datestring.split(/\s*\/\s*/g) : /\s/.test(datestring) && (date = datestring.split(/ +/g)); @@ -5291,6 +5552,9 @@ window.smartCard = function(modules) { __webpack_require__.d(__webpack_exports__, "ExtendableError", (function() { return util_ExtendableError; })); + __webpack_require__.d(__webpack_exports__, "sanitizeUrl", (function() { + return sanitizeUrl; + })); __webpack_require__.d(__webpack_exports__, "request", (function() { return request; })); @@ -5339,6 +5603,27 @@ window.smartCard = function(modules) { __webpack_require__.d(__webpack_exports__, "UID_HASH_LENGTH", (function() { return UID_HASH_LENGTH; })); + __webpack_require__.d(__webpack_exports__, "invalidProtocolRegex", (function() { + return invalidProtocolRegex; + })); + __webpack_require__.d(__webpack_exports__, "htmlEntitiesRegex", (function() { + return htmlEntitiesRegex; + })); + __webpack_require__.d(__webpack_exports__, "htmlCtrlEntityRegex", (function() { + return htmlCtrlEntityRegex; + })); + __webpack_require__.d(__webpack_exports__, "ctrlCharactersRegex", (function() { + return ctrlCharactersRegex; + })); + __webpack_require__.d(__webpack_exports__, "urlSchemeRegex", (function() { + return urlSchemeRegex; + })); + __webpack_require__.d(__webpack_exports__, "relativeFirstCharacters", (function() { + return relativeFirstCharacters; + })); + __webpack_require__.d(__webpack_exports__, "BLANK_URL", (function() { + return BLANK_URL; + })); __webpack_require__.d(__webpack_exports__, "sfvcScreens", (function() { return sfvcScreens; })); @@ -5515,9 +5800,9 @@ window.smartCard = function(modules) { void 0 === userAgent && (userAgent = getUserAgent()); return TABLET_PATTERN.test(userAgent); } - function isWebView() { - var userAgent = getUserAgent(); - return /(iPhone|iPod|iPad|Macintosh).*AppleWebKit(?!.*Safari)|.*WKWebView/i.test(userAgent) || /\bwv\b/.test(userAgent) || /Android.*Version\/(\d)\.(\d)/i.test(userAgent); + function isWebView(ua) { + void 0 === ua && (ua = getUserAgent()); + return /(iPhone|iPod|iPad|Macintosh).*AppleWebKit(?!.*Safari)|.*WKWebView/i.test(ua) || /\bwv\b/.test(ua) || /Android.*Version\/(\d)\.(\d)/i.test(ua); } function isStandAlone() { return !0 === window.navigator.standalone || window.matchMedia("(display-mode: standalone)").matches; @@ -5632,7 +5917,7 @@ window.smartCard = function(modules) { } function supportsPopups(ua) { void 0 === ua && (ua = getUserAgent()); - return !(isIosWebview(ua) || isAndroidWebview(ua) || isOperaMini(ua) || isFirefoxIOS(ua) || isEdgeIOS(ua) || isFacebookWebView(ua) || isQQBrowser(ua) || isElectron() || isMacOsCna() || isStandAlone()); + return !(isWebView(ua) || isIosWebview(ua) || isAndroidWebview(ua) || isOperaMini(ua) || isFirefoxIOS(ua) || isEdgeIOS(ua) || isFacebookWebView(ua) || isQQBrowser(ua) || isElectron() || isMacOsCna() || isStandAlone()); } function isChrome(ua) { void 0 === ua && (ua = getUserAgent()); @@ -6334,6 +6619,21 @@ window.smartCard = function(modules) { return _setPrototypeOf(Wrapper, Class); })(Class); } + var KEY_CODES = { + ENTER: 13, + SPACE: 32 + }; + var ATTRIBUTES = { + UID: "data-uid" + }; + var UID_HASH_LENGTH = 30; + var invalidProtocolRegex = /([^\w]*)(javascript|data|vbscript)/im; + var htmlEntitiesRegex = /&#(\w+)(^\w|;)?/g; + var htmlCtrlEntityRegex = /&(newline|tab);/gi; + var ctrlCharactersRegex = /[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim; + var urlSchemeRegex = /^.+(:|:)/gim; + var relativeFirstCharacters = [ ".", "/" ]; + var BLANK_URL = "about:blank"; function isElement(element) { var passed = !1; try { @@ -6728,13 +7028,13 @@ window.smartCard = function(modules) { var handlerList = handlers[eventName]; var promises = []; if (handlerList) { - var _loop = function(_i2) { + var _loop = function() { var handler = handlerList[_i2]; promises.push(promise_ZalgoPromise.try((function() { return handler.apply(void 0, args); }))); }; - for (var _i2 = 0; _i2 < handlerList.length; _i2++) _loop(_i2); + for (var _i2 = 0; _i2 < handlerList.length; _i2++) _loop(); } return promise_ZalgoPromise.all(promises).then(src_util_noop); }, @@ -6834,7 +7134,7 @@ window.smartCard = function(modules) { if (isPlainObject(item)) { var _result = {}; var _loop3 = function(key) { - if (!item.hasOwnProperty(key)) return "continue"; + if (!item.hasOwnProperty(key)) return 1; defineLazyProp(_result, key, (function() { var itemKey = fullKey ? fullKey + "." + key : "" + key; var child = replacer(item[key], key, itemKey); @@ -7026,14 +7326,19 @@ window.smartCard = function(modules) { } return ExtendableError; }(wrapNativeSuper_wrapNativeSuper(Error)); - var KEY_CODES = { - ENTER: 13, - SPACE: 32 - }; - var ATTRIBUTES = { - UID: "data-uid" - }; - var UID_HASH_LENGTH = 30; + function sanitizeUrl(url) { + if (!url) return BLANK_URL; + var sanitizedUrl = (str = url, str.replace(ctrlCharactersRegex, "").replace(htmlEntitiesRegex, (function(matchRegex, dec) { + return String.fromCharCode(dec); + }))).replace(htmlCtrlEntityRegex, "").replace(ctrlCharactersRegex, "").trim(); + var str; + if (!sanitizedUrl) return BLANK_URL; + if (function(url) { + return relativeFirstCharacters.indexOf(url[0]) > -1; + }(sanitizedUrl)) return sanitizedUrl; + var urlSchemeParseResults = sanitizedUrl.match(urlSchemeRegex); + return urlSchemeParseResults && invalidProtocolRegex.test(urlSchemeParseResults[0]) ? BLANK_URL : sanitizedUrl; + } function getBody() { var body = document.body; if (!body) throw new Error("Body element not found"); @@ -7727,7 +8032,7 @@ window.smartCard = function(modules) { getBody().removeChild(form); } function getStorage(_ref) { - var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime; + var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime, stickySessionId = _ref.stickySessionId; return inlineMemoize(getStorage, (function() { var STORAGE_KEY = "__" + name + "_storage__"; var newStateID = uniqueID(); @@ -7762,7 +8067,7 @@ window.smartCard = function(modules) { var now = Date.now(); session && now - session.created > lifetime && (session = null); session || (session = { - guid: uniqueID(), + guid: stickySessionId || uniqueID(), created: now }); storage.__session__ = session; @@ -8088,16 +8393,16 @@ window.smartCard = function(modules) { } ]); }, function(module, exports, __webpack_require__) { "use strict"; - var device = __webpack_require__(46); - var supportsInputFormatting = __webpack_require__(72); - var constants = __webpack_require__(73); - var isValidElement = __webpack_require__(74); - var IosStrategy = __webpack_require__(75); - var AndroidChromeStrategy = __webpack_require__(48); - var KitKatChromiumBasedWebViewStrategy = __webpack_require__(79); - var IE9Strategy = __webpack_require__(80); - var BaseStrategy = __webpack_require__(18); - var NoopStrategy = __webpack_require__(81); + var device = __webpack_require__(47); + var supportsInputFormatting = __webpack_require__(73); + var constants = __webpack_require__(74); + var isValidElement = __webpack_require__(75); + var IosStrategy = __webpack_require__(76); + var AndroidChromeStrategy = __webpack_require__(49); + var KitKatChromiumBasedWebViewStrategy = __webpack_require__(80); + var IE9Strategy = __webpack_require__(81); + var BaseStrategy = __webpack_require__(19); + var NoopStrategy = __webpack_require__(82); function RestrictedInput(options) { if (!isValidElement((options = options || {}).element)) throw new Error(constants.errors.INVALID_ELEMENT); if (!options.pattern) throw new Error(constants.errors.PATTERN_MISSING); @@ -8121,8 +8426,8 @@ window.smartCard = function(modules) { }; }, function(module, exports, __webpack_require__) { "use strict"; - var isEdge = __webpack_require__(68); - var isSamsung = __webpack_require__(69); + var isEdge = __webpack_require__(69); + var isSamsung = __webpack_require__(70); module.exports = function(ua) { return !(-1 === (ua = ua || navigator.userAgent).indexOf("Chrome") && -1 === ua.indexOf("CriOS") || isEdge(ua) || isSamsung(ua)); }; @@ -8150,7 +8455,7 @@ window.smartCard = function(modules) { }; }, function(module, exports, __webpack_require__) { "use strict"; - var device = __webpack_require__(46); + var device = __webpack_require__(47); module.exports = function() { return !device.isSamsungBrowser(); }; @@ -8169,10 +8474,10 @@ window.smartCard = function(modules) { }; }, function(module, exports, __webpack_require__) { "use strict"; - var BaseStrategy = __webpack_require__(18); - var keyCannotMutateValue = __webpack_require__(19); - var getSelection = __webpack_require__(14).get; - var setSelection = __webpack_require__(14).set; + var BaseStrategy = __webpack_require__(19); + var keyCannotMutateValue = __webpack_require__(20); + var getSelection = __webpack_require__(15).get; + var setSelection = __webpack_require__(15).set; function IosStrategy(options) { BaseStrategy.call(this, options); } @@ -8226,8 +8531,8 @@ window.smartCard = function(modules) { }; }, function(module, exports, __webpack_require__) { "use strict"; - var parsePattern = __webpack_require__(78); - var isBackspace = __webpack_require__(47); + var parsePattern = __webpack_require__(79); + var isBackspace = __webpack_require__(48); function Formatter(pattern) { this.setPattern(pattern); } @@ -8353,7 +8658,7 @@ window.smartCard = function(modules) { }; }, function(module, exports, __webpack_require__) { "use strict"; - var AndroidChromeStrategy = __webpack_require__(48); + var AndroidChromeStrategy = __webpack_require__(49); function KitKatChromiumBasedWebViewStrategy(options) { AndroidChromeStrategy.call(this, options); } @@ -8371,10 +8676,10 @@ window.smartCard = function(modules) { module.exports = KitKatChromiumBasedWebViewStrategy; }, function(module, exports, __webpack_require__) { "use strict"; - var BaseStrategy = __webpack_require__(18); - var keyCannotMutateValue = __webpack_require__(19); - var getSelection = __webpack_require__(14).get; - var setSelection = __webpack_require__(14).set; + var BaseStrategy = __webpack_require__(19); + var keyCannotMutateValue = __webpack_require__(20); + var getSelection = __webpack_require__(15).get; + var setSelection = __webpack_require__(15).set; function IE9Strategy(options) { BaseStrategy.call(this, options); } @@ -8529,76 +8834,84 @@ window.smartCard = function(modules) { __e: null, __d: void 0, __c: null, - __h: null, constructor: void 0, - __v: null == r ? ++preact_module_u : r + __v: null == r ? ++preact_module_u : r, + __i: -1, + __u: 0 }; return null == r && null != l.vnode && l.vnode(f), f; } - function k(n) { + function g(n) { return n.children; } function b(n, l) { this.props = n, this.context = l; } - function g(n, l) { - if (null == l) return n.__ ? g(n.__, n.__.__k.indexOf(n) + 1) : null; + function m(n, l) { + if (null == l) return n.__ ? m(n.__, n.__i + 1) : null; for (var u; l < n.__k.length; l++) if (null != (u = n.__k[l]) && null != u.__e) return u.__e; - return "function" == typeof n.type ? g(n) : null; + return "function" == typeof n.type ? m(n) : null; } - function m(n) { + function k(n) { var l, u; if (null != (n = n.__) && null != n.__c) { for (n.__e = n.__c.base = null, l = 0; l < n.__k.length; l++) if (null != (u = n.__k[l]) && null != u.__e) { n.__e = n.__c.base = u.__e; break; } - return m(n); + return k(n); } } function w(n) { (!n.__d && (n.__d = !0) && preact_module_i.push(n) && !x.__r++ || preact_module_o !== l.debounceRendering) && ((preact_module_o = l.debounceRendering) || preact_module_r)(x); } function x() { - var n, l, u, t, o, r, e, c, s; - for (preact_module_i.sort(f); n = preact_module_i.shift(); ) n.__d && (l = preact_module_i.length, - t = void 0, o = void 0, r = void 0, c = (e = (u = n).__v).__e, (s = u.__P) && (t = [], - o = [], (r = v({}, e)).__v = e.__v + 1, L(s, e, r, u.__n, void 0 !== s.ownerSVGElement, null != e.__h ? [ c ] : null, t, null == c ? g(e) : c, e.__h, o), - M(t, e, o), e.__e != c && m(e)), preact_module_i.length > l && preact_module_i.sort(f)); + var n, u, t, o, r, e, c, s, a; + for (preact_module_i.sort(f); n = preact_module_i.shift(); ) n.__d && (u = preact_module_i.length, + o = void 0, e = (r = (t = n).__v).__e, s = [], a = [], (c = t.__P) && ((o = v({}, r)).__v = r.__v + 1, + l.vnode && l.vnode(o), L(c, o, r, t.__n, void 0 !== c.ownerSVGElement, 32 & r.__u ? [ e ] : null, s, null == e ? m(r) : e, !!(32 & r.__u), a), + o.__.__k[o.__i] = o, M(s, o, a), o.__e != e && k(o)), preact_module_i.length > u && preact_module_i.sort(f)); x.__r = 0; } - function P(n, l, u, t, i, o, r, f, e, a, v) { - var p, y, _, b, m, w, x, P, C, H = 0, I = t && t.__k || preact_module_s, T = I.length, j = T, z = l.length; - for (u.__k = [], p = 0; p < z; p++) null != (b = u.__k[p] = null == (b = l[p]) || "boolean" == typeof b || "function" == typeof b ? null : "string" == typeof b || "number" == typeof b || "bigint" == typeof b ? preact_module_d(null, b, null, null, b) : h(b) ? preact_module_d(k, { - children: b - }, null, null, null) : b.__b > 0 ? preact_module_d(b.type, b.props, b.key, b.ref ? b.ref : null, b.__v) : b) ? (b.__ = u, - b.__b = u.__b + 1, -1 === (P = A(b, I, x = p + H, j)) ? _ = c : (_ = I[P] || c, - I[P] = void 0, j--), L(n, b, _, i, o, r, f, e, a, v), m = b.__e, (y = b.ref) && _.ref != y && (_.ref && O(_.ref, null, b), - v.push(y, b.__c || m, b)), null != m && (null == w && (w = m), (C = _ === c || null === _.__v) ? -1 == P && H-- : P !== x && (P === x + 1 ? H++ : P > x ? j > z - x ? H += P - x : H-- : H = P < x && P == x - 1 ? P - x : 0), - x = p + H, "function" != typeof b.type || P === x && _.__k !== b.__k ? "function" == typeof b.type || P === x && !C ? void 0 !== b.__d ? (e = b.__d, - b.__d = void 0) : e = m.nextSibling : e = S(n, m, e) : e = $(b, e, n), "function" == typeof u.type && (u.__d = e))) : (_ = I[p]) && null == _.key && _.__e && (_.__e == e && (e = g(_)), - q(_, _, !1), I[p] = null); - for (u.__e = w, p = T; p--; ) null != I[p] && ("function" == typeof u.type && null != I[p].__e && I[p].__e == u.__d && (u.__d = I[p].__e.nextSibling), - q(I[p], I[p])); - } - function $(n, l, u) { - for (var t, i = n.__k, o = 0; i && o < i.length; o++) (t = i[o]) && (t.__ = n, l = "function" == typeof t.type ? $(t, l, u) : S(u, t.__e, l)); - return l; + function C(n, l, u, t, i, o, r, f, e, a, h) { + var v, p, y, d, _, g = t && t.__k || preact_module_s, b = l.length; + for (u.__d = e, P(u, l, g), e = u.__d, v = 0; v < b; v++) null != (y = u.__k[v]) && "boolean" != typeof y && "function" != typeof y && (p = -1 === y.__i ? c : g[y.__i] || c, + y.__i = v, L(n, y, p, i, o, r, f, e, a, h), d = y.__e, y.ref && p.ref != y.ref && (p.ref && z(p.ref, null, y), + h.push(y.ref, y.__c || d, y)), null == _ && null != d && (_ = d), 65536 & y.__u || p.__k === y.__k ? e = S(y, e, n) : "function" == typeof y.type && void 0 !== y.__d ? e = y.__d : d && (e = d.nextSibling), + y.__d = void 0, y.__u &= -196609); + u.__d = e, u.__e = _; + } + function P(n, l, u) { + var t, i, o, r, f, e = l.length, c = u.length, s = c, a = 0; + for (n.__k = [], t = 0; t < e; t++) null != (i = n.__k[t] = null == (i = l[t]) || "boolean" == typeof i || "function" == typeof i ? null : "string" == typeof i || "number" == typeof i || "bigint" == typeof i || i.constructor == String ? preact_module_d(null, i, null, null, i) : h(i) ? preact_module_d(g, { + children: i + }, null, null, null) : i.__b > 0 ? preact_module_d(i.type, i.props, i.key, i.ref ? i.ref : null, i.__v) : i) ? (i.__ = n, + i.__b = n.__b + 1, f = H(i, u, r = t + a, s), i.__i = f, o = null, -1 !== f && (s--, + (o = u[f]) && (o.__u |= 131072)), null == o || null === o.__v ? (-1 == f && a--, + "function" != typeof i.type && (i.__u |= 65536)) : f !== r && (f === r + 1 ? a++ : f > r ? s > e - r ? a += f - r : a-- : a = f < r && f == r - 1 ? f - r : 0, + f !== t + a && (i.__u |= 65536))) : (o = u[t]) && null == o.key && o.__e && (o.__e == n.__d && (n.__d = m(o)), + N(o, o, !1), u[t] = null, s--); + if (s) for (t = 0; t < c; t++) null != (o = u[t]) && 0 == (131072 & o.__u) && (o.__e == n.__d && (n.__d = m(o)), + N(o, o)); } function S(n, l, u) { - return null == u || u.parentNode !== n ? n.insertBefore(l, null) : l == u && null != l.parentNode || n.insertBefore(l, u), - l.nextSibling; + var t, i; + if ("function" == typeof n.type) { + for (t = n.__k, i = 0; t && i < t.length; i++) t[i] && (t[i].__ = n, l = S(t[i], l, u)); + return l; + } + return n.__e != l && (u.insertBefore(n.__e, l || null), l = n.__e), l && l.nextSibling; } - function A(n, l, u, t) { + function H(n, l, u, t) { var i = n.key, o = n.type, r = u - 1, f = u + 1, e = l[u]; if (null === e || e && i == e.key && o === e.type) return u; - if (t > (null != e ? 1 : 0)) for (;r >= 0 || f < l.length; ) { + if (t > (null != e && 0 == (131072 & e.__u) ? 1 : 0)) for (;r >= 0 || f < l.length; ) { if (r >= 0) { - if ((e = l[r]) && i == e.key && o === e.type) return r; + if ((e = l[r]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return r; r--; } if (f < l.length) { - if ((e = l[f]) && i == e.key && o === e.type) return f; + if ((e = l[f]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return f; f++; } } @@ -8614,65 +8927,70 @@ window.smartCard = function(modules) { if (u) for (l in u) t && u[l] === t[l] || I(n.style, l, u[l]); } else if ("o" === l[0] && "n" === l[1]) o = l !== (l = l.replace(/(PointerCapture)$|Capture$/, "$1")), l = l.toLowerCase() in n ? l.toLowerCase().slice(2) : l.slice(2), n.l || (n.l = {}), - n.l[l + o] = u, u ? t || n.addEventListener(l, o ? z : j, o) : n.removeEventListener(l, o ? z : j, o); else if ("dangerouslySetInnerHTML" !== l) { - if (i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" !== l && "height" !== l && "href" !== l && "list" !== l && "form" !== l && "tabIndex" !== l && "download" !== l && "rowSpan" !== l && "colSpan" !== l && l in n) try { + n.l[l + o] = u, u ? t ? u.u = t.u : (u.u = Date.now(), n.addEventListener(l, o ? D : A, o)) : n.removeEventListener(l, o ? D : A, o); else { + if (i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" !== l && "height" !== l && "href" !== l && "list" !== l && "form" !== l && "tabIndex" !== l && "download" !== l && "rowSpan" !== l && "colSpan" !== l && "role" !== l && l in n) try { n[l] = null == u ? "" : u; break n; } catch (n) {} "function" == typeof u || (null == u || !1 === u && "-" !== l[4] ? n.removeAttribute(l) : n.setAttribute(l, u)); } } - function j(n) { - return this.l[n.type + !1](l.event ? l.event(n) : n); + function A(n) { + var u = this.l[n.type + !1]; + if (n.t) { + if (n.t <= u.u) return; + } else n.t = Date.now(); + return u(l.event ? l.event(n) : n); } - function z(n) { + function D(n) { return this.l[n.type + !0](l.event ? l.event(n) : n); } function L(n, u, t, i, o, r, f, e, c, s) { - var a, p, y, d, _, g, m, w, x, $, C, S, A, H, I, T = u.type; + var a, p, y, d, _, m, k, w, x, P, S, $, H, I, T, A = u.type; if (void 0 !== u.constructor) return null; - null != t.__h && (c = t.__h, e = u.__e = t.__e, u.__h = null, r = [ e ]), (a = l.__b) && a(u); - n: if ("function" == typeof T) try { - if (w = u.props, x = (a = T.contextType) && i[a.__c], $ = a ? x ? x.props.value : a.__ : i, - t.__c ? m = (p = u.__c = t.__c).__ = p.__E : ("prototype" in T && T.prototype.render ? u.__c = p = new T(w, $) : (u.__c = p = new b(w, $), - p.constructor = T, p.render = B), x && x.sub(p), p.props = w, p.state || (p.state = {}), - p.context = $, p.__n = i, y = p.__d = !0, p.__h = [], p._sb = []), null == p.__s && (p.__s = p.state), - null != T.getDerivedStateFromProps && (p.__s == p.state && (p.__s = v({}, p.__s)), - v(p.__s, T.getDerivedStateFromProps(w, p.__s))), d = p.props, _ = p.state, p.__v = u, - y) null == T.getDerivedStateFromProps && null != p.componentWillMount && p.componentWillMount(), + 128 & t.__u && (c = !!(32 & t.__u), r = [ e = u.__e = t.__e ]), (a = l.__b) && a(u); + n: if ("function" == typeof A) try { + if (w = u.props, x = (a = A.contextType) && i[a.__c], P = a ? x ? x.props.value : a.__ : i, + t.__c ? k = (p = u.__c = t.__c).__ = p.__E : ("prototype" in A && A.prototype.render ? u.__c = p = new A(w, P) : (u.__c = p = new b(w, P), + p.constructor = A, p.render = O), x && x.sub(p), p.props = w, p.state || (p.state = {}), + p.context = P, p.__n = i, y = p.__d = !0, p.__h = [], p._sb = []), null == p.__s && (p.__s = p.state), + null != A.getDerivedStateFromProps && (p.__s == p.state && (p.__s = v({}, p.__s)), + v(p.__s, A.getDerivedStateFromProps(w, p.__s))), d = p.props, _ = p.state, p.__v = u, + y) null == A.getDerivedStateFromProps && null != p.componentWillMount && p.componentWillMount(), null != p.componentDidMount && p.__h.push(p.componentDidMount); else { - if (null == T.getDerivedStateFromProps && w !== d && null != p.componentWillReceiveProps && p.componentWillReceiveProps(w, $), - !p.__e && (null != p.shouldComponentUpdate && !1 === p.shouldComponentUpdate(w, p.__s, $) || u.__v === t.__v)) { + if (null == A.getDerivedStateFromProps && w !== d && null != p.componentWillReceiveProps && p.componentWillReceiveProps(w, P), + !p.__e && (null != p.shouldComponentUpdate && !1 === p.shouldComponentUpdate(w, p.__s, P) || u.__v === t.__v)) { for (u.__v !== t.__v && (p.props = w, p.state = p.__s, p.__d = !1), u.__e = t.__e, u.__k = t.__k, u.__k.forEach((function(n) { n && (n.__ = u); - })), C = 0; C < p._sb.length; C++) p.__h.push(p._sb[C]); + })), S = 0; S < p._sb.length; S++) p.__h.push(p._sb[S]); p._sb = [], p.__h.length && f.push(p); break n; } - null != p.componentWillUpdate && p.componentWillUpdate(w, p.__s, $), null != p.componentDidUpdate && p.__h.push((function() { - p.componentDidUpdate(d, _, g); + null != p.componentWillUpdate && p.componentWillUpdate(w, p.__s, P), null != p.componentDidUpdate && p.__h.push((function() { + p.componentDidUpdate(d, _, m); })); } - if (p.context = $, p.props = w, p.__P = n, p.__e = !1, S = l.__r, A = 0, "prototype" in T && T.prototype.render) { - for (p.state = p.__s, p.__d = !1, S && S(u), a = p.render(p.props, p.state, p.context), - H = 0; H < p._sb.length; H++) p.__h.push(p._sb[H]); + if (p.context = P, p.props = w, p.__P = n, p.__e = !1, $ = l.__r, H = 0, "prototype" in A && A.prototype.render) { + for (p.state = p.__s, p.__d = !1, $ && $(u), a = p.render(p.props, p.state, p.context), + I = 0; I < p._sb.length; I++) p.__h.push(p._sb[I]); p._sb = []; } else do { - p.__d = !1, S && S(u), a = p.render(p.props, p.state, p.context), p.state = p.__s; - } while (p.__d && ++A < 25); + p.__d = !1, $ && $(u), a = p.render(p.props, p.state, p.context), p.state = p.__s; + } while (p.__d && ++H < 25); p.state = p.__s, null != p.getChildContext && (i = v(v({}, i), p.getChildContext())), - y || null == p.getSnapshotBeforeUpdate || (g = p.getSnapshotBeforeUpdate(d, _)), - P(n, h(I = null != a && a.type === k && null == a.key ? a.props.children : a) ? I : [ I ], u, t, i, o, r, f, e, c, s), - p.base = u.__e, u.__h = null, p.__h.length && f.push(p), m && (p.__E = p.__ = null); + y || null == p.getSnapshotBeforeUpdate || (m = p.getSnapshotBeforeUpdate(d, _)), + C(n, h(T = null != a && a.type === g && null == a.key ? a.props.children : a) ? T : [ T ], u, t, i, o, r, f, e, c, s), + p.base = u.__e, u.__u &= -161, p.__h.length && f.push(p), k && (p.__E = p.__ = null); } catch (n) { - u.__v = null, (c || null != r) && (u.__e = e, u.__h = !!c, r[r.indexOf(e)] = null), - l.__e(n, u, t); - } else null == r && u.__v === t.__v ? (u.__k = t.__k, u.__e = t.__e) : u.__e = N(t.__e, u, t, i, o, r, f, c, s); + u.__v = null, c || null != r ? (u.__e = e, u.__u |= c ? 160 : 32, r[r.indexOf(e)] = null) : (u.__e = t.__e, + u.__k = t.__k), l.__e(n, u, t); + } else null == r && u.__v === t.__v ? (u.__k = t.__k, u.__e = t.__e) : u.__e = j(t.__e, u, t, i, o, r, f, c, s); (a = l.diffed) && a(u); } function M(n, u, t) { - for (var i = 0; i < t.length; i++) O(t[i], t[++i], t[++i]); + u.__d = void 0; + for (var i = 0; i < t.length; i++) z(t[i], t[++i], t[++i]); l.__c && l.__c(u, n), n.some((function(u) { try { n = u.__h, u.__h = [], n.some((function(n) { @@ -8683,44 +9001,40 @@ window.smartCard = function(modules) { } })); } - function N(l, u, t, i, o, r, f, e, s) { - var a, v, y, d = t.props, _ = u.props, k = u.type, b = 0; - if ("svg" === k && (o = !0), null != r) for (;b < r.length; b++) if ((a = r[b]) && "setAttribute" in a == !!k && (k ? a.localName === k : 3 === a.nodeType)) { - l = a, r[b] = null; + function j(l, u, t, i, o, r, f, e, s) { + var a, v, y, d, _, g, b, k = t.props, w = u.props, x = u.type; + if ("svg" === x && (o = !0), null != r) for (a = 0; a < r.length; a++) if ((_ = r[a]) && "setAttribute" in _ == !!x && (x ? _.localName === x : 3 === _.nodeType)) { + l = _, r[a] = null; break; } if (null == l) { - if (null === k) return document.createTextNode(_); - l = o ? document.createElementNS("http://www.w3.org/2000/svg", k) : document.createElement(k, _.is && _), + if (null === x) return document.createTextNode(w); + l = o ? document.createElementNS("http://www.w3.org/2000/svg", x) : document.createElement(x, w.is && w), r = null, e = !1; } - if (null === k) d === _ || e && l.data === _ || (l.data = _); else { - if (r = r && n.call(l.childNodes), v = (d = t.props || c).dangerouslySetInnerHTML, - y = _.dangerouslySetInnerHTML, !e) { - if (null != r) for (d = {}, b = 0; b < l.attributes.length; b++) d[l.attributes[b].name] = l.attributes[b].value; - (y || v) && (y && (v && y.__html == v.__html || y.__html === l.innerHTML) || (l.innerHTML = y && y.__html || "")); - } - if (function(n, l, u, t, i) { - var o; - for (o in u) "children" === o || "key" === o || o in l || T(n, o, null, u[o], t); - for (o in l) i && "function" != typeof l[o] || "children" === o || "key" === o || "value" === o || "checked" === o || u[o] === l[o] || T(n, o, l[o], u[o], t); - }(l, _, d, o, e), y) u.__k = []; else if (P(l, h(b = u.props.children) ? b : [ b ], u, t, i, o && "foreignObject" !== k, r, f, r ? r[0] : t.__k && g(t, 0), e, s), - null != r) for (b = r.length; b--; ) null != r[b] && p(r[b]); - e || ("value" in _ && void 0 !== (b = _.value) && (b !== l.value || "progress" === k && !b || "option" === k && b !== d.value) && T(l, "value", b, d.value, !1), - "checked" in _ && void 0 !== (b = _.checked) && b !== l.checked && T(l, "checked", b, d.checked, !1)); + if (null === x) k === w || e && l.data === w || (l.data = w); else { + if (r = r && n.call(l.childNodes), k = t.props || c, !e && null != r) for (k = {}, + a = 0; a < l.attributes.length; a++) k[(_ = l.attributes[a]).name] = _.value; + for (a in k) _ = k[a], "children" == a || ("dangerouslySetInnerHTML" == a ? y = _ : "key" === a || a in w || T(l, a, null, _, o)); + for (a in w) _ = w[a], "children" == a ? d = _ : "dangerouslySetInnerHTML" == a ? v = _ : "value" == a ? g = _ : "checked" == a ? b = _ : "key" === a || e && "function" != typeof _ || k[a] === _ || T(l, a, _, k[a], o); + if (v) e || y && (v.__html === y.__html || v.__html === l.innerHTML) || (l.innerHTML = v.__html), + u.__k = []; else if (y && (l.innerHTML = ""), C(l, h(d) ? d : [ d ], u, t, i, o && "foreignObject" !== x, r, f, r ? r[0] : t.__k && m(t, 0), e, s), + null != r) for (a = r.length; a--; ) null != r[a] && p(r[a]); + e || (a = "value", void 0 !== g && (g !== l[a] || "progress" === x && !g || "option" === x && g !== k[a]) && T(l, a, g, k[a], !1), + a = "checked", void 0 !== b && b !== l[a] && T(l, a, b, k[a], !1)); } return l; } - function O(n, u, t) { + function z(n, u, t) { try { "function" == typeof n ? n(u) : n.current = u; } catch (n) { l.__e(n, t); } } - function q(n, u, t) { + function N(n, u, t) { var i, o; - if (l.unmount && l.unmount(n), (i = n.ref) && (i.current && i.current !== n.__e || O(i, null, u)), + if (l.unmount && l.unmount(n), (i = n.ref) && (i.current && i.current !== n.__e || z(i, null, u)), null != (i = n.__c)) { if (i.componentWillUnmount) try { i.componentWillUnmount(); @@ -8729,10 +9043,10 @@ window.smartCard = function(modules) { } i.base = i.__P = null, n.__c = void 0; } - if (i = n.__k) for (o = 0; o < i.length; o++) i[o] && q(i[o], u, t || "function" != typeof n.type); + if (i = n.__k) for (o = 0; o < i.length; o++) i[o] && N(i[o], u, t || "function" != typeof n.type); t || null == n.__e || p(n.__e), n.__ = n.__e = n.__d = void 0; } - function B(n, l, u) { + function O(n, l, u) { return this.constructor(n, u); } n = preact_module_s.slice, l = { @@ -8753,7 +9067,7 @@ window.smartCard = function(modules) { w(this)); }, b.prototype.forceUpdate = function(n) { this.__v && (this.__e = !0, n && this.__h.push(n), w(this)); - }, b.prototype.render = k, preact_module_i = [], preact_module_r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, + }, b.prototype.render = g, preact_module_i = [], preact_module_r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f = function(n, l) { return n.__v.__b - l.__v.__b; }, x.__r = 0; @@ -8889,11 +9203,12 @@ window.smartCard = function(modules) { function hooks_module_B(n, t) { return "function" == typeof t ? t(n) : t; } + var src = __webpack_require__(3); var lib = __webpack_require__(2); var dist = __webpack_require__(12); var dist_default = __webpack_require__.n(dist); var constants = __webpack_require__(1); - var src = __webpack_require__(0); + var sdk_constants_src = __webpack_require__(0); var _CARD_FIELD_TYPE_TO_F, _VALIDATOR_TO_TYPE_MA; var types = dist_default.a.creditCardType.types; var CARD_FIELD_TYPE_TO_FRAME_NAME = ((_CARD_FIELD_TYPE_TO_F = {}).single = constants.h.CARD_FIELD, @@ -8940,11 +9255,11 @@ window.smartCard = function(modules) { }; var FILTER_CSS_VALUES = [ /;/, /[<>]/, /\\/, /@import/i, /expression/i, /javascript/i, /url/i ]; var FILTER_CSS_SELECTORS = [ /^\s*$/, /supports/i, /import/i, /[{}]/, />>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,t={};return Object.freeze(t),e.set(t,"__testvalue__"),"__testvalue__"===e.get(t)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var t=e.prototype;return t._cleanupClosedWindows=function(){for(var e=this.weakmap,t=this.keys,n=0;n=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var n=e&&e.stack,r=e&&e.message;if(n&&r)return-1!==n.indexOf(r)?n:r+"\n"+n;if(n)return n;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+k(e,t+1)}}function R(e){var t="";return e?e instanceof Error?e.message||t:"string"==typeof e.message&&e.message||t:t}function j(e,t){void 0===t&&(t=Boolean);var n={};for(var r in e)e.hasOwnProperty(r)&&t(e[r],r)&&(n[r]=e[r]);return n}function V(e,t){var n,r;return void 0===t&&(t=50),E((function(){r&&clearTimeout(r);var i=n=n||new l.a;return r=setTimeout((function(){n=null,r=null,l.a.try(e).then((function(e){i.resolve(e)}),(function(e){i.reject(e)}))}),t),i}),g(e)+"::promiseDebounced")}function x(e,t){var n;return function r(){n=setTimeout((function(){e(),r()}),t)}(),{cancel:function(){clearTimeout(n)}}}function L(e){var t=[],n={};return function(r){if(-1===t.indexOf(r)){t.push(r);var i=k(r);if(!n[i])return n[i]=!0,e(r)}}}C.clear=function(){A=S},C((function(e){if(Object.values)return Object.values(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}));var F=function(e){function t(t){var n;return(n=e.call(this,t)||this).name=n.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(n),n.constructor):n.stack=new Error(t).stack,n}return s(t,e),t}(y(Error));function M(){return Boolean(document.body)&&"complete"===document.readyState}function U(){return Boolean(document.body)&&"interactive"===document.readyState}var B,H=C((function(){return new l.a((function(e){if(M()||U())return e();var t=setInterval((function(){if(M()||U())return clearInterval(t),e()}),10)}))}));function z(e){return N(z,(function(){var t={};if(!e)return t;if(-1===e.indexOf("="))return t;for(var n=0,r=e.split("&");n1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function K(){return H().then((function(){var e=G();if(e){var t=e.timing;return t.connectEnd&&t.domInteractive?t.domInteractive-t.connectEnd:void 0}}))}function q(){return"undefined"!=typeof window&&void 0!==window.location}function $(){return N($,(function(){try{if("undefined"==typeof window)return!1;if(window.localStorage){var e=Math.random().toString();window.localStorage.setItem("__test__localStorage__",e);var t=window.localStorage.getItem("__test__localStorage__");if(window.localStorage.removeItem("__test__localStorage__"),e===t)return!0}}catch(e){}return!1}))}s((function(){return B.apply(this,arguments)||this}),B=F);var X="undefined"!=typeof document?document.currentScript:null,J=C((function(){if(X)return X;if(X=function(){try{var e=function(){try{throw new Error("_")}catch(e){return e.stack||""}}(),t=/.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(e),n=t&&t[1];if(!n)return;for(var r=0,i=[].slice.call(document.getElementsByTagName("script")).reverse();rr&&(n=null),n||(n={guid:b(),created:i}),t.__session__=n,e(n)}))}return{getState:o,getID:a,isStateFresh:function(){return a()===i},getSessionState:function(e){return u((function(t){return t.state=t.state||{},e(t.state)}))},getSessionID:function(){return u((function(e){return e.guid}))}}}),[{name:t,lifetime:r}])}function ee(){return Z({name:"belter_experiment"})}function te(e){return ee().getSessionState((function(t){return t.loggedBeacons=t.loggedBeacons||[],-1===t.loggedBeacons.indexOf(e)&&(t.loggedBeacons.push(e),!0)}))}function ne(e){return Math.floor(Math.random()*e)}function re(e){var t,n=e.name,r=e.sample,i=void 0===r?50:r,o=e.logTreatment,a=void 0===o?P:o,u=e.logCheckpoint,c=void 0===u?P:u,s=e.sticky,l=void 0===s||s?function(e){return ee().getState((function(t){return t.throttlePercentiles=t.throttlePercentiles||{},t.throttlePercentiles[e]=t.throttlePercentiles[e]||ne(100),t.throttlePercentiles[e]}))}(n):ne(100),d=n+"_"+(t=l=50||i<=l&&l<2*i?"control":"throttle"),f=!1,p=!1;try{window.localStorage&&window.localStorage.getItem(n)&&(p=!0)}catch(e){}var h={isEnabled:function(){return"test"===t||p},isDisabled:function(){return"test"!==t&&!p},getTreatment:function(){return d},log:function(e,t){return void 0===t&&(t={}),f?(te(d+"_"+JSON.stringify(t))&&a({name:n,treatment:d,payload:t,throttle:l}),te(d+"_"+e+"_"+JSON.stringify(t))&&c({name:n,treatment:d,checkpoint:e,payload:t,throttle:l}),h):h},logStart:function(e){return void 0===e&&(e={}),f=!0,h.log("start",e)},logComplete:function(e){return void 0===e&&(e={}),h.log("complete",e)}};return h}C((function(){var e;try{e=J()}catch(e){return Q}var t=e.getAttribute("data-uid");if(t&&"string"==typeof t)return t;if((t=e.getAttribute("data-uid-auto"))&&"string"==typeof t)return t;if(e.src){var n=function(e){for(var t="",n=0;n=300){var o,a=new Error(s+" returned status "+t+" (Corr ID: "+r[u.i.PAYPAL_DEBUG_ID]+").\n\n"+JSON.stringify(n));throw a.response={status:t,headers:r,body:n},t===u.q.TOO_MANY_REQUESTS&&Object(c.c)().track(((o={})[i.e.TRANSITION]=u.g.CALL_REST_API,o[u.e.ERR_DESC]="Error: "+t+" - "+n,o[u.e.INFO_MSG]="URL: "+s,o)),f&&Object(c.c)().warn("rest_api_"+f+"_status_"+t+"_error"),a}return n}))}function l(e){var t=e.accessToken,n=e.url,r=e.method,a=void 0===r?"get":r,s=e.headers,l=void 0===s?{}:s,d=e.json,f=e.authenticated,p=void 0===f||f,h=e.eventName;if(l[u.i.REQUESTED_BY]=u.p,p&&!t)throw new Error("Buyer access token not present - can not call smart api: "+n);return t&&(l[u.i.ACCESS_TOKEN]=t),Object(o.t)({url:n,method:a,headers:l,json:d}).then((function(e){var t,r=e.status,o=e.body,s=e.headers;if("contingency"===o.ack){var d=new Error(o.contingency);throw d.response={url:n,method:a,headers:l,body:o},d.data=o.data,Object(c.c)().warn("smart_api_"+h+"_contingency_error"),d}if(r===u.q.TOO_MANY_REQUESTS&&Object(c.c)().track(((t={})[i.e.TRANSITION]=u.g.CALL_REST_API,t[u.e.ERR_DESC]="Error: "+r+" - "+o,t[u.e.INFO_MSG]="URL: "+n,t)),r>400)throw Object(c.c)().warn("smart_api_"+h+"_status_"+r+"_error"),new Error("Api: "+n+" returned status code: "+r+" (Corr ID: "+s[u.i.PAYPAL_DEBUG_ID]+")\n\n"+JSON.stringify(o));if("success"!==o.ack)throw Object(c.c)().warn("smart_api_"+h+"_ack_error"),new Error("Api: "+n+" returned ack: "+o.ack+" (Corr ID: "+s[u.i.PAYPAL_DEBUG_ID]+")\n\n"+JSON.stringify(o));return{data:o.data,headers:s}}))}function d(e){var t=e.name,n=e.query,i=e.variables,s=void 0===i?{}:i,l=e.headers,d=void 0===l?{}:l,f=e.returnErrorObject,p=void 0!==f&&f;return Object(o.t)({url:a.e+"?"+t,method:"POST",json:{query:n,variables:s},headers:Object(r.a)({"x-app-name":u.p},d)}).then((function(e){var n=e.status,r=e.body,i=r.errors||[];if(i.length){var o=i[0].message||JSON.stringify(i[0]);if(Object(c.c)().warn("graphql_"+t+"_error",{err:o}),p)throw i[0];throw new Error(o)}if(200!==n)throw Object(c.c)().warn("graphql_"+t+"_status_"+n+"_error"),new Error(a.e+" returned status "+n+"\n\n"+JSON.stringify(r));return r.data}))}function f(e){return e.headers[u.i.PAYPAL_DEBUG_ID]}function p(e){var t=null==e?void 0:e.response;if(t)return f(t)}},function(e,t,n){"use strict";n.d(t,"f",(function(){return o})),n.d(t,"a",(function(){return a})),n.d(t,"g",(function(){return u})),n.d(t,"h",(function(){return c})),n.d(t,"b",(function(){return s})),n.d(t,"j",(function(){return l})),n.d(t,"k",(function(){return d})),n.d(t,"i",(function(){return f})),n.d(t,"e",(function(){return p})),n.d(t,"d",(function(){return h})),n.d(t,"c",(function(){return _}));var r,i=n(0),o="/xoplatform/logger/api/logger",a="/v1/oauth2/token",u="/v2/checkout/orders",c="/v1/payments/payment",s="/v1/billing/subscriptions",l="validate-payment-method",d="/v3/vault/setup-tokens",f={AUTH:"/smart/api/auth",CHECKOUT:"/smart/api/checkout",ORDER:"/smart/api/order",PAYMENT:"/smart/api/payment",SUBSCRIPTION:"/smart/api/billagmt/subscriptions",VAULT:"/smart/api/vault"},p="/graphql",h=((r={})[i.g.PAYPAL]=i.g.PAYPAL,r[i.g.PAYLATER]=i.g.PAYPAL,r[i.g.CREDIT]=i.g.PAYPAL,{APP:"https://www.paypalobjects.com/checkout/js/lib/firebase-app.js",AUTH:"https://www.paypalobjects.com/checkout/js/lib/firebase-auth.js",DATABASE:"https://www.paypalobjects.com/checkout/js/lib/firebase-database.js"}),_=!1},function(e,t,n){"use strict";n.d(t,"f",(function(){return l})),n.d(t,"w",(function(){return _})),n.d(t,"g",(function(){return m})),n.d(t,"k",(function(){return g})),n.d(t,"p",(function(){return E})),n.d(t,"q",(function(){return w})),n.d(t,"d",(function(){return b})),n.d(t,"b",(function(){return T})),n.d(t,"r",(function(){return O})),n.d(t,"t",(function(){return I})),n.d(t,"e",(function(){return S})),n.d(t,"c",(function(){return A})),n.d(t,"v",(function(){return C})),n.d(t,"o",(function(){return N})),n.d(t,"m",(function(){return P})),n.d(t,"h",(function(){return D})),n.d(t,"l",(function(){return k})),n.d(t,"j",(function(){return R})),n.d(t,"s",(function(){return j})),n.d(t,"i",(function(){return x})),n.d(t,"u",(function(){return F})),n.d(t,"a",(function(){return M})),n.d(t,"n",(function(){return U}));var r=n(4),i=n(3),o=n(0),a=n(7),u=n(2),c=n(1),s=n(6);function l(e,t){var n=(void 0===t?{}:t).targetSubject;return Object(i.i)(l,(function(){Object(u.c)().info("rest_api_create_access_token");var t=Object(i.a)((e||"")+":"),r={grant_type:"client_credentials"};return n&&(r.target_subject=n),Object(i.t)({method:"post",url:a.a,headers:{Authorization:"Basic "+t},data:r}).then((function(t){var n=t.body;if(n&&"invalid_client"===n.error)throw Object(u.c)().warn("rest_api_v1_oauth2_token_create_error",{err:"invalid client id"}),new Error("Auth Api invalid client id: "+(e||"")+":\n\n"+JSON.stringify(n,null,4));if(!n||!n.access_token)throw Object(u.c)().warn("rest_api_v1_oauth2_token_create_error"),new Error("Auth Api response error:\n\n"+JSON.stringify(n,null,4));return n.access_token}))}),[e,n])}var d,f=!1,p=function(){return f},h=function(){return d};function _(e,t){var n,r=t.buyerAccessToken,o=t.orderID;return f=!1,d=null,f=!0,Object(s.a)({name:"UpgradeFacilitatorAccessToken",headers:(n={},n[c.i.ACCESS_TOKEN]=r,n[c.i.CLIENT_CONTEXT]=o,n),query:"\n mutation UpgradeFacilitatorAccessToken(\n $orderID: String!\n $buyerAccessToken: String!\n $facilitatorAccessToken: String!\n ) {\n upgradeLowScopeAccessToken(\n token: $orderID\n buyerAccessToken: $buyerAccessToken\n merchantLSAT: $facilitatorAccessToken\n )\n }\n ",variables:{facilitatorAccessToken:e,buyerAccessToken:r,orderID:o}}).then(i.p).catch((function(e){throw function(e){d=e}(e),e}))}var v=n(5);function m(e,t){var n,r=t.facilitatorAccessToken,i=t.partnerAttributionID;return Object(u.c)().info("rest_api_create_order_id"),Object(s.b)({accessToken:r,method:"post",url:""+a.g,eventName:"v2_checkout_orders_create",data:e,headers:(n={},n[c.i.PARTNER_ATTRIBUTION_ID]=i||"",n[c.i.PREFER]=c.m.REPRESENTATION,n)}).then((function(e){var t,n=e&&e.id;if(!n)throw new Error("Order Api response error:\n\n"+JSON.stringify(e,null,4));return Object(u.c)().track(((t={})[o.e.TRANSITION]=c.g.CREATE_ORDER,t[o.e.CONTEXT_TYPE]=c.d.ORDER_ID,t[o.e.TOKEN]=n,t[o.e.CONTEXT_ID]=n,t)),n}))}function y(e){var t;return Boolean(null==e||null==(t=e.response)||null==(t=t.body)||null==(t=t.details)?void 0:t.some((function(e){return e.issue===c.k.INVALID_RESOURCE_ID})))}function g(e,t){var n,r,o=t.facilitatorAccessToken,l=t.buyerAccessToken,d=t.partnerAttributionID,f=t.forceRestAPI,_=void 0!==f&&f;return Object(u.c)().info("get_order_lsat_upgrade_"+(p()?"called":"not_called")),Object(u.c)().info("get_order_lsat_upgrade_"+(h()?"errored":"did_not_error"),{err:Object(i.v)(h())}),_&&!h()?Object(s.b)({accessToken:o,url:a.g+"/"+e,eventName:"v2_checkout_orders_get",headers:(r={},r[c.i.PARTNER_ATTRIBUTION_ID]=d||"",r[c.i.PREFER]=c.m.REPRESENTATION,r)}).catch((function(t){var n,r=Object(s.d)(t);return Object(u.c)().warn("get_order_call_rest_api_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),y(t)&&Object(u.c)().warn("get_order_invalid_resource_id_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),Object(s.c)({accessToken:l,url:a.i.ORDER+"/"+e,eventName:"order_get",headers:(n={},n[c.i.CLIENT_CONTEXT]=e,n)}).then((function(t){var n=Object(s.e)(t);return Object(u.c)().info("get_order_smart_fallback_success",{smartCorrID:n,restCorrID:r,orderID:e}),t.data})).catch((function(n){var o=Object(s.d)(t);throw Object(u.c)().error("get_order_smart_fallback_error",{smartCorrID:o,restCorrID:r,orderID:e,err:Object(i.v)(n)}),n}))})):Object(s.c)({accessToken:l,url:a.i.ORDER+"/"+e,eventName:"order_get",headers:(n={},n[c.i.CLIENT_CONTEXT]=e,n)}).then((function(e){return e.data}))}function E(e){var t,n,r,i=null!=e&&null!=(t=e.response)&&null!=(t=t.body)&&null!=(t=t.data)&&t.details?null==e||null==(n=e.response)||null==(n=n.body)||null==(n=n.data)?void 0:n.details:null==e||null==(r=e.response)||null==(r=r.body)?void 0:r.details;return Boolean(null==i?void 0:i.some((function(e){return e.issue===c.k.INSTRUMENT_DECLINED||e.issue===c.k.PAYER_ACTION_REQUIRED})))}function w(e){var t;return Boolean(null==e||null==(t=e.response)||null==(t=t.body)||null==(t=t.details)?void 0:t.some((function(e){return e.issue===c.k.DUPLICATE_INVOICE_ID})))}function b(e,t){var n,r,o=t.facilitatorAccessToken,l=t.buyerAccessToken,d=t.partnerAttributionID,f=t.forceRestAPI,_=void 0!==f&&f;return Object(u.c)().info("capture_order_lsat_upgrade_"+(p()?"called":"not_called")),Object(u.c)().info("capture_order_lsat_upgrade_"+(h()?"errored":"did_not_error"),{err:Object(i.v)(h())}),_&&!h()?Object(s.b)({accessToken:o,method:"post",eventName:"v2_checkout_orders_capture",url:a.g+"/"+e+"/capture",headers:(r={},r[c.i.PARTNER_ATTRIBUTION_ID]=d||"",r[c.i.PREFER]=c.m.REPRESENTATION,r[c.i.PAYPAL_REQUEST_ID]=e,r)}).catch((function(t){var n,r=Object(s.d)(t);if(Object(u.c)().warn("capture_order_call_rest_api_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),y(t)&&Object(u.c)().warn("capture_order_invalid_resource_id_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),E(t)||w(t))throw t;return Object(s.c)({accessToken:l,method:"post",eventName:"order_capture",url:a.i.ORDER+"/"+e+"/capture",json:{data:{facilitatorAccessToken:o}},headers:(n={},n[c.i.CLIENT_CONTEXT]=e,n)}).then((function(t){var n=Object(s.e)(t);return Object(u.c)().info("capture_order_smart_fallback_success",{smartCorrID:n,restCorrID:r,orderID:e}),t.data})).catch((function(n){var o=Object(s.d)(t);throw Object(u.c)().info("capture_order_smart_fallback_error",{smartCorrID:o,restCorrID:r,orderID:e,err:Object(i.v)(n)}),n}))})):Object(s.c)({accessToken:l,method:"post",eventName:"order_capture",url:a.i.ORDER+"/"+e+"/capture",json:{data:{facilitatorAccessToken:o}},headers:(n={},n[c.i.CLIENT_CONTEXT]=e,n)}).then((function(e){return e.data}))}function T(e,t){var n,r,o=t.facilitatorAccessToken,l=t.buyerAccessToken,d=t.partnerAttributionID,f=t.forceRestAPI,_=void 0!==f&&f;return Object(u.c)().info("authorize_order_lsat_upgrade_"+(p()?"called":"not_called")),Object(u.c)().info("authorize_order_lsat_upgrade_"+(h()?"errored":"did_not_error"),{err:Object(i.v)(h())}),_&&!h()?Object(s.b)({accessToken:o,method:"post",eventName:"v2_checkout_orders_authorize",url:a.g+"/"+e+"/authorize",headers:(r={},r[c.i.PARTNER_ATTRIBUTION_ID]=d||"",r[c.i.PREFER]=c.m.REPRESENTATION,r)}).catch((function(t){var n,r=Object(s.d)(t);if(Object(u.c)().warn("authorize_order_call_rest_api_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),y(t)&&Object(u.c)().warn("authorize_order_invalid_resource_id_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),E(t))throw t;return Object(s.c)({accessToken:l,method:"post",eventName:"order_authorize",url:a.i.ORDER+"/"+e+"/authorize",json:{data:{facilitatorAccessToken:o}},headers:(n={},n[c.i.CLIENT_CONTEXT]=e,n)}).then((function(t){var n=Object(s.e)(t);return Object(u.c)().info("authorize_order_smart_fallback_success",{smartCorrID:n,restCorrID:r,orderID:e}),t.data})).catch((function(n){var o=Object(s.d)(t);throw Object(u.c)().info("authorize_order_smart_fallback_error",{smartCorrID:o,restCorrID:r,orderID:e,err:Object(i.v)(n)}),n}))})):(Object(u.c)().info("lsat_upgrade_false"),Object(s.c)({accessToken:l,method:"post",eventName:"order_authorize",url:a.i.ORDER+"/"+e+"/authorize",json:{data:{facilitatorAccessToken:o}},headers:(n={},n[c.i.CLIENT_CONTEXT]=e,n)}).then((function(e){return e.data})))}function O(e,t,n){var r,o,l,d=n.facilitatorAccessToken,f=n.buyerAccessToken,_=n.partnerAttributionID,m=n.forceRestAPI,g=void 0!==m&&m;return Object(u.c)().info("patch_order_lsat_upgrade_"+(p()?"called":"not_called")),Object(u.c)().info("patch_order_lsat_upgrade_"+(h()?"errored":"did_not_error"),{err:Object(i.v)(h())}),g&&!h()?Object(s.b)({accessToken:d,method:"PATCH",eventName:"v2_checkout_orders_patch",url:a.g+"/"+e,data:t,headers:(o={},o[c.i.PARTNER_ATTRIBUTION_ID]=_||"",o[c.i.PREFER]=c.m.REPRESENTATION,o)}).catch((function(n){var r,o,l=Object(s.d)(n);return Object(u.c)().warn("patch_order_call_rest_api_error",{restCorrID:l,orderID:e,err:Object(i.v)(n)}),y(n)&&Object(u.c)().warn("patch_order_invalid_resource_id_error",{restCorrID:l,orderID:e,err:Object(i.v)(n)}),o=Array.isArray(t)?{patch:t,facilitatorAccessToken:d}:Object(v.a)({},t,{facilitatorAccessToken:d}),Object(s.c)({accessToken:f,method:"post",eventName:"order_patch",url:a.i.ORDER+"/"+e+"/patch",json:{data:o},headers:(r={},r[c.i.CLIENT_CONTEXT]=e,r)}).then((function(t){var n=Object(s.e)(t);return Object(u.c)().info("patch_order_smart_fallback_success",{smartCorrID:n,restCorrID:l,orderID:e}),t.data})).catch((function(t){var r=Object(s.d)(n);throw Object(u.c)().info("patch_order_smart_fallback_error",{smartCorrID:r,restCorrID:l,orderID:e,err:Object(i.v)(t)}),t}))})):(Object(u.c)().info("lsat_upgrade_false"),l=Array.isArray(t)?{patch:t,facilitatorAccessToken:d}:Object(v.a)({},t,{facilitatorAccessToken:d}),Object(s.c)({accessToken:f,method:"post",eventName:"order_patch",url:a.i.ORDER+"/"+e+"/patch",json:{data:l},headers:(r={},r[c.i.CLIENT_CONTEXT]=e,r)}).then((function(e){return e.data})))}function I(e){var t=e.clientID,n=e.orderID,r=e.data;return Object(s.a)({name:"UpdateShipping",query:"\n mutation UpdateShipping(\n $clientID: String!\n $patch: [JSON]!\n $token: String!\n ) {\n updateShipping(\n clientID: $clientID,\n patch: $patch,\n token: $token,\n )\n }\n ",variables:{clientID:t,patch:r,token:n}})}function S(e,t,n){var r,i=n.facilitatorAccessToken,o=n.partnerAttributionID;return Object(s.b)({accessToken:i,method:"post",eventName:"order_confirm_payment_source",url:a.g+"/"+e+"/confirm-payment-source",data:t,headers:(r={},r[c.i.PARTNER_ATTRIBUTION_ID]=o||"",r[c.i.PREFER]=c.m.REPRESENTATION,r)})}function A(e){return Object(s.c)({authenticated:!1,method:"post",eventName:"payment_ectoken",url:a.i.PAYMENT+"/"+e+"/ectoken"}).then((function(e){return e.data.token}))}function C(e){return Object(s.c)({authenticated:!1,method:"post",eventName:"billagmt_subscriptions_cartid",url:a.i.SUBSCRIPTION+"/"+e+"/cartid"}).then((function(e){return e.data.token}))}var N=Object(i.o)((function(e){var t;return Object(s.a)({name:"GetCheckoutDetails",query:"\n query GetCheckoutDetails($orderID: String!) {\n checkoutSession(token: $orderID) {\n cart {\n billingType\n intent\n paymentId\n billingToken\n amounts {\n total {\n currencyValue\n currencyCode\n currencyFormatSymbolISOCurrency\n }\n }\n supplementary {\n initiationIntent\n }\n category\n }\n flags {\n isChangeShippingAddressAllowed\n }\n payees {\n merchantId\n email {\n stringValue\n }\n }\n }\n }\n ",variables:{orderID:e},headers:(t={},t[c.i.CLIENT_CONTEXT]=e,t)})})),P=function(e){var t;return Object(s.a)({name:"GetCheckoutDetails",query:"\n query GetCheckoutDetails($orderID: String!) {\n checkoutSession(token: $orderID) {\n cart {\n billingType\n intent\n paymentId\n billingToken\n amounts {\n total {\n currencyValue\n currencyCode\n currencyFormatSymbolISOCurrency\n }\n }\n supplementary {\n initiationIntent\n }\n category\n shippingAddress {\n firstName\n lastName\n line1\n line2\n city\n state\n postalCode\n country\n }\n shippingMethods {\n id\n amount {\n currencyCode\n currencyValue\n }\n label\n selected\n type\n }\n }\n flags {\n isChangeShippingAddressAllowed\n }\n payees {\n merchantId\n email {\n stringValue\n }\n }\n }\n }\n ",variables:{orderID:e},headers:(t={},t[c.i.CLIENT_CONTEXT]=e,t)})};function D(e,t){return function(e,t){var n,r=t.facilitatorAccessToken,i=t.partnerAttributionID;return Object(u.c)().info("rest_api_create_payment_id"),Object(s.b)({accessToken:r,method:"post",eventName:"v1_payments_payment_create",url:""+a.h,data:e,headers:(n={},n[c.i.PARTNER_ATTRIBUTION_ID]=i||"",n)}).then((function(e){var t,n=e&&e.id;if(!n)throw new Error("Payment Api response error:\n\n"+JSON.stringify(e,null,4));return Object(u.c)().track(((t={})[o.e.TRANSITION]=c.g.CREATE_PAYMENT,t[o.e.CONTEXT_TYPE]=c.d.PAYMENT_ID,t[o.e.TOKEN]=n,t[o.e.CONTEXT_ID]=n,t)),e}))}(e,{facilitatorAccessToken:t.facilitatorAccessToken,partnerAttributionID:t.partnerAttributionID}).then((function(e){if(e.links&&e.links.length)for(var t=0;tu.indexOf(d))){var r=[t];r.push(n),(n.error||n.warning)&&r.push("\n\n",n.error||n.warning);try{window.console[e]&&window.console[e].apply?window.console[e].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(e){}}}function S(){return i.a.try((function(){if(Object(o.k)()&&"file:"!==window.location.protocol&&(y.length||g.length||E.length)){for(var e={},n=0;n=0||(i[n]=e[n]);return i}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";var r=n(19),i=n(14).get,o=n(14).set,a=n(47),u=n(76),c=n(77);function s(e){this.isFormatted=!1,this.inputElement=e.element,this.formatter=new c(e.pattern),this._attachListeners()}function l(e){return!e.key&&!e.keyCode}s.prototype.getUnformattedValue=function(e){var t=this.inputElement.value;return(e||this.isFormatted)&&(t=this.formatter.unformat({value:this.inputElement.value,selection:{start:0,end:0}}).value),t},s.prototype.setPattern=function(e){this._unformatInput(),this.formatter=new c(e),this._reformatInput()},s.prototype._attachListeners=function(){var e=this;e.inputElement.addEventListener("keydown",(function(t){l(t)&&(e.isFormatted=!1),r(t)||e._isDeletion(t)&&e._unformatInput(t)})),e.inputElement.addEventListener("keypress",(function(t){l(t)&&(e.isFormatted=!1),r(t)||e._unformatInput(t)})),e.inputElement.addEventListener("keyup",(function(t){e._reformatInput(t)})),e.inputElement.addEventListener("input",(function(t){(t instanceof CustomEvent||!t.isTrusted)&&(e.isFormatted=!1),e._reformatInput(t)})),e.inputElement.addEventListener("paste",this._pasteEventHandler.bind(this))},s.prototype._isDeletion=function(e){return u(e)||a(e)},s.prototype._reformatInput=function(){var e,t;this.isFormatted||(this.isFormatted=!0,t=this.formatter.format({selection:i(e=this.inputElement),value:e.value}),e.value=t.value,o(e,t.selection.start,t.selection.end),this._afterReformatInput(t))},s.prototype._afterReformatInput=function(){},s.prototype._unformatInput=function(){var e,t,n;this.isFormatted&&(this.isFormatted=!1,n=i(e=this.inputElement),t=this.formatter.unformat({selection:n,value:e.value}),e.value=t.value,o(e,t.selection.start,t.selection.end))},s.prototype._prePasteEventHandler=function(e){e.preventDefault()},s.prototype._postPasteEventHandler=function(){this._reformatAfterPaste()},s.prototype._pasteEventHandler=function(e){var t,n,r="";this._prePasteEventHandler(e),this._unformatInput(),e.clipboardData?r=e.clipboardData.getData("Text"):window.clipboardData&&(r=window.clipboardData.getData("Text")),t=i(this.inputElement),(n=this.inputElement.value.split("")).splice(t.start,t.end-t.start,r),n=n.join(""),this.inputElement.value=n,o(this.inputElement,t.start+r.length,t.start+r.length),this._postPasteEventHandler()},s.prototype._reformatAfterPaste=function(){var e=document.createEvent("Event");this._reformatInput(),e.initEvent("input",!0,!0),this.inputElement.dispatchEvent(e)},s.prototype._getStateToFormat=function(){var e=this.inputElement,t=i(e),n={selection:t,value:e.value};return this._stateToFormat?(n=this._stateToFormat,delete this._stateToFormat):t.start===e.value.length&&(n=this.formatter.unformat(n)),n},e.exports=s},function(e,t,n){"use strict";var r=n(14).get;e.exports=function(e){var t=e.currentTarget||e.srcElement,n=r(t),i=0===n.start,o=n.start===t.value.length,a=!0===e.shiftKey;switch(e.key){case void 0:case"Unidentified":case"":break;case"Backspace":return i;case"Del":case"Delete":return o;default:return 1!==e.key.length}switch(e.keyCode){case 9:case 19:case 20:case 27:case 39:case 45:return!0;case 33:case 34:case 35:case 36:case 37:case 38:case 40:return!a;case 8:return i;case 46:return o;default:return!1}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(4);function i(e){var t=e.onInit;return function(e){var n=!0;return{initPromise:r.a.try((function(){if(t)return t(e,(i=function(e){n=e},{enable:function(){return r.a.try((function(){return i(!0)}))},disable:function(){return r.a.try((function(){return i(!1)}))}}));var i})),isEnabled:function(){return n}}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(4),i=(n(0),n(3));function o(e){var t=e.onClick;if(t)return Object(i.o)((function(e){var n;return t((n={fundingSource:e.fundingSource},{fundingSource:n.fundingSource}),{resolve:function(){return r.a.try((function(){return!0}))},reject:function(){return r.a.try((function(){return!1}))}}).then((function(e){return!1!==e}))}))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(4),i=n(3);function o(e){var t=e.onError,n=t?Object(i.b)(t):i.p;return function(e){return r.a.try((function(){return n(e)}))}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return a})),n(4);var r=n(7),i=n(6),o=function(e){var t=e.clientID,n=e.vaultSetupToken,r=e.paymentSource;return Object(i.a)({name:"UpdateVaultSetupToken",query:"\n mutation UpdateVaultSetupToken(\n $clientID: String!\n $vaultSetupToken: String!\n $paymentSource: PaymentSource\n ) {\n updateVaultSetupToken(\n clientId: $clientID\n vaultSetupToken: $vaultSetupToken\n paymentSource: $paymentSource\n ) {\n id,\n status,\n links {\n rel, href\n }\n }\n }",variables:{clientID:t,vaultSetupToken:n,paymentSource:r}})};function a(e){return Object(i.c)({authenticated:!1,method:"post",eventName:"vault_ectoken",url:r.i.VAULT+"/"+e+"/ectoken"}).then((function(e){return e.data.token}))}},function(e,t,n){"use strict";function r(e){if(null==e)throw new TypeError("Cannot destructure undefined")}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(e,t,n){return{isValid:e,isPotentiallyValid:t,isCurrentYear:n||!1}}Object.defineProperty(t,"__esModule",{value:!0}),t.expirationYear=void 0,t.expirationYear=function(e,t){var n;if(void 0===t&&(t=19),"string"!=typeof e)return r(!1,!1);if(""===e.replace(/\s/g,""))return r(!1,!0);if(!/^\d*$/.test(e))return r(!1,!1);var i=e.length;if(i<2)return r(!1,!0);var o=(new Date).getFullYear();if(3===i)return r(!1,e.slice(0,2)===String(o).slice(0,2));if(i>4)return r(!1,!1);var a=parseInt(e,10),u=Number(String(o).substr(2,2)),c=!1;if(2===i){if(String(o).substr(0,2)===e)return r(!1,!0);n=u===a,c=a>=u&&a<=u+t}else 4===i&&(n=o===a,c=a>=o&&a<=o+t);return r(c,c,n)}},function(e,t,n){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&n<13;return r(i,i,i&&n>=t)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return c})),n(0);var r=n(4),i=n(2),o=n(20),a=n(21),u=n(22);function c(e){var t=e.branded,n=e.enableOrdersApprovalSmartWallet,c=e.smartWalletOrderID,s=window.xprops,l=s.uid,d=s.env,f=s.vault,p=void 0!==f&&f,h=s.commit,_=s.locale,v=s.platform,m=s.sessionID,y=s.clientID,g=s.partnerAttributionID,E=s.merchantRequestedPopupsDisabled,w=s.clientMetadataID,b=s.sdkCorrelationID,T=s.getParentDomain,O=s.clientAccessToken,I=s.getPopupBridge,S=s.getPrerenderDetails,A=s.getPageUrl,C=s.enableThreeDomainSecure,N=s.enableVaultInstallments,P=s.enableNativeCheckout,D=void 0!==P&&P,k=s.remember,R=s.stageHost,j=s.apiStageHost,V=s.getParent,x=s.fundingSource,L=s.currency,F=s.connect,M=s.intent,U=s.merchantID,B=s.amount,H=s.userIDToken,z=s.enableFunding,W=s.disableFunding,Y=s.disableCard,G=s.disableAutocomplete,K=s.wallet,q=s.paymentMethodToken,$=void 0===q?s.paymentMethodNonce:q,X=s.getQueriedEligibleFunding,J=void 0===X?function(){return r.a.resolve([])}:X,Q=s.storageID,Z=s.applePay,ee=s.userExperienceFlow,te=s.allowBillingPayments,ne=s.paymentRequest,re=s.disableSetCookie,ie=void 0!==re&&re,oe=Object(o.a)({onInit:s.onInit}),ae="function"==typeof T?T():"unknown";z=z||[],W=W||[];var ue=Object(a.a)({onClick:s.onClick}),ce=Q&&Object(i.g)()?Q:Object(i.e)();return{uid:l,env:d,vault:p,commit:h,clientAccessToken:O,locale:_,sessionID:m,clientID:y,partnerAttributionID:g,clientMetadataID:w,sdkCorrelationID:b,merchantDomain:ae,platform:v,currency:L,intent:M,wallet:K,merchantRequestedPopupsDisabled:E,getPopupBridge:I,getPrerenderDetails:S,getPageUrl:A,rememberFunding:k,getParent:V,connect:F,fundingSource:x,enableFunding:z,disableFunding:W,disableCard:Y,disableAutocomplete:G,getQueriedEligibleFunding:J,amount:B,userIDToken:H,enableThreeDomainSecure:C,enableNativeCheckout:D,enableVaultInstallments:N,onClick:ue,onInit:oe,onError:Object(u.a)({onError:s.onError}),stageHost:R,apiStageHost:j,standaloneFundingSource:x,paymentMethodToken:$,branded:t,stickinessID:ce,applePay:Z,userExperienceFlow:ee,allowBillingPayments:te,paymentRequest:ne,merchantID:U,enableOrdersApprovalSmartWallet:n,smartWalletOrderID:c,disableSetCookie:ie}}},function(e,t,n){"use strict";n(5),n(4),n(3),n(0),n(10),n(8),n(1),n(2),n(7),n(23)},function(e,t,n){"use strict";n(4),n(3),n(0),n(8),n(1),n(2)},function(e,t,n){"use strict";n(0)},function(e,t,n){"use strict";n(0),n(8),n(2)},function(e,t,n){"use strict";n(3),n(4),n(0)},function(e,t,n){"use strict";n(5),n(4),n(3),n(0),n(8),n(1),n(2),n(7)},function(e,t,n){"use strict";n(4),n(3),n(0),n(2),n(1),n(8)},function(e,t,n){"use strict";n(3),n(4),n(0),n(2),n(1)},function(e,t,n){"use strict";n(24),n(5),n(17),n(4),n(0),n(8),n(1),n(2),n(9),n(11)},function(e,t,n){"use strict";n(24),n(5),n(17),n(4),n(0),n(8),n(1),n(2),n(9),n(11)},function(e,t,n){"use strict";n(4)},function(e,t,n){"use strict";n(4),n(0)},function(e,t,n){"use strict";n(4)},function(e,t,n){"use strict";n(4),n(3),n(8),n(2)},function(e,t,n){"use strict";n(4),n(0)},function(e,t){},function(e,t,n){"use strict";var r=window.navigator&&window.navigator.userAgent,i=n(66),o=n(67),a=n(70),u=n(71),c=/Version\/\d\.\d* Chrome\/\d*\.0\.0\.0/;e.exports={isIE9:u,isAndroidChrome:function(e){var t=e||r;return i(t)&&o(t)},isIos:a,isKitKatWebview:function(e){var t=e||r;return i(t)&&c.test(t)},isSamsungBrowser:function(e){return/SamsungBrowser/.test(e=e||r)||function(e){return!o(e)&&e.indexOf("Samsung")>-1}(e)}}},function(e,t,n){"use strict";e.exports=function(e){return"Backspace"===e.key||8===e.keyCode}},function(e,t,n){"use strict";var r=n(19),i=n(18),o=n(14).set;function a(e){i.call(this,e)}(a.prototype=Object.create(i.prototype)).constructor=a,a.prototype._attachListeners=function(){var e=this;e.inputElement.addEventListener("keydown",(function(t){r(t)||e._unformatInput(t)})),e.inputElement.addEventListener("keypress",(function(t){r(t)||e._unformatInput(t)})),e.inputElement.addEventListener("keyup",(function(t){e._reformatInput(t)})),e.inputElement.addEventListener("input",(function(t){e._reformatInput(t)})),e.inputElement.addEventListener("paste",this._pasteEventHandler.bind(this))},a.prototype._prePasteEventHandler=function(){},a.prototype._postPasteEventHandler=function(){setTimeout(this._reformatAfterPaste.bind(this),0)},a.prototype._afterReformatInput=function(e){var t=this.inputElement;setTimeout((function(){var n=e.selection;o(t,n.end,n.end)}),0)},e.exports=a},function(e,t,n){"use strict";var r=n(29);n.d(t,"getProps",(function(){return r.a})),n(30),n(31),n(32),n(33),n(34),n(35),n(36),n(20),n(37),n(9),n(38),n(39),n(21),n(22),n(40),n(41),n(42),n(43),n(44),n(45)},function(e,t,n){e.exports=n(65)},function(e,t,n){"use strict";e.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addMatchingCardsToResults=void 0;var r=n(27),i=n(53);t.addMatchingCardsToResults=function(e,t,n){var o,a;for(o=0;o=a&&(c.matchStrength=a),n.push(c);break}}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.matches=void 0,t.matches=function(e,t){return Array.isArray(t)?function(e,t,n){var r=String(t).length,i=e.substr(0,r),o=parseInt(i,10);return t=parseInt(String(t).substr(0,i.length),10),n=parseInt(String(n).substr(0,i.length),10),o>=t&&o<=n}(e,t[0],t[1]):function(e,t){return(t=String(t)).substring(0,e.length)===e.substring(0,t.length)}(e,t)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isValidInputType=void 0,t.isValidInputType=function(e){return"string"==typeof e||e instanceof String}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findBestMatch=void 0,t.findBestMatch=function(e){return function(e){var t=e.filter((function(e){return e.matchStrength})).length;return t>0&&t===e.length}(e)?e.reduce((function(e,t){return e?Number(e.matchStrength)255?i(!1,!1):r.test(e)?i(!1,!0):i(!0,!0)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cardNumber=void 0;var r=n(58),i=n(26);function o(e,t,n){return{card:e,isPotentiallyValid:t,isValid:n}}t.cardNumber=function(e,t){var n,a;if(void 0===t&&(t={}),"string"!=typeof e&&"number"!=typeof e)return o(null,!1,!1);var u=String(e).replace(/-|\s/g,"");if(!/^\d*$/.test(u))return o(null,!1,!1);var c=i(u);if(0===c.length)return o(null,!1,!1);if(1!==c.length)return o(null,!0,!1);var s=c[0];if(t.maxLength&&u.length>t.maxLength)return o(s,!1,!1);n=s.type===i.types.UNIONPAY&&!0!==t.luhnValidateUnionPay||r(u),a=Math.max.apply(null,s.lengths),t.maxLength&&(a=Math.min(t.maxLength,a));for(var l=0;l=0;)t=parseInt(e.charAt(i),10),r&&(t*=2)>9&&(t=t%10+1),r=!r,n+=t,i--;return n%10==0}},function(e,t,n){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n1||1===a&&Number(n[1])>2?1:1===a?(o=n.substr(1),r.expirationYear(o).isPotentiallyValid?1:2):5===n.length?1:n.length>5?2:1),c=e.substr(0,u);return{month:c,year:e.substr(c.length)}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isArray=void 0,t.isArray=Array.isArray||function(e){return"[object Array]"==={}.toString.call(e)}},function(e,t,n){"use strict";function r(e,t){return{isValid:e,isPotentiallyValid:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.cvv=void 0,t.cvv=function(e,t){return void 0===t&&(t=3),t=t instanceof Array?t:[t],"string"!=typeof e?r(!1,!1):/^\d*$/.test(e)?function(e,t){for(var n=0;nfunction(e){for(var t=3,n=0;nt?e[n]:t;return t}(t)?r(!1,!1):r(!0,!0):r(!1,!1)}},function(e,t,n){"use strict";function r(e,t){return{isValid:e,isPotentiallyValid:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.postalCode=void 0,t.postalCode=function(e,t){void 0===t&&(t={});var n=t.minLength||3;return"string"!=typeof e?r(!1,!1):r(!(e.length1&&a.zoomHeight&&a.zoomHeight[n]?-1!==a.zoomHeight[n].indexOf(o):-1!==a.textSizeHeights.indexOf(o)||-1!==a.textSizeHeightsNoTabs.indexOf(o))}return!1}function b(e){if(void 0===e&&(e=i()),v(e)){var t=w(e),n=m(e)?r[window.outerHeight]:null;if(!n)return!1;var o=window.innerHeight,a=Math.round(window.screen.width/window.innerWidth*100)/100,u=Math.round(o*a),c=n.maybeSafari,s=!1;return a>1&&c[a]&&-1!==c[a].indexOf(u)&&(s=!0),t||s}return!1}function T(e){return void 0===e&&(e=i()),!!_(e)&&/Version\/[\d.]+/.test(e)&&!h(e)}function O(){return!!window.document.documentMode||Boolean(window.navigator&&window.navigator.userAgent&&/Edge|MSIE|rv:11/i.test(window.navigator.userAgent))}function I(){var e=window.document.querySelector('meta[http-equiv="X-UA-Compatible"]'),t=window.document.querySelector('meta[content="IE=edge"]');return!(!e||!t)}function S(){return!("undefined"==typeof process||!process.versions||!process.versions.electron)}function A(){if(window.document.documentMode)try{var e=window.status;return window.status="testIntranetMode","testIntranetMode"===window.status&&(window.status=e,!0)}catch(e){return!1}return!1}function C(){var e=i();return/Macintosh.*AppleWebKit(?!.*Safari)/i.test(e)}function N(e){return void 0===e&&(e=i()),!(E(e)||T(e)||h(e)||f(e)||p(e)||l(e)||g(e)||S()||C()||s())}function P(e){return void 0===e&&(e=i()),/Chrome|Chromium|CriOS/.test(e)&&!/SamsungBrowser|Silk|EdgA/.test(e)}function D(e){return void 0===e&&(e=i()),/Safari/.test(e)&&!P(e)&&!/Silk|FxiOS|EdgiOS/.test(e)}function k(){try{if(window.ApplePaySession&&window.ApplePaySession.supportsVersion(3)&&window.ApplePaySession.canMakePayments())return!0}catch(e){return!1}return!1}function R(e){return-1===window.document.cookie.indexOf(e)}function j(e,t){return(j=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function V(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,j(e,t)}function x(){return(x=Object.assign||function(e){for(var t=1;t>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,t={};return Object.freeze(t),e.set(t,"__testvalue__"),"__testvalue__"===e.get(t)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var t=e.prototype;return t._cleanupClosedWindows=function(){for(var e=this.weakmap,t=this.keys,n=0;n=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var n=e&&e.stack,r=e&&e.message;if(n&&r)return-1!==n.indexOf(r)?n:r+"\n"+n;if(n)return n;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+je(e,t+1)}}function Ve(e){var t="";return e?e instanceof Error?e.message||t:"string"==typeof e.message&&e.message||t:t}function xe(e){return"string"==typeof e?e:e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}function Le(e,t){var n=(e=e.split("://")[1]).indexOf(t);return-1!==n&&e.slice(n)===t}function Fe(e,t,n){var r=e[t];e[t]=function(){var e=arguments,t=this;return n({context:this,args:[].slice.call(arguments),original:r,callOriginal:function(){return r.apply(t,e)}})}}function Me(e,t){if(!t)return e;if(Object.assign)return Object.assign(e,t);for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function Ue(e){if(Object.values)return Object.values(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}Te.clear=function(){be=we};var Be=Te(Ue);function He(e,t){return Math.round(e*t/100)}function ze(){return Math.min.apply(Math,arguments)}function We(){return Math.max.apply(Math,arguments)}function Ye(e,t){var n=e%t;return n?e-n+t:e}function Ge(e,t,n){var r=[];return e.replace(t,(function(e){r.push(n?n.apply(null,arguments):e)})),r}function Ke(e){return"data:image/svg+xml;base64,"+he(e)}function qe(e,t){void 0===t&&(t=Boolean);var n={};for(var r in e)e.hasOwnProperty(r)&&t(e[r],r)&&(n[r]=e[r]);return n}function $e(e){return e}function Xe(e,t){var n=[];return e.replace(t,(function(e){return n.push(e),""})),n}function Je(e,t){var n,r;return void 0===t&&(t=50),pe((function(){r&&clearTimeout(r);var i=n=n||new Y;return r=setTimeout((function(){n=null,r=null,Y.try(e).then((function(e){i.resolve(e)}),(function(e){i.reject(e)}))}),t),i}),fe(e)+"::promiseDebounced")}function Qe(e,t){var n;return function r(){n=setTimeout((function(){e(),r()}),t)}(),{cancel:function(){clearTimeout(n)}}}function Ze(e){return Boolean(e.match(/^[0-9]+$/))}function et(e){return Boolean(e.match(/^[0-9]+\.[0-9]+$/))}function tt(e){return e.toString()}function nt(e){return"true"===e||"false"!==e&&(Ze(e)?parseInt(e,10):et(e)?parseFloat(e):e)}function rt(e,t,n){for(var r in void 0===t&&(t=""),void 0===n&&(n={}),t=t?t+".":t,e)e.hasOwnProperty(r)&&null!=e[r]&&"function"!=typeof e[r]&&(e[r]&&Array.isArray(e[r])&&e[r].length&&e[r].every((function(e){return"object"!=typeof e}))?n[""+t+r+"[]"]=e[r].join(","):e[r]&&"object"==typeof e[r]?n=rt(e[r],""+t+r,n):n[""+t+r]=tt(e[r]));return n}function it(e){var t={};for(var n in e)if(e.hasOwnProperty(n)&&"string"==typeof e[n]){var r=e[n];n.match(/^.+\[\]$/)?(n=n.slice(0,-2),r=r.split(",").map(nt)):r=nt(r);for(var i=t,o=n.split("."),a=0;a1?n-1:0),i=1;i1?r-1:0),o=1;o1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function tn(){return Boolean(en())}function nn(){return zt().then((function(){var e=en();if(e){var t=e.timing;return t.connectEnd&&t.domInteractive?t.domInteractive-t.connectEnd:void 0}}))}function rn(e){return void 0===e&&(e=""),e.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function on(){return"undefined"!=typeof window&&void 0!==window.location}function an(e,t){return void 0===t&&(t=window.document),[].slice.call(t.querySelectorAll(e))}function un(e,t){e.addEventListener("touchstart",Ce,{passive:!0}),e.addEventListener("click",t),e.addEventListener("keypress",(function(e){if(e.keyCode===Vt.ENTER||e.keyCode===Vt.SPACE)return t(e)}))}function cn(e){var t=e.host,n=void 0===t?window.location.host:t,r=e.path,i=e.reverse,o=void 0!==i&&i;return Ae(cn,(function(){var e=""+n+r,t=[].slice.call(document.getElementsByTagName("script"));o&&t.reverse();for(var i=0;ir&&(n=null),n||(n={guid:ve(),created:i}),t.__session__=n,e(n)}))}return{getState:o,getID:a,isStateFresh:function(){return a()===i},getSessionState:function(e){return u((function(t){return t.state=t.state||{},e(t.state)}))},getSessionID:function(){return u((function(e){return e.guid}))}}}),[{name:t,lifetime:r}])}function ir(){return rr({name:"belter_experiment"})}function or(e){return ir().getSessionState((function(t){return t.loggedBeacons=t.loggedBeacons||[],-1===t.loggedBeacons.indexOf(e)&&(t.loggedBeacons.push(e),!0)}))}function ar(e){return Math.floor(Math.random()*e)}function ur(e){var t,n=e.name,r=e.sample,i=void 0===r?50:r,o=e.logTreatment,a=void 0===o?Ce:o,u=e.logCheckpoint,c=void 0===u?Ce:u,s=e.sticky,l=void 0===s||s?function(e){return ir().getState((function(t){return t.throttlePercentiles=t.throttlePercentiles||{},t.throttlePercentiles[e]=t.throttlePercentiles[e]||ar(100),t.throttlePercentiles[e]}))}(n):ar(100),d=n+"_"+(t=l=50||i<=l&&l<2*i?"control":"throttle"),f=!1,p=!1;try{window.localStorage&&window.localStorage.getItem(n)&&(p=!0)}catch(e){}var h={isEnabled:function(){return"test"===t||p},isDisabled:function(){return"test"!==t&&!p},getTreatment:function(){return d},log:function(e,t){return void 0===t&&(t={}),f?(or(d+"_"+JSON.stringify(t))&&a({name:n,treatment:d,payload:t,throttle:l}),or(d+"_"+e+"_"+JSON.stringify(t))&&c({name:n,treatment:d,checkpoint:e,payload:t,throttle:l}),h):h},logStart:function(e){return void 0===e&&(e={}),f=!0,h.log("start",e)},logComplete:function(e){return void 0===e&&(e={}),h.log("complete",e)}};return h}function cr(e){var t=e.name,n=e.version,r=void 0===n?"latest":n,i=me(),o="__"+t+"__"+r+"_global__",a=i[o]=i[o]||{};return{get:function(e,t){return t=t||{},a[e]=a[e]||t}}}var sr=[];function lr(e){var t=e.url,n=e.method,r=void 0===n?"get":n,i=e.headers,o=void 0===i?{}:i,a=e.json,u=e.data,c=e.body,s=e.win,l=void 0===s?window:s,d=e.timeout,f=void 0===d?0:d;return new Y((function(e,n){if(a&&u||a&&c||u&&a)throw new Error("Only options.json or options.data or options.body should be passed");for(var i={},s=0,d=Object.keys(o);si.length));t++)if(n.isPermaChar)null==r&&a.length!==n.index||(a+=n.value,n.index<=u.start&&u.start++,n.index<=u.end&&u.end++);else for(;o2&&(u.children=arguments.length>3?r.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(a in e.defaultProps)void 0===u[a]&&(u[a]=e.defaultProps[a]);return y(e,u,i,o,null)}function y(e,t,n,r,a){var u={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==a?++o:a};return null==a&&null!=i.vnode&&i.vnode(u),u}function g(e){return e.children}function E(e,t){this.props=e,this.context=t}function w(e,t){if(null==t)return e.__?w(e.__,e.__.__k.indexOf(e)+1):null;for(var n;tt&&a.sort(s));O.__r=0}function I(e,t,n,r,i,o,a,u,c,s,l){var p,_,v,m,E,b,T,O,I,N=0,P=r&&r.__k||f,D=P.length,k=D,j=t.length;for(n.__k=[],p=0;p0?y(m.type,m.props,m.key,m.ref?m.ref:null,m.__v):m)?(m.__=n,m.__b=n.__b+1,-1===(O=C(m,P,T=p+N,k))?v=d:(v=P[O]||d,P[O]=void 0,k--),R(e,m,v,i,o,a,u,c,s,l),E=m.__e,(_=m.ref)&&v.ref!=_&&(v.ref&&x(v.ref,null,m),l.push(_,m.__c||E,m)),null!=E&&(null==b&&(b=E),(I=v===d||null===v.__v)?-1==O&&N--:O!==T&&(O===T+1?N++:O>T?k>j-T?N+=O-T:N--:N=O(null!=c?1:0))for(;a>=0||u=0){if((c=t[a])&&i==c.key&&o===c.type)return a;a--}if(u=n.__.length&&n.__.push({__V:Y}),n.__[e]}function Q(e){return z=1,function(e,t,n){var r=J(M++,2);if(r.t=e,!r.__c&&(r.__=[ue(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=U,!U.u)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=r.__c.__H.__.filter((function(e){return e.__c}));if(i.every((function(e){return!e.__N})))return!o||o.call(this,e,t,n);var a=!1;return i.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(a=!0)}})),!(!a&&r.__c.props===e)&&(!o||o.call(this,e,t,n))};U.u=!0;var o=U.shouldComponentUpdate,a=U.componentWillUpdate;U.componentWillUpdate=function(e,t,n){if(this.__e){var r=o;o=void 0,i(e,t,n),o=r}a&&a.call(this,e,t,n)},U.shouldComponentUpdate=i}return r.__N||r.__}(ue,e)}function Z(e,t){var n=J(M++,3);!i.__s&&ae(n.__H,t)&&(n.__=e,n.i=t,U.__H.__h.push(n))}function ee(e){return z=5,function(e,t){var n=J(M++,7);return ae(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function te(){for(var e;e=W.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(ie),e.__H.__h.forEach(oe),e.__H.__h=[]}catch(t){e.__H.__h=[],i.__e(t,e.__v)}}i.__b=function(e){U=null,G&&G(e)},i.__r=function(e){K&&K(e),M=0;var t=(U=e.__c).__H;t&&(B===U?(t.__h=[],U.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=Y,e.__N=e.i=void 0}))):(t.__h.forEach(ie),t.__h.forEach(oe),t.__h=[],M=0)),B=U},i.diffed=function(e){q&&q(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==W.push(t)&&H===i.requestAnimationFrame||((H=i.requestAnimationFrame)||re)(te)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==Y&&(e.__=e.__V),e.i=void 0,e.__V=Y}))),B=U=null},i.__c=function(e,t){t.some((function(e){try{e.__h.forEach(ie),e.__h=e.__h.filter((function(e){return!e.__||oe(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],i.__e(n,e.__v)}})),$&&$(e,t)},i.unmount=function(e){X&&X(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{ie(e)}catch(e){t=e}})),n.__H=void 0,t&&i.__e(t,n.__v))};var ne="function"==typeof requestAnimationFrame;function re(e){var t,n=function(){clearTimeout(r),ne&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);ne&&(t=requestAnimationFrame(n))}function ie(e){var t=U,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),U=t}function oe(e){var t=U;e.__c=e.__(),U=t}function ae(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function ue(e,t){return"function"==typeof t?t(e):t}var ce,se,le=n(2),de=n(12),fe=n.n(de),pe=n(1),he=n(0),_e=fe.a.creditCardType.types,ve=((ce={}).single=pe.h.CARD_FIELD,ce.number=pe.h.CARD_NUMBER_FIELD,ce.cvv=pe.h.CARD_CVV_FIELD,ce.expiry=pe.h.CARD_EXPIRY_FIELD,ce.name=pe.h.CARD_NAME_FIELD,ce.postal=pe.h.CARD_POSTAL_FIELD,ce),me=["name"],ye={appearance:"appearance",color:"color",direction:"direction",font:"font",fontFamily:"font-family",fontSizeAdjust:"font-size-adjust",fontSize:"font-size",fontStretch:"font-stretch",fontStyle:"font-style",fontVariantAlternates:"font-variant-alternates",fontVariantCaps:"font-variant-caps",fontVariantEastAsian:"font-variant-east-asian",fontVariantLigatures:"font-variant-ligatures",fontVariantNumeric:"font-variant-numeric",fontVariant:"font-variant",fontWeight:"font-weight",letterSpacing:"letter-spacing",lineHeight:"line-height",opacity:"opacity",outline:"outline",padding:"padding",paddingTop:"padding-top",paddingRight:"padding-right",paddingBottom:"padding-bottom",paddingLeft:"padding-left",textShadow:"text-shadow",transition:"transition",MozApperance:"-moz-appearance",MozOsxFontSmoothing:"-moz-osx-font-smoothing",MozTapHighlightColor:"-moz-tap-highlight-color",MozTransition:"-moz-transition",WebkitAppearance:"-webkit-appearance",WebkitOsxFontSmoothing:"-webkit-osx-font-smoothing",WebkitTapHighlightColor:"-webkit-tap-highlight-color",WebkitTransition:"-webkit-transition"},ge=[/;/,/[<>]/,/\\/,/@import/i,/expression/i,/javascript/i,/url/i],Ee=[/^\s*$/,/supports/i,/import/i,/[{}]/,/ svg":{color:"#d9360b",width:"24px",height:"24px","margin-right":"0.25rem"},".card-field-validation-error.hidden":{visibility:"hidden"}},Se=["billingAddress"],Ae=["aria-invalid","aria-required","disabled","placeholder"],Ce=n(15),Ne={inputValue:"",maskedInputValue:"",cursorStart:0,cursorEnd:0,isFocused:!1,keyStrokeCount:0,isPotentiallyValid:!0,isValid:!1},Pe={isValid:!1,isPotentiallyValid:!0};function De(e,t,n){return e.slice(0,t)+n+e.slice(t)}function ke(e,t){if(!e)throw new TypeError(t)}function Re(e){return e.replace(/\s/g,"")}function je(e){return!ge.some((function(t){return t.test(String(e))}))}function Ve(e){return!!Ae.includes(e.toLocaleLowerCase())||(Object(le.c)().warn("attribute_warning",{warn:'HTML Attribute "'+e+'" was ignored. See allowed attribute list.'}),!1)}function xe(e){void 0===e&&(e={});var t=[];return Object.keys(e).forEach((function(n){var r=e[n];"string"==typeof r||"number"==typeof r?t.push(" "+n+": "+r+";"):"object"==typeof r&&(t.push(n+" {"),t.push(xe(r)),t.push("}"))})),t.join("\n")}function Le(e,t){var n=[];return n.push("/* default style */"),n.push(xe(Te)),n.push(xe(e)),n.push("/* custom style */"),n.push(xe(function e(t){var n={};return Object.keys(t).forEach((function(r){var i,o,a=t[r];"string"==typeof a||"number"==typeof a?ye[r]?(i=ye[r],je(a)&&(n[i]=a)):Object(Ce.values)(ye).includes(r.toLowerCase())?(i=r.toLowerCase(),je(a)&&(n[i]=a)):Object(le.c)().warn("style_warning",{warn:'CSS property "'+r+'" was ignored. See allowed CSS property list.'}):"object"==typeof a&&(o=r,Ee.some((function(e){return e.test(o)}))||(n[r]=e(a)))})),n}(t))),n.join("\n")}function Fe(e,t,n,r){var i,o=null==e||null==(i=e.current)?void 0:i.base;o&&(function(e){return me.includes(e.name)}(o)&&0===o.value.length?(o.classList.remove("valid"),o.classList.remove("invalid")):t.isValid||t.isPotentiallyValid&&n?(o.classList.add("valid"),o.classList.remove("invalid")):r&&(o.classList.add("invalid"),o.classList.remove("valid")))}function Me(e){return Re(e).replace(/\D/g,"")}function Ue(e){var t=Re(e),n=t.split("/"),r=t;return n[1]&&2===n[1].length&&(n[1]="20"+n[1],r=n.join("/")),r}function Be(e){return e.map((function(e){return{type:e.type,niceType:e.niceType,code:e.code}}))}function He(e){var t,n;return(null==(t=e.xprops)||null==(t=t.parent)?void 0:t.uid)||(null==(n=e.xprops)?void 0:n.uid)}function ze(e){if(!e||"string"!=typeof e)throw new Error("can not convert invalid expiry date: "+e);if(e.match("^[0-9]{4}-([1-9]|0[1-9]|1[0-2])$"))return e;if(e.match("^([1-9]|0[1-9]|1[0-2])/?([0-9]{4}|[0-9]{2})$")){var t=e.split("/"),n=t[0],r=t[1];return(2===r.length?"20"+r:r)+"-"+(1===n.length?"0"+n:n)}throw new Error("can not convert invalid expiry date: "+e)}function We(e,t){var n={card:{number:e.number,securityCode:e.cvv,expiry:ze(e.expiry)}};return t&&0!==Object.keys(t).length&&(n.card.billingAddress=t.billingAddress),e.name&&(n.card.name=e.name),e.postalCode&&(n.card.billingAddress={postalCode:e.postalCode}),n}function Ye(e){var t=e.split("-");return t.forEach((function(e,n){t[n]=0!==n?e.toLowerCase().replace(/^\w/,(function(e){return e.toUpperCase()})):e.toLowerCase()})),t.join("")}function Ge(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([a-z\d])(\d)/g,"$1_$2").toLowerCase()}function Ke(e){if(e.length>0){var t=fe.a.creditCardType.default(e);if(t.length>0)return t}return[be]}function qe(e,t){var n;!function(){for(var e=arguments.length,t=new Array(e),n=0;ne.length-1)break;e=De(e,o," ")}return e}function $e(e,t,n){var r,i=window.xprops.fundingEligibility,o=we[t.type],a=n===pe.l.VAULT_WITHOUT_PURCHASE;if(0===e.length)return!0;if(null!=i&&null!=(r=i.card)&&r.eligible&&o&&i.card.vendors&&!i.card.branded){var u=i.card.vendors[o];if(a&&null!=u&&u.vaultable&&null!=u&&u.eligible)return!0;if(!a&&null!=u&&u.eligible)return!0}return!1}fe.a.creditCardType.addCard({code:{name:"CVV",size:3},gaps:[4,8,12],lengths:[16,18,19],niceType:"Carte Bancaire",patterns:[],type:"cb-nationale"}),fe.a.creditCardType.addCard({code:{name:"CVV",size:3},gaps:[4,8,12,16],lengths:[19],niceType:"Carte Aurore",patterns:[],type:"cetelem"}),fe.a.creditCardType.addCard({code:{name:"",size:0},gaps:[4,8,12,16],lengths:[17],niceType:"Cofinoga ou Privilège",patterns:[],type:"cofinoga"}),fe.a.creditCardType.addCard({code:{name:"",size:0},gaps:[4,8],lengths:[8,9],niceType:"4 étoiles",patterns:[],type:"cofidis"});var Xe={next:function(){return Ce.noop},previous:function(){return Ce.noop}};function Je(e,t,n){window.requestAnimationFrame((function(){e.selectionStart=t,e.selectionEnd=null!=n?n:t}))}function Qe(e){return function(){Je(e.current.base,0),setTimeout((function(){return e.current.base.focus()}))}}function Ze(e){return function(){var t=e.current.base.value;t&&Je(e.current.base,t.length),setTimeout((function(){return e.current.base.focus()}))}}function et(e,t){var n=e.target,r=n.value,i=n.selectionStart,o=e.key;0!==i||0!==r.length&&r.length===n.selectionEnd||!["Backspace","ArrowLeft"].includes(o)||t.previous(),i===r.length&&["ArrowRight"].includes(o)&&t.next()}function tt(e,t,n,r){window.xprops.export({setAttribute:function(e,n){Ve(e)&&t((function(t){var r;return Object(l.a)({},t,((r={})[e]=n,r))}))},removeAttribute:function(e){Ve(e)&&t((function(t){var n;return Object(l.a)({},t,((n={})[e]="",n))}))},addClass:function(t){var n;null==e||null==(n=e.current)||n.classList.add(t)},removeClass:function(t){var n;null==e||null==(n=e.current)||n.classList.remove(t)},clear:function(){e&&e.current&&"function"==typeof n&&n((function(e){return Object(l.a)({},e,{inputValue:""})}))},focus:function(){var t;null==e||null==(t=e.current)||t.focus()},setMessage:function(e){r.current.innerText=e}})}var nt=n(10);function rt(e){try{for(var t=0,n=Object(nt.b)(window);tj.length&&" "===c[r-1]&&(s+=1,d+=1),Je(e.target,s,d),S(a),k(Object(l.a)({},D,u,{inputValue:o,maskedInputValue:c,cursorStart:s,cursorEnd:d,contentPasted:!1,keyStrokeCount:L+1}))},onFocus:function(e){"function"==typeof h&&h(e);var t=null==W?void 0:W.current;t&&t.classList.add("display-icon");var n=qe(R),r=Object(l.a)({},D,{maskedInputValue:n,displayCardIcon:!0});k((function(e){return Object(l.a)({},e,r)}))},onBlur:function(e){var t,n,r={maskedInputValue:j,isPotentiallyValid:M,contentPasted:!1,displayCardIcon:D.inputValue.length>0},i=null==W?void 0:W.current;i&&(D.inputValue.length>0?i.classList.add("display-icon"):i.classList.remove("display-icon")),F&&(r.maskedInputValue=(n=Re(t=j).slice(-4),t.replace(/\d/g,"•").slice(0,-4)+n)),"function"==typeof _&&_(e),"function"==typeof v&&v(!1),k((function(e){return Object(l.a)({},e,r)}))},onKeyDown:function(e){"function"==typeof v&&v("Enter"===e.key),c&&et(e,a)},onPaste:function(){k((function(e){return Object(l.a)({},e,{contentPasted:!0})}))}},b)),m(St,{iconId:Ct(H.type),iconClass:"card-icon"}),m(At,{ariaMessageId:"card-number-field-description",ariaMessageRef:Y}))}var Pt=n(50),Dt=n.n(Pt);function kt(e){var t=e.name,n=void 0===t?"expiry":t,r=e.autocomplete,i=void 0===r?"cc-exp":r,o=e.navigation,a=void 0===o?Xe:o,u=e.state,c=e.type,s=e.style,d=e.maxLength,f=e.onChange,p=e.onFocus,h=e.onBlur,_=e.onKeyDown,v=e.onValidityChange,y=e.allowNavigation,E=void 0!==y&&y,w=Q({placeholder:e.placeholder}),b=w[0],T=w[1],O=Q(Object(l.a)({},Ne,u)),I=O[0],S=O[1],A=I.maskedInputValue,C=I.isValid,N=I.isPotentiallyValid,P=Q({}),D=P[0],k=P[1],R=ee(),j=ee();return Z((function(){E||tt(R,T,S,j);var e=null==R?void 0:R.current;if(e){var t=new Dt.a({element:e,pattern:"{{99}} / {{9999}}"});k(t)}}),[]),Z((function(){f({maskedDate:I.maskedInputValue})}),[I]),Z((function(){"function"==typeof v&&v({isValid:C,isPotentiallyValid:N}),E&&A&&C&&a.next()}),[C,N]),m(g,null,m("input",Object(l.a)({"aria-describedby":"card-expiry-field-description",name:n,autocomplete:i,inputmode:"numeric",ref:R,type:c,className:"card-field-expiry",style:s,maxLength:d,onKeyUp:function(e){var t=e.target.value,n=fe.a.expirationDate(t);t.includes("/")||(function(e,t){return 0!==e.length&&("1"===e[0]&&"/"===t||"1"!==e[0]&&"0"!==e[0])}(t,e.key)?D.setPattern("0{{9}} / {{9999}}"):D.setPattern("{{99}} / {{9999}}")),S(Object(l.a)({},I,n,{inputValue:D.getUnformattedValue(),maskedInputValue:R.current.value}))},onKeyDown:function(e){"function"==typeof _&&(_("Enter"===e.key),E&&et(e,a))},onFocus:function(e){"function"==typeof p&&p(e)},onBlur:function(e){"function"==typeof h&&h(e),"function"==typeof _&&_(!1)},onPaste:function(){S((function(e){return Object(l.a)({},e,{contentPasted:!0})}))}},b)),m(At,{ariaMessageId:"card-expiry-field-description",ariaMessageRef:j}))}function Rt(e){var t,n=e.name,r=void 0===n?"cvv":n,i=e.autocomplete,o=void 0===i?"cc-csc":i,a=e.navigation,u=void 0===a?Xe:a,c=e.allowNavigation,s=void 0!==c&&c,d=e.state,f=e.type,p=e.style,h=e.onChange,_=e.onFocus,v=e.onBlur,y=e.onKeyDown,E=e.onValidityChange,w=Q({placeholder:e.placeholder}),b=w[0],T=w[1],O=Q(Object(l.a)({},Ne,d)),I=O[0],S=O[1],A=Q(be),C=A[0],N=A[1],P=Q(!1),D=P[0],k=P[1],R=I.inputValue,j=I.keyStrokeCount,V=I.isValid,x=I.isPotentiallyValid,L=ee(),F=ee();return Z((function(){s||tt(L,T,S,F);var e=Object(le.d)();if(e){var t=He(window);e.on("cardTypeChange",{domain:window.location.origin},(function(e){He(e.source)===t&&N(e.data)}))}}),[]),Z((function(){h({cardCvv:I.inputValue})}),[I]),Z((function(){var e,t=fe.a.cvv(R,null==C||null==(e=C.code)?void 0:e.size);D&&(t.isPotentiallyValid=!1),S((function(e){return Object(l.a)({},e,t)}))}),[C]),Z((function(){var e,t=fe.a.cvv(R,null==C||null==(e=C.code)?void 0:e.size);D&&(t.isPotentiallyValid=!1),S((function(e){return Object(l.a)({},e,t)}))}),[C]),Z((function(){"function"==typeof E&&E({isValid:V,isPotentiallyValid:x}),s&&R&&V&&u.next()}),[V,x]),m(g,null,m("input",Object(l.a)({"aria-describedby":"card-cvv-field-description",name:r,autocomplete:o,inputmode:"numeric",ref:L,type:f,className:"card-field-cvv",value:R,style:p,maxLength:C.code.size,onKeyDown:function(e){"function"==typeof y&&y("Enter"===e.key),s&&et(e,u)},onInput:function(e){var t,n=Me(e.target.value),r=fe.a.cvv(n,null==C||null==(t=C.code)?void 0:t.size);S(Object(l.a)({},I,r,{inputValue:n,maskedInputValue:n,keyStrokeCount:j+1}))},onFocus:function(e){D||k(!0),"function"==typeof _&&_(e)},onBlur:function(e){"function"==typeof v&&v(e),"function"==typeof y&&y(!1)}},b,{placeholder:null!=(t=b.placeholder)?t:C.code.name})),m(At,{ariaMessageId:"card-cvv-field-description",ariaMessageRef:F}))}function jt(e){var t=e.name,n=void 0===t?"name":t,r=e.navigation,i=void 0===r?Xe:r,o=e.allowNavigation,a=void 0!==o&&o,u=e.state,c=e.type,s=e.style,d=e.maxLength,f=e.onChange,p=e.onFocus,h=e.onBlur,_=e.onKeyDown,v=e.onValidityChange,y=Q({placeholder:e.placeholder}),E=y[0],w=y[1],b=Q(Object(l.a)({},Ne,u)),T=b[0],O=b[1],I=T.inputValue,S=T.keyStrokeCount,A=T.isValid,C=T.isPotentiallyValid,N=ee(),P=ee();return Z((function(){tt(N,w,O,P)}),[]),Z((function(){f({cardName:T.inputValue})}),[T]),Z((function(){"function"==typeof v&&v({isValid:A,isPotentiallyValid:C}),a&&I&&A&&i.next()}),[A,C]),m(g,null,m("input",Object(l.a)({"aria-describedby":"card-name-field-description",name:n,inputmode:"text",ref:N,type:c,className:"card-field-name",value:I,style:s,maxLength:d,onKeyDown:function(e){"function"==typeof _&&_("Enter"===e.key),a&&et(e,i)},onInput:function(e){var t=e.target.value,n=fe.a.cardholderName(t);O(Object(l.a)({},T,n,{inputValue:t,maskedInputValue:t,keyStrokeCount:S+1}))},onFocus:function(e){"function"==typeof p&&p(e)},onBlur:function(e){"function"==typeof h&&h(e),"function"==typeof _&&_(!1)}},E)),m(At,{ariaMessageId:"card-name-field-description",ariaMessageRef:P}))}function Vt(e){var t=e.name,n=void 0===t?"postal":t,r=e.navigation,i=void 0===r?Xe:r,o=e.allowNavigation,a=void 0!==o&&o,u=e.state,c=e.type,s=e.style,d=e.maxLength,f=e.onChange,p=e.onFocus,h=e.onBlur,_=e.onKeyDown,v=e.onValidityChange,y=e.minLength,E=Q({placeholder:e.placeholder}),w=E[0],b=E[1],T=Q(Object(l.a)({},Ne,u)),O=T[0],I=T[1],S=O.inputValue,A=O.keyStrokeCount,C=O.isValid,N=O.isPotentiallyValid,P=ee(),D=ee();return Z((function(){tt(P,b,I,D)}),[]),Z((function(){f({cardPostalCode:O.inputValue})}),[O]),Z((function(){"function"==typeof v&&v({isValid:C,isPotentiallyValid:N}),a&&S&&C&&i.next()}),[C,N]),m(g,null,m("input",Object(l.a)({"aria-describedby":"card-postalCode-field-description",name:n,inputmode:"numeric",ref:P,type:c,className:"card-field-postal-code",value:S,style:s,maxLength:d,onKeyDown:function(e){"function"==typeof _&&_("Enter"===e.key),a&&et(e,i)},onInput:function(e){var t=e.target.value,n=fe.a.postalCode(t,{minLength:y});I(Object(l.a)({},O,n,{inputValue:t,keyStrokeCount:A+1}))},onFocus:function(e){"function"==typeof p&&p(e)},onBlur:function(e){"function"==typeof h&&h(e),"function"==typeof _&&_(!1)},minLength:y},w)),m(At,{ariaMessageId:"card-postalCode-field-description",ariaMessageRef:D}))}function xt(e){var t,n,r=e.cspNonce,i=e.onChange,o=e.styleObject,a=void 0===o?{}:o,u=e.placeholder,c=void 0===u?{}:u,s=e.gqlErrorsObject,d=void 0===s?{}:s,f=e.autoFocusRef,p=e.autocomplete,h=Q({}),_=h[0],v=h[1],y=Q(""),E=y[0],w=y[1],b=Q(""),T=b[0],O=b[1],I=Q(""),S=I[0],A=I[1],C=Q(""),N=C[0],P=C[1],D=Q(!0),k=D[0],R=D[1],j=Q(""),V=j[0],x=j[1],L=Q(!0),F=L[0],M=L[1],U=Q(Pe),B=U[0],H=U[1],z=Q(Pe),W=z[0],Y=z[1],G=Q(Pe),K=G[0],q=G[1],$=Q(!1),X=$[0],J=$[1],te=Q(!1),ne=te[0],re=te[1],ie=ee(),oe=ee(),ae=ee(),ue=ee(),ce={next:Qe(oe),previous:function(){return Ce.noop}},se={next:Qe(ae),previous:Ze(ie)},le={next:function(){return Ce.noop},previous:Ze(oe)};Z((function(){f(ie),tt(ue,v)}),[]),Z((function(){w(Le(Ie,a))}),[a]),Z((function(){var e=d.field,t=d.errors;"number"===e&&t.length>0&&H({isPotentiallyValid:!1,isValid:!1}),"expiry"===e&&t.length>0&&Y({isPotentiallyValid:!1,isValid:!1}),"cvv"===e&&t.length>0&&q({isPotentiallyValid:!1,isValid:!1})}),[d]),Z((function(){x(F?B.isPotentiallyValid||B.isValid?W.isPotentiallyValid||W.isValid?K.isPotentiallyValid||K.isValid?"":"This security code is not valid.":"This expiration date is not valid.":"This card number is not valid.":"This card vendor is not eligible.");var e=Boolean(B.isValid&&K.isValid&&W.isValid);R(e);var t=function(e){var t=e.isNumberValid,n=e.isCvvValid,r=e.isExpiryValid,i=e.isNameValid,o=e.isPostalCodeValid,a=e.gqlErrorsObject,u=void 0===a?{}:a,c=[],s=u.field,l=u.errors;return!1===e.isCardEligible&&("number"===s&&l.length?c.push.apply(c,l):c.push("INELIGIBLE_CARD_VENDOR")),!1===t&&("number"===s&&l.length?c.push.apply(c,l):c.push("INVALID_NUMBER")),!1===r&&("expiry"===s&&l.length?c.push.apply(c,l):c.push("INVALID_EXPIRY")),!1===n&&("cvv"===s&&l.length?c.push.apply(c,l):c.push("INVALID_CVV")),!1===i&&("name"===s&&l.length?c.push.apply(c,l):c.push("INVALID_NAME")),!1===o&&("postal"===s&&l.length?c.push.apply(c,l):c.push("INVALID_POSTAL")),c}({isCardEligible:F,isNumberValid:B.isValid,isCvvValid:K.isValid,isExpiryValid:W.isValid,gqlErrorsObject:d});Fe(ie,B,ne,X),Fe(oe,W,ne,X),Fe(ae,K,ne,X),i({value:{number:T,cvv:S,expiry:N},valid:e,errors:t})}),[T,S,N,k,B,F,K,W]),Z((function(){var e=null==ue?void 0:ue.current;e&&(ne?e.classList.add("focus"):e.classList.remove("focus"),V.length>0?e.classList.add("invalid"):e.classList.remove("invalid"))}),[ne,V]);var de=function(){J(!0),re(!0)};return m(g,null,m("style",{nonce:r},E),m(It,null),m("fieldset",Object(l.a)({ref:ue,className:"card-field"},_),m(Nt,{ref:ie,autocomplete:p,navigation:ce,type:"text",allowNavigation:!0,placeholder:null!=(t=c.number)?t:"Card number",onChange:function(e){O(e.cardNumber)},onEligibilityChange:function(e){return M(e)},onValidityChange:function(e){return H(Object(l.a)({},e))},onFocus:de,onBlur:function(){return re(!1)}}),m(kt,{ref:oe,autocomplete:p,navigation:se,type:"text",allowNavigation:!0,placeholder:null!=(n=c.expiry)?n:"MM / YY",maxLength:"7",onChange:function(e){return P(Ue(e.maskedDate))},onValidityChange:function(e){return Y(Object(l.a)({},e))},onFocus:de,onBlur:function(){return re(!1)}}),m(Rt,{ref:ae,autocomplete:p,navigation:le,type:"text",allowNavigation:!0,placeholder:c.cvv,onChange:function(e){return A(e.cardCvv)},onValidityChange:function(e){return q(Object(l.a)({},e))},onFocus:de,onBlur:function(){return re(!1)}})),m(Lt,{message:V}))}function Lt(e){var t=e.message;return m("div",{className:"card-field-validation-error "+(t.length?"":"hidden")},m(St,{iconId:"icon-error"}),t)}function Ft(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.styleObject,o=void 0===i?{}:i,a=e.placeholder,u=e.autoFocusRef,c=e.autocomplete,s=e.onKeyDown,l=e.gqlErrors,d=void 0===l?[]:l,f=Q(""),p=f[0],h=f[1],_=Q(""),v=_[0],y=_[1],E=Q(!0),w=E[0],b=E[1],T=Q(Pe),O=T[0],I=T[1],S=Q([]),A=S[0],C=S[1],N=Q(!1),P=N[0],D=N[1],k=Q(!1),R=k[0],j=k[1],V=Q(!1),x=V[0],L=V[1],F=ee(),M=O.isValid,U=O.isPotentiallyValid;return Z((function(){u(F)}),[]),Z((function(){h(Le(Oe,o))}),[o]),Z((function(){d.length>0&&I({isPotentiallyValid:!1,isValid:!1})}),[d]),Z((function(){Fe(F,O,P,R),n({value:v,valid:O.isValid,isFocused:P,potentiallyValid:O.isPotentiallyValid,potentialCardTypes:A})}),[v,w,M,P,U,A]),Z((function(){r({isFocused:P})}),[P]),Z((function(){s({isInputSubmitRequest:x})}),[x]),m(g,null,m("style",{nonce:t},p),m(It,null),m(Nt,{ref:F,type:"text",autocomplete:c,placeholder:null!=a?a:"Card number",onChange:function(e){return t=e.potentialCardTypes,y(e.cardNumber),void C(t);var t},onEligibilityChange:function(e){return b(e)},onValidityChange:function(e){return I(e)},onFocus:function(){j(!0),D(!0)},onBlur:function(){return D(!1)},onKeyDown:function(e){return L(e)}}))}function Mt(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.onKeyDown,o=e.styleObject,a=void 0===o?{}:o,u=e.placeholder,c=e.autoFocusRef,s=e.autocomplete,l=e.gqlErrors,d=void 0===l?[]:l,f=Q(""),p=f[0],h=f[1],_=Q(""),v=_[0],y=_[1],E=Q(Pe),w=E[0],b=E[1],T=ee(),O=Q(!1),I=O[0],S=O[1],A=Q(!1),C=A[0],N=A[1],P=Q(!1),D=P[0],k=P[1],R=w.isValid,j=w.isPotentiallyValid;return Z((function(){c(T)}),[]),Z((function(){h(Le(Oe,a))}),[a]),Z((function(){d.length>0&&b({isPotentiallyValid:!1,isValid:!1})}),[d]),Z((function(){Fe(T,w,I,C),n({value:v,valid:w.isValid,isFocused:I,potentiallyValid:w.isPotentiallyValid})}),[v,R,I,j]),Z((function(){r({isFocused:I})}),[I]),Z((function(){i({isInputSubmitRequest:D})}),[D]),m(g,null,m("style",{nonce:t},p),m(kt,{ref:T,type:"text",autocomplete:s,placeholder:null!=u?u:"MM / YY",maxLength:"7",onChange:function(e){return y(Ue(e.maskedDate))},onValidityChange:function(e){return b(e)},onFocus:function(){N(!0),S(!0)},onBlur:function(){return S(!1)},onKeyDown:function(e){return k(e)}}))}function Ut(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.onKeyDown,o=e.styleObject,a=void 0===o?{}:o,u=e.placeholder,c=e.autoFocusRef,s=e.autocomplete,l=e.gqlErrors,d=void 0===l?[]:l,f=Q(""),p=f[0],h=f[1],_=Q(""),v=_[0],y=_[1],E=Q(Pe),w=E[0],b=E[1],T=ee(),O=Q(!1),I=O[0],S=O[1],A=Q(!1),C=A[0],N=A[1],P=Q(!1),D=P[0],k=P[1],R=w.isValid,j=w.isPotentiallyValid;return Z((function(){c(T)}),[]),Z((function(){h(Le(Oe,a))}),[a]),Z((function(){d.length>0&&b({isPotentiallyValid:!1,isValid:!1})}),[d]),Z((function(){Fe(T,w,I,C),n({value:v,valid:w.isValid,isFocused:I,potentiallyValid:w.isPotentiallyValid})}),[v,R,I,j]),Z((function(){r({isFocused:I})}),[I]),Z((function(){i({isInputSubmitRequest:D})}),[D]),m(g,null,m("style",{nonce:t},p),m(Rt,{ref:T,type:"text",autocomplete:s,placeholder:u,onChange:function(e){return y(e.cardCvv)},onValidityChange:function(e){return b(e)},onFocus:function(){N(!0),S(!0)},onBlur:function(){return S(!1)},onKeyDown:function(e){return k(e)}}))}function Bt(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.onKeyDown,o=e.styleObject,a=void 0===o?{}:o,u=e.placeholder,c=e.autoFocusRef,s=e.gqlErrors,l=void 0===s?[]:s,d=Q(""),f=d[0],p=d[1],h=Q(""),_=h[0],v=h[1],y=Q(Pe),E=y[0],w=y[1],b=ee(),T=Q(!1),O=T[0],I=T[1],S=Q(!1),A=S[0],C=S[1],N=Q(!1),P=N[0],D=N[1],k=E.isValid,R=E.isPotentiallyValid;return Z((function(){c(b)}),[]),Z((function(){p(Le(Oe,a))}),[a]),Z((function(){l.length>0&&w({isPotentiallyValid:!1,isValid:!1})}),[l]),Z((function(){Fe(b,E,A,O),n({value:_,valid:E.isValid,isFocused:A,potentiallyValid:E.isPotentiallyValid})}),[_,k,A,R]),Z((function(){r({isFocused:A})}),[A]),Z((function(){i({isInputSubmitRequest:P})}),[P]),m(g,null,m("style",{nonce:t},f),m(jt,{ref:b,type:"text",placeholder:null!=u?u:"Cardholder Name (optional)",maxLength:"255",onChange:function(e){return v(e.cardName)},onValidityChange:function(e){return w(e)},onFocus:function(){C(!0),I(!0)},onBlur:function(){return C(!1)},onKeyDown:function(e){return D(e)}}))}function Ht(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.onKeyDown,o=e.styleObject,a=void 0===o?{}:o,u=e.placeholder,c=e.minLength,s=e.maxLength,l=e.autoFocusRef,d=e.autocomplete,f=e.gqlErrors,p=void 0===f?[]:f,h=Q(""),_=h[0],v=h[1],y=Q(""),E=y[0],w=y[1],b=Q(Pe),T=b[0],O=b[1],I=ee(),S=Q(!1),A=S[0],C=S[1],N=Q(!1),P=N[0],D=N[1],k=Q(!1),R=k[0],j=k[1],V=T.isValid,x=T.isPotentiallyValid;return Z((function(){l(I)}),[]),Z((function(){v(Le(Oe,a))}),[a]),Z((function(){p.length>0&&O({isPotentiallyValid:!1,isValid:!1})}),[p]),Z((function(){Fe(I,T,A,P),n({value:E,valid:T.isValid,isFocused:A,potentiallyValid:T.isPotentiallyValid})}),[E,V,A,x]),Z((function(){r({isFocused:A})}),[A]),Z((function(){i({isInputSubmitRequest:R})}),[R]),m(g,null,m("style",{nonce:t},_),m(Vt,{ref:I,type:"text",autocomplete:d,placeholder:null!=u?u:"Postal code",minLength:c,maxLength:s,onChange:function(e){return w(e.cardPostalCode)},onValidityChange:function(e){return O(e)},onFocus:function(){D(!0),C(!0)},onBlur:function(){return C(!1)},onKeyDown:function(e){return j(e)}}))}function zt(e){var t,n=e.cspNonce,r=e.props,i=e.featureFlags,o=e.experiments,a=r.facilitatorAccessToken,u=r.style,c=r.disableAutocomplete,s=r.placeholder,d=r.type,f=r.export,p=r.minLength,h=r.maxLength,_=r.inputEvents||{},v=_.onChange,y=_.onFocus,E=_.onBlur,w=_.onInputSubmitRequest,b=Q(),T=b[0],O=b[1],I=Q(!1),S=I[0],A=I[1],C=Q(!0),N=C[0],P=C[1],D=Q([]),k=D[0],R=D[1],j=Q(!1),V=j[0],x=j[1],L=Q(!1),F=L[0],M=L[1],U=Q(),B=U[0],H=U[1],z=Q({singleField:{},numberField:[],expiryField:[],cvvField:[],nameField:[],postalCodeField:[]}),W=z[0],Y=z[1],G=ee(!0);c&&(t="off");var K=function(){return T},q=function(){return S},$=function(){return N},X=function(){return V},J=function(){return k},te=function(e){var t=e.errors,n=Object(l.a)({},W);if("single"===d)n.singleField=Object(l.a)({},e);else if(t&&t.length)switch(d){case"number":n.numberField=[].concat(t);break;case"expiry":n.expiryField=[].concat(t);break;case"cvv":n.cvvField=[].concat(t);break;case"name":n.nameField=[].concat(t);break;case"postal":n.postalCodeField=[].concat(t)}Y(n)},ne=function(){Y({singleField:{},numberField:[],expiryField:[],cvvField:[],nameField:[],postalCodeField:[]})},re=function(){var e=ut(),t=e.cards,n=e.fields,r=Ye(ve[d]);return n[r]={isEmpty:at(T),isFocused:V,isPotentiallyValid:N,isValid:S},{fields:n,potentialCardTypes:"cardNumberField"===r?Be(k):t}};Z((function(){if(G.current&&""===T)G.current=!1;else if(!G.current&&"function"==typeof v){var e=re(),t=e.fields,n=e.potentialCardTypes,r=ct(t);v({fields:t,cards:n,emittedBy:d,isFormValid:0===r.length,errors:r})}}),[T]),Z((function(){if(G.current&&""===T)G.current=!1;else if(!G.current&&"function"==typeof y){var e=re(),t=e.fields,n=e.potentialCardTypes,r=ct(t),i={fields:t,cards:n,emittedBy:d,isFormValid:0===r.length,errors:r};V?y(Object(l.a)({},i)):"function"!=typeof E||V||E(Object(l.a)({},i))}}),[V]),Z((function(){if(F&&"function"==typeof w){var e=re(),t=e.fields,n=e.potentialCardTypes,r=ct(t),i={fields:t,cards:n,emittedBy:d,isFormValid:0===r.length,errors:r};w(Object(l.a)({},i)),M(!1)}}),[F]),Z((function(){!function(e){if(e){var t=null;window.addEventListener("focus",(function(){t=setTimeout((function(){t=null,function(e){var t=""===e.value;t&&(e.value=" ");var n=e.selectionStart,r=e.selectionEnd;e.setSelectionRange(0,0),e.setSelectionRange(n,r),t&&(e.value="")}(e),e.focus()}))})),window.addEventListener("focusin",(function(e){t&&e.target instanceof HTMLInputElement&&(clearTimeout(t),t=null)}))}}(B)}),[B]),Z((function(){!function(e){window.exports={name:e.name,isFieldValid:e.isFieldValid,isFieldPotentiallyValid:e.isFieldPotentiallyValid,getPotentialCardTypes:e.getPotentialCardTypes,isFieldFocused:e.isFieldFocused,getFieldValue:e.getFieldValue,setGqlErrors:e.setGqlErrors,resetGQLErrors:e.resetGQLErrors}}({name:ve[d],isFieldPotentiallyValid:$,getPotentialCardTypes:J,isFieldValid:q,isFieldFocused:X,getFieldValue:K,setGqlErrors:te,resetGQLErrors:ne}),f({submit:function(e){var t=function(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:Object.keys(e).reduce((function(t,n){return Se.includes(n)&&(t[n]=e[n]),t}),{})}(e);return Ot({facilitatorAccessToken:a,extraFields:t,featureFlags:i,experiments:o})},getState:function(){var e=ut(),t=ct(e.fields);return Object(l.a)({},e,{isFormValid:0===t.length,errors:t})}})}),[S,T,V,N,k]);var ie=function(e){var t=e.valid,n=e.isFocused,r=e.potentiallyValid,i=e.potentialCardTypes;O(e.value),x(n),A(t),P(r),ne(),R(i)},oe=function(e){x(e.isFocused)},ae=function(e){M(e.isInputSubmitRequest)};return m(g,null,"single"===d?m(xt,{gqlErrorsObject:W.singleField,cspNonce:n,autocomplete:t,onChange:ie,styleObject:u,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"number"===d?m(Ft,{ref:B,gqlErrors:W.numberField,cspNonce:n,autocomplete:t,onChange:ie,onFocus:oe,onKeyDown:ae,styleObject:u,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"cvv"===d?m(Ut,{ref:B,gqlErrors:W.cvvField,cspNonce:n,autocomplete:t,onChange:ie,onKeyDown:ae,onFocus:oe,styleObject:u,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"expiry"===d?m(Mt,{ref:B,gqlErrors:W.expiryField,cspNonce:n,autocomplete:t,onChange:ie,onFocus:oe,onKeyDown:ae,styleObject:u,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"name"===d?m(Bt,{ref:B,gqlErrors:W.nameField,cspNonce:n,onChange:ie,onFocus:oe,onKeyDown:ae,styleObject:u,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"postal"===d?m(Ht,{ref:B,gqlErrors:W.postalCodeField,cspNonce:n,onChange:ie,onFocus:oe,onKeyDown:ae,styleObject:u,placeholder:s,minLength:p,maxLength:h||10,autoFocusRef:function(e){return H(e.current.base)}}):null)}function Wt(e){var t=e.cspNonce,n=e.featureFlags,o=e.experiments,a=e.buyerCountry,u=e.metadata,c=yt({facilitatorAccessToken:e.facilitatorAccessToken,featureFlags:n,experiments:o});!function(e){var t,n=e.env,r=e.sessionID,i=e.clientID,o=e.partnerAttributionID,a=e.sdkCorrelationID,u=e.cardCorrelationID,c=e.locale,s=e.merchantID,d=e.merchantDomain,f=e.buyerCountry,p=e.type,h=e.hcfSessionID,_=e.productAction,v=Object(le.c)();Object(le.k)({env:n,sessionID:r,clientID:i,sdkCorrelationID:a,locale:c,buyerCountry:f}),v.addTrackingBuilder((function(){var e;return(e={})[he.e.BUTTON_VERSION]="5.0.151",e.hcf_session_id=h,e.hcf_correlation_id=u,e[he.e.PARTNER_ATTRIBUTION_ID]=o,e[he.e.MERCHANT_DOMAIN]=d,e[he.e.TIMESTAMP]=Date.now().toString(),e.sdk_correlation_id=a,e[he.c.PAYMENTS_SDK]=i,e[he.e.SELLER_ID]=null==s?void 0:s[0],e.hcf_version="v2",e[he.e.PAYMENT_FLOW]=_,e}));var m=((t={})[he.e.STATE]=pe.f.CARD,t[he.e.TRANSITION]="hcf_"+p+"_field_rendered",t[he.e.EVENT_NAME]="hcf_"+p+"_field_rendered",t);ft.a.hash({pageRenderTime:Object(ht.d)()}).then((function(e){var t,n=e.pageRenderTime;v.track(Object(l.a)({},m,((t={})[he.e.CONTEXT_TYPE]="hosted_session_id",t[he.e.CONTEXT_ID]=h,t[he.e.PAGE_LOAD_TIME]=n?n.toString():"",t))),v.flush()}))}({env:c.env,sessionID:c.sessionID,cardSessionID:c.cardSessionID,clientID:c.clientID,partnerAttributionID:c.partnerAttributionID,sdkCorrelationID:c.sdkCorrelationID,cardCorrelationID:null==u?void 0:u.correlationID,locale:c.locale,merchantID:c.merchantID,merchantDomain:c.merchantDomain,buyerCountry:a,type:c.type,hcfSessionID:c.hcfSessionID,productAction:c.productAction}),function(e,t,n){var o,a,u;i.__&&i.__(e,t),o=!1?null:t.__k,a=[],u=[],R(t,e=t.__k=m(g,null,[e]),o||d,d,void 0!==t.ownerSVGElement,o?null:t.firstChild?r.call(t.childNodes):null,a,o?o.__e:t.firstChild,!1,u),j(a,e,u)}(m(zt,{cspNonce:t,props:c,featureFlags:n,experiments:o}),Object(le.a)())}}]); \ No newline at end of file +window.smartCard=function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return{}.hasOwnProperty.call(e,t)},n.p="",n(n.s=83)}([function(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"i",(function(){return a})),n.d(t,"e",(function(){return c})),n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return s})),n.d(t,"f",(function(){return l})),n.d(t,"g",(function(){return d})),n.d(t,"a",(function(){return f})),n.d(t,"h",(function(){return r})),n.d(t,"j",(function(){return i}));var r={CAPTURE:"capture",AUTHORIZE:"authorize",ORDER:"order",TOKENIZE:"tokenize",SUBSCRIPTION:"subscription"},i={COMPONENTS:"components",ENV:"env",DEBUG:"debug",CACHEBUST:"cachebust",CLIENT_ID:"client-id",MERCHANT_ID:"merchant-id",LOCALE:"locale",CURRENCY:"currency",INTENT:"intent",COMMIT:"commit",VAULT:"vault",BUYER_COUNTRY:"buyer-country",ENABLE_FUNDING:"enable-funding",DISABLE_FUNDING:"disable-funding",DISABLE_CARD:"disable-card",INTEGRATION_DATE:"integration-date",STAGE_HOST:"stage-host",STAGE_ALIAS:"stage-alias",CDN_REGISTRY:"cdn-registry",VERSION:"version"},o={LOCAL:"local",STAGE:"stage",SANDBOX:"sandbox",PRODUCTION:"production",TEST:"test"},a={ANDROID:"android",IOS:"iOS"},c={FEED:"feed_name",STATE:"state_name",EVENT_NAME:"event_name",TRANSITION:"transition_name",PAGE:"page_name",BUTTON_TYPE:"button_type",SESSION_UID:"page_session_id",BUTTON_SESSION_UID:"button_session_id",TOKEN:"token",CONTEXT_ID:"context_id",CONTEXT_TYPE:"context_type",REFERER:"referer_url",MERCHANT_DOMAIN:"merchant_domain",PAY_ID:"pay_id",SELLER_ID:"seller_id",CLIENT_ID:"client_id",DATA_SOURCE:"serverside_data_source",BUTTON_SOURCE:"button_source",ERROR_CODE:"ext_error_code",ERROR_DESC:"ext_error_desc",PAGE_LOAD_TIME:"page_load_time",EXPERIMENT_EXPERIENCE:"experimentation_experience",EXPERIMENT_TREATMENT:"experimentation_treatment",EXPERIMENT_NAME:"pxp_exp_id",TREATMENT_NAME:"pxp_trtmnt_id",TRANSITION_TIME:"transition_time",FUNDING_LIST:"eligible_payment_methods",FUNDING_COUNT:"eligible_payment_count",CHOSEN_FUNDING:"selected_payment_method",BUTTON_LAYOUT:"button_layout",VERSION:"checkoutjs_version",LOCALE:"locale",BUYER_COUNTRY:"buyer_cntry",INTEGRATION_IDENTIFIER:"integration_identifier",PARTNER_ATTRIBUTION_ID:"bn_code",PAGE_TYPE:"pp_placement",SDK_NAME:"sdk_name",SDK_VERSION:"sdk_version",SDK_ENVIRONMENT:"sdk_environment",MOBILE_APP_VERSION:"mobile_app_version",MOBILE_BUNDLE_IDENTIFIER:"mapv",USER_AGENT:"user_agent",USER_ACTION:"user_action",CONTEXT_CORRID:"context_correlation_id",SDK_CACHE:"sdk_cache",SDK_LOAD_TIME:"sdk_load_time",IS_VAULT:"is_vault",DISABLE_FUNDING:"disable_funding",DISABLE_CARD:"disable_card",RESPONSE_DURATION:"response_duration",SDK_INTEGRATION_SOURCE:"sdk_integration_source",PAYMENT_FLOW:"payment_flow",BUTTON_VERSION:"button_version",FI_LIST:"fi_list",FI_ID:"fi_id",PRODUCT:"product",CHOSEN_FI_TYPE:"chosen_fi_type",SELECTED_FI:"merchant_selected_funding_source",POTENTIAL_PAYMENT_METHODS:"potential_payment_methods",PAY_NOW:"pay_now",STICKINESS_ID:"stickiness_id",TIMESTAMP:"t",OPTION_SELECTED:"optsel",USER_IDENTITY_METHOD:"user_identity_method",FIELDS_COMPONENT_SESSION_ID:"fields_component_session_id",CPL_COMP_METRICS:"cpl_comp_metrics",CPL_CHUNK_METRICS:"cpl_chunk_metrics",CPL_QUERY_METRICS:"cpl_query_metrics"},u={PAYMENTS_SDK:"checkout"},s={PAYMENTS_SDK:"payments_sdk"},l={PAYMENTS_SDK:"payments_sdk"},d={PAYPAL:"paypal",VENMO:"venmo",APPLEPAY:"applepay",ITAU:"itau",CREDIT:"credit",PAYLATER:"paylater",CARD:"card",IDEAL:"ideal",SEPA:"sepa",BANCONTACT:"bancontact",GIROPAY:"giropay",SOFORT:"sofort",EPS:"eps",MYBANK:"mybank",P24:"p24",PAYU:"payu",BLIK:"blik",TRUSTLY:"trustly",OXXO:"oxxo",BOLETO:"boleto",BOLETOBANCARIO:"boletobancario",WECHATPAY:"wechatpay",MERCADOPAGO:"mercadopago",MULTIBANCO:"multibanco",SATISPAY:"satispay",PAIDY:"paidy"},f={VISA:"visa",MASTERCARD:"mastercard",AMEX:"amex",DISCOVER:"discover",HIPER:"hiper",ELO:"elo",JCB:"jcb",CUP:"cup"}},function(e,t,n){"use strict";n.d(t,"p",(function(){return r})),n.d(t,"i",(function(){return i})),n.d(t,"b",(function(){return o})),n.d(t,"a",(function(){return a})),n.d(t,"m",(function(){return c})),n.d(t,"k",(function(){return u})),n.d(t,"r",(function(){return s})),n.d(t,"j",(function(){return l})),n.d(t,"s",(function(){return d})),n.d(t,"n",(function(){return f})),n.d(t,"d",(function(){return p})),n.d(t,"f",(function(){return h})),n.d(t,"g",(function(){return _})),n.d(t,"e",(function(){return v})),n.d(t,"c",(function(){return m})),n.d(t,"h",(function(){return y})),n.d(t,"q",(function(){return g})),n.d(t,"o",(function(){return E})),n.d(t,"l",(function(){return b}));var r="smart-payment-buttons",i={AUTHORIZATION:"authorization",CONTENT_TYPE:"content-type",PREFER:"prefer",ACCESS_TOKEN:"x-paypal-internal-euat",CSRF_TOKEN:"x-csrf-jwt",SOURCE:"x-source",REQUESTED_BY:"x-requested-by",APP_NAME:"x-app-name",APP_VERSION:"x-app-version",CLIENT_CONTEXT:"paypal-client-context",PARTNER_ATTRIBUTION_ID:"paypal-partner-attribution-id",CLIENT_METADATA_ID:"paypal-client-metadata-id",PAYPAL_DEBUG_ID:"paypal-debug-id",PAYPAL_REQUEST_ID:"paypal-request-id",DISABLE_SET_COOKIE:"disable-set-cookie"},o={FUNDING_SOURCE:"data-funding-source",CARD:"data-card",PAYMENT_METHOD_ID:"data-payment-method-id",INSTRUMENT_ID:"data-instrument-id",INSTRUMENT_TYPE:"data-instrument-type",SECONDARY_INSTRUMENT_TYPE:"data-secondary-instrument-type",MENU:"data-menu",NONCE:"data-nonce",RENDER_VERSION:"data-render-version",CLIENT_VERSION:"data-client-version",PAY_NOW:"data-pay-now",RESPONSE_START_TIME:"data-response-start-time"},a={LOADING:"paypal-button-loading",CLICKED:"paypal-button-clicked",BUTTON:"paypal-button"},c={REPRESENTATION:"return=representation"},u={INSTRUMENT_DECLINED:"INSTRUMENT_DECLINED",PAYER_ACTION_REQUIRED:"PAYER_ACTION_REQUIRED",DUPLICATE_INVOICE_ID:"DUPLICATE_INVOICE_ID",INVALID_RESOURCE_ID:"INVALID_RESOURCE_ID"},s={BODY:"body"},l={PAYPAL_JS_SDK:"PAYPAL_JS_SDK"},d={INCONTEXT:"INCONTEXT",INLINE:"INLINE"},f={SMART_PAYMENT_BUTTONS:"SMART_PAYMENT_BUTTONS"},p={BUTTON_SESSION_ID:"button_session_id",WALLET_SESSION_ID:"wallet_session_id",ORDER_ID:"EC-Token",PAYMENT_ID:"Pay-ID",VAULT_SETUP_TOKEN:"vault_setup_token"},h={BUTTON:"smart_button",CARD:"card_field",WALLET:"smart_wallet",PXP:"PXP_CHECK",ELIGIBILITY_CHECK:"eligibility_check"},_={BUTTON_LOAD:"process_button_load",BUTTON_CLICK:"process_button_click",PXP:"process_pxp_check",WALLET_LOAD:"process_wallet_load",MENU_CLICK:"process_menu_click",CLICK_CHOOSE_FUNDING:"process_click_pay_with_different_payment_method",CLICK_CHOOSE_ACCOUNT:"process_click_pay_with_different_account",CLICK_UNLINK_ACCOUNT:"process_click_unlink_account",INSTALLMENTS_ELIGIBLE:"installments_eligible",INSTALLMENTS_INELIGIBLE:"installments_ineligible",CREATE_ORDER:"process_create_order",CONFIRM_ORDER:"process_confirm_order",RECEIVE_ORDER:"process_receive_order",RECEIVE_VAULT_SETUP_TOKEN:"process_receive_vault_setup_token",CREATE_PAYMENT:"process_create_payment",CAPTURE_AUTHORIZATION:"process_capture_authorization",CHECKOUT_SHIPPING_CHANGE:"process_checkout_shipping_change",CHECKOUT_SHIPPING_ADDRESS_CHANGE:"process_checkout_shipping_address_change",CHECKOUT_SHIPPING_OPTIONS_CHANGE:"process_checkout_shipping_options_change",CHECKOUT_APPROVE:"process_checkout_approve",CHECKOUT_COMPLETE:"process_checkout_complete",CHECKOUT_CANCEL:"process_checkout_cancel",CHECKOUT_ERROR:"process_checkout_error",TOKENIZE_APPROVE:"process_tokenize_approve",CONNECT_REDIRECT:"process_connect_redirect",FIREBASE_CONNECTION_OPENED:"firebase_connection_opened",FIREBASE_CONNECTION_ERRORED:"firebase_connection_errored",APPLEPAY_EVENT:"applepay_event",APPLEPAY_FLOW_ERROR:"applepay_flow_error",APPLEPAY_ON_CLICK_INVALID:"applepay_onclick_invalid",APPLEPAY_MERCHANT_VALIDATION_COMPLETION_ERROR:"applepay_merchant_validation_completion_error",APPLEPAY_MERCHANT_VALIDATION_ERROR:"applepay_merchant_validation_error",APPLEPAY_CREATE_ORDER_ERROR:"applepay_create_order_error",APPLEPAY_GET_DETAILS_ERROR:"applepay_get_details_error",APPLEPAY_PAYMENT_ERROR:"applepay_payment_error",APPLEPAY_CONFIG_ERROR:"applepay_config_error",NATIVE_DETECT_POSSIBLE_APP_SWITCH:"native_detect_possible_app_switch",NATIVE_DETECT_APP_SWITCH:"native_detect_app_switch",NATIVE_DETECT_WEB_SWITCH:"native_detect_web_switch",NATIVE_APP_SWITCH_ACK:"native_app_switch_ack",NATIVE_ERROR:"native_app_switch_ack",NATIVE_APP_INSTALLED:"native_app_installed",NATIVE_APP_SWITCH_INELIGIBLE:"app_switch_ineligible",NATIVE_ATTEMPT_APP_SWITCH:"app_switch_attempted",NATIVE_ATTEMPT_APP_SWITCH_ERRORED:"app_switch_attempted_errored",NATIVE_CLOSING_POPUP:"native_closing_popup",NATIVE_POPUP_CLOSED:"popup_closed",NATIVE_POPUP_HASHCHANGE:"popup_hashchange",NATIVE_POPUP_NO_OPENER:"popup_no_opener",NATIVE_POPUP_ANDROID_APP_ERROR:"native_popup_android_app_installed_error",NATIVE_POPUP_FALLBACK:"popup_fallback",NATIVE_FALLBACK_RETRY_VENMO_APP_SWITCH:"native_fallback_retry_venmo_app_switch",NATIVE_POPUP_SHOWN:"popup_shown",NATIVE_ON_APPROVE:"native_onapprove",NATIVE_ON_APPROVE_ERROR:"native_onapprove_error",NATIVE_ON_CANCEL:"native_oncancel",NATIVE_ON_CLICK_INVALID:"native_onclick_invalid",NATIVE_ON_COMPLETE:"native_oncomplete",NATIVE_ON_ERROR:"native_onerror",NATIVE_ON_SHIPPING_CHANGE:"native_onshippingchange",NATIVE_ON_FALLBACK:"native_onfallback",NATIVE_POPUP_INIT:"native_popup_init",NATIVE_POPUP_UNLOAD:"native_popup_unload",NATIVE_POPUP_BEFORE_UNLOAD:"native_popup_beforeunload",NATIVE_POPUP_PAGEHIDE:"native_popup_pagehide",NATIVE_POPUP_OPENER_DETECT_CLOSE:"native_popup_opener_detect_close",NATIVE_OPT_OUT:"native_opt_out",NATIVE_FALLBACK:"native_fallback",NATIVE_FALLBACK_VENMO:"native_fallback_venmo",NATIVE_VENMO_WEB:"native_venmo_web",NATIVE_VENMO_WEB_REDIRECT:"native_venmo_web_redirect",QR_LOAD:"qr_load",QR_SHOWN:"qr_shown",QR_CLOSING:"qr_closing",QR_SURVEY:"desktop_exit_survey_selection_submitted",QR_PREPARE_PAY:"qr_prepare_pay",QR_PROCESS_PAY_WITH:"qr_process_pay_with",HONEY_IDENTIFY:"honey_identify",CALL_REST_API:"call_rest_api",ORDER_VALIDATE:"process_order_validate"},v={ERR_DESC:"int_error_desc",HONEY_DEVICE_ID:"honey_device_id",HONEY_SESSION_ID:"honey_session_id",INTEGRATION_ISSUE:"integration_issue",INTEGRATION_WHITELIST:"whitelist",INFO_MSG:"info_msg",PMT_TOKEN:"pmt_token",TRANSITION_TYPE:"transition_type",TRANSITION_REASON:"transition_reason",SHIPPING_CALLBACK_PASSED:"shipping_callback_passed",SHIPPING_CALLBACK_INVOKED:"shipping_callback_invoked",DESKTOP_EXIT_SURVEY_REASON:"desktop_exit_survey_reason",ORDER_CREATED_BY:"order_created_by"},m={BUTTON_LAYOUT:"button_layout",BUTTON_COLOR:"button_color",BUTTON_SIZE:"button_size",BUTTON_SHAPE:"button_shape",BUTTON_LABEL:"button_label",BUTTON_WIDTH:"button_width",BUTTON_TYPE:"button_type",BUTTON_TAGLINE_ENABLED:"button_tagline_enabled",BUTTON_CORRELATION_ID:"button_correlation_id"},y={SMART_FIELDS:"smart-fields",CARD_FIELD:"card-field",CARD_NUMBER_FIELD:"card-number-field",CARD_CVV_FIELD:"card-cvv-field",CARD_EXPIRY_FIELD:"card-expiry-field",CARD_NAME_FIELD:"card-name-field",CARD_POSTAL_FIELD:"card-postal-field"},g={TOO_MANY_REQUESTS:429},E={SERVICE_WORKER_URL:"https://www.paypal.com/checkout-sw",SW_SCOPE:"/webapps/hermes",GET_SW_LOGS_EVENT_NAME:"GET_SW_LOGS",LOGS_CHANNEL_NAME:"logs-channel",GET_SW_LOGS_RESPONSE_EVENT_NAME:"GET_SW_LOGS_RESPONSE"},b={WITH_PURCHASE:"with_purchase",VAULT_WITHOUT_PURCHASE:"vault_without_purchase"}},function(e,t,n){"use strict";n.d(t,"l",(function(){return r.f})),n.d(t,"h",(function(){return r.e})),n.d(t,"a",(function(){return r.a})),n.d(t,"f",(function(){return r.c})),n.d(t,"b",(function(){return r.b})),n.d(t,"c",(function(){return i.a})),n.d(t,"i",(function(){return i.b})),n.d(t,"k",(function(){return i.c})),n.d(t,"e",(function(){return c})),n.d(t,"g",(function(){return u})),n.d(t,"j",(function(){return s})),n.d(t,"d",(function(){return l}));var r=n(17),i=n(9);n(1),n(10);var o=n(3);function a(){return Object(o.f)({name:"paypal",lifetime:36e5})}function c(){return a().getID()}function u(){return a().isStateFresh()}function s(e){}function l(){var e=function(){if(!window.paypal)throw new Error("paypal not found");return window.paypal}();if(!e.postRobot)throw new Error("paypal.postRobot not found");return e.postRobot}n(0)},function(e,t,n){"use strict";function r(){return window.navigator.mockUserAgent||window.navigator.userAgent}function i(e){return void 0===e&&(e=r()),/Android/.test(e)}function o(e){return void 0===e&&(e=r()),/iPhone|iPod|iPad/.test(e)}function a(e){return void 0===e&&(e=r()),/Chrome|Chromium|CriOS/.test(e)&&!/SamsungBrowser|Silk|EdgA/.test(e)}function c(e){return void 0===e&&(e=r()),/Safari/.test(e)&&!a(e)&&!/Silk|FxiOS|EdgiOS/.test(e)}function u(e,t){return(u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function s(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,u(e,t)}n.d(t,"g",(function(){return r})),n.d(t,"j",(function(){return i})),n.d(t,"m",(function(){return o})),n.d(t,"l",(function(){return a})),n.d(t,"n",(function(){return c})),n.d(t,"e",(function(){return W})),n.d(t,"s",(function(){return Y})),n.d(t,"d",(function(){return K})),n.d(t,"k",(function(){return G})),n.d(t,"c",(function(){return re})),n.d(t,"f",(function(){return Z})),n.d(t,"a",(function(){return b})),n.d(t,"x",(function(){return w})),n.d(t,"o",(function(){return C})),n.d(t,"i",(function(){return N})),n.d(t,"p",(function(){return D})),n.d(t,"h",(function(){return P})),n.d(t,"v",(function(){return k})),n.d(t,"w",(function(){return R})),n.d(t,"q",(function(){return j})),n.d(t,"r",(function(){return x})),n.d(t,"u",(function(){return V})),n.d(t,"b",(function(){return L})),n.d(t,"t",(function(){return oe})),n(5);var l=n(4),d=n(10);function f(e,t){for(var n=0;n>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,t={};return Object.freeze(t),e.set(t,"__testvalue__"),"__testvalue__"===e.get(t)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var t=e.prototype;return t._cleanupClosedWindows=function(){for(var e=this.weakmap,t=this.keys,n=0;n=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var n=e&&e.stack,r=e&&e.message;if(n&&r)return-1!==n.indexOf(r)?n:r+"\n"+n;if(n)return n;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+k(e,t+1)}}function R(e){var t="";return e?e instanceof Error?e.message||t:"string"==typeof e.message&&e.message||t:t}function j(e,t){void 0===t&&(t=Boolean);var n={};for(var r in e)e.hasOwnProperty(r)&&t(e[r],r)&&(n[r]=e[r]);return n}function x(e,t){var n,r;return void 0===t&&(t=50),E((function(){r&&clearTimeout(r);var i=n=n||new l.a;return r=setTimeout((function(){n=null,r=null,l.a.try(e).then((function(e){i.resolve(e)}),(function(e){i.reject(e)}))}),t),i}),g(e)+"::promiseDebounced")}function V(e,t){var n;return function r(){n=setTimeout((function(){e(),r()}),t)}(),{cancel:function(){clearTimeout(n)}}}function L(e){var t=[],n={};return function(r){if(-1===t.indexOf(r)){t.push(r);var i=k(r);if(!n[i])return n[i]=!0,e(r)}}}C.clear=function(){A=S},C((function(e){if(Object.values)return Object.values(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}));var F=function(e){function t(t){var n;return(n=e.call(this,t)||this).name=n.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(n),n.constructor):n.stack=new Error(t).stack,n}return s(t,e),t}(y(Error));function M(){return Boolean(document.body)&&"complete"===document.readyState}function U(){return Boolean(document.body)&&"interactive"===document.readyState}var B,H=C((function(){return new l.a((function(e){if(M()||U())return e();var t=setInterval((function(){if(M()||U())return clearInterval(t),e()}),10)}))}));function z(e){return N(z,(function(){var t={};if(!e)return t;if(-1===e.indexOf("="))return t;for(var n=0,r=e.split("&");n1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function K(){return H().then((function(){var e=q();if(e){var t=e.timing;return t.connectEnd&&t.domInteractive?t.domInteractive-t.connectEnd:void 0}}))}function G(){return"undefined"!=typeof window&&void 0!==window.location}function $(){return N($,(function(){try{if("undefined"==typeof window)return!1;if(window.localStorage){var e=Math.random().toString();window.localStorage.setItem("__test__localStorage__",e);var t=window.localStorage.getItem("__test__localStorage__");if(window.localStorage.removeItem("__test__localStorage__"),e===t)return!0}}catch(e){}return!1}))}s((function(){return B.apply(this,arguments)||this}),B=F);var X="undefined"!=typeof document?document.currentScript:null,J=C((function(){if(X)return X;if(X=function(){try{var e=function(){try{throw new Error("_")}catch(e){return e.stack||""}}(),t=/.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(e),n=t&&t[1];if(!n)return;for(var r=0,i=[].slice.call(document.getElementsByTagName("script")).reverse();rr&&(n=null),n||(n={guid:i||w(),created:o}),t.__session__=n,e(n)}))}return{getState:a,getID:c,isStateFresh:function(){return c()===o},getSessionState:function(e){return u((function(t){return t.state=t.state||{},e(t.state)}))},getSessionID:function(){return u((function(e){return e.guid}))}}}),[{name:t,lifetime:r}])}function ee(){return Z({name:"belter_experiment"})}function te(e){return ee().getSessionState((function(t){return t.loggedBeacons=t.loggedBeacons||[],-1===t.loggedBeacons.indexOf(e)&&(t.loggedBeacons.push(e),!0)}))}function ne(e){return Math.floor(Math.random()*e)}function re(e){var t,n=e.name,r=e.sample,i=void 0===r?50:r,o=e.logTreatment,a=void 0===o?D:o,c=e.logCheckpoint,u=void 0===c?D:c,s=e.sticky,l=void 0===s||s?function(e){return ee().getState((function(t){return t.throttlePercentiles=t.throttlePercentiles||{},t.throttlePercentiles[e]=t.throttlePercentiles[e]||ne(100),t.throttlePercentiles[e]}))}(n):ne(100),d=n+"_"+(t=l=50||i<=l&&l<2*i?"control":"throttle"),f=!1,p=!1;try{window.localStorage&&window.localStorage.getItem(n)&&(p=!0)}catch(e){}var h={isEnabled:function(){return"test"===t||p},isDisabled:function(){return"test"!==t&&!p},getTreatment:function(){return d},log:function(e,t){return void 0===t&&(t={}),f?(te(d+"_"+JSON.stringify(t))&&a({name:n,treatment:d,payload:t,throttle:l}),te(d+"_"+e+"_"+JSON.stringify(t))&&u({name:n,treatment:d,checkpoint:e,payload:t,throttle:l}),h):h},logStart:function(e){return void 0===e&&(e={}),f=!0,h.log("start",e)},logComplete:function(e){return void 0===e&&(e={}),h.log("complete",e)}};return h}C((function(){var e;try{e=J()}catch(e){return Q}var t=e.getAttribute("data-uid");if(t&&"string"==typeof t)return t;if((t=e.getAttribute("data-uid-auto"))&&"string"==typeof t)return t;if(e.src){var n=function(e){for(var t="",n=0;n=300){var o,a=new Error(s+" returned status "+t+" (Corr ID: "+r[c.i.PAYPAL_DEBUG_ID]+").\n\n"+JSON.stringify(n));throw a.response={status:t,headers:r,body:n},t===c.q.TOO_MANY_REQUESTS&&Object(u.c)().track(((o={})[i.e.TRANSITION]=c.g.CALL_REST_API,o[c.e.ERR_DESC]="Error: "+t+" - "+n,o[c.e.INFO_MSG]="URL: "+s,o)),Object(u.c)().warn("rest_api_"+f+"_status_"+t+"_error"),Object(u.i)({name:"pp.app.paypal_sdk.buttons.rest_api_"+f+".error.count",dimensions:h}),a}return Object(u.i)({name:"pp.app.paypal_sdk.buttons.rest_api_"+f+".success.count",dimensions:h}),n}))}function l(e){var t=e.accessToken,n=e.url,a=e.method,s=void 0===a?"get":a,l=e.headers,d=void 0===l?{}:l,f=e.json,p=e.authenticated,h=void 0===p||p,_=e.eventName,v=e.metricDimensions,m=void 0===v?{}:v;if(d[c.i.REQUESTED_BY]=c.p,h&&!t)throw new Error("Buyer access token not present - can not call smart api: "+n);return t&&(d[c.i.ACCESS_TOKEN]=t),Object(o.t)({url:n,method:s,headers:d,json:f}).then((function(e){var t,o=e.status,a=e.body,l=e.headers;if("contingency"===a.ack){var f=new Error(a.contingency);throw f.response={url:n,method:s,headers:d,body:a},f.data=a.data,Object(u.c)().warn("smart_api_"+_+"_contingency_error"),f}if(o===c.q.TOO_MANY_REQUESTS&&Object(u.c)().track(((t={})[i.e.TRANSITION]=c.g.CALL_REST_API,t[c.e.ERR_DESC]="Error: "+o+" - "+a,t[c.e.INFO_MSG]="URL: "+n,t)),o>400)throw Object(u.c)().warn("smart_api_"+_+"_status_"+o+"_error"),Object(u.i)({name:"pp.app.paypal_sdk.buttons.smart_api_"+_+".error.count",dimensions:Object(r.a)({status:o},m)}),new Error("Api: "+n+" returned status code: "+o+" (Corr ID: "+l[c.i.PAYPAL_DEBUG_ID]+")\n\n"+JSON.stringify(a));if("success"!==a.ack)throw Object(u.c)().warn("smart_api_"+_+"_ack_error"),Object(u.i)({name:"pp.app.paypal_sdk.buttons.smart_api_"+_+".error.count",dimensions:m}),new Error("Api: "+n+" returned ack: "+a.ack+" (Corr ID: "+l[c.i.PAYPAL_DEBUG_ID]+")\n\n"+JSON.stringify(a));return Object(u.i)({name:"pp.app.paypal_sdk.buttons.smart_api_"+_+".success.count",dimensions:m}),{data:a.data,headers:l}}))}function d(e){var t=e.name,n=e.query,i=e.variables,s=void 0===i?{}:i,l=e.headers,d=void 0===l?{}:l,f=e.returnErrorObject,p=void 0!==f&&f;return Object(o.t)({url:a.e+"?"+t,method:"POST",json:{query:n,variables:s},headers:Object(r.a)({"x-app-name":c.p},d)}).then((function(e){var n=e.status,r=e.body,i=r.errors||[];if(i.length){var o=i[0].message||JSON.stringify(i[0]);if(Object(u.c)().warn("graphql_"+t+"_error",{err:o}),p)throw i[0];throw Object(u.i)({name:"pp.app.paypal_sdk.buttons.graphql_"+t+".error.count",dimensions:{}}),new Error(o)}if(200!==n)throw Object(u.c)().warn("graphql_"+t+"_status_"+n+"_error"),Object(u.i)({name:"pp.app.paypal_sdk.buttons.graphql_"+t+".error.count",dimensions:{status:n}}),new Error(a.e+" returned status "+n+"\n\n"+JSON.stringify(r));return Object(u.i)({name:"pp.app.paypal_sdk.buttons.graphql_"+t+".success.count",dimensions:{}}),r.data}))}function f(e){return e.headers[c.i.PAYPAL_DEBUG_ID]}function p(e){var t=null==e?void 0:e.response;if(t)return f(t)}},function(e,t,n){"use strict";n.d(t,"f",(function(){return o})),n.d(t,"a",(function(){return a})),n.d(t,"g",(function(){return c})),n.d(t,"h",(function(){return u})),n.d(t,"b",(function(){return s})),n.d(t,"j",(function(){return l})),n.d(t,"k",(function(){return d})),n.d(t,"i",(function(){return f})),n.d(t,"e",(function(){return p})),n.d(t,"d",(function(){return h})),n.d(t,"c",(function(){return _}));var r,i=n(0),o="/xoplatform/logger/api/logger",a="/v1/oauth2/token",c="/v2/checkout/orders",u="/v1/payments/payment",s="/v1/billing/subscriptions",l="validate-payment-method",d="/v3/vault/setup-tokens",f={AUTH:"/smart/api/auth",CHECKOUT:"/smart/api/checkout",ORDER:"/smart/api/order",PAYMENT:"/smart/api/payment",SUBSCRIPTION:"/smart/api/billagmt/subscriptions",VAULT:"/smart/api/vault"},p="/graphql",h=((r={})[i.g.PAYPAL]=i.g.PAYPAL,r[i.g.PAYLATER]=i.g.PAYPAL,r[i.g.CREDIT]=i.g.PAYPAL,{APP:"https://www.paypalobjects.com/checkout/js/lib/firebase-app.js",AUTH:"https://www.paypalobjects.com/checkout/js/lib/firebase-auth.js",DATABASE:"https://www.paypalobjects.com/checkout/js/lib/firebase-database.js"}),_=!1},function(e,t,n){"use strict";n.d(t,"f",(function(){return l})),n.d(t,"x",(function(){return m})),n.d(t,"g",(function(){return g})),n.d(t,"k",(function(){return O})),n.d(t,"p",(function(){return I})),n.d(t,"q",(function(){return S})),n.d(t,"d",(function(){return A})),n.d(t,"b",(function(){return C})),n.d(t,"s",(function(){return N})),n.d(t,"u",(function(){return D})),n.d(t,"e",(function(){return P})),n.d(t,"c",(function(){return k})),n.d(t,"w",(function(){return R})),n.d(t,"o",(function(){return j})),n.d(t,"m",(function(){return x})),n.d(t,"h",(function(){return V})),n.d(t,"l",(function(){return L})),n.d(t,"j",(function(){return F})),n.d(t,"t",(function(){return M})),n.d(t,"i",(function(){return B})),n.d(t,"v",(function(){return z})),n.d(t,"a",(function(){return W})),n.d(t,"n",(function(){return Y})),n.d(t,"r",(function(){return $}));var r=n(4),i=n(3),o=n(0),a=n(7),c=n(2),u=n(1),s=n(6);function l(e,t){var n=(void 0===t?{}:t).targetSubject;return Object(i.i)(l,(function(){Object(c.c)().info("rest_api_create_access_token");var t=Object(i.a)((e||"")+":"),r={grant_type:"client_credentials"};return n&&(r.target_subject=n),Object(i.t)({method:"post",url:a.a,headers:{Authorization:"Basic "+t},data:r}).then((function(t){var n=t.body;if(n&&"invalid_client"===n.error)throw Object(c.c)().warn("rest_api_v1_oauth2_token_create_error",{err:"invalid client id"}),new Error("Auth Api invalid client id: "+(e||"")+":\n\n"+JSON.stringify(n,null,4));if(!n||!n.access_token)throw Object(c.c)().warn("rest_api_v1_oauth2_token_create_error"),new Error("Auth Api response error:\n\n"+JSON.stringify(n,null,4));return n.access_token}))}),[e,n])}var d,f=!1,p=!1,h=function(){return p},_=function(){return f},v=function(){return d};function m(e,t,n){return Object(i.i)(m,(function(){var r;return f=!1,d=null,p=!1,f=!0,p=!0,Object(s.a)({name:"CreateUpgradedLowScopeAccessToken",headers:(r={},r[u.i.ACCESS_TOKEN]=t,r[u.i.CLIENT_CONTEXT]=n,r),query:"\n mutation CreateUpgradedLowScopeAccessToken(\n $orderID: String!\n $buyerAccessToken: String!\n $facilitatorAccessToken: String!\n ) {\n createUpgradedLowScopeAccessToken(\n token: $orderID\n buyerAccessToken: $buyerAccessToken\n merchantLSAT: $facilitatorAccessToken\n )\n }\n ",variables:{facilitatorAccessToken:e,buyerAccessToken:t,orderID:n}}).then((function(e){return Object(c.c)().info("create_upgraded_low_scope_access_token_success",{orderID:n}),null==e?void 0:e.createUpgradedLowScopeAccessToken})).catch((function(t){return Object(c.c)().warn("create_upgraded_low_scope_access_token_error",{orderID:n}),function(e){d=e}(t),e}))}),[e,t,n])}var y=n(5);function g(e,t){var n,r=t.facilitatorAccessToken,i=t.partnerAttributionID;return Object(c.c)().info("rest_api_create_order_id"),Object(s.b)({accessToken:r,method:"post",url:""+a.g,eventName:"v2_checkout_orders_create",data:e,headers:(n={},n[u.i.PARTNER_ATTRIBUTION_ID]=i||"",n[u.i.PREFER]=u.m.REPRESENTATION,n)}).then((function(e){var t,n=e&&e.id;if(!n)throw new Error("Order Api response error:\n\n"+JSON.stringify(e,null,4));return Object(c.c)().track(((t={})[o.e.TRANSITION]=u.g.CREATE_ORDER,t[o.e.CONTEXT_TYPE]=u.d.ORDER_ID,t[o.e.TOKEN]=n,t[o.e.CONTEXT_ID]=n,t)),n}))}function E(e){var t;return Boolean(null==e||null==(t=e.response)||null==(t=t.body)||null==(t=t.details)?void 0:t.some((function(e){return e.issue===u.k.INVALID_RESOURCE_ID})))}function b(){return h()?"with_ignore_cache_lsat_upgrade":"without_ignore_cache_lsat_upgrade"}function w(){var e=Boolean(_()),t=Boolean(h()),n=Boolean(v()),r=t?"with_ignore_cache":"without_ignore_cache";return e?n?r+"_error":r+"_success":r+"_not_called"}function T(e,t){j(e).then((function(n){var r=(n.checkoutSession.payees||[]).map((function(e){return e.merchantId}));Object(c.c)().info("using_client_side_helper_"+t,{payee:r.join(),orderID:e})})).catch((function(n){Object(c.c)().warn("err_getting_payee_client_side_helper_"+t,{orderID:e,err:Object(i.v)(n)})}))}function O(e,t){var n,r,o=t.facilitatorAccessToken,l=t.buyerAccessToken,d=t.partnerAttributionID,f=t.forceRestAPI,p=void 0!==f&&f,h=t.experiments;return Object(c.c)().info("get_order_"+b()+"_"+(_()?"called":"not_called"),{orderID:e}),Object(c.c)().info("get_order_"+b()+"_"+(v()?"errored":"did_not_error"),{orderID:e,err:Object(i.v)(v())}),T(e,"get"),p&&!v()?Object(s.b)({accessToken:o,url:a.g+"/"+e,eventName:"v2_checkout_orders_get",headers:(r={},r[u.i.PARTNER_ATTRIBUTION_ID]=d||"",r[u.i.PREFER]=u.m.REPRESENTATION,r),metricDimensions:{lsatUpgrade:w()}}).catch((function(t){var n,r=Object(s.d)(t);if(Object(c.c)().warn("get_order_"+b()+"_call_rest_api_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),E(t)&&Object(c.c)().warn("get_order_"+b()+"_invalid_resource_id_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),h.disableSmartAPI)throw t;return Object(s.c)({accessToken:l,url:a.i.ORDER+"/"+e,eventName:"order_get",headers:(n={},n[u.i.CLIENT_CONTEXT]=e,n),metricDimensions:{lsatUpgrade:w(),smartApiType:"fallback"}}).then((function(t){var n=Object(s.e)(t);return Object(c.c)().info("get_order_"+b()+"_smart_fallback_success",{smartCorrID:n,restCorrID:r,orderID:e}),t.data})).catch((function(n){var o=Object(s.d)(t);throw Object(c.c)().error("get_order_"+b()+"_smart_fallback_error",{smartCorrID:o,restCorrID:r,orderID:e,err:Object(i.v)(n)}),n}))})).finally((function(){Object(c.c)().flush()})):Object(s.c)({accessToken:l,url:a.i.ORDER+"/"+e,eventName:"order_get",headers:(n={},n[u.i.CLIENT_CONTEXT]=e,n),metricDimensions:{lsatUpgrade:w(),smartApiType:"default"}}).then((function(e){return e.data})).finally((function(){Object(c.c)().flush()}))}function I(e){var t,n,r,i=null!=e&&null!=(t=e.response)&&null!=(t=t.body)&&null!=(t=t.data)&&t.details?null==e||null==(n=e.response)||null==(n=n.body)||null==(n=n.data)?void 0:n.details:null==e||null==(r=e.response)||null==(r=r.body)?void 0:r.details;return Boolean(null==i?void 0:i.some((function(e){return e.issue===u.k.INSTRUMENT_DECLINED||e.issue===u.k.PAYER_ACTION_REQUIRED})))}function S(e){var t;return Boolean(null==e||null==(t=e.response)||null==(t=t.body)||null==(t=t.details)?void 0:t.some((function(e){return e.issue===u.k.DUPLICATE_INVOICE_ID})))}function A(e,t){var n,r,o=t.facilitatorAccessToken,l=t.buyerAccessToken,d=t.partnerAttributionID,f=t.forceRestAPI,p=void 0!==f&&f,h=t.experiments;return Object(c.c)().info("capture_order_"+b()+"_"+(_()?"called":"not_called"),{orderID:e}),Object(c.c)().info("capture_order_"+b()+"_"+(v()?"errored":"did_not_error"),{orderID:e,err:Object(i.v)(v())}),T(e,"capture"),p&&!v()?Object(s.b)({accessToken:o,method:"post",eventName:"v2_checkout_orders_capture",url:a.g+"/"+e+"/capture",headers:(r={},r[u.i.PARTNER_ATTRIBUTION_ID]=d||"",r[u.i.PREFER]=u.m.REPRESENTATION,r[u.i.PAYPAL_REQUEST_ID]=e,r),metricDimensions:{lsatUpgrade:w()}}).catch((function(t){var n,r=Object(s.d)(t);if(Object(c.c)().warn("capture_order_"+b()+"_call_rest_api_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),E(t)&&Object(c.c)().warn("capture_order_"+b()+"_invalid_resource_id_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),I(t)||S(t))throw t;if(h.disableSmartAPI)throw t;return Object(s.c)({accessToken:l,method:"post",eventName:"order_capture",url:a.i.ORDER+"/"+e+"/capture",json:{data:{facilitatorAccessToken:o}},headers:(n={},n[u.i.CLIENT_CONTEXT]=e,n),metricDimensions:{lsatUpgrade:w(),smartApiType:"fallback"}}).then((function(t){var n=Object(s.e)(t);return Object(c.c)().info("capture_order_"+b()+"_smart_fallback_success",{smartCorrID:n,restCorrID:r,orderID:e}),t.data})).catch((function(n){var o=Object(s.d)(t);throw Object(c.c)().info("capture_order_"+b()+"_smart_fallback_error",{smartCorrID:o,restCorrID:r,orderID:e,err:Object(i.v)(n)}),n}))})).finally((function(){Object(c.c)().flush()})):Object(s.c)({accessToken:l,method:"post",eventName:"order_capture",url:a.i.ORDER+"/"+e+"/capture",json:{data:{facilitatorAccessToken:o}},headers:(n={},n[u.i.CLIENT_CONTEXT]=e,n),metricDimensions:{lsatUpgrade:w(),smartApiType:"default"}}).then((function(e){return e.data})).finally((function(){Object(c.c)().flush()}))}function C(e,t){var n,r,o=t.facilitatorAccessToken,l=t.buyerAccessToken,d=t.partnerAttributionID,f=t.forceRestAPI,p=void 0!==f&&f,h=t.experiments;return Object(c.c)().info("authorize_order_"+b()+"_"+(_()?"called":"not_called"),{orderID:e}),Object(c.c)().info("authorize_order_"+b()+"_"+(v()?"errored":"did_not_error"),{orderID:e,err:Object(i.v)(v())}),T(e,"authorize"),p&&!v()?Object(s.b)({accessToken:o,method:"post",eventName:"v2_checkout_orders_authorize",url:a.g+"/"+e+"/authorize",headers:(r={},r[u.i.PARTNER_ATTRIBUTION_ID]=d||"",r[u.i.PREFER]=u.m.REPRESENTATION,r),metricDimensions:{lsatUpgrade:w()}}).catch((function(t){var n,r=Object(s.d)(t);if(Object(c.c)().warn("authorize_order_"+b()+"_call_rest_api_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),E(t)&&Object(c.c)().warn("authorize_order_"+b()+"_invalid_resource_id_error",{restCorrID:r,orderID:e,err:Object(i.v)(t)}),I(t))throw t;if(h.disableSmartAPI)throw t;return Object(s.c)({accessToken:l,method:"post",eventName:"order_authorize",url:a.i.ORDER+"/"+e+"/authorize",json:{data:{facilitatorAccessToken:o}},headers:(n={},n[u.i.CLIENT_CONTEXT]=e,n),metricDimensions:{lsatUpgrade:w(),smartApiType:"fallback"}}).then((function(t){var n=Object(s.e)(t);return Object(c.c)().info("authorize_order_"+b()+"_smart_fallback_success",{smartCorrID:n,restCorrID:r,orderID:e}),t.data})).catch((function(n){var o=Object(s.d)(t);throw Object(c.c)().info("authorize_order_"+b()+"_smart_fallback_error",{smartCorrID:o,restCorrID:r,orderID:e,err:Object(i.v)(n)}),n}))})).finally((function(){Object(c.c)().flush()})):(Object(c.c)().info("lsat_upgrade_false"),Object(s.c)({accessToken:l,method:"post",eventName:"order_authorize",url:a.i.ORDER+"/"+e+"/authorize",json:{data:{facilitatorAccessToken:o}},headers:(n={},n[u.i.CLIENT_CONTEXT]=e,n),metricDimensions:{lsatUpgrade:w(),smartApiType:"default"}}).then((function(e){return e.data})).finally((function(){Object(c.c)().flush()})))}function N(e,t,n){var r,o,l,d=n.facilitatorAccessToken,f=n.buyerAccessToken,p=n.partnerAttributionID,h=n.forceRestAPI,m=void 0!==h&&h,g=n.experiments;return Object(c.c)().info("patch_order_"+b()+"_"+(_()?"called":"not_called"),{orderID:e}),Object(c.c)().info("patch_order_"+b()+"_"+(v()?"errored":"did_not_error"),{orderID:e,err:Object(i.v)(v())}),T(e,"patch"),m&&!v()?Object(s.b)({accessToken:d,method:"PATCH",eventName:"v2_checkout_orders_patch",url:a.g+"/"+e,data:t,headers:(o={},o[u.i.PARTNER_ATTRIBUTION_ID]=p||"",o[u.i.PREFER]=u.m.REPRESENTATION,o),metricDimensions:{lsatUpgrade:w()}}).catch((function(n){var r,o,l=Object(s.d)(n);if(Object(c.c)().warn("patch_order_"+b()+"_call_rest_api_error",{restCorrID:l,orderID:e,err:Object(i.v)(n)}),E(n)&&Object(c.c)().warn("patch_order_"+b()+"_invalid_resource_id_error",{restCorrID:l,orderID:e,err:Object(i.v)(n)}),g.disableSmartAPI)throw n;return o=Array.isArray(t)?{patch:t,facilitatorAccessToken:d}:Object(y.a)({},t,{facilitatorAccessToken:d}),Object(s.c)({accessToken:f,method:"post",eventName:"order_patch",url:a.i.ORDER+"/"+e+"/patch",json:{data:o},headers:(r={},r[u.i.CLIENT_CONTEXT]=e,r),metricDimensions:{lsatUpgrade:w(),smartApiType:"fallback"}}).then((function(t){var n=Object(s.e)(t);return Object(c.c)().info("patch_order_"+b()+"_smart_fallback_success",{smartCorrID:n,restCorrID:l,orderID:e}),t.data})).catch((function(t){var r=Object(s.d)(n);throw Object(c.c)().info("patch_order_"+b()+"_smart_fallback_error",{smartCorrID:r,restCorrID:l,orderID:e,err:Object(i.v)(t)}),t}))})).finally((function(){Object(c.c)().flush()})):(Object(c.c)().info("lsat_upgrade_false"),l=Array.isArray(t)?{patch:t,facilitatorAccessToken:d}:Object(y.a)({},t,{facilitatorAccessToken:d}),Object(s.c)({accessToken:f,method:"post",eventName:"order_patch",url:a.i.ORDER+"/"+e+"/patch",json:{data:l},headers:(r={},r[u.i.CLIENT_CONTEXT]=e,r),metricDimensions:{lsatUpgrade:w(),smartApiType:"default"}}).then((function(e){return e.data})).finally((function(){Object(c.c)().flush()})))}function D(e){var t=e.clientID,n=e.orderID,r=e.data;return Object(s.a)({name:"UpdateShipping",query:"\n mutation UpdateShipping(\n $clientID: String!\n $patch: [JSON]!\n $token: String!\n ) {\n updateShipping(\n clientID: $clientID,\n patch: $patch,\n token: $token,\n )\n }\n ",variables:{clientID:t,patch:r,token:n}})}function P(e,t,n){var r,i=n.facilitatorAccessToken,o=n.partnerAttributionID;return Object(s.b)({accessToken:i,method:"post",eventName:"order_confirm_payment_source",url:a.g+"/"+e+"/confirm-payment-source",data:t,headers:(r={},r[u.i.PARTNER_ATTRIBUTION_ID]=o||"",r[u.i.PREFER]=u.m.REPRESENTATION,r)})}function k(e){return Object(s.c)({authenticated:!1,method:"post",eventName:"payment_ectoken",url:a.i.PAYMENT+"/"+e+"/ectoken"}).then((function(e){return e.data.token}))}function R(e){return Object(s.c)({authenticated:!1,method:"post",eventName:"billagmt_subscriptions_cartid",url:a.i.SUBSCRIPTION+"/"+e+"/cartid"}).then((function(e){return e.data.token}))}var j=Object(i.o)((function(e){var t;return Object(s.a)({name:"GetCheckoutDetails",query:"\n query GetCheckoutDetails($orderID: String!) {\n checkoutSession(token: $orderID) {\n cart {\n billingType\n intent\n paymentId\n billingToken\n amounts {\n total {\n currencyValue\n currencyCode\n currencyFormatSymbolISOCurrency\n }\n }\n supplementary {\n initiationIntent\n }\n category\n }\n flags {\n isChangeShippingAddressAllowed\n }\n payees {\n merchantId\n email {\n stringValue\n }\n }\n }\n }\n ",variables:{orderID:e},headers:(t={},t[u.i.CLIENT_CONTEXT]=e,t)})})),x=function(e){var t;return Object(s.a)({name:"GetCheckoutDetails",query:"\n query GetCheckoutDetails($orderID: String!) {\n checkoutSession(token: $orderID) {\n cart {\n billingType\n intent\n paymentId\n billingToken\n amounts {\n total {\n currencyValue\n currencyCode\n currencyFormatSymbolISOCurrency\n }\n }\n supplementary {\n initiationIntent\n }\n category\n shippingAddress {\n firstName\n lastName\n line1\n line2\n city\n state\n postalCode\n country\n }\n shippingMethods {\n id\n amount {\n currencyCode\n currencyValue\n }\n label\n selected\n type\n }\n }\n flags {\n isChangeShippingAddressAllowed\n }\n payees {\n merchantId\n email {\n stringValue\n }\n }\n }\n }\n ",variables:{orderID:e},headers:(t={},t[u.i.CLIENT_CONTEXT]=e,t)})};function V(e,t){return function(e,t){var n,r=t.facilitatorAccessToken,i=t.partnerAttributionID;return Object(c.c)().info("rest_api_create_payment_id"),Object(s.b)({accessToken:r,method:"post",eventName:"v1_payments_payment_create",url:""+a.h,data:e,headers:(n={},n[u.i.PARTNER_ATTRIBUTION_ID]=i||"",n)}).then((function(e){var t,n=e&&e.id;if(!n)throw new Error("Payment Api response error:\n\n"+JSON.stringify(e,null,4));return Object(c.c)().track(((t={})[o.e.TRANSITION]=u.g.CREATE_PAYMENT,t[o.e.CONTEXT_TYPE]=u.d.PAYMENT_ID,t[o.e.TOKEN]=n,t[o.e.CONTEXT_ID]=n,t)),e}))}(e,{facilitatorAccessToken:t.facilitatorAccessToken,partnerAttributionID:t.partnerAttributionID}).then((function(e){if(e.links&&e.links.length)for(var t=0;tc.indexOf(d))){var r=[t];r.push(n),(n.error||n.warning)&&r.push("\n\n",n.error||n.warning);try{window.console[e]&&window.console[e].apply?window.console[e].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(e){}}}function S(){return i.a.try((function(){if(Object(o.k)()&&"file:"!==window.location.protocol&&(y.length||g.length||E.length)){for(var e={},n=0;n=0||(i[n]=e[n]);return i}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";var r=n(20),i=n(15).get,o=n(15).set,a=n(48),c=n(77),u=n(78);function s(e){this.isFormatted=!1,this.inputElement=e.element,this.formatter=new u(e.pattern),this._attachListeners()}function l(e){return!e.key&&!e.keyCode}s.prototype.getUnformattedValue=function(e){var t=this.inputElement.value;return(e||this.isFormatted)&&(t=this.formatter.unformat({value:this.inputElement.value,selection:{start:0,end:0}}).value),t},s.prototype.setPattern=function(e){this._unformatInput(),this.formatter=new u(e),this._reformatInput()},s.prototype._attachListeners=function(){var e=this;e.inputElement.addEventListener("keydown",(function(t){l(t)&&(e.isFormatted=!1),r(t)||e._isDeletion(t)&&e._unformatInput(t)})),e.inputElement.addEventListener("keypress",(function(t){l(t)&&(e.isFormatted=!1),r(t)||e._unformatInput(t)})),e.inputElement.addEventListener("keyup",(function(t){e._reformatInput(t)})),e.inputElement.addEventListener("input",(function(t){(t instanceof CustomEvent||!t.isTrusted)&&(e.isFormatted=!1),e._reformatInput(t)})),e.inputElement.addEventListener("paste",this._pasteEventHandler.bind(this))},s.prototype._isDeletion=function(e){return c(e)||a(e)},s.prototype._reformatInput=function(){var e,t;this.isFormatted||(this.isFormatted=!0,t=this.formatter.format({selection:i(e=this.inputElement),value:e.value}),e.value=t.value,o(e,t.selection.start,t.selection.end),this._afterReformatInput(t))},s.prototype._afterReformatInput=function(){},s.prototype._unformatInput=function(){var e,t,n;this.isFormatted&&(this.isFormatted=!1,n=i(e=this.inputElement),t=this.formatter.unformat({selection:n,value:e.value}),e.value=t.value,o(e,t.selection.start,t.selection.end))},s.prototype._prePasteEventHandler=function(e){e.preventDefault()},s.prototype._postPasteEventHandler=function(){this._reformatAfterPaste()},s.prototype._pasteEventHandler=function(e){var t,n,r="";this._prePasteEventHandler(e),this._unformatInput(),e.clipboardData?r=e.clipboardData.getData("Text"):window.clipboardData&&(r=window.clipboardData.getData("Text")),t=i(this.inputElement),(n=this.inputElement.value.split("")).splice(t.start,t.end-t.start,r),n=n.join(""),this.inputElement.value=n,o(this.inputElement,t.start+r.length,t.start+r.length),this._postPasteEventHandler()},s.prototype._reformatAfterPaste=function(){var e=document.createEvent("Event");this._reformatInput(),e.initEvent("input",!0,!0),this.inputElement.dispatchEvent(e)},s.prototype._getStateToFormat=function(){var e=this.inputElement,t=i(e),n={selection:t,value:e.value};return this._stateToFormat?(n=this._stateToFormat,delete this._stateToFormat):t.start===e.value.length&&(n=this.formatter.unformat(n)),n},e.exports=s},function(e,t,n){"use strict";var r=n(15).get;e.exports=function(e){var t=e.currentTarget||e.srcElement,n=r(t),i=0===n.start,o=n.start===t.value.length,a=!0===e.shiftKey;switch(e.key){case void 0:case"Unidentified":case"":break;case"Backspace":return i;case"Del":case"Delete":return o;default:return 1!==e.key.length}switch(e.keyCode){case 9:case 19:case 20:case 27:case 39:case 45:return!0;case 33:case 34:case 35:case 36:case 37:case 38:case 40:return!a;case 8:return i;case 46:return o;default:return!1}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(4);function i(e){var t=e.onInit;return function(e){var n=!0;return{initPromise:r.a.try((function(){if(t)return t(e,(i=function(e){n=e},{enable:function(){return r.a.try((function(){return i(!0)}))},disable:function(){return r.a.try((function(){return i(!1)}))}}));var i})),isEnabled:function(){return n}}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(4),i=(n(0),n(3));function o(e){var t=e.onClick;if(t)return Object(i.o)((function(e){var n;return t((n={fundingSource:e.fundingSource},{fundingSource:n.fundingSource}),{resolve:function(){return r.a.try((function(){return!0}))},reject:function(){return r.a.try((function(){return!1}))}}).then((function(e){return!1!==e}))}))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(4),i=n(3);function o(e){var t=e.onError,n=t?Object(i.b)(t):i.p;return function(e){return r.a.try((function(){return n(e)}))}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return a})),n(4);var r=n(7),i=n(6),o=function(e){var t=e.clientID,n=e.vaultSetupToken,r=e.paymentSource,o=e.idToken;return Object(i.a)({name:"UpdateVaultSetupToken",query:"\n mutation UpdateVaultSetupToken(\n $clientID: String!\n $vaultSetupToken: String!\n $paymentSource: PaymentSource\n $idToken: String\n ) {\n updateVaultSetupToken(\n clientId: $clientID\n vaultSetupToken: $vaultSetupToken\n paymentSource: $paymentSource\n idToken: $idToken\n ) {\n id,\n status,\n links {\n rel, href\n }\n }\n }",variables:{clientID:t,vaultSetupToken:n,paymentSource:r,idToken:o}})};function a(e){return Object(i.c)({authenticated:!1,method:"post",eventName:"vault_ectoken",url:r.i.VAULT+"/"+e+"/ectoken"}).then((function(e){return e.data.token}))}},function(e,t,n){"use strict";function r(e){if(null==e)throw new TypeError("Cannot destructure undefined")}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(e,t,n){return{isValid:e,isPotentiallyValid:t,isCurrentYear:n||!1}}Object.defineProperty(t,"__esModule",{value:!0}),t.expirationYear=void 0,t.expirationYear=function(e,t){var n;if(void 0===t&&(t=19),"string"!=typeof e)return r(!1,!1);if(""===e.replace(/\s/g,""))return r(!1,!0);if(!/^\d*$/.test(e))return r(!1,!1);var i=e.length;if(i<2)return r(!1,!0);var o=(new Date).getFullYear();if(3===i)return r(!1,e.slice(0,2)===String(o).slice(0,2));if(i>4)return r(!1,!1);var a=parseInt(e,10),c=Number(String(o).substr(2,2)),u=!1;if(2===i){if(String(o).substr(0,2)===e)return r(!1,!0);n=c===a,u=a>=c&&a<=c+t}else 4===i&&(n=o===a,u=a>=o&&a<=o+t);return r(u,u,n)}},function(e,t,n){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&n<13;return r(i,i,i&&n>=t)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n(0);var r=n(4),i=n(2),o=n(21),a=n(22),c=n(23);function u(e){var t=e.branded,n=window.xprops,u=n.uid,s=n.env,l=n.vault,d=void 0!==l&&l,f=n.commit,p=n.locale,h=n.platform,_=n.sessionID,v=n.clientID,m=n.partnerAttributionID,y=n.merchantRequestedPopupsDisabled,g=n.clientMetadataID,E=n.sdkCorrelationID,b=n.getParentDomain,w=n.clientAccessToken,T=n.getPopupBridge,O=n.getPrerenderDetails,I=n.getPageUrl,S=n.enableThreeDomainSecure,A=n.enableVaultInstallments,C=n.enableNativeCheckout,N=void 0!==C&&C,D=n.remember,P=n.stageHost,k=n.apiStageHost,R=n.getParent,j=n.fundingSource,x=n.currency,V=n.connect,L=n.intent,F=n.merchantID,M=n.amount,U=n.userIDToken,B=n.enableFunding,H=n.disableFunding,z=n.disableCard,W=n.disableAutocomplete,Y=n.wallet,q=n.paymentMethodToken,K=void 0===q?n.paymentMethodNonce:q,G=n.getQueriedEligibleFunding,$=void 0===G?function(){return r.a.resolve([])}:G,X=n.storageID,J=n.applePay,Q=n.userExperienceFlow,Z=n.allowBillingPayments,ee=n.paymentRequest,te=n.disableSetCookie,ne=void 0!==te&&te,re=Object(o.a)({onInit:n.onInit}),ie="function"==typeof b?b():"unknown";B=B||[],H=H||[];var oe=Object(a.a)({onClick:n.onClick}),ae=X&&Object(i.g)()?X:Object(i.e)();return{uid:u,env:s,vault:d,commit:f,clientAccessToken:w,locale:p,sessionID:_,clientID:v,partnerAttributionID:m,clientMetadataID:g,sdkCorrelationID:E,merchantDomain:ie,platform:h,currency:x,intent:L,wallet:Y,merchantRequestedPopupsDisabled:y,getPopupBridge:T,getPrerenderDetails:O,getPageUrl:I,rememberFunding:D,getParent:R,connect:V,fundingSource:j,enableFunding:B,disableFunding:H,disableCard:z,disableAutocomplete:W,getQueriedEligibleFunding:$,amount:M,userIDToken:U,enableThreeDomainSecure:S,enableNativeCheckout:N,enableVaultInstallments:A,onClick:oe,onInit:re,onError:Object(c.a)({onError:n.onError}),stageHost:P,apiStageHost:k,standaloneFundingSource:j,paymentMethodToken:K,branded:t,stickinessID:ae,applePay:J,userExperienceFlow:Q,allowBillingPayments:Z,paymentRequest:ee,merchantID:F,disableSetCookie:ne}}},function(e,t,n){"use strict";n(5),n(4),n(3),n(0),n(10),n(8),n(1),n(2),n(7),n(24)},function(e,t,n){"use strict";n(4),n(3),n(0),n(8),n(1),n(2)},function(e,t,n){"use strict";n(0)},function(e,t,n){"use strict";n(0),n(8),n(2)},function(e,t,n){"use strict";n(3),n(4),n(0),n(1),n(2)},function(e,t,n){"use strict";n(5),n(4),n(3),n(0),n(8),n(1),n(2),n(7),n(13)},function(e,t,n){"use strict";n(4),n(3),n(0),n(2),n(1),n(8),n(13)},function(e,t,n){"use strict";n(3),n(4),n(0),n(2),n(1),n(13)},function(e,t,n){"use strict";n(25),n(5),n(18),n(4),n(0),n(8),n(1),n(2),n(11),n(14)},function(e,t,n){"use strict";n(25),n(5),n(18),n(4),n(0),n(8),n(1),n(2),n(11),n(14)},function(e,t,n){"use strict";n(4)},function(e,t,n){"use strict";n(4),n(0)},function(e,t,n){"use strict";n(4)},function(e,t,n){"use strict";n(4),n(2)},function(e,t,n){"use strict";n(4),n(0)},function(e,t){},function(e,t,n){"use strict";var r=window.navigator&&window.navigator.userAgent,i=n(67),o=n(68),a=n(71),c=n(72),u=/Version\/\d\.\d* Chrome\/\d*\.0\.0\.0/;e.exports={isIE9:c,isAndroidChrome:function(e){var t=e||r;return i(t)&&o(t)},isIos:a,isKitKatWebview:function(e){var t=e||r;return i(t)&&u.test(t)},isSamsungBrowser:function(e){return/SamsungBrowser/.test(e=e||r)||function(e){return!o(e)&&e.indexOf("Samsung")>-1}(e)}}},function(e,t,n){"use strict";e.exports=function(e){return"Backspace"===e.key||8===e.keyCode}},function(e,t,n){"use strict";var r=n(20),i=n(19),o=n(15).set;function a(e){i.call(this,e)}(a.prototype=Object.create(i.prototype)).constructor=a,a.prototype._attachListeners=function(){var e=this;e.inputElement.addEventListener("keydown",(function(t){r(t)||e._unformatInput(t)})),e.inputElement.addEventListener("keypress",(function(t){r(t)||e._unformatInput(t)})),e.inputElement.addEventListener("keyup",(function(t){e._reformatInput(t)})),e.inputElement.addEventListener("input",(function(t){e._reformatInput(t)})),e.inputElement.addEventListener("paste",this._pasteEventHandler.bind(this))},a.prototype._prePasteEventHandler=function(){},a.prototype._postPasteEventHandler=function(){setTimeout(this._reformatAfterPaste.bind(this),0)},a.prototype._afterReformatInput=function(e){var t=this.inputElement;setTimeout((function(){var n=e.selection;o(t,n.end,n.end)}),0)},e.exports=a},function(e,t,n){"use strict";var r=n(30);n.d(t,"getProps",(function(){return r.a})),n(31),n(32),n(33),n(34),n(35),n(36),n(37),n(21),n(38),n(11),n(39),n(40),n(22),n(23),n(41),n(42),n(43),n(44),n(45),n(46)},function(e,t,n){e.exports=n(66)},function(e,t,n){"use strict";e.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.addMatchingCardsToResults=void 0;var r=n(28),i=n(54);t.addMatchingCardsToResults=function(e,t,n){var o,a;for(o=0;o=a&&(u.matchStrength=a),n.push(u);break}}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.matches=void 0,t.matches=function(e,t){return Array.isArray(t)?function(e,t,n){var r=String(t).length,i=e.substr(0,r),o=parseInt(i,10);return t=parseInt(String(t).substr(0,i.length),10),n=parseInt(String(n).substr(0,i.length),10),o>=t&&o<=n}(e,t[0],t[1]):function(e,t){return(t=String(t)).substring(0,e.length)===e.substring(0,t.length)}(e,t)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isValidInputType=void 0,t.isValidInputType=function(e){return"string"==typeof e||e instanceof String}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findBestMatch=void 0,t.findBestMatch=function(e){return function(e){var t=e.filter((function(e){return e.matchStrength})).length;return t>0&&t===e.length}(e)?e.reduce((function(e,t){return e?Number(e.matchStrength)255?i(!1,!1):r.test(e)?i(!1,!0):i(!0,!0)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cardNumber=void 0;var r=n(59),i=n(27);function o(e,t,n){return{card:e,isPotentiallyValid:t,isValid:n}}t.cardNumber=function(e,t){var n,a;if(void 0===t&&(t={}),"string"!=typeof e&&"number"!=typeof e)return o(null,!1,!1);var c=String(e).replace(/-|\s/g,"");if(!/^\d*$/.test(c))return o(null,!1,!1);var u=i(c);if(0===u.length)return o(null,!1,!1);if(1!==u.length)return o(null,!0,!1);var s=u[0];if(t.maxLength&&c.length>t.maxLength)return o(s,!1,!1);n=s.type===i.types.UNIONPAY&&!0!==t.luhnValidateUnionPay||r(c),a=Math.max.apply(null,s.lengths),t.maxLength&&(a=Math.min(t.maxLength,a));for(var l=0;l=0;)t=parseInt(e.charAt(i),10),r&&(t*=2)>9&&(t=t%10+1),r=!r,n+=t,i--;return n%10==0}},function(e,t,n){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n1||1===a&&Number(n[1])>2?1:1===a?(o=n.substr(1),r.expirationYear(o).isPotentiallyValid?1:2):5===n.length?1:n.length>5?2:1),u=e.substr(0,c);return{month:u,year:e.substr(u.length)}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isArray=void 0,t.isArray=Array.isArray||function(e){return"[object Array]"==={}.toString.call(e)}},function(e,t,n){"use strict";function r(e,t){return{isValid:e,isPotentiallyValid:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.cvv=void 0,t.cvv=function(e,t){return void 0===t&&(t=3),t=t instanceof Array?t:[t],"string"!=typeof e?r(!1,!1):/^\d*$/.test(e)?function(e,t){for(var n=0;nfunction(e){for(var t=3,n=0;nt?e[n]:t;return t}(t)?r(!1,!1):r(!0,!0):r(!1,!1)}},function(e,t,n){"use strict";function r(e,t){return{isValid:e,isPotentiallyValid:t}}Object.defineProperty(t,"__esModule",{value:!0}),t.postalCode=void 0,t.postalCode=function(e,t){void 0===t&&(t={});var n=t.minLength||3;return"string"!=typeof e?r(!1,!1):r(!(e.length1&&a.zoomHeight&&a.zoomHeight[n]?-1!==a.zoomHeight[n].indexOf(o):-1!==a.textSizeHeights.indexOf(o)||-1!==a.textSizeHeightsNoTabs.indexOf(o))}return!1}function w(e){if(void 0===e&&(e=i()),v(e)){var t=b(e),n=m(e)?r[window.outerHeight]:null;if(!n)return!1;var o=window.innerHeight,a=Math.round(window.screen.width/window.innerWidth*100)/100,c=Math.round(o*a),u=n.maybeSafari,s=!1;return a>1&&u[a]&&-1!==u[a].indexOf(c)&&(s=!0),t||s}return!1}function T(e){return void 0===e&&(e=i()),!!_(e)&&/Version\/[\d.]+/.test(e)&&!h(e)}function O(){return!!window.document.documentMode||Boolean(window.navigator&&window.navigator.userAgent&&/Edge|MSIE|rv:11/i.test(window.navigator.userAgent))}function I(){var e=window.document.querySelector('meta[http-equiv="X-UA-Compatible"]'),t=window.document.querySelector('meta[content="IE=edge"]');return!(!e||!t)}function S(){return!("undefined"==typeof process||!process.versions||!process.versions.electron)}function A(){if(window.document.documentMode)try{var e=window.status;return window.status="testIntranetMode","testIntranetMode"===window.status&&(window.status=e,!0)}catch(e){return!1}return!1}function C(){var e=i();return/Macintosh.*AppleWebKit(?!.*Safari)/i.test(e)}function N(e){return void 0===e&&(e=i()),!(u(e)||E(e)||T(e)||h(e)||f(e)||p(e)||l(e)||g(e)||S()||C()||s())}function D(e){return void 0===e&&(e=i()),/Chrome|Chromium|CriOS/.test(e)&&!/SamsungBrowser|Silk|EdgA/.test(e)}function P(e){return void 0===e&&(e=i()),/Safari/.test(e)&&!D(e)&&!/Silk|FxiOS|EdgiOS/.test(e)}function k(){try{if(window.ApplePaySession&&window.ApplePaySession.supportsVersion(3)&&window.ApplePaySession.canMakePayments())return!0}catch(e){return!1}return!1}function R(e){return-1===window.document.cookie.indexOf(e)}function j(e,t){return(j=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function x(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,j(e,t)}function V(){return(V=Object.assign||function(e){for(var t=1;t>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,t={};return Object.freeze(t),e.set(t,"__testvalue__"),"__testvalue__"===e.get(t)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var t=e.prototype;return t._cleanupClosedWindows=function(){for(var e=this.weakmap,t=this.keys,n=0;n=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var n=e&&e.stack,r=e&&e.message;if(n&&r)return-1!==n.indexOf(r)?n:r+"\n"+n;if(n)return n;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+We(e,t+1)}}function Ye(e){var t="";return e?e instanceof Error?e.message||t:"string"==typeof e.message&&e.message||t:t}function qe(e){return"string"==typeof e?e:e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}function Ke(e,t){var n=(e=e.split("://")[1]).indexOf(t);return-1!==n&&e.slice(n)===t}function Ge(e,t,n){var r=e[t];e[t]=function(){var e=arguments,t=this;return n({context:this,args:[].slice.call(arguments),original:r,callOriginal:function(){return r.apply(t,e)}})}}function $e(e,t){if(!t)return e;if(Object.assign)return Object.assign(e,t);for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function Xe(e){if(Object.values)return Object.values(e);var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}Re.clear=function(){ke=Pe};var Je=Re(Xe);function Qe(e,t){return Math.round(e*t/100)}function Ze(){return Math.min.apply(Math,arguments)}function et(){return Math.max.apply(Math,arguments)}function tt(e,t){var n=e%t;return n?e-n+t:e}function nt(e,t,n){var r=[];return e.replace(t,(function(e){r.push(n?n.apply(null,arguments):e)})),r}function rt(e){return"data:image/svg+xml;base64,"+Oe(e)}function it(e,t){void 0===t&&(t=Boolean);var n={};for(var r in e)e.hasOwnProperty(r)&&t(e[r],r)&&(n[r]=e[r]);return n}function ot(e){return e}function at(e,t){var n=[];return e.replace(t,(function(e){return n.push(e),""})),n}function ct(e,t){var n,r;return void 0===t&&(t=50),Te((function(){r&&clearTimeout(r);var i=n=n||new Y;return r=setTimeout((function(){n=null,r=null,Y.try(e).then((function(e){i.resolve(e)}),(function(e){i.reject(e)}))}),t),i}),we(e)+"::promiseDebounced")}function ut(e,t){var n;return function r(){n=setTimeout((function(){e(),r()}),t)}(),{cancel:function(){clearTimeout(n)}}}function st(e){return Boolean(e.match(/^[0-9]+$/))}function lt(e){return Boolean(e.match(/^[0-9]+\.[0-9]+$/))}function dt(e){return e.toString()}function ft(e){return"true"===e||"false"!==e&&(st(e)?parseInt(e,10):lt(e)?parseFloat(e):e)}function pt(e,t,n){for(var r in void 0===t&&(t=""),void 0===n&&(n={}),t=t?t+".":t,e)e.hasOwnProperty(r)&&null!=e[r]&&"function"!=typeof e[r]&&(e[r]&&Array.isArray(e[r])&&e[r].length&&e[r].every((function(e){return"object"!=typeof e}))?n[""+t+r+"[]"]=e[r].join(","):e[r]&&"object"==typeof e[r]?n=pt(e[r],""+t+r,n):n[""+t+r]=dt(e[r]));return n}function ht(e){var t={};for(var n in e)if(e.hasOwnProperty(n)&&"string"==typeof e[n]){var r=e[n];n.match(/^.+\[\]$/)?(n=n.slice(0,-2),r=r.split(",").map(ft)):r=ft(r);for(var i=t,o=n.split("."),a=0;a1?n-1:0),i=1;i1?r-1:0),o=1;o-1}(n))return n;var r=n.match(ye);return r&&he.test(r[0])?Ee:n}function qt(){var e=document.body;if(!e)throw new Error("Body element not found");return e}function Kt(){return Boolean(document.body)&&"complete"===document.readyState}function Gt(){return Boolean(document.body)&&"interactive"===document.readyState}function $t(e){return encodeURIComponent(e)}function Xt(){return Le(Xt,(function(){return new Y((function(e){Kt()&&e(),window.addEventListener("load",(function(){return e()}))}))}))}var Jt=Re((function(){return new Y((function(e){if(Kt()||Gt())return e();var t=setInterval((function(){if(Kt()||Gt())return clearInterval(t),e()}),10)}))}));function Qt(){return Y.try((function(){return document.body?document.body:Jt().then((function(){if(document.body)return document.body;throw new Error("Document ready but document.body not present")}))}))}function Zt(e){return Le(Zt,(function(){var t={};if(!e)return t;if(-1===e.indexOf("="))return t;for(var n=0,r=e.split("&");n1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function ln(){return Boolean(sn())}function dn(){return Jt().then((function(){var e=sn();if(e){var t=e.timing;return t.connectEnd&&t.domInteractive?t.domInteractive-t.connectEnd:void 0}}))}function fn(e){return void 0===e&&(e=""),e.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function pn(){return"undefined"!=typeof window&&void 0!==window.location}function hn(e,t){return void 0===t&&(t=window.document),[].slice.call(t.querySelectorAll(e))}function _n(e,t){e.addEventListener("touchstart",Fe,{passive:!0}),e.addEventListener("click",t),e.addEventListener("keypress",(function(e){if(e.keyCode===de.ENTER||e.keyCode===de.SPACE)return t(e)}))}function vn(e){var t=e.host,n=void 0===t?window.location.host:t,r=e.path,i=e.reverse,o=void 0!==i&&i;return Le(vn,(function(){var e=""+n+r,t=[].slice.call(document.getElementsByTagName("script"));o&&t.reverse();for(var i=0;ir&&(n=null),n||(n={guid:i||Se(),created:o}),t.__session__=n,e(n)}))}return{getState:a,getID:c,isStateFresh:function(){return c()===o},getSessionState:function(e){return u((function(t){return t.state=t.state||{},e(t.state)}))},getSessionID:function(){return u((function(e){return e.guid}))}}}),[{name:t,lifetime:r}])}function fr(){return dr({name:"belter_experiment"})}function pr(e){return fr().getSessionState((function(t){return t.loggedBeacons=t.loggedBeacons||[],-1===t.loggedBeacons.indexOf(e)&&(t.loggedBeacons.push(e),!0)}))}function hr(e){return Math.floor(Math.random()*e)}function _r(e){var t,n=e.name,r=e.sample,i=void 0===r?50:r,o=e.logTreatment,a=void 0===o?Fe:o,c=e.logCheckpoint,u=void 0===c?Fe:c,s=e.sticky,l=void 0===s||s?function(e){return fr().getState((function(t){return t.throttlePercentiles=t.throttlePercentiles||{},t.throttlePercentiles[e]=t.throttlePercentiles[e]||hr(100),t.throttlePercentiles[e]}))}(n):hr(100),d=n+"_"+(t=l=50||i<=l&&l<2*i?"control":"throttle"),f=!1,p=!1;try{window.localStorage&&window.localStorage.getItem(n)&&(p=!0)}catch(e){}var h={isEnabled:function(){return"test"===t||p},isDisabled:function(){return"test"!==t&&!p},getTreatment:function(){return d},log:function(e,t){return void 0===t&&(t={}),f?(pr(d+"_"+JSON.stringify(t))&&a({name:n,treatment:d,payload:t,throttle:l}),pr(d+"_"+e+"_"+JSON.stringify(t))&&u({name:n,treatment:d,checkpoint:e,payload:t,throttle:l}),h):h},logStart:function(e){return void 0===e&&(e={}),f=!0,h.log("start",e)},logComplete:function(e){return void 0===e&&(e={}),h.log("complete",e)}};return h}function vr(e){var t=e.name,n=e.version,r=void 0===n?"latest":n,i=Ae(),o="__"+t+"__"+r+"_global__",a=i[o]=i[o]||{};return{get:function(e,t){return t=t||{},a[e]=a[e]||t}}}var mr=[];function yr(e){var t=e.url,n=e.method,r=void 0===n?"get":n,i=e.headers,o=void 0===i?{}:i,a=e.json,c=e.data,u=e.body,s=e.win,l=void 0===s?window:s,d=e.timeout,f=void 0===d?0:d;return new Y((function(e,n){if(a&&c||a&&u||c&&a)throw new Error("Only options.json or options.data or options.body should be passed");for(var i={},s=0,d=Object.keys(o);si.length));t++)if(n.isPermaChar)null==r&&a.length!==n.index||(a+=n.value,n.index<=c.start&&c.start++,n.index<=c.end&&c.end++);else for(;o2&&(c.children=arguments.length>3?r.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(a in e.defaultProps)void 0===c[a]&&(c[a]=e.defaultProps[a]);return y(e,c,i,o,null)}function y(e,t,n,r,a){var c={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:null==a?++o:a,__i:-1,__u:0};return null==a&&null!=i.vnode&&i.vnode(c),c}function g(e){return e.children}function E(e,t){this.props=e,this.context=t}function b(e,t){if(null==t)return e.__?b(e.__,e.__i+1):null;for(var n;tt&&a.sort(s));O.__r=0}function I(e,t,n,r,i,o,a,c,u,s,l){var p,h,_,v,m,y=r&&r.__k||f,g=t.length;for(n.__d=u,S(n,t,y),u=n.__d,p=0;p0?y(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i)?(i.__=e,i.__b=e.__b+1,c=C(i,n,a=r+d,l),i.__i=c,o=null,-1!==c&&(l--,(o=n[c])&&(o.__u|=131072)),null==o||null===o.__v?(-1==c&&d--,"function"!=typeof i.type&&(i.__u|=65536)):c!==a&&(c===a+1?d++:c>a?l>u-a?d+=c-a:d--:d=c(null!=u&&0==(131072&u.__u)?1:0))for(;a>=0||c=0){if((u=t[a])&&0==(131072&u.__u)&&i==u.key&&o===u.type)return a;a--}if(c=n.__.length&&n.__.push({__V:Y}),n.__[e]}function Q(e){return z=1,function(e,t,n){var r=J(M++,2);if(r.t=e,!r.__c&&(r.__=[ce(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=U,!U.u)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=r.__c.__H.__.filter((function(e){return e.__c}));if(i.every((function(e){return!e.__N})))return!o||o.call(this,e,t,n);var a=!1;return i.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(a=!0)}})),!(!a&&r.__c.props===e)&&(!o||o.call(this,e,t,n))};U.u=!0;var o=U.shouldComponentUpdate,a=U.componentWillUpdate;U.componentWillUpdate=function(e,t,n){if(this.__e){var r=o;o=void 0,i(e,t,n),o=r}a&&a.call(this,e,t,n)},U.shouldComponentUpdate=i}return r.__N||r.__}(ce,e)}function Z(e,t){var n=J(M++,3);!i.__s&&ae(n.__H,t)&&(n.__=e,n.i=t,U.__H.__h.push(n))}function ee(e){return z=5,function(e,t){var n=J(M++,7);return ae(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function te(){for(var e;e=W.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(ie),e.__H.__h.forEach(oe),e.__H.__h=[]}catch(t){e.__H.__h=[],i.__e(t,e.__v)}}i.__b=function(e){U=null,q&&q(e)},i.__r=function(e){K&&K(e),M=0;var t=(U=e.__c).__H;t&&(B===U?(t.__h=[],U.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=Y,e.__N=e.i=void 0}))):(t.__h.forEach(ie),t.__h.forEach(oe),t.__h=[],M=0)),B=U},i.diffed=function(e){G&&G(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==W.push(t)&&H===i.requestAnimationFrame||((H=i.requestAnimationFrame)||re)(te)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==Y&&(e.__=e.__V),e.i=void 0,e.__V=Y}))),B=U=null},i.__c=function(e,t){t.some((function(e){try{e.__h.forEach(ie),e.__h=e.__h.filter((function(e){return!e.__||oe(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],i.__e(n,e.__v)}})),$&&$(e,t)},i.unmount=function(e){X&&X(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{ie(e)}catch(e){t=e}})),n.__H=void 0,t&&i.__e(t,n.__v))};var ne="function"==typeof requestAnimationFrame;function re(e){var t,n=function(){clearTimeout(r),ne&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);ne&&(t=requestAnimationFrame(n))}function ie(e){var t=U,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),U=t}function oe(e){var t=U;e.__c=e.__(),U=t}function ae(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function ce(e,t){return"function"==typeof t?t(e):t}var ue,se,le=n(3),de=n(2),fe=n(12),pe=n.n(fe),he=n(1),_e=n(0),ve=pe.a.creditCardType.types,me=((ue={}).single=he.h.CARD_FIELD,ue.number=he.h.CARD_NUMBER_FIELD,ue.cvv=he.h.CARD_CVV_FIELD,ue.expiry=he.h.CARD_EXPIRY_FIELD,ue.name=he.h.CARD_NAME_FIELD,ue.postal=he.h.CARD_POSTAL_FIELD,ue),ye=["name"],ge={appearance:"appearance",color:"color",direction:"direction",font:"font",fontFamily:"font-family",fontSizeAdjust:"font-size-adjust",fontSize:"font-size",fontStretch:"font-stretch",fontStyle:"font-style",fontVariantAlternates:"font-variant-alternates",fontVariantCaps:"font-variant-caps",fontVariantEastAsian:"font-variant-east-asian",fontVariantLigatures:"font-variant-ligatures",fontVariantNumeric:"font-variant-numeric",fontVariant:"font-variant",fontWeight:"font-weight",letterSpacing:"letter-spacing",lineHeight:"line-height",opacity:"opacity",outline:"outline",padding:"padding",paddingTop:"padding-top",paddingRight:"padding-right",paddingBottom:"padding-bottom",paddingLeft:"padding-left",textShadow:"text-shadow",transition:"transition",MozApperance:"-moz-appearance",MozOsxFontSmoothing:"-moz-osx-font-smoothing",MozTapHighlightColor:"-moz-tap-highlight-color",MozTransition:"-moz-transition",WebkitAppearance:"-webkit-appearance",WebkitOsxFontSmoothing:"-webkit-osx-font-smoothing",WebkitTapHighlightColor:"-webkit-tap-highlight-color",WebkitTransition:"-webkit-transition"},Ee=[/;/,/[<>]/,/\\/,/@import/i,/expression/i,/javascript/i,/url/i],be=[/^\s*$/,/supports/i,/import/i,/[{}]/,/ svg":{color:"#d9360b",width:"24px",height:"24px","margin-right":"0.25rem"},".card-field-validation-error.hidden":{visibility:"hidden"}},Ae=["billingAddress"],Ce=["aria-invalid","aria-required","disabled","placeholder"],Ne=n(16),De={inputValue:"",maskedInputValue:"",cursorStart:0,cursorEnd:0,isFocused:!1,keyStrokeCount:0,isPotentiallyValid:!0,isValid:!1},Pe={isValid:!1,isPotentiallyValid:!0};function ke(e,t,n){return e.slice(0,t)+n+e.slice(t)}function Re(e,t){if(!e)throw new TypeError(t)}function je(e){return e.replace(/\s/g,"")}function xe(e){return!Ee.some((function(t){return t.test(String(e))}))}function Ve(e){return!!Ce.includes(e.toLocaleLowerCase())||(Object(de.c)().warn("attribute_warning",{warn:'HTML Attribute "'+e+'" was ignored. See allowed attribute list.'}),!1)}function Le(e){void 0===e&&(e={});var t=[];return Object.keys(e).forEach((function(n){var r=e[n];"string"==typeof r||"number"==typeof r?t.push(" "+n+": "+r+";"):"object"==typeof r&&(t.push(n+" {"),t.push(Le(r)),t.push("}"))})),t.join("\n")}function Fe(e,t){var n=[];return n.push("/* default style */"),n.push(Le(Oe)),n.push(Le(e)),n.push("/* custom style */"),n.push(Le(function e(t){var n={};return Object.keys(t).forEach((function(r){var i,o,a=t[r];"string"==typeof a||"number"==typeof a?ge[r]?(i=ge[r],xe(a)&&(n[i]=a)):Object(Ne.values)(ge).includes(r.toLowerCase())?(i=r.toLowerCase(),xe(a)&&(n[i]=a)):Object(de.c)().warn("style_warning",{warn:'CSS property "'+r+'" was ignored. See allowed CSS property list.'}):"object"==typeof a&&(o=r,be.some((function(e){return e.test(o)}))||(n[r]=e(a)))})),n}(t))),n.join("\n")}function Me(e,t,n,r){var i,o=null==e||null==(i=e.current)?void 0:i.base;o&&(function(e){return ye.includes(e.name)}(o)&&0===o.value.length?(o.classList.remove("valid"),o.classList.remove("invalid")):t.isValid||t.isPotentiallyValid&&n?(o.classList.add("valid"),o.classList.remove("invalid")):r&&(o.classList.add("invalid"),o.classList.remove("valid")))}function Ue(e){return je(e).replace(/\D/g,"")}function Be(e){var t=je(e),n=t.split("/"),r=t;return n[1]&&2===n[1].length&&(n[1]="20"+n[1],r=n.join("/")),r}function He(e){return e.map((function(e){return{type:e.type,niceType:e.niceType,code:e.code}}))}function ze(e){var t,n;return(null==(t=e.xprops)||null==(t=t.parent)?void 0:t.uid)||(null==(n=e.xprops)?void 0:n.uid)}function We(e){if(!e||"string"!=typeof e)throw new Error("can not convert invalid expiry date: "+e);if(e.match("^[0-9]{4}-([1-9]|0[1-9]|1[0-2])$"))return e;if(e.match("^([1-9]|0[1-9]|1[0-2])/?([0-9]{4}|[0-9]{2})$")){var t=e.split("/"),n=t[0],r=t[1];return(2===r.length?"20"+r:r)+"-"+(1===n.length?"0"+n:n)}throw new Error("can not convert invalid expiry date: "+e)}function Ye(e,t){var n={card:{number:e.number,securityCode:e.cvv,expiry:We(e.expiry)}};return t&&0!==Object.keys(t).length&&(n.card.billingAddress=t.billingAddress),e.name&&(n.card.name=e.name),e.postalCode&&(n.card.billingAddress={postalCode:e.postalCode}),n}function qe(e){var t=e.split("-");return t.forEach((function(e,n){t[n]=0!==n?e.toLowerCase().replace(/^\w/,(function(e){return e.toUpperCase()})):e.toLowerCase()})),t.join("")}function Ke(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([a-z\d])(\d)/g,"$1_$2").toLowerCase()}function Ge(e){if(e.length>0){var t=pe.a.creditCardType.default(e);if(t.length>0)return t}return[Te]}function $e(e,t){var n;!function(){for(var e=arguments.length,t=new Array(e),n=0;ne.length-1)break;e=ke(e,o," ")}return e}function Xe(e,t,n){var r,i=window.xprops.fundingEligibility,o=we[t.type],a=n===he.l.VAULT_WITHOUT_PURCHASE;if(0===e.length)return!0;if(null!=i&&null!=(r=i.card)&&r.eligible&&o&&i.card.vendors&&!i.card.branded){var c=i.card.vendors[o];if(a&&null!=c&&c.vaultable&&null!=c&&c.eligible)return!0;if(!a&&null!=c&&c.eligible)return!0}return!1}pe.a.creditCardType.addCard({code:{name:"CVV",size:3},gaps:[4,8,12],lengths:[16,18,19],niceType:"Carte Bancaire",patterns:[],type:"cb-nationale"}),pe.a.creditCardType.addCard({code:{name:"CVV",size:3},gaps:[4,8,12,16],lengths:[19],niceType:"Carte Aurore",patterns:[],type:"cetelem"}),pe.a.creditCardType.addCard({code:{name:"",size:0},gaps:[4,8,12,16],lengths:[17],niceType:"Cofinoga ou Privilège",patterns:[],type:"cofinoga"}),pe.a.creditCardType.addCard({code:{name:"",size:0},gaps:[4,8],lengths:[8,9],niceType:"4 étoiles",patterns:[],type:"cofidis"});var Je={next:function(){return Ne.noop},previous:function(){return Ne.noop}};function Qe(e,t,n){window.requestAnimationFrame((function(){e.selectionStart=t,e.selectionEnd=null!=n?n:t}))}function Ze(e){return function(){Qe(e.current.base,0),setTimeout((function(){return e.current.base.focus()}))}}function et(e){return function(){var t=e.current.base.value;t&&Qe(e.current.base,t.length),setTimeout((function(){return e.current.base.focus()}))}}function tt(e,t){var n=e.target,r=n.value,i=n.selectionStart,o=e.key;0!==i||0!==r.length&&r.length===n.selectionEnd||!["Backspace","ArrowLeft"].includes(o)||t.previous(),i===r.length&&["ArrowRight"].includes(o)&&t.next()}function nt(e,t,n,r){window.xprops.export({setAttribute:function(e,n){Ve(e)&&t((function(t){var r;return Object(l.a)({},t,((r={})[e]=n,r))}))},removeAttribute:function(e){Ve(e)&&t((function(t){var n;return Object(l.a)({},t,((n={})[e]="",n))}))},addClass:function(t){var n;null==e||null==(n=e.current)||n.classList.add(t)},removeClass:function(t){var n;null==e||null==(n=e.current)||n.classList.remove(t)},clear:function(){e&&e.current&&"function"==typeof n&&n((function(e){return Object(l.a)({},e,{inputValue:""})}))},focus:function(){var t;null==e||null==(t=e.current)||t.focus()},setMessage:function(e){r.current.innerText=e}})}var rt=n(10);function it(e){try{for(var t=0,n=Object(rt.b)(window);tj.length&&" "===u[r-1]&&(s+=1,d+=1),Qe(e.target,s,d),S(a),k(Object(l.a)({},P,c,{inputValue:o,maskedInputValue:u,cursorStart:s,cursorEnd:d,contentPasted:!1,keyStrokeCount:L+1}))},onFocus:function(e){"function"==typeof h&&h(e);var t=null==W?void 0:W.current;t&&t.classList.add("display-icon");var n=$e(R),r=Object(l.a)({},P,{maskedInputValue:n,displayCardIcon:!0});k((function(e){return Object(l.a)({},e,r)}))},onBlur:function(e){var t,n,r={maskedInputValue:j,isPotentiallyValid:M,contentPasted:!1,displayCardIcon:P.inputValue.length>0},i=null==W?void 0:W.current;i&&(P.inputValue.length>0?i.classList.add("display-icon"):i.classList.remove("display-icon")),F&&(r.maskedInputValue=(n=je(t=j).slice(-4),t.replace(/\d/g,"•").slice(0,-4)+n)),"function"==typeof _&&_(e),"function"==typeof v&&v(!1),k((function(e){return Object(l.a)({},e,r)}))},onKeyDown:function(e){"function"==typeof v&&v("Enter"===e.key),u&&tt(e,a)},onPaste:function(){k((function(e){return Object(l.a)({},e,{contentPasted:!0})}))}},w)),m(At,{iconId:Nt(H.type),iconClass:"card-icon"}),m(Ct,{ariaMessageId:"card-number-field-description",ariaMessageRef:Y}))}var Pt=n(51),kt=n.n(Pt);function Rt(e){var t=e.name,n=void 0===t?"expiry":t,r=e.autocomplete,i=void 0===r?"cc-exp":r,o=e.navigation,a=void 0===o?Je:o,c=e.state,u=e.type,s=e.style,d=e.maxLength,f=e.onChange,p=e.onFocus,h=e.onBlur,_=e.onKeyDown,v=e.onValidityChange,y=e.allowNavigation,E=void 0!==y&&y,b=Q({placeholder:e.placeholder}),w=b[0],T=b[1],O=Q(Object(l.a)({},De,c)),I=O[0],S=O[1],A=I.maskedInputValue,C=I.isValid,N=I.isPotentiallyValid,D=Q({}),P=D[0],k=D[1],R=ee(),j=ee();return Z((function(){E||nt(R,T,S,j);var e=null==R?void 0:R.current;if(e){var t=new kt.a({element:e,pattern:"{{99}} / {{9999}}"});k(t)}}),[]),Z((function(){f({maskedDate:I.maskedInputValue})}),[I]),Z((function(){"function"==typeof v&&v({isValid:C,isPotentiallyValid:N}),E&&A&&C&&a.next()}),[C,N]),m(g,null,m("input",Object(l.a)({"aria-describedby":"card-expiry-field-description",name:n,autocomplete:i,inputmode:"numeric",ref:R,type:u,className:"card-field-expiry",style:s,maxLength:d,onKeyUp:function(e){var t=e.target.value,n=pe.a.expirationDate(t);t.includes("/")||(function(e,t){return 0!==e.length&&("1"===e[0]&&"/"===t||"1"!==e[0]&&"0"!==e[0])}(t,e.key)?P.setPattern("0{{9}} / {{9999}}"):P.setPattern("{{99}} / {{9999}}")),S(Object(l.a)({},I,n,{inputValue:P.getUnformattedValue(),maskedInputValue:R.current.value}))},onKeyDown:function(e){"function"==typeof _&&(_("Enter"===e.key),E&&tt(e,a))},onFocus:function(e){"function"==typeof p&&p(e)},onBlur:function(e){"function"==typeof h&&h(e),"function"==typeof _&&_(!1)},onPaste:function(){S((function(e){return Object(l.a)({},e,{contentPasted:!0})}))}},w)),m(Ct,{ariaMessageId:"card-expiry-field-description",ariaMessageRef:j}))}function jt(e){var t,n=e.name,r=void 0===n?"cvv":n,i=e.autocomplete,o=void 0===i?"cc-csc":i,a=e.navigation,c=void 0===a?Je:a,u=e.allowNavigation,s=void 0!==u&&u,d=e.state,f=e.type,p=e.style,h=e.onChange,_=e.onFocus,v=e.onBlur,y=e.onKeyDown,E=e.onValidityChange,b=Q({placeholder:e.placeholder}),w=b[0],T=b[1],O=Q(Object(l.a)({},De,d)),I=O[0],S=O[1],A=Q(Te),C=A[0],N=A[1],D=Q(!1),P=D[0],k=D[1],R=I.inputValue,j=I.keyStrokeCount,x=I.isValid,V=I.isPotentiallyValid,L=ee(),F=ee();return Z((function(){s||nt(L,T,S,F);var e=Object(de.d)();if(e){var t=ze(window);e.on("cardTypeChange",{domain:window.location.origin},(function(e){ze(e.source)===t&&N(e.data)}))}}),[]),Z((function(){h({cardCvv:I.inputValue})}),[I]),Z((function(){var e,t=pe.a.cvv(R,null==C||null==(e=C.code)?void 0:e.size);P&&(t.isPotentiallyValid=!1),S((function(e){return Object(l.a)({},e,t)}))}),[C]),Z((function(){var e,t=pe.a.cvv(R,null==C||null==(e=C.code)?void 0:e.size);P&&(t.isPotentiallyValid=!1),S((function(e){return Object(l.a)({},e,t)}))}),[C]),Z((function(){"function"==typeof E&&E({isValid:x,isPotentiallyValid:V}),s&&R&&x&&c.next()}),[x,V]),m(g,null,m("input",Object(l.a)({"aria-describedby":"card-cvv-field-description",name:r,autocomplete:o,inputmode:"numeric",ref:L,type:f,className:"card-field-cvv",value:R,style:p,maxLength:C.code.size,onKeyDown:function(e){"function"==typeof y&&y("Enter"===e.key),s&&tt(e,c)},onInput:function(e){var t,n=Ue(e.target.value),r=pe.a.cvv(n,null==C||null==(t=C.code)?void 0:t.size);S(Object(l.a)({},I,r,{inputValue:n,maskedInputValue:n,keyStrokeCount:j+1}))},onFocus:function(e){P||k(!0),"function"==typeof _&&_(e)},onBlur:function(e){"function"==typeof v&&v(e),"function"==typeof y&&y(!1)}},w,{placeholder:null!=(t=w.placeholder)?t:C.code.name})),m(Ct,{ariaMessageId:"card-cvv-field-description",ariaMessageRef:F}))}function xt(e){var t=e.name,n=void 0===t?"name":t,r=e.navigation,i=void 0===r?Je:r,o=e.allowNavigation,a=void 0!==o&&o,c=e.state,u=e.type,s=e.style,d=e.maxLength,f=e.onChange,p=e.onFocus,h=e.onBlur,_=e.onKeyDown,v=e.onValidityChange,y=Q({placeholder:e.placeholder}),E=y[0],b=y[1],w=Q(Object(l.a)({},De,c)),T=w[0],O=w[1],I=T.inputValue,S=T.keyStrokeCount,A=T.isValid,C=T.isPotentiallyValid,N=ee(),D=ee();return Z((function(){nt(N,b,O,D)}),[]),Z((function(){f({cardName:T.inputValue})}),[T]),Z((function(){"function"==typeof v&&v({isValid:A,isPotentiallyValid:C}),a&&I&&A&&i.next()}),[A,C]),m(g,null,m("input",Object(l.a)({"aria-describedby":"card-name-field-description",name:n,inputmode:"text",ref:N,type:u,className:"card-field-name",value:I,style:s,maxLength:d,onKeyDown:function(e){"function"==typeof _&&_("Enter"===e.key),a&&tt(e,i)},onInput:function(e){var t=e.target.value,n=pe.a.cardholderName(t);O(Object(l.a)({},T,n,{inputValue:t,maskedInputValue:t,keyStrokeCount:S+1}))},onFocus:function(e){"function"==typeof p&&p(e)},onBlur:function(e){"function"==typeof h&&h(e),"function"==typeof _&&_(!1)}},E)),m(Ct,{ariaMessageId:"card-name-field-description",ariaMessageRef:D}))}function Vt(e){var t=e.name,n=void 0===t?"postal":t,r=e.navigation,i=void 0===r?Je:r,o=e.allowNavigation,a=void 0!==o&&o,c=e.state,u=e.type,s=e.style,d=e.maxLength,f=e.onChange,p=e.onFocus,h=e.onBlur,_=e.onKeyDown,v=e.onValidityChange,y=e.minLength,E=Q({placeholder:e.placeholder}),b=E[0],w=E[1],T=Q(Object(l.a)({},De,c)),O=T[0],I=T[1],S=O.inputValue,A=O.keyStrokeCount,C=O.isValid,N=O.isPotentiallyValid,D=ee(),P=ee();return Z((function(){nt(D,w,I,P)}),[]),Z((function(){f({cardPostalCode:O.inputValue})}),[O]),Z((function(){"function"==typeof v&&v({isValid:C,isPotentiallyValid:N}),a&&S&&C&&i.next()}),[C,N]),m(g,null,m("input",Object(l.a)({"aria-describedby":"card-postalCode-field-description",name:n,inputmode:"numeric",ref:D,type:u,className:"card-field-postal-code",value:S,style:s,maxLength:d,onKeyDown:function(e){"function"==typeof _&&_("Enter"===e.key),a&&tt(e,i)},onInput:function(e){var t=e.target.value,n=pe.a.postalCode(t,{minLength:y});I(Object(l.a)({},O,n,{inputValue:t,keyStrokeCount:A+1}))},onFocus:function(e){"function"==typeof p&&p(e)},onBlur:function(e){"function"==typeof h&&h(e),"function"==typeof _&&_(!1)},minLength:y},b)),m(Ct,{ariaMessageId:"card-postalCode-field-description",ariaMessageRef:P}))}function Lt(e){var t,n,r=e.cspNonce,i=e.onChange,o=e.styleObject,a=void 0===o?{}:o,c=e.placeholder,u=void 0===c?{}:c,s=e.gqlErrorsObject,d=void 0===s?{}:s,f=e.autoFocusRef,p=e.autocomplete,h=Q({}),_=h[0],v=h[1],y=Q(""),E=y[0],b=y[1],w=Q(""),T=w[0],O=w[1],I=Q(""),S=I[0],A=I[1],C=Q(""),N=C[0],D=C[1],P=Q(!0),k=P[0],R=P[1],j=Q(""),x=j[0],V=j[1],L=Q(!0),F=L[0],M=L[1],U=Q(Pe),B=U[0],H=U[1],z=Q(Pe),W=z[0],Y=z[1],q=Q(Pe),K=q[0],G=q[1],$=Q(!1),X=$[0],J=$[1],te=Q(!1),ne=te[0],re=te[1],ie=ee(),oe=ee(),ae=ee(),ce=ee(),ue={next:Ze(oe),previous:function(){return Ne.noop}},se={next:Ze(ae),previous:et(ie)},le={next:function(){return Ne.noop},previous:et(oe)};Z((function(){f(ie),nt(ce,v)}),[]),Z((function(){b(Fe(Se,a))}),[a]),Z((function(){var e=d.field,t=d.errors;"number"===e&&t.length>0&&H({isPotentiallyValid:!1,isValid:!1}),"expiry"===e&&t.length>0&&Y({isPotentiallyValid:!1,isValid:!1}),"cvv"===e&&t.length>0&&G({isPotentiallyValid:!1,isValid:!1})}),[d]),Z((function(){V(F?B.isPotentiallyValid||B.isValid?W.isPotentiallyValid||W.isValid?K.isPotentiallyValid||K.isValid?"":"This security code is not valid.":"This expiration date is not valid.":"This card number is not valid.":"This card vendor is not eligible.");var e=Boolean(B.isValid&&K.isValid&&W.isValid);R(e);var t=function(e){var t=e.isNumberValid,n=e.isCvvValid,r=e.isExpiryValid,i=e.isNameValid,o=e.isPostalCodeValid,a=e.gqlErrorsObject,c=void 0===a?{}:a,u=[],s=c.field,l=c.errors;return!1===e.isCardEligible&&("number"===s&&l.length?u.push.apply(u,l):u.push("INELIGIBLE_CARD_VENDOR")),!1===t&&("number"===s&&l.length?u.push.apply(u,l):u.push("INVALID_NUMBER")),!1===r&&("expiry"===s&&l.length?u.push.apply(u,l):u.push("INVALID_EXPIRY")),!1===n&&("cvv"===s&&l.length?u.push.apply(u,l):u.push("INVALID_CVV")),!1===i&&("name"===s&&l.length?u.push.apply(u,l):u.push("INVALID_NAME")),!1===o&&("postal"===s&&l.length?u.push.apply(u,l):u.push("INVALID_POSTAL")),u}({isCardEligible:F,isNumberValid:B.isValid,isCvvValid:K.isValid,isExpiryValid:W.isValid,gqlErrorsObject:d});Me(ie,B,ne,X),Me(oe,W,ne,X),Me(ae,K,ne,X),i({value:{number:T,cvv:S,expiry:N},valid:e,errors:t})}),[T,S,N,k,B,F,K,W]),Z((function(){var e=null==ce?void 0:ce.current;e&&(ne?e.classList.add("focus"):e.classList.remove("focus"),x.length>0?e.classList.add("invalid"):e.classList.remove("invalid"))}),[ne,x]);var de=function(){J(!0),re(!0)};return m(g,null,m("style",{nonce:r},E),m(St,null),m("fieldset",Object(l.a)({ref:ce,className:"card-field"},_),m(Dt,{ref:ie,autocomplete:p,navigation:ue,type:"text",allowNavigation:!0,placeholder:null!=(t=u.number)?t:"Card number",onChange:function(e){O(e.cardNumber)},onEligibilityChange:function(e){return M(e)},onValidityChange:function(e){return H(Object(l.a)({},e))},onFocus:de,onBlur:function(){return re(!1)}}),m(Rt,{ref:oe,autocomplete:p,navigation:se,type:"text",allowNavigation:!0,placeholder:null!=(n=u.expiry)?n:"MM / YY",maxLength:"7",onChange:function(e){return D(Be(e.maskedDate))},onValidityChange:function(e){return Y(Object(l.a)({},e))},onFocus:de,onBlur:function(){return re(!1)}}),m(jt,{ref:ae,autocomplete:p,navigation:le,type:"text",allowNavigation:!0,placeholder:u.cvv,onChange:function(e){return A(e.cardCvv)},onValidityChange:function(e){return G(Object(l.a)({},e))},onFocus:de,onBlur:function(){return re(!1)}})),m(Ft,{message:x}))}function Ft(e){var t=e.message;return m("div",{className:"card-field-validation-error "+(t.length?"":"hidden")},m(At,{iconId:"icon-error"}),t)}function Mt(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.styleObject,o=void 0===i?{}:i,a=e.placeholder,c=e.autoFocusRef,u=e.autocomplete,s=e.onKeyDown,l=e.gqlErrors,d=void 0===l?[]:l,f=Q(""),p=f[0],h=f[1],_=Q(""),v=_[0],y=_[1],E=Q(!0),b=E[0],w=E[1],T=Q(Pe),O=T[0],I=T[1],S=Q([]),A=S[0],C=S[1],N=Q(!1),D=N[0],P=N[1],k=Q(!1),R=k[0],j=k[1],x=Q(!1),V=x[0],L=x[1],F=ee(),M=O.isValid,U=O.isPotentiallyValid;return Z((function(){c(F)}),[]),Z((function(){h(Fe(Ie,o))}),[o]),Z((function(){d.length>0&&I({isPotentiallyValid:!1,isValid:!1})}),[d]),Z((function(){Me(F,O,D,R),n({value:v,valid:O.isValid,isFocused:D,potentiallyValid:O.isPotentiallyValid,potentialCardTypes:A})}),[v,b,M,D,U,A]),Z((function(){r({isFocused:D})}),[D]),Z((function(){s({isInputSubmitRequest:V})}),[V]),m(g,null,m("style",{nonce:t},p),m(St,null),m(Dt,{ref:F,type:"text",autocomplete:u,placeholder:null!=a?a:"Card number",onChange:function(e){return t=e.potentialCardTypes,y(e.cardNumber),void C(t);var t},onEligibilityChange:function(e){return w(e)},onValidityChange:function(e){return I(e)},onFocus:function(){j(!0),P(!0)},onBlur:function(){return P(!1)},onKeyDown:function(e){return L(e)}}))}function Ut(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.onKeyDown,o=e.styleObject,a=void 0===o?{}:o,c=e.placeholder,u=e.autoFocusRef,s=e.autocomplete,l=e.gqlErrors,d=void 0===l?[]:l,f=Q(""),p=f[0],h=f[1],_=Q(""),v=_[0],y=_[1],E=Q(Pe),b=E[0],w=E[1],T=ee(),O=Q(!1),I=O[0],S=O[1],A=Q(!1),C=A[0],N=A[1],D=Q(!1),P=D[0],k=D[1],R=b.isValid,j=b.isPotentiallyValid;return Z((function(){u(T)}),[]),Z((function(){h(Fe(Ie,a))}),[a]),Z((function(){d.length>0&&w({isPotentiallyValid:!1,isValid:!1})}),[d]),Z((function(){Me(T,b,I,C),n({value:v,valid:b.isValid,isFocused:I,potentiallyValid:b.isPotentiallyValid})}),[v,R,I,j]),Z((function(){r({isFocused:I})}),[I]),Z((function(){i({isInputSubmitRequest:P})}),[P]),m(g,null,m("style",{nonce:t},p),m(Rt,{ref:T,type:"text",autocomplete:s,placeholder:null!=c?c:"MM / YY",maxLength:"7",onChange:function(e){return y(Be(e.maskedDate))},onValidityChange:function(e){return w(e)},onFocus:function(){N(!0),S(!0)},onBlur:function(){return S(!1)},onKeyDown:function(e){return k(e)}}))}function Bt(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.onKeyDown,o=e.styleObject,a=void 0===o?{}:o,c=e.placeholder,u=e.autoFocusRef,s=e.autocomplete,l=e.gqlErrors,d=void 0===l?[]:l,f=Q(""),p=f[0],h=f[1],_=Q(""),v=_[0],y=_[1],E=Q(Pe),b=E[0],w=E[1],T=ee(),O=Q(!1),I=O[0],S=O[1],A=Q(!1),C=A[0],N=A[1],D=Q(!1),P=D[0],k=D[1],R=b.isValid,j=b.isPotentiallyValid;return Z((function(){u(T)}),[]),Z((function(){h(Fe(Ie,a))}),[a]),Z((function(){d.length>0&&w({isPotentiallyValid:!1,isValid:!1})}),[d]),Z((function(){Me(T,b,I,C),n({value:v,valid:b.isValid,isFocused:I,potentiallyValid:b.isPotentiallyValid})}),[v,R,I,j]),Z((function(){r({isFocused:I})}),[I]),Z((function(){i({isInputSubmitRequest:P})}),[P]),m(g,null,m("style",{nonce:t},p),m(jt,{ref:T,type:"text",autocomplete:s,placeholder:c,onChange:function(e){return y(e.cardCvv)},onValidityChange:function(e){return w(e)},onFocus:function(){N(!0),S(!0)},onBlur:function(){return S(!1)},onKeyDown:function(e){return k(e)}}))}function Ht(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.onKeyDown,o=e.styleObject,a=void 0===o?{}:o,c=e.placeholder,u=e.autoFocusRef,s=e.gqlErrors,l=void 0===s?[]:s,d=Q(""),f=d[0],p=d[1],h=Q(""),_=h[0],v=h[1],y=Q(Pe),E=y[0],b=y[1],w=ee(),T=Q(!1),O=T[0],I=T[1],S=Q(!1),A=S[0],C=S[1],N=Q(!1),D=N[0],P=N[1],k=E.isValid,R=E.isPotentiallyValid;return Z((function(){u(w)}),[]),Z((function(){p(Fe(Ie,a))}),[a]),Z((function(){l.length>0&&b({isPotentiallyValid:!1,isValid:!1})}),[l]),Z((function(){Me(w,E,A,O),n({value:_,valid:E.isValid,isFocused:A,potentiallyValid:E.isPotentiallyValid})}),[_,k,A,R]),Z((function(){r({isFocused:A})}),[A]),Z((function(){i({isInputSubmitRequest:D})}),[D]),m(g,null,m("style",{nonce:t},f),m(xt,{ref:w,type:"text",placeholder:null!=c?c:"Cardholder Name (optional)",maxLength:"255",onChange:function(e){return v(e.cardName)},onValidityChange:function(e){return b(e)},onFocus:function(){C(!0),I(!0)},onBlur:function(){return C(!1)},onKeyDown:function(e){return P(e)}}))}function zt(e){var t=e.cspNonce,n=e.onChange,r=e.onFocus,i=e.onKeyDown,o=e.styleObject,a=void 0===o?{}:o,c=e.placeholder,u=e.minLength,s=e.maxLength,l=e.autoFocusRef,d=e.autocomplete,f=e.gqlErrors,p=void 0===f?[]:f,h=Q(""),_=h[0],v=h[1],y=Q(""),E=y[0],b=y[1],w=Q(Pe),T=w[0],O=w[1],I=ee(),S=Q(!1),A=S[0],C=S[1],N=Q(!1),D=N[0],P=N[1],k=Q(!1),R=k[0],j=k[1],x=T.isValid,V=T.isPotentiallyValid;return Z((function(){l(I)}),[]),Z((function(){v(Fe(Ie,a))}),[a]),Z((function(){p.length>0&&O({isPotentiallyValid:!1,isValid:!1})}),[p]),Z((function(){Me(I,T,A,D),n({value:E,valid:T.isValid,isFocused:A,potentiallyValid:T.isPotentiallyValid})}),[E,x,A,V]),Z((function(){r({isFocused:A})}),[A]),Z((function(){i({isInputSubmitRequest:R})}),[R]),m(g,null,m("style",{nonce:t},_),m(Vt,{ref:I,type:"text",autocomplete:d,placeholder:null!=c?c:"Postal code",minLength:u,maxLength:s,onChange:function(e){return b(e.cardPostalCode)},onValidityChange:function(e){return O(e)},onFocus:function(){P(!0),C(!0)},onBlur:function(){return C(!1)},onKeyDown:function(e){return j(e)}}))}function Wt(e){var t,n=e.cspNonce,r=e.props,i=e.featureFlags,o=e.experiments,a=r.facilitatorAccessToken,c=r.style,u=r.disableAutocomplete,s=r.placeholder,d=r.type,f=r.export,p=r.minLength,h=r.maxLength,_=r.inputEvents||{},v=_.onChange,y=_.onFocus,E=_.onBlur,b=_.onInputSubmitRequest,w=Q(),T=w[0],O=w[1],I=Q(!1),S=I[0],A=I[1],C=Q(!0),N=C[0],D=C[1],P=Q([]),k=P[0],R=P[1],j=Q(!1),x=j[0],V=j[1],L=Q(!1),F=L[0],M=L[1],U=Q(),B=U[0],H=U[1],z=Q({singleField:{},numberField:[],expiryField:[],cvvField:[],nameField:[],postalCodeField:[]}),W=z[0],Y=z[1],q=ee(!0);u&&(t="off");var K=function(){return T},G=function(){return S},$=function(){return N},X=function(){return x},J=function(){return k},te=function(e){var t=e.errors,n=Object(l.a)({},W);if("single"===d)n.singleField=Object(l.a)({},e);else if(t&&t.length)switch(d){case"number":n.numberField=[].concat(t);break;case"expiry":n.expiryField=[].concat(t);break;case"cvv":n.cvvField=[].concat(t);break;case"name":n.nameField=[].concat(t);break;case"postal":n.postalCodeField=[].concat(t)}Y(n)},ne=function(){Y({singleField:{},numberField:[],expiryField:[],cvvField:[],nameField:[],postalCodeField:[]})},re=function(){var e=ut(),t=e.cards,n=e.fields,r=qe(me[d]);return n[r]={isEmpty:ct(T),isFocused:x,isPotentiallyValid:N,isValid:S},{fields:n,potentialCardTypes:"cardNumberField"===r?He(k):t}};Z((function(){if(q.current&&""===T)q.current=!1;else if(!q.current&&"function"==typeof v){var e=re(),t=e.fields,n=e.potentialCardTypes,r=st(t);v({fields:t,cards:n,emittedBy:d,isFormValid:0===r.length,errors:r})}}),[T]),Z((function(){if(q.current&&""===T)q.current=!1;else if(!q.current&&"function"==typeof y){var e=re(),t=e.fields,n=e.potentialCardTypes,r=st(t),i={fields:t,cards:n,emittedBy:d,isFormValid:0===r.length,errors:r};x?y(Object(l.a)({},i)):"function"!=typeof E||x||E(Object(l.a)({},i))}}),[x]),Z((function(){if(F&&"function"==typeof b){var e=re(),t=e.fields,n=e.potentialCardTypes,r=st(t),i={fields:t,cards:n,emittedBy:d,isFormValid:0===r.length,errors:r};b(Object(l.a)({},i)),M(!1)}}),[F]),Z((function(){!function(e){if(e){var t=null;window.addEventListener("focus",(function(){t=setTimeout((function(){t=null,function(e){var t=""===e.value;t&&(e.value=" ");var n=e.selectionStart,r=e.selectionEnd;e.setSelectionRange(0,0),e.setSelectionRange(n,r),t&&(e.value="")}(e),e.focus()}))})),window.addEventListener("focusin",(function(e){t&&e.target instanceof HTMLInputElement&&(clearTimeout(t),t=null)}))}}(B)}),[B]),Z((function(){!function(e){window.exports={name:e.name,isFieldValid:e.isFieldValid,isFieldPotentiallyValid:e.isFieldPotentiallyValid,getPotentialCardTypes:e.getPotentialCardTypes,isFieldFocused:e.isFieldFocused,getFieldValue:e.getFieldValue,setGqlErrors:e.setGqlErrors,resetGQLErrors:e.resetGQLErrors}}({name:me[d],isFieldPotentiallyValid:$,getPotentialCardTypes:J,isFieldValid:G,isFieldFocused:X,getFieldValue:K,setGqlErrors:te,resetGQLErrors:ne}),f({submit:function(e){var t=function(e){return!e||"object"!=typeof e||Array.isArray(e)?{}:Object.keys(e).reduce((function(t,n){return Ae.includes(n)&&(t[n]=e[n]),t}),{})}(e);return It({facilitatorAccessToken:a,extraFields:t,featureFlags:i,experiments:o})},getState:function(){var e=ut(),t=st(e.fields);return Object(l.a)({},e,{isFormValid:0===t.length,errors:t})}})}),[S,T,x,N,k]);var ie=function(e){var t=e.valid,n=e.isFocused,r=e.potentiallyValid,i=e.potentialCardTypes;O(e.value),V(n),A(t),D(r),ne(),R(i)},oe=function(e){V(e.isFocused)},ae=function(e){M(e.isInputSubmitRequest)};return m(g,null,"single"===d?m(Lt,{gqlErrorsObject:W.singleField,cspNonce:n,autocomplete:t,onChange:ie,styleObject:c,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"number"===d?m(Mt,{ref:B,gqlErrors:W.numberField,cspNonce:n,autocomplete:t,onChange:ie,onFocus:oe,onKeyDown:ae,styleObject:c,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"cvv"===d?m(Bt,{ref:B,gqlErrors:W.cvvField,cspNonce:n,autocomplete:t,onChange:ie,onKeyDown:ae,onFocus:oe,styleObject:c,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"expiry"===d?m(Ut,{ref:B,gqlErrors:W.expiryField,cspNonce:n,autocomplete:t,onChange:ie,onFocus:oe,onKeyDown:ae,styleObject:c,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"name"===d?m(Ht,{ref:B,gqlErrors:W.nameField,cspNonce:n,onChange:ie,onFocus:oe,onKeyDown:ae,styleObject:c,placeholder:s,autoFocusRef:function(e){return H(e.current.base)}}):null,"postal"===d?m(zt,{ref:B,gqlErrors:W.postalCodeField,cspNonce:n,onChange:ie,onFocus:oe,onKeyDown:ae,styleObject:c,placeholder:s,minLength:p,maxLength:h||10,autoFocusRef:function(e){return H(e.current.base)}}):null)}function Yt(e){var t=e.cspNonce,n=e.featureFlags,o=e.experiments,a=e.buyerCountry,c=e.metadata,u=yt({facilitatorAccessToken:e.facilitatorAccessToken,featureFlags:n,experiments:o}),s=u.env,f=u.clientMetadataID;!function(e){var t,n=e.env,r=e.sessionID,i=e.clientID,o=e.partnerAttributionID,a=e.sdkCorrelationID,c=e.cardCorrelationID,u=e.locale,s=e.merchantID,d=e.merchantDomain,f=e.buyerCountry,p=e.type,h=e.hcfSessionID,_=e.productAction,v=Object(de.c)();Object(de.k)({env:n,sessionID:r,clientID:i,sdkCorrelationID:a,locale:u,buyerCountry:f}),v.addTrackingBuilder((function(){var e;return(e={})[_e.e.BUTTON_VERSION]="5.0.164",e.hcf_session_id=h,e.hcf_correlation_id=c,e[_e.e.PARTNER_ATTRIBUTION_ID]=o,e[_e.e.MERCHANT_DOMAIN]=d,e[_e.e.TIMESTAMP]=Date.now().toString(),e.sdk_correlation_id=a,e[_e.c.PAYMENTS_SDK]=i,e[_e.e.SELLER_ID]=null==s?void 0:s[0],e.hcf_version="v2",e[_e.e.PAYMENT_FLOW]=_,e}));var m=((t={})[_e.e.STATE]=he.f.CARD,t[_e.e.TRANSITION]="hcf_"+p+"_field_rendered",t[_e.e.EVENT_NAME]="hcf_"+p+"_field_rendered",t);pt.a.hash({pageRenderTime:Object(le.d)()}).then((function(e){var t,n=e.pageRenderTime;v.track(Object(l.a)({},m,((t={})[_e.e.CONTEXT_TYPE]="hosted_session_id",t[_e.e.CONTEXT_ID]=h,t[_e.e.PAGE_LOAD_TIME]=n?n.toString():"",t))),v.flush()}))}({env:s,sessionID:u.sessionID,cardSessionID:u.cardSessionID,clientID:u.clientID,partnerAttributionID:u.partnerAttributionID,sdkCorrelationID:u.sdkCorrelationID,cardCorrelationID:null==c?void 0:c.correlationID,locale:u.locale,merchantID:u.merchantID,merchantDomain:u.merchantDomain,buyerCountry:a,type:u.type,hcfSessionID:u.hcfSessionID,productAction:u.productAction}),Object(gt.r)({env:s,clientMetadataID:f,cspNonce:t}).catch(le.p).then((function(){!function(e,t,n){var o,a,c;i.__&&i.__(e,t),o=!1?null:t.__k,a=[],c=[],R(t,e=t.__k=m(g,null,[e]),o||d,d,void 0!==t.ownerSVGElement,o?null:t.firstChild?r.call(t.childNodes):null,a,o?o.__e:t.firstChild,!1,c),j(a,e,c)}(m(Wt,{cspNonce:t,props:u,featureFlags:n,experiments:o}),Object(de.a)())}))}}]); \ No newline at end of file diff --git a/dist/smart-menu.js b/dist/smart-menu.js index 71532af502..3acef2c0e1 100644 --- a/dist/smart-menu.js +++ b/dist/smart-menu.js @@ -90,76 +90,84 @@ window.spb = function(modules) { __e: null, __d: void 0, __c: null, - __h: null, constructor: void 0, - __v: null == r ? ++preact_module_u : r + __v: null == r ? ++preact_module_u : r, + __i: -1, + __u: 0 }; return null == r && null != l.vnode && l.vnode(f), f; } - function k(n) { + function g(n) { return n.children; } function b(n, l) { this.props = n, this.context = l; } - function g(n, l) { - if (null == l) return n.__ ? g(n.__, n.__.__k.indexOf(n) + 1) : null; + function m(n, l) { + if (null == l) return n.__ ? m(n.__, n.__i + 1) : null; for (var u; l < n.__k.length; l++) if (null != (u = n.__k[l]) && null != u.__e) return u.__e; - return "function" == typeof n.type ? g(n) : null; + return "function" == typeof n.type ? m(n) : null; } - function m(n) { + function k(n) { var l, u; if (null != (n = n.__) && null != n.__c) { for (n.__e = n.__c.base = null, l = 0; l < n.__k.length; l++) if (null != (u = n.__k[l]) && null != u.__e) { n.__e = n.__c.base = u.__e; break; } - return m(n); + return k(n); } } function w(n) { (!n.__d && (n.__d = !0) && preact_module_i.push(n) && !x.__r++ || preact_module_o !== l.debounceRendering) && ((preact_module_o = l.debounceRendering) || preact_module_r)(x); } function x() { - var n, l, u, t, o, r, e, c, s; - for (preact_module_i.sort(f); n = preact_module_i.shift(); ) n.__d && (l = preact_module_i.length, - t = void 0, o = void 0, r = void 0, c = (e = (u = n).__v).__e, (s = u.__P) && (t = [], - o = [], (r = v({}, e)).__v = e.__v + 1, L(s, e, r, u.__n, void 0 !== s.ownerSVGElement, null != e.__h ? [ c ] : null, t, null == c ? g(e) : c, e.__h, o), - M(t, e, o), e.__e != c && m(e)), preact_module_i.length > l && preact_module_i.sort(f)); + var n, u, t, o, r, e, c, s, a; + for (preact_module_i.sort(f); n = preact_module_i.shift(); ) n.__d && (u = preact_module_i.length, + o = void 0, e = (r = (t = n).__v).__e, s = [], a = [], (c = t.__P) && ((o = v({}, r)).__v = r.__v + 1, + l.vnode && l.vnode(o), L(c, o, r, t.__n, void 0 !== c.ownerSVGElement, 32 & r.__u ? [ e ] : null, s, null == e ? m(r) : e, !!(32 & r.__u), a), + o.__.__k[o.__i] = o, M(s, o, a), o.__e != e && k(o)), preact_module_i.length > u && preact_module_i.sort(f)); x.__r = 0; } - function P(n, l, u, t, i, o, r, f, e, a, v) { - var p, y, _, b, m, w, x, P, C, H = 0, I = t && t.__k || s, T = I.length, j = T, z = l.length; - for (u.__k = [], p = 0; p < z; p++) null != (b = u.__k[p] = null == (b = l[p]) || "boolean" == typeof b || "function" == typeof b ? null : "string" == typeof b || "number" == typeof b || "bigint" == typeof b ? d(null, b, null, null, b) : h(b) ? d(k, { - children: b - }, null, null, null) : b.__b > 0 ? d(b.type, b.props, b.key, b.ref ? b.ref : null, b.__v) : b) ? (b.__ = u, - b.__b = u.__b + 1, -1 === (P = A(b, I, x = p + H, j)) ? _ = c : (_ = I[P] || c, - I[P] = void 0, j--), L(n, b, _, i, o, r, f, e, a, v), m = b.__e, (y = b.ref) && _.ref != y && (_.ref && O(_.ref, null, b), - v.push(y, b.__c || m, b)), null != m && (null == w && (w = m), (C = _ === c || null === _.__v) ? -1 == P && H-- : P !== x && (P === x + 1 ? H++ : P > x ? j > z - x ? H += P - x : H-- : H = P < x && P == x - 1 ? P - x : 0), - x = p + H, "function" != typeof b.type || P === x && _.__k !== b.__k ? "function" == typeof b.type || P === x && !C ? void 0 !== b.__d ? (e = b.__d, - b.__d = void 0) : e = m.nextSibling : e = S(n, m, e) : e = $(b, e, n), "function" == typeof u.type && (u.__d = e))) : (_ = I[p]) && null == _.key && _.__e && (_.__e == e && (e = g(_)), - q(_, _, !1), I[p] = null); - for (u.__e = w, p = T; p--; ) null != I[p] && ("function" == typeof u.type && null != I[p].__e && I[p].__e == u.__d && (u.__d = I[p].__e.nextSibling), - q(I[p], I[p])); - } - function $(n, l, u) { - for (var t, i = n.__k, o = 0; i && o < i.length; o++) (t = i[o]) && (t.__ = n, l = "function" == typeof t.type ? $(t, l, u) : S(u, t.__e, l)); - return l; + function C(n, l, u, t, i, o, r, f, e, a, h) { + var v, p, y, d, _, g = t && t.__k || s, b = l.length; + for (u.__d = e, P(u, l, g), e = u.__d, v = 0; v < b; v++) null != (y = u.__k[v]) && "boolean" != typeof y && "function" != typeof y && (p = -1 === y.__i ? c : g[y.__i] || c, + y.__i = v, L(n, y, p, i, o, r, f, e, a, h), d = y.__e, y.ref && p.ref != y.ref && (p.ref && z(p.ref, null, y), + h.push(y.ref, y.__c || d, y)), null == _ && null != d && (_ = d), 65536 & y.__u || p.__k === y.__k ? e = S(y, e, n) : "function" == typeof y.type && void 0 !== y.__d ? e = y.__d : d && (e = d.nextSibling), + y.__d = void 0, y.__u &= -196609); + u.__d = e, u.__e = _; + } + function P(n, l, u) { + var t, i, o, r, f, e = l.length, c = u.length, s = c, a = 0; + for (n.__k = [], t = 0; t < e; t++) null != (i = n.__k[t] = null == (i = l[t]) || "boolean" == typeof i || "function" == typeof i ? null : "string" == typeof i || "number" == typeof i || "bigint" == typeof i || i.constructor == String ? d(null, i, null, null, i) : h(i) ? d(g, { + children: i + }, null, null, null) : i.__b > 0 ? d(i.type, i.props, i.key, i.ref ? i.ref : null, i.__v) : i) ? (i.__ = n, + i.__b = n.__b + 1, f = H(i, u, r = t + a, s), i.__i = f, o = null, -1 !== f && (s--, + (o = u[f]) && (o.__u |= 131072)), null == o || null === o.__v ? (-1 == f && a--, + "function" != typeof i.type && (i.__u |= 65536)) : f !== r && (f === r + 1 ? a++ : f > r ? s > e - r ? a += f - r : a-- : a = f < r && f == r - 1 ? f - r : 0, + f !== t + a && (i.__u |= 65536))) : (o = u[t]) && null == o.key && o.__e && (o.__e == n.__d && (n.__d = m(o)), + N(o, o, !1), u[t] = null, s--); + if (s) for (t = 0; t < c; t++) null != (o = u[t]) && 0 == (131072 & o.__u) && (o.__e == n.__d && (n.__d = m(o)), + N(o, o)); } function S(n, l, u) { - return null == u || u.parentNode !== n ? n.insertBefore(l, null) : l == u && null != l.parentNode || n.insertBefore(l, u), - l.nextSibling; + var t, i; + if ("function" == typeof n.type) { + for (t = n.__k, i = 0; t && i < t.length; i++) t[i] && (t[i].__ = n, l = S(t[i], l, u)); + return l; + } + return n.__e != l && (u.insertBefore(n.__e, l || null), l = n.__e), l && l.nextSibling; } - function A(n, l, u, t) { + function H(n, l, u, t) { var i = n.key, o = n.type, r = u - 1, f = u + 1, e = l[u]; if (null === e || e && i == e.key && o === e.type) return u; - if (t > (null != e ? 1 : 0)) for (;r >= 0 || f < l.length; ) { + if (t > (null != e && 0 == (131072 & e.__u) ? 1 : 0)) for (;r >= 0 || f < l.length; ) { if (r >= 0) { - if ((e = l[r]) && i == e.key && o === e.type) return r; + if ((e = l[r]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return r; r--; } if (f < l.length) { - if ((e = l[f]) && i == e.key && o === e.type) return f; + if ((e = l[f]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return f; f++; } } @@ -175,65 +183,70 @@ window.spb = function(modules) { if (u) for (l in u) t && u[l] === t[l] || I(n.style, l, u[l]); } else if ("o" === l[0] && "n" === l[1]) o = l !== (l = l.replace(/(PointerCapture)$|Capture$/, "$1")), l = l.toLowerCase() in n ? l.toLowerCase().slice(2) : l.slice(2), n.l || (n.l = {}), - n.l[l + o] = u, u ? t || n.addEventListener(l, o ? z : j, o) : n.removeEventListener(l, o ? z : j, o); else if ("dangerouslySetInnerHTML" !== l) { - if (i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" !== l && "height" !== l && "href" !== l && "list" !== l && "form" !== l && "tabIndex" !== l && "download" !== l && "rowSpan" !== l && "colSpan" !== l && l in n) try { + n.l[l + o] = u, u ? t ? u.u = t.u : (u.u = Date.now(), n.addEventListener(l, o ? D : A, o)) : n.removeEventListener(l, o ? D : A, o); else { + if (i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" !== l && "height" !== l && "href" !== l && "list" !== l && "form" !== l && "tabIndex" !== l && "download" !== l && "rowSpan" !== l && "colSpan" !== l && "role" !== l && l in n) try { n[l] = null == u ? "" : u; break n; } catch (n) {} "function" == typeof u || (null == u || !1 === u && "-" !== l[4] ? n.removeAttribute(l) : n.setAttribute(l, u)); } } - function j(n) { - return this.l[n.type + !1](l.event ? l.event(n) : n); + function A(n) { + var u = this.l[n.type + !1]; + if (n.t) { + if (n.t <= u.u) return; + } else n.t = Date.now(); + return u(l.event ? l.event(n) : n); } - function z(n) { + function D(n) { return this.l[n.type + !0](l.event ? l.event(n) : n); } function L(n, u, t, i, o, r, f, e, c, s) { - var a, p, y, d, _, g, m, w, x, $, C, S, A, H, I, T = u.type; + var a, p, y, d, _, m, k, w, x, P, S, $, H, I, T, A = u.type; if (void 0 !== u.constructor) return null; - null != t.__h && (c = t.__h, e = u.__e = t.__e, u.__h = null, r = [ e ]), (a = l.__b) && a(u); - n: if ("function" == typeof T) try { - if (w = u.props, x = (a = T.contextType) && i[a.__c], $ = a ? x ? x.props.value : a.__ : i, - t.__c ? m = (p = u.__c = t.__c).__ = p.__E : ("prototype" in T && T.prototype.render ? u.__c = p = new T(w, $) : (u.__c = p = new b(w, $), - p.constructor = T, p.render = B), x && x.sub(p), p.props = w, p.state || (p.state = {}), - p.context = $, p.__n = i, y = p.__d = !0, p.__h = [], p._sb = []), null == p.__s && (p.__s = p.state), - null != T.getDerivedStateFromProps && (p.__s == p.state && (p.__s = v({}, p.__s)), - v(p.__s, T.getDerivedStateFromProps(w, p.__s))), d = p.props, _ = p.state, p.__v = u, - y) null == T.getDerivedStateFromProps && null != p.componentWillMount && p.componentWillMount(), + 128 & t.__u && (c = !!(32 & t.__u), r = [ e = u.__e = t.__e ]), (a = l.__b) && a(u); + n: if ("function" == typeof A) try { + if (w = u.props, x = (a = A.contextType) && i[a.__c], P = a ? x ? x.props.value : a.__ : i, + t.__c ? k = (p = u.__c = t.__c).__ = p.__E : ("prototype" in A && A.prototype.render ? u.__c = p = new A(w, P) : (u.__c = p = new b(w, P), + p.constructor = A, p.render = O), x && x.sub(p), p.props = w, p.state || (p.state = {}), + p.context = P, p.__n = i, y = p.__d = !0, p.__h = [], p._sb = []), null == p.__s && (p.__s = p.state), + null != A.getDerivedStateFromProps && (p.__s == p.state && (p.__s = v({}, p.__s)), + v(p.__s, A.getDerivedStateFromProps(w, p.__s))), d = p.props, _ = p.state, p.__v = u, + y) null == A.getDerivedStateFromProps && null != p.componentWillMount && p.componentWillMount(), null != p.componentDidMount && p.__h.push(p.componentDidMount); else { - if (null == T.getDerivedStateFromProps && w !== d && null != p.componentWillReceiveProps && p.componentWillReceiveProps(w, $), - !p.__e && (null != p.shouldComponentUpdate && !1 === p.shouldComponentUpdate(w, p.__s, $) || u.__v === t.__v)) { + if (null == A.getDerivedStateFromProps && w !== d && null != p.componentWillReceiveProps && p.componentWillReceiveProps(w, P), + !p.__e && (null != p.shouldComponentUpdate && !1 === p.shouldComponentUpdate(w, p.__s, P) || u.__v === t.__v)) { for (u.__v !== t.__v && (p.props = w, p.state = p.__s, p.__d = !1), u.__e = t.__e, u.__k = t.__k, u.__k.forEach((function(n) { n && (n.__ = u); - })), C = 0; C < p._sb.length; C++) p.__h.push(p._sb[C]); + })), S = 0; S < p._sb.length; S++) p.__h.push(p._sb[S]); p._sb = [], p.__h.length && f.push(p); break n; } - null != p.componentWillUpdate && p.componentWillUpdate(w, p.__s, $), null != p.componentDidUpdate && p.__h.push((function() { - p.componentDidUpdate(d, _, g); + null != p.componentWillUpdate && p.componentWillUpdate(w, p.__s, P), null != p.componentDidUpdate && p.__h.push((function() { + p.componentDidUpdate(d, _, m); })); } - if (p.context = $, p.props = w, p.__P = n, p.__e = !1, S = l.__r, A = 0, "prototype" in T && T.prototype.render) { - for (p.state = p.__s, p.__d = !1, S && S(u), a = p.render(p.props, p.state, p.context), - H = 0; H < p._sb.length; H++) p.__h.push(p._sb[H]); + if (p.context = P, p.props = w, p.__P = n, p.__e = !1, $ = l.__r, H = 0, "prototype" in A && A.prototype.render) { + for (p.state = p.__s, p.__d = !1, $ && $(u), a = p.render(p.props, p.state, p.context), + I = 0; I < p._sb.length; I++) p.__h.push(p._sb[I]); p._sb = []; } else do { - p.__d = !1, S && S(u), a = p.render(p.props, p.state, p.context), p.state = p.__s; - } while (p.__d && ++A < 25); + p.__d = !1, $ && $(u), a = p.render(p.props, p.state, p.context), p.state = p.__s; + } while (p.__d && ++H < 25); p.state = p.__s, null != p.getChildContext && (i = v(v({}, i), p.getChildContext())), - y || null == p.getSnapshotBeforeUpdate || (g = p.getSnapshotBeforeUpdate(d, _)), - P(n, h(I = null != a && a.type === k && null == a.key ? a.props.children : a) ? I : [ I ], u, t, i, o, r, f, e, c, s), - p.base = u.__e, u.__h = null, p.__h.length && f.push(p), m && (p.__E = p.__ = null); + y || null == p.getSnapshotBeforeUpdate || (m = p.getSnapshotBeforeUpdate(d, _)), + C(n, h(T = null != a && a.type === g && null == a.key ? a.props.children : a) ? T : [ T ], u, t, i, o, r, f, e, c, s), + p.base = u.__e, u.__u &= -161, p.__h.length && f.push(p), k && (p.__E = p.__ = null); } catch (n) { - u.__v = null, (c || null != r) && (u.__e = e, u.__h = !!c, r[r.indexOf(e)] = null), - l.__e(n, u, t); - } else null == r && u.__v === t.__v ? (u.__k = t.__k, u.__e = t.__e) : u.__e = N(t.__e, u, t, i, o, r, f, c, s); + u.__v = null, c || null != r ? (u.__e = e, u.__u |= c ? 160 : 32, r[r.indexOf(e)] = null) : (u.__e = t.__e, + u.__k = t.__k), l.__e(n, u, t); + } else null == r && u.__v === t.__v ? (u.__k = t.__k, u.__e = t.__e) : u.__e = j(t.__e, u, t, i, o, r, f, c, s); (a = l.diffed) && a(u); } function M(n, u, t) { - for (var i = 0; i < t.length; i++) O(t[i], t[++i], t[++i]); + u.__d = void 0; + for (var i = 0; i < t.length; i++) z(t[i], t[++i], t[++i]); l.__c && l.__c(u, n), n.some((function(u) { try { n = u.__h, u.__h = [], n.some((function(n) { @@ -244,44 +257,40 @@ window.spb = function(modules) { } })); } - function N(l, u, t, i, o, r, f, e, s) { - var a, v, y, d = t.props, _ = u.props, k = u.type, b = 0; - if ("svg" === k && (o = !0), null != r) for (;b < r.length; b++) if ((a = r[b]) && "setAttribute" in a == !!k && (k ? a.localName === k : 3 === a.nodeType)) { - l = a, r[b] = null; + function j(l, u, t, i, o, r, f, e, s) { + var a, v, y, d, _, g, b, k = t.props, w = u.props, x = u.type; + if ("svg" === x && (o = !0), null != r) for (a = 0; a < r.length; a++) if ((_ = r[a]) && "setAttribute" in _ == !!x && (x ? _.localName === x : 3 === _.nodeType)) { + l = _, r[a] = null; break; } if (null == l) { - if (null === k) return document.createTextNode(_); - l = o ? document.createElementNS("http://www.w3.org/2000/svg", k) : document.createElement(k, _.is && _), + if (null === x) return document.createTextNode(w); + l = o ? document.createElementNS("http://www.w3.org/2000/svg", x) : document.createElement(x, w.is && w), r = null, e = !1; } - if (null === k) d === _ || e && l.data === _ || (l.data = _); else { - if (r = r && n.call(l.childNodes), v = (d = t.props || c).dangerouslySetInnerHTML, - y = _.dangerouslySetInnerHTML, !e) { - if (null != r) for (d = {}, b = 0; b < l.attributes.length; b++) d[l.attributes[b].name] = l.attributes[b].value; - (y || v) && (y && (v && y.__html == v.__html || y.__html === l.innerHTML) || (l.innerHTML = y && y.__html || "")); - } - if (function(n, l, u, t, i) { - var o; - for (o in u) "children" === o || "key" === o || o in l || T(n, o, null, u[o], t); - for (o in l) i && "function" != typeof l[o] || "children" === o || "key" === o || "value" === o || "checked" === o || u[o] === l[o] || T(n, o, l[o], u[o], t); - }(l, _, d, o, e), y) u.__k = []; else if (P(l, h(b = u.props.children) ? b : [ b ], u, t, i, o && "foreignObject" !== k, r, f, r ? r[0] : t.__k && g(t, 0), e, s), - null != r) for (b = r.length; b--; ) null != r[b] && p(r[b]); - e || ("value" in _ && void 0 !== (b = _.value) && (b !== l.value || "progress" === k && !b || "option" === k && b !== d.value) && T(l, "value", b, d.value, !1), - "checked" in _ && void 0 !== (b = _.checked) && b !== l.checked && T(l, "checked", b, d.checked, !1)); + if (null === x) k === w || e && l.data === w || (l.data = w); else { + if (r = r && n.call(l.childNodes), k = t.props || c, !e && null != r) for (k = {}, + a = 0; a < l.attributes.length; a++) k[(_ = l.attributes[a]).name] = _.value; + for (a in k) _ = k[a], "children" == a || ("dangerouslySetInnerHTML" == a ? y = _ : "key" === a || a in w || T(l, a, null, _, o)); + for (a in w) _ = w[a], "children" == a ? d = _ : "dangerouslySetInnerHTML" == a ? v = _ : "value" == a ? g = _ : "checked" == a ? b = _ : "key" === a || e && "function" != typeof _ || k[a] === _ || T(l, a, _, k[a], o); + if (v) e || y && (v.__html === y.__html || v.__html === l.innerHTML) || (l.innerHTML = v.__html), + u.__k = []; else if (y && (l.innerHTML = ""), C(l, h(d) ? d : [ d ], u, t, i, o && "foreignObject" !== x, r, f, r ? r[0] : t.__k && m(t, 0), e, s), + null != r) for (a = r.length; a--; ) null != r[a] && p(r[a]); + e || (a = "value", void 0 !== g && (g !== l[a] || "progress" === x && !g || "option" === x && g !== k[a]) && T(l, a, g, k[a], !1), + a = "checked", void 0 !== b && b !== l[a] && T(l, a, b, k[a], !1)); } return l; } - function O(n, u, t) { + function z(n, u, t) { try { "function" == typeof n ? n(u) : n.current = u; } catch (n) { l.__e(n, t); } } - function q(n, u, t) { + function N(n, u, t) { var i, o; - if (l.unmount && l.unmount(n), (i = n.ref) && (i.current && i.current !== n.__e || O(i, null, u)), + if (l.unmount && l.unmount(n), (i = n.ref) && (i.current && i.current !== n.__e || z(i, null, u)), null != (i = n.__c)) { if (i.componentWillUnmount) try { i.componentWillUnmount(); @@ -290,10 +299,10 @@ window.spb = function(modules) { } i.base = i.__P = null, n.__c = void 0; } - if (i = n.__k) for (o = 0; o < i.length; o++) i[o] && q(i[o], u, t || "function" != typeof n.type); + if (i = n.__k) for (o = 0; o < i.length; o++) i[o] && N(i[o], u, t || "function" != typeof n.type); t || null == n.__e || p(n.__e), n.__ = n.__e = n.__d = void 0; } - function B(n, l, u) { + function O(n, l, u) { return this.constructor(n, u); } n = s.slice, l = { @@ -314,7 +323,7 @@ window.spb = function(modules) { w(this)); }, b.prototype.forceUpdate = function(n) { this.__v && (this.__e = !0, n && this.__h.push(n), w(this)); - }, b.prototype.render = k, preact_module_i = [], preact_module_r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, + }, b.prototype.render = g, preact_module_i = [], preact_module_r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f = function(n, l) { return n.__v.__b - l.__v.__b; }, x.__r = 0; @@ -1914,7 +1923,7 @@ window.spb = function(modules) { onFocus: _ref.onFocus, onFocusFail: _ref.onFocusFail }); - return y(k, null, y("style", { + return y(g, null, y("style", { nonce: cspNonce }, '\n .menu {\n width: 100%;\n z-index: 5000;\n background: white;\n border-radius: 0 0 3px 3px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n letter-spacing: 0.5px;\n box-shadow: 0px 0px 3px 1px rgba(222,222,222,1);\n outline-style: none;\n user-select: none;\n text-align: center;\n margin-top: ' + verticalOffset + "px;\n overflow: hidden;\n }\n\n .menu-item {\n border-top: 2px solid rgba(230, 230, 230, 0.5);;\n color: #0070ba;\n cursor: pointer;\n }\n\n .menu-item:first-child {\n border-top: none;\n }\n\n .menu-item:hover {\n background: #fcfcfc;\n text-decoration: underline;\n }\n\n @media screen and (min-width: 0px) {\n .menu-item {\n font-size: 11px;\n line-height: 14px;\n padding: 8px;\n }\n }\n\n @media screen and (min-width: 300px) {\n .menu-item {\n font-size: 14px;\n line-height: 18px;\n padding: 14px;\n }\n }\n\n @media screen and (min-width: 500px) {\n .menu-item {\n font-size: 18px;\n line-height: 21px;\n padding: 17px;\n }\n }\n "), y("div", { class: "menu", @@ -2020,7 +2029,7 @@ window.spb = function(modules) { setOpaque(hasChoices); setVisible(hasChoices); }), [ choices ]); - return y(k, null, y("style", { + return y(g, null, y("style", { nonce: cspNonce }, "\n * {\n box-sizing: border-box;\n }\n\n html, body {\n margin: 0;\n padding: 0;\n opacity: " + (opaque ? "1" : "0") + ";\n transition: opacity " + .15.toFixed(2) + 's ease-in-out;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n }\n\n body {\n padding: 5px 20px;\n display: inline-block;\n width: 100%;\n }\n '), choices && visible ? y(Menu, { choices: choices, @@ -2049,7 +2058,7 @@ window.spb = function(modules) { var _ref3$pageVisible = _ref3.pageVisible; !function(u, t, i) { var r, f, e; - l.__ && l.__(u, t), r = !1 ? null : t.__k, f = [], e = [], L(t, u = t.__k = y(k, null, [ u ]), r || c, c, void 0 !== t.ownerSVGElement, r ? null : t.firstChild ? n.call(t.childNodes) : null, f, r ? r.__e : t.firstChild, !1, e), + l.__ && l.__(u, t), r = !1 ? null : t.__k, f = [], e = [], L(t, u = t.__k = y(g, null, [ u ]), r || c, c, void 0 !== t.ownerSVGElement, r ? null : t.firstChild ? n.call(t.childNodes) : null, f, r ? r.__e : t.firstChild, !1, e), M(f, u, e); }(y(Page, { cspNonce: _ref3.cspNonce, diff --git a/dist/smart-menu.min.js b/dist/smart-menu.min.js index 1a682da824..4dfe51a55f 100644 --- a/dist/smart-menu.min.js +++ b/dist/smart-menu.min.js @@ -1 +1 @@ -window.spb=function(e){var n={};function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(n){return e[n]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return{}.hasOwnProperty.call(e,n)},t.p="",t(t.s=0)}([function(e,n,t){"use strict";t.r(n),t.d(n,"setupMenu",(function(){return Nn}));var r,o,i,u,c,a,l,s={},f=[],d=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,h=Array.isArray;function p(e,n){for(var t in n)e[t]=n[t];return e}function _(e){var n=e.parentNode;n&&n.removeChild(e)}function v(e,n,t){var o,i,u,c={};for(u in n)"key"==u?o=n[u]:"ref"==u?i=n[u]:c[u]=n[u];if(arguments.length>2&&(c.children=arguments.length>3?r.call(arguments,2):t),"function"==typeof e&&null!=e.defaultProps)for(u in e.defaultProps)void 0===c[u]&&(c[u]=e.defaultProps[u]);return w(e,c,o,i,null)}function w(e,n,t,r,u){var c={type:e,props:n,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==u?++i:u};return null==u&&null!=o.vnode&&o.vnode(c),c}function y(e){return e.children}function m(e,n){this.props=e,this.context=n}function g(e,n){if(null==n)return e.__?g(e.__,e.__.__k.indexOf(e)+1):null;for(var t;nn&&u.sort(l));k.__r=0}function E(e,n,t,r,o,i,u,c,a,l,d){var p,_,v,m,b,x,k,E,O,P=0,T=r&&r.__k||f,H=T.length,M=H,W=n.length;for(t.__k=[],p=0;p0?w(m.type,m.props,m.key,m.ref?m.ref:null,m.__v):m)?(m.__=t,m.__b=t.__b+1,-1===(E=C(m,T,k=p+P,M))?v=s:(v=T[E]||s,T[E]=void 0,M--),N(e,m,v,o,i,u,c,a,l,d),b=m.__e,(_=m.ref)&&v.ref!=_&&(v.ref&&L(v.ref,null,m),d.push(_,m.__c||b,m)),null!=b&&(null==x&&(x=b),(O=v===s||null===v.__v)?-1==E&&P--:E!==k&&(E===k+1?P++:E>k?M>W-k?P+=E-k:P--:P=E(null!=a?1:0))for(;u>=0||c=0){if((a=n[u])&&o==a.key&&i===a.type)return u;u--}if(c=t.__.length&&t.__.push({__V:V}),t.__[e]}function Y(e){return z=1,function(e,n,t){var r=Z(R++,2);if(r.t=e,!r.__c&&(r.__=[ie(void 0,n),function(e){var n=r.__N?r.__N[0]:r.__[0],t=r.t(n,e);n!==t&&(r.__N=[t,r.__[1]],r.__c.setState({}))}],r.__c=F,!F.u)){var o=function(e,n,t){if(!r.__c.__H)return!0;var o=r.__c.__H.__.filter((function(e){return e.__c}));if(o.every((function(e){return!e.__N})))return!i||i.call(this,e,n,t);var u=!1;return o.forEach((function(e){if(e.__N){var n=e.__[0];e.__=e.__N,e.__N=void 0,n!==e.__[0]&&(u=!0)}})),!(!u&&r.__c.props===e)&&(!i||i.call(this,e,n,t))};F.u=!0;var i=F.shouldComponentUpdate,u=F.componentWillUpdate;F.componentWillUpdate=function(e,n,t){if(this.__e){var r=i;i=void 0,o(e,n,t),i=r}u&&u.call(this,e,n,t)},F.shouldComponentUpdate=o}return r.__N||r.__}(ie,e)}function K(e,n){var t=Z(R++,3);!o.__s&&oe(t.__H,n)&&(t.__=e,t.i=n,F.__H.__h.push(t))}function Q(){for(var e;e=I.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(te),e.__H.__h.forEach(re),e.__H.__h=[]}catch(n){e.__H.__h=[],o.__e(n,e.__v)}}o.__b=function(e){F=null,q&&q(e)},o.__r=function(e){$&&$(e),R=0;var n=(F=e.__c).__H;n&&(D===F?(n.__h=[],F.__h=[],n.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=V,e.__N=e.i=void 0}))):(n.__h.forEach(te),n.__h.forEach(re),n.__h=[],R=0)),D=F},o.diffed=function(e){J&&J(e);var n=e.__c;n&&n.__H&&(n.__H.__h.length&&(1!==I.push(n)&&U===o.requestAnimationFrame||((U=o.requestAnimationFrame)||ne)(Q)),n.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==V&&(e.__=e.__V),e.i=void 0,e.__V=V}))),D=F=null},o.__c=function(e,n){n.some((function(e){try{e.__h.forEach(te),e.__h=e.__h.filter((function(e){return!e.__||re(e)}))}catch(t){n.some((function(e){e.__h&&(e.__h=[])})),n=[],o.__e(t,e.__v)}})),G&&G(e,n)},o.unmount=function(e){X&&X(e);var n,t=e.__c;t&&t.__H&&(t.__H.__.forEach((function(e){try{te(e)}catch(e){n=e}})),t.__H=void 0,n&&o.__e(n,t.__v))};var ee="function"==typeof requestAnimationFrame;function ne(e){var n,t=function(){clearTimeout(r),ee&&cancelAnimationFrame(n),setTimeout(e)},r=setTimeout(t,100);ee&&(n=requestAnimationFrame(t))}function te(e){var n=F,t=e.__c;"function"==typeof t&&(e.__c=void 0,t()),F=n}function re(e){var n=F;e.__c=e.__(),F=n}function oe(e,n){return!e||e.length!==n.length||n.some((function(n,t){return n!==e[t]}))}function ie(e,n){return"function"==typeof n?n(e):n}function ue(e,n){return(ue=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function ce(e,n){e.prototype=Object.create(n.prototype),e.prototype.constructor=e,ue(e,n)}function ae(){return(ae=Object.assign||function(e){for(var n=1;n>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,n={};return Object.freeze(n),e.set(n,"__testvalue__"),"__testvalue__"===e.get(n)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var n=e.prototype;return n._cleanupClosedWindows=function(){for(var e=this.weakmap,n=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var t=e&&e.stack,r=e&&e.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+Je(e,n+1)}}function Ge(e,n){void 0===n&&(n=Boolean);var t={};for(var r in e)e.hasOwnProperty(r)&&n(e[r],r)&&(t[r]=e[r]);return t}function Xe(e){return[].slice.call(e)}qe.clear=function(){Ve=Ie},qe((function(e){if(Object.values)return Object.values(e);var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(e[t]);return n}));var Ze=function(e){function n(n){var t;return(t=e.call(this,n)||this).name=t.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t),t.constructor):t.stack=new Error(n).stack,t}return ce(n,e),n}(Be(Error));function Ye(){return Boolean(document.body)&&"complete"===document.readyState}function Ke(){return Boolean(document.body)&&"interactive"===document.readyState}function Qe(){return"undefined"!=typeof window&&void 0!==window.location}qe((function(){return new we((function(e){if(Ye()||Ke())return e();var n=setInterval((function(){if(Ye()||Ke())return clearInterval(n),e()}),10)}))}));var en=function(e){function n(){return e.apply(this,arguments)||this}return ce(n,e),n}(Ze),nn="undefined"!=typeof document?document.currentScript:null,tn=qe((function(){if(nn)return nn;if(nn=function(){try{var e=function(){try{throw new Error("_")}catch(e){return e.stack||""}}(),n=/.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(e),t=n&&n[1];if(!t)return;for(var r=0,o=[].slice.call(document.getElementsByTagName("script")).reverse();ran.indexOf(o))){var r=[n];r.push(t),(t.error||t.warning)&&r.push("\n\n",t.error||t.warning);try{window.console[e]&&window.console[e].apply?window.console[e].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(e){}}}function m(){return we.try((function(){if(Qe()&&"file:"!==window.location.protocol&&(f.length||d.length||h.length)){for(var e={},t=0;t<_.length;t++)ln(e,(0,_[t])(e));for(var r,o={},i=0;i1?new hn(n):void 0}(this.component(this.props,this.children));if(n)return n.render(e)},n.render=function(e){return e(this)},n.renderChildren=function(e){return fn(this.children,e)},e}();function vn(e){for(var n=[],t=0;t2?t-2:0),o=2;o2&&(c.children=arguments.length>3?r.call(arguments,2):t),"function"==typeof e&&null!=e.defaultProps)for(u in e.defaultProps)void 0===c[u]&&(c[u]=e.defaultProps[u]);return w(e,c,o,i,null)}function w(e,n,t,r,u){var c={type:e,props:n,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:null==u?++i:u,__i:-1,__u:0};return null==u&&null!=o.vnode&&o.vnode(c),c}function y(e){return e.children}function m(e,n){this.props=e,this.context=n}function g(e,n){if(null==n)return e.__?g(e.__,e.__i+1):null;for(var t;nn&&u.sort(l));k.__r=0}function E(e,n,t,r,o,i,u,c,a,l,d){var _,p,h,v,w,y=r&&r.__k||f,m=n.length;for(t.__d=a,j(t,n,y),a=t.__d,_=0;_0?w(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o)?(o.__=e,o.__b=e.__b+1,c=C(o,t,u=r+f,s),o.__i=c,i=null,-1!==c&&(s--,(i=t[c])&&(i.__u|=131072)),null==i||null===i.__v?(-1==c&&f--,"function"!=typeof o.type&&(o.__u|=65536)):c!==u&&(c===u+1?f++:c>u?s>a-u?f+=c-u:f--:f=c(null!=a&&0==(131072&a.__u)?1:0))for(;u>=0||c=0){if((a=n[u])&&0==(131072&a.__u)&&o==a.key&&i===a.type)return u;u--}if(c=t.__.length&&t.__.push({__V:V}),t.__[e]}function Y(e){return z=1,function(e,n,t){var r=Z(R++,2);if(r.t=e,!r.__c&&(r.__=[ie(void 0,n),function(e){var n=r.__N?r.__N[0]:r.__[0],t=r.t(n,e);n!==t&&(r.__N=[t,r.__[1]],r.__c.setState({}))}],r.__c=D,!D.u)){var o=function(e,n,t){if(!r.__c.__H)return!0;var o=r.__c.__H.__.filter((function(e){return e.__c}));if(o.every((function(e){return!e.__N})))return!i||i.call(this,e,n,t);var u=!1;return o.forEach((function(e){if(e.__N){var n=e.__[0];e.__=e.__N,e.__N=void 0,n!==e.__[0]&&(u=!0)}})),!(!u&&r.__c.props===e)&&(!i||i.call(this,e,n,t))};D.u=!0;var i=D.shouldComponentUpdate,u=D.componentWillUpdate;D.componentWillUpdate=function(e,n,t){if(this.__e){var r=i;i=void 0,o(e,n,t),i=r}u&&u.call(this,e,n,t)},D.shouldComponentUpdate=o}return r.__N||r.__}(ie,e)}function K(e,n){var t=Z(R++,3);!o.__s&&oe(t.__H,n)&&(t.__=e,t.i=n,D.__H.__h.push(t))}function Q(){for(var e;e=I.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(te),e.__H.__h.forEach(re),e.__H.__h=[]}catch(n){e.__H.__h=[],o.__e(n,e.__v)}}o.__b=function(e){D=null,q&&q(e)},o.__r=function(e){$&&$(e),R=0;var n=(D=e.__c).__H;n&&(F===D?(n.__h=[],D.__h=[],n.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=V,e.__N=e.i=void 0}))):(n.__h.forEach(te),n.__h.forEach(re),n.__h=[],R=0)),F=D},o.diffed=function(e){J&&J(e);var n=e.__c;n&&n.__H&&(n.__H.__h.length&&(1!==I.push(n)&&U===o.requestAnimationFrame||((U=o.requestAnimationFrame)||ne)(Q)),n.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==V&&(e.__=e.__V),e.i=void 0,e.__V=V}))),F=D=null},o.__c=function(e,n){n.some((function(e){try{e.__h.forEach(te),e.__h=e.__h.filter((function(e){return!e.__||re(e)}))}catch(t){n.some((function(e){e.__h&&(e.__h=[])})),n=[],o.__e(t,e.__v)}})),G&&G(e,n)},o.unmount=function(e){X&&X(e);var n,t=e.__c;t&&t.__H&&(t.__H.__.forEach((function(e){try{te(e)}catch(e){n=e}})),t.__H=void 0,n&&o.__e(n,t.__v))};var ee="function"==typeof requestAnimationFrame;function ne(e){var n,t=function(){clearTimeout(r),ee&&cancelAnimationFrame(n),setTimeout(e)},r=setTimeout(t,100);ee&&(n=requestAnimationFrame(t))}function te(e){var n=D,t=e.__c;"function"==typeof t&&(e.__c=void 0,t()),D=n}function re(e){var n=D;e.__c=e.__(),D=n}function oe(e,n){return!e||e.length!==n.length||n.some((function(n,t){return n!==e[t]}))}function ie(e,n){return"function"==typeof n?n(e):n}function ue(e,n){return(ue=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function ce(e,n){e.prototype=Object.create(n.prototype),e.prototype.constructor=e,ue(e,n)}function ae(){return(ae=Object.assign||function(e){for(var n=1;n>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,n={};return Object.freeze(n),e.set(n,"__testvalue__"),"__testvalue__"===e.get(n)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var n=e.prototype;return n._cleanupClosedWindows=function(){for(var e=this.weakmap,n=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var t=e&&e.stack,r=e&&e.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+Je(e,n+1)}}function Ge(e,n){void 0===n&&(n=Boolean);var t={};for(var r in e)e.hasOwnProperty(r)&&n(e[r],r)&&(t[r]=e[r]);return t}function Xe(e){return[].slice.call(e)}qe.clear=function(){Ve=Ie},qe((function(e){if(Object.values)return Object.values(e);var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(e[t]);return n}));var Ze=function(e){function n(n){var t;return(t=e.call(this,n)||this).name=t.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t),t.constructor):t.stack=new Error(n).stack,t}return ce(n,e),n}(Be(Error));function Ye(){return Boolean(document.body)&&"complete"===document.readyState}function Ke(){return Boolean(document.body)&&"interactive"===document.readyState}function Qe(){return"undefined"!=typeof window&&void 0!==window.location}qe((function(){return new we((function(e){if(Ye()||Ke())return e();var n=setInterval((function(){if(Ye()||Ke())return clearInterval(n),e()}),10)}))}));var en=function(e){function n(){return e.apply(this,arguments)||this}return ce(n,e),n}(Ze),nn="undefined"!=typeof document?document.currentScript:null,tn=qe((function(){if(nn)return nn;if(nn=function(){try{var e=function(){try{throw new Error("_")}catch(e){return e.stack||""}}(),n=/.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(e),t=n&&n[1];if(!t)return;for(var r=0,o=[].slice.call(document.getElementsByTagName("script")).reverse();ran.indexOf(o))){var r=[n];r.push(t),(t.error||t.warning)&&r.push("\n\n",t.error||t.warning);try{window.console[e]&&window.console[e].apply?window.console[e].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(e){}}}function m(){return we.try((function(){if(Qe()&&"file:"!==window.location.protocol&&(f.length||d.length||_.length)){for(var e={},t=0;t1?new _n(n):void 0}(this.component(this.props,this.children));if(n)return n.render(e)},n.render=function(e){return e(this)},n.renderChildren=function(e){return fn(this.children,e)},e}();function vn(e){for(var n=[],t=0;t2?t-2:0),o=2;o -1; + }(sanitizedUrl)) return sanitizedUrl; + var urlSchemeParseResults = sanitizedUrl.match(urlSchemeRegex); + return urlSchemeParseResults && invalidProtocolRegex.test(urlSchemeParseResults[0]) ? BLANK_URL : sanitizedUrl; + } function getBody() { var body = document.body; if (!body) throw new Error("Body element not found"); @@ -3078,7 +3122,7 @@ getBody().removeChild(form); } function getStorage(_ref) { - var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime; + var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime, stickySessionId = _ref.stickySessionId; return inlineMemoize(getStorage, (function() { var STORAGE_KEY = "__" + name + "_storage__"; var newStateID = uniqueID(); @@ -3113,7 +3157,7 @@ var now = Date.now(); session && now - session.created > lifetime && (session = null); session || (session = { - guid: uniqueID(), + guid: stickySessionId || uniqueID(), created: now }); storage.__session__ = session; @@ -4584,7 +4628,7 @@ return uid; })); function getStorage(_ref) { - var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime; + var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime, stickySessionId = _ref.stickySessionId; return inlineMemoize(getStorage, (function() { var STORAGE_KEY = "__" + name + "_storage__"; var newStateID = uniqueID(); @@ -4619,7 +4663,7 @@ var now = Date.now(); session && now - session.created > lifetime && (session = null); session || (session = { - guid: uniqueID(), + guid: stickySessionId || uniqueID(), created: now }); storage.__session__ = session; @@ -5059,7 +5103,7 @@ logger.addTrackingBuilder((function() { var _ref2; return (_ref2 = {}).state_name = "smart_button", _ref2.context_type = "button_session_id", - _ref2.context_id = buttonSessionID, _ref2.button_session_id = buttonSessionID, _ref2.button_version = "5.0.151", + _ref2.context_id = buttonSessionID, _ref2.button_session_id = buttonSessionID, _ref2.button_version = "5.0.164", _ref2.selected_payment_method = fundingSource, _ref2; })); (function() { diff --git a/dist/smart-native-popup.min.js b/dist/smart-native-popup.min.js index b1d1584560..a4a7d542cb 100644 --- a/dist/smart-native-popup.min.js +++ b/dist/smart-native-popup.min.js @@ -1 +1 @@ -!function(n,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("spbNativePopup",[],e):"object"==typeof exports?exports.spbNativePopup=e():n.spbNativePopup=e()}("undefined"!=typeof self?self:this,(function(){return function(n){var e={};function t(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return n[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=n,t.c=e,t.d=function(n,e,r){t.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:r})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,e){if(1&e&&(n=t(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)t.d(r,o,function(e){return n[e]}.bind(null,o));return r},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return{}.hasOwnProperty.call(n,e)},t.p="",t(t.s=2)}([function(n,e,t){n.exports=t(1)},function(n,e,t){"undefined"!=typeof self&&self,n.exports=function(n){var e={};function t(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return n[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=n,t.c=e,t.d=function(n,e,r){t.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:r})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,e){if(1&e&&(n=t(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)t.d(r,o,function(e){return n[e]}.bind(null,o));return r},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return{}.hasOwnProperty.call(n,e)},t.p="",t(t.s=0)}([function(n,e,t){"use strict";t.r(e),t.d(e,"getUserAgent",(function(){return o})),t.d(e,"isDevice",(function(){return u})),t.d(e,"isTablet",(function(){return a})),t.d(e,"isWebView",(function(){return c})),t.d(e,"isStandAlone",(function(){return s})),t.d(e,"isFacebookWebView",(function(){return f})),t.d(e,"isFirefox",(function(){return d})),t.d(e,"isFirefoxIOS",(function(){return l})),t.d(e,"isEdgeIOS",(function(){return h})),t.d(e,"isOperaMini",(function(){return p})),t.d(e,"isAndroid",(function(){return v})),t.d(e,"isIos",(function(){return w})),t.d(e,"isIOS14",(function(){return m})),t.d(e,"isGoogleSearchApp",(function(){return y})),t.d(e,"isQQBrowser",(function(){return g})),t.d(e,"isIosWebview",(function(){return b})),t.d(e,"isSFVC",(function(){return _})),t.d(e,"isSFVCorSafari",(function(){return S})),t.d(e,"isAndroidWebview",(function(){return E})),t.d(e,"isIE",(function(){return x})),t.d(e,"isIECompHeader",(function(){return k})),t.d(e,"isElectron",(function(){return O})),t.d(e,"isIEIntranet",(function(){return j})),t.d(e,"isMacOsCna",(function(){return C})),t.d(e,"supportsPopups",(function(){return P})),t.d(e,"isChrome",(function(){return T})),t.d(e,"isSafari",(function(){return I})),t.d(e,"isApplePaySupported",(function(){return A})),t.d(e,"isCrossSiteTrackingEnabled",(function(){return M})),t.d(e,"getBody",(function(){return Le})),t.d(e,"isDocumentReady",(function(){return Re})),t.d(e,"isDocumentInteractive",(function(){return Be})),t.d(e,"urlEncode",(function(){return Fe})),t.d(e,"waitForWindowReady",(function(){return Ue})),t.d(e,"waitForDocumentReady",(function(){return qe})),t.d(e,"waitForDocumentBody",(function(){return Ve})),t.d(e,"parseQuery",(function(){return Je})),t.d(e,"getQueryParam",(function(){return $e})),t.d(e,"urlWillRedirectPage",(function(){return Ge})),t.d(e,"formatQuery",(function(){return Qe})),t.d(e,"extendQuery",(function(){return Ke})),t.d(e,"extendUrl",(function(){return Ze})),t.d(e,"redirect",(function(){return Xe})),t.d(e,"hasMetaViewPort",(function(){return Ye})),t.d(e,"isElementVisible",(function(){return nt})),t.d(e,"getPerformance",(function(){return et})),t.d(e,"enablePerformance",(function(){return tt})),t.d(e,"getPageRenderTime",(function(){return rt})),t.d(e,"htmlEncode",(function(){return ot})),t.d(e,"isBrowser",(function(){return it})),t.d(e,"querySelectorAll",(function(){return ut})),t.d(e,"onClick",(function(){return at})),t.d(e,"getScript",(function(){return ct})),t.d(e,"isLocalStorageEnabled",(function(){return st})),t.d(e,"getBrowserLocales",(function(){return ft})),t.d(e,"appendChild",(function(){return dt})),t.d(e,"getElementSafe",(function(){return lt})),t.d(e,"getElement",(function(){return ht})),t.d(e,"elementReady",(function(){return pt})),t.d(e,"PopupOpenError",(function(){return wt})),t.d(e,"popup",(function(){return mt})),t.d(e,"writeToWindow",(function(){return yt})),t.d(e,"writeElementToWindow",(function(){return gt})),t.d(e,"setStyle",(function(){return bt})),t.d(e,"awaitFrameLoad",(function(){return _t})),t.d(e,"awaitFrameWindow",(function(){return St})),t.d(e,"createElement",(function(){return Et})),t.d(e,"iframe",(function(){return xt})),t.d(e,"addEventListener",(function(){return kt})),t.d(e,"bindEvents",(function(){return Ot})),t.d(e,"setVendorCSS",(function(){return Ct})),t.d(e,"animate",(function(){return It})),t.d(e,"makeElementVisible",(function(){return At})),t.d(e,"makeElementInvisible",(function(){return Mt})),t.d(e,"showElement",(function(){return Ht})),t.d(e,"hideElement",(function(){return zt})),t.d(e,"destroyElement",(function(){return Dt})),t.d(e,"showAndAnimate",(function(){return Nt})),t.d(e,"animateAndHide",(function(){return Wt})),t.d(e,"addClass",(function(){return Lt})),t.d(e,"removeClass",(function(){return Rt})),t.d(e,"isElementClosed",(function(){return Bt})),t.d(e,"watchElementForClose",(function(){return Ft})),t.d(e,"fixScripts",(function(){return Ut})),t.d(e,"onResize",(function(){return qt})),t.d(e,"getResourceLoadTime",(function(){return Vt})),t.d(e,"isShadowElement",(function(){return Jt})),t.d(e,"getShadowRoot",(function(){return $t})),t.d(e,"getShadowHost",(function(){return Gt})),t.d(e,"insertShadowSlot",(function(){return Qt})),t.d(e,"preventClickFocus",(function(){return Kt})),t.d(e,"getStackTrace",(function(){return Zt})),t.d(e,"getCurrentScript",(function(){return Yt})),t.d(e,"getCurrentScriptUID",(function(){return er})),t.d(e,"submitForm",(function(){return tr})),t.d(e,"experiment",(function(){return ar})),t.d(e,"getGlobalNameSpace",(function(){return cr})),t.d(e,"getStorage",(function(){return rr})),t.d(e,"isElement",(function(){return ln})),t.d(e,"getFunctionName",(function(){return hn})),t.d(e,"setFunctionName",(function(){return pn})),t.d(e,"base64encode",(function(){return vn})),t.d(e,"base64decode",(function(){return wn})),t.d(e,"uniqueID",(function(){return mn})),t.d(e,"getGlobal",(function(){return yn})),t.d(e,"getObjectID",(function(){return gn})),t.d(e,"getEmptyObject",(function(){return _n})),t.d(e,"memoize",(function(){return xn})),t.d(e,"promiseIdentity",(function(){return kn})),t.d(e,"memoizePromise",(function(){return On})),t.d(e,"promisify",(function(){return jn})),t.d(e,"inlineMemoize",(function(){return Cn})),t.d(e,"noop",(function(){return Pn})),t.d(e,"once",(function(){return Tn})),t.d(e,"hashStr",(function(){return In})),t.d(e,"strHashStr",(function(){return An})),t.d(e,"match",(function(){return Mn})),t.d(e,"awaitKey",(function(){return Hn})),t.d(e,"stringifyError",(function(){return zn})),t.d(e,"stringifyErrorMessage",(function(){return Dn})),t.d(e,"stringify",(function(){return Nn})),t.d(e,"domainMatches",(function(){return Wn})),t.d(e,"patchMethod",(function(){return Ln})),t.d(e,"extend",(function(){return Rn})),t.d(e,"values",(function(){return Bn})),t.d(e,"memoizedValues",(function(){return Fn})),t.d(e,"perc",(function(){return Un})),t.d(e,"min",(function(){return qn})),t.d(e,"max",(function(){return Vn})),t.d(e,"roundUp",(function(){return Jn})),t.d(e,"regexMap",(function(){return $n})),t.d(e,"svgToBase64",(function(){return Gn})),t.d(e,"objFilter",(function(){return Qn})),t.d(e,"identity",(function(){return Kn})),t.d(e,"regexTokenize",(function(){return Zn})),t.d(e,"promiseDebounce",(function(){return Xn})),t.d(e,"safeInterval",(function(){return Yn})),t.d(e,"isInteger",(function(){return ne})),t.d(e,"isFloat",(function(){return ee})),t.d(e,"serializePrimitive",(function(){return te})),t.d(e,"deserializePrimitive",(function(){return re})),t.d(e,"dotify",(function(){return oe})),t.d(e,"undotify",(function(){return ie})),t.d(e,"eventEmitter",(function(){return ue})),t.d(e,"camelToDasherize",(function(){return ae})),t.d(e,"dasherizeToCamel",(function(){return ce})),t.d(e,"capitalizeFirstLetter",(function(){return se})),t.d(e,"get",(function(){return fe})),t.d(e,"safeTimeout",(function(){return de})),t.d(e,"defineLazyProp",(function(){return le})),t.d(e,"arrayFrom",(function(){return he})),t.d(e,"isObject",(function(){return pe})),t.d(e,"isObjectObject",(function(){return ve})),t.d(e,"isPlainObject",(function(){return we})),t.d(e,"replaceObject",(function(){return me})),t.d(e,"copyProp",(function(){return ye})),t.d(e,"regex",(function(){return ge})),t.d(e,"regexAll",(function(){return be})),t.d(e,"isDefined",(function(){return _e})),t.d(e,"cycle",(function(){return Se})),t.d(e,"debounce",(function(){return Ee})),t.d(e,"isRegex",(function(){return xe})),t.d(e,"weakMapMemoize",(function(){return ke})),t.d(e,"weakMapMemoizePromise",(function(){return Oe})),t.d(e,"getOrSet",(function(){return je})),t.d(e,"cleanup",(function(){return Ce})),t.d(e,"tryCatch",(function(){return Pe})),t.d(e,"removeFromArray",(function(){return Te})),t.d(e,"assertExists",(function(){return Ie})),t.d(e,"unique",(function(){return Ae})),t.d(e,"constHas",(function(){return Me})),t.d(e,"dedupeErrors",(function(){return He})),t.d(e,"ExtendableError",(function(){return ze})),t.d(e,"request",(function(){return fr})),t.d(e,"addHeaderBuilder",(function(){return dr})),t.d(e,"TYPES",(function(){return lr})),t.d(e,"memoized",(function(){return hr})),t.d(e,"promise",(function(){return pr})),t.d(e,"isPerc",(function(){return vr})),t.d(e,"isPx",(function(){return wr})),t.d(e,"toNum",(function(){return mr})),t.d(e,"toPx",(function(){return yr})),t.d(e,"toCSS",(function(){return gr})),t.d(e,"percOf",(function(){return br})),t.d(e,"normalizeDimension",(function(){return _r})),t.d(e,"wrapPromise",(function(){return Sr})),t.d(e,"KEY_CODES",(function(){return De})),t.d(e,"ATTRIBUTES",(function(){return Ne})),t.d(e,"UID_HASH_LENGTH",(function(){return We})),t.d(e,"sfvcScreens",(function(){return r}));var r={932:{textSizeHeights:[746,742,738],textSizeHeightsNoTabs:[854,852,850,848],zoomHeight:{1.15:[746,742,738],1.25:[746,743],1.5:[746,743],1.75:[746,742,739],2:[746,742],2.5:[745,743],3:[749],3.01:[749]},maybeSafari:{1:[732],1.15:[733],1.25:[738,733],1.5:[738,732],1.75:[732],2:[738,732],2.5:[738,733],3:[743,740,734],3.01:[743,740,734]}},926:{textSizeHeights:[752,748,744,738],textSizeHeightsNoTabs:[860,858,856,854],zoomHeight:{1.15:[752,747,744,738],1.25:[753,748,744,738],1.5:[752,749,744,738],1.75:[753,747,744,739],2:[752,748,744],2.5:[753,748],3:[753,744]},maybeSafari:{2:[738],2.5:[745,738],3:[747,738]}},896:{textSizeHeights:[721,717,713,707],textSizeHeightsNoTabs:[829,827,825,823],zoomHeight:{1.15:[721,716,713,707],1.25:[721,718,713,708],1.5:[722,717,713],1.75:[721,718,712,707],2:[722,718,714,708],2.5:[720,718,713,708],3:[720,717,708]},maybeSafari:{1.5:[707],3:[714]}},852:{textSizeHeights:[666,662,658],textSizeHeightsNoTabs:[774,772,770,768],zoomHeight:{1.15:[666,662,658],1.25:[665,661,658],1.5:[666,662,659],1.75:[667,662],1.99:[663,659],2:[663,659],2.5:[665,663],3:[666,663]},maybeSafari:{1:[652],1.15:[652],1.25:[651],1.5:[653],1.75:[658,653],1.99:[655,649],2:[655,649],2.5:[658,653],3:[657,651]}},844:{textSizeHeights:[670,666,662,656],textSizeHeightsNoTabs:[778,776,774,772],zoomHeight:{1.15:[670,666,662],1.25:[670,666,663,656],1.5:[671,666,662],1.75:[670,667,662,656],2:[670,666,662],2.5:[670,663],3:[669,666,663,657]},maybeSafari:{1.15:[656],1.5:[656],2:[656],2.5:[665,655],3:[663]}},812:{textSizeHeights:[641,637,633,627],textSizeHeightsNoTabs:[749,747,745,743],zoomHeight:{1.15:[641,637,633,627],1.25:[641,638,633,628],1.5:[641,638,633,627],1.75:[641,637,634],2:[642,638,634,628],2.5:[640,638,633,628],3:[642,633]},maybeSafari:{1.75:[627],3:[636,627]}},736:{textSizeHeights:[628,624,620,614],textSizeHeightsNoTabs:[736,734,732,730],zoomHeight:{1.15:[628,624,620,614],1.25:[628,624,620,614],1.5:[629,624,620],1.75:[628,625,620,614],2:[628,624,620],2.5:[628,625,620,615],3:[627,624,615]},maybeSafari:{1.5:[614],2:[614],3:[621]}},667:{textSizeHeights:[559,555,551,545],textSizeHeightsNoTabs:[667,665,663,661],zoomHeight:{1.15:[559,555,551,545],1.25:[559,555,551,545],1.5:[560,555,551],1.75:[558,555,551],2:[560,556,552,546],2.5:[560,555,550],3:[558,555,546]},maybeSafari:{1.5:[545],1.75:[544],2.5:[545],3:[552]}}};function o(){return window.navigator.mockUserAgent||window.navigator.userAgent}var i=/ip(a|ro)d|silk|xoom|playbook|tablet|kindle|Nexus 7|GT-P10|SC-01C|SHW-M180S|SM-T320|SGH-T849|SCH-I800|SHW-M180L|SPH-P100|SGH-I987|zt180|HTC( Flyer|_Flyer)|Sprint ATP51|ViewPad7|pandigital(sprnova|nova)|Ideos S7|Dell Streak 7|Advent Vega|A101IT|A70BHT|MID7015|Next2|nook|FOLIO|MB511.*RUTEM|Mac OS.*Silk/i;function u(n){return void 0===n&&(n=o()),!!n.match(/Android|webOS|iPhone|iPad|iPod|bada|Symbian|Palm|CriOS|BlackBerry|IEMobile|WindowsMobile|Opera Mini/i)}function a(n){return void 0===n&&(n=o()),i.test(n)}function c(){var n=o();return/(iPhone|iPod|iPad|Macintosh).*AppleWebKit(?!.*Safari)|.*WKWebView/i.test(n)||/\bwv\b/.test(n)||/Android.*Version\/(\d)\.(\d)/i.test(n)}function s(){return!0===window.navigator.standalone||window.matchMedia("(display-mode: standalone)").matches}function f(n){return void 0===n&&(n=o()),/FBAN/.test(n)||/FBAV/.test(n)}function d(n){return void 0===n&&(n=o()),/Firefox/i.test(n)}function l(n){return void 0===n&&(n=o()),/FxiOS/i.test(n)}function h(n){return void 0===n&&(n=o()),/EdgiOS/i.test(n)}function p(n){return void 0===n&&(n=o()),/Opera Mini/i.test(n)}function v(n){return void 0===n&&(n=o()),/Android/.test(n)}function w(n){return void 0===n&&(n=o()),/iPhone|iPod|iPad/.test(n)}function m(n){return void 0===n&&(n=o()),/iPhone.*OS.*(1)?(?:(1)[0-4]| [0-9])_/.test(n)}function y(n){return void 0===n&&(n=o()),/\bGSA\b/.test(n)}function g(n){return void 0===n&&(n=o()),/QQBrowser/.test(n)}function b(n){return void 0===n&&(n=o()),!!w(n)&&(!!y(n)||/.+AppleWebKit(?!.*Safari)|.*WKWebView/.test(n))}function _(n){if(void 0===n&&(n=o()),w(n)){var e=window.innerHeight,t=Math.round(window.screen.width/window.innerWidth*100)/100,i=Math.round(e*t),u=null;if(m(n))u=r[window.outerHeight];else{if(1!==t)return!0;u=r[window.outerHeight]}return!u||(t>1&&u.zoomHeight&&u.zoomHeight[t]?-1!==u.zoomHeight[t].indexOf(i):-1!==u.textSizeHeights.indexOf(i)||-1!==u.textSizeHeightsNoTabs.indexOf(i))}return!1}function S(n){if(void 0===n&&(n=o()),w(n)){var e=_(n),t=m(n)?r[window.outerHeight]:null;if(!t)return!1;var i=window.innerHeight,u=Math.round(window.screen.width/window.innerWidth*100)/100,a=Math.round(i*u),c=t.maybeSafari,s=!1;return u>1&&c[u]&&-1!==c[u].indexOf(a)&&(s=!0),e||s}return!1}function E(n){return void 0===n&&(n=o()),!!v(n)&&/Version\/[\d.]+/.test(n)&&!p(n)}function x(){return!!window.document.documentMode||Boolean(window.navigator&&window.navigator.userAgent&&/Edge|MSIE|rv:11/i.test(window.navigator.userAgent))}function k(){var n=window.document.querySelector('meta[http-equiv="X-UA-Compatible"]'),e=window.document.querySelector('meta[content="IE=edge"]');return!(!n||!e)}function O(){return!("undefined"==typeof process||!process.versions||!process.versions.electron)}function j(){if(window.document.documentMode)try{var n=window.status;return window.status="testIntranetMode","testIntranetMode"===window.status&&(window.status=n,!0)}catch(n){return!1}return!1}function C(){var n=o();return/Macintosh.*AppleWebKit(?!.*Safari)/i.test(n)}function P(n){return void 0===n&&(n=o()),!(b(n)||E(n)||p(n)||l(n)||h(n)||f(n)||g(n)||O()||C()||s())}function T(n){return void 0===n&&(n=o()),/Chrome|Chromium|CriOS/.test(n)&&!/SamsungBrowser|Silk|EdgA/.test(n)}function I(n){return void 0===n&&(n=o()),/Safari/.test(n)&&!T(n)&&!/Silk|FxiOS|EdgiOS/.test(n)}function A(){try{if(window.ApplePaySession&&window.ApplePaySession.supportsVersion(3)&&window.ApplePaySession.canMakePayments())return!0}catch(n){return!1}return!1}function M(n){return-1===window.document.cookie.indexOf(n)}function H(n,e){return(H=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function z(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,H(n,e)}function D(){return(D=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var t=n&&n.stack,r=n&&n.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+zn(n,e+1)}}function Dn(n){var e="";return n?n instanceof Error?n.message||e:"string"==typeof n.message&&n.message||e:e}function Nn(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function Wn(n,e){var t=(n=n.split("://")[1]).indexOf(e);return-1!==t&&n.slice(t)===e}function Ln(n,e,t){var r=n[e];n[e]=function(){var n=arguments,e=this;return t({context:this,args:[].slice.call(arguments),original:r,callOriginal:function(){return r.apply(e,n)}})}}function Rn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}function Bn(n){if(Object.values)return Object.values(n);var e=[];for(var t in n)n.hasOwnProperty(t)&&e.push(n[t]);return e}xn.clear=function(){En=Sn};var Fn=xn(Bn);function Un(n,e){return Math.round(n*e/100)}function qn(){return Math.min.apply(Math,arguments)}function Vn(){return Math.max.apply(Math,arguments)}function Jn(n,e){var t=n%e;return t?n-t+e:n}function $n(n,e,t){var r=[];return n.replace(e,(function(n){r.push(t?t.apply(null,arguments):n)})),r}function Gn(n){return"data:image/svg+xml;base64,"+vn(n)}function Qn(n,e){void 0===e&&(e=Boolean);var t={};for(var r in n)n.hasOwnProperty(r)&&e(n[r],r)&&(t[r]=n[r]);return t}function Kn(n){return n}function Zn(n,e){var t=[];return n.replace(e,(function(n){return t.push(n),""})),t}function Xn(n,e){var t,r;return void 0===e&&(e=50),pn((function(){r&&clearTimeout(r);var o=t=t||new V;return r=setTimeout((function(){t=null,r=null,V.try(n).then((function(n){o.resolve(n)}),(function(n){o.reject(n)}))}),e),o}),hn(n)+"::promiseDebounced")}function Yn(n,e){var t;return function r(){t=setTimeout((function(){n(),r()}),e)}(),{cancel:function(){clearTimeout(t)}}}function ne(n){return Boolean(n.match(/^[0-9]+$/))}function ee(n){return Boolean(n.match(/^[0-9]+\.[0-9]+$/))}function te(n){return n.toString()}function re(n){return"true"===n||"false"!==n&&(ne(n)?parseInt(n,10):ee(n)?parseFloat(n):n)}function oe(n,e,t){for(var r in void 0===e&&(e=""),void 0===t&&(t={}),e=e?e+".":e,n)n.hasOwnProperty(r)&&null!=n[r]&&"function"!=typeof n[r]&&(n[r]&&Array.isArray(n[r])&&n[r].length&&n[r].every((function(n){return"object"!=typeof n}))?t[""+e+r+"[]"]=n[r].join(","):n[r]&&"object"==typeof n[r]?t=oe(n[r],""+e+r,t):t[""+e+r]=te(n[r]));return t}function ie(n){var e={};for(var t in n)if(n.hasOwnProperty(t)&&"string"==typeof n[t]){var r=n[t];t.match(/^.+\[\]$/)?(t=t.slice(0,-2),r=r.split(",").map(re)):r=re(r);for(var o=e,i=t.split("."),u=0;u1?t-1:0),o=1;o1?r-1:0),i=1;i1e3&&n.now()-(n.timing.connectEnd-n.timing.navigationStart)>0)return n}))}function tt(){return Boolean(et())}function rt(){return qe().then((function(){var n=et();if(n){var e=n.timing;return e.connectEnd&&e.domInteractive?e.domInteractive-e.connectEnd:void 0}}))}function ot(n){return void 0===n&&(n=""),n.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function it(){return"undefined"!=typeof window&&void 0!==window.location}function ut(n,e){return void 0===e&&(e=window.document),[].slice.call(e.querySelectorAll(n))}function at(n,e){n.addEventListener("touchstart",Pn,{passive:!0}),n.addEventListener("click",e),n.addEventListener("keypress",(function(n){if(n.keyCode===De.ENTER||n.keyCode===De.SPACE)return e(n)}))}function ct(n){var e=n.host,t=void 0===e?window.location.host:e,r=n.path,o=n.reverse,i=void 0!==o&&o;return Cn(ct,(function(){var n=""+t+r,e=[].slice.call(document.getElementsByTagName("script"));i&&e.reverse();for(var o=0;or&&(t=null),t||(t={guid:mn(),created:o}),e.__session__=t,n(t)}))}return{getState:i,getID:u,isStateFresh:function(){return u()===o},getSessionState:function(n){return a((function(e){return e.state=e.state||{},n(e.state)}))},getSessionID:function(){return a((function(n){return n.guid}))}}}),[{name:e,lifetime:r}])}function or(){return rr({name:"belter_experiment"})}function ir(n){return or().getSessionState((function(e){return e.loggedBeacons=e.loggedBeacons||[],-1===e.loggedBeacons.indexOf(n)&&(e.loggedBeacons.push(n),!0)}))}function ur(n){return Math.floor(Math.random()*n)}function ar(n){var e,t=n.name,r=n.sample,o=void 0===r?50:r,i=n.logTreatment,u=void 0===i?Pn:i,a=n.logCheckpoint,c=void 0===a?Pn:a,s=n.sticky,f=void 0===s||s?function(n){return or().getState((function(e){return e.throttlePercentiles=e.throttlePercentiles||{},e.throttlePercentiles[n]=e.throttlePercentiles[n]||ur(100),e.throttlePercentiles[n]}))}(t):ur(100),d=t+"_"+(e=f=50||o<=f&&f<2*o?"control":"throttle"),l=!1,h=!1;try{window.localStorage&&window.localStorage.getItem(t)&&(h=!0)}catch(n){}var p={isEnabled:function(){return"test"===e||h},isDisabled:function(){return"test"!==e&&!h},getTreatment:function(){return d},log:function(n,e){return void 0===e&&(e={}),l?(ir(d+"_"+JSON.stringify(e))&&u({name:t,treatment:d,payload:e,throttle:f}),ir(d+"_"+n+"_"+JSON.stringify(e))&&c({name:t,treatment:d,checkpoint:n,payload:e,throttle:f}),p):p},logStart:function(n){return void 0===n&&(n={}),l=!0,p.log("start",n)},logComplete:function(n){return void 0===n&&(n={}),p.log("complete",n)}};return p}function cr(n){var e=n.name,t=n.version,r=void 0===t?"latest":t,o=yn(),i="__"+e+"__"+r+"_global__",u=o[i]=o[i]||{};return{get:function(n,e){return e=e||{},u[n]=u[n]||e}}}var sr=[];function fr(n){var e=n.url,t=n.method,r=void 0===t?"get":t,o=n.headers,i=void 0===o?{}:o,u=n.json,a=n.data,c=n.body,s=n.win,f=void 0===s?window:s,d=n.timeout,l=void 0===d?0:d;return new V((function(n,t){if(u&&a||u&&c||a&&u)throw new Error("Only options.json or options.data or options.body should be passed");for(var o={},s=0,d=Object.keys(i);s1&&c.zoomHeight&&c.zoomHeight[t]?-1!==c.zoomHeight[t].indexOf(a):-1!==c.textSizeHeights.indexOf(a)||-1!==c.textSizeHeightsNoTabs.indexOf(a))}return!1}function c(n,e){return(c=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function s(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,c(n,e)}function f(){return(f=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var t=n&&n.stack,r=n&&n.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+Z(n,e+1)}}function X(n){var e="";return n?n instanceof Error?n.message||e:"string"==typeof n.message&&n.message||e:e}function Y(n,e){void 0===e&&(e=Boolean);var t={};for(var r in n)n.hasOwnProperty(r)&&e(n[r],r)&&(t[r]=n[r]);return t}G.clear=function(){$=J},G((function(n){if(Object.values)return Object.values(n);var e=[];for(var t in n)n.hasOwnProperty(t)&&e.push(n[t]);return e}));var nn=function(n){function e(e){var t;return(t=n.call(this,e)||this).name=t.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(n){if(void 0===n)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}(t),t.constructor):t.stack=new Error(e).stack,t}return s(e,n),e}(W(Error));function en(){return Boolean(document.body)&&"complete"===document.readyState}function tn(){return Boolean(document.body)&&"interactive"===document.readyState}var rn,on=G((function(){return new g((function(n){if(en()||tn())return n();var e=setInterval((function(){if(en()||tn())return clearInterval(e),n()}),10)}))}));function un(n){return Q(un,(function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var t=0,r=n.split("&");t1e3&&n.now()-(n.timing.connectEnd-n.timing.navigationStart)>0)return n}))}function cn(){return"undefined"!=typeof window&&void 0!==window.location}function sn(){return Q(sn,(function(){try{if("undefined"==typeof window)return!1;if(window.localStorage){var n=Math.random().toString();window.localStorage.setItem("__test__localStorage__",n);var e=window.localStorage.getItem("__test__localStorage__");if(window.localStorage.removeItem("__test__localStorage__"),n===e)return!0}}catch(n){}return!1}))}s((function(){return rn.apply(this,arguments)||this}),rn=nn);var fn="undefined"!=typeof document?document.currentScript:null,dn=G((function(){if(fn)return fn;if(fn=function(){try{var n=function(){try{throw new Error("_")}catch(n){return n.stack||""}}(),e=/.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(n),t=e&&e[1];if(!t)return;for(var r=0,o=[].slice.call(document.getElementsByTagName("script")).reverse();rr&&(t=null),t||(t={guid:F(),created:o}),e.__session__=t,n(t)}))}return{getState:i,getID:u,isStateFresh:function(){return u()===o},getSessionState:function(n){return a((function(e){return e.state=e.state||{},n(e.state)}))},getSessionID:function(){return a((function(n){return n.guid}))}}}),[{name:e,lifetime:r}])}G((function(){var n;try{n=dn()}catch(n){return ln}var e=n.getAttribute("data-uid");if(e&&"string"==typeof e)return e;if((e=n.getAttribute("data-uid-auto"))&&"string"==typeof e)return e;if(n.src){var t=function(n){for(var e="",t=0;tmn.indexOf(i))){var r=[e];r.push(t),(t.error||t.warning)&&r.push("\n\n",t.error||t.warning);try{window.console[n]&&window.console[n].apply?window.console[n].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(n){}}}function S(){return g.try((function(){if(cn()&&"file:"!==window.location.protocol&&(h.length||p.length||v.length)){for(var n={},e=0;e1&&d[s]&&-1!==d[s].indexOf(f)&&(l=!0),e||l}return!1}(),E=_?"sfvc":S?"sfvcOrSafari":"browser";if(_n()){var x,k=window.innerHeight,O=Math.round(window.screen.width/window.innerWidth*100)/100,j=Math.round(k*O),C="native_popup_init_"+E;v.info(C).track((x={},x.transition_name=C,x.info_msg="computed height: "+j+", height: "+window.outerHeight+", width: "+window.outerWidth+", innerHeight: "+k+", scale: "+O,x)).flush()}window.addEventListener("beforeunload",(function(){var n;v.info("native_popup_beforeunload").track((n={},n.transition_name="native_popup_beforeunload",n)).flush()})),window.addEventListener("unload",(function(){var n;v.info("native_popup_unload").track((n={},n.transition_name="native_popup_unload",n)).flush()})),window.addEventListener("pagehide",(function(){var n;v.info("native_popup_pagehide").track((n={},n.transition_name="native_popup_pagehide",n)).flush()}));var P,I,A,M,H,z=function(n){return window.location.replace("#"+n.replace(/^#/,""))},D=function(){window.close(),z("closed")},N=function(){return(window.location.hash||"none").replace(/^#/,"").replace(/\?.+/,"")},W=window.opener;if(!W){var F;if(_n()){var U,q="popup_no_opener_hash_"+N()+"_"+E;v.info(q).track((U={},U.transition_name=q,U)).flush()}throw v.info("native_popup_no_opener",{buttonSessionID:d,href:B(window.location.href)}).info("native_popup_no_opener_hash_"+N()).track((F={},F.transition_name="popup_no_opener_hash_"+N(),F.info_msg="location: "+B(window.location.href),F)).flush().then(D),new Error("Expected window to have opener")}P=window.opener,I=function(){var n;v.info("native_popup_opener_detect_close").track((n={},n.transition_name="native_popup_opener_detect_close",n)).flush().then(D)},void 0===(A=500)&&(A=1e3),void 0===M&&(M=1/0),function n(){if(T(P))return H&&clearTimeout(H),I();M<=0?clearTimeout(H):(M-=A,H=setTimeout(n,A))}();var V,J,$,G,Q=(J=[],$=!1,G={set:function(n,e){return $||((void 0)[n]=e,G.register((function(){delete(void 0)[n]}))),e},register:function(n){var e=function(n){var e=!1;return R((function(){if(!e)return e=!0,n.apply(this,arguments)}),L(n)+"::once")}((function(){return n(V)}));return $?n(V):J.push(e),{cancel:function(){var n=J.indexOf(e);-1!==n&&J.splice(n,1)}}},all:function(n){V=n;var e=[];for($=!0;J.length;){var t=J.shift();e.push(t())}return g.all(e).then(K)}}),Y=function(){var n=Sn();if(!n.postRobot)throw new Error("paypal.postRobot not found");return n.postRobot}(),nn=function(n,e){return void 0===e&&(e={}),Y.send(W,n,e,{domain:c}).then((function(n){return n.data}))},en=function(){if(window.location.hash&&"#"!==window.location.hash){var n=(window.location.hash&&window.location.hash.slice(1)).split("?"),e=n[0],t=n[1];switch(e){case"init":case"loaded":case"appswitch":case"webswitch":case"closed":break;case"onApprove":var r=un(t);nn("onApprove",{payerID:r.payerID,paymentID:r.paymentID,billingToken:r.billingToken}).finally(D);break;case"onCancel":nn("onCancel").finally(D);break;case"fallback":var o=un(t);nn("onFallback",{type:o.type,skip_native_duration:o.skip_native_duration,fallback_reason:o.fallback_reason});break;case"onError":var i=un(t);nn("onError",{message:i.message}).finally(D);break;case"close":nn("onComplete").finally(D);break;case"test":break;default:nn("onError",{message:"Invalid event sent from native, "+e+", from URL, "+window.location.href}).finally(D)}}};window.addEventListener("hashchange",en),Q.register((function(){return window.removeEventListener("hashchange",en)})),z("loaded"),en();var tn=hn({name:"paypal",lifetime:36e5}).getID(),rn=window.location.href.split("#")[0]+"#close";return b.then((function(n){nn("awaitRedirect",{app:n,pageUrl:rn,sfvc:_=!!_||!0===S,stickinessID:tn}).then((function(n){var e=n.redirect,t=n.redirectUrl,r=n.orderID,o=n.appSwitch,i=void 0===o||o;if(void 0===e||e){r&&v.addTrackingBuilder((function(){var n;return(n={}).context_type="EC-Token",n.context_id=r,n.token=r,n})),z(i?"appswitch":"webswitch"),window.location.replace(t);var u=!1,a=function(){u=!0};if(window.addEventListener("beforeunload",a),Q.register((function(){return window.removeEventListener("beforeunload",a)})),window.addEventListener("unload",a),Q.register((function(){return window.removeEventListener("unload",a)})),window.addEventListener("pagehide",a),Q.register((function(){return window.removeEventListener("pagehide",a)})),i){var c=setTimeout((function(){u||nn("detectAppSwitch")}),1500);Q.register((function(){return clearTimeout(c)}))}}}))})),{destroy:function(){return Q.all()}}}function On(n,e){for(var t=[],r=0;r1?new Cn(e):void 0}(this.component(this.props,this.children));if(e)return e.render(n)},e.render=function(n){return n(this)},e.renderChildren=function(n){return On(this.children,n)},n}();function In(n){for(var e=[],t=0;t2?t-2:0),o=2;o1&&u.zoomHeight&&u.zoomHeight[t]?-1!==u.zoomHeight[t].indexOf(i):-1!==u.textSizeHeights.indexOf(i)||-1!==u.textSizeHeightsNoTabs.indexOf(i))}return!1}function S(n){if(void 0===n&&(n=o()),w(n)){var e=_(n),t=m(n)?r[window.outerHeight]:null;if(!t)return!1;var i=window.innerHeight,u=Math.round(window.screen.width/window.innerWidth*100)/100,a=Math.round(i*u),c=t.maybeSafari,s=!1;return u>1&&c[u]&&-1!==c[u].indexOf(a)&&(s=!0),e||s}return!1}function E(n){return void 0===n&&(n=o()),!!v(n)&&/Version\/[\d.]+/.test(n)&&!p(n)}function x(){return!!window.document.documentMode||Boolean(window.navigator&&window.navigator.userAgent&&/Edge|MSIE|rv:11/i.test(window.navigator.userAgent))}function k(){var n=window.document.querySelector('meta[http-equiv="X-UA-Compatible"]'),e=window.document.querySelector('meta[content="IE=edge"]');return!(!n||!e)}function O(){return!("undefined"==typeof process||!process.versions||!process.versions.electron)}function j(){if(window.document.documentMode)try{var n=window.status;return window.status="testIntranetMode","testIntranetMode"===window.status&&(window.status=n,!0)}catch(n){return!1}return!1}function C(){var n=o();return/Macintosh.*AppleWebKit(?!.*Safari)/i.test(n)}function P(n){return void 0===n&&(n=o()),!(c(n)||b(n)||E(n)||p(n)||l(n)||h(n)||f(n)||g(n)||O()||C()||s())}function T(n){return void 0===n&&(n=o()),/Chrome|Chromium|CriOS/.test(n)&&!/SamsungBrowser|Silk|EdgA/.test(n)}function I(n){return void 0===n&&(n=o()),/Safari/.test(n)&&!T(n)&&!/Silk|FxiOS|EdgiOS/.test(n)}function A(){try{if(window.ApplePaySession&&window.ApplePaySession.supportsVersion(3)&&window.ApplePaySession.canMakePayments())return!0}catch(n){return!1}return!1}function M(n){return-1===window.document.cookie.indexOf(n)}function H(n,e){return(H=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function z(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,H(n,e)}function D(){return(D=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var t=n&&n.stack,r=n&&n.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+Vn(n,e+1)}}function Jn(n){var e="";return n?n instanceof Error?n.message||e:"string"==typeof n.message&&n.message||e:e}function $n(n){return"string"==typeof n?n:n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}function Gn(n,e){var t=(n=n.split("://")[1]).indexOf(e);return-1!==t&&n.slice(t)===e}function Kn(n,e,t){var r=n[e];n[e]=function(){var n=arguments,e=this;return t({context:this,args:[].slice.call(arguments),original:r,callOriginal:function(){return r.apply(e,n)}})}}function Qn(n,e){if(!e)return n;if(Object.assign)return Object.assign(n,e);for(var t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}function Zn(n){if(Object.values)return Object.values(n);var e=[];for(var t in n)n.hasOwnProperty(t)&&e.push(n[t]);return e}Hn.clear=function(){Mn=An};var Xn=Hn(Zn);function Yn(n,e){return Math.round(n*e/100)}function ne(){return Math.min.apply(Math,arguments)}function ee(){return Math.max.apply(Math,arguments)}function te(n,e){var t=n%e;return t?n-t+e:n}function re(n,e,t){var r=[];return n.replace(e,(function(n){r.push(t?t.apply(null,arguments):n)})),r}function oe(n){return"data:image/svg+xml;base64,"+kn(n)}function ie(n,e){void 0===e&&(e=Boolean);var t={};for(var r in n)n.hasOwnProperty(r)&&e(n[r],r)&&(t[r]=n[r]);return t}function ue(n){return n}function ae(n,e){var t=[];return n.replace(e,(function(n){return t.push(n),""})),t}function ce(n,e){var t,r;return void 0===e&&(e=50),xn((function(){r&&clearTimeout(r);var o=t=t||new V;return r=setTimeout((function(){t=null,r=null,V.try(n).then((function(n){o.resolve(n)}),(function(n){o.reject(n)}))}),e),o}),En(n)+"::promiseDebounced")}function se(n,e){var t;return function r(){t=setTimeout((function(){n(),r()}),e)}(),{cancel:function(){clearTimeout(t)}}}function fe(n){return Boolean(n.match(/^[0-9]+$/))}function de(n){return Boolean(n.match(/^[0-9]+\.[0-9]+$/))}function le(n){return n.toString()}function he(n){return"true"===n||"false"!==n&&(fe(n)?parseInt(n,10):de(n)?parseFloat(n):n)}function pe(n,e,t){for(var r in void 0===e&&(e=""),void 0===t&&(t={}),e=e?e+".":e,n)n.hasOwnProperty(r)&&null!=n[r]&&"function"!=typeof n[r]&&(n[r]&&Array.isArray(n[r])&&n[r].length&&n[r].every((function(n){return"object"!=typeof n}))?t[""+e+r+"[]"]=n[r].join(","):n[r]&&"object"==typeof n[r]?t=pe(n[r],""+e+r,t):t[""+e+r]=le(n[r]));return t}function ve(n){var e={};for(var t in n)if(n.hasOwnProperty(t)&&"string"==typeof n[t]){var r=n[t];t.match(/^.+\[\]$/)?(t=t.slice(0,-2),r=r.split(",").map(he)):r=he(r);for(var o=e,i=t.split("."),u=0;u1?t-1:0),o=1;o1?r-1:0),i=1;i-1}(t))return t;var r=t.match(gn);return r&&vn.test(r[0])?_n:t}function $e(){var n=document.body;if(!n)throw new Error("Body element not found");return n}function Ge(){return Boolean(document.body)&&"complete"===document.readyState}function Ke(){return Boolean(document.body)&&"interactive"===document.readyState}function Qe(n){return encodeURIComponent(n)}function Ze(){return Rn(Ze,(function(){return new V((function(n){Ge()&&n(),window.addEventListener("load",(function(){return n()}))}))}))}var Xe=Hn((function(){return new V((function(n){if(Ge()||Ke())return n();var e=setInterval((function(){if(Ge()||Ke())return clearInterval(e),n()}),10)}))}));function Ye(){return V.try((function(){return document.body?document.body:Xe().then((function(){if(document.body)return document.body;throw new Error("Document ready but document.body not present")}))}))}function nt(n){return Rn(nt,(function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var t=0,r=n.split("&");t1e3&&n.now()-(n.timing.connectEnd-n.timing.navigationStart)>0)return n}))}function ft(){return Boolean(st())}function dt(){return Xe().then((function(){var n=st();if(n){var e=n.timing;return e.connectEnd&&e.domInteractive?e.domInteractive-e.connectEnd:void 0}}))}function lt(n){return void 0===n&&(n=""),n.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function ht(){return"undefined"!=typeof window&&void 0!==window.location}function pt(n,e){return void 0===e&&(e=window.document),[].slice.call(e.querySelectorAll(n))}function vt(n,e){n.addEventListener("touchstart",Ln,{passive:!0}),n.addEventListener("click",e),n.addEventListener("keypress",(function(n){if(n.keyCode===ln.ENTER||n.keyCode===ln.SPACE)return e(n)}))}function wt(n){var e=n.host,t=void 0===e?window.location.host:e,r=n.path,o=n.reverse,i=void 0!==o&&o;return Rn(wt,(function(){var n=""+t+r,e=[].slice.call(document.getElementsByTagName("script"));i&&e.reverse();for(var o=0;or&&(t=null),t||(t={guid:o||jn(),created:i}),e.__session__=t,n(t)}))}return{getState:u,getID:a,isStateFresh:function(){return a()===i},getSessionState:function(n){return c((function(e){return e.state=e.state||{},n(e.state)}))},getSessionID:function(){return c((function(n){return n.guid}))}}}),[{name:e,lifetime:r}])}function lr(){return dr({name:"belter_experiment"})}function hr(n){return lr().getSessionState((function(e){return e.loggedBeacons=e.loggedBeacons||[],-1===e.loggedBeacons.indexOf(n)&&(e.loggedBeacons.push(n),!0)}))}function pr(n){return Math.floor(Math.random()*n)}function vr(n){var e,t=n.name,r=n.sample,o=void 0===r?50:r,i=n.logTreatment,u=void 0===i?Ln:i,a=n.logCheckpoint,c=void 0===a?Ln:a,s=n.sticky,f=void 0===s||s?function(n){return lr().getState((function(e){return e.throttlePercentiles=e.throttlePercentiles||{},e.throttlePercentiles[n]=e.throttlePercentiles[n]||pr(100),e.throttlePercentiles[n]}))}(t):pr(100),d=t+"_"+(e=f=50||o<=f&&f<2*o?"control":"throttle"),l=!1,h=!1;try{window.localStorage&&window.localStorage.getItem(t)&&(h=!0)}catch(n){}var p={isEnabled:function(){return"test"===e||h},isDisabled:function(){return"test"!==e&&!h},getTreatment:function(){return d},log:function(n,e){return void 0===e&&(e={}),l?(hr(d+"_"+JSON.stringify(e))&&u({name:t,treatment:d,payload:e,throttle:f}),hr(d+"_"+n+"_"+JSON.stringify(e))&&c({name:t,treatment:d,checkpoint:n,payload:e,throttle:f}),p):p},logStart:function(n){return void 0===n&&(n={}),l=!0,p.log("start",n)},logComplete:function(n){return void 0===n&&(n={}),p.log("complete",n)}};return p}function wr(n){var e=n.name,t=n.version,r=void 0===t?"latest":t,o=Cn(),i="__"+e+"__"+r+"_global__",u=o[i]=o[i]||{};return{get:function(n,e){return e=e||{},u[n]=u[n]||e}}}var mr=[];function yr(n){var e=n.url,t=n.method,r=void 0===t?"get":t,o=n.headers,i=void 0===o?{}:o,u=n.json,a=n.data,c=n.body,s=n.win,f=void 0===s?window:s,d=n.timeout,l=void 0===d?0:d;return new V((function(n,t){if(u&&a||u&&c||a&&u)throw new Error("Only options.json or options.data or options.body should be passed");for(var o={},s=0,d=Object.keys(i);s1&&c.zoomHeight&&c.zoomHeight[t]?-1!==c.zoomHeight[t].indexOf(a):-1!==c.textSizeHeights.indexOf(a)||-1!==c.textSizeHeightsNoTabs.indexOf(a))}return!1}function c(n,e){return(c=Object.setPrototypeOf||function(n,e){return n.__proto__=e,n})(n,e)}function s(n,e){n.prototype=Object.create(e.prototype),n.prototype.constructor=n,c(n,e)}function f(){return(f=Object.assign||function(n){for(var e=1;e>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var n=new WeakMap,e={};return Object.freeze(e),n.set(e,"__testvalue__"),"__testvalue__"===n.get(e)}catch(n){return!1}}())try{this.weakmap=new WeakMap}catch(n){}this.keys=[],this.values=[]}var e=n.prototype;return e._cleanupClosedWindows=function(){for(var n=this.weakmap,e=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!n)return"";if("string"==typeof n)return n;if(n instanceof Error){var t=n&&n.stack,r=n&&n.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return n&&n.toString&&"function"==typeof n.toString?n.toString():{}.toString.call(n)}catch(n){return"Error while stringifying error: "+Z(n,e+1)}}function X(n){var e="";return n?n instanceof Error?n.message||e:"string"==typeof n.message&&n.message||e:e}function Y(n,e){void 0===e&&(e=Boolean);var t={};for(var r in n)n.hasOwnProperty(r)&&e(n[r],r)&&(t[r]=n[r]);return t}G.clear=function(){$=J},G((function(n){if(Object.values)return Object.values(n);var e=[];for(var t in n)n.hasOwnProperty(t)&&e.push(n[t]);return e}));var nn=function(n){function e(e){var t;return(t=n.call(this,e)||this).name=t.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(n){if(void 0===n)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}(t),t.constructor):t.stack=new Error(e).stack,t}return s(e,n),e}(R(Error));function en(){return Boolean(document.body)&&"complete"===document.readyState}function tn(){return Boolean(document.body)&&"interactive"===document.readyState}var rn,on=G((function(){return new g((function(n){if(en()||tn())return n();var e=setInterval((function(){if(en()||tn())return clearInterval(e),n()}),10)}))}));function un(n){return K(un,(function(){var e={};if(!n)return e;if(-1===n.indexOf("="))return e;for(var t=0,r=n.split("&");t1e3&&n.now()-(n.timing.connectEnd-n.timing.navigationStart)>0)return n}))}function cn(){return"undefined"!=typeof window&&void 0!==window.location}function sn(){return K(sn,(function(){try{if("undefined"==typeof window)return!1;if(window.localStorage){var n=Math.random().toString();window.localStorage.setItem("__test__localStorage__",n);var e=window.localStorage.getItem("__test__localStorage__");if(window.localStorage.removeItem("__test__localStorage__"),n===e)return!0}}catch(n){}return!1}))}s((function(){return rn.apply(this,arguments)||this}),rn=nn);var fn="undefined"!=typeof document?document.currentScript:null,dn=G((function(){if(fn)return fn;if(fn=function(){try{var n=function(){try{throw new Error("_")}catch(n){return n.stack||""}}(),e=/.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(n),t=e&&e[1];if(!t)return;for(var r=0,o=[].slice.call(document.getElementsByTagName("script")).reverse();rr&&(t=null),t||(t={guid:o||F(),created:i}),e.__session__=t,n(t)}))}return{getState:u,getID:a,isStateFresh:function(){return a()===i},getSessionState:function(n){return c((function(e){return e.state=e.state||{},n(e.state)}))},getSessionID:function(){return c((function(n){return n.guid}))}}}),[{name:e,lifetime:r}])}G((function(){var n;try{n=dn()}catch(n){return ln}var e=n.getAttribute("data-uid");if(e&&"string"==typeof e)return e;if((e=n.getAttribute("data-uid-auto"))&&"string"==typeof e)return e;if(n.src){var t=function(n){for(var e="",t=0;tmn.indexOf(i))){var r=[e];r.push(t),(t.error||t.warning)&&r.push("\n\n",t.error||t.warning);try{window.console[n]&&window.console[n].apply?window.console[n].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(n){}}}function S(){return g.try((function(){if(cn()&&"file:"!==window.location.protocol&&(h.length||p.length||v.length)){for(var n={},e=0;e1&&d[s]&&-1!==d[s].indexOf(f)&&(l=!0),e||l}return!1}(),E=_?"sfvc":S?"sfvcOrSafari":"browser";if(_n()){var x,k=window.innerHeight,O=Math.round(window.screen.width/window.innerWidth*100)/100,j=Math.round(k*O),C="native_popup_init_"+E;v.info(C).track((x={},x.transition_name=C,x.info_msg="computed height: "+j+", height: "+window.outerHeight+", width: "+window.outerWidth+", innerHeight: "+k+", scale: "+O,x)).flush()}window.addEventListener("beforeunload",(function(){var n;v.info("native_popup_beforeunload").track((n={},n.transition_name="native_popup_beforeunload",n)).flush()})),window.addEventListener("unload",(function(){var n;v.info("native_popup_unload").track((n={},n.transition_name="native_popup_unload",n)).flush()})),window.addEventListener("pagehide",(function(){var n;v.info("native_popup_pagehide").track((n={},n.transition_name="native_popup_pagehide",n)).flush()}));var P,I,A,M,H,z=function(n){return window.location.replace("#"+n.replace(/^#/,""))},D=function(){window.close(),z("closed")},N=function(){return(window.location.hash||"none").replace(/^#/,"").replace(/\?.+/,"")},R=window.opener;if(!R){var F;if(_n()){var U,q="popup_no_opener_hash_"+N()+"_"+E;v.info(q).track((U={},U.transition_name=q,U)).flush()}throw v.info("native_popup_no_opener",{buttonSessionID:d,href:B(window.location.href)}).info("native_popup_no_opener_hash_"+N()).track((F={},F.transition_name="popup_no_opener_hash_"+N(),F.info_msg="location: "+B(window.location.href),F)).flush().then(D),new Error("Expected window to have opener")}P=window.opener,I=function(){var n;v.info("native_popup_opener_detect_close").track((n={},n.transition_name="native_popup_opener_detect_close",n)).flush().then(D)},void 0===(A=500)&&(A=1e3),void 0===M&&(M=1/0),function n(){if(T(P))return H&&clearTimeout(H),I();M<=0?clearTimeout(H):(M-=A,H=setTimeout(n,A))}();var V,J,$,G,K=(J=[],$=!1,G={set:function(n,e){return $||((void 0)[n]=e,G.register((function(){delete(void 0)[n]}))),e},register:function(n){var e=function(n){var e=!1;return W((function(){if(!e)return e=!0,n.apply(this,arguments)}),L(n)+"::once")}((function(){return n(V)}));return $?n(V):J.push(e),{cancel:function(){var n=J.indexOf(e);-1!==n&&J.splice(n,1)}}},all:function(n){V=n;var e=[];for($=!0;J.length;){var t=J.shift();e.push(t())}return g.all(e).then(Q)}}),Y=function(){var n=Sn();if(!n.postRobot)throw new Error("paypal.postRobot not found");return n.postRobot}(),nn=function(n,e){return void 0===e&&(e={}),Y.send(R,n,e,{domain:c}).then((function(n){return n.data}))},en=function(){if(window.location.hash&&"#"!==window.location.hash){var n=(window.location.hash&&window.location.hash.slice(1)).split("?"),e=n[0],t=n[1];switch(e){case"init":case"loaded":case"appswitch":case"webswitch":case"closed":break;case"onApprove":var r=un(t);nn("onApprove",{payerID:r.payerID,paymentID:r.paymentID,billingToken:r.billingToken}).finally(D);break;case"onCancel":nn("onCancel").finally(D);break;case"fallback":var o=un(t);nn("onFallback",{type:o.type,skip_native_duration:o.skip_native_duration,fallback_reason:o.fallback_reason});break;case"onError":var i=un(t);nn("onError",{message:i.message}).finally(D);break;case"close":nn("onComplete").finally(D);break;case"test":break;default:nn("onError",{message:"Invalid event sent from native, "+e+", from URL, "+window.location.href}).finally(D)}}};window.addEventListener("hashchange",en),K.register((function(){return window.removeEventListener("hashchange",en)})),z("loaded"),en();var tn=hn({name:"paypal",lifetime:36e5}).getID(),rn=window.location.href.split("#")[0]+"#close";return b.then((function(n){nn("awaitRedirect",{app:n,pageUrl:rn,sfvc:_=!!_||!0===S,stickinessID:tn}).then((function(n){var e=n.redirect,t=n.redirectUrl,r=n.orderID,o=n.appSwitch,i=void 0===o||o;if(void 0===e||e){r&&v.addTrackingBuilder((function(){var n;return(n={}).context_type="EC-Token",n.context_id=r,n.token=r,n})),z(i?"appswitch":"webswitch"),window.location.replace(t);var u=!1,a=function(){u=!0};if(window.addEventListener("beforeunload",a),K.register((function(){return window.removeEventListener("beforeunload",a)})),window.addEventListener("unload",a),K.register((function(){return window.removeEventListener("unload",a)})),window.addEventListener("pagehide",a),K.register((function(){return window.removeEventListener("pagehide",a)})),i){var c=setTimeout((function(){u||nn("detectAppSwitch")}),1500);K.register((function(){return clearTimeout(c)}))}}}))})),{destroy:function(){return K.all()}}}function On(n,e){for(var t=[],r=0;r1?new Cn(e):void 0}(this.component(this.props,this.children));if(e)return e.render(n)},e.render=function(n){return n(this)},e.renderChildren=function(n){return On(this.children,n)},n}();function In(n){for(var e=[],t=0;t2?t-2:0),o=2;o -1; + }(sanitizedUrl)) return sanitizedUrl; + var urlSchemeParseResults = sanitizedUrl.match(urlSchemeRegex); + return urlSchemeParseResults && invalidProtocolRegex.test(urlSchemeParseResults[0]) ? BLANK_URL : sanitizedUrl; + } function getBody() { var body = document.body; if (!body) throw new Error("Body element not found"); @@ -3363,7 +3407,7 @@ window.spb = function(modules) { getBody().removeChild(form); } function getStorage(_ref) { - var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime; + var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime, stickySessionId = _ref.stickySessionId; return inlineMemoize(getStorage, (function() { var STORAGE_KEY = "__" + name + "_storage__"; var newStateID = uniqueID(); @@ -3398,7 +3442,7 @@ window.spb = function(modules) { var now = Date.now(); session && now - session.created > lifetime && (session = null); session || (session = { - guid: uniqueID(), + guid: stickySessionId || uniqueID(), created: now }); storage.__session__ = session; @@ -4248,6 +4292,9 @@ window.spb = function(modules) { __webpack_require__.d(__webpack_exports__, "ExtendableError", (function() { return util_ExtendableError; })); + __webpack_require__.d(__webpack_exports__, "sanitizeUrl", (function() { + return sanitizeUrl; + })); __webpack_require__.d(__webpack_exports__, "request", (function() { return request; })); @@ -4296,6 +4343,27 @@ window.spb = function(modules) { __webpack_require__.d(__webpack_exports__, "UID_HASH_LENGTH", (function() { return UID_HASH_LENGTH; })); + __webpack_require__.d(__webpack_exports__, "invalidProtocolRegex", (function() { + return invalidProtocolRegex; + })); + __webpack_require__.d(__webpack_exports__, "htmlEntitiesRegex", (function() { + return htmlEntitiesRegex; + })); + __webpack_require__.d(__webpack_exports__, "htmlCtrlEntityRegex", (function() { + return htmlCtrlEntityRegex; + })); + __webpack_require__.d(__webpack_exports__, "ctrlCharactersRegex", (function() { + return ctrlCharactersRegex; + })); + __webpack_require__.d(__webpack_exports__, "urlSchemeRegex", (function() { + return urlSchemeRegex; + })); + __webpack_require__.d(__webpack_exports__, "relativeFirstCharacters", (function() { + return relativeFirstCharacters; + })); + __webpack_require__.d(__webpack_exports__, "BLANK_URL", (function() { + return BLANK_URL; + })); __webpack_require__.d(__webpack_exports__, "sfvcScreens", (function() { return sfvcScreens; })); @@ -4472,9 +4540,9 @@ window.spb = function(modules) { void 0 === userAgent && (userAgent = getUserAgent()); return TABLET_PATTERN.test(userAgent); } - function isWebView() { - var userAgent = getUserAgent(); - return /(iPhone|iPod|iPad|Macintosh).*AppleWebKit(?!.*Safari)|.*WKWebView/i.test(userAgent) || /\bwv\b/.test(userAgent) || /Android.*Version\/(\d)\.(\d)/i.test(userAgent); + function isWebView(ua) { + void 0 === ua && (ua = getUserAgent()); + return /(iPhone|iPod|iPad|Macintosh).*AppleWebKit(?!.*Safari)|.*WKWebView/i.test(ua) || /\bwv\b/.test(ua) || /Android.*Version\/(\d)\.(\d)/i.test(ua); } function isStandAlone() { return !0 === window.navigator.standalone || window.matchMedia("(display-mode: standalone)").matches; @@ -4589,7 +4657,7 @@ window.spb = function(modules) { } function supportsPopups(ua) { void 0 === ua && (ua = getUserAgent()); - return !(isIosWebview(ua) || isAndroidWebview(ua) || isOperaMini(ua) || isFirefoxIOS(ua) || isEdgeIOS(ua) || isFacebookWebView(ua) || isQQBrowser(ua) || isElectron() || isMacOsCna() || isStandAlone()); + return !(isWebView(ua) || isIosWebview(ua) || isAndroidWebview(ua) || isOperaMini(ua) || isFirefoxIOS(ua) || isEdgeIOS(ua) || isFacebookWebView(ua) || isQQBrowser(ua) || isElectron() || isMacOsCna() || isStandAlone()); } function isChrome(ua) { void 0 === ua && (ua = getUserAgent()); @@ -4808,6 +4876,21 @@ window.spb = function(modules) { return _setPrototypeOf(Wrapper, Class); })(Class); } + var KEY_CODES = { + ENTER: 13, + SPACE: 32 + }; + var ATTRIBUTES = { + UID: "data-uid" + }; + var UID_HASH_LENGTH = 30; + var invalidProtocolRegex = /([^\w]*)(javascript|data|vbscript)/im; + var htmlEntitiesRegex = /&#(\w+)(^\w|;)?/g; + var htmlCtrlEntityRegex = /&(newline|tab);/gi; + var ctrlCharactersRegex = /[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim; + var urlSchemeRegex = /^.+(:|:)/gim; + var relativeFirstCharacters = [ ".", "/" ]; + var BLANK_URL = "about:blank"; function isElement(element) { var passed = !1; try { @@ -5500,14 +5583,19 @@ window.spb = function(modules) { } return ExtendableError; }(wrapNativeSuper_wrapNativeSuper(Error)); - var KEY_CODES = { - ENTER: 13, - SPACE: 32 - }; - var ATTRIBUTES = { - UID: "data-uid" - }; - var UID_HASH_LENGTH = 30; + function sanitizeUrl(url) { + if (!url) return BLANK_URL; + var sanitizedUrl = (str = url, str.replace(ctrlCharactersRegex, "").replace(htmlEntitiesRegex, (function(matchRegex, dec) { + return String.fromCharCode(dec); + }))).replace(htmlCtrlEntityRegex, "").replace(ctrlCharactersRegex, "").trim(); + var str; + if (!sanitizedUrl) return BLANK_URL; + if (function(url) { + return relativeFirstCharacters.indexOf(url[0]) > -1; + }(sanitizedUrl)) return sanitizedUrl; + var urlSchemeParseResults = sanitizedUrl.match(urlSchemeRegex); + return urlSchemeParseResults && invalidProtocolRegex.test(urlSchemeParseResults[0]) ? BLANK_URL : sanitizedUrl; + } function getBody() { var body = document.body; if (!body) throw new Error("Body element not found"); @@ -6182,7 +6270,7 @@ window.spb = function(modules) { getBody().removeChild(form); } function getStorage(_ref) { - var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime; + var name = _ref.name, _ref$lifetime = _ref.lifetime, lifetime = void 0 === _ref$lifetime ? 12e5 : _ref$lifetime, stickySessionId = _ref.stickySessionId; return inlineMemoize(getStorage, (function() { var STORAGE_KEY = "__" + name + "_storage__"; var newStateID = uniqueID(); @@ -6217,7 +6305,7 @@ window.spb = function(modules) { var now = Date.now(); session && now - session.created > lifetime && (session = null); session || (session = { - guid: uniqueID(), + guid: stickySessionId || uniqueID(), created: now }); storage.__session__ = session; @@ -7668,6 +7756,9 @@ window.spb = function(modules) { __webpack_require__.d(__webpack_exports__, "MERCHANT_ID_MAX", (function() { return MERCHANT_ID_MAX; })); + __webpack_require__.d(__webpack_exports__, "DISPLAY_ONLY_VALUES", (function() { + return DISPLAY_ONLY_VALUES; + })); __webpack_require__.d(__webpack_exports__, "PLATFORM", (function() { return PLATFORM; })); @@ -8261,7 +8352,8 @@ window.spb = function(modules) { CLIENT_METADATA_ID: "data-client-metadata-id", PAGE_TYPE: "data-page-type", USER_EXPERIENCE_FLOW: "data-user-experience-flow", - POPUPS_DISABLED: "data-popups-disabled" + POPUPS_DISABLED: "data-popups-disabled", + SDK_TOKEN: "data-sdk-client-token" }; var SDK_QUERY_KEYS = { COMPONENTS: "components", @@ -8314,6 +8406,9 @@ window.spb = function(modules) { MINI_CART: "mini-cart" }; var MERCHANT_ID_MAX = 10; + var DISPLAY_ONLY_VALUES = { + VAULTABLE: "vaultable" + }; var DEFAULT_COUNTRY = COUNTRY.US; var DEFAULT_CURRENCY = CURRENCY.USD; var DEFAULT_INTENT = INTENT.CAPTURE; @@ -9125,7 +9220,7 @@ window.spb = function(modules) { var _lib__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__("./src/lib/index.js"); function callRestAPI(_ref) { var _extends2; - var accessToken = _ref.accessToken, method = _ref.method, url = _ref.url, data = _ref.data, headers = _ref.headers, eventName = _ref.eventName; + var accessToken = _ref.accessToken, method = _ref.method, url = _ref.url, data = _ref.data, headers = _ref.headers, eventName = _ref.eventName, _ref$metricDimensions = _ref.metricDimensions, metricDimensions = void 0 === _ref$metricDimensions ? {} : _ref$metricDimensions; if (!accessToken) throw new Error("No access token passed to " + url); var requestHeaders = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.default)(((_extends2 = {})[_constants__WEBPACK_IMPORTED_MODULE_5__.HEADERS.AUTHORIZATION] = "Bearer " + accessToken, _extends2[_constants__WEBPACK_IMPORTED_MODULE_5__.HEADERS.CONTENT_TYPE] = "application/json", @@ -9151,14 +9246,22 @@ window.spb = function(modules) { _getLogger$track[_constants__WEBPACK_IMPORTED_MODULE_5__.FPTI_CUSTOM_KEY.INFO_MSG] = "URL: " + url, _getLogger$track)); } - eventName && Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().warn("rest_api_" + eventName + "_status_" + status + "_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().warn("rest_api_" + eventName + "_status_" + status + "_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.rest_api_" + eventName + ".error.count", + dimensions: metricDimensions + }); throw error; } + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.rest_api_" + eventName + ".success.count", + dimensions: metricDimensions + }); return body; })); } function callSmartAPI(_ref3) { - var accessToken = _ref3.accessToken, url = _ref3.url, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? "get" : _ref3$method, _ref3$headers = _ref3.headers, reqHeaders = void 0 === _ref3$headers ? {} : _ref3$headers, json = _ref3.json, _ref3$authenticated = _ref3.authenticated, authenticated = void 0 === _ref3$authenticated || _ref3$authenticated, eventName = _ref3.eventName; + var accessToken = _ref3.accessToken, url = _ref3.url, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? "get" : _ref3$method, _ref3$headers = _ref3.headers, reqHeaders = void 0 === _ref3$headers ? {} : _ref3$headers, json = _ref3.json, _ref3$authenticated = _ref3.authenticated, authenticated = void 0 === _ref3$authenticated || _ref3$authenticated, eventName = _ref3.eventName, _ref3$metricDimension = _ref3.metricDimensions, metricDimensions = void 0 === _ref3$metricDimension ? {} : _ref3$metricDimension; reqHeaders[_constants__WEBPACK_IMPORTED_MODULE_5__.HEADERS.REQUESTED_BY] = _constants__WEBPACK_IMPORTED_MODULE_5__.SMART_PAYMENT_BUTTONS; if (authenticated && !accessToken) throw new Error("Buyer access token not present - can not call smart api: " + url); accessToken && (reqHeaders[_constants__WEBPACK_IMPORTED_MODULE_5__.HEADERS.ACCESS_TOKEN] = accessToken); @@ -9190,12 +9293,26 @@ window.spb = function(modules) { } if (status > 400) { Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().warn("smart_api_" + eventName + "_status_" + status + "_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.smart_api_" + eventName + ".error.count", + dimensions: Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.default)({ + status: status + }, metricDimensions) + }); throw new Error("Api: " + url + " returned status code: " + status + " (Corr ID: " + headers[_constants__WEBPACK_IMPORTED_MODULE_5__.HEADERS.PAYPAL_DEBUG_ID] + ")\n\n" + JSON.stringify(body)); } if ("success" !== body.ack) { Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().warn("smart_api_" + eventName + "_ack_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.smart_api_" + eventName + ".error.count", + dimensions: metricDimensions + }); throw new Error("Api: " + url + " returned ack: " + body.ack + " (Corr ID: " + headers[_constants__WEBPACK_IMPORTED_MODULE_5__.HEADERS.PAYPAL_DEBUG_ID] + ")\n\n" + JSON.stringify(body)); } + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.smart_api_" + eventName + ".success.count", + dimensions: metricDimensions + }); return { data: body.data, headers: headers @@ -9223,12 +9340,26 @@ window.spb = function(modules) { err: message }); if (returnErrorObject) throw errors[0]; + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".error.count", + dimensions: {} + }); throw new Error(message); } if (200 !== status) { Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().warn("graphql_" + name + "_status_" + status + "_error"); + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".error.count", + dimensions: { + status: status + } + }); throw new Error(_config__WEBPACK_IMPORTED_MODULE_4__.GRAPHQL_URI + " returned status " + status + "\n\n" + JSON.stringify(body)); } + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".success.count", + dimensions: {} + }); return body.data; })); } @@ -9252,6 +9383,9 @@ window.spb = function(modules) { __webpack_require__.d(__webpack_exports__, "onLsatUpgradeCalled", (function() { return onLsatUpgradeCalled; })); + __webpack_require__.d(__webpack_exports__, "getLsatUpgradeWithIgnoreCache", (function() { + return getLsatUpgradeWithIgnoreCache; + })); __webpack_require__.d(__webpack_exports__, "getLsatUpgradeCalled", (function() { return getLsatUpgradeCalled; })); @@ -9267,6 +9401,9 @@ window.spb = function(modules) { __webpack_require__.d(__webpack_exports__, "upgradeFacilitatorAccessToken", (function() { return upgradeFacilitatorAccessToken; })); + __webpack_require__.d(__webpack_exports__, "upgradeFacilitatorAccessTokenWithIgnoreCache", (function() { + return upgradeFacilitatorAccessTokenWithIgnoreCache; + })); __webpack_require__.d(__webpack_exports__, "exchangeAccessTokenForAuthCode", (function() { return exchangeAccessTokenForAuthCode; })); @@ -9482,23 +9619,28 @@ window.spb = function(modules) { return res.firebase.auth.sessionToken; })); } - var lsatUpgradeCalled = !1; - var lsatUpgradeError; + var auth_lsatUpgradeCalled = !1; + var auth_lsatUpgradeError; + var lsatUpgradeWithIgnoreCache = !1; var onLsatUpgradeCalled = function() { - lsatUpgradeCalled = !0; + auth_lsatUpgradeCalled = !0; + }; + var getLsatUpgradeWithIgnoreCache = function() { + return lsatUpgradeWithIgnoreCache; }; var getLsatUpgradeCalled = function() { - return lsatUpgradeCalled; + return auth_lsatUpgradeCalled; }; var onLsatUpgradeError = function(err) { - lsatUpgradeError = err; + auth_lsatUpgradeError = err; }; var getLsatUpgradeError = function() { - return lsatUpgradeError; + return auth_lsatUpgradeError; }; var clearLsatState = function() { - lsatUpgradeCalled = !1; - lsatUpgradeError = null; + auth_lsatUpgradeCalled = !1; + auth_lsatUpgradeError = null; + lsatUpgradeWithIgnoreCache = !1; }; function upgradeFacilitatorAccessToken(facilitatorAccessToken, _ref3) { var _headers; @@ -9520,6 +9662,36 @@ window.spb = function(modules) { throw err; })); } + function upgradeFacilitatorAccessTokenWithIgnoreCache(facilitatorAccessToken, buyerAccessToken, orderID) { + return Object(belter_src.inlineMemoize)(upgradeFacilitatorAccessTokenWithIgnoreCache, (function() { + var _headers2; + clearLsatState(); + onLsatUpgradeCalled(); + lsatUpgradeWithIgnoreCache = !0; + return Object(api.callGraphQL)({ + name: "CreateUpgradedLowScopeAccessToken", + headers: (_headers2 = {}, _headers2[constants.HEADERS.ACCESS_TOKEN] = buyerAccessToken, + _headers2[constants.HEADERS.CLIENT_CONTEXT] = orderID, _headers2), + query: "\n mutation CreateUpgradedLowScopeAccessToken(\n $orderID: String!\n $buyerAccessToken: String!\n $facilitatorAccessToken: String!\n ) {\n createUpgradedLowScopeAccessToken(\n token: $orderID\n buyerAccessToken: $buyerAccessToken\n merchantLSAT: $facilitatorAccessToken\n )\n }\n ", + variables: { + facilitatorAccessToken: facilitatorAccessToken, + buyerAccessToken: buyerAccessToken, + orderID: orderID + } + }).then((function(res) { + Object(lib.getLogger)().info("create_upgraded_low_scope_access_token_success", { + orderID: orderID + }); + return null == res ? void 0 : res.createUpgradedLowScopeAccessToken; + })).catch((function(err) { + Object(lib.getLogger)().warn("create_upgraded_low_scope_access_token_error", { + orderID: orderID + }); + onLsatUpgradeError(err); + return facilitatorAccessToken; + })); + }), [ facilitatorAccessToken, buyerAccessToken, orderID ]); + } function exchangeAccessTokenForAuthCode(buyerAccessToken) { return Object(api.callGraphQL)({ name: "ExchangeAuthCode", @@ -9578,13 +9750,43 @@ window.spb = function(modules) { return detail.issue === constants.ORDER_API_ERROR.INVALID_RESOURCE_ID; }))); } + function lsatUpgradeType() { + return getLsatUpgradeWithIgnoreCache() ? "with_ignore_cache_lsat_upgrade" : "without_ignore_cache_lsat_upgrade"; + } + function lsatUpgradeMetricValue() { + var lsatUpgradeCalled = Boolean(getLsatUpgradeCalled()); + var lsatUpgradeIgnoreCache = Boolean(getLsatUpgradeWithIgnoreCache()); + var lsatUpgradeError = Boolean(getLsatUpgradeError()); + var cacheType = lsatUpgradeIgnoreCache ? "with_ignore_cache" : "without_ignore_cache"; + return lsatUpgradeCalled ? lsatUpgradeError ? cacheType + "_error" : cacheType + "_success" : cacheType + "_not_called"; + } + function logPayeeInfoForClientSideHelpers(orderID, method) { + getSupplementalOrderInfo(orderID).then((function(order) { + var merchantIds = (order.checkoutSession.payees || []).map((function(p) { + return p.merchantId; + })); + Object(lib.getLogger)().info("using_client_side_helper_" + method, { + payee: merchantIds.join(), + orderID: orderID + }); + })).catch((function(err) { + Object(lib.getLogger)().warn("err_getting_payee_client_side_helper_" + method, { + orderID: orderID, + err: Object(belter_src.stringifyError)(err) + }); + })); + } function getOrder(orderID, _ref2) { var _headers4; - var facilitatorAccessToken = _ref2.facilitatorAccessToken, buyerAccessToken = _ref2.buyerAccessToken, partnerAttributionID = _ref2.partnerAttributionID, _ref2$forceRestAPI = _ref2.forceRestAPI, forceRestAPI = void 0 !== _ref2$forceRestAPI && _ref2$forceRestAPI; - Object(lib.getLogger)().info("get_order_lsat_upgrade_" + (getLsatUpgradeCalled() ? "called" : "not_called")); - Object(lib.getLogger)().info("get_order_lsat_upgrade_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + var facilitatorAccessToken = _ref2.facilitatorAccessToken, buyerAccessToken = _ref2.buyerAccessToken, partnerAttributionID = _ref2.partnerAttributionID, _ref2$forceRestAPI = _ref2.forceRestAPI, forceRestAPI = void 0 !== _ref2$forceRestAPI && _ref2$forceRestAPI, experiments = _ref2.experiments; + Object(lib.getLogger)().info("get_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeCalled() ? "called" : "not_called"), { + orderID: orderID + }); + Object(lib.getLogger)().info("get_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + orderID: orderID, err: Object(belter_src.stringifyError)(getLsatUpgradeError()) }); + logPayeeInfoForClientSideHelpers(orderID, "get"); if (forceRestAPI && !getLsatUpgradeError()) { var _headers2; return Object(api.callRestAPI)({ @@ -9592,29 +9794,37 @@ window.spb = function(modules) { url: src_config.ORDERS_API_URL + "/" + orderID, eventName: "v2_checkout_orders_get", headers: (_headers2 = {}, _headers2[constants.HEADERS.PARTNER_ATTRIBUTION_ID] = partnerAttributionID || "", - _headers2[constants.HEADERS.PREFER] = constants.PREFER.REPRESENTATION, _headers2) + _headers2[constants.HEADERS.PREFER] = constants.PREFER.REPRESENTATION, _headers2), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue() + } }).catch((function(err) { var _headers3; var restCorrID = Object(api.getErrorResponseCorrelationID)(err); - Object(lib.getLogger)().warn("get_order_call_rest_api_error", { + Object(lib.getLogger)().warn("get_order_" + lsatUpgradeType() + "_call_rest_api_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.stringifyError)(err) }); - isInvalidResourceIDError(err) && Object(lib.getLogger)().warn("get_order_invalid_resource_id_error", { + isInvalidResourceIDError(err) && Object(lib.getLogger)().warn("get_order_" + lsatUpgradeType() + "_invalid_resource_id_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.stringifyError)(err) }); + if (experiments.disableSmartAPI) throw err; return Object(api.callSmartAPI)({ accessToken: buyerAccessToken, url: src_config.SMART_API_URI.ORDER + "/" + orderID, eventName: "order_get", headers: (_headers3 = {}, _headers3[constants.HEADERS.CLIENT_CONTEXT] = orderID, - _headers3) + _headers3), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback" + } }).then((function(res) { var smartCorrID = Object(api.getResponseCorrelationID)(res); - Object(lib.getLogger)().info("get_order_smart_fallback_success", { + Object(lib.getLogger)().info("get_order_" + lsatUpgradeType() + "_smart_fallback_success", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID @@ -9622,7 +9832,7 @@ window.spb = function(modules) { return res.data; })).catch((function(smartErr) { var smartCorrID = Object(api.getErrorResponseCorrelationID)(err); - Object(lib.getLogger)().error("get_order_smart_fallback_error", { + Object(lib.getLogger)().error("get_order_" + lsatUpgradeType() + "_smart_fallback_error", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID, @@ -9630,6 +9840,8 @@ window.spb = function(modules) { }); throw smartErr; })); + })).finally((function() { + Object(lib.getLogger)().flush(); })); } return Object(api.callSmartAPI)({ @@ -9637,9 +9849,15 @@ window.spb = function(modules) { url: src_config.SMART_API_URI.ORDER + "/" + orderID, eventName: "order_get", headers: (_headers4 = {}, _headers4[constants.HEADERS.CLIENT_CONTEXT] = orderID, - _headers4) + _headers4), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default" + } }).then((function(_ref3) { return _ref3.data; + })).finally((function() { + Object(lib.getLogger)().flush(); })); } function isProcessorDeclineError(err) { @@ -9657,11 +9875,15 @@ window.spb = function(modules) { } function captureOrder(orderID, _ref4) { var _headers7; - var facilitatorAccessToken = _ref4.facilitatorAccessToken, buyerAccessToken = _ref4.buyerAccessToken, partnerAttributionID = _ref4.partnerAttributionID, _ref4$forceRestAPI = _ref4.forceRestAPI, forceRestAPI = void 0 !== _ref4$forceRestAPI && _ref4$forceRestAPI; - Object(lib.getLogger)().info("capture_order_lsat_upgrade_" + (getLsatUpgradeCalled() ? "called" : "not_called")); - Object(lib.getLogger)().info("capture_order_lsat_upgrade_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + var facilitatorAccessToken = _ref4.facilitatorAccessToken, buyerAccessToken = _ref4.buyerAccessToken, partnerAttributionID = _ref4.partnerAttributionID, _ref4$forceRestAPI = _ref4.forceRestAPI, forceRestAPI = void 0 !== _ref4$forceRestAPI && _ref4$forceRestAPI, experiments = _ref4.experiments; + Object(lib.getLogger)().info("capture_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeCalled() ? "called" : "not_called"), { + orderID: orderID + }); + Object(lib.getLogger)().info("capture_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + orderID: orderID, err: Object(belter_src.stringifyError)(getLsatUpgradeError()) }); + logPayeeInfoForClientSideHelpers(orderID, "capture"); if (forceRestAPI && !getLsatUpgradeError()) { var _headers5; return Object(api.callRestAPI)({ @@ -9671,21 +9893,25 @@ window.spb = function(modules) { url: src_config.ORDERS_API_URL + "/" + orderID + "/capture", headers: (_headers5 = {}, _headers5[constants.HEADERS.PARTNER_ATTRIBUTION_ID] = partnerAttributionID || "", _headers5[constants.HEADERS.PREFER] = constants.PREFER.REPRESENTATION, _headers5[constants.HEADERS.PAYPAL_REQUEST_ID] = orderID, - _headers5) + _headers5), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue() + } }).catch((function(err) { var _headers6; var restCorrID = Object(api.getErrorResponseCorrelationID)(err); - Object(lib.getLogger)().warn("capture_order_call_rest_api_error", { + Object(lib.getLogger)().warn("capture_order_" + lsatUpgradeType() + "_call_rest_api_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.stringifyError)(err) }); - isInvalidResourceIDError(err) && Object(lib.getLogger)().warn("capture_order_invalid_resource_id_error", { + isInvalidResourceIDError(err) && Object(lib.getLogger)().warn("capture_order_" + lsatUpgradeType() + "_invalid_resource_id_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.stringifyError)(err) }); if (isProcessorDeclineError(err) || isUnprocessableEntityError(err)) throw err; + if (experiments.disableSmartAPI) throw err; return Object(api.callSmartAPI)({ accessToken: buyerAccessToken, method: "post", @@ -9697,10 +9923,14 @@ window.spb = function(modules) { } }, headers: (_headers6 = {}, _headers6[constants.HEADERS.CLIENT_CONTEXT] = orderID, - _headers6) + _headers6), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback" + } }).then((function(res) { var smartCorrID = Object(api.getResponseCorrelationID)(res); - Object(lib.getLogger)().info("capture_order_smart_fallback_success", { + Object(lib.getLogger)().info("capture_order_" + lsatUpgradeType() + "_smart_fallback_success", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID @@ -9708,7 +9938,7 @@ window.spb = function(modules) { return res.data; })).catch((function(smartErr) { var smartCorrID = Object(api.getErrorResponseCorrelationID)(err); - Object(lib.getLogger)().info("capture_order_smart_fallback_error", { + Object(lib.getLogger)().info("capture_order_" + lsatUpgradeType() + "_smart_fallback_error", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID, @@ -9716,6 +9946,8 @@ window.spb = function(modules) { }); throw smartErr; })); + })).finally((function() { + Object(lib.getLogger)().flush(); })); } return Object(api.callSmartAPI)({ @@ -9729,18 +9961,28 @@ window.spb = function(modules) { } }, headers: (_headers7 = {}, _headers7[constants.HEADERS.CLIENT_CONTEXT] = orderID, - _headers7) + _headers7), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default" + } }).then((function(_ref5) { return _ref5.data; + })).finally((function() { + Object(lib.getLogger)().flush(); })); } function authorizeOrder(orderID, _ref6) { var _headers10; - var facilitatorAccessToken = _ref6.facilitatorAccessToken, buyerAccessToken = _ref6.buyerAccessToken, partnerAttributionID = _ref6.partnerAttributionID, _ref6$forceRestAPI = _ref6.forceRestAPI, forceRestAPI = void 0 !== _ref6$forceRestAPI && _ref6$forceRestAPI; - Object(lib.getLogger)().info("authorize_order_lsat_upgrade_" + (getLsatUpgradeCalled() ? "called" : "not_called")); - Object(lib.getLogger)().info("authorize_order_lsat_upgrade_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + var facilitatorAccessToken = _ref6.facilitatorAccessToken, buyerAccessToken = _ref6.buyerAccessToken, partnerAttributionID = _ref6.partnerAttributionID, _ref6$forceRestAPI = _ref6.forceRestAPI, forceRestAPI = void 0 !== _ref6$forceRestAPI && _ref6$forceRestAPI, experiments = _ref6.experiments; + Object(lib.getLogger)().info("authorize_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeCalled() ? "called" : "not_called"), { + orderID: orderID + }); + Object(lib.getLogger)().info("authorize_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + orderID: orderID, err: Object(belter_src.stringifyError)(getLsatUpgradeError()) }); + logPayeeInfoForClientSideHelpers(orderID, "authorize"); if (forceRestAPI && !getLsatUpgradeError()) { var _headers8; return Object(api.callRestAPI)({ @@ -9749,21 +9991,25 @@ window.spb = function(modules) { eventName: "v2_checkout_orders_authorize", url: src_config.ORDERS_API_URL + "/" + orderID + "/authorize", headers: (_headers8 = {}, _headers8[constants.HEADERS.PARTNER_ATTRIBUTION_ID] = partnerAttributionID || "", - _headers8[constants.HEADERS.PREFER] = constants.PREFER.REPRESENTATION, _headers8) + _headers8[constants.HEADERS.PREFER] = constants.PREFER.REPRESENTATION, _headers8), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue() + } }).catch((function(err) { var _headers9; var restCorrID = Object(api.getErrorResponseCorrelationID)(err); - Object(lib.getLogger)().warn("authorize_order_call_rest_api_error", { + Object(lib.getLogger)().warn("authorize_order_" + lsatUpgradeType() + "_call_rest_api_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.stringifyError)(err) }); - isInvalidResourceIDError(err) && Object(lib.getLogger)().warn("authorize_order_invalid_resource_id_error", { + isInvalidResourceIDError(err) && Object(lib.getLogger)().warn("authorize_order_" + lsatUpgradeType() + "_invalid_resource_id_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.stringifyError)(err) }); if (isProcessorDeclineError(err)) throw err; + if (experiments.disableSmartAPI) throw err; return Object(api.callSmartAPI)({ accessToken: buyerAccessToken, method: "post", @@ -9775,10 +10021,14 @@ window.spb = function(modules) { } }, headers: (_headers9 = {}, _headers9[constants.HEADERS.CLIENT_CONTEXT] = orderID, - _headers9) + _headers9), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback" + } }).then((function(res) { var smartCorrID = Object(api.getResponseCorrelationID)(res); - Object(lib.getLogger)().info("authorize_order_smart_fallback_success", { + Object(lib.getLogger)().info("authorize_order_" + lsatUpgradeType() + "_smart_fallback_success", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID @@ -9786,7 +10036,7 @@ window.spb = function(modules) { return res.data; })).catch((function(smartErr) { var smartCorrID = Object(api.getErrorResponseCorrelationID)(err); - Object(lib.getLogger)().info("authorize_order_smart_fallback_error", { + Object(lib.getLogger)().info("authorize_order_" + lsatUpgradeType() + "_smart_fallback_error", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID, @@ -9794,6 +10044,8 @@ window.spb = function(modules) { }); throw smartErr; })); + })).finally((function() { + Object(lib.getLogger)().flush(); })); } Object(lib.getLogger)().info("lsat_upgrade_false"); @@ -9808,18 +10060,28 @@ window.spb = function(modules) { } }, headers: (_headers10 = {}, _headers10[constants.HEADERS.CLIENT_CONTEXT] = orderID, - _headers10) + _headers10), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default" + } }).then((function(_ref7) { return _ref7.data; + })).finally((function() { + Object(lib.getLogger)().flush(); })); } function patchOrder(orderID, data, _ref8) { var _headers13; - var facilitatorAccessToken = _ref8.facilitatorAccessToken, buyerAccessToken = _ref8.buyerAccessToken, partnerAttributionID = _ref8.partnerAttributionID, _ref8$forceRestAPI = _ref8.forceRestAPI, forceRestAPI = void 0 !== _ref8$forceRestAPI && _ref8$forceRestAPI; - Object(lib.getLogger)().info("patch_order_lsat_upgrade_" + (getLsatUpgradeCalled() ? "called" : "not_called")); - Object(lib.getLogger)().info("patch_order_lsat_upgrade_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + var facilitatorAccessToken = _ref8.facilitatorAccessToken, buyerAccessToken = _ref8.buyerAccessToken, partnerAttributionID = _ref8.partnerAttributionID, _ref8$forceRestAPI = _ref8.forceRestAPI, forceRestAPI = void 0 !== _ref8$forceRestAPI && _ref8$forceRestAPI, experiments = _ref8.experiments; + Object(lib.getLogger)().info("patch_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeCalled() ? "called" : "not_called"), { + orderID: orderID + }); + Object(lib.getLogger)().info("patch_order_" + lsatUpgradeType() + "_" + (getLsatUpgradeError() ? "errored" : "did_not_error"), { + orderID: orderID, err: Object(belter_src.stringifyError)(getLsatUpgradeError()) }); + logPayeeInfoForClientSideHelpers(orderID, "patch"); if (forceRestAPI && !getLsatUpgradeError()) { var _headers11; return Object(api.callRestAPI)({ @@ -9829,20 +10091,24 @@ window.spb = function(modules) { url: src_config.ORDERS_API_URL + "/" + orderID, data: data, headers: (_headers11 = {}, _headers11[constants.HEADERS.PARTNER_ATTRIBUTION_ID] = partnerAttributionID || "", - _headers11[constants.HEADERS.PREFER] = constants.PREFER.REPRESENTATION, _headers11) + _headers11[constants.HEADERS.PREFER] = constants.PREFER.REPRESENTATION, _headers11), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue() + } }).catch((function(err) { var _headers12; var restCorrID = Object(api.getErrorResponseCorrelationID)(err); - Object(lib.getLogger)().warn("patch_order_call_rest_api_error", { + Object(lib.getLogger)().warn("patch_order_" + lsatUpgradeType() + "_call_rest_api_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.stringifyError)(err) }); - isInvalidResourceIDError(err) && Object(lib.getLogger)().warn("patch_order_invalid_resource_id_error", { + isInvalidResourceIDError(err) && Object(lib.getLogger)().warn("patch_order_" + lsatUpgradeType() + "_invalid_resource_id_error", { restCorrID: restCorrID, orderID: orderID, err: Object(belter_src.stringifyError)(err) }); + if (experiments.disableSmartAPI) throw err; var requestData; requestData = Array.isArray(data) ? { patch: data, @@ -9859,10 +10125,14 @@ window.spb = function(modules) { data: requestData }, headers: (_headers12 = {}, _headers12[constants.HEADERS.CLIENT_CONTEXT] = orderID, - _headers12) + _headers12), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback" + } }).then((function(res) { var smartCorrID = Object(api.getResponseCorrelationID)(res); - Object(lib.getLogger)().info("patch_order_smart_fallback_success", { + Object(lib.getLogger)().info("patch_order_" + lsatUpgradeType() + "_smart_fallback_success", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID @@ -9870,7 +10140,7 @@ window.spb = function(modules) { return res.data; })).catch((function(smartErr) { var smartCorrID = Object(api.getErrorResponseCorrelationID)(err); - Object(lib.getLogger)().info("patch_order_smart_fallback_error", { + Object(lib.getLogger)().info("patch_order_" + lsatUpgradeType() + "_smart_fallback_error", { smartCorrID: smartCorrID, restCorrID: restCorrID, orderID: orderID, @@ -9878,6 +10148,8 @@ window.spb = function(modules) { }); throw smartErr; })); + })).finally((function() { + Object(lib.getLogger)().flush(); })); } Object(lib.getLogger)().info("lsat_upgrade_false"); @@ -9897,9 +10169,15 @@ window.spb = function(modules) { data: requestData }, headers: (_headers13 = {}, _headers13[constants.HEADERS.CLIENT_CONTEXT] = orderID, - _headers13) + _headers13), + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default" + } }).then((function(_ref9) { return _ref9.data; + })).finally((function() { + Object(lib.getLogger)().flush(); })); } function patchShipping(_ref10) { @@ -9927,21 +10205,24 @@ window.spb = function(modules) { _headers14[constants.HEADERS.PREFER] = constants.PREFER.REPRESENTATION, _headers14) }); } - function buildPaymentSource(tokenID) { - return { - token: { - id: tokenID, - type: "NONCE" + function buildPaymentSource(_ref12) { + var _ref13; + var paymentMethodID = _ref12.paymentMethodID, enableThreeDomainSecure = _ref12.enableThreeDomainSecure; + return (_ref13 = {})[_ref12.fundingSource] = Object(esm_extends.default)({ + vault_id: paymentMethodID + }, enableThreeDomainSecure && { + verification_method: { + method: "SCA_ALWAYS" } - }; + }), _ref13; } - function validatePaymentMethod(_ref12) { + function validatePaymentMethod(_ref14) { var _headers15; - var accessToken = _ref12.accessToken, orderID = _ref12.orderID, paymentMethodID = _ref12.paymentMethodID, enableThreeDomainSecure = _ref12.enableThreeDomainSecure, partnerAttributionID = _ref12.partnerAttributionID, clientMetadataID = _ref12.clientMetadataID, installmentPlan = _ref12.installmentPlan; + var accessToken = _ref14.accessToken, orderID = _ref14.orderID, paymentMethodID = _ref14.paymentMethodID, enableThreeDomainSecure = _ref14.enableThreeDomainSecure, partnerAttributionID = _ref14.partnerAttributionID, clientMetadataID = _ref14.clientMetadataID, installmentPlan = _ref14.installmentPlan; Object(lib.getLogger)().info("rest_api_create_order_token"); var headers = ((_headers15 = {})[constants.HEADERS.AUTHORIZATION] = "Bearer " + accessToken, _headers15[constants.HEADERS.PARTNER_ATTRIBUTION_ID] = partnerAttributionID, _headers15[constants.HEADERS.CLIENT_METADATA_ID] = clientMetadataID, - _headers15[constants.HEADERS.APP_NAME] = constants.SMART_PAYMENT_BUTTONS, _headers15[constants.HEADERS.APP_VERSION] = "5.0.151", + _headers15[constants.HEADERS.APP_NAME] = constants.SMART_PAYMENT_BUTTONS, _headers15[constants.HEADERS.APP_VERSION] = "5.0.164", _headers15); var paymentSource = { token: { @@ -9972,8 +10253,8 @@ window.spb = function(modules) { method: "post", eventName: "payment_ectoken", url: src_config.SMART_API_URI.PAYMENT + "/" + billingToken + "/ectoken" - }).then((function(_ref13) { - return _ref13.data.token; + }).then((function(_ref15) { + return _ref15.data.token; })); } function subscriptionIdToCartId(subscriptionID) { @@ -9982,19 +10263,19 @@ window.spb = function(modules) { method: "post", eventName: "billagmt_subscriptions_cartid", url: src_config.SMART_API_URI.SUBSCRIPTION + "/" + subscriptionID + "/cartid" - }).then((function(_ref14) { - return _ref14.data.token; + }).then((function(_ref16) { + return _ref16.data.token; })); } - function enableVault(_ref15) { + function enableVault(_ref17) { var _headers16; - var orderID = _ref15.orderID, clientAccessToken = _ref15.clientAccessToken; + var orderID = _ref17.orderID, clientAccessToken = _ref17.clientAccessToken; var clientConfig = { - fundingSource: _ref15.fundingSource, - integrationArtifact: _ref15.integrationArtifact, - userExperienceFlow: _ref15.userExperienceFlow, - productFlow: _ref15.productFlow, - buttonSessionID: _ref15.buttonSessionID + fundingSource: _ref17.fundingSource, + integrationArtifact: _ref17.integrationArtifact, + userExperienceFlow: _ref17.userExperienceFlow, + productFlow: _ref17.productFlow, + buttonSessionID: _ref17.buttonSessionID }; return Object(api.callGraphQL)({ name: "EnableVault", @@ -10007,9 +10288,9 @@ window.spb = function(modules) { _headers16[constants.HEADERS.CLIENT_CONTEXT] = orderID, _headers16) }); } - function deleteVault(_ref16) { + function deleteVault(_ref18) { var _headers17; - var paymentMethodID = _ref16.paymentMethodID, clientAccessToken = _ref16.clientAccessToken; + var paymentMethodID = _ref18.paymentMethodID, clientAccessToken = _ref18.clientAccessToken; return Object(api.callGraphQL)({ name: "DeleteVault", query: "\n mutation DeleteVault(\n $paymentMethodID : String!\n ) {\n deleteVault(\n paymentMethodID: $paymentMethodID\n )\n }\n ", @@ -10020,9 +10301,9 @@ window.spb = function(modules) { _headers17) }); } - function updateClientConfig(_ref17) { + function updateClientConfig(_ref19) { var _headers18; - var orderID = _ref17.orderID, fundingSource = _ref17.fundingSource, integrationArtifact = _ref17.integrationArtifact, userExperienceFlow = _ref17.userExperienceFlow, productFlow = _ref17.productFlow, buttonSessionID = _ref17.buttonSessionID, featureFlags = _ref17.featureFlags; + var orderID = _ref19.orderID, fundingSource = _ref19.fundingSource, integrationArtifact = _ref19.integrationArtifact, userExperienceFlow = _ref19.userExperienceFlow, productFlow = _ref19.productFlow, buttonSessionID = _ref19.buttonSessionID, featureFlags = _ref19.featureFlags; featureFlags && featureFlags.isButtonClientConfigCallBlocking ? Object(lib.getLogger)().info("blocking_cco_call", { time: Object(lib.getClientsideTimestamp)(), buttonSessionID: buttonSessionID, @@ -10047,9 +10328,9 @@ window.spb = function(modules) { _headers18) }).then(belter_src.noop); } - function approveOrder(_ref18) { + function approveOrder(_ref20) { var _headers19; - var orderID = _ref18.orderID, planID = _ref18.planID, buyerAccessToken = _ref18.buyerAccessToken; + var orderID = _ref20.orderID, planID = _ref20.planID, buyerAccessToken = _ref20.buyerAccessToken; return Object(api.callGraphQL)({ name: "ApproveOrder", query: "\n mutation ApproveOrder(\n $orderID : String!\n $planID : String!\n ) {\n approvePayment(\n token: $orderID\n selectedPlanId: $planID\n ) {\n buyer {\n userId\n auth {\n accessToken\n }\n }\n }\n }\n ", @@ -10059,34 +10340,32 @@ window.spb = function(modules) { }, headers: (_headers19 = {}, _headers19[constants.HEADERS.ACCESS_TOKEN] = buyerAccessToken, _headers19[constants.HEADERS.CLIENT_CONTEXT] = orderID, _headers19) - }).then((function(_ref19) { + }).then((function(_ref21) { var _approvePayment$buyer; - var approvePayment = _ref19.approvePayment; + var approvePayment = _ref21.approvePayment; Object(lib.setBuyerAccessToken)(null == approvePayment || null == (_approvePayment$buyer = approvePayment.buyer) || null == (_approvePayment$buyer = _approvePayment$buyer.auth) ? void 0 : _approvePayment$buyer.accessToken); return { payerID: approvePayment.buyer.userId }; })); } - function oneClickApproveOrder(_ref20) { + function oneClickApproveOrder(_ref22) { var _headers20; - var orderID = _ref20.orderID, instrumentType = _ref20.instrumentType, instrumentID = _ref20.instrumentID, buyerAccessToken = _ref20.buyerAccessToken, clientMetadataID = _ref20.clientMetadataID, planID = _ref20.planID, _ref20$useExistingPla = _ref20.useExistingPlanning, useExistingPlanning = void 0 !== _ref20$useExistingPla && _ref20$useExistingPla, enableOrdersApprovalSmartWallet = _ref20.enableOrdersApprovalSmartWallet; + var orderID = _ref22.orderID, instrumentType = _ref22.instrumentType, instrumentID = _ref22.instrumentID, buyerAccessToken = _ref22.buyerAccessToken, clientMetadataID = _ref22.clientMetadataID; return Object(api.callGraphQL)({ name: "OneClickApproveOrder", - query: "\n mutation OneClickApproveOrder(\n $orderID : String!\n $instrumentType : String!\n $instrumentID : String!\n $planID: String\n $useExistingPlanning: Boolean\n ) {\n oneClickPayment(\n token: $orderID\n selectedInstrumentType : $instrumentType\n selectedInstrumentId : $instrumentID\n selectedPlanId: $planID\n useExistingPlanning: $useExistingPlanning\n ) {\n userId\n " + (enableOrdersApprovalSmartWallet ? "" : "auth {\n accessToken\n }") + "\n }\n }\n ", + query: "\n mutation OneClickApproveOrder(\n $orderID : String!\n $instrumentType : String!\n $instrumentID : String!\n ) {\n oneClickPayment(\n token: $orderID\n selectedInstrumentType : $instrumentType\n selectedInstrumentId : $instrumentID\n ) {\n userId\n auth {\n accessToken\n }\n }\n }\n ", variables: { orderID: orderID, instrumentType: instrumentType, - instrumentID: instrumentID, - planID: planID, - useExistingPlanning: useExistingPlanning + instrumentID: instrumentID }, headers: (_headers20 = {}, _headers20[constants.HEADERS.ACCESS_TOKEN] = buyerAccessToken, _headers20[constants.HEADERS.CLIENT_CONTEXT] = orderID, _headers20[constants.HEADERS.CLIENT_METADATA_ID] = clientMetadataID || orderID, _headers20) - }).then((function(_ref21) { + }).then((function(_ref23) { var _oneClickPayment$auth; - var oneClickPayment = _ref21.oneClickPayment; + var oneClickPayment = _ref23.oneClickPayment; null != oneClickPayment && null != (_oneClickPayment$auth = oneClickPayment.auth) && _oneClickPayment$auth.accessToken && Object(lib.setBuyerAccessToken)(oneClickPayment.auth.accessToken); return { payerID: oneClickPayment.userId @@ -10130,20 +10409,20 @@ window.spb = function(modules) { _headers23) }); }; - function updateButtonClientConfig(_ref22) { - var _ref22$inline = _ref22.inline; + function updateButtonClientConfig(_ref24) { + var _ref24$inline = _ref24.inline; return updateClientConfig({ - orderID: _ref22.orderID, - fundingSource: _ref22.fundingSource, + orderID: _ref24.orderID, + fundingSource: _ref24.fundingSource, integrationArtifact: constants.INTEGRATION_ARTIFACT.PAYPAL_JS_SDK, - userExperienceFlow: _ref22.userExperienceFlow || (void 0 !== _ref22$inline && _ref22$inline ? constants.USER_EXPERIENCE_FLOW.INLINE : constants.USER_EXPERIENCE_FLOW.INCONTEXT), + userExperienceFlow: _ref24.userExperienceFlow || (void 0 !== _ref24$inline && _ref24$inline ? constants.USER_EXPERIENCE_FLOW.INLINE : constants.USER_EXPERIENCE_FLOW.INCONTEXT), productFlow: constants.PRODUCT_FLOW.SMART_PAYMENT_BUTTONS, - buttonSessionID: _ref22.buttonSessionID, - featureFlags: _ref22.featureFlags + buttonSessionID: _ref24.buttonSessionID, + featureFlags: _ref24.featureFlags }); } - function approveCardPayment(_ref23) { - var card = _ref23.card, orderID = _ref23.orderID, clientID = _ref23.clientID, branded = _ref23.branded; + function approveCardPayment(_ref25) { + var card = _ref25.card, orderID = _ref25.orderID, clientID = _ref25.clientID, branded = _ref25.branded; return Object(api.callGraphQL)({ name: "ProcessPayment", query: '\n mutation ProcessPayment(\n $orderID: String!\n $clientID: String!\n $card: CardInput!\n $branded: Boolean!\n ) {\n processPayment(\n clientID: $clientID\n paymentMethod: { type: CARD, card: $card }\n branded: $branded\n orderID: $orderID\n buttonSessionID: "f7r7367r4"\n )\n }\n ', @@ -10248,13 +10527,14 @@ window.spb = function(modules) { var token = applePayPayment.token, billingContact = applePayPayment.billingContact, shippingContact = applePayPayment.shippingContact; return Object(api.callGraphQL)({ name: "ApproveApplePayPayment", - query: "\n mutation ApproveApplePayPayment(\n $token: ApplePayPaymentToken!\n $orderID: String!\n $clientID : String!\n $billingContact: ApplePayPaymentContact!\n $shippingContact: ApplePayPaymentContact\n ) {\n approveApplePayPayment(\n token: $token\n orderID: $orderID\n clientID: $clientID\n billingContact: $billingContact\n shippingContact: $shippingContact\n )\n }\n ", + query: "\n mutation ApproveApplePayPayment(\n $token: ApplePayPaymentToken!\n $orderID: String!\n $clientID : String!\n $billingContact: ApplePayPaymentContact!\n $shippingContact: ApplePayPaymentContact\n $productFlow: String\n ) {\n approveApplePayPayment(\n token: $token\n orderID: $orderID\n clientID: $clientID\n billingContact: $billingContact\n shippingContact: $shippingContact\n productFlow: $productFlow\n )\n }\n ", variables: { token: token, orderID: orderID, clientID: clientID, billingContact: billingContact, - shippingContact: shippingContact + shippingContact: shippingContact, + productFlow: constants.PRODUCT_FLOW.SMART_PAYMENT_BUTTONS } }).then((function(gqlResult) { if (!gqlResult || !gqlResult.approveApplePayPayment) throw new Error("GraphQL GetApplePayPayment returned no applePayment object"); @@ -10697,8 +10977,8 @@ window.spb = function(modules) { }); } var _FRAUDNET_URL; - var FRAUDNET_URL = ((_FRAUDNET_URL = {})[sdk_constants_src.ENV.LOCAL] = "https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js", - _FRAUDNET_URL[sdk_constants_src.ENV.STAGE] = "https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js", + var FRAUDNET_URL = ((_FRAUDNET_URL = {})[sdk_constants_src.ENV.LOCAL] = "https://www.msmaster.qa.paypal.com/en_US/m/fb-raw.js", + _FRAUDNET_URL[sdk_constants_src.ENV.STAGE] = "https://stage2mb044.qa.paypal.com/fraudnetjsnodeweb/automate/develop/stage_raw.js", _FRAUDNET_URL[sdk_constants_src.ENV.SANDBOX] = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL[sdk_constants_src.ENV.PRODUCTION] = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL[sdk_constants_src.ENV.TEST] = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL); @@ -10738,7 +11018,7 @@ window.spb = function(modules) { })); })); var getSmartWallet = Object(belter_src.memoize)((function(_ref) { - var clientID = _ref.clientID, merchantID = _ref.merchantID, currency = _ref.currency, _ref$amount = _ref.amount, amount = void 0 === _ref$amount ? "0.00" : _ref$amount, clientMetadataID = _ref.clientMetadataID, userIDToken = _ref.userIDToken, _ref$vetted = _ref.vetted, vetted = void 0 === _ref$vetted || _ref$vetted, paymentMethodToken = _ref.paymentMethodToken, branded = _ref.branded, _ref$allowBillingPaym = _ref.allowBillingPayments, allowBillingPayments = void 0 === _ref$allowBillingPaym || _ref$allowBillingPaym, _ref$headers = _ref.headers, headers = void 0 === _ref$headers ? {} : _ref$headers; + var clientID = _ref.clientID, merchantID = _ref.merchantID, currency = _ref.currency, _ref$amount = _ref.amount, amount = void 0 === _ref$amount ? "0" : _ref$amount, clientMetadataID = _ref.clientMetadataID, userIDToken = _ref.userIDToken, _ref$vetted = _ref.vetted, vetted = void 0 === _ref$vetted || _ref$vetted, paymentMethodToken = _ref.paymentMethodToken, branded = _ref.branded, _ref$allowBillingPaym = _ref.allowBillingPayments, allowBillingPayments = void 0 === _ref$allowBillingPaym || _ref$allowBillingPaym, _ref$headers = _ref.headers, headers = void 0 === _ref$headers ? {} : _ref$headers; clientMetadataID && (headers[constants.HEADERS.CLIENT_METADATA_ID] = String(clientMetadataID)); return Object(api.callGraphQL)({ name: "GetSmartWallet", @@ -10882,14 +11162,15 @@ window.spb = function(modules) { }); }; var updateVaultSetupToken = function(_ref2) { - var clientID = _ref2.clientID, vaultSetupToken = _ref2.vaultSetupToken, paymentSource = _ref2.paymentSource; + var clientID = _ref2.clientID, vaultSetupToken = _ref2.vaultSetupToken, paymentSource = _ref2.paymentSource, idToken = _ref2.idToken; return Object(_api__WEBPACK_IMPORTED_MODULE_2__.callGraphQL)({ name: "UpdateVaultSetupToken", - query: "\n mutation UpdateVaultSetupToken(\n $clientID: String!\n $vaultSetupToken: String!\n $paymentSource: PaymentSource\n ) {\n updateVaultSetupToken(\n clientId: $clientID\n vaultSetupToken: $vaultSetupToken\n paymentSource: $paymentSource\n ) {\n id,\n status,\n links {\n rel, href\n }\n }\n }", + query: "\n mutation UpdateVaultSetupToken(\n $clientID: String!\n $vaultSetupToken: String!\n $paymentSource: PaymentSource\n $idToken: String\n ) {\n updateVaultSetupToken(\n clientId: $clientID\n vaultSetupToken: $vaultSetupToken\n paymentSource: $paymentSource\n idToken: $idToken\n ) {\n id,\n status,\n links {\n rel, href\n }\n }\n }", variables: { clientID: clientID, vaultSetupToken: vaultSetupToken, - paymentSource: paymentSource + paymentSource: paymentSource, + idToken: idToken } }); }; @@ -10946,7 +11227,7 @@ window.spb = function(modules) { var TYPES = !0; function getButtonProps(_ref) { var _branded; - var facilitatorAccessToken = _ref.facilitatorAccessToken, paymentSource = _ref.paymentSource, experiments = _ref.experiments, featureFlags = _ref.featureFlags, enableOrdersApprovalSmartWallet = _ref.enableOrdersApprovalSmartWallet, smartWalletOrderID = _ref.smartWalletOrderID; + var facilitatorAccessToken = _ref.facilitatorAccessToken, paymentSource = _ref.paymentSource, experiments = _ref.experiments, featureFlags = _ref.featureFlags; var xprops = window.xprops; var buttonSessionID = xprops.buttonSessionID, style = xprops.style, branded = xprops.branded, intent = xprops.intent, partnerAttributionID = xprops.partnerAttributionID, merchantID = xprops.merchantID, clientID = xprops.clientID, clientAccessToken = xprops.clientAccessToken, _xprops$vault = xprops.vault, vault = void 0 !== _xprops$vault && _xprops$vault, currency = xprops.currency, flow = xprops.flow; branded = null != (_branded = branded) ? _branded : _ref.brandedDefault; @@ -10972,12 +11253,10 @@ window.spb = function(modules) { if (xprops.createOrder || xprops.createBillingAgreement) throw new Error("Must not pass createOrder or createBillingAgreement with intent=tokenize"); } var props = Object(props_props.getProps)({ - branded: branded, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, - smartWalletOrderID: smartWalletOrderID + branded: branded }); var callbackProps = function(_ref) { - var paymentSource = _ref.paymentSource, partnerAttributionID = _ref.partnerAttributionID, merchantID = _ref.merchantID, clientID = _ref.clientID, facilitatorAccessToken = _ref.facilitatorAccessToken, currency = _ref.currency, intent = _ref.intent, enableOrdersApprovalSmartWallet = _ref.enableOrdersApprovalSmartWallet, smartWalletOrderID = _ref.smartWalletOrderID, branded = _ref.branded, clientAccessToken = _ref.clientAccessToken, _ref$vault = _ref.vault, vault = void 0 !== _ref$vault && _ref$vault, _ref$experiments = _ref.experiments, experiments = void 0 === _ref$experiments ? {} : _ref$experiments, featureFlags = _ref.featureFlags, inputCreateBillingAgreement = _ref.createBillingAgreement, inputCreateSubscription = _ref.createSubscription, inputCreateOrder = _ref.createOrder, onError = _ref.onError, inputOnApprove = _ref.onApprove, inputOnComplete = _ref.onComplete, inputOnCancel = _ref.onCancel, inputOnShippingChange = _ref.onShippingChange, inputOnShippingAddressChange = _ref.onShippingAddressChange, inputOnShippingOptionsChange = _ref.onShippingOptionsChange, inputCreateVaultSetupToken = _ref.createVaultSetupToken, flow = _ref.flow; + var paymentSource = _ref.paymentSource, partnerAttributionID = _ref.partnerAttributionID, merchantID = _ref.merchantID, clientID = _ref.clientID, facilitatorAccessToken = _ref.facilitatorAccessToken, currency = _ref.currency, intent = _ref.intent, branded = _ref.branded, clientAccessToken = _ref.clientAccessToken, _ref$vault = _ref.vault, vault = void 0 !== _ref$vault && _ref$vault, _ref$experiments = _ref.experiments, experiments = void 0 === _ref$experiments ? {} : _ref$experiments, featureFlags = _ref.featureFlags, inputCreateBillingAgreement = _ref.createBillingAgreement, inputCreateSubscription = _ref.createSubscription, inputCreateOrder = _ref.createOrder, onError = _ref.onError, inputOnApprove = _ref.onApprove, inputOnComplete = _ref.onComplete, inputOnCancel = _ref.onCancel, inputOnShippingChange = _ref.onShippingChange, inputOnShippingAddressChange = _ref.onShippingAddressChange, inputOnShippingOptionsChange = _ref.onShippingOptionsChange, inputCreateVaultSetupToken = _ref.createVaultSetupToken, flow = _ref.flow; var createBillingAgreement = Object(props_createBillingAgreement.getCreateBillingAgreement)({ createBillingAgreement: inputCreateBillingAgreement, paymentSource: paymentSource @@ -11001,13 +11280,12 @@ window.spb = function(modules) { intent: intent, merchantID: merchantID, partnerAttributionID: partnerAttributionID, - paymentSource: paymentSource + paymentSource: paymentSource, + experiments: experiments }, { facilitatorAccessToken: facilitatorAccessToken, createBillingAgreement: createBillingAgreement, createSubscription: createSubscription, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, - smartWalletOrderID: smartWalletOrderID, createVaultSetupToken: createVaultSetupToken, flow: flow }); @@ -11042,7 +11320,8 @@ window.spb = function(modules) { clientID: clientID, facilitatorAccessToken: facilitatorAccessToken, createOrder: createOrder, - featureFlags: featureFlags + featureFlags: featureFlags, + experiments: experiments }), onCancel: Object(props_onCancel.getOnCancel)({ onCancel: inputOnCancel, @@ -11055,29 +11334,23 @@ window.spb = function(modules) { partnerAttributionID: partnerAttributionID, experiments: experiments, featureFlags: featureFlags, - clientID: clientID + clientID: clientID, + paymentSource: paymentSource }, { facilitatorAccessToken: facilitatorAccessToken, createOrder: createOrder }), onShippingAddressChange: Object(props_onShippingAddressChange.getOnShippingAddressChange)({ - onShippingAddressChange: inputOnShippingAddressChange, - clientID: clientID + onShippingAddressChange: inputOnShippingAddressChange }, { createOrder: createOrder }), onShippingOptionsChange: Object(props_onShippingOptionsChange.getOnShippingOptionsChange)({ - onShippingOptionsChange: inputOnShippingOptionsChange, - clientID: clientID + onShippingOptionsChange: inputOnShippingOptionsChange }, { createOrder: createOrder }), - onAuth: Object(props_onAuth.getOnAuth)({ - facilitatorAccessToken: facilitatorAccessToken, - createOrder: createOrder, - createSubscription: createSubscription, - featureFlags: featureFlags - }) + onAuth: Object(props_onAuth.getOnAuth)() }; }({ paymentSource: paymentSource, @@ -11087,8 +11360,6 @@ window.spb = function(modules) { facilitatorAccessToken: facilitatorAccessToken, currency: currency, intent: intent, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, - smartWalletOrderID: smartWalletOrderID, branded: branded, clientAccessToken: clientAccessToken, vault: vault, @@ -11159,9 +11430,6 @@ window.spb = function(modules) { featureFlags: _ref3.featureFlags }; } - function getButtons() { - return Object(src.querySelectorAll)("[ " + constants.DATA_ATTRIBUTES.FUNDING_SOURCE + " ]"); - } function enableLoadingSpinner(button) { button.classList.add(constants.CLASS.LOADING); } @@ -11898,6 +12166,21 @@ window.spb = function(modules) { var smokeHash = ""; var buyerAccessTokenReceivedOnAuth = null; var checkout_getDimensions = function(fundingSource, popupIncreaseDimensions) { + if (Object(src.isWebView)()) { + Object(lib.getLogger)().info("popup_dimensions_" + fundingSource); + Object(lib.sendCountMetric)({ + name: "pp.app.paypal_sdk.checkout_ui.dimension.count", + dimensions: { + spbPaymentFlow: "checkout", + fundingSource: fundingSource, + dimensionType: "webview" + } + }); + return { + width: window.outerWidth - 4, + height: window.outerHeight - 20 + }; + } if (-1 !== sdk_constants_src.APM_LIST.indexOf(fundingSource)) { Object(lib.getLogger)().info("popup_dimensions_value_" + fundingSource); Object(lib.sendCountMetric)({ @@ -12017,6 +12300,7 @@ window.spb = function(modules) { clientAccessToken: clientAccessToken, venmoPayloadID: venmoPayloadID, smokeHash: smokeHash, + sign_out_user: buyerIntent === constants.BUYER_INTENT.PAY_WITH_DIFFERENT_ACCOUNT, createAuthCode: function() { return zalgo_promise_src.ZalgoPromise.try((function() { var fundingSkipLogin = src_config.FUNDING_SKIP_LOGIN[fundingSource]; @@ -12133,62 +12417,9 @@ window.spb = function(modules) { return close().then(src.noop); })).catch(src.noop); }, - onSmartWalletEligible: function(_ref8) { - var eligibilityReason = _ref8.eligibilityReason, orderID = _ref8.orderID; - var _ref9 = _ref8.locale || locale, country = _ref9.country, lang = _ref9.lang; - var access_token = _ref8.accessToken || buyerAccessToken || ""; - if (window.innerWidth < 250 || buyerIntent === constants.BUYER_INTENT.PAY_WITH_DIFFERENT_FUNDING_SHIPPING || buyerIntent === constants.BUYER_INTENT.PAY_WITH_DIFFERENT_ACCOUNT) { - var _getLogger$info$track2; - Object(lib.getLogger)().info("checkout_smart_wallet_not_eligible ", { - buyerIntent: buyerIntent, - width: window.innerWidth - }).track((_getLogger$info$track2 = {}, _getLogger$info$track2[sdk_constants_src.FPTI_KEY.STATE] = constants.FPTI_STATE.BUTTON, - _getLogger$info$track2[sdk_constants_src.FPTI_KEY.STATE] = constants.FPTI_STATE.ELIGIBILITY_CHECK, - _getLogger$info$track2[sdk_constants_src.FPTI_KEY.TRANSITION] = eligibilityReason + "_ineligible", - _getLogger$info$track2[sdk_constants_src.FPTI_KEY.CONTEXT_ID] = orderID, _getLogger$info$track2[sdk_constants_src.FPTI_KEY.CONTEXT_TYPE] = constants.FPTI_CONTEXT_TYPE.ORDER_ID, - _getLogger$info$track2)).flush(); - return zalgo_promise_src.ZalgoPromise.resolve({ - smartWalletRendered: !1, - buyerIntent: buyerIntent - }); - } - _createOrder().then((function(walletOrderID) { - var _getLogger$info$track3; - Object(lib.getLogger)().info("checkout_smart_wallet_eligible ", { - buyerIntent: buyerIntent, - eligibilityReason: eligibilityReason - }).track((_getLogger$info$track3 = {}, _getLogger$info$track3[sdk_constants_src.FPTI_KEY.STATE] = constants.FPTI_STATE.BUTTON, - _getLogger$info$track3[sdk_constants_src.FPTI_KEY.STATE] = constants.FPTI_STATE.ELIGIBILITY_CHECK, - _getLogger$info$track3[sdk_constants_src.FPTI_KEY.TRANSITION] = eligibilityReason + "_eligible", - _getLogger$info$track3[sdk_constants_src.FPTI_KEY.CONTEXT_ID] = walletOrderID, _getLogger$info$track3[sdk_constants_src.FPTI_KEY.CONTEXT_TYPE] = constants.FPTI_CONTEXT_TYPE.ORDER_ID, - _getLogger$info$track3)).flush().then((function() { - close().then((function() { - getButtons().forEach((function(smartButton) { - return enableLoadingSpinner(smartButton); - })); - Object(src.submitForm)({ - url: document.location.href, - target: "_self", - body: { - buyerAccessToken: access_token, - smartWalletOrderID: walletOrderID, - enableOrdersApprovalSmartWallet: !0, - "locale.country": country, - "locale.lang": lang, - product: eligibilityReason - } - }); - })); - })); - })); - return zalgo_promise_src.ZalgoPromise.resolve({ - smartWalletRendered: !0, - buyerIntent: buyerIntent - }); - }, - onAuth: function(_ref10) { + onAuth: function(_ref8) { return _onAuth({ - accessToken: buyerAccessTokenReceivedOnAuth = _ref10.accessToken || buyerAccessToken + accessToken: buyerAccessTokenReceivedOnAuth = _ref8.accessToken || buyerAccessToken }).then((function(token) { buyerAccessToken = token; })); @@ -12204,11 +12435,11 @@ window.spb = function(modules) { }, data), actions); } : null, onShippingAddressChange: onShippingAddressChange ? function(data, actions) { - if (!data.shipping_address) throw new Error("Must pass shipping_address in data to handle changes in shipping address."); + if (!data.shippingAddress) throw new Error("Must pass shippingAddress in data to handle changes in shipping address."); return onShippingAddressChange(Object(esm_extends.default)({}, data), actions); } : null, onShippingOptionsChange: onShippingOptionsChange ? function(data, actions) { - if (!data.selected_shipping_option) throw new Error("Must pass selected_shipping_option in data to handle changes in shipping options."); + if (!data.selectedShippingOption) throw new Error("Must pass selectedShippingOption in data to handle changes in shipping options."); return onShippingOptionsChange(Object(esm_extends.default)({}, data), actions); } : null, onClose: function() { @@ -12219,14 +12450,14 @@ window.spb = function(modules) { }).catch(src.noop) : forceClosed || approved ? void 0 : _onCancel(); }, onError: function(err) { - var _getLogger$info$track4; + var _getLogger$info$track2; Object(lib.getLogger)().info("checkout_flow_error ", { err: Object(src.stringifyError)(err) - }).track((_getLogger$info$track4 = {}, _getLogger$info$track4[sdk_constants_src.FPTI_KEY.STATE] = constants.FPTI_STATE.BUTTON, - _getLogger$info$track4[sdk_constants_src.FPTI_KEY.TRANSITION] = constants.FPTI_TRANSITION.CHECKOUT_ERROR, - _getLogger$info$track4[sdk_constants_src.FPTI_KEY.EVENT_NAME] = constants.FPTI_TRANSITION.CHECKOUT_ERROR, - _getLogger$info$track4[sdk_constants_src.FPTI_KEY.ERROR_DESC] = Object(src.stringifyError)(err), - _getLogger$info$track4)).flush(); + }).track((_getLogger$info$track2 = {}, _getLogger$info$track2[sdk_constants_src.FPTI_KEY.STATE] = constants.FPTI_STATE.BUTTON, + _getLogger$info$track2[sdk_constants_src.FPTI_KEY.TRANSITION] = constants.FPTI_TRANSITION.CHECKOUT_ERROR, + _getLogger$info$track2[sdk_constants_src.FPTI_KEY.EVENT_NAME] = constants.FPTI_TRANSITION.CHECKOUT_ERROR, + _getLogger$info$track2[sdk_constants_src.FPTI_KEY.ERROR_DESC] = Object(src.stringifyError)(err), + _getLogger$info$track2)).flush(); return _onError(err); }, dimensions: checkout_getDimensions(fundingSource, null != (_experiments$popupInc = null == experiments ? void 0 : experiments.popupIncreaseDimensions) && _experiments$popupInc), @@ -12321,8 +12552,8 @@ window.spb = function(modules) { close: close }; }, - updateFlowClientConfig: function(_ref11) { - var orderID = _ref11.orderID, payment = _ref11.payment, userExperienceFlow = _ref11.userExperienceFlow, featureFlags = _ref11.featureFlags; + updateFlowClientConfig: function(_ref9) { + var orderID = _ref9.orderID, payment = _ref9.payment, userExperienceFlow = _ref9.userExperienceFlow, featureFlags = _ref9.featureFlags; return zalgo_promise_src.ZalgoPromise.try((function() { var buyerIntent = payment.buyerIntent, fundingSource = payment.fundingSource; var updateClientConfigPromise = Object(api.updateButtonClientConfig)({ @@ -12836,6 +13067,7 @@ window.spb = function(modules) { return (_ref9 = {})["3ds_auth_status"] = authStatus, _ref9; })); }; + var lib_logger = __webpack_require__("./src/lib/logger.js"); function handleThreeDomainSecureRedirect(_ref) { var ThreeDomainSecure = _ref.ThreeDomainSecure, vaultToken = _ref.vaultToken, createOrder = _ref.createOrder, action = _ref.action, getParent = _ref.getParent; var promise = new zalgo_promise_src.ZalgoPromise; @@ -12867,7 +13099,7 @@ window.spb = function(modules) { })).finally(instance.close); } function handleThreeDomainSecureContingency(_ref2) { - var status = _ref2.status, links = _ref2.links, ThreeDomainSecure = _ref2.ThreeDomainSecure, createOrder = _ref2.createOrder, getParent = _ref2.getParent; + var status = _ref2.status, links = _ref2.links, ThreeDomainSecure = _ref2.ThreeDomainSecure, createOrder = _ref2.createOrder, getParent = _ref2.getParent, paymentFlow = _ref2.paymentFlow, fundingSource = _ref2.fundingSource; return zalgo_promise_src.ZalgoPromise.try((function() { if ("PAYER_ACTION_REQUIRED" === status && links.some((function(link) { return function(link) { @@ -12876,6 +13108,20 @@ window.spb = function(modules) { return "approve" === link.rel && link.href.includes("helios"); }(link); }))) { + var contingency = "confirm_payment_source_three_ds_contingency"; + "vault-capture" === paymentFlow ? Object(lib_logger.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.vault_capture.contingency.count", + dimensions: { + fundingSource: fundingSource, + contingency: contingency + } + }) : Object(lib_logger.sendCountMetric)({ + name: "pp.app.paypal_sdk.card_fields.submit.contingency.count", + dimensions: { + paymentFlow: paymentFlow, + contingency: contingency + } + }); var _getThreeDSParams = function(links) { var helioslink = links.find((function(link) { return link.href.includes("helios"); @@ -12915,7 +13161,7 @@ window.spb = function(modules) { click: function() {}, start: function() { return function(_ref) { - var facilitatorAccessToken = _ref.facilitatorAccessToken, extraFields = _ref.extraFields; + var facilitatorAccessToken = _ref.facilitatorAccessToken, extraFields = _ref.extraFields, experiments = _ref.experiments; var cardProps = function(_ref2) { var _fundingEligibility$c, _fundingEligibility$c2; var facilitatorAccessToken = _ref2.facilitatorAccessToken; @@ -12936,7 +13182,8 @@ window.spb = function(modules) { facilitatorAccessToken: facilitatorAccessToken, sdkCorrelationID: xprops.sdkCorrelationID, partnerAttributionID: xprops.partnerAttributionID, - hcfSessionID: xprops.hcfSessionID + hcfSessionID: xprops.hcfSessionID, + userIDToken: xprops.userIDToken }; var baseProps = Object(src_props.getProps)({ branded: branded @@ -12962,8 +13209,9 @@ window.spb = function(modules) { }({ facilitatorAccessToken: facilitatorAccessToken, featureFlags: _ref.featureFlags, - experiments: _ref.experiments + experiments: experiments }); + experiments.useIDToken && (cardProps.userIDToken ? facilitatorAccessToken = cardProps.userIDToken : Object(lib_logger.getLogger)().info("hcf_userIDToken_present_false")); !function(_ref10) { var _getLogger$track5; var cardFlowType = _ref10.cardFlowType, hcfSessionID = _ref10.hcfSessionID; @@ -13031,7 +13279,7 @@ window.spb = function(modules) { return function(cardProps, card, extraFields, facilitatorAccessToken) { var orderID; var ThreeDomainSecure = props_getComponents().ThreeDomainSecure; - var createOrder = cardProps.createOrder, getParent = cardProps.getParent; + var createOrder = cardProps.createOrder, getParent = cardProps.getParent, productAction = cardProps.productAction; return cardProps.createOrder().then((function(id) { var payment_source = convertCardToPaymentSource(card, extraFields); var data = { @@ -13055,7 +13303,8 @@ window.spb = function(modules) { orderID = id; return Object(api.confirmOrderAPI)(orderID, data, { facilitatorAccessToken: facilitatorAccessToken, - partnerAttributionID: "" + partnerAttributionID: "", + experiments: {} }); })).then((function(res) { return handleThreeDomainSecureContingency({ @@ -13063,7 +13312,8 @@ window.spb = function(modules) { links: res.links, ThreeDomainSecure: ThreeDomainSecure, createOrder: createOrder, - getParent: getParent + getParent: getParent, + paymentFlow: productAction }); })).then((function(threeDsResponse) { return cardProps.onApprove({ @@ -13117,8 +13367,9 @@ window.spb = function(modules) { case constants.PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE: return function(cardProps, card, extraFields) { var _getComponents = props_getComponents(); + var userIDToken = cardProps.userIDToken, productAction = cardProps.productAction; return function(_ref) { - var onApprove = _ref.onApprove, onError = _ref.onError, clientID = _ref.clientID, paymentSource = _ref.paymentSource, getParent = _ref.getParent, ThreeDomainSecure = _ref.ThreeDomainSecure; + var onApprove = _ref.onApprove, onError = _ref.onError, clientID = _ref.clientID, paymentSource = _ref.paymentSource, getParent = _ref.getParent, ThreeDomainSecure = _ref.ThreeDomainSecure, idToken = _ref.idToken, productAction = _ref.productAction; var vaultToken; return (0, _ref.createVaultSetupToken)().then((function(vaultSetupToken) { if ("string" != typeof vaultSetupToken) throw new TypeError("Expected createVaultSetupToken to return a promise that resolves with vaultSetupToken as a string"); @@ -13126,7 +13377,8 @@ window.spb = function(modules) { return Object(api_vault.updateVaultSetupToken)({ vaultSetupToken: vaultSetupToken, clientID: clientID, - paymentSource: paymentSource + paymentSource: paymentSource, + idToken: idToken }); })).then((function(res) { var _ref2 = (null == res ? void 0 : res.updateVaultSetupToken) || {}; @@ -13134,7 +13386,8 @@ window.spb = function(modules) { status: _ref2.status, links: _ref2.links, getParent: getParent, - ThreeDomainSecure: ThreeDomainSecure + ThreeDomainSecure: ThreeDomainSecure, + paymentFlow: productAction }); })).then((function(threeDsResponse) { return onApprove({ @@ -13190,7 +13443,9 @@ window.spb = function(modules) { getParent: cardProps.getParent, ThreeDomainSecure: _getComponents.ThreeDomainSecure, clientID: cardProps.clientID, - paymentSource: convertCardToPaymentSource(card, extraFields) + paymentSource: convertCardToPaymentSource(card, extraFields), + idToken: userIDToken, + productAction: productAction }); }(cardProps, card, extraFields); @@ -13202,7 +13457,8 @@ window.spb = function(modules) { facilitatorAccessToken: facilitatorAccessToken, featureFlags: serviceData.featureFlags, experiments: { - hostedCardFields: !0 + hostedCardFields: !0, + useIDToken: !0 } }); }, @@ -13232,8 +13488,8 @@ window.spb = function(modules) { return !(payment.win || !payment.paymentMethodID || window.innerWidth < 250 && payment.fundingSource === sdk_constants_src.FUNDING.PAYPAL); }, init: function(_ref5) { - var props = _ref5.props, components = _ref5.components, payment = _ref5.payment, serviceData = _ref5.serviceData, config = _ref5.config; - var createOrder = props.createOrder, onApprove = props.onApprove, clientAccessToken = props.clientAccessToken, enableThreeDomainSecure = props.enableThreeDomainSecure, partnerAttributionID = props.partnerAttributionID, getParent = props.getParent, userIDToken = props.userIDToken, clientID = props.clientID, env = props.env, merchantID = props.merchantID, disableSetCookie = props.disableSetCookie; + var props = _ref5.props, components = _ref5.components, payment = _ref5.payment, serviceData = _ref5.serviceData, config = _ref5.config, experiments = _ref5.experiments; + var createOrder = props.createOrder, onApprove = props.onApprove, clientAccessToken = props.clientAccessToken, enableThreeDomainSecure = props.enableThreeDomainSecure, partnerAttributionID = props.partnerAttributionID, getParent = props.getParent, userIDToken = props.userIDToken, clientID = props.clientID, env = props.env, disableSetCookie = props.disableSetCookie; var ThreeDomainSecure = components.ThreeDomainSecure, Installments = components.Installments; var fundingSource = payment.fundingSource, paymentMethodID = payment.paymentMethodID, button = payment.button; var facilitatorAccessToken = serviceData.facilitatorAccessToken, buyerCountry = serviceData.buyerCountry; @@ -13244,8 +13500,7 @@ window.spb = function(modules) { }({ props: props }); - var accessToken = facilitatorAccessToken; - clientAccessToken && (accessToken = clientAccessToken); + var accessToken = null != clientAccessToken ? clientAccessToken : facilitatorAccessToken; if (!paymentMethodID) throw new Error("Payment method id required for vault capture"); if (!accessToken) throw new Error("Client access token required for vault capture"); var restart = function() { @@ -13253,29 +13508,25 @@ window.spb = function(modules) { throw new Error("Vault capture restart not implemented"); })); }; + var fallbackToWebCheckout = function() { + Object(lib.getLogger)().info("web_checkout_fallback").flush(); + return checkout.init({ + props: props, + components: components, + serviceData: serviceData, + payment: Object(esm_extends.default)({}, payment, { + isClick: !1, + buyerIntent: constants.BUYER_INTENT.PAY_WITH_DIFFERENT_FUNDING_SHIPPING + }), + config: config, + restart: restart + }).start(); + }; var shippingRequired = function(orderID) { return Object(api.getSupplementalOrderInfo)(orderID).then((function(order) { return !!order.checkoutSession.flags.isChangeShippingAddressAllowed; })); }; - if (userIDToken && merchantID && merchantID[0]) { - Object(lib.getLogger)().info("vault_create_access_token", { - merchantID: merchantID[0], - clientID: clientID - }); - zalgo_promise_src.ZalgoPromise.try((function() { - return Object(api.createAccessToken)(clientID, { - targetSubject: merchantID[0] - }).catch((function(err) { - Object(lib.getLogger)().warn("vault_access_token_with_target_subject_failure", { - error: Object(src.stringifyError)(err) - }); - throw err; - })); - })).then((function(accessTokenWithTargetSubject) { - accessToken = accessTokenWithTargetSubject; - })); - } var startPaymentFlow = function(orderID, installmentPlan) { return zalgo_promise_src.ZalgoPromise.hash({ validate: Object(api.validatePaymentMethod)({ @@ -13291,36 +13542,43 @@ window.spb = function(modules) { }).then((function(_ref6) { var validate = _ref6.validate; if (_ref6.requireShipping) { - if (fundingSource !== sdk_constants_src.FUNDING.PAYPAL) { - Object(lib.getLogger)().error("vault_shipping_required"); - throw new Error("Shipping address requested for " + fundingSource + " payment"); - } - return function() { - Object(lib.getLogger)().info("web_checkout_fallback").flush(); - return checkout.init({ - props: props, - components: components, - serviceData: serviceData, - payment: Object(esm_extends.default)({}, payment, { - isClick: !1, - buyerIntent: constants.BUYER_INTENT.PAY_WITH_DIFFERENT_FUNDING_SHIPPING - }), - config: config, - restart: restart - }).start(); - }(); + Object(lib.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.vault_capture.error.count", + event: "error", + dimensions: { + errorName: "shipping_required_failure_or_fallback", + fundingSource: fundingSource + } + }); + if (fundingSource !== sdk_constants_src.FUNDING.PAYPAL) throw new Error("Shipping address requested for " + fundingSource + " payment"); + return fallbackToWebCheckout(); } return function(_ref3) { var ThreeDomainSecure = _ref3.ThreeDomainSecure, status = _ref3.status, body = _ref3.body, createOrder = _ref3.createOrder, getParent = _ref3.getParent; return zalgo_promise_src.ZalgoPromise.try((function() { if (422 === status && body.links && body.links.some((function(link) { return "3ds-contingency-resolution" === link.rel; - }))) return handleThreeDomainSecureRedirect({ - ThreeDomainSecure: ThreeDomainSecure, - createOrder: createOrder, - getParent: getParent - }); + }))) { + Object(lib_logger.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.vault_capture.contingency.count", + dimensions: { + contingency: "validate_payment_method_three_ds_contingency" + } + }); + return handleThreeDomainSecureRedirect({ + ThreeDomainSecure: ThreeDomainSecure, + createOrder: createOrder, + getParent: getParent + }); + } if (200 !== status) { + Object(lib_logger.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.vault_capture.error.count", + event: "error", + dimensions: { + errorName: "validate_payment_method_failure" + } + }); if (Array.isArray(body.details)) { var _ref4$issue = (body.details && body.details[0] || {}).issue, issue = void 0 === _ref4$issue ? "" : _ref4$issue; if (0 !== issue.trim().length) throw new Error("Validate payment failed with issue: " + issue); @@ -13336,11 +13594,23 @@ window.spb = function(modules) { getParent: getParent }).then((function() { return Object(api.confirmOrderAPI)(orderID, { - payment_source: Object(api.buildPaymentSource)(paymentMethodID) + payment_source: Object(api.buildPaymentSource)({ + paymentMethodID: paymentMethodID, + fundingSource: fundingSource + }) }, { facilitatorAccessToken: accessToken, - partnerAttributionID: partnerAttributionID + partnerAttributionID: partnerAttributionID, + experiments: {} }).then((function() { + Object(lib.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.vault_capture.success.count", + event: "success", + dimensions: { + fundingSource: fundingSource, + experimentInUse: "none" + } + }); return onApprove({}, { restart: restart }); @@ -13529,7 +13799,58 @@ window.spb = function(modules) { onPay: startPaymentFlow, getLogger: lib.getLogger }); - })) : startPaymentFlow(orderID); + })) : null != experiments && experiments.deprecateVaultValidatePaymentMethod ? function(orderID) { + userIDToken && (accessToken = userIDToken); + zalgo_promise_src.ZalgoPromise.try((function() { + return shippingRequired(orderID).then((function(shippingRequiredFlag) { + if (shippingRequiredFlag) { + Object(lib.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.vault_capture.error.count", + event: "error", + dimensions: { + errorName: "shipping_required_failure_or_fallback", + fundingSource: fundingSource + } + }); + if (fundingSource !== sdk_constants_src.FUNDING.PAYPAL) throw new Error("Shipping address requested for " + fundingSource + " payment"); + return fallbackToWebCheckout(); + } + return Object(api.confirmOrderAPI)(orderID, { + payment_source: Object(api.buildPaymentSource)({ + paymentMethodID: paymentMethodID, + fundingSource: fundingSource, + enableThreeDomainSecure: enableThreeDomainSecure + }) + }, { + facilitatorAccessToken: accessToken, + partnerAttributionID: partnerAttributionID, + experiments: {} + }).then((function(res) { + return handleThreeDomainSecureContingency({ + status: res.status, + links: res.links, + ThreeDomainSecure: ThreeDomainSecure, + createOrder: createOrder, + getParent: getParent, + paymentFlow: "vault_capture", + fundingSource: fundingSource + }); + })).then((function() { + Object(lib.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.vault_capture.success.count", + event: "success", + dimensions: { + fundingSource: fundingSource, + experimentInUse: "deprecated_validate_payment_method_experiment" + } + }); + return onApprove({}, { + restart: restart + }); + })); + })); + })); + }(orderID) : startPaymentFlow(orderID); })); })); }, @@ -13750,17 +14071,15 @@ window.spb = function(modules) { }, init: function(_ref6) { var props = _ref6.props, components = _ref6.components, payment = _ref6.payment, serviceData = _ref6.serviceData, config = _ref6.config, fullRestart = _ref6.restart; - var createOrder = props.createOrder, onApprove = props.onApprove, clientMetadataID = props.clientMetadataID, vault = props.vault, onAuth = props.onAuth, enableOrdersApprovalSmartWallet = props.enableOrdersApprovalSmartWallet; + var createOrder = props.createOrder, onApprove = props.onApprove, clientMetadataID = props.clientMetadataID, vault = props.vault, onAuth = props.onAuth; var fundingSource = payment.fundingSource, instrumentID = payment.instrumentID; var wallet = serviceData.wallet; if (!wallet || !smartWalletPromise) throw new Error("No smart wallet found"); if (!instrumentID) throw new Error("Instrument id required for wallet capture"); var instrument = getInstrument(wallet, fundingSource, instrumentID); - var planID = null == instrument ? void 0 : instrument.planID; var createAccessToken = function() { if (!smartWalletPromise) throw new Error("No smart wallet found"); - var buyerAccessToken = Object(lib.getBuyerAccessToken)(); - return buyerAccessToken && enableOrdersApprovalSmartWallet ? buyerAccessToken : smartWalletPromise.then((function(smartWallet) { + return smartWalletPromise.then((function(smartWallet) { var accessToken = getInstrument(smartWallet, fundingSource, instrumentID).accessToken; if (!accessToken) throw new Error("Instrument access token not found"); return accessToken; @@ -13785,7 +14104,7 @@ window.spb = function(modules) { Object(lib.getLogger)().info("web_checkout_fallback").flush(); return getWebCheckoutFallback().start(); }; - if (!instrument.oneClick || smartWalletErrored || vault && !enableOrdersApprovalSmartWallet) return getWebCheckoutFallback(); + if (!instrument.oneClick || smartWalletErrored || vault) return getWebCheckoutFallback(); var restart = function() { return fallbackToWebCheckout(); }; @@ -13800,12 +14119,11 @@ window.spb = function(modules) { orderID: createOrder(), smartWallet: smartWalletPromise }).then((function(_ref7) { - var orderID = _ref7.orderID, smartWallet = _ref7.smartWallet; - var buyerAccessToken = enableOrdersApprovalSmartWallet && Object(lib.getBuyerAccessToken)() || getInstrument(smartWallet, fundingSource, instrumentID).accessToken; + var orderID = _ref7.orderID; + var buyerAccessToken = getInstrument(_ref7.smartWallet, fundingSource, instrumentID).accessToken; if (!buyerAccessToken) throw new Error("No access token available for instrument"); var instrumentType = instrument.type; if (!instrumentType) throw new Error("Instrument has no type"); - var useExistingPlanning = Boolean(props.smartWalletOrderID); return zalgo_promise_src.ZalgoPromise.hash({ requireShipping: shippingRequired(orderID), orderApproval: Object(api.oneClickApproveOrder)({ @@ -13813,10 +14131,7 @@ window.spb = function(modules) { instrumentType: instrumentType, buyerAccessToken: buyerAccessToken, instrumentID: instrumentID, - clientMetadataID: clientMetadataID, - planID: planID, - useExistingPlanning: useExistingPlanning, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet + clientMetadataID: clientMetadataID }), onAuth: onAuth({ accessToken: buyerAccessToken @@ -13849,7 +14164,7 @@ window.spb = function(modules) { width: dimensions.WIDTH, height: dimensions.HEIGHT }; - var createOrder = props.createOrder, enableOrdersApprovalSmartWallet = props.enableOrdersApprovalSmartWallet; + var createOrder = props.createOrder; var fundingSource = payment.fundingSource, instrumentID = payment.instrumentID; var wallet = serviceData.wallet, content = serviceData.content, featureFlags = serviceData.featureFlags; if (!wallet) throw new Error("Can not render wallet menu without wallet"); @@ -13876,7 +14191,7 @@ window.spb = function(modules) { }).start(); }; var newFundingSource = instrument.type === sdk_constants_src.WALLET_INSTRUMENT.CREDIT ? sdk_constants_src.FUNDING.CREDIT : fundingSource; - var CHOOSE_FUNDING_SHIPPING = { + if (fundingSource === sdk_constants_src.FUNDING.PAYPAL || fundingSource === sdk_constants_src.FUNDING.CREDIT) return [ { label: content.payWithDifferentMethod, popup: POPUP_OPTIONS, onSelect: function(_ref11) { @@ -13906,8 +14221,6 @@ window.spb = function(modules) { fundingSource: newFundingSource, createAccessToken: function() { return smartWalletPromise.then((function(smartWallet) { - var buyerAccessToken = Object(lib.getBuyerAccessToken)(); - if (enableOrdersApprovalSmartWallet && buyerAccessToken) return buyerAccessToken; var smartInstrument = getInstrument(smartWallet, fundingSource, instrumentID); if (!smartInstrument) throw new Error("Instrument not found"); if (!smartInstrument.accessToken) throw new Error("Instrument access token not found"); @@ -13918,8 +14231,7 @@ window.spb = function(modules) { }); })); } - }; - if (fundingSource === sdk_constants_src.FUNDING.PAYPAL || fundingSource === sdk_constants_src.FUNDING.CREDIT) return props.smartWalletOrderID ? [ CHOOSE_FUNDING_SHIPPING ] : [ CHOOSE_FUNDING_SHIPPING, { + }, { label: content.payWithDifferentAccount, popup: POPUP_OPTIONS, onSelect: function(_ref12) { @@ -13980,8 +14292,8 @@ window.spb = function(modules) { _NATIVE_CHECKOUT_FALL); var VENMO_WEB_URL = ((_VENMO_WEB_URL = {})[sdk_constants_src.ENV.TEST] = "https://account.dev.venmo.com/go/web/paypal", _VENMO_WEB_URL[sdk_constants_src.ENV.LOCAL] = "https://account.dev.venmo.com/go/web/paypal", - _VENMO_WEB_URL[sdk_constants_src.ENV.STAGE] = Object(cross_domain_utils_src.getDomain)().includes("cibns") ? "https://account.dev.venmo.com/go/web/paypal" : "https://account.qa.venmo.com/go/web/paypal", - _VENMO_WEB_URL[sdk_constants_src.ENV.SANDBOX] = "https://account.qa.venmo.com/go/web/paypal", + _VENMO_WEB_URL[sdk_constants_src.ENV.STAGE] = Object(cross_domain_utils_src.getDomain)().includes("cibns") ? "https://account.qa.venmo.com/go/web/paypal" : "https://account.dev.venmo.com/go/web/paypal", + _VENMO_WEB_URL[sdk_constants_src.ENV.SANDBOX] = "https://account.venmo.com/go/web/paypal", _VENMO_WEB_URL[sdk_constants_src.ENV.PRODUCTION] = "https://account.venmo.com/go/web/paypal", _VENMO_WEB_URL); function isNativeOptedIn(_ref) { @@ -14943,8 +15255,8 @@ window.spb = function(modules) { var venmo_getDimensions = function(fundingSource) { Object(lib.getLogger)().info("popup_dimensions_" + fundingSource).flush(); return { - width: 534, - height: 590 + width: 500, + height: 692 }; }; function initVenmoWeb(_ref4) { @@ -15044,11 +15356,11 @@ window.spb = function(modules) { }, data), actions); } : null, onShippingAddressChange: onShippingAddressChange ? function(data, actions) { - if (!data.shipping_address) throw new Error("Must pass shipping_address in data to handle changes in shipping address."); + if (!data.shippingAddress) throw new Error("Must pass shippingAddress in data to handle changes in shipping address."); return onShippingAddressChange(Object(esm_extends.default)({}, data), actions); } : null, onShippingOptionsChange: onShippingOptionsChange ? function(data, actions) { - if (!data.selected_shipping_option) throw new Error("Must pass selected_shipping_option in data to handle changes in shipping options."); + if (!data.selectedShippingOption) throw new Error("Must pass selectedShippingOption in data to handle changes in shipping options."); return onShippingOptionsChange(Object(esm_extends.default)({}, data), actions); } : null, onClose: function() { @@ -15220,13 +15532,14 @@ window.spb = function(modules) { var payment = _ref7.payment; var platform = _ref7.props.platform; var fundingSource = payment.fundingSource, win = payment.win; + var venmoWebEnabled = _ref7.serviceData.eligibility.venmoWebEnabled; return !!(NATIVE_CHECKOUT_URI[fundingSource] && NATIVE_CHECKOUT_POPUP_URI[fundingSource] && NATIVE_CHECKOUT_FALLBACK_URI[fundingSource]) && !(!canUsePopupAppSwitch({ fundingSource: fundingSource, win: win }) && !canUseNativeQRCode({ fundingSource: fundingSource, win: win - })) && (platform && platform === sdk_constants_src.PLATFORM.DESKTOP ? !(!nativeEligibilityResults || !nativeEligibilityResults[fundingSource]) && nativeEligibilityResults[fundingSource].eligibility : !(win && !Object(lib.toProxyWindow)(win).getWindow())); + })) && (platform && platform === sdk_constants_src.PLATFORM.DESKTOP ? !!venmoWebEnabled || !(!nativeEligibilityResults || !nativeEligibilityResults[fundingSource]) && nativeEligibilityResults[fundingSource].eligibility : !(win && !Object(lib.toProxyWindow)(win).getWindow())); }, init: function(_ref2) { var props = _ref2.props, components = _ref2.components, config = _ref2.config, payment = _ref2.payment, serviceData = _ref2.serviceData, restart = _ref2.restart; @@ -15532,7 +15845,6 @@ window.spb = function(modules) { spinner: !0 }; var confirmOrder = __webpack_require__("./src/props/confirmOrder.js"); - var lib_logger = __webpack_require__("./src/lib/logger.js"); function isValidMerchantIDs(merchantIDs, payees) { if (merchantIDs.length !== payees.length) return !1; var merchantEmails = []; @@ -15634,7 +15946,8 @@ window.spb = function(modules) { serviceData: serviceData, config: config, components: components, - props: props + props: props, + experiments: experiments }); }, experiments: experiments @@ -15916,7 +16229,7 @@ window.spb = function(modules) { }, throwError: !1 }); - !cartBillingType || cartAmount || intent === sdk_constants_src.INTENT.TOKENIZE || window.xprops.createVaultSetupToken || triggerIntegrationError({ + !cartBillingType || cartAmount || intent === sdk_constants_src.INTENT.TOKENIZE || window.xprops.createVaultSetupToken || window.xprops.createSubscription || triggerIntegrationError({ error: "smart_button_validation_error_billing_without_purchase_intent_tokenize_not_passed", message: "Expected " + sdk_constants_src.SDK_QUERY_KEYS.INTENT + "=" + sdk_constants_src.INTENT.TOKENIZE + " for a billing-without-purchase transaction", featureFlags: featureFlags, @@ -16065,10 +16378,9 @@ window.spb = function(modules) { } } catch (err) {} function setupButton(_ref) { - var facilitatorAccessToken = _ref.facilitatorAccessToken, eligibility = _ref.eligibility, fundingEligibility = _ref.fundingEligibility, buyerGeoCountry = _ref.buyerCountry, sdkMeta = _ref.sdkMeta, buyerAccessToken = _ref.buyerAccessToken, wallet = _ref.wallet, cookies = _ref.cookies, serverCSPNonce = _ref.cspNonce, serverMerchantID = _ref.merchantID, firebaseConfig = _ref.firebaseConfig, content = _ref.content, personalization = _ref.personalization, _ref$correlationID = _ref.correlationID, buttonCorrelationID = void 0 === _ref$correlationID ? "" : _ref$correlationID, _ref$brandedDefault = _ref.brandedDefault, brandedDefault = void 0 === _ref$brandedDefault ? null : _ref$brandedDefault, _ref$experiments = _ref.experiments, experiments = void 0 === _ref$experiments ? {} : _ref$experiments, featureFlags = _ref.featureFlags, smartWalletOrderID = _ref.smartWalletOrderID, enableOrdersApprovalSmartWallet = _ref.enableOrdersApprovalSmartWallet, product = _ref.product, dumbledoreCurrentReleaseHash = _ref.dumbledoreCurrentReleaseHash, dumbledoreServiceWorker = _ref.dumbledoreServiceWorker; + var facilitatorAccessToken = _ref.facilitatorAccessToken, eligibility = _ref.eligibility, fundingEligibility = _ref.fundingEligibility, buyerGeoCountry = _ref.buyerCountry, sdkMeta = _ref.sdkMeta, buyerAccessToken = _ref.buyerAccessToken, wallet = _ref.wallet, cookies = _ref.cookies, serverCSPNonce = _ref.cspNonce, serverMerchantID = _ref.merchantID, firebaseConfig = _ref.firebaseConfig, content = _ref.content, personalization = _ref.personalization, _ref$correlationID = _ref.correlationID, buttonCorrelationID = void 0 === _ref$correlationID ? "" : _ref$correlationID, _ref$brandedDefault = _ref.brandedDefault, brandedDefault = void 0 === _ref$brandedDefault ? null : _ref$brandedDefault, _ref$experiments = _ref.experiments, experiments = void 0 === _ref$experiments ? {} : _ref$experiments, featureFlags = _ref.featureFlags, product = _ref.product, dumbledoreCurrentReleaseHash = _ref.dumbledoreCurrentReleaseHash, dumbledoreServiceWorker = _ref.dumbledoreServiceWorker; if (!window.paypal) throw new Error("PayPal SDK not loaded"); var clientID = window.xprops.clientID; - buyerAccessToken && smartWalletOrderID && Object(lib.setBuyerAccessToken)(buyerAccessToken); var serviceData = getServiceData({ eligibility: eligibility, facilitatorAccessToken: facilitatorAccessToken, @@ -16087,10 +16399,8 @@ window.spb = function(modules) { var props = getButtonProps({ facilitatorAccessToken: facilitatorAccessToken, brandedDefault: brandedDefault, - paymentSource: enableOrdersApprovalSmartWallet ? sdk_constants_src.FUNDING.PAYPAL : null, + paymentSource: null, featureFlags: featureFlags, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, - smartWalletOrderID: smartWalletOrderID, experiments: experiments }); var env = props.env, sessionID = props.sessionID, partnerAttributionID = props.partnerAttributionID, commit = props.commit, sdkCorrelationID = props.sdkCorrelationID, locale = props.locale, onShippingChange = props.onShippingChange, buttonSessionID = props.buttonSessionID, merchantDomain = props.merchantDomain, onInit = props.onInit, getPrerenderDetails = props.getPrerenderDetails, rememberFunding = props.rememberFunding, getQueriedEligibleFunding = props.getQueriedEligibleFunding, style = props.style, fundingSource = props.fundingSource, intent = props.intent, createBillingAgreement = props.createBillingAgreement, createSubscription = props.createSubscription, stickinessID = props.stickinessID; @@ -16139,7 +16449,7 @@ window.spb = function(modules) { })); } menu_menu = null; - getButtons().forEach((function(button) { + Object(src.querySelectorAll)("[ " + constants.DATA_ATTRIBUTES.FUNDING_SOURCE + " ]").forEach((function(button) { var menuToggle = function(button) { var menu = button.querySelector("[" + constants.DATA_ATTRIBUTES.MENU + "]"); if (menu) return menu; @@ -16197,8 +16507,6 @@ window.spb = function(modules) { brandedDefault: brandedDefault, paymentSource: paymentFundingSource, featureFlags: featureFlags, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, - smartWalletOrderID: smartWalletOrderID, experiments: experiments }); var payPromise = initiatePayment({ @@ -16275,7 +16583,8 @@ window.spb = function(modules) { serviceData: serviceData, config: config, components: components, - props: props + props: props, + experiments: experiments }); }, experiments: experiments @@ -16381,8 +16690,6 @@ window.spb = function(modules) { brandedDefault: brandedDefault, paymentSource: paymentFundingSource, featureFlags: featureFlags, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, - smartWalletOrderID: smartWalletOrderID, experiments: experiments }); var payPromise = initiatePayment({ @@ -16427,7 +16734,7 @@ window.spb = function(modules) { fundingEligibility: fundingEligibility }); var setupButtonLogsTask = function(_ref) { - var env = _ref.env, sessionID = _ref.sessionID, buttonSessionID = _ref.buttonSessionID, clientID = _ref.clientID, partnerAttributionID = _ref.partnerAttributionID, commit = _ref.commit, sdkCorrelationID = _ref.sdkCorrelationID, buttonCorrelationID = _ref.buttonCorrelationID, locale = _ref.locale, merchantID = _ref.merchantID, merchantDomain = _ref.merchantDomain, sdkVersion = _ref.sdkVersion, style = _ref.style, fundingSource = _ref.fundingSource, getQueriedEligibleFunding = _ref.getQueriedEligibleFunding, stickinessID = _ref.stickinessID, buyerCountry = _ref.buyerCountry, onShippingChange = _ref.onShippingChange, wallet = _ref.wallet, smartWalletOrderID = _ref.smartWalletOrderID, product = _ref.product; + var env = _ref.env, sessionID = _ref.sessionID, buttonSessionID = _ref.buttonSessionID, clientID = _ref.clientID, partnerAttributionID = _ref.partnerAttributionID, commit = _ref.commit, sdkCorrelationID = _ref.sdkCorrelationID, buttonCorrelationID = _ref.buttonCorrelationID, locale = _ref.locale, merchantID = _ref.merchantID, merchantDomain = _ref.merchantDomain, sdkVersion = _ref.sdkVersion, style = _ref.style, fundingSource = _ref.fundingSource, getQueriedEligibleFunding = _ref.getQueriedEligibleFunding, stickinessID = _ref.stickinessID, buyerCountry = _ref.buyerCountry, onShippingChange = _ref.onShippingChange, product = _ref.product; var logger = Object(lib.getLogger)(); Object(lib.setupLogger)({ env: env, @@ -16448,14 +16755,13 @@ window.spb = function(modules) { var _ref2; return (_ref2 = {})[sdk_constants_src.FPTI_KEY.CONTEXT_TYPE] = constants.FPTI_CONTEXT_TYPE.BUTTON_SESSION_ID, _ref2[sdk_constants_src.FPTI_KEY.CONTEXT_ID] = buttonSessionID, _ref2[sdk_constants_src.FPTI_KEY.BUTTON_SESSION_UID] = buttonSessionID, - _ref2[sdk_constants_src.FPTI_KEY.BUTTON_VERSION] = "5.0.151", _ref2[constants.FPTI_BUTTON_KEY.BUTTON_CORRELATION_ID] = buttonCorrelationID, + _ref2[sdk_constants_src.FPTI_KEY.BUTTON_VERSION] = "5.0.164", _ref2[constants.FPTI_BUTTON_KEY.BUTTON_CORRELATION_ID] = buttonCorrelationID, _ref2[sdk_constants_src.FPTI_KEY.STICKINESS_ID] = Object(lib.isAndroidChrome)() ? stickinessID : null, _ref2[sdk_constants_src.FPTI_KEY.PARTNER_ATTRIBUTION_ID] = partnerAttributionID, _ref2[sdk_constants_src.FPTI_KEY.USER_ACTION] = commit ? sdk_constants_src.FPTI_USER_ACTION.COMMIT : sdk_constants_src.FPTI_USER_ACTION.CONTINUE, _ref2[sdk_constants_src.FPTI_KEY.SELLER_ID] = merchantID[0], _ref2[sdk_constants_src.FPTI_KEY.MERCHANT_DOMAIN] = merchantDomain, _ref2[sdk_constants_src.FPTI_KEY.CHOSEN_FUNDING] = fundingSource, _ref2[sdk_constants_src.FPTI_KEY.PRODUCT] = product, - _ref2[sdk_constants_src.FPTI_KEY.TOKEN] = smartWalletOrderID, _ref2[sdk_constants_src.FPTI_KEY.TIMESTAMP] = Date.now().toString(), - _ref2; + _ref2[sdk_constants_src.FPTI_KEY.TIMESTAMP] = Date.now().toString(), _ref2; })); Object(src.isIEIntranet)() && logger.warn("button_child_intranet_mode"); return zalgo_promise_src.ZalgoPromise.hash({ @@ -16478,7 +16784,7 @@ window.spb = function(modules) { Object(lib.isIOSSafari)() ? nativeDevice = "ios_safari" : Object(lib.isAndroidChrome)() && (nativeDevice = "android_chrome"); var serverRenderVersion = (document.body && document.body.getAttribute("" + constants.DATA_ATTRIBUTES.RENDER_VERSION) || "unknown").replace(/[^a-zA-Z0-9]+/g, "_"); if (serverRenderVersion.split("_").join(".") !== sdkVersion) { - logger.warn("server_render_version_mismatch", { + logger.info("server_render_version_mismatch", { sdkVersion: sdkVersion, serverRenderVersion: serverRenderVersion }); @@ -16532,9 +16838,6 @@ window.spb = function(modules) { _tracking[constants.FPTI_BUTTON_KEY.BUTTON_TAGLINE_ENABLED] = tagline ? "1" : "0", _tracking[constants.FPTI_CUSTOM_KEY.SHIPPING_CALLBACK_PASSED] = onShippingChange ? "1" : "0", _tracking); - var fundingInstrumentId = null != wallet && null != (_wallet$paypal = wallet.paypal) && null != (_wallet$paypal = _wallet$paypal.instruments[0]) && _wallet$paypal.secondaryInstruments && wallet.paypal.instruments[0].instrumentID ? wallet.paypal.instruments[0].instrumentID + "," + wallet.paypal.instruments[0].secondaryInstruments[0].instrumentID : null != wallet && null != (_wallet$paypal2 = wallet.paypal) && null != (_wallet$paypal2 = _wallet$paypal2.instruments[0]) && _wallet$paypal2.instrumentID ? "" + wallet.paypal.instruments[0].instrumentID : void 0; - var _wallet$paypal, _wallet$paypal2; - fundingInstrumentId && (tracking["" + sdk_constants_src.FPTI_KEY.FI_ID] = fundingInstrumentId); logger.track(tracking); logger.flush(); })); @@ -16557,9 +16860,6 @@ window.spb = function(modules) { getQueriedEligibleFunding: getQueriedEligibleFunding, buyerCountry: buyerCountry, onShippingChange: onShippingChange, - wallet: wallet, - smartWalletOrderID: smartWalletOrderID, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, product: product }); var setupPaymentFlowsTask = function(_ref) { @@ -16968,7 +17268,8 @@ window.spb = function(modules) { BUTTON_SESSION_ID: "button_session_id", WALLET_SESSION_ID: "wallet_session_id", ORDER_ID: "EC-Token", - PAYMENT_ID: "Pay-ID" + PAYMENT_ID: "Pay-ID", + VAULT_SETUP_TOKEN: "vault_setup_token" }; var FPTI_STATE = { BUTTON: "smart_button", @@ -16991,6 +17292,7 @@ window.spb = function(modules) { CREATE_ORDER: "process_create_order", CONFIRM_ORDER: "process_confirm_order", RECEIVE_ORDER: "process_receive_order", + RECEIVE_VAULT_SETUP_TOKEN: "process_receive_vault_setup_token", CREATE_PAYMENT: "process_create_payment", CAPTURE_AUTHORIZATION: "process_capture_authorization", CHECKOUT_SHIPPING_CHANGE: "process_checkout_shipping_change", @@ -17831,7 +18133,8 @@ window.spb = function(modules) { return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_0__.ZalgoPromise.try((function() { return Object(_api__WEBPACK_IMPORTED_MODULE_3__.confirmOrderAPI)(orderID, payload, { facilitatorAccessToken: facilitatorAccessToken, - partnerAttributionID: partnerAttributionID + partnerAttributionID: partnerAttributionID, + experiments: {} }); })).catch((function(err) { Object(_lib__WEBPACK_IMPORTED_MODULE_5__.getLogger)().error("confirm_order_error", { @@ -17919,7 +18222,7 @@ window.spb = function(modules) { }; } function buildOrderActions(_ref2) { - var facilitatorAccessToken = _ref2.facilitatorAccessToken, intent = _ref2.intent, currency = _ref2.currency, merchantID = _ref2.merchantID, partnerAttributionID = _ref2.partnerAttributionID; + var facilitatorAccessToken = _ref2.facilitatorAccessToken, intent = _ref2.intent, currency = _ref2.currency, merchantID = _ref2.merchantID, partnerAttributionID = _ref2.partnerAttributionID, experiments = _ref2.experiments; return { create: function(data) { var order = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.default)({}, data); @@ -17948,7 +18251,8 @@ window.spb = function(modules) { return Object(_api__WEBPACK_IMPORTED_MODULE_5__.createOrderID)(order, { facilitatorAccessToken: facilitatorAccessToken, partnerAttributionID: partnerAttributionID, - forceRestAPI: !1 + forceRestAPI: !1, + experiments: experiments }); } }; @@ -17993,20 +18297,22 @@ window.spb = function(modules) { }; } function buildXCreateOrderActions(_ref4) { - var facilitatorAccessToken = _ref4.facilitatorAccessToken, intent = _ref4.intent, currency = _ref4.currency, merchantID = _ref4.merchantID, partnerAttributionID = _ref4.partnerAttributionID; + var facilitatorAccessToken = _ref4.facilitatorAccessToken, intent = _ref4.intent, currency = _ref4.currency, merchantID = _ref4.merchantID, partnerAttributionID = _ref4.partnerAttributionID, experiments = _ref4.experiments; var order = buildOrderActions({ facilitatorAccessToken: facilitatorAccessToken, intent: intent, currency: currency, merchantID: merchantID, - partnerAttributionID: partnerAttributionID + partnerAttributionID: partnerAttributionID, + experiments: experiments }); var payment = buildPaymentActions({ facilitatorAccessToken: facilitatorAccessToken, intent: intent, currency: currency, merchantID: merchantID, - partnerAttributionID: partnerAttributionID + partnerAttributionID: partnerAttributionID, + experiments: experiments }); return { order: order, @@ -18014,8 +18320,9 @@ window.spb = function(modules) { }; } function getCreateOrder(_ref5, _ref6) { - var createOrder = _ref5.createOrder, intent = _ref5.intent, currency = _ref5.currency, merchantID = _ref5.merchantID, partnerAttributionID = _ref5.partnerAttributionID; - var facilitatorAccessToken = _ref6.facilitatorAccessToken, createBillingAgreement = _ref6.createBillingAgreement, createSubscription = _ref6.createSubscription, enableOrdersApprovalSmartWallet = _ref6.enableOrdersApprovalSmartWallet, smartWalletOrderID = _ref6.smartWalletOrderID, createVaultSetupToken = _ref6.createVaultSetupToken, flow = _ref6.flow; + var createOrder = _ref5.createOrder, intent = _ref5.intent, currency = _ref5.currency, merchantID = _ref5.merchantID, partnerAttributionID = _ref5.partnerAttributionID, experiments = _ref5.experiments; + var facilitatorAccessToken = _ref6.facilitatorAccessToken, createBillingAgreement = _ref6.createBillingAgreement, createSubscription = _ref6.createSubscription, createVaultSetupToken = _ref6.createVaultSetupToken, flow = _ref6.flow; + var isVaultWithoutPurchase = "vault_without_purchase" === flow && createVaultSetupToken; var data = buildXCreateOrderData({ paymentSource: _ref5.paymentSource }); @@ -18024,16 +18331,16 @@ window.spb = function(modules) { intent: intent, currency: currency, merchantID: merchantID, - partnerAttributionID: partnerAttributionID + partnerAttributionID: partnerAttributionID, + experiments: experiments }); var integrationType = "server-side"; return Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.memoize)((function() { var queryOrderID = Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.getQueryParam)("orderID"); if (queryOrderID) return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__.ZalgoPromise.resolve(queryOrderID); - if (enableOrdersApprovalSmartWallet && smartWalletOrderID) return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__.ZalgoPromise.resolve(smartWalletOrderID); var startTime = Date.now(); return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__.ZalgoPromise.try((function() { - if ("vault_without_purchase" === flow && createVaultSetupToken) return createVaultSetupToken().then(_api_vault__WEBPACK_IMPORTED_MODULE_9__.vaultApprovalSessionIdToOrderId); + if (isVaultWithoutPurchase) return createVaultSetupToken().then(_api_vault__WEBPACK_IMPORTED_MODULE_9__.vaultApprovalSessionIdToOrderId); if (createBillingAgreement) return createBillingAgreement().then(_api__WEBPACK_IMPORTED_MODULE_5__.billingTokenToOrderID); if (createSubscription) return createSubscription().then(_api__WEBPACK_IMPORTED_MODULE_5__.subscriptionIdToCartId); if (createOrder) return createOrder(data, actions); @@ -18047,25 +18354,26 @@ window.spb = function(modules) { } ] }); })).catch((function(err) { - var _getLogger$error$trac; - Object(_lib__WEBPACK_IMPORTED_MODULE_7__.sendCountMetric)({ - name: "pp.app.paypal_sdk.buttons.create_order.error.count", - dimensions: { - errorName: "generic", - flow: flow, - intent: intent, - integrationType: integrationType - } - }); - Object(_lib__WEBPACK_IMPORTED_MODULE_7__.getLogger)().error("create_order_error", { - err: Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.stringifyErrorMessage)(err) - }).track(((_getLogger$error$trac = {})[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.STATE] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_STATE.BUTTON, - _getLogger$error$trac[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.ERROR_CODE] = "smart_buttons_create_order_error", - _getLogger$error$trac[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.ERROR_DESC] = Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.stringifyErrorMessage)(err), - _getLogger$error$trac)); + if (!isVaultWithoutPurchase) { + var _getLogger$error$trac; + Object(_lib__WEBPACK_IMPORTED_MODULE_7__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.create_order.error.count", + dimensions: { + errorName: "generic", + flow: flow, + intent: intent, + integrationType: integrationType + } + }); + Object(_lib__WEBPACK_IMPORTED_MODULE_7__.getLogger)().error("create_order_error", { + err: Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.stringifyErrorMessage)(err) + }).track(((_getLogger$error$trac = {})[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.STATE] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_STATE.BUTTON, + _getLogger$error$trac[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.ERROR_CODE] = "smart_buttons_create_order_error", + _getLogger$error$trac[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.ERROR_DESC] = Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.stringifyErrorMessage)(err), + _getLogger$error$trac)); + } throw err; })).then((function(orderID) { - var _getLogger$addPayload; if (!orderID || "string" != typeof orderID) { var _getLogger$track; Object(_lib__WEBPACK_IMPORTED_MODULE_7__.sendCountMetric)({ @@ -18100,35 +18408,38 @@ window.spb = function(modules) { _getLogger$track2)); throw new Error("Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead"); } - var duration = Date.now() - startTime; - Object(_lib__WEBPACK_IMPORTED_MODULE_7__.sendCountMetric)({ - name: "pp.app.paypal_sdk.buttons.create_order.count", - dimensions: { - flow: flow, - intent: intent, - integrationType: integrationType - } - }); - Object(_lib__WEBPACK_IMPORTED_MODULE_7__.getLogger)().addPayloadBuilder((function() { - return { - token: orderID - }; - })).addTrackingBuilder((function() { - var _ref7; - return (_ref7 = {})[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_TYPE] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_CONTEXT_TYPE.ORDER_ID, - _ref7[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_ID] = orderID, - _ref7[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TOKEN] = orderID, - _ref7; - })).track((_getLogger$addPayload = {}, _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.STATE] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_STATE.BUTTON, - _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TRANSITION] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_TRANSITION.RECEIVE_ORDER, - _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.EVENT_NAME] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_TRANSITION.RECEIVE_ORDER, - _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_TYPE] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_CONTEXT_TYPE.ORDER_ID, - _getLogger$addPayload[_constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_BUTTON_KEY.BUTTON_WIDTH] = window.innerWidth, - _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_ID] = orderID, - _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TOKEN] = orderID, - _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.RESPONSE_DURATION] = duration.toString(), - _getLogger$addPayload.client_time = Object(_lib__WEBPACK_IMPORTED_MODULE_7__.getClientsideTimestamp)(), - _getLogger$addPayload)).flush(); + if (!isVaultWithoutPurchase) { + var _getLogger$addPayload; + var duration = Date.now() - startTime; + Object(_lib__WEBPACK_IMPORTED_MODULE_7__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.create_order.count", + dimensions: { + flow: flow, + intent: intent, + integrationType: integrationType + } + }); + Object(_lib__WEBPACK_IMPORTED_MODULE_7__.getLogger)().addPayloadBuilder((function() { + return { + token: orderID + }; + })).addTrackingBuilder((function() { + var _ref7; + return (_ref7 = {})[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_TYPE] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_CONTEXT_TYPE.ORDER_ID, + _ref7[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_ID] = orderID, + _ref7[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TOKEN] = orderID, + _ref7; + })).track((_getLogger$addPayload = {}, _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.STATE] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_STATE.BUTTON, + _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TRANSITION] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_TRANSITION.RECEIVE_ORDER, + _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.EVENT_NAME] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_TRANSITION.RECEIVE_ORDER, + _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_TYPE] = _constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_CONTEXT_TYPE.ORDER_ID, + _getLogger$addPayload[_constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_BUTTON_KEY.BUTTON_WIDTH] = window.innerWidth, + _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_ID] = orderID, + _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TOKEN] = orderID, + _getLogger$addPayload[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.RESPONSE_DURATION] = duration.toString(), + _getLogger$addPayload.client_time = Object(_lib__WEBPACK_IMPORTED_MODULE_7__.getClientsideTimestamp)(), + _getLogger$addPayload)).flush(); + } return orderID; })); })); @@ -18212,7 +18523,9 @@ window.spb = function(modules) { })); var _krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./node_modules/@krakenjs/belter/src/index.js"); __webpack_require__("./node_modules/@krakenjs/zalgo-promise/src/index.js"); - __webpack_require__("./node_modules/@paypal/sdk-constants/src/index.js"); + var _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./node_modules/@paypal/sdk-constants/src/index.js"); + var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/constants.js"); + var _lib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("./src/lib/index.js"); function buildXCreateVaultSetupTokenData(_ref) { return { paymentSource: _ref.paymentSource @@ -18223,11 +18536,64 @@ window.spb = function(modules) { var data = buildXCreateVaultSetupTokenData({ paymentSource: _ref2.paymentSource }); + var startTime = Date.now(); return Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_0__.memoize)((function() { if (!createVaultSetupToken) throw new Error("createVaultSetupToken undefined"); return createVaultSetupToken(data).then((function(vaultSetupToken) { - if (!vaultSetupToken || "string" != typeof vaultSetupToken) throw new Error("Expected a vault setup token to be returned from createVaultSetupToken"); + var _getLogger$addTrackin; + if (!vaultSetupToken || "string" != typeof vaultSetupToken) { + var _getLogger$error$trac; + var errString = "Expected a vault setup token to be returned from createVaultSetupToken"; + Object(_lib__WEBPACK_IMPORTED_MODULE_4__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.create_vault_setup_token.count", + event: "error", + dimensions: { + errorName: "no_setup_token" + } + }); + Object(_lib__WEBPACK_IMPORTED_MODULE_4__.getLogger)().error("create_vault_setup_token", { + err: errString + }).track(((_getLogger$error$trac = {})[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.STATE] = _constants__WEBPACK_IMPORTED_MODULE_3__.FPTI_STATE.BUTTON, + _getLogger$error$trac[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.ERROR_CODE] = "smart_buttons_create_vault_setup_token", + _getLogger$error$trac[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.ERROR_DESC] = errString, + _getLogger$error$trac)); + throw new Error(errString); + } + Object(_lib__WEBPACK_IMPORTED_MODULE_4__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.create_vault_setup_token.count", + event: "success", + dimensions: { + errorName: "no_vault_setup_token" + } + }); + Object(_lib__WEBPACK_IMPORTED_MODULE_4__.getLogger)().addTrackingBuilder((function() { + var _ref3; + return (_ref3 = {})[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.CONTEXT_TYPE] = _constants__WEBPACK_IMPORTED_MODULE_3__.FPTI_CONTEXT_TYPE.VAULT_SETUP_TOKEN, + _ref3[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.CONTEXT_ID] = vaultSetupToken, + _ref3; + })).track(((_getLogger$addTrackin = {})[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.STATE] = _constants__WEBPACK_IMPORTED_MODULE_3__.FPTI_STATE.BUTTON, + _getLogger$addTrackin[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.TRANSITION] = _constants__WEBPACK_IMPORTED_MODULE_3__.FPTI_TRANSITION.RECEIVE_VAULT_SETUP_TOKEN, + _getLogger$addTrackin[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.EVENT_NAME] = _constants__WEBPACK_IMPORTED_MODULE_3__.FPTI_TRANSITION.RECEIVE_VAULT_SETUP_TOKEN, + _getLogger$addTrackin[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.RESPONSE_DURATION] = (Date.now() - startTime).toString(), + _getLogger$addTrackin.client_time = Object(_lib__WEBPACK_IMPORTED_MODULE_4__.getClientsideTimestamp)(), + _getLogger$addTrackin)); return vaultSetupToken; + })).catch((function(err) { + var _getLogger$error$trac2; + Object(_lib__WEBPACK_IMPORTED_MODULE_4__.sendCountMetric)({ + name: "pp.app.paypal_sdk.buttons.create_vault_setup_token.count", + event: "error", + dimensions: { + errorName: "generic" + } + }); + Object(_lib__WEBPACK_IMPORTED_MODULE_4__.getLogger)().error("create_vault_setup_token_error", { + err: Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_0__.stringifyErrorMessage)(err) + }).track((_getLogger$error$trac2 = {}, _getLogger$error$trac2[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.STATE] = _constants__WEBPACK_IMPORTED_MODULE_3__.FPTI_STATE.BUTTON, + _getLogger$error$trac2[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.ERROR_CODE] = "smart_buttons_create_vault_setup_token_error", + _getLogger$error$trac2[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.ERROR_DESC] = Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_0__.stringifyErrorMessage)(err), + _getLogger$error$trac2)).flush(); + throw err; })); })); }; @@ -18374,6 +18740,15 @@ window.spb = function(modules) { __webpack_require__.d(__webpack_exports__, "buildXOnShippingChangeData", (function() { return _onShippingChange__WEBPACK_IMPORTED_MODULE_10__.buildXOnShippingChangeData; })); + __webpack_require__.d(__webpack_exports__, "sanitizePatch", (function() { + return _onShippingChange__WEBPACK_IMPORTED_MODULE_10__.sanitizePatch; + })); + __webpack_require__.d(__webpack_exports__, "isWeasley", (function() { + return _onShippingChange__WEBPACK_IMPORTED_MODULE_10__.isWeasley; + })); + __webpack_require__.d(__webpack_exports__, "logInvalidShippingChangePatches", (function() { + return _onShippingChange__WEBPACK_IMPORTED_MODULE_10__.logInvalidShippingChangePatches; + })); __webpack_require__.d(__webpack_exports__, "buildXShippingChangeActions", (function() { return _onShippingChange__WEBPACK_IMPORTED_MODULE_10__.buildXShippingChangeActions; })); @@ -18435,7 +18810,7 @@ window.spb = function(modules) { })); __webpack_require__("./src/props/getQueriedEligibleFunding.js"); var _paymentRequest__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__("./src/props/paymentRequest.js"); - for (var __WEBPACK_IMPORT_KEY__ in _paymentRequest__WEBPACK_IMPORTED_MODULE_20__) [ "default", "TYPES", "getProps", "buildXCreateOrderData", "buildOrderActions", "buildPaymentActions", "buildXCreateOrderActions", "getCreateOrder", "getConfirmOrder", "buildXCreateBillingAgreementData", "buildXCreateBillingAgreementActions", "getCreateBillingAgreement", "buildXCreateSubscriptionData", "buildXCreateSubscriptionActions", "getCreateSubscription", "buildXCreateVaultSetupTokenData", "getCreateVaultSetupToken", "getOnApproveOrder", "getOnApproveBilling", "getOnApproveTokenize", "getOnApproveSubscription", "getOnApproveVaultWithoutPurchase", "getOnApprove", "getOnComplete", "buildXOnInitActions", "getOnInit", "buildXOnCancelData", "buildXOnCancelActions", "getOnCancel", "ON_SHIPPING_CHANGE_PATHS", "SHIPPING_ADDRESS_ERROR_MESSAGES", "SHIPPING_OPTIONS_ERROR_MESSAGES", "GENERIC_REJECT_ADDRESS_MESSAGE", "buildXOnShippingChangeData", "buildXShippingChangeActions", "getOnShippingChange", "buildXOnShippingAddressChangeData", "buildXOnShippingAddressChangeActions", "getOnShippingAddressChange", "buildXOnShippingOptionsChangeData", "buildXOnShippingOptionsChangeActions", "getOnShippingOptionsChange", "CLICK_VALID", "buildXOnClickData", "buildXOnClickActions", "getOnClick", "getOnError", "POPUP_BRIDGE_OPTYPE", "getRememberFunding", "getGetPageUrl", "getOnAuth" ].indexOf(__WEBPACK_IMPORT_KEY__) < 0 && function(key) { + for (var __WEBPACK_IMPORT_KEY__ in _paymentRequest__WEBPACK_IMPORTED_MODULE_20__) [ "default", "TYPES", "getProps", "buildXCreateOrderData", "buildOrderActions", "buildPaymentActions", "buildXCreateOrderActions", "getCreateOrder", "getConfirmOrder", "buildXCreateBillingAgreementData", "buildXCreateBillingAgreementActions", "getCreateBillingAgreement", "buildXCreateSubscriptionData", "buildXCreateSubscriptionActions", "getCreateSubscription", "buildXCreateVaultSetupTokenData", "getCreateVaultSetupToken", "getOnApproveOrder", "getOnApproveBilling", "getOnApproveTokenize", "getOnApproveSubscription", "getOnApproveVaultWithoutPurchase", "getOnApprove", "getOnComplete", "buildXOnInitActions", "getOnInit", "buildXOnCancelData", "buildXOnCancelActions", "getOnCancel", "ON_SHIPPING_CHANGE_PATHS", "SHIPPING_ADDRESS_ERROR_MESSAGES", "SHIPPING_OPTIONS_ERROR_MESSAGES", "GENERIC_REJECT_ADDRESS_MESSAGE", "buildXOnShippingChangeData", "sanitizePatch", "isWeasley", "logInvalidShippingChangePatches", "buildXShippingChangeActions", "getOnShippingChange", "buildXOnShippingAddressChangeData", "buildXOnShippingAddressChangeActions", "getOnShippingAddressChange", "buildXOnShippingOptionsChangeData", "buildXOnShippingOptionsChangeActions", "getOnShippingOptionsChange", "CLICK_VALID", "buildXOnClickData", "buildXOnClickActions", "getOnClick", "getOnError", "POPUP_BRIDGE_OPTYPE", "getRememberFunding", "getGetPageUrl", "getOnAuth" ].indexOf(__WEBPACK_IMPORT_KEY__) < 0 && function(key) { __webpack_require__.d(__webpack_exports__, key, (function() { return _paymentRequest__WEBPACK_IMPORTED_MODULE_20__[key]; })); @@ -18470,19 +18845,7 @@ window.spb = function(modules) { var _constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("./src/constants.js"); var _lib__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__("./src/lib/index.js"); var _config__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__("./src/config.js"); - var redirect = function(url) { - if (!url) throw new Error("Expected redirect url"); - if (-1 === url.indexOf("://")) { - Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().warn("redir_url_non_scheme", { - url: url - }).flush(); - throw new Error("Invalid redirect url: " + url + " - must be fully qualified url"); - } - url.match(/^https?:\/\//) || Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().warn("redir_url_non_http", { - url: url - }).flush(); - return Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.redirect)(url, window.top); - }; + var _utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__("./src/props/utils.js"); var handleProcessorError = function(err, restart, onError) { if (Object(_api__WEBPACK_IMPORTED_MODULE_4__.isUnprocessableEntityError)(err)) { err && err.response && (err.message = JSON.stringify(err.response) || err.message); @@ -18517,8 +18880,7 @@ window.spb = function(modules) { }).flush(); return Object(_api__WEBPACK_IMPORTED_MODULE_4__.getSupplementalOrderInfo)(orderID).then((function(supplementalData) { billingToken = billingToken || supplementalData && supplementalData.checkoutSession && supplementalData.checkoutSession.cart && supplementalData.checkoutSession.cart.billingToken; - paymentID = paymentID || supplementalData && supplementalData.checkoutSession && supplementalData.checkoutSession.cart && supplementalData.checkoutSession.cart.paymentId; - experiments.btSdkOrdersV2Migration && !paymentID && (paymentID = orderID.replace(/EC-/, "")); + (paymentID = paymentID || supplementalData && supplementalData.checkoutSession && supplementalData.checkoutSession.cart && supplementalData.checkoutSession.cart.paymentId) || billingToken || (paymentID = orderID.replace(/EC-/, "")); var data = { orderID: orderID, payerID: payerID, @@ -18531,35 +18893,66 @@ window.spb = function(modules) { var actions = function(_ref3) { var intent = _ref3.intent, orderID = _ref3.orderID, paymentID = _ref3.paymentID, payerID = _ref3.payerID, restart = _ref3.restart, facilitatorAccessToken = _ref3.facilitatorAccessToken, buyerAccessToken = _ref3.buyerAccessToken, partnerAttributionID = _ref3.partnerAttributionID, forceRestAPI = _ref3.forceRestAPI, onError = _ref3.onError; var order = function(_ref) { - var intent = _ref.intent, orderID = _ref.orderID, restart = _ref.restart, facilitatorAccessToken = _ref.facilitatorAccessToken, buyerAccessToken = _ref.buyerAccessToken, partnerAttributionID = _ref.partnerAttributionID, forceRestAPI = _ref.forceRestAPI, onError = _ref.onError; + var intent = _ref.intent, orderID = _ref.orderID, restart = _ref.restart, facilitatorAccessToken = _ref.facilitatorAccessToken, buyerAccessToken = _ref.buyerAccessToken, partnerAttributionID = _ref.partnerAttributionID, forceRestAPI = _ref.forceRestAPI, onError = _ref.onError, experiments = _ref.experiments, paymentSource = _ref.paymentSource; var get = Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.memoize)((function() { - return Object(_api__WEBPACK_IMPORTED_MODULE_4__.getOrder)(orderID, { + return Object(_utils__WEBPACK_IMPORTED_MODULE_8__.checkUlsatNotRequired)(paymentSource, buyerAccessToken) ? Object(_api__WEBPACK_IMPORTED_MODULE_4__.getOrder)(orderID, { facilitatorAccessToken: facilitatorAccessToken, buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, - forceRestAPI: forceRestAPI - }); + forceRestAPI: forceRestAPI, + experiments: experiments + }) : Object(_api__WEBPACK_IMPORTED_MODULE_4__.upgradeFacilitatorAccessTokenWithIgnoreCache)(facilitatorAccessToken, buyerAccessToken, orderID).then((function(upgradedFacilitatorAccessToken) { + return Object(_api__WEBPACK_IMPORTED_MODULE_4__.getOrder)(orderID, { + facilitatorAccessToken: upgradedFacilitatorAccessToken, + buyerAccessToken: buyerAccessToken, + partnerAttributionID: partnerAttributionID, + forceRestAPI: forceRestAPI, + experiments: experiments + }); + })); })); var capture = Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.memoize)((function() { if (intent !== _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.INTENT.CAPTURE) throw new Error("Use " + _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.SDK_QUERY_KEYS.INTENT + "=" + _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.INTENT.CAPTURE + " to use client-side capture"); - return Object(_api__WEBPACK_IMPORTED_MODULE_4__.captureOrder)(orderID, { + return Object(_utils__WEBPACK_IMPORTED_MODULE_8__.checkUlsatNotRequired)(paymentSource, buyerAccessToken) ? Object(_api__WEBPACK_IMPORTED_MODULE_4__.captureOrder)(orderID, { facilitatorAccessToken: facilitatorAccessToken, buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, - forceRestAPI: forceRestAPI + forceRestAPI: forceRestAPI, + experiments: experiments }).finally(get.reset).finally(capture.reset).catch((function(err) { return handleProcessorError(err, restart, onError); + })) : Object(_api__WEBPACK_IMPORTED_MODULE_4__.upgradeFacilitatorAccessTokenWithIgnoreCache)(facilitatorAccessToken, buyerAccessToken, orderID).then((function(upgradedFacilitatorAccessToken) { + return Object(_api__WEBPACK_IMPORTED_MODULE_4__.captureOrder)(orderID, { + facilitatorAccessToken: upgradedFacilitatorAccessToken, + buyerAccessToken: buyerAccessToken, + partnerAttributionID: partnerAttributionID, + forceRestAPI: forceRestAPI, + experiments: experiments + }).finally(get.reset).finally(capture.reset).catch((function(err) { + return handleProcessorError(err, restart, onError); + })); })); })); var authorize = Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_2__.memoize)((function() { if (intent !== _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.INTENT.AUTHORIZE) throw new Error("Use " + _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.SDK_QUERY_KEYS.INTENT + "=" + _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.INTENT.AUTHORIZE + " to use client-side authorize"); - return Object(_api__WEBPACK_IMPORTED_MODULE_4__.authorizeOrder)(orderID, { + return Object(_utils__WEBPACK_IMPORTED_MODULE_8__.checkUlsatNotRequired)(paymentSource, buyerAccessToken) ? Object(_api__WEBPACK_IMPORTED_MODULE_4__.authorizeOrder)(orderID, { facilitatorAccessToken: facilitatorAccessToken, buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, - forceRestAPI: forceRestAPI + forceRestAPI: forceRestAPI, + experiments: experiments }).finally(get.reset).finally(authorize.reset).catch((function(err) { return handleProcessorError(err, restart, onError); + })) : Object(_api__WEBPACK_IMPORTED_MODULE_4__.upgradeFacilitatorAccessTokenWithIgnoreCache)(facilitatorAccessToken, buyerAccessToken, orderID).then((function(upgradedFacilitatorAccessToken) { + return Object(_api__WEBPACK_IMPORTED_MODULE_4__.authorizeOrder)(orderID, { + facilitatorAccessToken: upgradedFacilitatorAccessToken, + buyerAccessToken: buyerAccessToken, + partnerAttributionID: partnerAttributionID, + forceRestAPI: forceRestAPI, + experiments: experiments + }).finally(get.reset).finally(authorize.reset).catch((function(err) { + return handleProcessorError(err, restart, onError); + })); })); })); return { @@ -18567,13 +18960,24 @@ window.spb = function(modules) { authorize: authorize, patch: function(data) { void 0 === data && (data = {}); - return Object(_api__WEBPACK_IMPORTED_MODULE_4__.patchOrder)(orderID, data, { + return Object(_utils__WEBPACK_IMPORTED_MODULE_8__.checkUlsatNotRequired)(paymentSource, buyerAccessToken) ? Object(_api__WEBPACK_IMPORTED_MODULE_4__.patchOrder)(orderID, data, { facilitatorAccessToken: facilitatorAccessToken, buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, - forceRestAPI: forceRestAPI + forceRestAPI: forceRestAPI, + experiments: experiments }).catch((function() { throw new Error("Order could not be patched"); + })) : Object(_api__WEBPACK_IMPORTED_MODULE_4__.upgradeFacilitatorAccessTokenWithIgnoreCache)(facilitatorAccessToken, buyerAccessToken, orderID).then((function(upgradedFacilitatorAccessToken) { + return Object(_api__WEBPACK_IMPORTED_MODULE_4__.patchOrder)(orderID, data, { + facilitatorAccessToken: upgradedFacilitatorAccessToken, + buyerAccessToken: buyerAccessToken, + partnerAttributionID: partnerAttributionID, + forceRestAPI: forceRestAPI, + experiments: experiments + }).catch((function() { + throw new Error("Order could not be patched"); + })); })); }, get: get @@ -18588,7 +18992,9 @@ window.spb = function(modules) { buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, forceRestAPI: forceRestAPI, - onError: onError + onError: onError, + experiments: _ref3.experiments, + paymentSource: _ref3.paymentSource }); var payment = function(_ref2) { var intent = _ref2.intent, paymentID = _ref2.paymentID, payerID = _ref2.payerID, restart = _ref2.restart, facilitatorAccessToken = _ref2.facilitatorAccessToken, buyerAccessToken = _ref2.buyerAccessToken, partnerAttributionID = _ref2.partnerAttributionID, onError = _ref2.onError; @@ -18642,7 +19048,7 @@ window.spb = function(modules) { order: order, payment: _config__WEBPACK_IMPORTED_MODULE_7__.ENABLE_PAYMENT_API ? payment : null, restart: restart, - redirect: redirect + redirect: _utils__WEBPACK_IMPORTED_MODULE_8__.redirect }; }({ orderID: orderID, @@ -18653,8 +19059,10 @@ window.spb = function(modules) { facilitatorAccessToken: facilitatorAccessToken, buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, + onError: onError, forceRestAPI: forceRestAPI, - onError: onError + experiments: experiments, + paymentSource: paymentSource }); beforeOnApprove(); return onApprove(data, actions).catch((function(err) { @@ -18695,7 +19103,7 @@ window.spb = function(modules) { }; var actions = { restart: restart, - redirect: redirect + redirect: _utils__WEBPACK_IMPORTED_MODULE_8__.redirect }; beforeOnApprove(); return onApprove(data, actions).catch((function(err) { @@ -18729,7 +19137,7 @@ window.spb = function(modules) { }; var actions = { restart: restart, - redirect: redirect + redirect: _utils__WEBPACK_IMPORTED_MODULE_8__.redirect }; beforeOnApprove(); return onApprove(data, actions).catch((function(err) { @@ -18784,7 +19192,7 @@ window.spb = function(modules) { })) }, restart: restart, - redirect: redirect + redirect: _utils__WEBPACK_IMPORTED_MODULE_8__.redirect }; }({ restart: restart, @@ -18824,7 +19232,16 @@ window.spb = function(modules) { vaultSetupToken: vaultSetupToken }; beforeOnApprove(); - return onApprove(data).catch((function(err) { + return onApprove(data).then((function(res) { + var _getLogger$track; + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().track((_getLogger$track = {}, + _getLogger$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TRANSITION] = _constants__WEBPACK_IMPORTED_MODULE_5__.FPTI_TRANSITION.CHECKOUT_APPROVE, + _getLogger$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_TYPE] = _constants__WEBPACK_IMPORTED_MODULE_5__.FPTI_CONTEXT_TYPE.VAULT_SETUP_TOKEN, + _getLogger$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TOKEN] = vaultSetupToken, + _getLogger$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_ID] = vaultSetupToken, + _getLogger$track)).flush(); + return res; + })).catch((function(err) { return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__.ZalgoPromise.try((function() { return onError(err); })).then((function() { @@ -18903,29 +19320,16 @@ window.spb = function(modules) { return getOnAuth; })); var _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./node_modules/@krakenjs/zalgo-promise/src/index.js"); - var _krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./node_modules/@krakenjs/belter/src/index.js"); - var _api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./src/api/index.js"); - var _lib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/lib/index.js"); - function getOnAuth(_ref) { - var facilitatorAccessToken = _ref.facilitatorAccessToken, createOrder = _ref.createOrder, createSubscription = _ref.createSubscription, featureFlags = _ref.featureFlags; - return function(_ref2) { - var accessToken = _ref2.accessToken; - Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().info("spb_onauth_access_token_" + (accessToken ? "present" : "not_present")); + var _lib__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/lib/index.js"); + function getOnAuth() { + return function(_ref) { + var accessToken = _ref.accessToken; + Object(_lib__WEBPACK_IMPORTED_MODULE_1__.getLogger)().info("spb_onauth_access_token_" + (accessToken ? "present" : "not_present")); return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_0__.ZalgoPromise.try((function() { - if (accessToken) return featureFlags.isLsatUpgradable ? createOrder().then((function(orderID) { - return createSubscription ? accessToken : Object(_api__WEBPACK_IMPORTED_MODULE_2__.upgradeFacilitatorAccessToken)(facilitatorAccessToken, { - buyerAccessToken: accessToken, - orderID: orderID - }); - })).then((function() { - Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().info("upgrade_lsat_success"); + if (accessToken) { + Object(_lib__WEBPACK_IMPORTED_MODULE_1__.setBuyerAccessToken)(accessToken); return accessToken; - })).catch((function(err) { - Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().warn("upgrade_lsat_failure", { - error: Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__.stringifyError)(err) - }); - return accessToken; - })) : accessToken; + } })); }; } @@ -18947,6 +19351,7 @@ window.spb = function(modules) { var _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./node_modules/@paypal/sdk-constants/src/index.js"); var _lib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/lib/index.js"); var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("./src/constants.js"); + var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("./src/props/utils.js"); function buildXOnCancelData(_ref) { return { orderID: _ref.orderID @@ -18954,19 +19359,7 @@ window.spb = function(modules) { } function buildXOnCancelActions() { return { - redirect: function(url) { - if (!url) throw new Error("Expected redirect url"); - if (-1 === url.indexOf("://")) { - Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().warn("redir_url_non_scheme", { - url: url - }).flush(); - throw new Error("Invalid redirect url: " + url + " - must be fully qualified url"); - } - url.match(/^https?:\/\//) || Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().warn("redir_url_non_http", { - url: url - }).flush(); - return Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_0__.redirect)(url, window.top); - } + redirect: _utils__WEBPACK_IMPORTED_MODULE_5__.redirect }; } function getOnCancel(_ref2, _ref3) { @@ -19055,21 +19448,9 @@ window.spb = function(modules) { var _lib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/lib/index.js"); var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("./src/constants.js"); var _api__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("./src/api/index.js"); - var redirect = function(url) { - if (!url) throw new Error("Expected redirect url"); - if (-1 === url.indexOf("://")) { - Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().warn("redir_url_non_scheme", { - url: url - }).flush(); - throw new Error("Invalid redirect url: " + url + " - must be fully qualified url"); - } - url.match(/^https?:\/\//) || Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().warn("redir_url_non_http", { - url: url - }).flush(); - return Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__.redirect)(url, window.top); - }; + var _utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__("./src/props/utils.js"); function getOnComplete(_ref2) { - var intent = _ref2.intent, onComplete = _ref2.onComplete, partnerAttributionID = _ref2.partnerAttributionID, onError = _ref2.onError, facilitatorAccessToken = _ref2.facilitatorAccessToken, createOrder = _ref2.createOrder, featureFlags = _ref2.featureFlags; + var intent = _ref2.intent, onComplete = _ref2.onComplete, partnerAttributionID = _ref2.partnerAttributionID, onError = _ref2.onError, facilitatorAccessToken = _ref2.facilitatorAccessToken, createOrder = _ref2.createOrder, featureFlags = _ref2.featureFlags, experiments = _ref2.experiments; return onComplete ? Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__.memoize)((function(_ref3) { var buyerAccessToken = _ref3.buyerAccessToken, _ref3$forceRestAPI = _ref3.forceRestAPI, forceRestAPI = void 0 === _ref3$forceRestAPI ? featureFlags.isLsatUpgradable : _ref3$forceRestAPI; return createOrder().then((function(orderID) { @@ -19082,28 +19463,30 @@ window.spb = function(modules) { _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.CONTEXT_ID] = orderID, _getLogger$info$track)).flush(); var actions = function(_ref) { - var orderID = _ref.orderID, facilitatorAccessToken = _ref.facilitatorAccessToken, buyerAccessToken = _ref.buyerAccessToken, partnerAttributionID = _ref.partnerAttributionID, forceRestAPI = _ref.forceRestAPI; + var orderID = _ref.orderID, facilitatorAccessToken = _ref.facilitatorAccessToken, buyerAccessToken = _ref.buyerAccessToken, partnerAttributionID = _ref.partnerAttributionID, forceRestAPI = _ref.forceRestAPI, experiments = _ref.experiments; var get = Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__.memoize)((function() { return Object(_api__WEBPACK_IMPORTED_MODULE_5__.getOrder)(orderID, { facilitatorAccessToken: facilitatorAccessToken, buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, - forceRestAPI: forceRestAPI + forceRestAPI: forceRestAPI, + experiments: experiments }).finally(get.reset); })); return { order: { get: get }, - redirect: redirect + redirect: _utils__WEBPACK_IMPORTED_MODULE_6__.redirect }; }({ orderID: orderID, facilitatorAccessToken: facilitatorAccessToken, buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, + onError: onError, forceRestAPI: forceRestAPI, - onError: onError + experiments: experiments }); return onComplete({ orderID: orderID, @@ -19199,10 +19582,10 @@ window.spb = function(modules) { var _constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__("./src/constants.js"); var _lib__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__("./src/lib/index.js"); var _onShippingChange__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__("./src/props/onShippingChange.js"); - var _utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__("./src/props/utils.js"); - var _excluded = [ "amount", "buyerAccessToken", "event", "forceRestAPI", "shipping_address" ]; + var _shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__("./src/props/shippingChangeUtils.js"); + var _excluded = [ "amount", "buyerAccessToken", "event", "forceRestAPI", "shippingAddress" ]; function buildXOnShippingAddressChangeData(data) { - var shippingAddress = data.shipping_address, rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_2__.default)(data, _excluded); + var shippingAddress = data.shippingAddress, rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_2__.default)(data, _excluded); return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.default)({ errors: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.SHIPPING_ADDRESS_ERROR_MESSAGES, shippingAddress: shippingAddress @@ -19210,143 +19593,78 @@ window.spb = function(modules) { } function buildXOnShippingAddressChangeActions(_ref) { var _data$amount; - var clientID = _ref.clientID, data = _ref.data, passedActions = _ref.actions, orderID = _ref.orderID; + var data = _ref.data, passedActions = _ref.actions, orderID = _ref.orderID; var patchQueries = {}; - var newAmount; - var breakdown = (null == (_data$amount = data.amount) ? void 0 : _data$amount.breakdown) || {}; + var breakdown = null != (_data$amount = data.amount) && _data$amount.breakdown ? Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.breakdownKeyChanges)(data.amount.breakdown) : {}; if (0 === Object.keys(breakdown).length) throw new Error("Must pass amount with breakdown into data attribute for onShippingAddressChange callback."); - var actions = { + return { reject: passedActions.reject ? function(message) { return -1 === Object.values(_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.SHIPPING_ADDRESS_ERROR_MESSAGES).indexOf(message) ? passedActions.reject(_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.GENERIC_REJECT_ADDRESS_MESSAGE) : passedActions.reject(message); } : function() { throw new Error("Missing reject action callback"); }, - updateTax: function(_ref2) { - var _data$amount2; - var tax = _ref2.tax; - breakdown = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.buildBreakdown)({ - breakdown: breakdown, - updatedAmounts: { - tax_total: tax - } - }); - newAmount = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.calculateTotalFromShippingBreakdownAmounts)({ - breakdown: breakdown, - updatedAmounts: { - tax_total: tax - } - }); - patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT] = { - op: "replace", - path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT, - value: { - value: "" + newAmount, - currency_code: null == data || null == (_data$amount2 = data.amount) ? void 0 : _data$amount2.currency_code, - breakdown: breakdown - } - }; - return actions; - }, - updateShippingOptions: function(_ref3) { - var _selectedShippingOpti, _data$amount3; - var options = _ref3.options; - var selectedShippingOption = options.filter((function(option) { + buildOrderPatchPayload: function(_temp) { + var _selectedShippingOpti, _selectedShippingOpti2; + var _ref2 = void 0 === _temp ? {} : _temp, discount = _ref2.discount, handling = _ref2.handling, insurance = _ref2.insurance, itemTotal = _ref2.itemTotal, shippingOptions = _ref2.shippingOptions, shippingDiscount = _ref2.shippingDiscount, taxTotal = _ref2.taxTotal; + var selectedShippingOption = null == shippingOptions ? void 0 : shippingOptions.find((function(option) { return !0 === option.selected; })); - var selectedShippingOptionAmount = selectedShippingOption && selectedShippingOption.length > 0 ? null == (_selectedShippingOpti = selectedShippingOption[0]) || null == (_selectedShippingOpti = _selectedShippingOpti.amount) ? void 0 : _selectedShippingOpti.value : "0.00"; - breakdown = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.buildBreakdown)({ - breakdown: breakdown, - updatedAmounts: { - shipping: selectedShippingOptionAmount - } - }); - newAmount = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.calculateTotalFromShippingBreakdownAmounts)({ - breakdown: breakdown, - updatedAmounts: { - shipping: selectedShippingOptionAmount - } - }); - patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT] = { - op: "replace", - path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT, - value: { - value: "" + newAmount, - currency_code: null == data || null == (_data$amount3 = data.amount) ? void 0 : _data$amount3.currency_code, - breakdown: breakdown - } - }; - patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.OPTIONS] = { - op: (null == data ? void 0 : data.event) || "replace", - path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.OPTIONS, - value: options - }; - return actions; - }, - updateShippingDiscount: function(_ref4) { - var _data$amount4; - var discount = _ref4.discount; - newAmount = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.calculateTotalFromShippingBreakdownAmounts)({ + var selectedShippingOptionAmount = null != (_selectedShippingOpti = null == selectedShippingOption || null == (_selectedShippingOpti2 = selectedShippingOption.amount) ? void 0 : _selectedShippingOpti2.value) ? _selectedShippingOpti : "0.00"; + var updatedAmounts = {}; + discount && (updatedAmounts.discount = discount); + handling && (updatedAmounts.handling = handling); + insurance && (updatedAmounts.insurance = insurance); + itemTotal && (updatedAmounts.item_total = itemTotal); + selectedShippingOption && (updatedAmounts.shipping = selectedShippingOptionAmount); + shippingDiscount && (updatedAmounts.shipping_discount = shippingDiscount); + taxTotal && (updatedAmounts.tax_total = taxTotal); + breakdown = Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.buildBreakdown)({ breakdown: breakdown, - updatedAmounts: { - shipping_discount: discount - } + updatedAmounts: updatedAmounts }); - breakdown = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.buildBreakdown)({ + var newAmount = Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.calculateTotalFromShippingBreakdownAmounts)({ breakdown: breakdown, - updatedAmounts: { - shipping_discount: discount - } + updatedAmounts: updatedAmounts }); - patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT] = { - op: "replace", - path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT, - value: { - value: "" + newAmount, - currency_code: null == data || null == (_data$amount4 = data.amount) ? void 0 : _data$amount4.currency_code, - breakdown: breakdown - } - }; - return actions; - }, - patch: function() { + if (Object.keys(updatedAmounts).length) { + var _data$amount2; + patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT] = { + op: "replace", + path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT, + value: { + value: "" + newAmount, + currency_code: null == data || null == (_data$amount2 = data.amount) ? void 0 : _data$amount2.currencyCode, + breakdown: breakdown + } + }; + } return Object(_api__WEBPACK_IMPORTED_MODULE_5__.getShippingOrderInfo)(orderID).then((function(sessionData) { var _sessionData$checkout; - var queries; var shippingMethods = (null == sessionData || null == (_sessionData$checkout = sessionData.checkoutSession) || null == (_sessionData$checkout = _sessionData$checkout.cart) ? void 0 : _sessionData$checkout.shippingMethods) || []; - queries = Boolean(shippingMethods.length > 0) ? Object(_utils__WEBPACK_IMPORTED_MODULE_9__.updateOperationForShippingOptions)({ - queries: patchQueries - }) : Object(_utils__WEBPACK_IMPORTED_MODULE_9__.convertQueriesToArray)({ - queries: patchQueries - }); - return Object(_api__WEBPACK_IMPORTED_MODULE_5__.patchShipping)({ - clientID: clientID, - orderID: orderID, - data: queries - }).catch((function() { - throw new Error("Order could not be patched"); - })); - })); - }, - query: function() { - return Object(_api__WEBPACK_IMPORTED_MODULE_5__.getShippingOrderInfo)(orderID).then((function(sessionData) { - var _sessionData$checkout2; - var shippingMethods = (null == sessionData || null == (_sessionData$checkout2 = sessionData.checkoutSession) || null == (_sessionData$checkout2 = _sessionData$checkout2.cart) ? void 0 : _sessionData$checkout2.shippingMethods) || []; - return Boolean(shippingMethods.length > 0) ? Object(_utils__WEBPACK_IMPORTED_MODULE_9__.updateOperationForShippingOptions)({ + var hasShippingMethods = Boolean(shippingMethods.length > 0); + if (null != shippingOptions && shippingOptions.length) { + var ordersV2Options = Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.optionsKeyChanges)(shippingOptions); + patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.OPTIONS] = { + op: hasShippingMethods ? "replace" : "add", + path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.OPTIONS, + value: ordersV2Options + }; + } + return hasShippingMethods ? Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.updateOperationForShippingOptions)({ queries: patchQueries - }) : Object(_utils__WEBPACK_IMPORTED_MODULE_9__.convertQueriesToArray)({ + }) : Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.convertQueriesToArray)({ queries: patchQueries }); })); } }; - return actions; - } - function getOnShippingAddressChange(_ref5, _ref6) { - var onShippingAddressChange = _ref5.onShippingAddressChange, clientID = _ref5.clientID; - var createOrder = _ref6.createOrder; - if (onShippingAddressChange) return function(_ref7, actions) { - var data = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.default)({}, (Object(_babel_runtime_helpers_esm_objectDestructuringEmpty__WEBPACK_IMPORTED_MODULE_0__.default)(_ref7), - _ref7)); + } + function getOnShippingAddressChange(_ref3, _ref4) { + var onShippingAddressChange = _ref3.onShippingAddressChange; + var createOrder = _ref4.createOrder; + if (onShippingAddressChange) return function(_ref5, actions) { + var data = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.default)({}, (Object(_babel_runtime_helpers_esm_objectDestructuringEmpty__WEBPACK_IMPORTED_MODULE_0__.default)(_ref5), + _ref5)); return createOrder().then((function(orderID) { var _getLogger$info$track; Object(_lib__WEBPACK_IMPORTED_MODULE_7__.getLogger)().info("button_shipping_address_change").track((_getLogger$info$track = {}, @@ -19358,7 +19676,6 @@ window.spb = function(modules) { _getLogger$info$track[_constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_CUSTOM_KEY.SHIPPING_CALLBACK_INVOKED] = "1", _getLogger$info$track)).flush(); return onShippingAddressChange(buildXOnShippingAddressChangeData(data), buildXOnShippingAddressChangeActions({ - clientID: clientID, data: data, actions: actions, orderID: orderID @@ -19385,6 +19702,15 @@ window.spb = function(modules) { __webpack_require__.d(__webpack_exports__, "buildXOnShippingChangeData", (function() { return buildXOnShippingChangeData; })); + __webpack_require__.d(__webpack_exports__, "sanitizePatch", (function() { + return sanitizePatch; + })); + __webpack_require__.d(__webpack_exports__, "isWeasley", (function() { + return isWeasley; + })); + __webpack_require__.d(__webpack_exports__, "logInvalidShippingChangePatches", (function() { + return logInvalidShippingChangePatches; + })); __webpack_require__.d(__webpack_exports__, "buildXShippingChangeActions", (function() { return buildXShippingChangeActions; })); @@ -19392,12 +19718,14 @@ window.spb = function(modules) { return getOnShippingChange; })); var _babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js"); - var _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./node_modules/@krakenjs/zalgo-promise/src/index.js"); - var _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./node_modules/@paypal/sdk-constants/src/index.js"); - var _api__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/api/index.js"); - var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("./src/constants.js"); - var _lib__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("./src/lib/index.js"); - var _excluded = [ "buyerAccessToken", "forceRestAPI" ]; + var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"); + var _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./node_modules/@krakenjs/zalgo-promise/src/index.js"); + var _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./node_modules/@paypal/sdk-constants/src/index.js"); + var _api__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("./src/api/index.js"); + var _constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("./src/constants.js"); + var _lib__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__("./src/lib/index.js"); + var _utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__("./src/props/utils.js"); + var _excluded = [ "buyerAccessToken", "forceRestAPI", "appName" ]; var ON_SHIPPING_CHANGE_PATHS = { AMOUNT: "/purchase_units/@reference_id=='default'/amount", OPTIONS: "/purchase_units/@reference_id=='default'/shipping/options" @@ -19416,53 +19744,100 @@ window.spb = function(modules) { function buildXOnShippingChangeData(data) { return data; } - function buildXShippingChangeActions(_ref) { - var orderID = _ref.orderID, facilitatorAccessToken = _ref.facilitatorAccessToken, buyerAccessToken = _ref.buyerAccessToken, partnerAttributionID = _ref.partnerAttributionID, forceRestAPI = _ref.forceRestAPI, clientID = _ref.clientID; - var useShippingChangeCallbackMutation = _ref.experiments.useShippingChangeCallbackMutation; + var pathPattern = new RegExp(/^\/purchase_units\/@reference_id=='(?:\w|-)*'\/(?:amount|shipping\/(?:options|address|name))$/); + var sanitizePatch = function(rejected, patch) { + var path = patch.path; + pathPattern.test(path) || rejected.push(path); + return rejected; + }; + var isWeasley = function(appName) { + return "weasley" === appName; + }; + var logInvalidShippingChangePatches = function(_ref) { + var appName = _ref.appName, data = _ref.data, shouldUsePatchShipping = _ref.shouldUsePatchShipping; + var payload = { + appName: appName, + hasBuyerAccessToken: String(Boolean(_ref.buyerAccessToken)), + shouldUsePatchShipping: String(shouldUsePatchShipping) + }; + try { + if (Array.isArray(data)) { + var rejected = data.reduce(sanitizePatch, []); + rejected.length > 0 && Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().info("button_shipping_change_patch_data_has_invalid_path_" + appName, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.default)({}, payload, { + rejected: JSON.stringify(rejected) + })); + } else Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().info("button_shipping_change_patch_data_is_object", payload); + } catch (err) { + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().error("button_shipping_change_patch_data_logging_failed", Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.default)({}, payload, { + errMessage: JSON.stringify(err) + })); + } + }; + function buildXShippingChangeActions(_ref2) { + var orderID = _ref2.orderID, facilitatorAccessToken = _ref2.facilitatorAccessToken, buyerAccessToken = _ref2.buyerAccessToken, partnerAttributionID = _ref2.partnerAttributionID, forceRestAPI = _ref2.forceRestAPI, clientID = _ref2.clientID, experiments = _ref2.experiments, appName = _ref2.appName, paymentSource = _ref2.paymentSource; + var useShippingChangeCallbackMutation = experiments.useShippingChangeCallbackMutation; return { resolve: function() { - return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__.ZalgoPromise.resolve(); + return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_2__.ZalgoPromise.resolve(); }, - reject: _ref.actions.reject || function() { + reject: _ref2.actions.reject || function() { throw new Error("Missing reject action callback"); }, order: { patch: function(data) { void 0 === data && (data = {}); - return useShippingChangeCallbackMutation ? Object(_api__WEBPACK_IMPORTED_MODULE_3__.patchShipping)({ + var shouldUsePatchShipping = Boolean(useShippingChangeCallbackMutation && !buyerAccessToken && isWeasley(appName)); + logInvalidShippingChangePatches({ + appName: appName, + buyerAccessToken: buyerAccessToken, + data: data, + shouldUsePatchShipping: shouldUsePatchShipping + }); + return shouldUsePatchShipping ? Object(_api__WEBPACK_IMPORTED_MODULE_4__.patchShipping)({ clientID: clientID, data: data, orderID: orderID }).catch((function() { throw new Error("Order could not be patched"); - })) : Object(_api__WEBPACK_IMPORTED_MODULE_3__.patchOrder)(orderID, data, { + })) : Object(_utils__WEBPACK_IMPORTED_MODULE_7__.checkUlsatNotRequired)(paymentSource, buyerAccessToken) ? Object(_api__WEBPACK_IMPORTED_MODULE_4__.patchOrder)(orderID, data, { facilitatorAccessToken: facilitatorAccessToken, buyerAccessToken: buyerAccessToken, partnerAttributionID: partnerAttributionID, - forceRestAPI: forceRestAPI + forceRestAPI: forceRestAPI, + experiments: experiments }).catch((function() { throw new Error("Order could not be patched"); + })) : Object(_api__WEBPACK_IMPORTED_MODULE_4__.upgradeFacilitatorAccessTokenWithIgnoreCache)(facilitatorAccessToken, buyerAccessToken, orderID).then((function(upgradedFacilitatorAccessToken) { + return Object(_api__WEBPACK_IMPORTED_MODULE_4__.patchOrder)(orderID, data, { + facilitatorAccessToken: upgradedFacilitatorAccessToken, + buyerAccessToken: buyerAccessToken, + partnerAttributionID: partnerAttributionID, + forceRestAPI: forceRestAPI, + experiments: experiments + }).catch((function() { + throw new Error("Order could not be patched"); + })); })); } } }; } - function getOnShippingChange(_ref2, _ref3) { - var onShippingChange = _ref2.onShippingChange, partnerAttributionID = _ref2.partnerAttributionID, featureFlags = _ref2.featureFlags, experiments = _ref2.experiments, clientID = _ref2.clientID; - var facilitatorAccessToken = _ref3.facilitatorAccessToken, createOrder = _ref3.createOrder; - if (onShippingChange) return function(_ref4, actions) { - var buyerAccessToken = _ref4.buyerAccessToken, _ref4$forceRestAPI = _ref4.forceRestAPI, forceRestAPI = void 0 === _ref4$forceRestAPI ? featureFlags.isLsatUpgradable : _ref4$forceRestAPI, data = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_0__.default)(_ref4, _excluded); + function getOnShippingChange(_ref3, _ref4) { + var onShippingChange = _ref3.onShippingChange, partnerAttributionID = _ref3.partnerAttributionID, featureFlags = _ref3.featureFlags, experiments = _ref3.experiments, clientID = _ref3.clientID, paymentSource = _ref3.paymentSource; + var facilitatorAccessToken = _ref4.facilitatorAccessToken, createOrder = _ref4.createOrder; + if (onShippingChange) return function(_ref5, actions) { + var buyerAccessToken = _ref5.buyerAccessToken, _ref5$forceRestAPI = _ref5.forceRestAPI, forceRestAPI = void 0 === _ref5$forceRestAPI ? featureFlags.isLsatUpgradable : _ref5$forceRestAPI, _ref5$appName = _ref5.appName, appName = void 0 === _ref5$appName ? "not_available" : _ref5$appName, data = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_0__.default)(_ref5, _excluded); return createOrder().then((function(orderID) { var _getLogger$info$track; - Object(_lib__WEBPACK_IMPORTED_MODULE_5__.getLogger)().info("button_shipping_change").track((_getLogger$info$track = {}, - _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.TRANSITION] = _constants__WEBPACK_IMPORTED_MODULE_4__.FPTI_TRANSITION.CHECKOUT_SHIPPING_CHANGE, - _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.EVENT_NAME] = _constants__WEBPACK_IMPORTED_MODULE_4__.FPTI_TRANSITION.CHECKOUT_SHIPPING_CHANGE, - _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.CONTEXT_TYPE] = _constants__WEBPACK_IMPORTED_MODULE_4__.FPTI_CONTEXT_TYPE.ORDER_ID, - _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.TOKEN] = orderID, - _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_2__.FPTI_KEY.CONTEXT_ID] = orderID, - _getLogger$info$track[_constants__WEBPACK_IMPORTED_MODULE_4__.FPTI_CUSTOM_KEY.SHIPPING_CALLBACK_INVOKED] = "1", + Object(_lib__WEBPACK_IMPORTED_MODULE_6__.getLogger)().info("button_shipping_change").track((_getLogger$info$track = {}, + _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TRANSITION] = _constants__WEBPACK_IMPORTED_MODULE_5__.FPTI_TRANSITION.CHECKOUT_SHIPPING_CHANGE, + _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.EVENT_NAME] = _constants__WEBPACK_IMPORTED_MODULE_5__.FPTI_TRANSITION.CHECKOUT_SHIPPING_CHANGE, + _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_TYPE] = _constants__WEBPACK_IMPORTED_MODULE_5__.FPTI_CONTEXT_TYPE.ORDER_ID, + _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.TOKEN] = orderID, + _getLogger$info$track[_paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_3__.FPTI_KEY.CONTEXT_ID] = orderID, + _getLogger$info$track[_constants__WEBPACK_IMPORTED_MODULE_5__.FPTI_CUSTOM_KEY.SHIPPING_CALLBACK_INVOKED] = "1", _getLogger$info$track)).flush(); - if (experiments.btSdkOrdersV2Migration && !data.paymentID) { + if (!data.paymentID) { var _data$orderID; data.paymentID = null == (_data$orderID = data.orderID) ? void 0 : _data$orderID.replace("EC-", ""); data.paymentId = data.paymentID; @@ -19475,7 +19850,9 @@ window.spb = function(modules) { partnerAttributionID: partnerAttributionID, forceRestAPI: forceRestAPI, clientID: clientID, - experiments: experiments + experiments: experiments, + appName: appName, + paymentSource: paymentSource })); })); }; @@ -19502,10 +19879,10 @@ window.spb = function(modules) { var _constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__("./src/constants.js"); var _lib__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__("./src/lib/index.js"); var _onShippingChange__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__("./src/props/onShippingChange.js"); - var _utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__("./src/props/utils.js"); - var _excluded = [ "amount", "buyerAccessToken", "event", "forceRestAPI", "options", "selected_shipping_option" ]; + var _shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__("./src/props/shippingChangeUtils.js"); + var _excluded = [ "amount", "buyerAccessToken", "event", "forceRestAPI", "options", "selectedShippingOption" ]; function buildXOnShippingOptionsChangeData(data) { - var selectedShippingOption = data.selected_shipping_option, rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_2__.default)(data, _excluded); + var selectedShippingOption = data.selectedShippingOption, rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_2__.default)(data, _excluded); return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.default)({ errors: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.SHIPPING_OPTIONS_ERROR_MESSAGES, selectedShippingOption: selectedShippingOption @@ -19513,120 +19890,76 @@ window.spb = function(modules) { } function buildXOnShippingOptionsChangeActions(_ref) { var _data$amount; - var clientID = _ref.clientID, data = _ref.data, passedActions = _ref.actions, orderID = _ref.orderID; + var data = _ref.data, passedActions = _ref.actions, orderID = _ref.orderID; var patchQueries = {}; - var newAmount; - var breakdown = (null == (_data$amount = data.amount) ? void 0 : _data$amount.breakdown) || {}; + var breakdown = null != (_data$amount = data.amount) && _data$amount.breakdown ? Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.breakdownKeyChanges)(data.amount.breakdown) : {}; if (0 === Object.keys(breakdown).length) throw new Error("Must pass breakdown into data attribute for onShippingAddressChange callback."); - var actions = { + return { reject: passedActions.reject ? function(message) { return -1 === Object.values(_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.SHIPPING_OPTIONS_ERROR_MESSAGES).indexOf(message) ? passedActions.reject(_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.GENERIC_REJECT_ADDRESS_MESSAGE) : passedActions.reject(message); } : function() { throw new Error("Missing reject action callback"); }, - updateShippingOption: function(_ref2) { - var option = _ref2.option; - if (option && data.options) { - var _option$amount, _data$amount2, _data$amount3; - var selectedShippingOptionAmount = null == option || null == (_option$amount = option.amount) ? void 0 : _option$amount.value; - var options = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.updateShippingOptions)({ - option: option, - options: data.options - }); - newAmount = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.calculateTotalFromShippingBreakdownAmounts)({ - breakdown: (null == data || null == (_data$amount2 = data.amount) ? void 0 : _data$amount2.breakdown) || {}, - updatedAmounts: { - shipping: selectedShippingOptionAmount - } - }); - breakdown = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.buildBreakdown)({ - breakdown: breakdown, - updatedAmounts: { - shipping: selectedShippingOptionAmount - } - }); - options && options.length > 0 && (patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.OPTIONS] = { - op: (null == data ? void 0 : data.event) || "replace", - path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.OPTIONS, - value: options - }); + buildOrderPatchPayload: function(_temp) { + var _shippingOption$amoun; + var _ref2 = void 0 === _temp ? {} : _temp, discount = _ref2.discount, handling = _ref2.handling, insurance = _ref2.insurance, itemTotal = _ref2.itemTotal, shippingOption = _ref2.shippingOption, shippingDiscount = _ref2.shippingDiscount, taxTotal = _ref2.taxTotal; + var selectedShippingOptionAmount = null == shippingOption || null == (_shippingOption$amoun = shippingOption.amount) ? void 0 : _shippingOption$amoun.value; + var options = shippingOption && data.options ? Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.optionsKeyChanges)(Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.updateShippingOptions)({ + option: shippingOption, + options: data.options + })) : void 0; + var updatedAmounts = {}; + discount && (updatedAmounts.discount = discount); + handling && (updatedAmounts.handling = handling); + insurance && (updatedAmounts.insurance = insurance); + itemTotal && (updatedAmounts.item_total = itemTotal); + selectedShippingOptionAmount && (updatedAmounts.shipping = selectedShippingOptionAmount); + shippingDiscount && (updatedAmounts.shipping_discount = shippingDiscount); + taxTotal && (updatedAmounts.tax_total = taxTotal); + var newAmount = Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.calculateTotalFromShippingBreakdownAmounts)({ + breakdown: breakdown, + updatedAmounts: updatedAmounts + }); + breakdown = Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.buildBreakdown)({ + breakdown: breakdown, + updatedAmounts: updatedAmounts + }); + if (Object.keys(updatedAmounts).length) { + var _data$amount2; patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT] = { op: "replace", path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT, value: { value: "" + newAmount, - currency_code: null == data || null == (_data$amount3 = data.amount) ? void 0 : _data$amount3.currency_code, + currency_code: null == data || null == (_data$amount2 = data.amount) ? void 0 : _data$amount2.currencyCode, breakdown: breakdown } }; } - return actions; - }, - updateShippingDiscount: function(_ref3) { - var _data$amount4, _data$amount5; - var discount = _ref3.discount; - newAmount = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.calculateTotalFromShippingBreakdownAmounts)({ - breakdown: (null == data || null == (_data$amount4 = data.amount) ? void 0 : _data$amount4.breakdown) || {}, - updatedAmounts: { - shipping_discount: discount - } - }); - breakdown = Object(_utils__WEBPACK_IMPORTED_MODULE_9__.buildBreakdown)({ - breakdown: breakdown, - updatedAmounts: { - shipping_discount: discount - } - }); - patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT] = { - op: "replace", - path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.AMOUNT, - value: { - value: "" + newAmount, - currency_code: null == data || null == (_data$amount5 = data.amount) ? void 0 : _data$amount5.currency_code, - breakdown: breakdown - } - }; - return actions; - }, - patch: function() { return Object(_api__WEBPACK_IMPORTED_MODULE_5__.getShippingOrderInfo)(orderID).then((function(sessionData) { var _sessionData$checkout; - var queries; var shippingMethods = (null == sessionData || null == (_sessionData$checkout = sessionData.checkoutSession) || null == (_sessionData$checkout = _sessionData$checkout.cart) ? void 0 : _sessionData$checkout.shippingMethods) || []; - queries = Boolean(shippingMethods.length > 0) ? Object(_utils__WEBPACK_IMPORTED_MODULE_9__.updateOperationForShippingOptions)({ - queries: patchQueries - }) : Object(_utils__WEBPACK_IMPORTED_MODULE_9__.convertQueriesToArray)({ - queries: patchQueries + var hasShippingMethods = Boolean(shippingMethods.length > 0); + null != options && options.length && (patchQueries[_onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.OPTIONS] = { + op: hasShippingMethods ? "replace" : "add", + path: _onShippingChange__WEBPACK_IMPORTED_MODULE_8__.ON_SHIPPING_CHANGE_PATHS.OPTIONS, + value: options }); - return Object(_api__WEBPACK_IMPORTED_MODULE_5__.patchShipping)({ - clientID: clientID, - orderID: orderID, - data: queries - }).catch((function() { - throw new Error("Order could not be patched"); - })); - })); - }, - query: function() { - return Object(_api__WEBPACK_IMPORTED_MODULE_5__.getShippingOrderInfo)(orderID).then((function(sessionData) { - var _sessionData$checkout2; - var shippingMethods = (null == sessionData || null == (_sessionData$checkout2 = sessionData.checkoutSession) || null == (_sessionData$checkout2 = _sessionData$checkout2.cart) ? void 0 : _sessionData$checkout2.shippingMethods) || []; - return Boolean(shippingMethods.length > 0) ? Object(_utils__WEBPACK_IMPORTED_MODULE_9__.updateOperationForShippingOptions)({ + return hasShippingMethods ? Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.updateOperationForShippingOptions)({ queries: patchQueries - }) : Object(_utils__WEBPACK_IMPORTED_MODULE_9__.convertQueriesToArray)({ + }) : Object(_shippingChangeUtils__WEBPACK_IMPORTED_MODULE_9__.convertQueriesToArray)({ queries: patchQueries }); })); } }; - return actions; - } - function getOnShippingOptionsChange(_ref4, _ref5) { - var onShippingOptionsChange = _ref4.onShippingOptionsChange, clientID = _ref4.clientID; - var createOrder = _ref5.createOrder; - if (onShippingOptionsChange) return function(_ref6, actions) { - var data = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.default)({}, (Object(_babel_runtime_helpers_esm_objectDestructuringEmpty__WEBPACK_IMPORTED_MODULE_0__.default)(_ref6), - _ref6)); + } + function getOnShippingOptionsChange(_ref3, _ref4) { + var onShippingOptionsChange = _ref3.onShippingOptionsChange; + var createOrder = _ref4.createOrder; + if (onShippingOptionsChange) return function(_ref5, actions) { + var data = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_1__.default)({}, (Object(_babel_runtime_helpers_esm_objectDestructuringEmpty__WEBPACK_IMPORTED_MODULE_0__.default)(_ref5), + _ref5)); return createOrder().then((function(orderID) { var _getLogger$info$track; Object(_lib__WEBPACK_IMPORTED_MODULE_7__.getLogger)().info("button_shipping_options_change").track((_getLogger$info$track = {}, @@ -19638,7 +19971,6 @@ window.spb = function(modules) { _getLogger$info$track[_constants__WEBPACK_IMPORTED_MODULE_6__.FPTI_CUSTOM_KEY.SHIPPING_CALLBACK_INVOKED] = "1", _getLogger$info$track)).flush(); return onShippingOptionsChange(buildXOnShippingOptionsChangeData(data), buildXOnShippingOptionsChangeActions({ - clientID: clientID, data: data, actions: actions, orderID: orderID @@ -19665,7 +19997,7 @@ window.spb = function(modules) { var _onError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("./src/props/onError.js"); var TYPES = !0; function getProps(_ref) { - var branded = _ref.branded, enableOrdersApprovalSmartWallet = _ref.enableOrdersApprovalSmartWallet, smartWalletOrderID = _ref.smartWalletOrderID; + var branded = _ref.branded; var xprops = window.xprops; var uid = xprops.uid, env = xprops.env, _xprops$vault = xprops.vault, vault = void 0 !== _xprops$vault && _xprops$vault, commit = xprops.commit, locale = xprops.locale, platform = xprops.platform, sessionID = xprops.sessionID, clientID = xprops.clientID, partnerAttributionID = xprops.partnerAttributionID, merchantRequestedPopupsDisabled = xprops.merchantRequestedPopupsDisabled, clientMetadataID = xprops.clientMetadataID, sdkCorrelationID = xprops.sdkCorrelationID, getParentDomain = xprops.getParentDomain, clientAccessToken = xprops.clientAccessToken, getPopupBridge = xprops.getPopupBridge, getPrerenderDetails = xprops.getPrerenderDetails, getPageUrl = xprops.getPageUrl, enableThreeDomainSecure = xprops.enableThreeDomainSecure, enableVaultInstallments = xprops.enableVaultInstallments, _xprops$enableNativeC = xprops.enableNativeCheckout, enableNativeCheckout = void 0 !== _xprops$enableNativeC && _xprops$enableNativeC, rememberFunding = xprops.remember, stageHost = xprops.stageHost, apiStageHost = xprops.apiStageHost, getParent = xprops.getParent, fundingSource = xprops.fundingSource, currency = xprops.currency, connect = xprops.connect, intent = xprops.intent, merchantID = xprops.merchantID, amount = xprops.amount, userIDToken = xprops.userIDToken, enableFunding = xprops.enableFunding, disableFunding = xprops.disableFunding, disableCard = xprops.disableCard, disableAutocomplete = xprops.disableAutocomplete, wallet = xprops.wallet, _xprops$paymentMethod = xprops.paymentMethodToken, paymentMethodToken = void 0 === _xprops$paymentMethod ? xprops.paymentMethodNonce : _xprops$paymentMethod, _xprops$getQueriedEli = xprops.getQueriedEligibleFunding, getQueriedEligibleFunding = void 0 === _xprops$getQueriedEli ? function() { return _krakenjs_zalgo_promise_src__WEBPACK_IMPORTED_MODULE_1__.ZalgoPromise.resolve([]); @@ -19731,8 +20063,6 @@ window.spb = function(modules) { allowBillingPayments: allowBillingPayments, paymentRequest: paymentRequest, merchantID: merchantID, - enableOrdersApprovalSmartWallet: enableOrdersApprovalSmartWallet, - smartWalletOrderID: smartWalletOrderID, disableSetCookie: disableSetCookie }; } @@ -19749,12 +20079,18 @@ window.spb = function(modules) { return _ref.remember; } }, - "./src/props/utils.js": function(module, __webpack_exports__, __webpack_require__) { + "./src/props/shippingChangeUtils.js": function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); __webpack_require__.d(__webpack_exports__, "calculateTotalFromShippingBreakdownAmounts", (function() { return calculateTotalFromShippingBreakdownAmounts; })); + __webpack_require__.d(__webpack_exports__, "optionsKeyChanges", (function() { + return optionsKeyChanges; + })); + __webpack_require__.d(__webpack_exports__, "breakdownKeyChanges", (function() { + return breakdownKeyChanges; + })); __webpack_require__.d(__webpack_exports__, "buildBreakdown", (function() { return buildBreakdown; })); @@ -19767,7 +20103,8 @@ window.spb = function(modules) { __webpack_require__.d(__webpack_exports__, "updateOperationForShippingOptions", (function() { return updateOperationForShippingOptions; })); - var _onShippingChange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/props/onShippingChange.js"); + var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./node_modules/@babel/runtime/helpers/esm/extends.js"); + var _onShippingChange__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/props/onShippingChange.js"); var calculateTotalFromShippingBreakdownAmounts = function(_ref) { var breakdown = _ref.breakdown, updatedAmounts = _ref.updatedAmounts; var newAmount = 0; @@ -19787,6 +20124,57 @@ window.spb = function(modules) { })); return newAmount.toFixed(2); }; + var optionsKeyChanges = function(options) { + var ordersV2Options = []; + options.forEach((function(element) { + var shippingOption = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.default)({}, element, { + amount: { + value: element.amount.value, + currency_code: element.amount.currencyCode + } + }); + ordersV2Options.push(shippingOption); + })); + return ordersV2Options; + }; + var breakdownKeyChanges = function(breakdown) { + return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__.default)({}, breakdown.discount ? { + discount: { + value: breakdown.discount.value, + currency_code: breakdown.discount.currencyCode + } + } : void 0, breakdown.handling ? { + handling: { + value: breakdown.handling.value, + currency_code: breakdown.handling.currencyCode + } + } : void 0, breakdown.insurance ? { + insurance: { + value: breakdown.insurance.value, + currency_code: breakdown.insurance.currencyCode + } + } : void 0, breakdown.itemTotal ? { + item_total: { + value: breakdown.itemTotal.value, + currency_code: breakdown.itemTotal.currencyCode + } + } : void 0, breakdown.shipping ? { + shipping: { + value: breakdown.shipping.value, + currency_code: breakdown.shipping.currencyCode + } + } : void 0, breakdown.shippingDiscount ? { + shipping_discount: { + value: breakdown.shippingDiscount.value, + currency_code: breakdown.shippingDiscount.currencyCode + } + } : void 0, breakdown.taxTotal ? { + tax_total: { + value: breakdown.taxTotal.value, + currency_code: breakdown.taxTotal.currencyCode + } + } : void 0); + }; var buildBreakdown = function(_ref2) { var _Object$values$; var _ref2$breakdown = _ref2.breakdown, breakdown = void 0 === _ref2$breakdown ? {} : _ref2$breakdown, _ref2$updatedAmounts = _ref2.updatedAmounts, updatedAmounts = void 0 === _ref2$updatedAmounts ? {} : _ref2$updatedAmounts; @@ -19810,8 +20198,8 @@ window.spb = function(modules) { _ref4.options.forEach((function(opt) { if (!opt.id) throw new Error("Must provide an id with each shipping option."); if (opt.id === option.id) { - opt.selected = !0; - updatedOptions.push(opt); + option.selected = !0; + updatedOptions.push(option); } else { opt.selected = !1; updatedOptions.push(opt); @@ -19821,10 +20209,48 @@ window.spb = function(modules) { }; var updateOperationForShippingOptions = function(_ref5) { var queries = _ref5.queries; - queries[_onShippingChange__WEBPACK_IMPORTED_MODULE_0__.ON_SHIPPING_CHANGE_PATHS.OPTIONS] && (queries[_onShippingChange__WEBPACK_IMPORTED_MODULE_0__.ON_SHIPPING_CHANGE_PATHS.OPTIONS].op = "replace"); + queries[_onShippingChange__WEBPACK_IMPORTED_MODULE_1__.ON_SHIPPING_CHANGE_PATHS.OPTIONS] && (queries[_onShippingChange__WEBPACK_IMPORTED_MODULE_1__.ON_SHIPPING_CHANGE_PATHS.OPTIONS].op = "replace"); return convertQueriesToArray({ queries: queries }); }; + }, + "./src/props/utils.js": function(module, __webpack_exports__, __webpack_require__) { + "use strict"; + __webpack_require__.r(__webpack_exports__); + __webpack_require__.d(__webpack_exports__, "checkUlsatNotRequired", (function() { + return checkUlsatNotRequired; + })); + __webpack_require__.d(__webpack_exports__, "redirect", (function() { + return redirect; + })); + var _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./node_modules/@paypal/sdk-constants/src/index.js"); + var _krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./node_modules/@krakenjs/belter/src/index.js"); + __webpack_require__("./node_modules/@krakenjs/zalgo-promise/src/index.js"); + var _lib__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("./src/lib/index.js"); + var checkUlsatNotRequired = function(paymentSource, buyerAccessToken) { + return paymentSource === _paypal_sdk_constants_src__WEBPACK_IMPORTED_MODULE_0__.FUNDING.VENMO && !buyerAccessToken; + }; + var redirect = function(url) { + if (!url) throw new Error("Expected redirect url"); + if (-1 === url.indexOf("://")) { + Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().warn("redir_url_non_scheme", { + url: url + }).flush(); + throw new Error("Invalid redirect url: " + url + " - must be fully qualified url"); + } + if (!url.match(/^https:\/\//)) { + Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().warn("redir_url_non_http", { + url: url + }).flush(); + if (url.toLowerCase().replace(/[^a-z:]+/g, "").match(/^javascript:/)) { + Object(_lib__WEBPACK_IMPORTED_MODULE_3__.getLogger)().warn("redir_url_has_javascript", { + url: url + }).flush(); + throw new Error("Invalid redirect url: " + url + " - must be fully qualified url"); + } + } + return Object(_krakenjs_belter_src__WEBPACK_IMPORTED_MODULE_1__.redirect)(url, window.top); + }; } }); \ No newline at end of file diff --git a/dist/smart-payment-buttons.min.js b/dist/smart-payment-buttons.min.js index 44149232a6..12c280f351 100644 --- a/dist/smart-payment-buttons.min.js +++ b/dist/smart-payment-buttons.min.js @@ -1 +1 @@ -window.spb=function(e){var n={};function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(n){return e[n]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return{}.hasOwnProperty.call(e,n)},t.p="",t(t.s=59)}([function(e,n,t){"use strict";t.d(n,"d",(function(){return u})),t.d(n,"l",(function(){return s})),t.d(n,"g",(function(){return l})),t.d(n,"i",(function(){return d})),t.d(n,"e",(function(){return f})),t.d(n,"f",(function(){return p})),t.d(n,"h",(function(){return h})),t.d(n,"j",(function(){return m})),t.d(n,"b",(function(){return g})),t.d(n,"q",(function(){return _})),t.d(n,"c",(function(){return r})),t.d(n,"k",(function(){return o})),t.d(n,"p",(function(){return i})),t.d(n,"o",(function(){return a})),t.d(n,"n",(function(){return c})),t.d(n,"m",(function(){return v})),t.d(n,"a",(function(){return b}));var r={AD:"AD",AE:"AE",AG:"AG",AI:"AI",AL:"AL",AM:"AM",AN:"AN",AO:"AO",AR:"AR",AT:"AT",AU:"AU",AW:"AW",AZ:"AZ",BA:"BA",BB:"BB",BE:"BE",BF:"BF",BG:"BG",BH:"BH",BI:"BI",BJ:"BJ",BM:"BM",BN:"BN",BO:"BO",BR:"BR",BS:"BS",BT:"BT",BW:"BW",BY:"BY",BZ:"BZ",CA:"CA",CD:"CD",CG:"CG",CH:"CH",CI:"CI",CK:"CK",CL:"CL",CM:"CM",CN:"CN",CO:"CO",CR:"CR",CV:"CV",CY:"CY",CZ:"CZ",DE:"DE",DJ:"DJ",DK:"DK",DM:"DM",DO:"DO",DZ:"DZ",EC:"EC",EE:"EE",EG:"EG",ER:"ER",ES:"ES",ET:"ET",FI:"FI",FJ:"FJ",FK:"FK",FM:"FM",FO:"FO",FR:"FR",GA:"GA",GB:"GB",GD:"GD",GE:"GE",GF:"GF",GI:"GI",GL:"GL",GM:"GM",GN:"GN",GP:"GP",GR:"GR",GT:"GT",GW:"GW",GY:"GY",HK:"HK",HN:"HN",HR:"HR",HU:"HU",ID:"ID",IE:"IE",IL:"IL",IN:"IN",IS:"IS",IT:"IT",JM:"JM",JO:"JO",JP:"JP",KE:"KE",KG:"KG",KH:"KH",KI:"KI",KM:"KM",KN:"KN",KR:"KR",KW:"KW",KY:"KY",KZ:"KZ",LA:"LA",LC:"LC",LI:"LI",LK:"LK",LS:"LS",LT:"LT",LU:"LU",LV:"LV",MA:"MA",MC:"MC",MD:"MD",ME:"ME",MG:"MG",MH:"MH",MK:"MK",ML:"ML",MN:"MN",MQ:"MQ",MR:"MR",MS:"MS",MT:"MT",MU:"MU",MV:"MV",MW:"MW",MX:"MX",MY:"MY",MZ:"MZ",NA:"NA",NC:"NC",NE:"NE",NF:"NF",NG:"NG",NI:"NI",NL:"NL",NO:"NO",NP:"NP",NR:"NR",NU:"NU",NZ:"NZ",OM:"OM",PA:"PA",PE:"PE",PF:"PF",PG:"PG",PH:"PH",PL:"PL",PM:"PM",PN:"PN",PT:"PT",PW:"PW",PY:"PY",QA:"QA",RE:"RE",RO:"RO",RS:"RS",RU:"RU",RW:"RW",SA:"SA",SB:"SB",SC:"SC",SE:"SE",SG:"SG",SH:"SH",SI:"SI",SJ:"SJ",SK:"SK",SL:"SL",SM:"SM",SN:"SN",SO:"SO",SR:"SR",ST:"ST",SV:"SV",SZ:"SZ",TC:"TC",TD:"TD",TG:"TG",TH:"TH",TJ:"TJ",TM:"TM",TN:"TN",TO:"TO",TR:"TR",TT:"TT",TV:"TV",TW:"TW",TZ:"TZ",UA:"UA",UG:"UG",US:"US",UY:"UY",VA:"VA",VC:"VC",VE:"VE",VG:"VG",VN:"VN",VU:"VU",WF:"WF",WS:"WS",YE:"YE",YT:"YT",ZA:"ZA",ZM:"ZM",ZW:"ZW"},o={CAPTURE:"capture",AUTHORIZE:"authorize",ORDER:"order",TOKENIZE:"tokenize",SUBSCRIPTION:"subscription"},i={TRUE:!0,FALSE:!1},a={NAMESPACE:"data-namespace",CLIENT_TOKEN:"data-client-token",MERCHANT_ID:"data-merchant-id",PARTNER_ATTRIBUTION_ID:"data-partner-attribution-id",STAGE_HOST:"data-stage-host",API_STAGE_HOST:"data-api-stage-host",CSP_NONCE:"data-csp-nonce",ENABLE_3DS:"data-enable-3ds",SDK_INTEGRATION_SOURCE:"data-sdk-integration-source",USER_ID_TOKEN:"data-user-id-token",AMOUNT:"data-amount",CLIENT_METADATA_ID:"data-client-metadata-id",PAGE_TYPE:"data-page-type",USER_EXPERIENCE_FLOW:"data-user-experience-flow",POPUPS_DISABLED:"data-popups-disabled"},c={COMPONENTS:"components",ENV:"env",DEBUG:"debug",CACHEBUST:"cachebust",CLIENT_ID:"client-id",MERCHANT_ID:"merchant-id",LOCALE:"locale",CURRENCY:"currency",INTENT:"intent",COMMIT:"commit",VAULT:"vault",BUYER_COUNTRY:"buyer-country",ENABLE_FUNDING:"enable-funding",DISABLE_FUNDING:"disable-funding",DISABLE_CARD:"disable-card",INTEGRATION_DATE:"integration-date",STAGE_HOST:"stage-host",STAGE_ALIAS:"stage-alias",CDN_REGISTRY:"cdn-registry",VERSION:"version"},u={LOCAL:"local",STAGE:"stage",SANDBOX:"sandbox",PRODUCTION:"production",TEST:"test"},s={ANDROID:"android",IOS:"iOS"},l={FEED:"feed_name",STATE:"state_name",EVENT_NAME:"event_name",TRANSITION:"transition_name",PAGE:"page_name",BUTTON_TYPE:"button_type",SESSION_UID:"page_session_id",BUTTON_SESSION_UID:"button_session_id",TOKEN:"token",CONTEXT_ID:"context_id",CONTEXT_TYPE:"context_type",REFERER:"referer_url",MERCHANT_DOMAIN:"merchant_domain",PAY_ID:"pay_id",SELLER_ID:"seller_id",CLIENT_ID:"client_id",DATA_SOURCE:"serverside_data_source",BUTTON_SOURCE:"button_source",ERROR_CODE:"ext_error_code",ERROR_DESC:"ext_error_desc",PAGE_LOAD_TIME:"page_load_time",EXPERIMENT_EXPERIENCE:"experimentation_experience",EXPERIMENT_TREATMENT:"experimentation_treatment",EXPERIMENT_NAME:"pxp_exp_id",TREATMENT_NAME:"pxp_trtmnt_id",TRANSITION_TIME:"transition_time",FUNDING_LIST:"eligible_payment_methods",FUNDING_COUNT:"eligible_payment_count",CHOSEN_FUNDING:"selected_payment_method",BUTTON_LAYOUT:"button_layout",VERSION:"checkoutjs_version",LOCALE:"locale",BUYER_COUNTRY:"buyer_cntry",INTEGRATION_IDENTIFIER:"integration_identifier",PARTNER_ATTRIBUTION_ID:"bn_code",PAGE_TYPE:"pp_placement",SDK_NAME:"sdk_name",SDK_VERSION:"sdk_version",SDK_ENVIRONMENT:"sdk_environment",MOBILE_APP_VERSION:"mobile_app_version",MOBILE_BUNDLE_IDENTIFIER:"mapv",USER_AGENT:"user_agent",USER_ACTION:"user_action",CONTEXT_CORRID:"context_correlation_id",SDK_CACHE:"sdk_cache",SDK_LOAD_TIME:"sdk_load_time",IS_VAULT:"is_vault",DISABLE_FUNDING:"disable_funding",DISABLE_CARD:"disable_card",RESPONSE_DURATION:"response_duration",SDK_INTEGRATION_SOURCE:"sdk_integration_source",PAYMENT_FLOW:"payment_flow",BUTTON_VERSION:"button_version",FI_LIST:"fi_list",FI_ID:"fi_id",PRODUCT:"product",CHOSEN_FI_TYPE:"chosen_fi_type",SELECTED_FI:"merchant_selected_funding_source",POTENTIAL_PAYMENT_METHODS:"potential_payment_methods",PAY_NOW:"pay_now",STICKINESS_ID:"stickiness_id",TIMESTAMP:"t",OPTION_SELECTED:"optsel",USER_IDENTITY_METHOD:"user_identity_method",FIELDS_COMPONENT_SESSION_ID:"fields_component_session_id",CPL_COMP_METRICS:"cpl_comp_metrics",CPL_CHUNK_METRICS:"cpl_chunk_metrics",CPL_QUERY_METRICS:"cpl_query_metrics"},d={COMMIT:"commit",CONTINUE:"continue"},f={PAYMENTS_SDK:"checkout"},p={PAYMENTS_SDK:"payments_sdk"},h={PAYMENTS_SDK:"payments_sdk"},m={PAYPAL:"paypal",VENMO:"venmo",APPLEPAY:"applepay",ITAU:"itau",CREDIT:"credit",PAYLATER:"paylater",CARD:"card",IDEAL:"ideal",SEPA:"sepa",BANCONTACT:"bancontact",GIROPAY:"giropay",SOFORT:"sofort",EPS:"eps",MYBANK:"mybank",P24:"p24",PAYU:"payu",BLIK:"blik",TRUSTLY:"trustly",OXXO:"oxxo",BOLETO:"boleto",BOLETOBANCARIO:"boletobancario",WECHATPAY:"wechatpay",MERCADOPAGO:"mercadopago",MULTIBANCO:"multibanco",SATISPAY:"satispay",PAIDY:"paidy"},g={VISA:"visa",MASTERCARD:"mastercard",AMEX:"amex",DISCOVER:"discover",HIPER:"hiper",ELO:"elo",JCB:"jcb",CUP:"cup"},_={BALANCE:"balance",CARD:"card",BANK:"bank",CREDIT:"credit"},v={DESKTOP:"desktop",MOBILE:"mobile"},b=[m.IDEAL,m.BANCONTACT,m.GIROPAY,m.SOFORT,m.EPS,m.MYBANK,m.P24,m.PAYU,m.BLIK,m.TRUSTLY,m.OXXO,m.BOLETO,m.BOLETOBANCARIO,m.WECHATPAY,m.MERCADOPAGO,m.MULTIBANCO,m.SATISPAY,m.PAIDY]},function(e,n,t){"use strict";t.d(n,"x",(function(){return r})),t.d(n,"b",(function(){return o})),t.d(n,"n",(function(){return i})),t.d(n,"e",(function(){return a})),t.d(n,"c",(function(){return c})),t.d(n,"t",(function(){return u})),t.d(n,"q",(function(){return s})),t.d(n,"d",(function(){return l})),t.d(n,"z",(function(){return d})),t.d(n,"o",(function(){return f})),t.d(n,"B",(function(){return p})),t.d(n,"u",(function(){return h})),t.d(n,"h",(function(){return m})),t.d(n,"k",(function(){return g})),t.d(n,"l",(function(){return _})),t.d(n,"j",(function(){return v})),t.d(n,"g",(function(){return b})),t.d(n,"i",(function(){return E})),t.d(n,"f",(function(){return y})),t.d(n,"A",(function(){return I})),t.d(n,"m",(function(){return T})),t.d(n,"v",(function(){return O})),t.d(n,"p",(function(){return w})),t.d(n,"a",(function(){return S})),t.d(n,"y",(function(){return A})),t.d(n,"w",(function(){return D})),t.d(n,"s",(function(){return C})),t.d(n,"r",(function(){return N}));var r="smart-payment-buttons",o={PAY:"pay",PAY_WITH_DIFFERENT_ACCOUNT:"pay_with_different_account",PAY_WITH_DIFFERENT_FUNDING_SHIPPING:"pay_with_different_funding_shipping"},i={AUTHORIZATION:"authorization",CONTENT_TYPE:"content-type",PREFER:"prefer",ACCESS_TOKEN:"x-paypal-internal-euat",CSRF_TOKEN:"x-csrf-jwt",SOURCE:"x-source",REQUESTED_BY:"x-requested-by",APP_NAME:"x-app-name",APP_VERSION:"x-app-version",CLIENT_CONTEXT:"paypal-client-context",PARTNER_ATTRIBUTION_ID:"paypal-partner-attribution-id",CLIENT_METADATA_ID:"paypal-client-metadata-id",PAYPAL_DEBUG_ID:"paypal-debug-id",PAYPAL_REQUEST_ID:"paypal-request-id",DISABLE_SET_COOKIE:"disable-set-cookie"},a={FUNDING_SOURCE:"data-funding-source",CARD:"data-card",PAYMENT_METHOD_ID:"data-payment-method-id",INSTRUMENT_ID:"data-instrument-id",INSTRUMENT_TYPE:"data-instrument-type",SECONDARY_INSTRUMENT_TYPE:"data-secondary-instrument-type",MENU:"data-menu",NONCE:"data-nonce",RENDER_VERSION:"data-render-version",CLIENT_VERSION:"data-client-version",PAY_NOW:"data-pay-now",RESPONSE_START_TIME:"data-response-start-time"},c={LOADING:"paypal-button-loading",CLICKED:"paypal-button-clicked",BUTTON:"paypal-button"},u={REPRESENTATION:"return=representation"},s={INSTRUMENT_DECLINED:"INSTRUMENT_DECLINED",PAYER_ACTION_REQUIRED:"PAYER_ACTION_REQUIRED",DUPLICATE_INVOICE_ID:"DUPLICATE_INVOICE_ID",INVALID_RESOURCE_ID:"INVALID_RESOURCE_ID"},l={IFRAME:"iframe",POPUP:"popup"},d={BODY:"body"},f={PAYPAL_JS_SDK:"PAYPAL_JS_SDK"},p={INCONTEXT:"INCONTEXT",INLINE:"INLINE"},h={SMART_PAYMENT_BUTTONS:"SMART_PAYMENT_BUTTONS"},m={BUTTON_SESSION_ID:"button_session_id",WALLET_SESSION_ID:"wallet_session_id",ORDER_ID:"EC-Token",PAYMENT_ID:"Pay-ID"},g={BUTTON:"smart_button",CARD:"card_field",WALLET:"smart_wallet",PXP:"PXP_CHECK",ELIGIBILITY_CHECK:"eligibility_check"},_={BUTTON_LOAD:"process_button_load",BUTTON_CLICK:"process_button_click",PXP:"process_pxp_check",WALLET_LOAD:"process_wallet_load",MENU_CLICK:"process_menu_click",CLICK_CHOOSE_FUNDING:"process_click_pay_with_different_payment_method",CLICK_CHOOSE_ACCOUNT:"process_click_pay_with_different_account",CLICK_UNLINK_ACCOUNT:"process_click_unlink_account",INSTALLMENTS_ELIGIBLE:"installments_eligible",INSTALLMENTS_INELIGIBLE:"installments_ineligible",CREATE_ORDER:"process_create_order",CONFIRM_ORDER:"process_confirm_order",RECEIVE_ORDER:"process_receive_order",CREATE_PAYMENT:"process_create_payment",CAPTURE_AUTHORIZATION:"process_capture_authorization",CHECKOUT_SHIPPING_CHANGE:"process_checkout_shipping_change",CHECKOUT_SHIPPING_ADDRESS_CHANGE:"process_checkout_shipping_address_change",CHECKOUT_SHIPPING_OPTIONS_CHANGE:"process_checkout_shipping_options_change",CHECKOUT_APPROVE:"process_checkout_approve",CHECKOUT_COMPLETE:"process_checkout_complete",CHECKOUT_CANCEL:"process_checkout_cancel",CHECKOUT_ERROR:"process_checkout_error",TOKENIZE_APPROVE:"process_tokenize_approve",CONNECT_REDIRECT:"process_connect_redirect",FIREBASE_CONNECTION_OPENED:"firebase_connection_opened",FIREBASE_CONNECTION_ERRORED:"firebase_connection_errored",APPLEPAY_EVENT:"applepay_event",APPLEPAY_FLOW_ERROR:"applepay_flow_error",APPLEPAY_ON_CLICK_INVALID:"applepay_onclick_invalid",APPLEPAY_MERCHANT_VALIDATION_COMPLETION_ERROR:"applepay_merchant_validation_completion_error",APPLEPAY_MERCHANT_VALIDATION_ERROR:"applepay_merchant_validation_error",APPLEPAY_CREATE_ORDER_ERROR:"applepay_create_order_error",APPLEPAY_GET_DETAILS_ERROR:"applepay_get_details_error",APPLEPAY_PAYMENT_ERROR:"applepay_payment_error",APPLEPAY_CONFIG_ERROR:"applepay_config_error",NATIVE_DETECT_POSSIBLE_APP_SWITCH:"native_detect_possible_app_switch",NATIVE_DETECT_APP_SWITCH:"native_detect_app_switch",NATIVE_DETECT_WEB_SWITCH:"native_detect_web_switch",NATIVE_APP_SWITCH_ACK:"native_app_switch_ack",NATIVE_ERROR:"native_app_switch_ack",NATIVE_APP_INSTALLED:"native_app_installed",NATIVE_APP_SWITCH_INELIGIBLE:"app_switch_ineligible",NATIVE_ATTEMPT_APP_SWITCH:"app_switch_attempted",NATIVE_ATTEMPT_APP_SWITCH_ERRORED:"app_switch_attempted_errored",NATIVE_CLOSING_POPUP:"native_closing_popup",NATIVE_POPUP_CLOSED:"popup_closed",NATIVE_POPUP_HASHCHANGE:"popup_hashchange",NATIVE_POPUP_NO_OPENER:"popup_no_opener",NATIVE_POPUP_ANDROID_APP_ERROR:"native_popup_android_app_installed_error",NATIVE_POPUP_FALLBACK:"popup_fallback",NATIVE_FALLBACK_RETRY_VENMO_APP_SWITCH:"native_fallback_retry_venmo_app_switch",NATIVE_POPUP_SHOWN:"popup_shown",NATIVE_ON_APPROVE:"native_onapprove",NATIVE_ON_APPROVE_ERROR:"native_onapprove_error",NATIVE_ON_CANCEL:"native_oncancel",NATIVE_ON_CLICK_INVALID:"native_onclick_invalid",NATIVE_ON_COMPLETE:"native_oncomplete",NATIVE_ON_ERROR:"native_onerror",NATIVE_ON_SHIPPING_CHANGE:"native_onshippingchange",NATIVE_ON_FALLBACK:"native_onfallback",NATIVE_POPUP_INIT:"native_popup_init",NATIVE_POPUP_UNLOAD:"native_popup_unload",NATIVE_POPUP_BEFORE_UNLOAD:"native_popup_beforeunload",NATIVE_POPUP_PAGEHIDE:"native_popup_pagehide",NATIVE_POPUP_OPENER_DETECT_CLOSE:"native_popup_opener_detect_close",NATIVE_OPT_OUT:"native_opt_out",NATIVE_FALLBACK:"native_fallback",NATIVE_FALLBACK_VENMO:"native_fallback_venmo",NATIVE_VENMO_WEB:"native_venmo_web",NATIVE_VENMO_WEB_REDIRECT:"native_venmo_web_redirect",QR_LOAD:"qr_load",QR_SHOWN:"qr_shown",QR_CLOSING:"qr_closing",QR_SURVEY:"desktop_exit_survey_selection_submitted",QR_PREPARE_PAY:"qr_prepare_pay",QR_PROCESS_PAY_WITH:"qr_process_pay_with",HONEY_IDENTIFY:"honey_identify",CALL_REST_API:"call_rest_api",ORDER_VALIDATE:"process_order_validate"},v={CHOOSE_FUNDING:"pay_with_different_payment_method",CHOOSE_ACCOUNT:"pay_with_different_account",UNLINK_ACCOUNT:"unlink_account"},b={IFRAME:"iframe"},E={ERR_DESC:"int_error_desc",HONEY_DEVICE_ID:"honey_device_id",HONEY_SESSION_ID:"honey_session_id",INTEGRATION_ISSUE:"integration_issue",INTEGRATION_WHITELIST:"whitelist",INFO_MSG:"info_msg",PMT_TOKEN:"pmt_token",TRANSITION_TYPE:"transition_type",TRANSITION_REASON:"transition_reason",SHIPPING_CALLBACK_PASSED:"shipping_callback_passed",SHIPPING_CALLBACK_INVOKED:"shipping_callback_invoked",DESKTOP_EXIT_SURVEY_REASON:"desktop_exit_survey_reason",ORDER_CREATED_BY:"order_created_by"},y={BUTTON_LAYOUT:"button_layout",BUTTON_COLOR:"button_color",BUTTON_SIZE:"button_size",BUTTON_SHAPE:"button_shape",BUTTON_LABEL:"button_label",BUTTON_WIDTH:"button_width",BUTTON_TYPE:"button_type",BUTTON_TAGLINE_ENABLED:"button_tagline_enabled",BUTTON_CORRELATION_ID:"button_correlation_id"},I={COMMIT:"commit",CONTINUE:"continue"},T={SMART_FIELDS:"smart-fields",CARD_FIELD:"card-field",CARD_NUMBER_FIELD:"card-number-field",CARD_CVV_FIELD:"card-cvv-field",CARD_EXPIRY_FIELD:"card-expiry-field",CARD_NAME_FIELD:"card-name-field",CARD_POSTAL_FIELD:"card-postal-field"},O={ERROR:"qr_error",SCANNED:"qr_scanned",AUTHORIZED:"qr_authorized",DEFAULT:"qr_default"},w={DIGITAL:"DIGITAL",DONATION:"DONATION",PHYSICAL:"PHYSICAL"},S={DONATE:"donate"},A={TOO_MANY_REQUESTS:429},D={SERVICE_WORKER_URL:"https://www.paypal.com/checkout-sw",SW_SCOPE:"/webapps/hermes",GET_SW_LOGS_EVENT_NAME:"GET_SW_LOGS",LOGS_CHANNEL_NAME:"logs-channel",GET_SW_LOGS_RESPONSE_EVENT_NAME:"GET_SW_LOGS_RESPONSE"},C={WITH_PURCHASE:"with_purchase",VAULT_WITHOUT_PURCHASE:"vault_without_purchase"},N={HONEY:"honey",UNKNOWN_EVENT:"unknown_event",BUTTON_CLICK:"button_click"}},function(e,n,t){"use strict";t.d(n,"z",(function(){return r.l})),t.d(n,"r",(function(){return r.j})),t.d(n,"b",(function(){return r.b})),t.d(n,"t",(function(){return r.k})),t.d(n,"l",(function(){return r.f})),t.d(n,"a",(function(){return r.a})),t.d(n,"m",(function(){return r.g})),t.d(n,"k",(function(){return r.e})),t.d(n,"o",(function(){return r.i})),t.d(n,"f",(function(){return r.d})),t.d(n,"d",(function(){return r.c})),t.d(n,"e",(function(){return o.a})),t.d(n,"u",(function(){return o.b})),t.d(n,"w",(function(){return o.c})),t.d(n,"g",(function(){return a})),t.d(n,"h",(function(){return u})),t.d(n,"j",(function(){return f})),t.d(n,"i",(function(){return p})),t.d(n,"n",(function(){return h})),t.d(n,"c",(function(){return m})),t.d(n,"v",(function(){return g})),t.d(n,"x",(function(){return v})),t.d(n,"p",(function(){return b})),t.d(n,"q",(function(){return E})),t.d(n,"s",(function(){return k})),t.d(n,"y",(function(){return P}));var r=t(16),o=t(11),i=t(1);function a(){var e="";return document.body&&(e=document.body.getAttribute(""+i.e.NONCE)||""),e}var c=t(9);function u(e){try{for(var n=0,t=Object(c.b)(window);n>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,n={};return Object.freeze(n),e.set(n,"__testvalue__"),"__testvalue__"===e.get(n)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var n=e.prototype;return n._cleanupClosedWindows=function(){for(var e=this.weakmap,n=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var t=e&&e.stack,r=e&&e.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+F(e,n+1)}}function B(e){var n="";return e?e instanceof Error?e.message||n:"string"==typeof e.message&&e.message||n:n}function V(e,n){void 0===n&&(n=Boolean);var t={};for(var r in e)e.hasOwnProperty(r)&&n(e[r],r)&&(t[r]=e[r]);return t}function H(e,n){var t,r;return void 0===n&&(n=50),S((function(){r&&clearTimeout(r);var o=t=t||new g.a;return r=setTimeout((function(){t=null,r=null,g.a.try(e).then((function(e){o.resolve(e)}),(function(e){o.reject(e)}))}),n),o}),w(e)+"::promiseDebounced")}function W(e,n){var t;return function r(){t=setTimeout((function(){e(),r()}),n)}(),{cancel:function(){clearTimeout(t)}}}function G(e){return[].slice.call(e)}function Y(e,n){var t;return void 0===n&&(n=100),S((function(){var r=arguments,o=this;clearTimeout(t),t=setTimeout((function(){return e.apply(o,r)}),n)}),w(e)+"::debounced")}function K(e){var n,t=[],r=!1,o={set:function(n,t){return r||(e[n]=t,o.register((function(){delete e[n]}))),t},register:function(e){var o=U((function(){return e(n)}));return r?e(n):t.push(o),{cancel:function(){var e=t.indexOf(o);-1!==e&&t.splice(e,1)}}},all:function(e){n=e;var o=[];for(r=!0;t.length;){var i=t.shift();o.push(i())}return g.a.all(o).then(M)}};return o}function q(e){var n=[],t={};return function(r){if(-1===n.indexOf(r)){n.push(r);var o=F(r);if(!t[o])return t[o]=!0,e(r)}}}j.clear=function(){R=P},j((function(e){if(Object.values)return Object.values(e);var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(e[t]);return n}));var $=function(e){function n(n){var t;return(t=e.call(this,n)||this).name=t.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t),t.constructor):t.stack=new Error(n).stack,t}return h(n,e),n}(O(Error));function z(){var e=document.body;if(!e)throw new Error("Body element not found");return e}function X(){return Boolean(document.body)&&"complete"===document.readyState}function J(){return Boolean(document.body)&&"interactive"===document.readyState}function Z(e){return encodeURIComponent(e)}var Q=j((function(){return new g.a((function(e){if(X()||J())return e();var n=setInterval((function(){if(X()||J())return clearInterval(n),e()}),10)}))}));function ee(e){return L(ee,(function(){var n={};if(!e)return n;if(-1===e.indexOf("="))return n;for(var t=0,r=e.split("&");t1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function ae(){return Q().then((function(){var e=ie();if(e){var n=e.timing;return n.connectEnd&&n.domInteractive?n.domInteractive-n.connectEnd:void 0}}))}function ce(){return"undefined"!=typeof window&&void 0!==window.location}function ue(e,n){return void 0===n&&(n=window.document),[].slice.call(n.querySelectorAll(e))}function se(e,n){e.addEventListener("touchstart",M,{passive:!0}),e.addEventListener("click",n),e.addEventListener("keypress",(function(e){if(13===e.keyCode||32===e.keyCode)return n(e)}))}function le(){return L(le,(function(){try{if("undefined"==typeof window)return!1;if(window.localStorage){var e=Math.random().toString();window.localStorage.setItem("__test__localStorage__",e);var n=window.localStorage.getItem("__test__localStorage__");if(window.localStorage.removeItem("__test__localStorage__"),e===n)return!0}}catch(e){}return!1}))}var de=function(e){function n(){return e.apply(this,arguments)||this}return h(n,e),n}($);function fe(e,n){var t=(n=n||{}).closeOnUnload,r=void 0===t?1:t,o=n.name,i=void 0===o?"":o,a=n.width,c=n.height,u=0,s=0;a&&(window.outerWidth?s=Math.round((window.outerWidth-a)/2)+window.screenX:window.screen.width&&(s=Math.round((window.screen.width-a)/2))),c&&(window.outerHeight?u=Math.round((window.outerHeight-c)/2)+window.screenY:window.screen.height&&(u=Math.round((window.screen.height-c)/2))),delete n.closeOnUnload,delete n.name,a&&c&&(n=Object(m.a)({top:u,left:s,width:a,height:c,status:1,toolbar:0,menubar:0,resizable:1,scrollbars:1},n));var l,d,f=Object.keys(n).map((function(e){if(null!=n[e])return e+"="+("string"==typeof(t=n[e])?t:t&&t.toString&&"function"==typeof t.toString?t.toString():{}.toString.call(t));var t})).filter(Boolean).join(",");try{l=window.open(e,i,f)}catch(d){throw new de("Can not open popup window - "+(d.stack||d.message))}if(Object(_.h)(l))throw new de("Can not open popup window - blocked");return r&&window.addEventListener("unload",(function(){return l.close()})),l}function pe(e,n){var t=n.tagName.toLowerCase();if("html"!==t)throw new Error("Expected element to be html, got "+t);for(var r=e.document.documentElement,o=0,i=G(r.children);or&&(t=null),t||(t={guid:D(),created:o}),n.__session__=t,e(t)}))}return{getState:i,getID:a,isStateFresh:function(){return a()===o},getSessionState:function(e){return c((function(n){return n.state=n.state||{},e(n.state)}))},getSessionID:function(){return c((function(e){return e.guid}))}}}),[{name:n,lifetime:r}])}function ye(){return Ee({name:"belter_experiment"})}function Ie(e){return ye().getSessionState((function(n){return n.loggedBeacons=n.loggedBeacons||[],-1===n.loggedBeacons.indexOf(e)&&(n.loggedBeacons.push(e),!0)}))}function Te(e){return Math.floor(Math.random()*e)}function Oe(e){var n,t=e.name,r=e.sample,o=void 0===r?50:r,i=e.logTreatment,a=void 0===i?M:i,c=e.logCheckpoint,u=void 0===c?M:c,s=e.sticky,l=void 0===s||s?function(e){return ye().getState((function(n){return n.throttlePercentiles=n.throttlePercentiles||{},n.throttlePercentiles[e]=n.throttlePercentiles[e]||Te(100),n.throttlePercentiles[e]}))}(t):Te(100),d=t+"_"+(n=l=50||o<=l&&l<2*o?"control":"throttle"),f=!1,p=!1;try{window.localStorage&&window.localStorage.getItem(t)&&(p=!0)}catch(e){}var h={isEnabled:function(){return"test"===n||p},isDisabled:function(){return"test"!==n&&!p},getTreatment:function(){return d},log:function(e,n){return void 0===n&&(n={}),f?(Ie(d+"_"+JSON.stringify(n))&&a({name:t,treatment:d,payload:n,throttle:l}),Ie(d+"_"+e+"_"+JSON.stringify(n))&&u({name:t,treatment:d,checkpoint:e,payload:n,throttle:l}),h):h},logStart:function(e){return void 0===e&&(e={}),f=!0,h.log("start",e)},logComplete:function(e){return void 0===e&&(e={}),h.log("complete",e)}};return h}j((function(){var e;try{e=_e()}catch(e){return ve}var n=e.getAttribute("data-uid");if(n&&"string"==typeof n)return n;if((n=e.getAttribute("data-uid-auto"))&&"string"==typeof n)return n;if(e.src){var t=function(e){for(var n="",t=0;t=300){var i,a=new Error(s+" returned status "+n+" (Corr ID: "+r[c.n.PAYPAL_DEBUG_ID]+").\n\n"+JSON.stringify(t));throw a.response={status:n,headers:r,body:t},n===c.y.TOO_MANY_REQUESTS&&Object(u.e)().track(((i={})[o.g.TRANSITION]=c.l.CALL_REST_API,i[c.i.ERR_DESC]="Error: "+n+" - "+t,i[c.i.INFO_MSG]="URL: "+s,i)),f&&Object(u.e)().warn("rest_api_"+f+"_status_"+n+"_error"),a}return t}))}function l(e){var n=e.accessToken,t=e.url,r=e.method,a=void 0===r?"get":r,s=e.headers,l=void 0===s?{}:s,d=e.json,f=e.authenticated,p=void 0===f||f,h=e.eventName;if(l[c.n.REQUESTED_BY]=c.x,p&&!n)throw new Error("Buyer access token not present - can not call smart api: "+t);return n&&(l[c.n.ACCESS_TOKEN]=n),Object(i.H)({url:t,method:a,headers:l,json:d}).then((function(e){var n,r=e.status,i=e.body,s=e.headers;if("contingency"===i.ack){var d=new Error(i.contingency);throw d.response={url:t,method:a,headers:l,body:i},d.data=i.data,Object(u.e)().warn("smart_api_"+h+"_contingency_error"),d}if(r===c.y.TOO_MANY_REQUESTS&&Object(u.e)().track(((n={})[o.g.TRANSITION]=c.l.CALL_REST_API,n[c.i.ERR_DESC]="Error: "+r+" - "+i,n[c.i.INFO_MSG]="URL: "+t,n)),r>400)throw Object(u.e)().warn("smart_api_"+h+"_status_"+r+"_error"),new Error("Api: "+t+" returned status code: "+r+" (Corr ID: "+s[c.n.PAYPAL_DEBUG_ID]+")\n\n"+JSON.stringify(i));if("success"!==i.ack)throw Object(u.e)().warn("smart_api_"+h+"_ack_error"),new Error("Api: "+t+" returned ack: "+i.ack+" (Corr ID: "+s[c.n.PAYPAL_DEBUG_ID]+")\n\n"+JSON.stringify(i));return{data:i.data,headers:s}}))}function d(e){var n=e.name,t=e.query,o=e.variables,s=void 0===o?{}:o,l=e.headers,d=void 0===l?{}:l,f=e.returnErrorObject,p=void 0!==f&&f;return Object(i.H)({url:a.f+"?"+n,method:"POST",json:{query:t,variables:s},headers:Object(r.a)({"x-app-name":c.x},d)}).then((function(e){var t=e.status,r=e.body,o=r.errors||[];if(o.length){var i=o[0].message||JSON.stringify(o[0]);if(Object(u.e)().warn("graphql_"+n+"_error",{err:i}),p)throw o[0];throw new Error(i)}if(200!==t)throw Object(u.e)().warn("graphql_"+n+"_status_"+t+"_error"),new Error(a.f+" returned status "+t+"\n\n"+JSON.stringify(r));return r.data}))}function f(e){return e.headers[c.n.PAYPAL_DEBUG_ID]}function p(e){var n=null==e?void 0:e.response;if(n)return f(n)}},function(e,n,t){"use strict";t.d(n,"g",(function(){return i})),t.d(n,"a",(function(){return a})),t.d(n,"h",(function(){return c})),t.d(n,"i",(function(){return u})),t.d(n,"b",(function(){return s})),t.d(n,"k",(function(){return l})),t.d(n,"l",(function(){return d})),t.d(n,"j",(function(){return f})),t.d(n,"f",(function(){return p})),t.d(n,"m",(function(){return h})),t.d(n,"e",(function(){return m})),t.d(n,"d",(function(){return g})),t.d(n,"c",(function(){return _}));var r,o=t(0),i="/xoplatform/logger/api/logger",a="/v1/oauth2/token",c="/v2/checkout/orders",u="/v1/payments/payment",s="/v1/billing/subscriptions",l="validate-payment-method",d="/v3/vault/setup-tokens",f={AUTH:"/smart/api/auth",CHECKOUT:"/smart/api/checkout",ORDER:"/smart/api/order",PAYMENT:"/smart/api/payment",SUBSCRIPTION:"/smart/api/billagmt/subscriptions",VAULT:"/smart/api/vault"},p="/graphql",h="/checkoutnow",m=((r={})[o.j.PAYPAL]=o.j.PAYPAL,r[o.j.PAYLATER]=o.j.PAYPAL,r[o.j.CREDIT]=o.j.PAYPAL,r),g={APP:"https://www.paypalobjects.com/checkout/js/lib/firebase-app.js",AUTH:"https://www.paypalobjects.com/checkout/js/lib/firebase-auth.js",DATABASE:"https://www.paypalobjects.com/checkout/js/lib/firebase-database.js"},_=!1},function(e,n,t){"use strict";t.d(n,"d",(function(){return c})),t.d(n,"c",(function(){return l})),t.d(n,"f",(function(){return d})),t.d(n,"a",(function(){return f})),t.d(n,"e",(function(){return m})),t.d(n,"b",(function(){return g})),t.d(n,"h",(function(){return b})),t.d(n,"i",(function(){return E})),t.d(n,"j",(function(){return y})),t.d(n,"g",(function(){return I}));var r="Call was rejected by callee.\r\n";function o(e){return void 0===e&&(e=window),e.location.protocol}function i(e){if(void 0===e&&(e=window),e.mockDomain){var n=e.mockDomain.split("//")[0];if(n)return n}return o(e)}function a(e){return void 0===e&&(e=window),"about:"===i(e)}function c(e){if(void 0===e&&(e=window),e)try{if(e.parent&&e.parent!==e)return e.parent}catch(e){}}function u(e){try{return!0}catch(e){}return!1}function s(e){void 0===e&&(e=window);var n=e.location;if(!n)throw new Error("Can not read window location");var t=o(e);if(!t)throw new Error("Can not read window protocol");if("file:"===t)return"file://";if("about:"===t){var r=c(e);return r&&u()?s(r):"about://"}var i=n.host;if(!i)throw new Error("Can not read window host");return t+"//"+i}function l(e){void 0===e&&(e=window);var n=s(e);return n&&e.mockDomain&&0===e.mockDomain.indexOf("mock:")?e.mockDomain:n}function d(e){if(!function(e){try{if(e===window)return!0}catch(e){}try{var n=Object.getOwnPropertyDescriptor(e,"location");if(n&&!1===n.enumerable)return!1}catch(e){}try{if(a(e)&&u())return!0}catch(e){}try{if(function(e){return void 0===e&&(e=window),"mock:"===i(e)}(e)&&u())return!0}catch(e){}try{if(s(e)===s(window))return!0}catch(e){}return!1}(e))return!1;try{if(e===window)return!0;if(a(e)&&u())return!0;if(l(window)===l(e))return!0}catch(e){}return!1}function f(e){if(!d(e))throw new Error("Expected window to be same domain");return e}function p(e,n){if(!e||!n)return!1;var t=c(n);return t?t===e:-1!==function(e){var n=[];try{for(;e.parent!==e;)n.push(e.parent),e=e.parent}catch(e){}return n}(n).indexOf(e)}function h(e){for(var n=[],t=0,r=function(e){var n,t,r=[];try{n=e.frames}catch(t){n=e}try{t=n.length}catch(e){}if(0===t)return r;if(t){for(var o=0;o=0||(o[t]=e[t]);return o}t.d(n,"a",(function(){return r}))},function(e,n,t){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,n,t,r){void 0===r&&(r=t),Object.defineProperty(e,r,{enumerable:!0,get:function(){return n[t]}})}:function(e,n,t,r){void 0===r&&(r=t),e[r]=n[t]}),o=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),i=(this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&r(n,e,t);return o(n,e),n})(t(42)),a=t(50),c=t(51),u=t(53),s=t(44),l=t(36),d=t(56),f=t(57);e.exports={creditCardType:i,cardholderName:a.cardholderName,number:c.cardNumber,expirationDate:u.expirationDate,expirationMonth:s.expirationMonth,expirationYear:l.expirationYear,cvv:d.cvv,postalCode:f.postalCode}},function(e,n,t){"use strict";var r=t(18);t.d(n,"getProps",(function(){return r.a})),t(24);var o=t(32);t.d(n,"getConfirmOrder",(function(){return o.a})),t(22),t(23),t(31),t(25),t(26),t(19),t(27),t(10),t(28),t(29),t(20),t(21);var i=t(37);t.d(n,"POPUP_BRIDGE_OPTYPE",(function(){return i.a})),t(38),t(39),t(30),t(40),t(41)},function(e,n,t){"use strict";t.d(n,"l",(function(){return l})),t.d(n,"j",(function(){return d})),t.d(n,"b",(function(){return f})),t.d(n,"k",(function(){return p})),t.d(n,"h",(function(){return h})),t.d(n,"f",(function(){return m})),t.d(n,"a",(function(){return g})),t.d(n,"g",(function(){return _})),t.d(n,"e",(function(){return v})),t.d(n,"i",(function(){return b})),t.d(n,"d",(function(){return E})),t.d(n,"c",(function(){return y}));var r=t(6),o=t(4),i=t(3),a=t(0),c=t(9),u=t(1),s=t(11);function l(){return new o.a(i.x)}function d(){return o.a.resolve()}function f(){var e=document.body;if(!e)throw new Error("Document body not found");return e}function p(e){var n=document.createElement("img");n.src=e,n.style.visibility="hidden",n.style.position="absolute",document.body&&document.body.appendChild(n)}function h(e){return new o.a((function(n,t){var r=document.body||document.head;if(!r)return t(new Error("Can not find container for script: "+e));var o=document.createElement("script");o.setAttribute("src",e),o.addEventListener("load",(function(){return n(o)})),o.addEventListener("error",(function(e){return t(e)})),r.appendChild(o)}))}function m(e){return Boolean(e.match(/^.+@.+\..+$/))}function g(e,n){var t=n.sample,o=n.sticky,c=void 0===o||o,l=Object(s.a)();return Object(i.g)({name:e,sample:t,logTreatment:function(n){var t,o=n.treatment,i=n.payload,c=Object(r.a)(((t={})[a.g.STATE]=u.k.PXP,t[a.g.TRANSITION]=u.l.PXP,t[a.g.EXPERIMENT_NAME]=e,t[a.g.TREATMENT_NAME]=o,t),i);l.track(c),l.flush()},logCheckpoint:function(e){var n=e.payload,t=e.throttle;l.info(e.treatment+"_"+e.checkpoint,Object(r.a)({},n,{throttle:t.toString()})),l.flush()},sticky:c})}function _(){return Object(i.u)()&&Object(i.v)()}function v(){return Object(i.o)()&&Object(i.q)()}function b(e,n,t,r){void 0===t&&(t=1e3),void 0===r&&(r=1/0);var o=!1,i=function(){o=!0};return e.awaitWindow().then((function(e){o||(i=Object(c.j)(e,n,t,r).cancel)})),{cancel:i}}function E(){if(window.performance){var e=window.performance.now(),n=(new Date).getTime();return window.performance.timeOrigin||window.performance.timing.navigationStart||n-e}throw new Error("window.performance not supported")}function y(){try{return String((new Date).getTime())}catch(e){return"invalid_timestamp"}}},function(e,n,t){e.exports=t(58)},function(e,n,t){"use strict";t.d(n,"a",(function(){return u})),t(0);var r=t(4),o=t(2),i=t(19),a=t(20),c=t(21);function u(e){var n=e.branded,t=e.enableOrdersApprovalSmartWallet,u=e.smartWalletOrderID,s=window.xprops,l=s.uid,d=s.env,f=s.vault,p=void 0!==f&&f,h=s.commit,m=s.locale,g=s.platform,_=s.sessionID,v=s.clientID,b=s.partnerAttributionID,E=s.merchantRequestedPopupsDisabled,y=s.clientMetadataID,I=s.sdkCorrelationID,T=s.getParentDomain,O=s.clientAccessToken,w=s.getPopupBridge,S=s.getPrerenderDetails,A=s.getPageUrl,D=s.enableThreeDomainSecure,C=s.enableVaultInstallments,N=s.enableNativeCheckout,k=void 0!==N&&N,P=s.remember,R=s.stageHost,j=s.apiStageHost,L=s.getParent,M=s.fundingSource,U=s.currency,x=s.connect,F=s.intent,B=s.merchantID,V=s.amount,H=s.userIDToken,W=s.enableFunding,G=s.disableFunding,Y=s.disableCard,K=s.disableAutocomplete,q=s.wallet,$=s.paymentMethodToken,z=void 0===$?s.paymentMethodNonce:$,X=s.getQueriedEligibleFunding,J=void 0===X?function(){return r.a.resolve([])}:X,Z=s.storageID,Q=s.applePay,ee=s.userExperienceFlow,ne=s.allowBillingPayments,te=s.paymentRequest,re=s.disableSetCookie,oe=void 0!==re&&re,ie=Object(i.a)({onInit:s.onInit}),ae="function"==typeof T?T():"unknown";W=W||[],G=G||[];var ce=Object(a.a)({onClick:s.onClick}),ue=Z&&Object(o.n)()?Z:Object(o.i)();return{uid:l,env:d,vault:p,commit:h,clientAccessToken:O,locale:m,sessionID:_,clientID:v,partnerAttributionID:b,clientMetadataID:y,sdkCorrelationID:I,merchantDomain:ae,platform:g,currency:U,intent:F,wallet:q,merchantRequestedPopupsDisabled:E,getPopupBridge:w,getPrerenderDetails:S,getPageUrl:A,rememberFunding:P,getParent:L,connect:x,fundingSource:M,enableFunding:W,disableFunding:G,disableCard:Y,disableAutocomplete:K,getQueriedEligibleFunding:J,amount:V,userIDToken:H,enableThreeDomainSecure:D,enableNativeCheckout:k,enableVaultInstallments:C,onClick:ce,onInit:ie,onError:Object(c.a)({onError:s.onError}),stageHost:R,apiStageHost:j,standaloneFundingSource:M,paymentMethodToken:z,branded:n,stickinessID:ue,applePay:Q,userExperienceFlow:ee,allowBillingPayments:ne,paymentRequest:te,merchantID:B,enableOrdersApprovalSmartWallet:t,smartWalletOrderID:u,disableSetCookie:oe}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return o}));var r=t(4);function o(e){var n=e.onInit;return function(e){var t=!0;return{initPromise:r.a.try((function(){if(n)return n(e,(o=function(e){t=e},{enable:function(){return r.a.try((function(){return o(!0)}))},disable:function(){return r.a.try((function(){return o(!1)}))}}));var o})),isEnabled:function(){return t}}}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return i}));var r=t(4),o=(t(0),t(3));function i(e){var n=e.onClick;if(n)return Object(o.w)((function(e){var t;return n((t={fundingSource:e.fundingSource},{fundingSource:t.fundingSource}),{resolve:function(){return r.a.try((function(){return!0}))},reject:function(){return r.a.try((function(){return!1}))}}).then((function(e){return!1!==e}))}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return i}));var r=t(4),o=t(3);function i(e){var n=e.onError,t=n?Object(o.e)(n):o.x;return function(e){return r.a.try((function(){return t(e)}))}}},function(e,n,t){"use strict";function r(e){var n=e.createBillingAgreement,t=e.paymentSource;if(n)return function(){return n((e={paymentSource:t},{paymentSource:e.paymentSource}),{}).then((function(e){if(!e||"string"!=typeof e)throw new Error("Expected a billing token to be passed to createBillingAgreement");return e}));var e}}t.d(n,"a",(function(){return r})),t(0)},function(e,n,t){"use strict";t.d(n,"a",(function(){return i})),t(0);var r=t(5),o=t(2);function i(e,n){var t=e.createSubscription,i=e.partnerAttributionID,a=e.merchantID,c=e.clientID,u=e.paymentSource,s=n.facilitatorAccessToken;if(t)return a&&a[0]&&(Object(o.e)().info("src_props_subscriptions_recreate_access_token_cache"),Object(r.h)(c,{targetSubject:a[0]})),function(){return t((e={paymentSource:u},{paymentSource:e.paymentSource}),function(e){var n=e.facilitatorAccessToken,t=e.partnerAttributionID,o=e.merchantID,i=e.clientID;return{subscription:{create:function(e){return Object(r.k)(n,e,{partnerAttributionID:t,merchantID:o,clientID:i})},revise:function(e,a){return Object(r.L)(n,e,a,{partnerAttributionID:t,merchantID:o,clientID:i})}}}}({facilitatorAccessToken:s,partnerAttributionID:i,merchantID:a,clientID:c})).then((function(e){if(!e||"string"!=typeof e)throw new Error("Expected an subscription id to be passed to createSubscription");return e}));var e}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return p}));var r=t(6),o=t(4),i=t(3),a=t(0),c=t(9),u=t(5),s=t(1),l=t(2),d=t(8),f=t(33);function p(e,n){var t=e.createOrder,p=e.intent,h=e.currency,m=n.createBillingAgreement,g=n.createSubscription,_=n.enableOrdersApprovalSmartWallet,v=n.smartWalletOrderID,b=n.createVaultSetupToken,E=n.flow,y={paymentSource:e.paymentSource},I=function(e){var n=e.facilitatorAccessToken,t=e.intent,o=e.currency,i=e.merchantID,s=e.partnerAttributionID,f=function(e){var n=e.facilitatorAccessToken,t=e.intent,o=e.currency,i=e.merchantID,c=e.partnerAttributionID;return{create:function(e){var s=Object(r.a)({},e);if(s.intent&&s.intent.toLowerCase()!==t)throw new Error("Unexpected intent: "+s.intent+" passed to order.create. Please ensure you are passing /sdk/js?"+a.n.INTENT+"="+s.intent.toLowerCase()+" in the paypal script tag.");return(s=Object(r.a)({},s,{intent:t.toUpperCase()})).purchase_units=s.purchase_units.map((function(e){if(e.amount.currency_code&&e.amount.currency_code!==o)throw new Error("Unexpected currency: "+e.amount.currency_code+" passed to order.create. Please ensure you are passing /sdk/js?"+a.n.CURRENCY+"="+e.amount.currency_code+" in the paypal script tag.");var n=e.payee;if(i&&1===i.length&&i[0]){var t=i[0];n=Object(l.l)(t)?Object(r.a)({},n,{email_address:t}):Object(r.a)({},n,{merchant_id:t})}return Object(r.a)({},e,{payee:n,amount:Object(r.a)({},e.amount,{currency_code:o})})})),s.application_context=s.application_context||{},Object(u.i)(s,{facilitatorAccessToken:n,partnerAttributionID:c,forceRestAPI:!1})}}}({facilitatorAccessToken:n,intent:t,currency:o,merchantID:i,partnerAttributionID:s}),p=function(e){var n=e.facilitatorAccessToken,t=e.intent,o=e.currency,i=e.merchantID,s=e.partnerAttributionID;return{create:function(e){var d=Object(r.a)({},e),f=t===a.k.CAPTURE?"sale":t;if(d.intent&&d.intent!==f)throw new Error("Unexpected intent: "+d.intent+" passed to order.create. Expected "+f);return(d=Object(r.a)({},d,{intent:f})).transactions=d.transactions.map((function(e){if(e.amount.currency&&e.amount.currency!==o)throw new Error("Unexpected currency: "+e.amount.currency+" passed to order.create. Please ensure you are passing /sdk/js?"+a.n.CURRENCY+"="+e.amount.currency+" in the paypal script tag.");var n=e.payee;if(i&&1===i.length&&i[0]){var t=i[0];n=Object(l.l)(t)?Object(r.a)({},n,{email_address:t}):Object(r.a)({},n,{merchant_id:t})}return Object(r.a)({},e,{payee:n,amount:Object(r.a)({},e.amount,{currency:o})})})),d.redirect_urls=d.redirect_urls||{},d.redirect_urls.return_url=d.redirect_urls.return_url||Object(c.c)()+"/checkoutnow/error",d.redirect_urls.cancel_url=d.redirect_urls.cancel_url||Object(c.c)()+"/checkoutnow/error",d.payer=d.payer||{},d.payer.payment_method=d.payer.payment_method||"paypal",Object(u.j)(d,{facilitatorAccessToken:n,partnerAttributionID:s})}}}({facilitatorAccessToken:n,intent:t,currency:o,merchantID:i,partnerAttributionID:s});return{order:f,payment:d.c?p:null}}({facilitatorAccessToken:n.facilitatorAccessToken,intent:p,currency:h,merchantID:e.merchantID,partnerAttributionID:e.partnerAttributionID}),T="server-side";return Object(i.w)((function(){var e=Object(i.j)("orderID");if(e)return o.a.resolve(e);if(_&&v)return o.a.resolve(v);var n=Date.now();return o.a.try((function(){return"vault_without_purchase"===E&&b?b().then(f.b):m?m().then(u.d):g?g().then(u.M):t?t(y,I):(T="client-side",I.order.create({purchase_units:[{amount:{currency_code:h,value:"0.01"}}]}))})).catch((function(e){var n;throw Object(l.u)({name:"pp.app.paypal_sdk.buttons.create_order.error.count",dimensions:{errorName:"generic",flow:E,intent:p,integrationType:T}}),Object(l.e)().error("create_order_error",{err:Object(i.K)(e)}).track(((n={})[a.g.STATE]=s.k.BUTTON,n[a.g.ERROR_CODE]="smart_buttons_create_order_error",n[a.g.ERROR_DESC]=Object(i.K)(e),n)),e})).then((function(e){var t,r,o;if(!e||"string"!=typeof e)throw Object(l.u)({name:"pp.app.paypal_sdk.buttons.create_order.error.count",dimensions:{errorName:"no_order_id",flow:E,intent:p,integrationType:T}}),Object(l.e)().track(((r={})[a.g.STATE]=s.k.BUTTON,r[a.g.ERROR_CODE]="smart_buttons_create_order_error",r[a.g.ERROR_DESC]="Expected an order id to be passed",r)),new Error("Expected an order id to be passed");if(0===e.indexOf("PAY-")||0===e.indexOf("PAYID-"))throw Object(l.u)({name:"pp.app.paypal_sdk.buttons.create_order.error.count",dimensions:{errorName:"pay_id",flow:E,intent:p,integrationType:T}}),Object(l.e)().track(((o={})[a.g.STATE]=s.k.BUTTON,o[a.g.ERROR_CODE]="smart_buttons_create_order_error",o[a.g.ERROR_DESC]="Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead",o)),new Error("Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead");var i=Date.now()-n;return Object(l.u)({name:"pp.app.paypal_sdk.buttons.create_order.count",dimensions:{flow:E,intent:p,integrationType:T}}),Object(l.e)().addPayloadBuilder((function(){return{token:e}})).addTrackingBuilder((function(){var n;return(n={})[a.g.CONTEXT_TYPE]=s.h.ORDER_ID,n[a.g.CONTEXT_ID]=e,n[a.g.TOKEN]=e,n})).track((t={},t[a.g.STATE]=s.k.BUTTON,t[a.g.TRANSITION]=s.l.RECEIVE_ORDER,t[a.g.EVENT_NAME]=s.l.RECEIVE_ORDER,t[a.g.CONTEXT_TYPE]=s.h.ORDER_ID,t[s.f.BUTTON_WIDTH]=window.innerWidth,t[a.g.CONTEXT_ID]=e,t[a.g.TOKEN]=e,t[a.g.RESPONSE_DURATION]=i.toString(),t.client_time=Object(l.d)(),t)).flush(),e}))}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return p}));var r=t(6),o=t(4),i=t(3),a=t(0),c=t(5),u=t(1),s=t(2),l=t(8),d=function(e){if(!e)throw new Error("Expected redirect url");if(-1===e.indexOf("://"))throw Object(s.e)().warn("redir_url_non_scheme",{url:e}).flush(),new Error("Invalid redirect url: "+e+" - must be fully qualified url");return e.match(/^https?:\/\//)||Object(s.e)().warn("redir_url_non_http",{url:e}).flush(),Object(i.G)(e,window.top)},f=function(e,n,t){if(Object(c.E)(e))return e&&e.response&&(e.message=JSON.stringify(e.response)||e.message),t(e).then(s.z);if(Object(c.D)(e))return n().then(s.z);throw e};function p(e){var n=e.intent,t=e.createBillingAgreement,p=e.createSubscription,h=e.onApprove,m=e.partnerAttributionID,g=e.onError,_=e.clientAccessToken,v=e.vault,b=e.clientID,E=e.facilitatorAccessToken,y=e.branded,I=e.createOrder,T=e.paymentSource,O=e.featureFlags,w=e.createVaultSetupToken,S=e.flow,A=e.experiments,D=function(){Object(s.u)({name:"pp.app.paypal_sdk.buttons.click.success.count",dimensions:Object(r.a)({spbPaymentFlow:S},A)})};if(S&&"vault_without_purchase"===S&&w)return function(e){var n=e.onApprove,t=e.onError,r=e.facilitatorAccessToken,c=e.createOrder,l=e.paymentSource,d=e.createVaultSetupToken,f=e.beforeOnApprove;if(!n)throw new Error("Expected onApprove");return Object(i.w)((function(e){var i=e.payerID;return c().then((function(e){var c;return Object(s.e)().info("button_approve").track((c={},c[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,c[a.g.EVENT_NAME]=u.l.CHECKOUT_APPROVE,c[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,c[a.g.TOKEN]=e,c[a.g.CONTEXT_ID]=e,c)).flush(),d().then((function(e){var a={payerID:i,facilitatorAccessToken:r,paymentSource:l,vaultSetupToken:e};return f(),n(a).catch((function(e){return o.a.try((function(){return t(e)})).then((function(){throw e}))}))}))}))}))}({onApprove:h,onError:g,facilitatorAccessToken:E,createOrder:I,paymentSource:T,createVaultSetupToken:w,beforeOnApprove:D});if(t)return function(e){var n=e.onApprove,t=void 0===n?function(){throw new Error("Expected onApprove")}:n,r=e.onError,l=e.facilitatorAccessToken,f=e.createOrder,p=e.paymentSource,h=e.beforeOnApprove;if(!t)throw new Error("Expected onApprove");return Object(i.w)((function(e,n){var i=e.payerID,m=e.paymentID,g=e.billingToken,_=n.restart;return f().then((function(e){var n;return Object(s.e)().info("button_approve").track((n={},n[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,n[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,n[a.g.TOKEN]=e,n[a.g.CONTEXT_ID]=e,n)).flush(),Object(c.C)(e).then((function(n){var a={orderID:e,payerID:i,paymentID:m=m||n&&n.checkoutSession&&n.checkoutSession.cart&&n.checkoutSession.cart.paymentId,billingToken:g=g||n&&n.checkoutSession&&n.checkoutSession.cart&&n.checkoutSession.cart.billingToken,facilitatorAccessToken:l,paymentSource:p},c={restart:_,redirect:d};return h(),t(a,c).catch((function(e){return o.a.try((function(){return r(e)})).then((function(){throw e}))}))}))}))}))}({onApprove:h,onError:g,facilitatorAccessToken:E,createOrder:I,paymentSource:T,beforeOnApprove:D});if(n===a.k.SUBSCRIPTION||p)return function(e){var n=e.onApprove,t=void 0===n?function(){throw new Error("Expected onApprove")}:n,r=e.onError,l=e.facilitatorAccessToken,f=e.createOrder,p=e.paymentSource,h=e.beforeOnApprove;if(!t)throw new Error("Expected onApprove");return Object(i.w)((function(e,n){var m=e.payerID,g=e.subscriptionID,_=e.buyerAccessToken,v=n.restart;if(!g)throw new Error("Expected subscriptionID");return f().then((function(e){var n;Object(s.e)().info("button_approve").track((n={},n[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,n[a.g.EVENT_NAME]=u.l.CHECKOUT_APPROVE,n[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,n[a.g.TOKEN]=e,n[a.g.CONTEXT_ID]=e,n)).flush();var f={orderID:e,payerID:m,subscriptionID:g,facilitatorAccessToken:l,paymentSource:p},b=function(e){var n=e.restart,t=e.subscriptionID,r=e.buyerAccessToken;return{subscription:{get:Object(i.w)((function(){if(!t)throw new Error("No subscription ID present");return Object(c.B)(t,{buyerAccessToken:r})})),activate:Object(i.w)((function(){if(!t)throw new Error("No subscription ID present");return Object(c.a)(t,{buyerAccessToken:r})}))},restart:n,redirect:d}}({restart:v,subscriptionID:g,buyerAccessToken:_});return h(),t(f,b).catch((function(e){return o.a.try((function(){return r(e)})).then((function(){throw e}))}))}))}))}({clientID:b,onApprove:h,onError:g,facilitatorAccessToken:E,createOrder:I,paymentSource:T,beforeOnApprove:D});if(n===a.k.CAPTURE||n===a.k.AUTHORIZE||n===a.k.ORDER)return function(e){var n=e.intent,t=e.onApprove,r=void 0===t?function(e){return function(n,t){if(e===a.k.CAPTURE)return t.order.capture().then(i.x);if(e===a.k.AUTHORIZE)return t.order.authorize().then(i.x);throw new Error("Unsupported intent for auto-capture: "+e)}}(n):t,p=e.partnerAttributionID,h=e.onError,m=e.clientAccessToken,g=e.vault,_=e.facilitatorAccessToken,v=e.branded,b=e.createOrder,E=e.paymentSource,y=e.featureFlags,I=e.experiments,T=e.beforeOnApprove;if(!r)throw new Error("Expected onApprove");return Object(i.w)((function(e,t){var O=e.payerID,w=e.paymentID,S=e.billingToken,A=e.buyerAccessToken,D=e.authCode,C=e.forceRestAPI,N=void 0===C?y.isLsatUpgradable:C,k=t.restart;return b().then((function(e){var t;return Object(s.e)().info("button_approve").track((t={},t[a.g.STATE]=u.k.BUTTON,t[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,t[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,t[a.g.TOKEN]=e,t[a.g.CONTEXT_ID]=e,t)).flush(),S||m||g||!O&&v&&Object(s.e)().warn("onapprove_payerid_not_present_for_branded_standalone_button",{orderID:e}).flush(),Object(c.C)(e).then((function(t){S=S||t&&t.checkoutSession&&t.checkoutSession.cart&&t.checkoutSession.cart.billingToken,w=w||t&&t.checkoutSession&&t.checkoutSession.cart&&t.checkoutSession.cart.paymentId,I.btSdkOrdersV2Migration&&!w&&(w=e.replace(/EC-/,""));var u={orderID:e,payerID:O,paymentID:w,billingToken:S,facilitatorAccessToken:_,authCode:D,paymentSource:E},s=function(e){var n=e.intent,t=e.orderID,r=e.paymentID,o=e.payerID,u=e.restart,s=e.facilitatorAccessToken,p=e.buyerAccessToken,h=e.partnerAttributionID,m=e.forceRestAPI,g=e.onError,_=function(e){var n=e.intent,t=e.orderID,r=e.restart,o=e.facilitatorAccessToken,u=e.buyerAccessToken,s=e.partnerAttributionID,l=e.forceRestAPI,d=e.onError,p=Object(i.w)((function(){return Object(c.x)(t,{facilitatorAccessToken:o,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l})})),h=Object(i.w)((function(){if(n!==a.k.CAPTURE)throw new Error("Use "+a.n.INTENT+"="+a.k.CAPTURE+" to use client-side capture");return Object(c.f)(t,{facilitatorAccessToken:o,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l}).finally(p.reset).finally(h.reset).catch((function(e){return f(e,r,d)}))})),m=Object(i.w)((function(){if(n!==a.k.AUTHORIZE)throw new Error("Use "+a.n.INTENT+"="+a.k.AUTHORIZE+" to use client-side authorize");return Object(c.c)(t,{facilitatorAccessToken:o,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l}).finally(p.reset).finally(m.reset).catch((function(e){return f(e,r,d)}))}));return{capture:h,authorize:m,patch:function(e){return void 0===e&&(e={}),Object(c.I)(t,e,{facilitatorAccessToken:o,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l}).catch((function(){throw new Error("Order could not be patched")}))},get:p}}({intent:n,orderID:t,paymentID:r,payerID:o,restart:u,facilitatorAccessToken:s,buyerAccessToken:p,partnerAttributionID:h,forceRestAPI:m,onError:g}),v=function(e){var n=e.intent,t=e.paymentID,r=e.payerID,o=e.restart,u=e.facilitatorAccessToken,s=e.buyerAccessToken,l=e.partnerAttributionID,d=e.onError;if(t){var p=Object(i.w)((function(){return Object(c.y)(t,{facilitatorAccessToken:u,buyerAccessToken:s,partnerAttributionID:l})})),h=Object(i.w)((function(){if(!r)throw new Error("payerID required for payment execute");if(n!==a.k.CAPTURE)throw new Error("Use "+a.n.INTENT+"="+a.k.CAPTURE+" to use client-side capture");return Object(c.o)(t,r,{facilitatorAccessToken:u,buyerAccessToken:s,partnerAttributionID:l}).finally(p.reset).finally(h.reset).catch((function(e){return f(e,o,d)}))}));return{execute:h,patch:function(e){return void 0===e&&(e={}),Object(c.J)(t,e,{facilitatorAccessToken:u,buyerAccessToken:s,partnerAttributionID:l}).catch((function(){throw new Error("Order could not be patched")}))},get:p}}}({intent:n,orderID:t,paymentID:r,payerID:o,restart:u,facilitatorAccessToken:s,buyerAccessToken:p,partnerAttributionID:h,forceRestAPI:m,onError:g});return{order:_,payment:l.c?v:null,restart:u,redirect:d}}({orderID:e,paymentID:w,payerID:O,intent:n,restart:k,facilitatorAccessToken:_,buyerAccessToken:A,partnerAttributionID:p,forceRestAPI:N,onError:h});return T(),r(u,s).catch((function(e){return o.a.try((function(){return h(e)})).then((function(){throw e}))}))}))}))}))}({intent:n,onApprove:h,partnerAttributionID:m,onError:g,clientAccessToken:_,vault:v,facilitatorAccessToken:E,branded:y,createOrder:I,paymentSource:T,featureFlags:O,experiments:A,beforeOnApprove:D});if(n===a.k.TOKENIZE)return function(e){var n=e.onApprove,t=void 0===n?function(){throw new Error("Expected onApprove")}:n,r=e.onError,c=e.facilitatorAccessToken,l=e.paymentSource,f=e.beforeOnApprove;if(!t)throw new Error("Expected onApprove");return Object(i.w)((function(e,n){var i,p=e.paymentMethodToken,h=n.restart;if(!p)throw new Error("Payment method token required for tokenize onApprove");Object(s.e)().info("button_approve").track((i={},i[a.g.TRANSITION]=u.l.TOKENIZE_APPROVE,i)).flush();var m={facilitatorAccessToken:c,paymentMethodToken:p,paymentSource:l},g={restart:h,redirect:d};return f(),t(m,g).catch((function(e){return o.a.try((function(){return r(e)})).then((function(){throw e}))}))}))}({onApprove:h,onError:g,facilitatorAccessToken:E,paymentSource:T,beforeOnApprove:D});throw new Error("Unsupported intent: "+n)}},function(e,n,t){"use strict";t.d(n,"a",(function(){return l}));var r=t(4),o=t(3),i=t(0),a=t(2),c=t(1),u=t(5),s=function(e){if(!e)throw new Error("Expected redirect url");if(-1===e.indexOf("://"))throw Object(a.e)().warn("redir_url_non_scheme",{url:e}).flush(),new Error("Invalid redirect url: "+e+" - must be fully qualified url");return e.match(/^https?:\/\//)||Object(a.e)().warn("redir_url_non_http",{url:e}).flush(),Object(o.G)(e,window.top)};function l(e){var n=e.intent,t=e.onComplete,l=e.partnerAttributionID,d=e.onError,f=e.facilitatorAccessToken,p=e.createOrder,h=e.featureFlags;return t?Object(o.w)((function(e){var m=e.buyerAccessToken,g=e.forceRestAPI,_=void 0===g?h.isLsatUpgradable:g;return p().then((function(e){var p;Object(a.e)().info("button_complete").track((p={},p[i.g.TRANSITION]=c.l.CHECKOUT_COMPLETE,p[i.g.EVENT_NAME]=c.l.CHECKOUT_COMPLETE,p[i.g.CONTEXT_TYPE]=c.h.ORDER_ID,p[i.g.TOKEN]=e,p[i.g.CONTEXT_ID]=e,p)).flush();var h=function(e){var n=e.orderID,t=e.facilitatorAccessToken,r=e.buyerAccessToken,i=e.partnerAttributionID,a=e.forceRestAPI,c=Object(o.w)((function(){return Object(u.x)(n,{facilitatorAccessToken:t,buyerAccessToken:r,partnerAttributionID:i,forceRestAPI:a}).finally(c.reset)}));return{order:{get:c},redirect:s}}({orderID:e,facilitatorAccessToken:f,buyerAccessToken:m,partnerAttributionID:l,forceRestAPI:_,onError:d});return t({orderID:e,intent:n},h).catch((function(e){return r.a.try((function(){return d(e)})).then((function(){throw e}))}))}))})):a.r}},function(e,n,t){"use strict";t.d(n,"a",(function(){return c}));var r=t(3),o=(t(4),t(0)),i=t(2),a=t(1);function c(e,n){var t=e.onCancel,c=void 0===t?i.r:t,u=e.onError,s=n.createOrder;return Object(r.w)((function(){return s().then((function(e){var n;return Object(i.e)().info("button_cancel").track((n={},n[o.g.TRANSITION]=a.l.CHECKOUT_CANCEL,n[o.g.EVENT_NAME]=a.l.CHECKOUT_CANCEL,n[o.g.CONTEXT_TYPE]=a.h.ORDER_ID,n[o.g.TOKEN]=e,n[o.g.CONTEXT_ID]=e,n)).flush(),c({orderID:{orderID:e}.orderID},{redirect:function(e){if(!e)throw new Error("Expected redirect url");if(-1===e.indexOf("://"))throw Object(i.e)().warn("redir_url_non_scheme",{url:e}).flush(),new Error("Invalid redirect url: "+e+" - must be fully qualified url");return e.match(/^https?:\/\//)||Object(i.e)().warn("redir_url_non_http",{url:e}).flush(),Object(r.G)(e,window.top)}})})).catch((function(e){return u(e)}))}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return p}));var r=t(34),o=t(6),i=t(13),a=(t(4),t(0)),c=t(5),u=t(1),s=t(2),l=t(10),d=t(12),f=["amount","buyerAccessToken","event","forceRestAPI","shipping_address"];function p(e,n){var t=e.onShippingAddressChange,p=e.clientID,h=n.createOrder;if(t)return function(e,n){var m=Object(o.a)({},(Object(r.a)(e),e));return h().then((function(e){var r;return Object(s.e)().info("button_shipping_address_change").track((r={},r[a.g.TRANSITION]=u.l.CHECKOUT_SHIPPING_ADDRESS_CHANGE,r[a.g.EVENT_NAME]=u.l.CHECKOUT_SHIPPING_ADDRESS_CHANGE,r[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,r[a.g.TOKEN]=e,r[a.g.CONTEXT_ID]=e,r[u.i.SHIPPING_CALLBACK_INVOKED]="1",r)).flush(),t(function(e){var n=e.shipping_address,t=Object(i.a)(e,f);return Object(o.a)({errors:l.c,shippingAddress:n},t)}(m),function(e){var n,t,r=e.clientID,o=e.data,i=e.actions,a=e.orderID,u={},s=(null==(n=o.amount)?void 0:n.breakdown)||{};if(0===Object.keys(s).length)throw new Error("Must pass amount with breakdown into data attribute for onShippingAddressChange callback.");var f={reject:i.reject?function(e){return-1===Object.values(l.c).indexOf(e)?i.reject(l.a):i.reject(e)}:function(){throw new Error("Missing reject action callback")},updateTax:function(e){var n,r=e.tax;return s=Object(d.a)({breakdown:s,updatedAmounts:{tax_total:r}}),t=Object(d.b)({breakdown:s,updatedAmounts:{tax_total:r}}),u[l.b.AMOUNT]={op:"replace",path:l.b.AMOUNT,value:{value:""+t,currency_code:null==o||null==(n=o.amount)?void 0:n.currency_code,breakdown:s}},f},updateShippingOptions:function(e){var n,r,i=e.options,a=i.filter((function(e){return!0===e.selected})),c=a&&a.length>0?null==(n=a[0])||null==(n=n.amount)?void 0:n.value:"0.00";return s=Object(d.a)({breakdown:s,updatedAmounts:{shipping:c}}),t=Object(d.b)({breakdown:s,updatedAmounts:{shipping:c}}),u[l.b.AMOUNT]={op:"replace",path:l.b.AMOUNT,value:{value:""+t,currency_code:null==o||null==(r=o.amount)?void 0:r.currency_code,breakdown:s}},u[l.b.OPTIONS]={op:(null==o?void 0:o.event)||"replace",path:l.b.OPTIONS,value:i},f},updateShippingDiscount:function(e){var n,r=e.discount;return t=Object(d.b)({breakdown:s,updatedAmounts:{shipping_discount:r}}),s=Object(d.a)({breakdown:s,updatedAmounts:{shipping_discount:r}}),u[l.b.AMOUNT]={op:"replace",path:l.b.AMOUNT,value:{value:""+t,currency_code:null==o||null==(n=o.amount)?void 0:n.currency_code,breakdown:s}},f},patch:function(){return Object(c.z)(a).then((function(e){var n,t,o=(null==e||null==(n=e.checkoutSession)||null==(n=n.cart)?void 0:n.shippingMethods)||[];return t=Boolean(o.length>0)?Object(d.d)({queries:u}):Object(d.c)({queries:u}),Object(c.K)({clientID:r,orderID:a,data:t}).catch((function(){throw new Error("Order could not be patched")}))}))},query:function(){return Object(c.z)(a).then((function(e){var n,t=(null==e||null==(n=e.checkoutSession)||null==(n=n.cart)?void 0:n.shippingMethods)||[];return Boolean(t.length>0)?Object(d.d)({queries:u}):Object(d.c)({queries:u})}))}};return f}({clientID:p,data:m,actions:n,orderID:e}))}))}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return p}));var r=t(34),o=t(6),i=t(13),a=(t(4),t(0)),c=t(5),u=t(1),s=t(2),l=t(10),d=t(12),f=["amount","buyerAccessToken","event","forceRestAPI","options","selected_shipping_option"];function p(e,n){var t=e.onShippingOptionsChange,p=e.clientID,h=n.createOrder;if(t)return function(e,n){var m=Object(o.a)({},(Object(r.a)(e),e));return h().then((function(e){var r;return Object(s.e)().info("button_shipping_options_change").track((r={},r[a.g.TRANSITION]=u.l.CHECKOUT_SHIPPING_OPTIONS_CHANGE,r[a.g.EVENT_NAME]=u.l.CHECKOUT_SHIPPING_OPTIONS_CHANGE,r[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,r[a.g.TOKEN]=e,r[a.g.CONTEXT_ID]=e,r[u.i.SHIPPING_CALLBACK_INVOKED]="1",r)).flush(),t(function(e){var n=e.selected_shipping_option,t=Object(i.a)(e,f);return Object(o.a)({errors:l.d,selectedShippingOption:n},t)}(m),function(e){var n,t,r=e.clientID,o=e.data,i=e.actions,a=e.orderID,u={},s=(null==(n=o.amount)?void 0:n.breakdown)||{};if(0===Object.keys(s).length)throw new Error("Must pass breakdown into data attribute for onShippingAddressChange callback.");var f={reject:i.reject?function(e){return-1===Object.values(l.d).indexOf(e)?i.reject(l.a):i.reject(e)}:function(){throw new Error("Missing reject action callback")},updateShippingOption:function(e){var n=e.option;if(n&&o.options){var r,i,a,c=null==n||null==(r=n.amount)?void 0:r.value,p=Object(d.e)({option:n,options:o.options});t=Object(d.b)({breakdown:(null==o||null==(i=o.amount)?void 0:i.breakdown)||{},updatedAmounts:{shipping:c}}),s=Object(d.a)({breakdown:s,updatedAmounts:{shipping:c}}),p&&p.length>0&&(u[l.b.OPTIONS]={op:(null==o?void 0:o.event)||"replace",path:l.b.OPTIONS,value:p}),u[l.b.AMOUNT]={op:"replace",path:l.b.AMOUNT,value:{value:""+t,currency_code:null==o||null==(a=o.amount)?void 0:a.currency_code,breakdown:s}}}return f},updateShippingDiscount:function(e){var n,r,i=e.discount;return t=Object(d.b)({breakdown:(null==o||null==(n=o.amount)?void 0:n.breakdown)||{},updatedAmounts:{shipping_discount:i}}),s=Object(d.a)({breakdown:s,updatedAmounts:{shipping_discount:i}}),u[l.b.AMOUNT]={op:"replace",path:l.b.AMOUNT,value:{value:""+t,currency_code:null==o||null==(r=o.amount)?void 0:r.currency_code,breakdown:s}},f},patch:function(){return Object(c.z)(a).then((function(e){var n,t,o=(null==e||null==(n=e.checkoutSession)||null==(n=n.cart)?void 0:n.shippingMethods)||[];return t=Boolean(o.length>0)?Object(d.d)({queries:u}):Object(d.c)({queries:u}),Object(c.K)({clientID:r,orderID:a,data:t}).catch((function(){throw new Error("Order could not be patched")}))}))},query:function(){return Object(c.z)(a).then((function(e){var n,t=(null==e||null==(n=e.checkoutSession)||null==(n=n.cart)?void 0:n.shippingMethods)||[];return Boolean(t.length>0)?Object(d.d)({queries:u}):Object(d.c)({queries:u})}))}};return f}({clientID:p,data:m,actions:n,orderID:e}))}))}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return c}));var r=t(4),o=t(3),i=t(5),a=t(2);function c(e){var n=e.facilitatorAccessToken,t=e.createOrder,c=e.createSubscription,u=e.featureFlags;return function(e){var s=e.accessToken;return Object(a.e)().info("spb_onauth_access_token_"+(s?"present":"not_present")),r.a.try((function(){if(s)return u.isLsatUpgradable?t().then((function(e){return c?s:Object(i.O)(n,{buyerAccessToken:s,orderID:e})})).then((function(){return Object(a.e)().info("upgrade_lsat_success"),s})).catch((function(e){return Object(a.e)().warn("upgrade_lsat_failure",{error:Object(o.J)(e)}),s})):s}))}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return o}));var r=t(3);t(4),t(0);var o=function(e){var n=e.createVaultSetupToken,t={paymentSource:e.paymentSource};return Object(r.w)((function(){if(!n)throw new Error("createVaultSetupToken undefined");return n(t).then((function(e){if(!e||"string"!=typeof e)throw new Error("Expected a vault setup token to be returned from createVaultSetupToken");return e}))}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return s}));var r=t(4),o=t(3),i=t(0),a=t(5),c=t(1),u=t(2);function s(e,n){var t=e.orderID,s=e.payload,l=e.partnerAttributionID,d=n.facilitatorAccessToken,f=Date.now();return r.a.try((function(){return Object(a.g)(t,s,{facilitatorAccessToken:d,partnerAttributionID:l})})).catch((function(e){throw Object(u.e)().error("confirm_order_error",{err:Object(o.J)(e)}),e})).then((function(){var e,n=Date.now()-f;Object(u.e)().track((e={},e[i.g.STATE]=c.k.BUTTON,e[i.g.TRANSITION]=c.l.CONFIRM_ORDER,e[i.g.CONTEXT_TYPE]=c.h.ORDER_ID,e[i.g.CONTEXT_ID]=t,e[i.g.TOKEN]=t,e[i.g.RESPONSE_DURATION]=n.toString(),e)).flush()}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return i})),t.d(n,"b",(function(){return a})),t(4);var r=t(8),o=t(7),i=function(e){var n=e.clientID,t=e.vaultSetupToken,r=e.paymentSource;return Object(o.a)({name:"UpdateVaultSetupToken",query:"\n mutation UpdateVaultSetupToken(\n $clientID: String!\n $vaultSetupToken: String!\n $paymentSource: PaymentSource\n ) {\n updateVaultSetupToken(\n clientId: $clientID\n vaultSetupToken: $vaultSetupToken\n paymentSource: $paymentSource\n ) {\n id,\n status,\n links {\n rel, href\n }\n }\n }",variables:{clientID:n,vaultSetupToken:t,paymentSource:r}})};function a(e){return Object(o.c)({authenticated:!1,method:"post",eventName:"vault_ectoken",url:r.j.VAULT+"/"+e+"/ectoken"}).then((function(e){return e.data.token}))}},function(e,n,t){"use strict";function r(e){if(null==e)throw new TypeError("Cannot destructure undefined")}t.d(n,"a",(function(){return r}))},function(e,n,t){"use strict";t.d(n,"a",(function(){return l}));var r=t(6),o=t(4),i=t(3),a=["warn","error"],c=["error","warn","info","debug"],u=function(e,n){for(var t in n)n.hasOwnProperty(t)&&(e[t]=n[t])},s=t(9);function l(e){var n=e.url,t=e.prefix,l=e.logLevel,d=void 0===l?"warn":l,f=e.transport,p=void 0===f?function(e){var n=e.url,t=e.method,r=e.headers,a=e.json,c=e.enableSendBeacon,u=void 0!==c&&c;return o.a.try((function(){var e=window,o=Object(s.f)(e)?Object(s.a)(e):window,c=!1;return function(e){var n=e.headers,t=e.enableSendBeacon,r=n&&Object.keys(n).length;return!!(window&&window.navigator.sendBeacon&&!r&&t&&window.Blob)}({headers:r,enableSendBeacon:u})&&(c=function(e){var n=e.win,t=void 0===n?window:n,r=e.url,o=e.data,i=e.useBlob,a=void 0===i||i;try{var c=JSON.stringify(o);if(!t.navigator.sendBeacon)throw new Error("No sendBeacon available");if(a){var u=new Blob([c],{type:"application/json"});return t.navigator.sendBeacon(r,u)}return t.navigator.sendBeacon(r,c)}catch(e){return!1}}({win:o,url:n,data:a,useBlob:!0})),c||Object(i.H)({win:o,url:n,method:t,headers:r,json:a})})).then(i.x)}:f,h=e.flushInterval,m=void 0===h?6e4:h,g=e.enableSendBeacon,_=void 0!==g&&g,v=[],b=[],E=[],y=[],I=[],T=[],O=[];function w(e,n,t){if(Object(i.p)()&&window.console&&window.console.log&&!(c.indexOf(e)>c.indexOf(d))){var r=[n];r.push(t),(t.error||t.warning)&&r.push("\n\n",t.error||t.warning);try{window.console[e]&&window.console[e].apply?window.console[e].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(e){}}}function S(){return o.a.try((function(){if(Object(i.p)()&&"file:"!==window.location.protocol&&(v.length||b.length||E.length)){for(var e={},t=0;t4)return r(!1,!1);var a=parseInt(e,10),c=Number(String(i).substr(2,2)),u=!1;if(2===o){if(String(i).substr(0,2)===e)return r(!1,!0);t=c===a,u=a>=c&&a<=c+n}else 4===o&&(t=i===a,u=a>=i&&a<=i+n);return r(u,u,t)}},function(e,n,t){"use strict";t.d(n,"a",(function(){return r})),t(4);var r={PAYMENT:"payment",CANCEL:"cancel"}},function(e,n,t){"use strict";t(4),t(0)},function(e,n,t){"use strict";t(4)},function(e,n,t){"use strict";t(4),t(0)},function(e,n){},function(e,n,t){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var n,t=1,r=arguments.length;t0&&t<13;return r(o,o,o&&t>=n)}},function(e,n,t){"use strict";e.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.addMatchingCardsToResults=void 0;var r=t(43),o=t(47);n.addMatchingCardsToResults=function(e,n,t){var i,a;for(i=0;i=a&&(u.matchStrength=a),t.push(u);break}}}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.matches=void 0,n.matches=function(e,n){return Array.isArray(n)?function(e,n,t){var r=String(n).length,o=e.substr(0,r),i=parseInt(o,10);return n=parseInt(String(n).substr(0,o.length),10),t=parseInt(String(t).substr(0,o.length),10),i>=n&&i<=t}(e,n[0],n[1]):function(e,n){return(n=String(n)).substring(0,e.length)===e.substring(0,n.length)}(e,n)}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isValidInputType=void 0,n.isValidInputType=function(e){return"string"==typeof e||e instanceof String}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.findBestMatch=void 0,n.findBestMatch=function(e){return function(e){var n=e.filter((function(e){return e.matchStrength})).length;return n>0&&n===e.length}(e)?e.reduce((function(e,n){return e?Number(e.matchStrength)255?o(!1,!1):r.test(e)?o(!1,!0):o(!0,!0)}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.cardNumber=void 0;var r=t(52),o=t(42);function i(e,n,t){return{card:e,isPotentiallyValid:n,isValid:t}}n.cardNumber=function(e,n){var t,a;if(void 0===n&&(n={}),"string"!=typeof e&&"number"!=typeof e)return i(null,!1,!1);var c=String(e).replace(/-|\s/g,"");if(!/^\d*$/.test(c))return i(null,!1,!1);var u=o(c);if(0===u.length)return i(null,!1,!1);if(1!==u.length)return i(null,!0,!1);var s=u[0];if(n.maxLength&&c.length>n.maxLength)return i(s,!1,!1);t=s.type===o.types.UNIONPAY&&!0!==n.luhnValidateUnionPay||r(c),a=Math.max.apply(null,s.lengths),n.maxLength&&(a=Math.min(n.maxLength,a));for(var l=0;l=0;)n=parseInt(e.charAt(o),10),r&&(n*=2)>9&&(n=n%10+1),r=!r,t+=n,o--;return t%10==0}},function(e,n,t){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var n,t=1,r=arguments.length;t1||1===a&&Number(t[1])>2?1:1===a?(i=t.substr(1),r.expirationYear(i).isPotentiallyValid?1:2):5===t.length?1:t.length>5?2:1),u=e.substr(0,c);return{month:u,year:e.substr(u.length)}}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isArray=void 0,n.isArray=Array.isArray||function(e){return"[object Array]"==={}.toString.call(e)}},function(e,n,t){"use strict";function r(e,n){return{isValid:e,isPotentiallyValid:n}}Object.defineProperty(n,"__esModule",{value:!0}),n.cvv=void 0,n.cvv=function(e,n){return void 0===n&&(n=3),n=n instanceof Array?n:[n],"string"!=typeof e?r(!1,!1):/^\d*$/.test(e)?function(e,n){for(var t=0;tfunction(e){for(var n=3,t=0;tn?e[t]:n;return n}(n)?r(!1,!1):r(!0,!0):r(!1,!1)}},function(e,n,t){"use strict";function r(e,n){return{isValid:e,isPotentiallyValid:n}}Object.defineProperty(n,"__esModule",{value:!0}),n.postalCode=void 0,n.postalCode=function(e,n){void 0===n&&(n={});var t=n.minLength||3;return"string"!=typeof e?r(!1,!1):r(!(e.length1&&a.zoomHeight&&a.zoomHeight[t]?-1!==a.zoomHeight[t].indexOf(i):-1!==a.textSizeHeights.indexOf(i)||-1!==a.textSizeHeightsNoTabs.indexOf(i))}return!1}function I(e){if(void 0===e&&(e=o()),g(e)){var n=y(e),t=_(e)?r[window.outerHeight]:null;if(!t)return!1;var i=window.innerHeight,a=Math.round(window.screen.width/window.innerWidth*100)/100,c=Math.round(i*a),u=t.maybeSafari,s=!1;return a>1&&u[a]&&-1!==u[a].indexOf(c)&&(s=!0),n||s}return!1}function T(e){return void 0===e&&(e=o()),!!m(e)&&/Version\/[\d.]+/.test(e)&&!h(e)}function O(){return!!window.document.documentMode||Boolean(window.navigator&&window.navigator.userAgent&&/Edge|MSIE|rv:11/i.test(window.navigator.userAgent))}function w(){var e=window.document.querySelector('meta[http-equiv="X-UA-Compatible"]'),n=window.document.querySelector('meta[content="IE=edge"]');return!(!e||!n)}function S(){return!("undefined"==typeof process||!process.versions||!process.versions.electron)}function A(){if(window.document.documentMode)try{var e=window.status;return window.status="testIntranetMode","testIntranetMode"===window.status&&(window.status=e,!0)}catch(e){return!1}return!1}function D(){var e=o();return/Macintosh.*AppleWebKit(?!.*Safari)/i.test(e)}function C(e){return void 0===e&&(e=o()),!(E(e)||T(e)||h(e)||f(e)||p(e)||l(e)||b(e)||S()||D()||s())}function N(e){return void 0===e&&(e=o()),/Chrome|Chromium|CriOS/.test(e)&&!/SamsungBrowser|Silk|EdgA/.test(e)}function k(e){return void 0===e&&(e=o()),/Safari/.test(e)&&!N(e)&&!/Silk|FxiOS|EdgiOS/.test(e)}function P(){try{if(window.ApplePaySession&&window.ApplePaySession.supportsVersion(3)&&window.ApplePaySession.canMakePayments())return!0}catch(e){return!1}return!1}function R(e){return-1===window.document.cookie.indexOf(e)}function j(e,n){return(j=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function L(e,n){e.prototype=Object.create(n.prototype),e.prototype.constructor=e,j(e,n)}function M(){return(M=Object.assign||function(e){for(var n=1;n>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,n={};return Object.freeze(n),e.set(n,"__testvalue__"),"__testvalue__"===e.get(n)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var n=e.prototype;return n._cleanupClosedWindows=function(){for(var e=this.weakmap,n=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var t=e&&e.stack,r=e&&e.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+je(e,n+1)}}function Le(e){var n="";return e?e instanceof Error?e.message||n:"string"==typeof e.message&&e.message||n:n}function Me(e){return"string"==typeof e?e:e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}function Ue(e,n){var t=(e=e.split("://")[1]).indexOf(n);return-1!==t&&e.slice(t)===n}function xe(e,n,t){var r=e[n];e[n]=function(){var e=arguments,n=this;return t({context:this,args:[].slice.call(arguments),original:r,callOriginal:function(){return r.apply(n,e)}})}}function Fe(e,n){if(!n)return e;if(Object.assign)return Object.assign(e,n);for(var t in n)n.hasOwnProperty(t)&&(e[t]=n[t]);return e}function Be(e){if(Object.values)return Object.values(e);var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(e[t]);return n}Te.clear=function(){Ie=ye};var Ve=Te(Be);function He(e,n){return Math.round(e*n/100)}function We(){return Math.min.apply(Math,arguments)}function Ge(){return Math.max.apply(Math,arguments)}function Ye(e,n){var t=e%n;return t?e-t+n:e}function Ke(e,n,t){var r=[];return e.replace(n,(function(e){r.push(t?t.apply(null,arguments):e)})),r}function qe(e){return"data:image/svg+xml;base64,"+he(e)}function $e(e,n){void 0===n&&(n=Boolean);var t={};for(var r in e)e.hasOwnProperty(r)&&n(e[r],r)&&(t[r]=e[r]);return t}function ze(e){return e}function Xe(e,n){var t=[];return e.replace(n,(function(e){return t.push(e),""})),t}function Je(e,n){var t,r;return void 0===n&&(n=50),pe((function(){r&&clearTimeout(r);var o=t=t||new Y;return r=setTimeout((function(){t=null,r=null,Y.try(e).then((function(e){o.resolve(e)}),(function(e){o.reject(e)}))}),n),o}),fe(e)+"::promiseDebounced")}function Ze(e,n){var t;return function r(){t=setTimeout((function(){e(),r()}),n)}(),{cancel:function(){clearTimeout(t)}}}function Qe(e){return Boolean(e.match(/^[0-9]+$/))}function en(e){return Boolean(e.match(/^[0-9]+\.[0-9]+$/))}function nn(e){return e.toString()}function tn(e){return"true"===e||"false"!==e&&(Qe(e)?parseInt(e,10):en(e)?parseFloat(e):e)}function rn(e,n,t){for(var r in void 0===n&&(n=""),void 0===t&&(t={}),n=n?n+".":n,e)e.hasOwnProperty(r)&&null!=e[r]&&"function"!=typeof e[r]&&(e[r]&&Array.isArray(e[r])&&e[r].length&&e[r].every((function(e){return"object"!=typeof e}))?t[""+n+r+"[]"]=e[r].join(","):e[r]&&"object"==typeof e[r]?t=rn(e[r],""+n+r,t):t[""+n+r]=nn(e[r]));return t}function on(e){var n={};for(var t in e)if(e.hasOwnProperty(t)&&"string"==typeof e[t]){var r=e[t];t.match(/^.+\[\]$/)?(t=t.slice(0,-2),r=r.split(",").map(tn)):r=tn(r);for(var o=n,i=t.split("."),a=0;a1?t-1:0),o=1;o1?r-1:0),i=1;i1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function tt(){return Boolean(nt())}function rt(){return Gn().then((function(){var e=nt();if(e){var n=e.timing;return n.connectEnd&&n.domInteractive?n.domInteractive-n.connectEnd:void 0}}))}function ot(e){return void 0===e&&(e=""),e.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function it(){return"undefined"!=typeof window&&void 0!==window.location}function at(e,n){return void 0===n&&(n=window.document),[].slice.call(n.querySelectorAll(e))}function ct(e,n){e.addEventListener("touchstart",De,{passive:!0}),e.addEventListener("click",n),e.addEventListener("keypress",(function(e){if(e.keyCode===Mn.ENTER||e.keyCode===Mn.SPACE)return n(e)}))}function ut(e){var n=e.host,t=void 0===n?window.location.host:n,r=e.path,o=e.reverse,i=void 0!==o&&o;return Ae(ut,(function(){var e=""+t+r,n=[].slice.call(document.getElementsByTagName("script"));i&&n.reverse();for(var o=0;or&&(t=null),t||(t={guid:ge(),created:o}),n.__session__=t,e(t)}))}return{getState:i,getID:a,isStateFresh:function(){return a()===o},getSessionState:function(e){return c((function(n){return n.state=n.state||{},e(n.state)}))},getSessionID:function(){return c((function(e){return e.guid}))}}}),[{name:n,lifetime:r}])}function or(){return rr({name:"belter_experiment"})}function ir(e){return or().getSessionState((function(n){return n.loggedBeacons=n.loggedBeacons||[],-1===n.loggedBeacons.indexOf(e)&&(n.loggedBeacons.push(e),!0)}))}function ar(e){return Math.floor(Math.random()*e)}function cr(e){var n,t=e.name,r=e.sample,o=void 0===r?50:r,i=e.logTreatment,a=void 0===i?De:i,c=e.logCheckpoint,u=void 0===c?De:c,s=e.sticky,l=void 0===s||s?function(e){return or().getState((function(n){return n.throttlePercentiles=n.throttlePercentiles||{},n.throttlePercentiles[e]=n.throttlePercentiles[e]||ar(100),n.throttlePercentiles[e]}))}(t):ar(100),d=t+"_"+(n=l=50||o<=l&&l<2*o?"control":"throttle"),f=!1,p=!1;try{window.localStorage&&window.localStorage.getItem(t)&&(p=!0)}catch(e){}var h={isEnabled:function(){return"test"===n||p},isDisabled:function(){return"test"!==n&&!p},getTreatment:function(){return d},log:function(e,n){return void 0===n&&(n={}),f?(ir(d+"_"+JSON.stringify(n))&&a({name:t,treatment:d,payload:n,throttle:l}),ir(d+"_"+e+"_"+JSON.stringify(n))&&u({name:t,treatment:d,checkpoint:e,payload:n,throttle:l}),h):h},logStart:function(e){return void 0===e&&(e={}),f=!0,h.log("start",e)},logComplete:function(e){return void 0===e&&(e={}),h.log("complete",e)}};return h}function ur(e){var n=e.name,t=e.version,r=void 0===t?"latest":t,o=_e(),i="__"+n+"__"+r+"_global__",a=o[i]=o[i]||{};return{get:function(e,n){return n=n||{},a[e]=a[e]||n}}}var sr=[];function lr(e){var n=e.url,t=e.method,r=void 0===t?"get":t,o=e.headers,i=void 0===o?{}:o,a=e.json,c=e.data,u=e.body,s=e.win,l=void 0===s?window:s,d=e.timeout,f=void 0===d?0:d;return new Y((function(e,t){if(a&&c||a&&u||c&&a)throw new Error("Only options.json or options.data or options.body should be passed");for(var o={},s=0,d=Object.keys(i);s1?new x(n):void 0}(this.component(this.props,this.children));if(n)return n.render(e)},n.render=function(e){return e(this)},n.renderChildren=function(e){return M(this.children,e)},e}();function V(e){for(var n=[],t=0;t2?t-2:0),o=2;o1||p[0]&&p[0].discount){var h,m=p.map((function(e){return Object(u.a)({term:e.term,intervalDuration:e.intervalDuration},e.discount&&{percent:e.discount.percentage},{amount:e.monthlyPayment.currencyFormatSymbolISOCurrency,totalAmount:e.totalCost.currencyFormatSymbolISOCurrency,onSelect:function(e){var n;f().info("installment_option_selected_"+e.term+"x").track((n={},n[o.g.TRANSITION]="installment_select",n[o.g.CONTEXT_TYPE]="EC-Token",n[o.g.TOKEN]=c,n[o.g.CONTEXT_ID]=c,n)).flush()}})})),g={cartAmount:s,onPay:function(e){var n;!function(e){e.classList.add("paypal-button-loading")}(a),f().info("installments_pay_button_clicked_"+(e?e.term:"")+"x").track((n={},n[o.g.TRANSITION]="installments_pay",n[o.g.CONTEXT_TYPE]="EC-Token",n[o.g.TOKEN]=c,n[o.g.CONTEXT_ID]=c,n)).flush();var t=null;return e&&(t={term:e.term,interval_duration:e.intervalDuration}),i.a.try((function(){return l(c,t)})).finally((function(){!function(e){e.classList.remove("paypal-button-loading")}(a)}))},onClose:function(){var e;f().info("installments_modal_close").track((e={},e[o.g.TRANSITION]="installments_close",e[o.g.CONTEXT_TYPE]="EC-Token",e[o.g.TOKEN]=c,e[o.g.CONTEXT_ID]=c,e)).flush()},options:m,orderID:c};return f().info("initiate_installments_modal").track((h={},h[o.g.TRANSITION]="installments_load_modal",h[o.g.CONTEXT_TYPE]="EC-Token",h[o.g.TOKEN]=c,h[o.g.CONTEXT_ID]=c,h)).flush(),function(e){var n=e.clientID,t=e.Installments,o=e.data;if(!n)throw new Error("Can not render installments without client id");var i=t({clientID:n}),a=i.renderTo,c=i.updateProps,u=i.show,s=i.close,l=Object(r.w)((function(){return a(window.xprops.getParent(),"#installments-modal")}));return l(),l().then((function(){return c({clientID:n,data:o,close:s})})).then((function(){return u()}))}({clientID:n,Installments:t,data:g})}return l(c)}throw new Error("Installments fetch returns null")})).catch((function(e){return i.a.try((function(){var n;return f().error("installment_fetch_error",{err:Object(r.J)(e)}).track((n={},n[o.g.TRANSITION]="installments_error",n[o.g.CONTEXT_TYPE]="EC-Token",n[o.g.TOKEN]=c,n[o.g.CONTEXT_ID]=c,n.err=Object(r.J)(e),n)).flush(),l(c)}))}))}({clientID:b,Installments:O,paymentMethodID:S,button:A,buyerCountry:N,orderID:e,accessToken:R,cartAmount:n.checkoutSession.cart.amounts.total.currencyFormatSymbolISOCurrency,onPay:M,getLogger:a.e})})):M(e)}))}))},close:function(){return i.a.resolve()}}},setupMenu:function(e){var n=e.props,t=e.payment,s=e.serviceData,l=e.components,d=e.config,f=e.restart,p=e.experiments,h=null!=p&&p.popupIncreaseDimensions?oe:re,m={width:h.WIDTH,height:h.HEIGHT},g=n.clientAccessToken,_=n.createOrder,v=n.enableThreeDomainSecure,b=n.partnerAttributionID,E=n.sessionID,y=n.clientMetadataID,I=n.userIDToken,T=t.fundingSource,O=t.paymentMethodID,w=t.button,S=s.content,A=s.facilitatorAccessToken,D=s.featureFlags;if(!g||!O)throw new Error("Client access token and payment method id required");Object(a.e)().info("popup_dimensions_value_vault_capture"),Object(a.u)({name:"pp.app.paypal_sdk.checkout_ui.dimension.count",dimensions:{spbPaymentFlow:"vault_capture",fundingSource:T,dimensionType:null!=p&&p.popupIncreaseDimensions?"experiment_default":"default"}});var N=function(){return i.a.try((function(){return _()})).then((function(e){return Object(C.N)({fundingSource:T,orderID:e,inline:!1,featureFlags:D})}))},k=function(e){return se.init({props:n,components:l,serviceData:s,config:d,payment:e.payment,restart:f}).start()};if(T===o.j.PAYPAL)return[{label:S.payWithDifferentMethod,popup:m,onSelect:function(e){var n,r=e.win;return Object(a.e)().info("click_choose_funding").track((n={},n[o.g.TRANSITION]=c.l.CLICK_CHOOSE_FUNDING,n[o.g.OPTION_SELECTED]=c.j.CHOOSE_FUNDING,n)).flush(),i.a.try((function(){return N()})).then((function(){return e=I?A:g,i.a.try((function(){return _()})).then((function(n){return Object(C.P)({accessToken:e,orderID:n,paymentMethodID:O,enableThreeDomainSecure:v,partnerAttributionID:b,clientMetadataID:y||E})}));var e})).then((function(){return k({payment:Object(u.a)({},t,{win:r,buyerIntent:c.b.PAY_WITH_DIFFERENT_FUNDING_SHIPPING})})}))}},{label:S.payWithDifferentAccount,popup:m,onSelect:function(e){var n,r=e.win;return Object(a.e)().info("click_choose_account").track((n={},n[o.g.TRANSITION]=c.l.CLICK_CHOOSE_ACCOUNT,n[o.g.OPTION_SELECTED]=c.j.CHOOSE_ACCOUNT,n)).flush(),i.a.try((function(){return N()})).then((function(){return k({payment:Object(u.a)({},t,{win:r,buyerIntent:c.b.PAY_WITH_DIFFERENT_ACCOUNT})})}))}}];if(T===o.j.CARD)return[{label:S.deleteVaultedCard,spinner:!0,onSelect:function(){var e,n=w.parentElement||w;return Object(a.e)().info("click_unlink_account").track((e={},e[o.g.TRANSITION]=c.l.CLICK_UNLINK_ACCOUNT,e[o.g.OPTION_SELECTED]=c.j.UNLINK_ACCOUNT,e)).flush(),Object(C.l)({paymentMethodID:O,clientAccessToken:g}).then((function(){Object(r.f)(n)}))}}];throw new Error("Can not render menu for "+T)},updateFlowClientConfig:function(e){var n=e.orderID,t=e.featureFlags,r=e.payment.fundingSource;return Object(C.N)({fundingSource:r,orderID:n,inline:!0,featureFlags:t})},spinner:!0,inline:!0},Ye=!1;function Ke(e,n,t){var r,o=e[n];if(!o)throw new Error("Wallet has no "+n);for(var i=0,a=o.instruments;i850}({version:null==n?void 0:n.version}))}({fundingSource:n,appDetect:l})&&(!i||n===o.j.VENMO)&&d().then((function(e){var t;return Object(C.w)({vault:f,platform:p,shippingCallbackEnabled:T,clientID:h,buyerCountry:E,currency:m,buttonSessionID:g,cookies:y,orderID:e,enableFunding:_,stickinessID:s,merchantID:I[0],domain:v,headers:(t={},t[c.n.DISABLE_SET_COOKIE]=String(b),t)}).then((function(t){var r,i,u=t&&null!=(r=t[n])&&r.ineligibilityReason?t[n].ineligibilityReason:"";return!!(t&&t[n]&&t[n].eligibility)||(Object(a.e)().info("native_appswitch_ineligible",{orderID:e}).track((i={},i[o.g.STATE]=c.k.BUTTON,i[o.g.TRANSITION]=c.l.NATIVE_APP_SWITCH_INELIGIBLE,i[c.i.INFO_MSG]=u,i)).flush(),!1)}))})))}))}function On(e){var n,t=e.payment,u=e.props,s=e.serviceData,l=e.config,d=e.sessionUID,f=e.fallback,p=e.callbacks,h=e.clean,m=u.buttonSessionID,g=u.onClick,_=u.createOrder,v=t.fundingSource,b=t.win,E=p.onInit,y=p.onApprove,I=p.onCancel,T=p.onError,O=p.onClose,w=p.onDestroy,S=p.onShippingChange;if(!l.firebase)throw new Error("Can not load popup without firebase config");return{click:function(){n=new i.a((function(e,n){var t=function(e){var n=e.props,t=e.fundingSource,o=function(e){var n=e.props,t=e.serviceData,o=n.buttonSessionID,i=n.env,a=n.clientID,c=n.sessionID,u=n.sdkCorrelationID,s=t.sdkMeta,l=t.buyerCountry,d=Object(L.c)();return{buttonSessionID:o,buyerCountry:l,clientID:a,channel:Object(r.s)()?"mobile-web":"desktop-web",env:i,parentDomain:d,sdkCorrelationID:u,sdkMeta:s,sessionID:c}}({props:n,serviceData:e.serviceData,fundingSource:t});return Object(r.h)(""+mn({props:n})+cn[t],{query:o})+"#init"}({props:u,serviceData:s,fundingSource:v}),p=mn({props:u}),A=function(e){var n,t;if(b){var i=Object(a.x)(b);i.setLocation(e),t=i}else t=Object(a.x)(Object(r.C)(e));return Object(a.e)().info("native_attempt_appswitch_popup_shown").track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_POPUP_SHOWN,n)).flush(),t}(t),D=h.register((function(){return A.close()})),N=i.a.try((function(){return!g||g({fundingSource:v})})).then((function(e){var n;return e||Object(a.e)().info("native_onclick_invalid").track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_ON_CLICK_INVALID,n)).flush(),e})),k=N.then((function(e){return e?_():Object(a.z)()})),P=function(e){return D.cancel(),f({win:A,fallbackOptions:e}).then((function(){return{buttonSessionID:m}}))},R=function(e){var n=e.pageUrl,t=e.stickinessID,r=e.fallbackOptions;return A.isClosed().then((function(e){return e?P(r):(r&&pn(r),k.then((function(e){A.setLocation(vn({props:u,serviceData:s,config:l,fundingSource:v,sessionUID:d,pageUrl:n,orderID:e,stickinessID:t}))})))}))},j=Object(r.A)((function(){return i.a.try((function(){var n;e(),Object(C.G)(),Object(a.e)().info("native_detect_app_switch").track((n={},n[o.g.TRANSITION]=c.l.NATIVE_DETECT_APP_SWITCH,n)).flush(),Object(a.j)((function(e){var n=e.lastAppSwitchTime,t=void 0===n?0:n,r=e.lastWebSwitchTime,o=void 0===r?0:r;t>o&&Object(a.e)().info("app_switch_detect_with_previous_app_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),o>t&&Object(a.e)().info("app_switch_detect_with_previous_web_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),t||o||Object(a.e)().info("app_switch_detect_with_no_previous_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),e.lastAppSwitchTime=Date.now()}))}))})),M=Object(r.A)((function(e){var t=e.pageUrl,r=e.stickinessID;return i.a.try((function(){var e;Object(C.G)(),Object(a.e)().info("native_detect_possible_app_switch").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_DETECT_POSSIBLE_APP_SWITCH,e)).flush();var i=En({config:l,sessionUID:d,callbacks:{onInit:function(){return j(),E()},onApprove:function(e){var n=e.data;return j(),y({data:n})},onCancel:function(){return j(),I()},onShippingChange:function(e){var n=e.data;return j(),S({data:n})},onError:function(e){var t=e.data;return j(),n(new Error(t.message)),T({data:t})},onFallback:function(e){var n=e.data;return j(),R({pageUrl:t,stickinessID:r,fallbackOptions:n}).then((function(){return{buttonSessionID:m}}))}}});h.register(i.cancel)})).catch(n)})),U=Object(r.A)((function(){return i.a.try((function(){var e;return Object(a.j)((function(e){var n=e.lastAppSwitchTime,t=void 0===n?0:n,r=e.lastWebSwitchTime,o=void 0===r?0:r;t>o&&Object(a.e)().info("web_switch_detect_with_previous_app_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),o>t&&Object(a.e)().info("web_switch_detect_with_previous_web_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),t||o||Object(a.e)().info("web_switch_detect_with_no_previous_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),e.lastWebSwitchTime=Date.now()})),Object(a.e)().info("native_detect_web_switch").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_DETECT_WEB_SWITCH,e)).flush(),P().then(r.x)})).then(e,n)})),x=Object(a.o)(A,(function(){var e;Object(a.e)().info("native_popup_closed").track((e={},e[o.g.STATE]=c.k.BUTTON,e[o.g.TRANSITION]=c.l.NATIVE_POPUP_CLOSED,e)).flush(),n(new Error("Native popup closed")),O()}),500),F=function(e){var n;Object(a.e)().info("native_closing_popup_"+e).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=e?c.l.NATIVE_CLOSING_POPUP+"_"+e:c.l.NATIVE_CLOSING_POPUP,n)).flush(),x.cancel(),A.close()},B=Object(a.p)("awaitRedirect",{proxyWin:A,domain:p},(function(e){var t=e.data,f=t.app,m=t.pageUrl,g=t.sfvc,_=t.stickinessID;Object(a.e)().info("native_post_message_await_redirect").flush(),function(e){if(e){var n,t="native_app";Object.keys(e).forEach((function(n){t+="_"+String(e[n])})),Object(a.e)().info(t).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_APP_INSTALLED,n[c.i.INFO_MSG]=t,n)).flush()}}(f),Object(a.e)().addTrackingBuilder((function(){var e;return(e={})[o.g.STICKINESS_ID]=_,e}));var b=Object(a.p)("detectAppSwitch",{proxyWin:A,domain:p},(function(){return Object(a.e)().info("native_post_message_detect_possible_app_switch").flush(),M({pageUrl:m,stickinessID:_})})),E=Object(a.p)("detectWebSwitch",{proxyWin:A,domain:hn({props:u})},(function(){return Object(a.e)().info("native_post_message_detect_web_switch").flush(),U()})),O=Object(a.p)("onApprove",{proxyWin:A,domain:p},(function(e){var n=e.data;j(),y({data:n}),F("onApprove")})),S=Object(a.p)("onCancel",{proxyWin:A,domain:p},(function(){j(),I(),F("onCancel")})),D=Object(a.p)("onFallback",{proxyWin:A,domain:p},(function(e){var n,t=e.data;j(),Object(a.e)().info("native_message_onfallback").track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ON_FALLBACK,n)).flush(),R({pageUrl:m,stickinessID:_,fallbackOptions:t})})),C=Object(a.p)("onComplete",{proxyWin:A,domain:p},(function(){var e;j(),Object(a.e)().info("native_post_message_on_complete").track((e={},e[o.g.STATE]=c.k.BUTTON,e[o.g.TRANSITION]=c.l.NATIVE_ON_COMPLETE,e)).flush(),F("onComplete")})),P=Object(a.p)("onError",{proxyWin:A,domain:p},(function(e){var t=e.data;T({data:t}),F("onError"),n(new Error(t.message))}));return window.addEventListener("pagehide",(function(){return F("pagehide")})),window.addEventListener("unload",(function(){return F("unload")})),h.register((function(){return i.a.all([B.cancel(),b.cancel(),O.cancel(),S.cancel(),D.cancel(),C.cancel(),P.cancel(),E.cancel(),x.cancel()]).then(r.x)})),i.a.hash({valid:N,eligible:Tn({fundingSource:v,props:u,serviceData:s,sfvc:g,validatePromise:N,stickinessID:_,appDetect:f})}).then((function(e){return e.valid?k.then(e.eligible?function(e){var n,t=_n({props:u,serviceData:s,config:l,fundingSource:v,sessionUID:d,pageUrl:m,orderID:e,stickinessID:_});if(Object(a.e)().info("native_attempt_appswitch_url_popup",{url:t}).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_ATTEMPT_APP_SWITCH,n[c.i.INFO_MSG]=t,n)).flush(),Object(a.k)()){x.cancel();var r=Object(a.o)(A,(function(){return M({pageUrl:m,stickinessID:_})}),50);setTimeout(r.cancel,1e3)}return{appSwitch:!0,orderID:e,redirect:!0,redirectUrl:t}}:function(e){return{redirect:!0,appSwitch:!1,orderID:e,redirectUrl:vn({props:u,serviceData:s,config:l,fundingSource:v,sessionUID:d,pageUrl:m,orderID:e,stickinessID:_})}}):(x.cancel(),A.close(),w().then((function(){return{appSwitch:!1,orderID:null,redirect:!1}})))})).catch((function(e){var n;return Object(a.e)().info("native_attempt_appswitch_url_popup_errored").track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_ATTEMPT_APP_SWITCH_ERRORED,n[c.i.ERR_DESC]=Object(r.J)(e),n)).flush(),k.then((function(e){return{appSwitch:!1,orderID:e,redirect:!0,redirectUrl:vn({props:u,serviceData:s,config:l,fundingSource:v,sessionUID:d,pageUrl:m,orderID:e,stickinessID:_})}}))})).catch((function(e){return A.close(),n(e),w().then((function(){return T({data:{message:Object(r.J)(e)}})})).then((function(){return{redirect:!1,appSwitch:!1}}))}))}))}))},start:function(){if(!n)throw new Error("Expected native popup promise to be set");return n}}}var wn=!1;function Sn(){var e=Object(L.e)(window);return wn&&e?e:Object(L.d)()?Object(L.d)():window}var An,Dn,Cn=function(e){return Object(a.e)().info("popup_dimensions_"+e).flush(),{width:534,height:590}};function Nn(e){var n,t=e.props,s=e.components,l=e.serviceData,d=e.payment,f=e.config,p=e.fallback,h=s.Venmo,m=t.sessionID,g=t.buttonSessionID,_=t.createOrder,v=t.onApprove,b=t.onCancel,E=t.onError,y=t.onComplete,I=t.onShippingChange,T=t.onShippingAddressChange,O=t.onShippingOptionsChange,w=t.locale,S=t.commit,A=t.clientAccessToken,D=t.onClick,C=t.clientMetadataID,N=t.onAuth,k=t.env,P=t.enableFunding,R=t.stickinessID,j=t.standaloneFundingSource,M=t.branded,U=t.merchantRequestedPopupsDisabled,x=d.button,F=d.win,B=d.fundingSource,V=d.card,H=d.buyerAccessToken,W=void 0===H?l.buyerAccessToken:H,G=d.venmoPayloadID,Y=d.buyerIntent,K=l.buyerCountry,q=l.eligibility.venmoWebEnabled,$=f.cspNonce,z=function(e){var n=e.win,t=e.isClick,o=e.merchantRequestedPopupsDisabled,i=Object(r.M)();return Object(a.e)().info("spb_decide_context",{merchantRequestedPopupsDisabled:Boolean(o),isClick:Boolean(t),popupSupported:Boolean(i)}),!o&&n||!o&&t&&i?c.d.POPUP:c.d.IFRAME}({win:F,isClick:d.isClick,merchantRequestedPopupsDisabled:U}),X=!1,J=!1,Z=!1,Q=function(){return i.a.try((function(){if(n)return Z=!0,n.close()}))},ee=Object(r.w)((function(){return(n=h({window:F,sessionID:m,buttonSessionID:g,stickinessID:R,clientAccessToken:A,venmoPayloadID:G,parentDomain:Object(L.c)(),venmoWebUrl:sn[k],venmoWebEnabled:q,createOrder:function(){return _().then((function(e){return e}))},onApprove:function(e){var n=void 0===e?{}:e,t=n.approveOnClose,o=n.payerID,i=n.paymentID,c=n.billingToken,u=n.subscriptionID,s=n.authCode;if(void 0===t||!t)return X=!0,Object(a.e)().info("spb_onapprove_access_token_"+(W?"present":"not_present")).flush(),Object(a.v)(W),v({payerID:o,paymentID:i,billingToken:c,subscriptionID:u,buyerAccessToken:W,authCode:s},{restart:te}).finally((function(){return Q().then(r.x)})).catch(r.x);J=!0},onComplete:function(){return Object(a.e)().info("spb_oncomplete_access_token_"+(W?"present":"not_present")).flush(),Object(a.v)(W),y({buyerAccessToken:W}).finally((function(){return Q().then(r.x)})).catch(r.x)},onAuth:function(e){return N({accessToken:e.accessToken||W}).then((function(e){W=e}))},onCancel:function(){return Q().then((function(){return b()}))},onShippingChange:I?function(e,n){return I(Object(u.a)({buyerAccessToken:W},e),n)}:null,onShippingAddressChange:T?function(e,n){if(!e.shipping_address)throw new Error("Must pass shipping_address in data to handle changes in shipping address.");return T(Object(u.a)({},e),n)}:null,onShippingOptionsChange:O?function(e,n){if(!e.selected_shipping_option)throw new Error("Must pass selected_shipping_option in data to handle changes in shipping options.");return O(Object(u.a)({},e),n)}:null,onClose:function(){return J&&!X?v({forceRestAPI:!0},{restart:te}).catch(r.x):Z||X?void 0:b()},onError:function(e){var n;return Object(a.e)().info("venmo_flow_error ",{err:Object(r.J)(e)}).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.CHECKOUT_ERROR,n[o.g.EVENT_NAME]=c.l.CHECKOUT_ERROR,n[o.g.ERROR_DESC]=Object(r.J)(e),n)).flush(),E(e)},dimensions:Cn(B),fundingSource:B,card:V,buyerCountry:K,locale:w,commit:S,cspNonce:$,clientMetadataID:C,enableFunding:P,standaloneFundingSource:j,branded:M,restart:function(){return p(F?{win:F}:{win:Sn()})}})).renderTo(Sn(),c.z.BODY,z)})),te=Object(r.w)((function(){return Q().finally((function(){return Nn({props:t,components:s,serviceData:l,config:f,payment:{button:x,fundingSource:B,card:V,buyerIntent:Y,isClick:!1,checkoutRestart:!0},fallback:p}).start().finally(a.z)}))}));return{click:function(){return i.a.try((function(){if(!U&&!F&&Object(r.M)())try{var e=Cn(B);F=ne({width:e.width,height:e.height})}catch(e){if(Object(a.e)().warn("popup_open_error_iframe_fallback",{err:Object(r.J)(e)}),!(e instanceof r.a))throw e;z=c.d.IFRAME}return i.a.try((function(){return!D||D({fundingSource:B})})).then((function(e){var n;return F&&!e&&(Object(a.e)().info("native_onclick_invalid").track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_ON_CLICK_INVALID,n)).flush(),F.close()),e}))}))},start:ee,close:Q}}var kn,Pn={name:"native",setup:function(e){var n=e.props,t=e.serviceData;return n.fundingSource===o.j.VENMO&&t.eligibility.venmoWebEnabled&&function(e){var n=e.components.Venmo,t=[Object(L.d)(window),Object(L.e)(window)],o=t[0],a=t[1],c={};a&&o&&o!==a&&(c.canRenderTo=n.canRenderTo(a).then((function(e){wn=e}))),i.a.hash(c).then(r.x)}({components:e.components}),function(e){var n,t=e.props,r=e.serviceData,o=t.clientID,i=t.currency,a=t.platform,u=t.vault,s=t.buttonSessionID,l=t.enableFunding,d=t.merchantDomain,f=t.disableSetCookie,p=r.merchantID,h=r.buyerCountry,m=r.cookies,g=!r.eligibility.venmoWebEnabled&&Boolean(t.onShippingChange);return Object(C.w)({vault:u,platform:a,shippingCallbackEnabled:g,clientID:o,buyerCountry:h,currency:i,buttonSessionID:s,cookies:m,enableFunding:l,stickinessID:null,skipElmo:!0,merchantID:p[0],domain:d,headers:(n={},n[c.n.DISABLE_SET_COOKIE]=String(f),n)}).then((function(e){en=e}))}({props:n,serviceData:t}).then(r.x)},isEligible:function(e){var n,t,i,c=e.props,u=e.serviceData,s=c.fundingSource,l=c.onShippingChange,d=c.createBillingAgreement,f=c.createSubscription,p=c.env,h=c.platform,m=u.cookies,g=u.merchantID,_=u.fundingEligibility,v=u.eligibility.venmoWebEnabled,b=null==_||null==(n=_.venmo)?void 0:n.eligible,E=s===o.j.VENMO,y=p===o.d.LOCAL||p===o.d.STAGE;return!(!e.config.firebase||h&&h===o.m.DESKTOP&&!b||!dn({fundingSource:s})&&!fn({fundingSource:s})||(t=Date.now(),i=0,Object(a.j)((function(e){var n=e.nativeOptOutLifetime;n&&"number"==typeof n&&(i=n)})),i>t||!ln({props:c})&&(!m&&s===o.j.PAYPAL||!Object(r.M)()||!v&&l||d||f||!E&&y||g.length>1||!u.featureFlags.isLsatUpgradable)))},isPaymentEligible:function(e){var n=e.payment,t=e.props.platform,r=n.fundingSource,i=n.win;return!!(an[r]&&cn[r]&&un[r])&&!(!dn({fundingSource:r,win:i})&&!fn({fundingSource:r,win:i}))&&(t&&t===o.m.DESKTOP?!(!en||!en[r])&&en[r].eligibility:!(i&&!Object(a.x)(i).getWindow()))},init:function(e){var n=e.props,t=e.components,s=e.config,l=e.payment,d=e.serviceData,f=e.restart,p=n.onApprove,h=n.onCancel,m=n.onError,g=n.buttonSessionID,_=n.onShippingChange,v=d.eligibility.venmoWebEnabled,b=l.fundingSource,E=l.win;if(!s.firebase)throw new Error("Can not run native flow without firebase config");An&&An.all(),An=Object(r.c)();var y=!1,I=!1,T=!1,O=Object(r.w)((function(){return An.all()})),w=function(e){return T=!0,i.a.try((function(){return!e||Object(a.x)(e).isClosed()})).then((function(a){var c,p=a?null:e,h=Object(u.a)({},l,{win:p,isClick:!1});return c=b===o.j.VENMO&&v?Nn({props:n,components:t,payment:h,config:s,serviceData:d,fallback:Dn}):se.init({props:n,components:t,payment:h,config:s,serviceData:d,restart:f}),i.a.all([O(),c.start()]).then(r.x)}))};Dn=function(e){var n=e||{},t=n.win,r=n.fallbackOptions,u=void 0===r?{}:r;return i.a.try((function(){var e,n,r=pn(u),i=u.fallback_reason;return n=r?c.l.NATIVE_OPT_OUT:b===o.j.VENMO&&v?c.l.NATIVE_FALLBACK_VENMO:c.l.NATIVE_FALLBACK,Object(a.e)().info("native_message_onfallback").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_ON_FALLBACK,e[c.i.TRANSITION_TYPE]=n,e[c.i.TRANSITION_REASON]=i||"",e)).flush(),w(t)}))};var S,A,D=Object(r.N)();if(function(e){var n=e.fundingSource;return!(!e.serviceData.eligibility.venmoWebEnabled||n&&n!==o.j.VENMO||e.win)}({fundingSource:b,win:E,serviceData:d})&&Boolean(_))Object(a.e)().info("venmo_web").track((A={},A[o.g.TRANSITION]=c.l.NATIVE_VENMO_WEB,A)).flush(),S=Nn;else if(dn({fundingSource:b,win:E}))S=On;else{if(!fn({fundingSource:b,win:E}))throw new Error("No valid native payment flow found");S=In}var N=S({payment:l,props:n,serviceData:d,config:s,components:t,clean:An,sessionUID:D,fallback:Dn,callbacks:{onInit:function(){return i.a.try((function(){return Object(C.G)(),{buttonSessionID:g}}))},onApprove:function(e){var n,t=e.data,u=t.payerID,s=t.paymentID,l=t.billingToken;return y=!0,Object(a.e)().info("native_message_onapprove",{payerID:u,paymentID:s,billingToken:l}).track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ON_APPROVE,n[c.i.INFO_MSG]="payerID: "+u+", paymentID: "+(s||"undefined")+", billingToken: "+(l||"undefined"),n)).flush(),i.a.all([p({payerID:u,paymentID:s,billingToken:l,forceRestAPI:!0},{restart:function(){return w()}}).catch((function(e){var n;Object(a.e)().info("native_message_onapprove_error",{payerID:u,paymentID:s,billingToken:l}).track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ON_APPROVE_ERROR,n[c.i.INFO_MSG]="Error: "+Object(r.J)(e),n)).flush(),m(e)})),O()]).then((function(){return{buttonSessionID:g}}))},onCancel:function(){var e;return I=!0,Object(a.e)().info("native_message_oncancel").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_ON_CANCEL,e)).flush(),i.a.all([h(),O()]).then((function(){return{buttonSessionID:g}}))},onError:function(e){var n,t=e.data.message;return Object(a.e)().info("native_message_onerror",{err:t}).track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ON_ERROR,n[c.i.INFO_MSG]="Error message: "+t,n)).flush(),i.a.all([m(new Error(t)),O()]).then((function(){return{buttonSessionID:g}}))},onShippingChange:function(e){var n=e.data;return i.a.try((function(){var e;if(Object(a.e)().info("native_message_onshippingchange").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_ON_SHIPPING_CHANGE,e)).flush(),_){var t=!0,r={resolve:function(){return i.a.try((function(){t=!0}))},reject:function(){return i.a.try((function(){t=!1}))}};return _(Object(u.a)({},n,{forceRestAPI:!0}),r).then((function(){return{resolved:t}}))}return{resolved:!0}}))},onClose:function(){return i.a.delay(1e3).then((function(){if(!(y||I||T||Object(a.k)()))return i.a.try((function(){return O()}))})).then(r.x)},onDestroy:O}});return{click:function(){return N.click()},start:function(){return i.a.try((function(){return N.start()})).catch((function(e){return O().then((function(){var n;throw Object(a.e)().error("native_error",{err:Object(r.J)(e)}).track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ERROR,n[o.g.ERROR_CODE]="native_error",n[o.g.ERROR_DESC]=Object(r.K)(e),n)).flush(),e}))}))},close:O}},updateFlowClientConfig:function(e){var n=e.orderID,t=e.payment,r=e.userExperienceFlow,o=e.buttonSessionID,a=e.featureFlags;return i.a.try((function(){var e=t.fundingSource;return Object(C.N)({fundingSource:e,orderID:n,inline:!1,userExperienceFlow:r,buttonSessionID:o,featureFlags:a})}))},spinner:!0},Rn={name:"popup_bridge",setup:function(e){var n=e.props;return i.a.try((function(){var e=n.getPopupBridge;if(e)return e().then((function(e){kn=e}))}))},isEligible:function(e){var n=e.props;return!(n.onShippingChange||n.onShippingAddressChange||n.onShippingOptionsChange)},isPaymentEligible:function(e){return!e.payment.win&&!!kn},init:function(e){var n=e.props,t=n.createOrder,o=n.onApprove,i=n.onCancel,u=n.commit,s=e.payment.fundingSource;return{start:function e(){return t().then((function(e){if(!kn)throw new Error("Popup bridge required");var n=Object(r.h)(""+Object(L.c)()+te.m,{query:{fundingSource:s,token:e,useraction:u?c.A.COMMIT:c.A.CONTINUE,redirect_uri:kn.nativeUrl,native_xo:"1"}});return kn.start(n)})).then((function(n){var t=n.opType,r=n.PayerID,a=n.paymentId,c=n.ba_token;if(t===ve.POPUP_BRIDGE_OPTYPE.PAYMENT){if(!r&&!c)throw new Error("Expected payerID to be passed");return o({payerID:r,paymentID:a,billingToken:c},{restart:e})}if(t===ve.POPUP_BRIDGE_OPTYPE.CANCEL)return i();throw new Error("Unhandleable opType: "+t)}))},close:a.r}},spinner:!0},jn=t(32),Ln=t(11);function Mn(e,n){if(e.length!==n.length)return!1;var t=[],r=[];e.forEach((function(e){Object(a.l)(e)?t.push(e.toLowerCase()):r.push(e)}));var o=t.every((function(e){return n.some((function(n){return e===(n.email&&n.email.stringValue&&n.email.stringValue.toLowerCase())}))})),i=r.every((function(e){return n.some((function(n){return e===n.merchantId}))}));return!(!o||!i)&&n.every((function(e){return r.indexOf(e.merchantId)>-1||t.indexOf(e.email&&e.email.stringValue&&e.email.stringValue.toLowerCase())>-1}))}function Un(e){var n,t=e.error,r=e.message,i=void 0===r?t:r,a=e.orderID,u=e.loggerPayload,s=void 0===u?{}:u,l=e.throwError,d=(void 0===l||l)&&e.featureFlags.shouldThrowIntegrationError;if(Object(Ln.a)().warn(t,s).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.ORDER_VALIDATE,n[o.g.CONTEXT_TYPE]=c.h.ORDER_ID,n[o.g.TOKEN]=a,n[o.g.CONTEXT_ID]=a,n[c.i.INTEGRATION_ISSUE]=t,n[c.i.INTEGRATION_WHITELIST]=d?"false":"true",n[o.g.ERROR_DESC]=i,n)).flush(),d)throw console.error(i),new Error(i);console.warn(i)}var xn,Fn=[o.k.CAPTURE,o.k.AUTHORIZE,o.k.ORDER];function Bn(e){var n=e.containerUID;if(xn)return xn;var t=(0,e.Menu)({clientID:e.clientID});return t.hide(),t.renderTo(window.xprops.getParent(),"#"+n+" #smart-menu"),xn=t}var Vn=[Ge,nn,Be,_e,Ie,Rn,j,Pn,se];function Hn(e){var n=e.props,t=e.payment,r=e.config,o=e.serviceData;!n.fundingSource&&t.fundingSource&&(n.fundingSource=t.fundingSource);for(var i=0;i>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,n={};return Object.freeze(n),e.set(n,"__testvalue__"),"__testvalue__"===e.get(n)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var n=e.prototype;return n._cleanupClosedWindows=function(){for(var e=this.weakmap,n=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var t=e&&e.stack,r=e&&e.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+B(e,n+1)}}function V(e){var n="";return e?e instanceof Error?e.message||n:"string"==typeof e.message&&e.message||n:n}function H(e,n){void 0===n&&(n=Boolean);var t={};for(var r in e)e.hasOwnProperty(r)&&n(e[r],r)&&(t[r]=e[r]);return t}function G(e,n){var t,r;return void 0===n&&(n=50),A((function(){r&&clearTimeout(r);var o=t=t||new g.a;return r=setTimeout((function(){t=null,r=null,g.a.try(e).then((function(e){o.resolve(e)}),(function(e){o.reject(e)}))}),n),o}),S(e)+"::promiseDebounced")}function K(e,n){var t;return function r(){t=setTimeout((function(){e(),r()}),n)}(),{cancel:function(){clearTimeout(t)}}}function Y(e){return[].slice.call(e)}function W(e,n){var t;return void 0===n&&(n=100),A((function(){var r=arguments,o=this;clearTimeout(t),t=setTimeout((function(){return e.apply(o,r)}),n)}),S(e)+"::debounced")}function q(e){var n,t=[],r=!1,o={set:function(n,t){return r||(e[n]=t,o.register((function(){delete e[n]}))),t},register:function(e){var o=x((function(){return e(n)}));return r?e(n):t.push(o),{cancel:function(){var e=t.indexOf(o);-1!==e&&t.splice(e,1)}}},all:function(e){n=e;var o=[];for(r=!0;t.length;){var i=t.shift();o.push(i())}return g.a.all(o).then(M)}};return o}function $(e){var n=[],t={};return function(r){if(-1===n.indexOf(r)){n.push(r);var o=B(r);if(!t[o])return t[o]=!0,e(r)}}}L.clear=function(){j=R},L((function(e){if(Object.values)return Object.values(e);var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(e[t]);return n}));var z=function(e){function n(n){var t;return(t=e.call(this,n)||this).name=t.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t),t.constructor):t.stack=new Error(n).stack,t}return m(n,e),n}(w(Error));function X(){return Boolean(document.body)&&"complete"===document.readyState}function J(){return Boolean(document.body)&&"interactive"===document.readyState}function Q(e){return encodeURIComponent(e)}var Z=L((function(){return new g.a((function(e){if(X()||J())return e();var n=setInterval((function(){if(X()||J())return clearInterval(n),e()}),10)}))}));function ee(e){return U(ee,(function(){var n={};if(!e)return n;if(-1===e.indexOf("="))return n;for(var t=0,r=e.split("&");t1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function ae(){return Z().then((function(){var e=ie();if(e){var n=e.timing;return n.connectEnd&&n.domInteractive?n.domInteractive-n.connectEnd:void 0}}))}function ce(){return"undefined"!=typeof window&&void 0!==window.location}function ue(e,n){return void 0===n&&(n=window.document),[].slice.call(n.querySelectorAll(e))}function se(e,n){e.addEventListener("touchstart",M,{passive:!0}),e.addEventListener("click",n),e.addEventListener("keypress",(function(e){if(13===e.keyCode||32===e.keyCode)return n(e)}))}function le(){return U(le,(function(){try{if("undefined"==typeof window)return!1;if(window.localStorage){var e=Math.random().toString();window.localStorage.setItem("__test__localStorage__",e);var n=window.localStorage.getItem("__test__localStorage__");if(window.localStorage.removeItem("__test__localStorage__"),e===n)return!0}}catch(e){}return!1}))}var de=function(e){function n(){return e.apply(this,arguments)||this}return m(n,e),n}(z);function fe(e,n){var t=(n=n||{}).closeOnUnload,r=void 0===t?1:t,o=n.name,i=void 0===o?"":o,a=n.width,c=n.height,u=0,s=0;a&&(window.outerWidth?s=Math.round((window.outerWidth-a)/2)+window.screenX:window.screen.width&&(s=Math.round((window.screen.width-a)/2))),c&&(window.outerHeight?u=Math.round((window.outerHeight-c)/2)+window.screenY:window.screen.height&&(u=Math.round((window.screen.height-c)/2))),delete n.closeOnUnload,delete n.name,a&&c&&(n=Object(_.a)({top:u,left:s,width:a,height:c,status:1,toolbar:0,menubar:0,resizable:1,scrollbars:1},n));var l,d,f=Object.keys(n).map((function(e){if(null!=n[e])return e+"="+("string"==typeof(t=n[e])?t:t&&t.toString&&"function"==typeof t.toString?t.toString():{}.toString.call(t));var t})).filter(Boolean).join(",");try{l=window.open(e,i,f)}catch(d){throw new de("Can not open popup window - "+(d.stack||d.message))}if(Object(v.h)(l))throw new de("Can not open popup window - blocked");return r&&window.addEventListener("unload",(function(){return l.close()})),l}function pe(e,n){var t=n.tagName.toLowerCase();if("html"!==t)throw new Error("Expected element to be html, got "+t);for(var r=e.document.documentElement,o=0,i=Y(r.children);or&&(t=null),t||(t={guid:o||C(),created:i}),n.__session__=t,e(t)}))}return{getState:a,getID:c,isStateFresh:function(){return c()===i},getSessionState:function(e){return u((function(n){return n.state=n.state||{},e(n.state)}))},getSessionID:function(){return u((function(e){return e.guid}))}}}),[{name:n,lifetime:r}])}function ye(){return be({name:"belter_experiment"})}function Ee(e){return ye().getSessionState((function(n){return n.loggedBeacons=n.loggedBeacons||[],-1===n.loggedBeacons.indexOf(e)&&(n.loggedBeacons.push(e),!0)}))}function Te(e){return Math.floor(Math.random()*e)}function Oe(e){var n,t=e.name,r=e.sample,o=void 0===r?50:r,i=e.logTreatment,a=void 0===i?M:i,c=e.logCheckpoint,u=void 0===c?M:c,s=e.sticky,l=void 0===s||s?function(e){return ye().getState((function(n){return n.throttlePercentiles=n.throttlePercentiles||{},n.throttlePercentiles[e]=n.throttlePercentiles[e]||Te(100),n.throttlePercentiles[e]}))}(t):Te(100),d=t+"_"+(n=l=50||o<=l&&l<2*o?"control":"throttle"),f=!1,p=!1;try{window.localStorage&&window.localStorage.getItem(t)&&(p=!0)}catch(e){}var h={isEnabled:function(){return"test"===n||p},isDisabled:function(){return"test"!==n&&!p},getTreatment:function(){return d},log:function(e,n){return void 0===n&&(n={}),f?(Ee(d+"_"+JSON.stringify(n))&&a({name:t,treatment:d,payload:n,throttle:l}),Ee(d+"_"+e+"_"+JSON.stringify(n))&&u({name:t,treatment:d,checkpoint:e,payload:n,throttle:l}),h):h},logStart:function(e){return void 0===e&&(e={}),f=!0,h.log("start",e)},logComplete:function(e){return void 0===e&&(e={}),h.log("complete",e)}};return h}L((function(){var e;try{e=ge()}catch(e){return ve}var n=e.getAttribute("data-uid");if(n&&"string"==typeof n)return n;if((n=e.getAttribute("data-uid-auto"))&&"string"==typeof n)return n;if(e.src){var t=function(e){for(var n="",t=0;t=300){var i,a=new Error(s+" returned status "+n+" (Corr ID: "+r[c.n.PAYPAL_DEBUG_ID]+").\n\n"+JSON.stringify(t));throw a.response={status:n,headers:r,body:t},n===c.y.TOO_MANY_REQUESTS&&Object(u.e)().track(((i={})[o.g.TRANSITION]=c.l.CALL_REST_API,i[c.i.ERR_DESC]="Error: "+n+" - "+t,i[c.i.INFO_MSG]="URL: "+s,i)),Object(u.e)().warn("rest_api_"+f+"_status_"+n+"_error"),Object(u.u)({name:"pp.app.paypal_sdk.buttons.rest_api_"+f+".error.count",dimensions:h}),a}return Object(u.u)({name:"pp.app.paypal_sdk.buttons.rest_api_"+f+".success.count",dimensions:h}),t}))}function l(e){var n=e.accessToken,t=e.url,a=e.method,s=void 0===a?"get":a,l=e.headers,d=void 0===l?{}:l,f=e.json,p=e.authenticated,h=void 0===p||p,m=e.eventName,_=e.metricDimensions,g=void 0===_?{}:_;if(d[c.n.REQUESTED_BY]=c.x,h&&!n)throw new Error("Buyer access token not present - can not call smart api: "+t);return n&&(d[c.n.ACCESS_TOKEN]=n),Object(i.I)({url:t,method:s,headers:d,json:f}).then((function(e){var n,i=e.status,a=e.body,l=e.headers;if("contingency"===a.ack){var f=new Error(a.contingency);throw f.response={url:t,method:s,headers:d,body:a},f.data=a.data,Object(u.e)().warn("smart_api_"+m+"_contingency_error"),f}if(i===c.y.TOO_MANY_REQUESTS&&Object(u.e)().track(((n={})[o.g.TRANSITION]=c.l.CALL_REST_API,n[c.i.ERR_DESC]="Error: "+i+" - "+a,n[c.i.INFO_MSG]="URL: "+t,n)),i>400)throw Object(u.e)().warn("smart_api_"+m+"_status_"+i+"_error"),Object(u.u)({name:"pp.app.paypal_sdk.buttons.smart_api_"+m+".error.count",dimensions:Object(r.a)({status:i},g)}),new Error("Api: "+t+" returned status code: "+i+" (Corr ID: "+l[c.n.PAYPAL_DEBUG_ID]+")\n\n"+JSON.stringify(a));if("success"!==a.ack)throw Object(u.e)().warn("smart_api_"+m+"_ack_error"),Object(u.u)({name:"pp.app.paypal_sdk.buttons.smart_api_"+m+".error.count",dimensions:g}),new Error("Api: "+t+" returned ack: "+a.ack+" (Corr ID: "+l[c.n.PAYPAL_DEBUG_ID]+")\n\n"+JSON.stringify(a));return Object(u.u)({name:"pp.app.paypal_sdk.buttons.smart_api_"+m+".success.count",dimensions:g}),{data:a.data,headers:l}}))}function d(e){var n=e.name,t=e.query,o=e.variables,s=void 0===o?{}:o,l=e.headers,d=void 0===l?{}:l,f=e.returnErrorObject,p=void 0!==f&&f;return Object(i.I)({url:a.f+"?"+n,method:"POST",json:{query:t,variables:s},headers:Object(r.a)({"x-app-name":c.x},d)}).then((function(e){var t=e.status,r=e.body,o=r.errors||[];if(o.length){var i=o[0].message||JSON.stringify(o[0]);if(Object(u.e)().warn("graphql_"+n+"_error",{err:i}),p)throw o[0];throw Object(u.u)({name:"pp.app.paypal_sdk.buttons.graphql_"+n+".error.count",dimensions:{}}),new Error(i)}if(200!==t)throw Object(u.e)().warn("graphql_"+n+"_status_"+t+"_error"),Object(u.u)({name:"pp.app.paypal_sdk.buttons.graphql_"+n+".error.count",dimensions:{status:t}}),new Error(a.f+" returned status "+t+"\n\n"+JSON.stringify(r));return Object(u.u)({name:"pp.app.paypal_sdk.buttons.graphql_"+n+".success.count",dimensions:{}}),r.data}))}function f(e){return e.headers[c.n.PAYPAL_DEBUG_ID]}function p(e){var n=null==e?void 0:e.response;if(n)return f(n)}},function(e,n,t){"use strict";t.d(n,"g",(function(){return i})),t.d(n,"a",(function(){return a})),t.d(n,"h",(function(){return c})),t.d(n,"i",(function(){return u})),t.d(n,"b",(function(){return s})),t.d(n,"k",(function(){return l})),t.d(n,"l",(function(){return d})),t.d(n,"j",(function(){return f})),t.d(n,"f",(function(){return p})),t.d(n,"m",(function(){return h})),t.d(n,"e",(function(){return m})),t.d(n,"d",(function(){return _})),t.d(n,"c",(function(){return g}));var r,o=t(0),i="/xoplatform/logger/api/logger",a="/v1/oauth2/token",c="/v2/checkout/orders",u="/v1/payments/payment",s="/v1/billing/subscriptions",l="validate-payment-method",d="/v3/vault/setup-tokens",f={AUTH:"/smart/api/auth",CHECKOUT:"/smart/api/checkout",ORDER:"/smart/api/order",PAYMENT:"/smart/api/payment",SUBSCRIPTION:"/smart/api/billagmt/subscriptions",VAULT:"/smart/api/vault"},p="/graphql",h="/checkoutnow",m=((r={})[o.j.PAYPAL]=o.j.PAYPAL,r[o.j.PAYLATER]=o.j.PAYPAL,r[o.j.CREDIT]=o.j.PAYPAL,r),_={APP:"https://www.paypalobjects.com/checkout/js/lib/firebase-app.js",AUTH:"https://www.paypalobjects.com/checkout/js/lib/firebase-auth.js",DATABASE:"https://www.paypalobjects.com/checkout/js/lib/firebase-database.js"},g=!1},function(e,n,t){"use strict";t.d(n,"d",(function(){return c})),t.d(n,"c",(function(){return l})),t.d(n,"f",(function(){return d})),t.d(n,"a",(function(){return f})),t.d(n,"e",(function(){return m})),t.d(n,"b",(function(){return _})),t.d(n,"h",(function(){return b})),t.d(n,"i",(function(){return y})),t.d(n,"j",(function(){return E})),t.d(n,"g",(function(){return T}));var r="Call was rejected by callee.\r\n";function o(e){return void 0===e&&(e=window),e.location.protocol}function i(e){if(void 0===e&&(e=window),e.mockDomain){var n=e.mockDomain.split("//")[0];if(n)return n}return o(e)}function a(e){return void 0===e&&(e=window),"about:"===i(e)}function c(e){if(void 0===e&&(e=window),e)try{if(e.parent&&e.parent!==e)return e.parent}catch(e){}}function u(e){try{return!0}catch(e){}return!1}function s(e){void 0===e&&(e=window);var n=e.location;if(!n)throw new Error("Can not read window location");var t=o(e);if(!t)throw new Error("Can not read window protocol");if("file:"===t)return"file://";if("about:"===t){var r=c(e);return r&&u()?s(r):"about://"}var i=n.host;if(!i)throw new Error("Can not read window host");return t+"//"+i}function l(e){void 0===e&&(e=window);var n=s(e);return n&&e.mockDomain&&0===e.mockDomain.indexOf("mock:")?e.mockDomain:n}function d(e){if(!function(e){try{if(e===window)return!0}catch(e){}try{var n=Object.getOwnPropertyDescriptor(e,"location");if(n&&!1===n.enumerable)return!1}catch(e){}try{if(a(e)&&u())return!0}catch(e){}try{if(function(e){return void 0===e&&(e=window),"mock:"===i(e)}(e)&&u())return!0}catch(e){}try{if(s(e)===s(window))return!0}catch(e){}return!1}(e))return!1;try{if(e===window)return!0;if(a(e)&&u())return!0;if(l(window)===l(e))return!0}catch(e){}return!1}function f(e){if(!d(e))throw new Error("Expected window to be same domain");return e}function p(e,n){if(!e||!n)return!1;var t=c(n);return t?t===e:-1!==function(e){var n=[];try{for(;e.parent!==e;)n.push(e.parent),e=e.parent}catch(e){}return n}(n).indexOf(e)}function h(e){for(var n=[],t=0,r=function(e){var n,t,r=[];try{n=e.frames}catch(t){n=e}try{t=n.length}catch(e){}if(0===t)return r;if(t){for(var o=0;o0&&Object(s.e)().info("button_shipping_change_patch_data_has_invalid_path_"+n,Object(o.a)({},i,{rejected:JSON.stringify(a)}))}else Object(s.e)().info("button_shipping_change_patch_data_is_object",i)}catch(e){Object(s.e)().error("button_shipping_change_patch_data_logging_failed",Object(o.a)({},i,{errMessage:JSON.stringify(e)}))}}({appName:p,buyerAccessToken:r,data:e,shouldUsePatchShipping:i}),i?Object(c.K)({clientID:d,data:e,orderID:n}).catch((function(){throw new Error("Order could not be patched")})):Object(l.a)(h,r)?Object(c.I)(n,e,{facilitatorAccessToken:t,buyerAccessToken:r,partnerAttributionID:a,forceRestAPI:u,experiments:f}).catch((function(){throw new Error("Order could not be patched")})):Object(c.P)(t,r,n).then((function(t){return Object(c.I)(n,e,{facilitatorAccessToken:t,buyerAccessToken:r,partnerAttributionID:a,forceRestAPI:u,experiments:f}).catch((function(){throw new Error("Order could not be patched")}))}))}}}}({orderID:e,facilitatorAccessToken:v,buyerAccessToken:y,actions:n,partnerAttributionID:f,forceRestAPI:T,clientID:m,experiments:h,appName:I,paymentSource:_}))}))}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return a})),t.d(n,"b",(function(){return c}));var r=t(0),o=t(3),i=(t(4),t(2)),a=function(e,n){return e===r.j.VENMO&&!n},c=function(e){if(!e)throw new Error("Expected redirect url");if(-1===e.indexOf("://"))throw Object(i.e)().warn("redir_url_non_scheme",{url:e}).flush(),new Error("Invalid redirect url: "+e+" - must be fully qualified url");if(!e.match(/^https:\/\//)&&(Object(i.e)().warn("redir_url_non_http",{url:e}).flush(),e.toLowerCase().replace(/[^a-z:]+/g,"").match(/^javascript:/)))throw Object(i.e)().warn("redir_url_has_javascript",{url:e}).flush(),new Error("Invalid redirect url: "+e+" - must be fully qualified url");return Object(o.H)(e,window.top)}},function(e,n,t){"use strict";t.d(n,"c",(function(){return i})),t.d(n,"e",(function(){return a})),t.d(n,"a",(function(){return c})),t.d(n,"b",(function(){return u})),t.d(n,"d",(function(){return s})),t.d(n,"g",(function(){return l})),t.d(n,"f",(function(){return d}));var r=t(6),o=t(11),i=function(e){var n=e.breakdown,t=e.updatedAmounts,r=0,o=Object.keys(t)||[],i=["shipping_discount","discount"];return Object.keys(n).forEach((function(e){var a,c;-1!==o.indexOf(e)?i.includes(e)?r-=Math.abs(parseFloat(t[e])):r+=parseFloat(t[e]):i.includes(e)?r-=Math.abs(parseFloat(null==(a=n[e])?void 0:a.value)):r+=parseFloat(null==(c=n[e])?void 0:c.value)})),o.forEach((function(e){n[e]||t[e]&&(i.includes(e)?r-=Math.abs(parseFloat(t[e])):r+=parseFloat(t[e]))})),r.toFixed(2)},a=function(e){var n=[];return e.forEach((function(e){var t=Object(r.a)({},e,{amount:{value:e.amount.value,currency_code:e.amount.currencyCode}});n.push(t)})),n},c=function(e){return Object(r.a)({},e.discount?{discount:{value:e.discount.value,currency_code:e.discount.currencyCode}}:void 0,e.handling?{handling:{value:e.handling.value,currency_code:e.handling.currencyCode}}:void 0,e.insurance?{insurance:{value:e.insurance.value,currency_code:e.insurance.currencyCode}}:void 0,e.itemTotal?{item_total:{value:e.itemTotal.value,currency_code:e.itemTotal.currencyCode}}:void 0,e.shipping?{shipping:{value:e.shipping.value,currency_code:e.shipping.currencyCode}}:void 0,e.shippingDiscount?{shipping_discount:{value:e.shippingDiscount.value,currency_code:e.shippingDiscount.currencyCode}}:void 0,e.taxTotal?{tax_total:{value:e.taxTotal.value,currency_code:e.taxTotal.currencyCode}}:void 0)},u=function(e){var n,t=e.breakdown,r=void 0===t?{}:t,o=e.updatedAmounts,i=void 0===o?{}:o,a=["shipping_discount","discount"],c=Object.keys(i),u=null==(n=Object.values(r)[0])?void 0:n.currency_code;return c.forEach((function(e){r[e]?r[e].value=i[e]:i[e]&&(r[e]={currency_code:u,value:i[e]&&a.includes(e)?Math.abs(parseFloat(i[e])).toFixed(2):i[e]})})),r},s=function(e){return Object.values(e.queries)||[]},l=function(e){var n=e.option,t=[];return e.options.forEach((function(e){if(!e.id)throw new Error("Must provide an id with each shipping option.");e.id===n.id?(n.selected=!0,t.push(n)):(e.selected=!1,t.push(e))})),t},d=function(e){var n=e.queries;return n[o.b.OPTIONS]&&(n[o.b.OPTIONS].op="replace"),s({queries:n})}},function(e,n,t){"use strict";function r(e,n){if(null==e)return{};var t,r,o={},i=Object.keys(e);for(r=0;r=0||(o[t]=e[t]);return o}t.d(n,"a",(function(){return r}))},function(e,n,t){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,n,t,r){void 0===r&&(r=t),Object.defineProperty(e,r,{enumerable:!0,get:function(){return n[t]}})}:function(e,n,t,r){void 0===r&&(r=t),e[r]=n[t]}),o=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),i=(this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&r(n,e,t);return o(n,e),n})(t(43)),a=t(51),c=t(52),u=t(54),s=t(45),l=t(37),d=t(57),f=t(58);e.exports={creditCardType:i,cardholderName:a.cardholderName,number:c.cardNumber,expirationDate:u.expirationDate,expirationMonth:s.expirationMonth,expirationYear:l.expirationYear,cvv:d.cvv,postalCode:f.postalCode}},function(e,n,t){"use strict";var r=t(19);t.d(n,"getProps",(function(){return r.a})),t(25);var o=t(33);t.d(n,"getConfirmOrder",(function(){return o.a})),t(23),t(24),t(32),t(26),t(27),t(20),t(28),t(11),t(29),t(30),t(21),t(22);var i=t(38);t.d(n,"POPUP_BRIDGE_OPTYPE",(function(){return i.a})),t(39),t(40),t(31),t(41),t(42)},function(e,n,t){"use strict";t.d(n,"l",(function(){return l})),t.d(n,"j",(function(){return d})),t.d(n,"b",(function(){return f})),t.d(n,"k",(function(){return p})),t.d(n,"h",(function(){return h})),t.d(n,"f",(function(){return m})),t.d(n,"a",(function(){return _})),t.d(n,"g",(function(){return g})),t.d(n,"e",(function(){return v})),t.d(n,"i",(function(){return b})),t.d(n,"d",(function(){return y})),t.d(n,"c",(function(){return E}));var r=t(6),o=t(4),i=t(3),a=t(0),c=t(9),u=t(1),s=t(10);function l(){return new o.a(i.y)}function d(){return o.a.resolve()}function f(){var e=document.body;if(!e)throw new Error("Document body not found");return e}function p(e){var n=document.createElement("img");n.src=e,n.style.visibility="hidden",n.style.position="absolute",document.body&&document.body.appendChild(n)}function h(e){return new o.a((function(n,t){var r=document.body||document.head;if(!r)return t(new Error("Can not find container for script: "+e));var o=document.createElement("script");o.setAttribute("src",e),o.addEventListener("load",(function(){return n(o)})),o.addEventListener("error",(function(e){return t(e)})),r.appendChild(o)}))}function m(e){return Boolean(e.match(/^.+@.+\..+$/))}function _(e,n){var t=n.sample,o=n.sticky,c=void 0===o||o,l=Object(s.a)();return Object(i.g)({name:e,sample:t,logTreatment:function(n){var t,o=n.treatment,i=n.payload,c=Object(r.a)(((t={})[a.g.STATE]=u.k.PXP,t[a.g.TRANSITION]=u.l.PXP,t[a.g.EXPERIMENT_NAME]=e,t[a.g.TREATMENT_NAME]=o,t),i);l.track(c),l.flush()},logCheckpoint:function(e){var n=e.payload,t=e.throttle;l.info(e.treatment+"_"+e.checkpoint,Object(r.a)({},n,{throttle:t.toString()})),l.flush()},sticky:c})}function g(){return Object(i.u)()&&Object(i.v)()}function v(){return Object(i.o)()&&Object(i.q)()}function b(e,n,t,r){void 0===t&&(t=1e3),void 0===r&&(r=1/0);var o=!1,i=function(){o=!0};return e.awaitWindow().then((function(e){o||(i=Object(c.j)(e,n,t,r).cancel)})),{cancel:i}}function y(){if(window.performance){var e=window.performance.now(),n=(new Date).getTime();return window.performance.timeOrigin||window.performance.timing.navigationStart||n-e}throw new Error("window.performance not supported")}function E(){try{return String((new Date).getTime())}catch(e){return"invalid_timestamp"}}},function(e,n,t){e.exports=t(59)},function(e,n,t){"use strict";t.d(n,"a",(function(){return u})),t(0);var r=t(4),o=t(2),i=t(20),a=t(21),c=t(22);function u(e){var n=e.branded,t=window.xprops,u=t.uid,s=t.env,l=t.vault,d=void 0!==l&&l,f=t.commit,p=t.locale,h=t.platform,m=t.sessionID,_=t.clientID,g=t.partnerAttributionID,v=t.merchantRequestedPopupsDisabled,b=t.clientMetadataID,y=t.sdkCorrelationID,E=t.getParentDomain,T=t.clientAccessToken,O=t.getPopupBridge,I=t.getPrerenderDetails,w=t.getPageUrl,S=t.enableThreeDomainSecure,A=t.enableVaultInstallments,D=t.enableNativeCheckout,C=void 0!==D&&D,N=t.remember,k=t.stageHost,P=t.apiStageHost,R=t.getParent,j=t.fundingSource,L=t.currency,U=t.connect,M=t.intent,x=t.merchantID,F=t.amount,B=t.userIDToken,V=t.enableFunding,H=t.disableFunding,G=t.disableCard,K=t.disableAutocomplete,Y=t.wallet,W=t.paymentMethodToken,q=void 0===W?t.paymentMethodNonce:W,$=t.getQueriedEligibleFunding,z=void 0===$?function(){return r.a.resolve([])}:$,X=t.storageID,J=t.applePay,Q=t.userExperienceFlow,Z=t.allowBillingPayments,ee=t.paymentRequest,ne=t.disableSetCookie,te=void 0!==ne&&ne,re=Object(i.a)({onInit:t.onInit}),oe="function"==typeof E?E():"unknown";V=V||[],H=H||[];var ie=Object(a.a)({onClick:t.onClick}),ae=X&&Object(o.n)()?X:Object(o.i)();return{uid:u,env:s,vault:d,commit:f,clientAccessToken:T,locale:p,sessionID:m,clientID:_,partnerAttributionID:g,clientMetadataID:b,sdkCorrelationID:y,merchantDomain:oe,platform:h,currency:L,intent:M,wallet:Y,merchantRequestedPopupsDisabled:v,getPopupBridge:O,getPrerenderDetails:I,getPageUrl:w,rememberFunding:N,getParent:R,connect:U,fundingSource:j,enableFunding:V,disableFunding:H,disableCard:G,disableAutocomplete:K,getQueriedEligibleFunding:z,amount:F,userIDToken:B,enableThreeDomainSecure:S,enableNativeCheckout:C,enableVaultInstallments:A,onClick:ie,onInit:re,onError:Object(c.a)({onError:t.onError}),stageHost:k,apiStageHost:P,standaloneFundingSource:j,paymentMethodToken:q,branded:n,stickinessID:ae,applePay:J,userExperienceFlow:Q,allowBillingPayments:Z,paymentRequest:ee,merchantID:x,disableSetCookie:te}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return o}));var r=t(4);function o(e){var n=e.onInit;return function(e){var t=!0;return{initPromise:r.a.try((function(){if(n)return n(e,(o=function(e){t=e},{enable:function(){return r.a.try((function(){return o(!0)}))},disable:function(){return r.a.try((function(){return o(!1)}))}}));var o})),isEnabled:function(){return t}}}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return i}));var r=t(4),o=(t(0),t(3));function i(e){var n=e.onClick;if(n)return Object(o.x)((function(e){var t;return n((t={fundingSource:e.fundingSource},{fundingSource:t.fundingSource}),{resolve:function(){return r.a.try((function(){return!0}))},reject:function(){return r.a.try((function(){return!1}))}}).then((function(e){return!1!==e}))}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return i}));var r=t(4),o=t(3);function i(e){var n=e.onError,t=n?Object(o.e)(n):o.y;return function(e){return r.a.try((function(){return t(e)}))}}},function(e,n,t){"use strict";function r(e){var n=e.createBillingAgreement,t=e.paymentSource;if(n)return function(){return n((e={paymentSource:t},{paymentSource:e.paymentSource}),{}).then((function(e){if(!e||"string"!=typeof e)throw new Error("Expected a billing token to be passed to createBillingAgreement");return e}));var e}}t.d(n,"a",(function(){return r})),t(0)},function(e,n,t){"use strict";t.d(n,"a",(function(){return i})),t(0);var r=t(5),o=t(2);function i(e,n){var t=e.createSubscription,i=e.partnerAttributionID,a=e.merchantID,c=e.clientID,u=e.paymentSource,s=n.facilitatorAccessToken;if(t)return a&&a[0]&&(Object(o.e)().info("src_props_subscriptions_recreate_access_token_cache"),Object(r.h)(c,{targetSubject:a[0]})),function(){return t((e={paymentSource:u},{paymentSource:e.paymentSource}),function(e){var n=e.facilitatorAccessToken,t=e.partnerAttributionID,o=e.merchantID,i=e.clientID;return{subscription:{create:function(e){return Object(r.k)(n,e,{partnerAttributionID:t,merchantID:o,clientID:i})},revise:function(e,a){return Object(r.L)(n,e,a,{partnerAttributionID:t,merchantID:o,clientID:i})}}}}({facilitatorAccessToken:s,partnerAttributionID:i,merchantID:a,clientID:c})).then((function(e){if(!e||"string"!=typeof e)throw new Error("Expected an subscription id to be passed to createSubscription");return e}));var e}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return p}));var r=t(6),o=t(4),i=t(3),a=t(0),c=t(9),u=t(5),s=t(1),l=t(2),d=t(8),f=t(34);function p(e,n){var t=e.createOrder,p=e.intent,h=e.currency,m=n.createBillingAgreement,_=n.createSubscription,g=n.createVaultSetupToken,v=n.flow,b="vault_without_purchase"===v&&g,y={paymentSource:e.paymentSource},E=function(e){var n=e.facilitatorAccessToken,t=e.intent,o=e.currency,i=e.merchantID,s=e.partnerAttributionID,f=e.experiments,p=function(e){var n=e.facilitatorAccessToken,t=e.intent,o=e.currency,i=e.merchantID,c=e.partnerAttributionID,s=e.experiments;return{create:function(e){var d=Object(r.a)({},e);if(d.intent&&d.intent.toLowerCase()!==t)throw new Error("Unexpected intent: "+d.intent+" passed to order.create. Please ensure you are passing /sdk/js?"+a.n.INTENT+"="+d.intent.toLowerCase()+" in the paypal script tag.");return(d=Object(r.a)({},d,{intent:t.toUpperCase()})).purchase_units=d.purchase_units.map((function(e){if(e.amount.currency_code&&e.amount.currency_code!==o)throw new Error("Unexpected currency: "+e.amount.currency_code+" passed to order.create. Please ensure you are passing /sdk/js?"+a.n.CURRENCY+"="+e.amount.currency_code+" in the paypal script tag.");var n=e.payee;if(i&&1===i.length&&i[0]){var t=i[0];n=Object(l.l)(t)?Object(r.a)({},n,{email_address:t}):Object(r.a)({},n,{merchant_id:t})}return Object(r.a)({},e,{payee:n,amount:Object(r.a)({},e.amount,{currency_code:o})})})),d.application_context=d.application_context||{},Object(u.i)(d,{facilitatorAccessToken:n,partnerAttributionID:c,forceRestAPI:!1,experiments:s})}}}({facilitatorAccessToken:n,intent:t,currency:o,merchantID:i,partnerAttributionID:s,experiments:f}),h=function(e){var n=e.facilitatorAccessToken,t=e.intent,o=e.currency,i=e.merchantID,s=e.partnerAttributionID;return{create:function(e){var d=Object(r.a)({},e),f=t===a.k.CAPTURE?"sale":t;if(d.intent&&d.intent!==f)throw new Error("Unexpected intent: "+d.intent+" passed to order.create. Expected "+f);return(d=Object(r.a)({},d,{intent:f})).transactions=d.transactions.map((function(e){if(e.amount.currency&&e.amount.currency!==o)throw new Error("Unexpected currency: "+e.amount.currency+" passed to order.create. Please ensure you are passing /sdk/js?"+a.n.CURRENCY+"="+e.amount.currency+" in the paypal script tag.");var n=e.payee;if(i&&1===i.length&&i[0]){var t=i[0];n=Object(l.l)(t)?Object(r.a)({},n,{email_address:t}):Object(r.a)({},n,{merchant_id:t})}return Object(r.a)({},e,{payee:n,amount:Object(r.a)({},e.amount,{currency:o})})})),d.redirect_urls=d.redirect_urls||{},d.redirect_urls.return_url=d.redirect_urls.return_url||Object(c.c)()+"/checkoutnow/error",d.redirect_urls.cancel_url=d.redirect_urls.cancel_url||Object(c.c)()+"/checkoutnow/error",d.payer=d.payer||{},d.payer.payment_method=d.payer.payment_method||"paypal",Object(u.j)(d,{facilitatorAccessToken:n,partnerAttributionID:s})}}}({facilitatorAccessToken:n,intent:t,currency:o,merchantID:i,partnerAttributionID:s,experiments:f});return{order:p,payment:d.c?h:null}}({facilitatorAccessToken:n.facilitatorAccessToken,intent:p,currency:h,merchantID:e.merchantID,partnerAttributionID:e.partnerAttributionID,experiments:e.experiments}),T="server-side";return Object(i.x)((function(){var e=Object(i.j)("orderID");if(e)return o.a.resolve(e);var n=Date.now();return o.a.try((function(){return b?g().then(f.b):m?m().then(u.d):_?_().then(u.M):t?t(y,E):(T="client-side",E.order.create({purchase_units:[{amount:{currency_code:h,value:"0.01"}}]}))})).catch((function(e){var n;throw b||(Object(l.u)({name:"pp.app.paypal_sdk.buttons.create_order.error.count",dimensions:{errorName:"generic",flow:v,intent:p,integrationType:T}}),Object(l.e)().error("create_order_error",{err:Object(i.L)(e)}).track(((n={})[a.g.STATE]=s.k.BUTTON,n[a.g.ERROR_CODE]="smart_buttons_create_order_error",n[a.g.ERROR_DESC]=Object(i.L)(e),n))),e})).then((function(e){var t,r;if(!e||"string"!=typeof e)throw Object(l.u)({name:"pp.app.paypal_sdk.buttons.create_order.error.count",dimensions:{errorName:"no_order_id",flow:v,intent:p,integrationType:T}}),Object(l.e)().track(((t={})[a.g.STATE]=s.k.BUTTON,t[a.g.ERROR_CODE]="smart_buttons_create_order_error",t[a.g.ERROR_DESC]="Expected an order id to be passed",t)),new Error("Expected an order id to be passed");if(0===e.indexOf("PAY-")||0===e.indexOf("PAYID-"))throw Object(l.u)({name:"pp.app.paypal_sdk.buttons.create_order.error.count",dimensions:{errorName:"pay_id",flow:v,intent:p,integrationType:T}}),Object(l.e)().track(((r={})[a.g.STATE]=s.k.BUTTON,r[a.g.ERROR_CODE]="smart_buttons_create_order_error",r[a.g.ERROR_DESC]="Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead",r)),new Error("Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead");if(!b){var o,i=Date.now()-n;Object(l.u)({name:"pp.app.paypal_sdk.buttons.create_order.count",dimensions:{flow:v,intent:p,integrationType:T}}),Object(l.e)().addPayloadBuilder((function(){return{token:e}})).addTrackingBuilder((function(){var n;return(n={})[a.g.CONTEXT_TYPE]=s.h.ORDER_ID,n[a.g.CONTEXT_ID]=e,n[a.g.TOKEN]=e,n})).track((o={},o[a.g.STATE]=s.k.BUTTON,o[a.g.TRANSITION]=s.l.RECEIVE_ORDER,o[a.g.EVENT_NAME]=s.l.RECEIVE_ORDER,o[a.g.CONTEXT_TYPE]=s.h.ORDER_ID,o[s.f.BUTTON_WIDTH]=window.innerWidth,o[a.g.CONTEXT_ID]=e,o[a.g.TOKEN]=e,o[a.g.RESPONSE_DURATION]=i.toString(),o.client_time=Object(l.d)(),o)).flush()}return e}))}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return p}));var r=t(6),o=t(4),i=t(3),a=t(0),c=t(5),u=t(1),s=t(2),l=t(8),d=t(12),f=function(e,n,t){if(Object(c.E)(e))return e&&e.response&&(e.message=JSON.stringify(e.response)||e.message),t(e).then(s.z);if(Object(c.D)(e))return n().then(s.z);throw e};function p(e){var n=e.intent,t=e.createBillingAgreement,p=e.createSubscription,h=e.onApprove,m=e.partnerAttributionID,_=e.onError,g=e.clientAccessToken,v=e.vault,b=e.clientID,y=e.facilitatorAccessToken,E=e.branded,T=e.createOrder,O=e.paymentSource,I=e.featureFlags,w=e.createVaultSetupToken,S=e.flow,A=e.experiments,D=function(){Object(s.u)({name:"pp.app.paypal_sdk.buttons.click.success.count",dimensions:Object(r.a)({spbPaymentFlow:S},A)})};if(S&&"vault_without_purchase"===S&&w)return function(e){var n=e.onApprove,t=e.onError,r=e.facilitatorAccessToken,c=e.createOrder,l=e.paymentSource,d=e.createVaultSetupToken,f=e.beforeOnApprove;if(!n)throw new Error("Expected onApprove");return Object(i.x)((function(e){var i=e.payerID;return c().then((function(e){var c;return Object(s.e)().info("button_approve").track((c={},c[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,c[a.g.EVENT_NAME]=u.l.CHECKOUT_APPROVE,c[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,c[a.g.TOKEN]=e,c[a.g.CONTEXT_ID]=e,c)).flush(),d().then((function(e){var c={payerID:i,facilitatorAccessToken:r,paymentSource:l,vaultSetupToken:e};return f(),n(c).then((function(n){var t;return Object(s.e)().track((t={},t[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,t[a.g.CONTEXT_TYPE]=u.h.VAULT_SETUP_TOKEN,t[a.g.TOKEN]=e,t[a.g.CONTEXT_ID]=e,t)).flush(),n})).catch((function(e){return o.a.try((function(){return t(e)})).then((function(){throw e}))}))}))}))}))}({onApprove:h,onError:_,facilitatorAccessToken:y,createOrder:T,paymentSource:O,createVaultSetupToken:w,beforeOnApprove:D});if(t)return function(e){var n=e.onApprove,t=void 0===n?function(){throw new Error("Expected onApprove")}:n,r=e.onError,l=e.facilitatorAccessToken,f=e.createOrder,p=e.paymentSource,h=e.beforeOnApprove;if(!t)throw new Error("Expected onApprove");return Object(i.x)((function(e,n){var i=e.payerID,m=e.paymentID,_=e.billingToken,g=n.restart;return f().then((function(e){var n;return Object(s.e)().info("button_approve").track((n={},n[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,n[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,n[a.g.TOKEN]=e,n[a.g.CONTEXT_ID]=e,n)).flush(),Object(c.C)(e).then((function(n){var a={orderID:e,payerID:i,paymentID:m=m||n&&n.checkoutSession&&n.checkoutSession.cart&&n.checkoutSession.cart.paymentId,billingToken:_=_||n&&n.checkoutSession&&n.checkoutSession.cart&&n.checkoutSession.cart.billingToken,facilitatorAccessToken:l,paymentSource:p},c={restart:g,redirect:d.b};return h(),t(a,c).catch((function(e){return o.a.try((function(){return r(e)})).then((function(){throw e}))}))}))}))}))}({onApprove:h,onError:_,facilitatorAccessToken:y,createOrder:T,paymentSource:O,beforeOnApprove:D});if(n===a.k.SUBSCRIPTION||p)return function(e){var n=e.onApprove,t=void 0===n?function(){throw new Error("Expected onApprove")}:n,r=e.onError,l=e.facilitatorAccessToken,f=e.createOrder,p=e.paymentSource,h=e.beforeOnApprove;if(!t)throw new Error("Expected onApprove");return Object(i.x)((function(e,n){var m=e.payerID,_=e.subscriptionID,g=e.buyerAccessToken,v=n.restart;if(!_)throw new Error("Expected subscriptionID");return f().then((function(e){var n;Object(s.e)().info("button_approve").track((n={},n[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,n[a.g.EVENT_NAME]=u.l.CHECKOUT_APPROVE,n[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,n[a.g.TOKEN]=e,n[a.g.CONTEXT_ID]=e,n)).flush();var f={orderID:e,payerID:m,subscriptionID:_,facilitatorAccessToken:l,paymentSource:p},b=function(e){var n=e.restart,t=e.subscriptionID,r=e.buyerAccessToken;return{subscription:{get:Object(i.x)((function(){if(!t)throw new Error("No subscription ID present");return Object(c.B)(t,{buyerAccessToken:r})})),activate:Object(i.x)((function(){if(!t)throw new Error("No subscription ID present");return Object(c.a)(t,{buyerAccessToken:r})}))},restart:n,redirect:d.b}}({restart:v,subscriptionID:_,buyerAccessToken:g});return h(),t(f,b).catch((function(e){return o.a.try((function(){return r(e)})).then((function(){throw e}))}))}))}))}({clientID:b,onApprove:h,onError:_,facilitatorAccessToken:y,createOrder:T,paymentSource:O,beforeOnApprove:D});if(n===a.k.CAPTURE||n===a.k.AUTHORIZE||n===a.k.ORDER)return function(e){var n=e.intent,t=e.onApprove,r=void 0===t?function(e){return function(n,t){if(e===a.k.CAPTURE)return t.order.capture().then(i.y);if(e===a.k.AUTHORIZE)return t.order.authorize().then(i.y);throw new Error("Unsupported intent for auto-capture: "+e)}}(n):t,p=e.partnerAttributionID,h=e.onError,m=e.clientAccessToken,_=e.vault,g=e.facilitatorAccessToken,v=e.branded,b=e.createOrder,y=e.paymentSource,E=e.featureFlags,T=e.experiments,O=e.beforeOnApprove;if(!r)throw new Error("Expected onApprove");return Object(i.x)((function(e,t){var I=e.payerID,w=e.paymentID,S=e.billingToken,A=e.buyerAccessToken,D=e.authCode,C=e.forceRestAPI,N=void 0===C?E.isLsatUpgradable:C,k=t.restart;return b().then((function(e){var t;return Object(s.e)().info("button_approve").track((t={},t[a.g.STATE]=u.k.BUTTON,t[a.g.TRANSITION]=u.l.CHECKOUT_APPROVE,t[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,t[a.g.TOKEN]=e,t[a.g.CONTEXT_ID]=e,t)).flush(),S||m||_||!I&&v&&Object(s.e)().warn("onapprove_payerid_not_present_for_branded_standalone_button",{orderID:e}).flush(),Object(c.C)(e).then((function(t){S=S||t&&t.checkoutSession&&t.checkoutSession.cart&&t.checkoutSession.cart.billingToken,(w=w||t&&t.checkoutSession&&t.checkoutSession.cart&&t.checkoutSession.cart.paymentId)||S||(w=e.replace(/EC-/,""));var u={orderID:e,payerID:I,paymentID:w,billingToken:S,facilitatorAccessToken:g,authCode:D,paymentSource:y},s=function(e){var n=e.intent,t=e.orderID,r=e.paymentID,o=e.payerID,u=e.restart,s=e.facilitatorAccessToken,p=e.buyerAccessToken,h=e.partnerAttributionID,m=e.forceRestAPI,_=e.onError,g=function(e){var n=e.intent,t=e.orderID,r=e.restart,o=e.facilitatorAccessToken,u=e.buyerAccessToken,s=e.partnerAttributionID,l=e.forceRestAPI,p=e.onError,h=e.experiments,m=e.paymentSource,_=Object(i.x)((function(){return Object(d.a)(m,u)?Object(c.x)(t,{facilitatorAccessToken:o,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l,experiments:h}):Object(c.P)(o,u,t).then((function(e){return Object(c.x)(t,{facilitatorAccessToken:e,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l,experiments:h})}))})),g=Object(i.x)((function(){if(n!==a.k.CAPTURE)throw new Error("Use "+a.n.INTENT+"="+a.k.CAPTURE+" to use client-side capture");return Object(d.a)(m,u)?Object(c.f)(t,{facilitatorAccessToken:o,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l,experiments:h}).finally(_.reset).finally(g.reset).catch((function(e){return f(e,r,p)})):Object(c.P)(o,u,t).then((function(e){return Object(c.f)(t,{facilitatorAccessToken:e,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l,experiments:h}).finally(_.reset).finally(g.reset).catch((function(e){return f(e,r,p)}))}))})),v=Object(i.x)((function(){if(n!==a.k.AUTHORIZE)throw new Error("Use "+a.n.INTENT+"="+a.k.AUTHORIZE+" to use client-side authorize");return Object(d.a)(m,u)?Object(c.c)(t,{facilitatorAccessToken:o,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l,experiments:h}).finally(_.reset).finally(v.reset).catch((function(e){return f(e,r,p)})):Object(c.P)(o,u,t).then((function(e){return Object(c.c)(t,{facilitatorAccessToken:e,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l,experiments:h}).finally(_.reset).finally(v.reset).catch((function(e){return f(e,r,p)}))}))}));return{capture:g,authorize:v,patch:function(e){return void 0===e&&(e={}),Object(d.a)(m,u)?Object(c.I)(t,e,{facilitatorAccessToken:o,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l,experiments:h}).catch((function(){throw new Error("Order could not be patched")})):Object(c.P)(o,u,t).then((function(n){return Object(c.I)(t,e,{facilitatorAccessToken:n,buyerAccessToken:u,partnerAttributionID:s,forceRestAPI:l,experiments:h}).catch((function(){throw new Error("Order could not be patched")}))}))},get:_}}({intent:n,orderID:t,paymentID:r,payerID:o,restart:u,facilitatorAccessToken:s,buyerAccessToken:p,partnerAttributionID:h,forceRestAPI:m,onError:_,experiments:e.experiments,paymentSource:e.paymentSource}),v=function(e){var n=e.intent,t=e.paymentID,r=e.payerID,o=e.restart,u=e.facilitatorAccessToken,s=e.buyerAccessToken,l=e.partnerAttributionID,d=e.onError;if(t){var p=Object(i.x)((function(){return Object(c.y)(t,{facilitatorAccessToken:u,buyerAccessToken:s,partnerAttributionID:l})})),h=Object(i.x)((function(){if(!r)throw new Error("payerID required for payment execute");if(n!==a.k.CAPTURE)throw new Error("Use "+a.n.INTENT+"="+a.k.CAPTURE+" to use client-side capture");return Object(c.o)(t,r,{facilitatorAccessToken:u,buyerAccessToken:s,partnerAttributionID:l}).finally(p.reset).finally(h.reset).catch((function(e){return f(e,o,d)}))}));return{execute:h,patch:function(e){return void 0===e&&(e={}),Object(c.J)(t,e,{facilitatorAccessToken:u,buyerAccessToken:s,partnerAttributionID:l}).catch((function(){throw new Error("Order could not be patched")}))},get:p}}}({intent:n,orderID:t,paymentID:r,payerID:o,restart:u,facilitatorAccessToken:s,buyerAccessToken:p,partnerAttributionID:h,forceRestAPI:m,onError:_});return{order:g,payment:l.c?v:null,restart:u,redirect:d.b}}({orderID:e,paymentID:w,payerID:I,intent:n,restart:k,facilitatorAccessToken:g,buyerAccessToken:A,partnerAttributionID:p,onError:h,forceRestAPI:N,experiments:T,paymentSource:y});return O(),r(u,s).catch((function(e){return o.a.try((function(){return h(e)})).then((function(){throw e}))}))}))}))}))}({intent:n,onApprove:h,partnerAttributionID:m,onError:_,clientAccessToken:g,vault:v,facilitatorAccessToken:y,branded:E,createOrder:T,paymentSource:O,featureFlags:I,experiments:A,beforeOnApprove:D});if(n===a.k.TOKENIZE)return function(e){var n=e.onApprove,t=void 0===n?function(){throw new Error("Expected onApprove")}:n,r=e.onError,c=e.facilitatorAccessToken,l=e.paymentSource,f=e.beforeOnApprove;if(!t)throw new Error("Expected onApprove");return Object(i.x)((function(e,n){var i,p=e.paymentMethodToken,h=n.restart;if(!p)throw new Error("Payment method token required for tokenize onApprove");Object(s.e)().info("button_approve").track((i={},i[a.g.TRANSITION]=u.l.TOKENIZE_APPROVE,i)).flush();var m={facilitatorAccessToken:c,paymentMethodToken:p,paymentSource:l},_={restart:h,redirect:d.b};return f(),t(m,_).catch((function(e){return o.a.try((function(){return r(e)})).then((function(){throw e}))}))}))}({onApprove:h,onError:_,facilitatorAccessToken:y,paymentSource:O,beforeOnApprove:D});throw new Error("Unsupported intent: "+n)}},function(e,n,t){"use strict";t.d(n,"a",(function(){return l}));var r=t(4),o=t(3),i=t(0),a=t(2),c=t(1),u=t(5),s=t(12);function l(e){var n=e.intent,t=e.onComplete,l=e.partnerAttributionID,d=e.onError,f=e.facilitatorAccessToken,p=e.createOrder,h=e.featureFlags,m=e.experiments;return t?Object(o.x)((function(e){var _=e.buyerAccessToken,g=e.forceRestAPI,v=void 0===g?h.isLsatUpgradable:g;return p().then((function(e){var p;Object(a.e)().info("button_complete").track((p={},p[i.g.TRANSITION]=c.l.CHECKOUT_COMPLETE,p[i.g.EVENT_NAME]=c.l.CHECKOUT_COMPLETE,p[i.g.CONTEXT_TYPE]=c.h.ORDER_ID,p[i.g.TOKEN]=e,p[i.g.CONTEXT_ID]=e,p)).flush();var h=function(e){var n=e.orderID,t=e.facilitatorAccessToken,r=e.buyerAccessToken,i=e.partnerAttributionID,a=e.forceRestAPI,c=e.experiments,l=Object(o.x)((function(){return Object(u.x)(n,{facilitatorAccessToken:t,buyerAccessToken:r,partnerAttributionID:i,forceRestAPI:a,experiments:c}).finally(l.reset)}));return{order:{get:l},redirect:s.b}}({orderID:e,facilitatorAccessToken:f,buyerAccessToken:_,partnerAttributionID:l,onError:d,forceRestAPI:v,experiments:m});return t({orderID:e,intent:n},h).catch((function(e){return r.a.try((function(){return d(e)})).then((function(){throw e}))}))}))})):a.r}},function(e,n,t){"use strict";t.d(n,"a",(function(){return u}));var r=t(3),o=(t(4),t(0)),i=t(2),a=t(1),c=t(12);function u(e,n){var t=e.onCancel,u=void 0===t?i.r:t,s=e.onError,l=n.createOrder;return Object(r.x)((function(){return l().then((function(e){var n;return Object(i.e)().info("button_cancel").track((n={},n[o.g.TRANSITION]=a.l.CHECKOUT_CANCEL,n[o.g.EVENT_NAME]=a.l.CHECKOUT_CANCEL,n[o.g.CONTEXT_TYPE]=a.h.ORDER_ID,n[o.g.TOKEN]=e,n[o.g.CONTEXT_ID]=e,n)).flush(),u({orderID:{orderID:e}.orderID},{redirect:c.b})})).catch((function(e){return s(e)}))}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return p}));var r=t(35),o=t(6),i=t(14),a=(t(4),t(0)),c=t(5),u=t(1),s=t(2),l=t(11),d=t(13),f=["amount","buyerAccessToken","event","forceRestAPI","shippingAddress"];function p(e,n){var t=e.onShippingAddressChange,p=n.createOrder;if(t)return function(e,n){var h=Object(o.a)({},(Object(r.a)(e),e));return p().then((function(e){var r;return Object(s.e)().info("button_shipping_address_change").track((r={},r[a.g.TRANSITION]=u.l.CHECKOUT_SHIPPING_ADDRESS_CHANGE,r[a.g.EVENT_NAME]=u.l.CHECKOUT_SHIPPING_ADDRESS_CHANGE,r[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,r[a.g.TOKEN]=e,r[a.g.CONTEXT_ID]=e,r[u.i.SHIPPING_CALLBACK_INVOKED]="1",r)).flush(),t(function(e){var n=e.shippingAddress,t=Object(i.a)(e,f);return Object(o.a)({errors:l.c,shippingAddress:n},t)}(h),function(e){var n,t=e.data,r=e.actions,o=e.orderID,i={},a=null!=(n=t.amount)&&n.breakdown?Object(d.a)(t.amount.breakdown):{};if(0===Object.keys(a).length)throw new Error("Must pass amount with breakdown into data attribute for onShippingAddressChange callback.");return{reject:r.reject?function(e){return-1===Object.values(l.c).indexOf(e)?r.reject(l.a):r.reject(e)}:function(){throw new Error("Missing reject action callback")},buildOrderPatchPayload:function(e){var n,r,u=void 0===e?{}:e,s=u.discount,f=u.handling,p=u.insurance,h=u.itemTotal,m=u.shippingOptions,_=u.shippingDiscount,g=u.taxTotal,v=null==m?void 0:m.find((function(e){return!0===e.selected})),b=null!=(n=null==v||null==(r=v.amount)?void 0:r.value)?n:"0.00",y={};s&&(y.discount=s),f&&(y.handling=f),p&&(y.insurance=p),h&&(y.item_total=h),v&&(y.shipping=b),_&&(y.shipping_discount=_),g&&(y.tax_total=g),a=Object(d.b)({breakdown:a,updatedAmounts:y});var E,T=Object(d.c)({breakdown:a,updatedAmounts:y});return Object.keys(y).length&&(i[l.b.AMOUNT]={op:"replace",path:l.b.AMOUNT,value:{value:""+T,currency_code:null==t||null==(E=t.amount)?void 0:E.currencyCode,breakdown:a}}),Object(c.z)(o).then((function(e){var n,t=(null==e||null==(n=e.checkoutSession)||null==(n=n.cart)?void 0:n.shippingMethods)||[],r=Boolean(t.length>0);if(null!=m&&m.length){var o=Object(d.e)(m);i[l.b.OPTIONS]={op:r?"replace":"add",path:l.b.OPTIONS,value:o}}return r?Object(d.f)({queries:i}):Object(d.d)({queries:i})}))}}}({data:h,actions:n,orderID:e}))}))}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return p}));var r=t(35),o=t(6),i=t(14),a=(t(4),t(0)),c=t(5),u=t(1),s=t(2),l=t(11),d=t(13),f=["amount","buyerAccessToken","event","forceRestAPI","options","selectedShippingOption"];function p(e,n){var t=e.onShippingOptionsChange,p=n.createOrder;if(t)return function(e,n){var h=Object(o.a)({},(Object(r.a)(e),e));return p().then((function(e){var r;return Object(s.e)().info("button_shipping_options_change").track((r={},r[a.g.TRANSITION]=u.l.CHECKOUT_SHIPPING_OPTIONS_CHANGE,r[a.g.EVENT_NAME]=u.l.CHECKOUT_SHIPPING_OPTIONS_CHANGE,r[a.g.CONTEXT_TYPE]=u.h.ORDER_ID,r[a.g.TOKEN]=e,r[a.g.CONTEXT_ID]=e,r[u.i.SHIPPING_CALLBACK_INVOKED]="1",r)).flush(),t(function(e){var n=e.selectedShippingOption,t=Object(i.a)(e,f);return Object(o.a)({errors:l.d,selectedShippingOption:n},t)}(h),function(e){var n,t=e.data,r=e.actions,o=e.orderID,i={},a=null!=(n=t.amount)&&n.breakdown?Object(d.a)(t.amount.breakdown):{};if(0===Object.keys(a).length)throw new Error("Must pass breakdown into data attribute for onShippingAddressChange callback.");return{reject:r.reject?function(e){return-1===Object.values(l.d).indexOf(e)?r.reject(l.a):r.reject(e)}:function(){throw new Error("Missing reject action callback")},buildOrderPatchPayload:function(e){var n,r=void 0===e?{}:e,u=r.discount,s=r.handling,f=r.insurance,p=r.itemTotal,h=r.shippingOption,m=r.shippingDiscount,_=r.taxTotal,g=null==h||null==(n=h.amount)?void 0:n.value,v=h&&t.options?Object(d.e)(Object(d.g)({option:h,options:t.options})):void 0,b={};u&&(b.discount=u),s&&(b.handling=s),f&&(b.insurance=f),p&&(b.item_total=p),g&&(b.shipping=g),m&&(b.shipping_discount=m),_&&(b.tax_total=_);var y,E=Object(d.c)({breakdown:a,updatedAmounts:b});return a=Object(d.b)({breakdown:a,updatedAmounts:b}),Object.keys(b).length&&(i[l.b.AMOUNT]={op:"replace",path:l.b.AMOUNT,value:{value:""+E,currency_code:null==t||null==(y=t.amount)?void 0:y.currencyCode,breakdown:a}}),Object(c.z)(o).then((function(e){var n,t=(null==e||null==(n=e.checkoutSession)||null==(n=n.cart)?void 0:n.shippingMethods)||[],r=Boolean(t.length>0);return null!=v&&v.length&&(i[l.b.OPTIONS]={op:r?"replace":"add",path:l.b.OPTIONS,value:v}),r?Object(d.f)({queries:i}):Object(d.d)({queries:i})}))}}}({data:h,actions:n,orderID:e}))}))}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return i}));var r=t(4),o=t(2);function i(){return function(e){var n=e.accessToken;return Object(o.e)().info("spb_onauth_access_token_"+(n?"present":"not_present")),r.a.try((function(){if(n)return Object(o.v)(n),n}))}}},function(e,n,t){"use strict";t.d(n,"a",(function(){return c}));var r=t(3),o=(t(4),t(0)),i=t(1),a=t(2),c=function(e){var n=e.createVaultSetupToken,t={paymentSource:e.paymentSource},c=Date.now();return Object(r.x)((function(){if(!n)throw new Error("createVaultSetupToken undefined");return n(t).then((function(e){var n;if(!e||"string"!=typeof e){var t,r="Expected a vault setup token to be returned from createVaultSetupToken";throw Object(a.u)({name:"pp.app.paypal_sdk.buttons.create_vault_setup_token.count",event:"error",dimensions:{errorName:"no_setup_token"}}),Object(a.e)().error("create_vault_setup_token",{err:r}).track(((t={})[o.g.STATE]=i.k.BUTTON,t[o.g.ERROR_CODE]="smart_buttons_create_vault_setup_token",t[o.g.ERROR_DESC]=r,t)),new Error(r)}return Object(a.u)({name:"pp.app.paypal_sdk.buttons.create_vault_setup_token.count",event:"success",dimensions:{errorName:"no_vault_setup_token"}}),Object(a.e)().addTrackingBuilder((function(){var n;return(n={})[o.g.CONTEXT_TYPE]=i.h.VAULT_SETUP_TOKEN,n[o.g.CONTEXT_ID]=e,n})).track(((n={})[o.g.STATE]=i.k.BUTTON,n[o.g.TRANSITION]=i.l.RECEIVE_VAULT_SETUP_TOKEN,n[o.g.EVENT_NAME]=i.l.RECEIVE_VAULT_SETUP_TOKEN,n[o.g.RESPONSE_DURATION]=(Date.now()-c).toString(),n.client_time=Object(a.d)(),n)),e})).catch((function(e){var n;throw Object(a.u)({name:"pp.app.paypal_sdk.buttons.create_vault_setup_token.count",event:"error",dimensions:{errorName:"generic"}}),Object(a.e)().error("create_vault_setup_token_error",{err:Object(r.L)(e)}).track((n={},n[o.g.STATE]=i.k.BUTTON,n[o.g.ERROR_CODE]="smart_buttons_create_vault_setup_token_error",n[o.g.ERROR_DESC]=Object(r.L)(e),n)).flush(),e}))}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return s}));var r=t(4),o=t(3),i=t(0),a=t(5),c=t(1),u=t(2);function s(e,n){var t=e.orderID,s=e.payload,l=e.partnerAttributionID,d=n.facilitatorAccessToken,f=Date.now();return r.a.try((function(){return Object(a.g)(t,s,{facilitatorAccessToken:d,partnerAttributionID:l,experiments:{}})})).catch((function(e){throw Object(u.e)().error("confirm_order_error",{err:Object(o.K)(e)}),e})).then((function(){var e,n=Date.now()-f;Object(u.e)().track((e={},e[i.g.STATE]=c.k.BUTTON,e[i.g.TRANSITION]=c.l.CONFIRM_ORDER,e[i.g.CONTEXT_TYPE]=c.h.ORDER_ID,e[i.g.CONTEXT_ID]=t,e[i.g.TOKEN]=t,e[i.g.RESPONSE_DURATION]=n.toString(),e)).flush()}))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return i})),t.d(n,"b",(function(){return a})),t(4);var r=t(8),o=t(7),i=function(e){var n=e.clientID,t=e.vaultSetupToken,r=e.paymentSource,i=e.idToken;return Object(o.a)({name:"UpdateVaultSetupToken",query:"\n mutation UpdateVaultSetupToken(\n $clientID: String!\n $vaultSetupToken: String!\n $paymentSource: PaymentSource\n $idToken: String\n ) {\n updateVaultSetupToken(\n clientId: $clientID\n vaultSetupToken: $vaultSetupToken\n paymentSource: $paymentSource\n idToken: $idToken\n ) {\n id,\n status,\n links {\n rel, href\n }\n }\n }",variables:{clientID:n,vaultSetupToken:t,paymentSource:r,idToken:i}})};function a(e){return Object(o.c)({authenticated:!1,method:"post",eventName:"vault_ectoken",url:r.j.VAULT+"/"+e+"/ectoken"}).then((function(e){return e.data.token}))}},function(e,n,t){"use strict";function r(e){if(null==e)throw new TypeError("Cannot destructure undefined")}t.d(n,"a",(function(){return r}))},function(e,n,t){"use strict";t.d(n,"a",(function(){return l}));var r=t(6),o=t(4),i=t(3),a=["warn","error"],c=["error","warn","info","debug"],u=function(e,n){for(var t in n)n.hasOwnProperty(t)&&(e[t]=n[t])},s=t(9);function l(e){var n=e.url,t=e.prefix,l=e.logLevel,d=void 0===l?"warn":l,f=e.transport,p=void 0===f?function(e){var n=e.url,t=e.method,r=e.headers,a=e.json,c=e.enableSendBeacon,u=void 0!==c&&c;return o.a.try((function(){var e=window,o=Object(s.f)(e)?Object(s.a)(e):window,c=!1;return function(e){var n=e.headers,t=e.enableSendBeacon,r=n&&Object.keys(n).length;return!!(window&&window.navigator.sendBeacon&&!r&&t&&window.Blob)}({headers:r,enableSendBeacon:u})&&(c=function(e){var n=e.win,t=void 0===n?window:n,r=e.url,o=e.data,i=e.useBlob,a=void 0===i||i;try{var c=JSON.stringify(o);if(!t.navigator.sendBeacon)throw new Error("No sendBeacon available");if(a){var u=new Blob([c],{type:"application/json"});return t.navigator.sendBeacon(r,u)}return t.navigator.sendBeacon(r,c)}catch(e){return!1}}({win:o,url:n,data:a,useBlob:!0})),c||Object(i.I)({win:o,url:n,method:t,headers:r,json:a})})).then(i.y)}:f,h=e.flushInterval,m=void 0===h?6e4:h,_=e.enableSendBeacon,g=void 0!==_&&_,v=[],b=[],y=[],E=[],T=[],O=[],I=[];function w(e,n,t){if(Object(i.p)()&&window.console&&window.console.log&&!(c.indexOf(e)>c.indexOf(d))){var r=[n];r.push(t),(t.error||t.warning)&&r.push("\n\n",t.error||t.warning);try{window.console[e]&&window.console[e].apply?window.console[e].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(e){}}}function S(){return o.a.try((function(){if(Object(i.p)()&&"file:"!==window.location.protocol&&(v.length||b.length||y.length)){for(var e={},t=0;t4)return r(!1,!1);var a=parseInt(e,10),c=Number(String(i).substr(2,2)),u=!1;if(2===o){if(String(i).substr(0,2)===e)return r(!1,!0);t=c===a,u=a>=c&&a<=c+n}else 4===o&&(t=i===a,u=a>=i&&a<=i+n);return r(u,u,t)}},function(e,n,t){"use strict";t.d(n,"a",(function(){return r})),t(4);var r={PAYMENT:"payment",CANCEL:"cancel"}},function(e,n,t){"use strict";t(4),t(0)},function(e,n,t){"use strict";t(4)},function(e,n,t){"use strict";t(4),t(0)},function(e,n){},function(e,n,t){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var n,t=1,r=arguments.length;t0&&t<13;return r(o,o,o&&t>=n)}},function(e,n,t){"use strict";e.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.addMatchingCardsToResults=void 0;var r=t(44),o=t(48);n.addMatchingCardsToResults=function(e,n,t){var i,a;for(i=0;i=a&&(u.matchStrength=a),t.push(u);break}}}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.matches=void 0,n.matches=function(e,n){return Array.isArray(n)?function(e,n,t){var r=String(n).length,o=e.substr(0,r),i=parseInt(o,10);return n=parseInt(String(n).substr(0,o.length),10),t=parseInt(String(t).substr(0,o.length),10),i>=n&&i<=t}(e,n[0],n[1]):function(e,n){return(n=String(n)).substring(0,e.length)===e.substring(0,n.length)}(e,n)}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isValidInputType=void 0,n.isValidInputType=function(e){return"string"==typeof e||e instanceof String}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.findBestMatch=void 0,n.findBestMatch=function(e){return function(e){var n=e.filter((function(e){return e.matchStrength})).length;return n>0&&n===e.length}(e)?e.reduce((function(e,n){return e?Number(e.matchStrength)255?o(!1,!1):r.test(e)?o(!1,!0):o(!0,!0)}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.cardNumber=void 0;var r=t(53),o=t(43);function i(e,n,t){return{card:e,isPotentiallyValid:n,isValid:t}}n.cardNumber=function(e,n){var t,a;if(void 0===n&&(n={}),"string"!=typeof e&&"number"!=typeof e)return i(null,!1,!1);var c=String(e).replace(/-|\s/g,"");if(!/^\d*$/.test(c))return i(null,!1,!1);var u=o(c);if(0===u.length)return i(null,!1,!1);if(1!==u.length)return i(null,!0,!1);var s=u[0];if(n.maxLength&&c.length>n.maxLength)return i(s,!1,!1);t=s.type===o.types.UNIONPAY&&!0!==n.luhnValidateUnionPay||r(c),a=Math.max.apply(null,s.lengths),n.maxLength&&(a=Math.min(n.maxLength,a));for(var l=0;l=0;)n=parseInt(e.charAt(o),10),r&&(n*=2)>9&&(n=n%10+1),r=!r,t+=n,o--;return t%10==0}},function(e,n,t){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var n,t=1,r=arguments.length;t1||1===a&&Number(t[1])>2?1:1===a?(i=t.substr(1),r.expirationYear(i).isPotentiallyValid?1:2):5===t.length?1:t.length>5?2:1),u=e.substr(0,c);return{month:u,year:e.substr(u.length)}}},function(e,n,t){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.isArray=void 0,n.isArray=Array.isArray||function(e){return"[object Array]"==={}.toString.call(e)}},function(e,n,t){"use strict";function r(e,n){return{isValid:e,isPotentiallyValid:n}}Object.defineProperty(n,"__esModule",{value:!0}),n.cvv=void 0,n.cvv=function(e,n){return void 0===n&&(n=3),n=n instanceof Array?n:[n],"string"!=typeof e?r(!1,!1):/^\d*$/.test(e)?function(e,n){for(var t=0;tfunction(e){for(var n=3,t=0;tn?e[t]:n;return n}(n)?r(!1,!1):r(!0,!0):r(!1,!1)}},function(e,n,t){"use strict";function r(e,n){return{isValid:e,isPotentiallyValid:n}}Object.defineProperty(n,"__esModule",{value:!0}),n.postalCode=void 0,n.postalCode=function(e,n){void 0===n&&(n={});var t=n.minLength||3;return"string"!=typeof e?r(!1,!1):r(!(e.length1&&a.zoomHeight&&a.zoomHeight[t]?-1!==a.zoomHeight[t].indexOf(i):-1!==a.textSizeHeights.indexOf(i)||-1!==a.textSizeHeightsNoTabs.indexOf(i))}return!1}function T(e){if(void 0===e&&(e=o()),_(e)){var n=E(e),t=g(e)?r[window.outerHeight]:null;if(!t)return!1;var i=window.innerHeight,a=Math.round(window.screen.width/window.innerWidth*100)/100,c=Math.round(i*a),u=t.maybeSafari,s=!1;return a>1&&u[a]&&-1!==u[a].indexOf(c)&&(s=!0),n||s}return!1}function O(e){return void 0===e&&(e=o()),!!m(e)&&/Version\/[\d.]+/.test(e)&&!h(e)}function I(){return!!window.document.documentMode||Boolean(window.navigator&&window.navigator.userAgent&&/Edge|MSIE|rv:11/i.test(window.navigator.userAgent))}function w(){var e=window.document.querySelector('meta[http-equiv="X-UA-Compatible"]'),n=window.document.querySelector('meta[content="IE=edge"]');return!(!e||!n)}function S(){return!("undefined"==typeof process||!process.versions||!process.versions.electron)}function A(){if(window.document.documentMode)try{var e=window.status;return window.status="testIntranetMode","testIntranetMode"===window.status&&(window.status=e,!0)}catch(e){return!1}return!1}function D(){var e=o();return/Macintosh.*AppleWebKit(?!.*Safari)/i.test(e)}function C(e){return void 0===e&&(e=o()),!(u(e)||y(e)||O(e)||h(e)||f(e)||p(e)||l(e)||b(e)||S()||D()||s())}function N(e){return void 0===e&&(e=o()),/Chrome|Chromium|CriOS/.test(e)&&!/SamsungBrowser|Silk|EdgA/.test(e)}function k(e){return void 0===e&&(e=o()),/Safari/.test(e)&&!N(e)&&!/Silk|FxiOS|EdgiOS/.test(e)}function P(){try{if(window.ApplePaySession&&window.ApplePaySession.supportsVersion(3)&&window.ApplePaySession.canMakePayments())return!0}catch(e){return!1}return!1}function R(e){return-1===window.document.cookie.indexOf(e)}function j(e,n){return(j=Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}function L(e,n){e.prototype=Object.create(n.prototype),e.prototype.constructor=e,j(e,n)}function U(){return(U=Object.assign||function(e){for(var n=1;n>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,n={};return Object.freeze(n),e.set(n,"__testvalue__"),"__testvalue__"===e.get(n)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var n=e.prototype;return n._cleanupClosedWindows=function(){for(var e=this.weakmap,n=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var t=e&&e.stack,r=e&&e.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+Ke(e,n+1)}}function Ye(e){var n="";return e?e instanceof Error?e.message||n:"string"==typeof e.message&&e.message||n:n}function We(e){return"string"==typeof e?e:e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}function qe(e,n){var t=(e=e.split("://")[1]).indexOf(n);return-1!==t&&e.slice(t)===n}function $e(e,n,t){var r=e[n];e[n]=function(){var e=arguments,n=this;return t({context:this,args:[].slice.call(arguments),original:r,callOriginal:function(){return r.apply(n,e)}})}}function ze(e,n){if(!n)return e;if(Object.assign)return Object.assign(e,n);for(var t in n)n.hasOwnProperty(t)&&(e[t]=n[t]);return e}function Xe(e){if(Object.values)return Object.values(e);var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(e[t]);return n}Re.clear=function(){Pe=ke};var Je=Re(Xe);function Qe(e,n){return Math.round(e*n/100)}function Ze(){return Math.min.apply(Math,arguments)}function en(){return Math.max.apply(Math,arguments)}function nn(e,n){var t=e%n;return t?e-t+n:e}function tn(e,n,t){var r=[];return e.replace(n,(function(e){r.push(t?t.apply(null,arguments):e)})),r}function rn(e){return"data:image/svg+xml;base64,"+Ie(e)}function on(e,n){void 0===n&&(n=Boolean);var t={};for(var r in e)e.hasOwnProperty(r)&&n(e[r],r)&&(t[r]=e[r]);return t}function an(e){return e}function cn(e,n){var t=[];return e.replace(n,(function(e){return t.push(e),""})),t}function un(e,n){var t,r;return void 0===n&&(n=50),Oe((function(){r&&clearTimeout(r);var o=t=t||new Y;return r=setTimeout((function(){t=null,r=null,Y.try(e).then((function(e){o.resolve(e)}),(function(e){o.reject(e)}))}),n),o}),Te(e)+"::promiseDebounced")}function sn(e,n){var t;return function r(){t=setTimeout((function(){e(),r()}),n)}(),{cancel:function(){clearTimeout(t)}}}function ln(e){return Boolean(e.match(/^[0-9]+$/))}function dn(e){return Boolean(e.match(/^[0-9]+\.[0-9]+$/))}function fn(e){return e.toString()}function pn(e){return"true"===e||"false"!==e&&(ln(e)?parseInt(e,10):dn(e)?parseFloat(e):e)}function hn(e,n,t){for(var r in void 0===n&&(n=""),void 0===t&&(t={}),n=n?n+".":n,e)e.hasOwnProperty(r)&&null!=e[r]&&"function"!=typeof e[r]&&(e[r]&&Array.isArray(e[r])&&e[r].length&&e[r].every((function(e){return"object"!=typeof e}))?t[""+n+r+"[]"]=e[r].join(","):e[r]&&"object"==typeof e[r]?t=hn(e[r],""+n+r,t):t[""+n+r]=fn(e[r]));return t}function mn(e){var n={};for(var t in e)if(e.hasOwnProperty(t)&&"string"==typeof e[t]){var r=e[t];t.match(/^.+\[\]$/)?(t=t.slice(0,-2),r=r.split(",").map(pn)):r=pn(r);for(var o=n,i=t.split("."),a=0;a1?t-1:0),o=1;o1?r-1:0),i=1;i-1}(t))return t;var r=t.match(ve);return r&&he.test(r[0])?ye:t}function qn(){var e=document.body;if(!e)throw new Error("Body element not found");return e}function $n(){return Boolean(document.body)&&"complete"===document.readyState}function zn(){return Boolean(document.body)&&"interactive"===document.readyState}function Xn(e){return encodeURIComponent(e)}function Jn(){return Me(Jn,(function(){return new Y((function(e){$n()&&e(),window.addEventListener("load",(function(){return e()}))}))}))}var Qn=Re((function(){return new Y((function(e){if($n()||zn())return e();var n=setInterval((function(){if($n()||zn())return clearInterval(n),e()}),10)}))}));function Zn(){return Y.try((function(){return document.body?document.body:Qn().then((function(){if(document.body)return document.body;throw new Error("Document ready but document.body not present")}))}))}function et(e){return Me(et,(function(){var n={};if(!e)return n;if(-1===e.indexOf("="))return n;for(var t=0,r=e.split("&");t1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function lt(){return Boolean(st())}function dt(){return Qn().then((function(){var e=st();if(e){var n=e.timing;return n.connectEnd&&n.domInteractive?n.domInteractive-n.connectEnd:void 0}}))}function ft(e){return void 0===e&&(e=""),e.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function pt(){return"undefined"!=typeof window&&void 0!==window.location}function ht(e,n){return void 0===n&&(n=window.document),[].slice.call(n.querySelectorAll(e))}function mt(e,n){e.addEventListener("touchstart",xe,{passive:!0}),e.addEventListener("click",n),e.addEventListener("keypress",(function(e){if(e.keyCode===de.ENTER||e.keyCode===de.SPACE)return n(e)}))}function _t(e){var n=e.host,t=void 0===n?window.location.host:n,r=e.path,o=e.reverse,i=void 0!==o&&o;return Me(_t,(function(){var e=""+t+r,n=[].slice.call(document.getElementsByTagName("script"));i&&n.reverse();for(var o=0;or&&(t=null),t||(t={guid:o||Se(),created:i}),n.__session__=t,e(t)}))}return{getState:a,getID:c,isStateFresh:function(){return c()===i},getSessionState:function(e){return u((function(n){return n.state=n.state||{},e(n.state)}))},getSessionID:function(){return u((function(e){return e.guid}))}}}),[{name:n,lifetime:r}])}function fr(){return dr({name:"belter_experiment"})}function pr(e){return fr().getSessionState((function(n){return n.loggedBeacons=n.loggedBeacons||[],-1===n.loggedBeacons.indexOf(e)&&(n.loggedBeacons.push(e),!0)}))}function hr(e){return Math.floor(Math.random()*e)}function mr(e){var n,t=e.name,r=e.sample,o=void 0===r?50:r,i=e.logTreatment,a=void 0===i?xe:i,c=e.logCheckpoint,u=void 0===c?xe:c,s=e.sticky,l=void 0===s||s?function(e){return fr().getState((function(n){return n.throttlePercentiles=n.throttlePercentiles||{},n.throttlePercentiles[e]=n.throttlePercentiles[e]||hr(100),n.throttlePercentiles[e]}))}(t):hr(100),d=t+"_"+(n=l=50||o<=l&&l<2*o?"control":"throttle"),f=!1,p=!1;try{window.localStorage&&window.localStorage.getItem(t)&&(p=!0)}catch(e){}var h={isEnabled:function(){return"test"===n||p},isDisabled:function(){return"test"!==n&&!p},getTreatment:function(){return d},log:function(e,n){return void 0===n&&(n={}),f?(pr(d+"_"+JSON.stringify(n))&&a({name:t,treatment:d,payload:n,throttle:l}),pr(d+"_"+e+"_"+JSON.stringify(n))&&u({name:t,treatment:d,checkpoint:e,payload:n,throttle:l}),h):h},logStart:function(e){return void 0===e&&(e={}),f=!0,h.log("start",e)},logComplete:function(e){return void 0===e&&(e={}),h.log("complete",e)}};return h}function _r(e){var n=e.name,t=e.version,r=void 0===t?"latest":t,o=Ae(),i="__"+n+"__"+r+"_global__",a=o[i]=o[i]||{};return{get:function(e,n){return n=n||{},a[e]=a[e]||n}}}var gr=[];function vr(e){var n=e.url,t=e.method,r=void 0===t?"get":t,o=e.headers,i=void 0===o?{}:o,a=e.json,c=e.data,u=e.body,s=e.win,l=void 0===s?window:s,d=e.timeout,f=void 0===d?0:d;return new Y((function(e,t){if(a&&c||a&&u||c&&a)throw new Error("Only options.json or options.data or options.body should be passed");for(var o={},s=0,d=Object.keys(i);s1?new M(n):void 0}(this.component(this.props,this.children));if(n)return n.render(e)},n.render=function(e){return e(this)},n.renderChildren=function(e){return L(this.children,e)},e}();function B(e){for(var n=[],t=0;t2?t-2:0),o=2;o1||p[0]&&p[0].discount){var h,m=p.map((function(e){return Object(u.a)({term:e.term,intervalDuration:e.intervalDuration},e.discount&&{percent:e.discount.percentage},{amount:e.monthlyPayment.currencyFormatSymbolISOCurrency,totalAmount:e.totalCost.currencyFormatSymbolISOCurrency,onSelect:function(e){var n;f().info("installment_option_selected_"+e.term+"x").track((n={},n[o.g.TRANSITION]="installment_select",n[o.g.CONTEXT_TYPE]="EC-Token",n[o.g.TOKEN]=c,n[o.g.CONTEXT_ID]=c,n)).flush()}})})),_={cartAmount:s,onPay:function(e){var n;!function(e){e.classList.add("paypal-button-loading")}(a),f().info("installments_pay_button_clicked_"+(e?e.term:"")+"x").track((n={},n[o.g.TRANSITION]="installments_pay",n[o.g.CONTEXT_TYPE]="EC-Token",n[o.g.TOKEN]=c,n[o.g.CONTEXT_ID]=c,n)).flush();var t=null;return e&&(t={term:e.term,interval_duration:e.intervalDuration}),i.a.try((function(){return l(c,t)})).finally((function(){!function(e){e.classList.remove("paypal-button-loading")}(a)}))},onClose:function(){var e;f().info("installments_modal_close").track((e={},e[o.g.TRANSITION]="installments_close",e[o.g.CONTEXT_TYPE]="EC-Token",e[o.g.TOKEN]=c,e[o.g.CONTEXT_ID]=c,e)).flush()},options:m,orderID:c};return f().info("initiate_installments_modal").track((h={},h[o.g.TRANSITION]="installments_load_modal",h[o.g.CONTEXT_TYPE]="EC-Token",h[o.g.TOKEN]=c,h[o.g.CONTEXT_ID]=c,h)).flush(),function(e){var n=e.clientID,t=e.Installments,o=e.data;if(!n)throw new Error("Can not render installments without client id");var i=t({clientID:n}),a=i.renderTo,c=i.updateProps,u=i.show,s=i.close,l=Object(r.x)((function(){return a(window.xprops.getParent(),"#installments-modal")}));return l(),l().then((function(){return c({clientID:n,data:o,close:s})})).then((function(){return u()}))}({clientID:n,Installments:t,data:_})}return l(c)}throw new Error("Installments fetch returns null")})).catch((function(e){return i.a.try((function(){var n;return f().error("installment_fetch_error",{err:Object(r.K)(e)}).track((n={},n[o.g.TRANSITION]="installments_error",n[o.g.CONTEXT_TYPE]="EC-Token",n[o.g.TOKEN]=c,n[o.g.CONTEXT_ID]=c,n.err=Object(r.K)(e),n)).flush(),l(c)}))}))}({clientID:y,Installments:I,paymentMethodID:S,button:A,buyerCountry:N,orderID:e,accessToken:R,cartAmount:n.checkoutSession.cart.amounts.total.currencyFormatSymbolISOCurrency,onPay:M,getLogger:a.e})})):null!=f&&f.deprecateVaultValidatePaymentMethod?function(e){b&&(R=b),i.a.try((function(){return U(e).then((function(n){if(n){if(Object(a.u)({name:"pp.app.paypal_sdk.buttons.vault_capture.error.count",event:"error",dimensions:{errorName:"shipping_required_failure_or_fallback",fundingSource:w}}),w!==o.j.PAYPAL)throw new Error("Shipping address requested for "+w+" payment");return L()}return Object(D.g)(e,{payment_source:Object(D.e)({paymentMethodID:S,fundingSource:w,enableThreeDomainSecure:_})},{facilitatorAccessToken:R,partnerAttributionID:g,experiments:{}}).then((function(e){return xe({status:e.status,links:e.links,ThreeDomainSecure:O,createOrder:p,getParent:v,paymentFlow:"vault_capture",fundingSource:w})})).then((function(){return Object(a.u)({name:"pp.app.paypal_sdk.buttons.vault_capture.success.count",event:"success",dimensions:{fundingSource:w,experimentInUse:"deprecated_validate_payment_method_experiment"}}),h({},{restart:j})}))}))}))}(e):M(e)}))}))},close:function(){return i.a.resolve()}}},setupMenu:function(e){var n=e.props,t=e.payment,s=e.serviceData,l=e.components,d=e.config,f=e.restart,p=e.experiments,h=null!=p&&p.popupIncreaseDimensions?re:te,m={width:h.WIDTH,height:h.HEIGHT},_=n.clientAccessToken,g=n.createOrder,v=n.enableThreeDomainSecure,b=n.partnerAttributionID,y=n.sessionID,E=n.clientMetadataID,T=n.userIDToken,O=t.fundingSource,I=t.paymentMethodID,w=t.button,S=s.content,A=s.facilitatorAccessToken,C=s.featureFlags;if(!_||!I)throw new Error("Client access token and payment method id required");Object(a.e)().info("popup_dimensions_value_vault_capture"),Object(a.u)({name:"pp.app.paypal_sdk.checkout_ui.dimension.count",dimensions:{spbPaymentFlow:"vault_capture",fundingSource:O,dimensionType:null!=p&&p.popupIncreaseDimensions?"experiment_default":"default"}});var N=function(){return i.a.try((function(){return g()})).then((function(e){return Object(D.N)({fundingSource:O,orderID:e,inline:!1,featureFlags:C})}))},k=function(e){return ue.init({props:n,components:l,serviceData:s,config:d,payment:e.payment,restart:f}).start()};if(O===o.j.PAYPAL)return[{label:S.payWithDifferentMethod,popup:m,onSelect:function(e){var n,r=e.win;return Object(a.e)().info("click_choose_funding").track((n={},n[o.g.TRANSITION]=c.l.CLICK_CHOOSE_FUNDING,n[o.g.OPTION_SELECTED]=c.j.CHOOSE_FUNDING,n)).flush(),i.a.try((function(){return N()})).then((function(){return e=T?A:_,i.a.try((function(){return g()})).then((function(n){return Object(D.Q)({accessToken:e,orderID:n,paymentMethodID:I,enableThreeDomainSecure:v,partnerAttributionID:b,clientMetadataID:E||y})}));var e})).then((function(){return k({payment:Object(u.a)({},t,{win:r,buyerIntent:c.b.PAY_WITH_DIFFERENT_FUNDING_SHIPPING})})}))}},{label:S.payWithDifferentAccount,popup:m,onSelect:function(e){var n,r=e.win;return Object(a.e)().info("click_choose_account").track((n={},n[o.g.TRANSITION]=c.l.CLICK_CHOOSE_ACCOUNT,n[o.g.OPTION_SELECTED]=c.j.CHOOSE_ACCOUNT,n)).flush(),i.a.try((function(){return N()})).then((function(){return k({payment:Object(u.a)({},t,{win:r,buyerIntent:c.b.PAY_WITH_DIFFERENT_ACCOUNT})})}))}}];if(O===o.j.CARD)return[{label:S.deleteVaultedCard,spinner:!0,onSelect:function(){var e,n=w.parentElement||w;return Object(a.e)().info("click_unlink_account").track((e={},e[o.g.TRANSITION]=c.l.CLICK_UNLINK_ACCOUNT,e[o.g.OPTION_SELECTED]=c.j.UNLINK_ACCOUNT,e)).flush(),Object(D.l)({paymentMethodID:I,clientAccessToken:_}).then((function(){Object(r.f)(n)}))}}];throw new Error("Can not render menu for "+O)},updateFlowClientConfig:function(e){var n=e.orderID,t=e.featureFlags,r=e.payment.fundingSource;return Object(D.N)({fundingSource:r,orderID:n,inline:!0,featureFlags:t})},spinner:!0,inline:!0},Ye=!1;function We(e,n,t){var r,o=e[n];if(!o)throw new Error("Wallet has no "+n);for(var i=0,a=o.instruments;i850}({version:null==n?void 0:n.version}))}({fundingSource:n,appDetect:l})&&(!i||n===o.j.VENMO)&&d().then((function(e){var t;return Object(D.w)({vault:f,platform:p,shippingCallbackEnabled:O,clientID:h,buyerCountry:y,currency:m,buttonSessionID:_,cookies:E,orderID:e,enableFunding:g,stickinessID:s,merchantID:T[0],domain:v,headers:(t={},t[c.n.DISABLE_SET_COOKIE]=String(b),t)}).then((function(t){var r,i,u=t&&null!=(r=t[n])&&r.ineligibilityReason?t[n].ineligibilityReason:"";return!!(t&&t[n]&&t[n].eligibility)||(Object(a.e)().info("native_appswitch_ineligible",{orderID:e}).track((i={},i[o.g.STATE]=c.k.BUTTON,i[o.g.TRANSITION]=c.l.NATIVE_APP_SWITCH_INELIGIBLE,i[c.i.INFO_MSG]=u,i)).flush(),!1)}))})))}))}function In(e){var n,t=e.payment,u=e.props,s=e.serviceData,l=e.config,d=e.sessionUID,f=e.fallback,p=e.callbacks,h=e.clean,m=u.buttonSessionID,_=u.onClick,g=u.createOrder,v=t.fundingSource,b=t.win,y=p.onInit,E=p.onApprove,T=p.onCancel,O=p.onError,I=p.onClose,w=p.onDestroy,S=p.onShippingChange;if(!l.firebase)throw new Error("Can not load popup without firebase config");return{click:function(){n=new i.a((function(e,n){var t=function(e){var n=e.props,t=e.fundingSource,o=function(e){var n=e.props,t=e.serviceData,o=n.buttonSessionID,i=n.env,a=n.clientID,c=n.sessionID,u=n.sdkCorrelationID,s=t.sdkMeta,l=t.buyerCountry,d=Object(j.c)();return{buttonSessionID:o,buyerCountry:l,clientID:a,channel:Object(r.s)()?"mobile-web":"desktop-web",env:i,parentDomain:d,sdkCorrelationID:u,sdkMeta:s,sessionID:c}}({props:n,serviceData:e.serviceData,fundingSource:t});return Object(r.h)(""+mn({props:n})+cn[t],{query:o})+"#init"}({props:u,serviceData:s,fundingSource:v}),p=mn({props:u}),A=function(e){var n,t;if(b){var i=Object(a.x)(b);i.setLocation(e),t=i}else t=Object(a.x)(Object(r.D)(e));return Object(a.e)().info("native_attempt_appswitch_popup_shown").track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_POPUP_SHOWN,n)).flush(),t}(t),C=h.register((function(){return A.close()})),N=i.a.try((function(){return!_||_({fundingSource:v})})).then((function(e){var n;return e||Object(a.e)().info("native_onclick_invalid").track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_ON_CLICK_INVALID,n)).flush(),e})),k=N.then((function(e){return e?g():Object(a.z)()})),P=function(e){return C.cancel(),f({win:A,fallbackOptions:e}).then((function(){return{buttonSessionID:m}}))},R=function(e){var n=e.pageUrl,t=e.stickinessID,r=e.fallbackOptions;return A.isClosed().then((function(e){return e?P(r):(r&&pn(r),k.then((function(e){A.setLocation(vn({props:u,serviceData:s,config:l,fundingSource:v,sessionUID:d,pageUrl:n,orderID:e,stickinessID:t}))})))}))},L=Object(r.B)((function(){return i.a.try((function(){var n;e(),Object(D.G)(),Object(a.e)().info("native_detect_app_switch").track((n={},n[o.g.TRANSITION]=c.l.NATIVE_DETECT_APP_SWITCH,n)).flush(),Object(a.j)((function(e){var n=e.lastAppSwitchTime,t=void 0===n?0:n,r=e.lastWebSwitchTime,o=void 0===r?0:r;t>o&&Object(a.e)().info("app_switch_detect_with_previous_app_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),o>t&&Object(a.e)().info("app_switch_detect_with_previous_web_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),t||o||Object(a.e)().info("app_switch_detect_with_no_previous_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),e.lastAppSwitchTime=Date.now()}))}))})),U=Object(r.B)((function(e){var t=e.pageUrl,r=e.stickinessID;return i.a.try((function(){var e;Object(D.G)(),Object(a.e)().info("native_detect_possible_app_switch").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_DETECT_POSSIBLE_APP_SWITCH,e)).flush();var i=yn({config:l,sessionUID:d,callbacks:{onInit:function(){return L(),y()},onApprove:function(e){var n=e.data;return L(),E({data:n})},onCancel:function(){return L(),T()},onShippingChange:function(e){var n=e.data;return L(),S({data:n})},onError:function(e){var t=e.data;return L(),n(new Error(t.message)),O({data:t})},onFallback:function(e){var n=e.data;return L(),R({pageUrl:t,stickinessID:r,fallbackOptions:n}).then((function(){return{buttonSessionID:m}}))}}});h.register(i.cancel)})).catch(n)})),M=Object(r.B)((function(){return i.a.try((function(){var e;return Object(a.j)((function(e){var n=e.lastAppSwitchTime,t=void 0===n?0:n,r=e.lastWebSwitchTime,o=void 0===r?0:r;t>o&&Object(a.e)().info("web_switch_detect_with_previous_app_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),o>t&&Object(a.e)().info("web_switch_detect_with_previous_web_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),t||o||Object(a.e)().info("web_switch_detect_with_no_previous_switch",{lastAppSwitchTime:t.toString(),lastWebSwitchTime:o.toString()}),e.lastWebSwitchTime=Date.now()})),Object(a.e)().info("native_detect_web_switch").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_DETECT_WEB_SWITCH,e)).flush(),P().then(r.y)})).then(e,n)})),x=Object(a.o)(A,(function(){var e;Object(a.e)().info("native_popup_closed").track((e={},e[o.g.STATE]=c.k.BUTTON,e[o.g.TRANSITION]=c.l.NATIVE_POPUP_CLOSED,e)).flush(),n(new Error("Native popup closed")),I()}),500),F=function(e){var n;Object(a.e)().info("native_closing_popup_"+e).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=e?c.l.NATIVE_CLOSING_POPUP+"_"+e:c.l.NATIVE_CLOSING_POPUP,n)).flush(),x.cancel(),A.close()},B=Object(a.p)("awaitRedirect",{proxyWin:A,domain:p},(function(e){var t=e.data,f=t.app,m=t.pageUrl,_=t.sfvc,g=t.stickinessID;Object(a.e)().info("native_post_message_await_redirect").flush(),function(e){if(e){var n,t="native_app";Object.keys(e).forEach((function(n){t+="_"+String(e[n])})),Object(a.e)().info(t).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_APP_INSTALLED,n[c.i.INFO_MSG]=t,n)).flush()}}(f),Object(a.e)().addTrackingBuilder((function(){var e;return(e={})[o.g.STICKINESS_ID]=g,e}));var b=Object(a.p)("detectAppSwitch",{proxyWin:A,domain:p},(function(){return Object(a.e)().info("native_post_message_detect_possible_app_switch").flush(),U({pageUrl:m,stickinessID:g})})),y=Object(a.p)("detectWebSwitch",{proxyWin:A,domain:hn({props:u})},(function(){return Object(a.e)().info("native_post_message_detect_web_switch").flush(),M()})),I=Object(a.p)("onApprove",{proxyWin:A,domain:p},(function(e){var n=e.data;L(),E({data:n}),F("onApprove")})),S=Object(a.p)("onCancel",{proxyWin:A,domain:p},(function(){L(),T(),F("onCancel")})),D=Object(a.p)("onFallback",{proxyWin:A,domain:p},(function(e){var n,t=e.data;L(),Object(a.e)().info("native_message_onfallback").track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ON_FALLBACK,n)).flush(),R({pageUrl:m,stickinessID:g,fallbackOptions:t})})),C=Object(a.p)("onComplete",{proxyWin:A,domain:p},(function(){var e;L(),Object(a.e)().info("native_post_message_on_complete").track((e={},e[o.g.STATE]=c.k.BUTTON,e[o.g.TRANSITION]=c.l.NATIVE_ON_COMPLETE,e)).flush(),F("onComplete")})),P=Object(a.p)("onError",{proxyWin:A,domain:p},(function(e){var t=e.data;O({data:t}),F("onError"),n(new Error(t.message))}));return window.addEventListener("pagehide",(function(){return F("pagehide")})),window.addEventListener("unload",(function(){return F("unload")})),h.register((function(){return i.a.all([B.cancel(),b.cancel(),I.cancel(),S.cancel(),D.cancel(),C.cancel(),P.cancel(),y.cancel(),x.cancel()]).then(r.y)})),i.a.hash({valid:N,eligible:On({fundingSource:v,props:u,serviceData:s,sfvc:_,validatePromise:N,stickinessID:g,appDetect:f})}).then((function(e){return e.valid?k.then(e.eligible?function(e){var n,t=gn({props:u,serviceData:s,config:l,fundingSource:v,sessionUID:d,pageUrl:m,orderID:e,stickinessID:g});if(Object(a.e)().info("native_attempt_appswitch_url_popup",{url:t}).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_ATTEMPT_APP_SWITCH,n[c.i.INFO_MSG]=t,n)).flush(),Object(a.k)()){x.cancel();var r=Object(a.o)(A,(function(){return U({pageUrl:m,stickinessID:g})}),50);setTimeout(r.cancel,1e3)}return{appSwitch:!0,orderID:e,redirect:!0,redirectUrl:t}}:function(e){return{redirect:!0,appSwitch:!1,orderID:e,redirectUrl:vn({props:u,serviceData:s,config:l,fundingSource:v,sessionUID:d,pageUrl:m,orderID:e,stickinessID:g})}}):(x.cancel(),A.close(),w().then((function(){return{appSwitch:!1,orderID:null,redirect:!1}})))})).catch((function(e){var n;return Object(a.e)().info("native_attempt_appswitch_url_popup_errored").track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_ATTEMPT_APP_SWITCH_ERRORED,n[c.i.ERR_DESC]=Object(r.K)(e),n)).flush(),k.then((function(e){return{appSwitch:!1,orderID:e,redirect:!0,redirectUrl:vn({props:u,serviceData:s,config:l,fundingSource:v,sessionUID:d,pageUrl:m,orderID:e,stickinessID:g})}}))})).catch((function(e){return A.close(),n(e),w().then((function(){return O({data:{message:Object(r.K)(e)}})})).then((function(){return{redirect:!1,appSwitch:!1}}))}))}))}))},start:function(){if(!n)throw new Error("Expected native popup promise to be set");return n}}}var wn=!1;function Sn(){var e=Object(j.e)(window);return wn&&e?e:Object(j.d)()?Object(j.d)():window}var An,Dn,Cn=function(e){return Object(a.e)().info("popup_dimensions_"+e).flush(),{width:500,height:692}};function Nn(e){var n,t=e.props,s=e.components,l=e.serviceData,d=e.payment,f=e.config,p=e.fallback,h=s.Venmo,m=t.sessionID,_=t.buttonSessionID,g=t.createOrder,v=t.onApprove,b=t.onCancel,y=t.onError,E=t.onComplete,T=t.onShippingChange,O=t.onShippingAddressChange,I=t.onShippingOptionsChange,w=t.locale,S=t.commit,A=t.clientAccessToken,D=t.onClick,C=t.clientMetadataID,N=t.onAuth,k=t.env,P=t.enableFunding,R=t.stickinessID,L=t.standaloneFundingSource,U=t.branded,M=t.merchantRequestedPopupsDisabled,x=d.button,F=d.win,B=d.fundingSource,V=d.card,H=d.buyerAccessToken,G=void 0===H?l.buyerAccessToken:H,K=d.venmoPayloadID,Y=d.buyerIntent,W=l.buyerCountry,q=l.eligibility.venmoWebEnabled,$=f.cspNonce,z=function(e){var n=e.win,t=e.isClick,o=e.merchantRequestedPopupsDisabled,i=Object(r.M)();return Object(a.e)().info("spb_decide_context",{merchantRequestedPopupsDisabled:Boolean(o),isClick:Boolean(t),popupSupported:Boolean(i)}),!o&&n||!o&&t&&i?c.d.POPUP:c.d.IFRAME}({win:F,isClick:d.isClick,merchantRequestedPopupsDisabled:M}),X=!1,J=!1,Q=!1,Z=function(){return i.a.try((function(){if(n)return Q=!0,n.close()}))},ne=Object(r.x)((function(){return(n=h({window:F,sessionID:m,buttonSessionID:_,stickinessID:R,clientAccessToken:A,venmoPayloadID:K,parentDomain:Object(j.c)(),venmoWebUrl:sn[k],venmoWebEnabled:q,createOrder:function(){return g().then((function(e){return e}))},onApprove:function(e){var n=void 0===e?{}:e,t=n.approveOnClose,o=n.payerID,i=n.paymentID,c=n.billingToken,u=n.subscriptionID,s=n.authCode;if(void 0===t||!t)return X=!0,Object(a.e)().info("spb_onapprove_access_token_"+(G?"present":"not_present")).flush(),Object(a.v)(G),v({payerID:o,paymentID:i,billingToken:c,subscriptionID:u,buyerAccessToken:G,authCode:s},{restart:te}).finally((function(){return Z().then(r.y)})).catch(r.y);J=!0},onComplete:function(){return Object(a.e)().info("spb_oncomplete_access_token_"+(G?"present":"not_present")).flush(),Object(a.v)(G),E({buyerAccessToken:G}).finally((function(){return Z().then(r.y)})).catch(r.y)},onAuth:function(e){return N({accessToken:e.accessToken||G}).then((function(e){G=e}))},onCancel:function(){return Z().then((function(){return b()}))},onShippingChange:T?function(e,n){return T(Object(u.a)({buyerAccessToken:G},e),n)}:null,onShippingAddressChange:O?function(e,n){if(!e.shippingAddress)throw new Error("Must pass shippingAddress in data to handle changes in shipping address.");return O(Object(u.a)({},e),n)}:null,onShippingOptionsChange:I?function(e,n){if(!e.selectedShippingOption)throw new Error("Must pass selectedShippingOption in data to handle changes in shipping options.");return I(Object(u.a)({},e),n)}:null,onClose:function(){return J&&!X?v({forceRestAPI:!0},{restart:te}).catch(r.y):Q||X?void 0:b()},onError:function(e){var n;return Object(a.e)().info("venmo_flow_error ",{err:Object(r.K)(e)}).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.CHECKOUT_ERROR,n[o.g.EVENT_NAME]=c.l.CHECKOUT_ERROR,n[o.g.ERROR_DESC]=Object(r.K)(e),n)).flush(),y(e)},dimensions:Cn(B),fundingSource:B,card:V,buyerCountry:W,locale:w,commit:S,cspNonce:$,clientMetadataID:C,enableFunding:P,standaloneFundingSource:L,branded:U,restart:function(){return p(F?{win:F}:{win:Sn()})}})).renderTo(Sn(),c.z.BODY,z)})),te=Object(r.x)((function(){return Z().finally((function(){return Nn({props:t,components:s,serviceData:l,config:f,payment:{button:x,fundingSource:B,card:V,buyerIntent:Y,isClick:!1,checkoutRestart:!0},fallback:p}).start().finally(a.z)}))}));return{click:function(){return i.a.try((function(){if(!M&&!F&&Object(r.M)())try{var e=Cn(B);F=ee({width:e.width,height:e.height})}catch(e){if(Object(a.e)().warn("popup_open_error_iframe_fallback",{err:Object(r.K)(e)}),!(e instanceof r.a))throw e;z=c.d.IFRAME}return i.a.try((function(){return!D||D({fundingSource:B})})).then((function(e){var n;return F&&!e&&(Object(a.e)().info("native_onclick_invalid").track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.NATIVE_ON_CLICK_INVALID,n)).flush(),F.close()),e}))}))},start:ne,close:Z}}var kn,Pn={name:"native",setup:function(e){var n=e.props,t=e.serviceData;return n.fundingSource===o.j.VENMO&&t.eligibility.venmoWebEnabled&&function(e){var n=e.components.Venmo,t=[Object(j.d)(window),Object(j.e)(window)],o=t[0],a=t[1],c={};a&&o&&o!==a&&(c.canRenderTo=n.canRenderTo(a).then((function(e){wn=e}))),i.a.hash(c).then(r.y)}({components:e.components}),function(e){var n,t=e.props,r=e.serviceData,o=t.clientID,i=t.currency,a=t.platform,u=t.vault,s=t.buttonSessionID,l=t.enableFunding,d=t.merchantDomain,f=t.disableSetCookie,p=r.merchantID,h=r.buyerCountry,m=r.cookies,_=!r.eligibility.venmoWebEnabled&&Boolean(t.onShippingChange);return Object(D.w)({vault:u,platform:a,shippingCallbackEnabled:_,clientID:o,buyerCountry:h,currency:i,buttonSessionID:s,cookies:m,enableFunding:l,stickinessID:null,skipElmo:!0,merchantID:p[0],domain:d,headers:(n={},n[c.n.DISABLE_SET_COOKIE]=String(f),n)}).then((function(e){en=e}))}({props:n,serviceData:t}).then(r.y)},isEligible:function(e){var n,t,i,c=e.props,u=e.serviceData,s=c.fundingSource,l=c.onShippingChange,d=c.createBillingAgreement,f=c.createSubscription,p=c.env,h=c.platform,m=u.cookies,_=u.merchantID,g=u.fundingEligibility,v=u.eligibility.venmoWebEnabled,b=null==g||null==(n=g.venmo)?void 0:n.eligible,y=s===o.j.VENMO,E=p===o.d.LOCAL||p===o.d.STAGE;return!(!e.config.firebase||h&&h===o.m.DESKTOP&&!b||!dn({fundingSource:s})&&!fn({fundingSource:s})||(t=Date.now(),i=0,Object(a.j)((function(e){var n=e.nativeOptOutLifetime;n&&"number"==typeof n&&(i=n)})),i>t||!ln({props:c})&&(!m&&s===o.j.PAYPAL||!Object(r.M)()||!v&&l||d||f||!y&&E||_.length>1||!u.featureFlags.isLsatUpgradable)))},isPaymentEligible:function(e){var n=e.payment,t=e.props.platform,r=n.fundingSource,i=n.win,c=e.serviceData.eligibility.venmoWebEnabled;return!!(an[r]&&cn[r]&&un[r])&&!(!dn({fundingSource:r,win:i})&&!fn({fundingSource:r,win:i}))&&(t&&t===o.m.DESKTOP?!!c||!(!en||!en[r])&&en[r].eligibility:!(i&&!Object(a.x)(i).getWindow()))},init:function(e){var n=e.props,t=e.components,s=e.config,l=e.payment,d=e.serviceData,f=e.restart,p=n.onApprove,h=n.onCancel,m=n.onError,_=n.buttonSessionID,g=n.onShippingChange,v=d.eligibility.venmoWebEnabled,b=l.fundingSource,y=l.win;if(!s.firebase)throw new Error("Can not run native flow without firebase config");An&&An.all(),An=Object(r.c)();var E=!1,T=!1,O=!1,I=Object(r.x)((function(){return An.all()})),w=function(e){return O=!0,i.a.try((function(){return!e||Object(a.x)(e).isClosed()})).then((function(a){var c,p=a?null:e,h=Object(u.a)({},l,{win:p,isClick:!1});return c=b===o.j.VENMO&&v?Nn({props:n,components:t,payment:h,config:s,serviceData:d,fallback:Dn}):ue.init({props:n,components:t,payment:h,config:s,serviceData:d,restart:f}),i.a.all([I(),c.start()]).then(r.y)}))};Dn=function(e){var n=e||{},t=n.win,r=n.fallbackOptions,u=void 0===r?{}:r;return i.a.try((function(){var e,n,r=pn(u),i=u.fallback_reason;return n=r?c.l.NATIVE_OPT_OUT:b===o.j.VENMO&&v?c.l.NATIVE_FALLBACK_VENMO:c.l.NATIVE_FALLBACK,Object(a.e)().info("native_message_onfallback").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_ON_FALLBACK,e[c.i.TRANSITION_TYPE]=n,e[c.i.TRANSITION_REASON]=i||"",e)).flush(),w(t)}))};var S,A,C=Object(r.N)();if(function(e){var n=e.fundingSource;return!(!e.serviceData.eligibility.venmoWebEnabled||n&&n!==o.j.VENMO||e.win)}({fundingSource:b,win:y,serviceData:d})&&Boolean(g))Object(a.e)().info("venmo_web").track((A={},A[o.g.TRANSITION]=c.l.NATIVE_VENMO_WEB,A)).flush(),S=Nn;else if(dn({fundingSource:b,win:y}))S=In;else{if(!fn({fundingSource:b,win:y}))throw new Error("No valid native payment flow found");S=Tn}var N=S({payment:l,props:n,serviceData:d,config:s,components:t,clean:An,sessionUID:C,fallback:Dn,callbacks:{onInit:function(){return i.a.try((function(){return Object(D.G)(),{buttonSessionID:_}}))},onApprove:function(e){var n,t=e.data,u=t.payerID,s=t.paymentID,l=t.billingToken;return E=!0,Object(a.e)().info("native_message_onapprove",{payerID:u,paymentID:s,billingToken:l}).track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ON_APPROVE,n[c.i.INFO_MSG]="payerID: "+u+", paymentID: "+(s||"undefined")+", billingToken: "+(l||"undefined"),n)).flush(),i.a.all([p({payerID:u,paymentID:s,billingToken:l,forceRestAPI:!0},{restart:function(){return w()}}).catch((function(e){var n;Object(a.e)().info("native_message_onapprove_error",{payerID:u,paymentID:s,billingToken:l}).track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ON_APPROVE_ERROR,n[c.i.INFO_MSG]="Error: "+Object(r.K)(e),n)).flush(),m(e)})),I()]).then((function(){return{buttonSessionID:_}}))},onCancel:function(){var e;return T=!0,Object(a.e)().info("native_message_oncancel").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_ON_CANCEL,e)).flush(),i.a.all([h(),I()]).then((function(){return{buttonSessionID:_}}))},onError:function(e){var n,t=e.data.message;return Object(a.e)().info("native_message_onerror",{err:t}).track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ON_ERROR,n[c.i.INFO_MSG]="Error message: "+t,n)).flush(),i.a.all([m(new Error(t)),I()]).then((function(){return{buttonSessionID:_}}))},onShippingChange:function(e){var n=e.data;return i.a.try((function(){var e;if(Object(a.e)().info("native_message_onshippingchange").track((e={},e[o.g.TRANSITION]=c.l.NATIVE_ON_SHIPPING_CHANGE,e)).flush(),g){var t=!0,r={resolve:function(){return i.a.try((function(){t=!0}))},reject:function(){return i.a.try((function(){t=!1}))}};return g(Object(u.a)({},n,{forceRestAPI:!0}),r).then((function(){return{resolved:t}}))}return{resolved:!0}}))},onClose:function(){return i.a.delay(1e3).then((function(){if(!(E||T||O||Object(a.k)()))return i.a.try((function(){return I()}))})).then(r.y)},onDestroy:I}});return{click:function(){return N.click()},start:function(){return i.a.try((function(){return N.start()})).catch((function(e){return I().then((function(){var n;throw Object(a.e)().error("native_error",{err:Object(r.K)(e)}).track((n={},n[o.g.TRANSITION]=c.l.NATIVE_ERROR,n[o.g.ERROR_CODE]="native_error",n[o.g.ERROR_DESC]=Object(r.L)(e),n)).flush(),e}))}))},close:I}},updateFlowClientConfig:function(e){var n=e.orderID,t=e.payment,r=e.userExperienceFlow,o=e.buttonSessionID,a=e.featureFlags;return i.a.try((function(){var e=t.fundingSource;return Object(D.N)({fundingSource:e,orderID:n,inline:!1,userExperienceFlow:r,buttonSessionID:o,featureFlags:a})}))},spinner:!0},Rn={name:"popup_bridge",setup:function(e){var n=e.props;return i.a.try((function(){var e=n.getPopupBridge;if(e)return e().then((function(e){kn=e}))}))},isEligible:function(e){var n=e.props;return!(n.onShippingChange||n.onShippingAddressChange||n.onShippingOptionsChange)},isPaymentEligible:function(e){return!e.payment.win&&!!kn},init:function(e){var n=e.props,t=n.createOrder,o=n.onApprove,i=n.onCancel,u=n.commit,s=e.payment.fundingSource;return{start:function e(){return t().then((function(e){if(!kn)throw new Error("Popup bridge required");var n=Object(r.h)(""+Object(j.c)()+ne.m,{query:{fundingSource:s,token:e,useraction:u?c.A.COMMIT:c.A.CONTINUE,redirect_uri:kn.nativeUrl,native_xo:"1"}});return kn.start(n)})).then((function(n){var t=n.opType,r=n.PayerID,a=n.paymentId,c=n.ba_token;if(t===ge.POPUP_BRIDGE_OPTYPE.PAYMENT){if(!r&&!c)throw new Error("Expected payerID to be passed");return o({payerID:r,paymentID:a,billingToken:c},{restart:e})}if(t===ge.POPUP_BRIDGE_OPTYPE.CANCEL)return i();throw new Error("Unhandleable opType: "+t)}))},close:a.r}},spinner:!0},jn=t(33);function Ln(e,n){if(e.length!==n.length)return!1;var t=[],r=[];e.forEach((function(e){Object(a.l)(e)?t.push(e.toLowerCase()):r.push(e)}));var o=t.every((function(e){return n.some((function(n){return e===(n.email&&n.email.stringValue&&n.email.stringValue.toLowerCase())}))})),i=r.every((function(e){return n.some((function(n){return e===n.merchantId}))}));return!(!o||!i)&&n.every((function(e){return r.indexOf(e.merchantId)>-1||t.indexOf(e.email&&e.email.stringValue&&e.email.stringValue.toLowerCase())>-1}))}function Un(e){var n,t=e.error,r=e.message,i=void 0===r?t:r,a=e.orderID,u=e.loggerPayload,s=void 0===u?{}:u,l=e.throwError,d=(void 0===l||l)&&e.featureFlags.shouldThrowIntegrationError;if(Object(Ue.a)().warn(t,s).track((n={},n[o.g.STATE]=c.k.BUTTON,n[o.g.TRANSITION]=c.l.ORDER_VALIDATE,n[o.g.CONTEXT_TYPE]=c.h.ORDER_ID,n[o.g.TOKEN]=a,n[o.g.CONTEXT_ID]=a,n[c.i.INTEGRATION_ISSUE]=t,n[c.i.INTEGRATION_WHITELIST]=d?"false":"true",n[o.g.ERROR_DESC]=i,n)).flush(),d)throw console.error(i),new Error(i);console.warn(i)}var Mn,xn=[o.k.CAPTURE,o.k.AUTHORIZE,o.k.ORDER];function Fn(e){var n=e.containerUID;if(Mn)return Mn;var t=(0,e.Menu)({clientID:e.clientID});return t.hide(),t.renderTo(window.xprops.getParent(),"#"+n+" #smart-menu"),Mn=t}var Bn=[Ke,nn,Be,_e,Ee,Rn,R,Pn,ue];function Vn(e){var n=e.props,t=e.payment,r=e.config,o=e.serviceData;!n.fundingSource&&t.fundingSource&&(n.fundingSource=t.fundingSource);for(var i=0;i l && preact_module_i.sort(f)); + var n, u, t, o, r, e, c, s, a; + for (preact_module_i.sort(f); n = preact_module_i.shift(); ) n.__d && (u = preact_module_i.length, + o = void 0, e = (r = (t = n).__v).__e, s = [], a = [], (c = t.__P) && ((o = v({}, r)).__v = r.__v + 1, + l.vnode && l.vnode(o), L(c, o, r, t.__n, void 0 !== c.ownerSVGElement, 32 & r.__u ? [ e ] : null, s, null == e ? m(r) : e, !!(32 & r.__u), a), + o.__.__k[o.__i] = o, M(s, o, a), o.__e != e && k(o)), preact_module_i.length > u && preact_module_i.sort(f)); x.__r = 0; } - function P(n, l, u, t, i, o, r, f, e, a, v) { - var p, y, _, b, m, w, x, P, C, H = 0, I = t && t.__k || s, T = I.length, j = T, z = l.length; - for (u.__k = [], p = 0; p < z; p++) null != (b = u.__k[p] = null == (b = l[p]) || "boolean" == typeof b || "function" == typeof b ? null : "string" == typeof b || "number" == typeof b || "bigint" == typeof b ? d(null, b, null, null, b) : h(b) ? d(k, { - children: b - }, null, null, null) : b.__b > 0 ? d(b.type, b.props, b.key, b.ref ? b.ref : null, b.__v) : b) ? (b.__ = u, - b.__b = u.__b + 1, -1 === (P = A(b, I, x = p + H, j)) ? _ = c : (_ = I[P] || c, - I[P] = void 0, j--), L(n, b, _, i, o, r, f, e, a, v), m = b.__e, (y = b.ref) && _.ref != y && (_.ref && O(_.ref, null, b), - v.push(y, b.__c || m, b)), null != m && (null == w && (w = m), (C = _ === c || null === _.__v) ? -1 == P && H-- : P !== x && (P === x + 1 ? H++ : P > x ? j > z - x ? H += P - x : H-- : H = P < x && P == x - 1 ? P - x : 0), - x = p + H, "function" != typeof b.type || P === x && _.__k !== b.__k ? "function" == typeof b.type || P === x && !C ? void 0 !== b.__d ? (e = b.__d, - b.__d = void 0) : e = m.nextSibling : e = S(n, m, e) : e = $(b, e, n), "function" == typeof u.type && (u.__d = e))) : (_ = I[p]) && null == _.key && _.__e && (_.__e == e && (e = g(_)), - q(_, _, !1), I[p] = null); - for (u.__e = w, p = T; p--; ) null != I[p] && ("function" == typeof u.type && null != I[p].__e && I[p].__e == u.__d && (u.__d = I[p].__e.nextSibling), - q(I[p], I[p])); - } - function $(n, l, u) { - for (var t, i = n.__k, o = 0; i && o < i.length; o++) (t = i[o]) && (t.__ = n, l = "function" == typeof t.type ? $(t, l, u) : S(u, t.__e, l)); - return l; + function C(n, l, u, t, i, o, r, f, e, a, h) { + var v, p, y, d, _, g = t && t.__k || s, b = l.length; + for (u.__d = e, P(u, l, g), e = u.__d, v = 0; v < b; v++) null != (y = u.__k[v]) && "boolean" != typeof y && "function" != typeof y && (p = -1 === y.__i ? c : g[y.__i] || c, + y.__i = v, L(n, y, p, i, o, r, f, e, a, h), d = y.__e, y.ref && p.ref != y.ref && (p.ref && z(p.ref, null, y), + h.push(y.ref, y.__c || d, y)), null == _ && null != d && (_ = d), 65536 & y.__u || p.__k === y.__k ? e = S(y, e, n) : "function" == typeof y.type && void 0 !== y.__d ? e = y.__d : d && (e = d.nextSibling), + y.__d = void 0, y.__u &= -196609); + u.__d = e, u.__e = _; + } + function P(n, l, u) { + var t, i, o, r, f, e = l.length, c = u.length, s = c, a = 0; + for (n.__k = [], t = 0; t < e; t++) null != (i = n.__k[t] = null == (i = l[t]) || "boolean" == typeof i || "function" == typeof i ? null : "string" == typeof i || "number" == typeof i || "bigint" == typeof i || i.constructor == String ? d(null, i, null, null, i) : h(i) ? d(g, { + children: i + }, null, null, null) : i.__b > 0 ? d(i.type, i.props, i.key, i.ref ? i.ref : null, i.__v) : i) ? (i.__ = n, + i.__b = n.__b + 1, f = H(i, u, r = t + a, s), i.__i = f, o = null, -1 !== f && (s--, + (o = u[f]) && (o.__u |= 131072)), null == o || null === o.__v ? (-1 == f && a--, + "function" != typeof i.type && (i.__u |= 65536)) : f !== r && (f === r + 1 ? a++ : f > r ? s > e - r ? a += f - r : a-- : a = f < r && f == r - 1 ? f - r : 0, + f !== t + a && (i.__u |= 65536))) : (o = u[t]) && null == o.key && o.__e && (o.__e == n.__d && (n.__d = m(o)), + N(o, o, !1), u[t] = null, s--); + if (s) for (t = 0; t < c; t++) null != (o = u[t]) && 0 == (131072 & o.__u) && (o.__e == n.__d && (n.__d = m(o)), + N(o, o)); } function S(n, l, u) { - return null == u || u.parentNode !== n ? n.insertBefore(l, null) : l == u && null != l.parentNode || n.insertBefore(l, u), - l.nextSibling; + var t, i; + if ("function" == typeof n.type) { + for (t = n.__k, i = 0; t && i < t.length; i++) t[i] && (t[i].__ = n, l = S(t[i], l, u)); + return l; + } + return n.__e != l && (u.insertBefore(n.__e, l || null), l = n.__e), l && l.nextSibling; } - function A(n, l, u, t) { + function H(n, l, u, t) { var i = n.key, o = n.type, r = u - 1, f = u + 1, e = l[u]; if (null === e || e && i == e.key && o === e.type) return u; - if (t > (null != e ? 1 : 0)) for (;r >= 0 || f < l.length; ) { + if (t > (null != e && 0 == (131072 & e.__u) ? 1 : 0)) for (;r >= 0 || f < l.length; ) { if (r >= 0) { - if ((e = l[r]) && i == e.key && o === e.type) return r; + if ((e = l[r]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return r; r--; } if (f < l.length) { - if ((e = l[f]) && i == e.key && o === e.type) return f; + if ((e = l[f]) && 0 == (131072 & e.__u) && i == e.key && o === e.type) return f; f++; } } @@ -704,65 +712,70 @@ if (u) for (l in u) t && u[l] === t[l] || I(n.style, l, u[l]); } else if ("o" === l[0] && "n" === l[1]) o = l !== (l = l.replace(/(PointerCapture)$|Capture$/, "$1")), l = l.toLowerCase() in n ? l.toLowerCase().slice(2) : l.slice(2), n.l || (n.l = {}), - n.l[l + o] = u, u ? t || n.addEventListener(l, o ? z : j, o) : n.removeEventListener(l, o ? z : j, o); else if ("dangerouslySetInnerHTML" !== l) { - if (i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" !== l && "height" !== l && "href" !== l && "list" !== l && "form" !== l && "tabIndex" !== l && "download" !== l && "rowSpan" !== l && "colSpan" !== l && l in n) try { + n.l[l + o] = u, u ? t ? u.u = t.u : (u.u = Date.now(), n.addEventListener(l, o ? D : A, o)) : n.removeEventListener(l, o ? D : A, o); else { + if (i) l = l.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" !== l && "height" !== l && "href" !== l && "list" !== l && "form" !== l && "tabIndex" !== l && "download" !== l && "rowSpan" !== l && "colSpan" !== l && "role" !== l && l in n) try { n[l] = null == u ? "" : u; break n; } catch (n) {} "function" == typeof u || (null == u || !1 === u && "-" !== l[4] ? n.removeAttribute(l) : n.setAttribute(l, u)); } } - function j(n) { - return this.l[n.type + !1](l.event ? l.event(n) : n); + function A(n) { + var u = this.l[n.type + !1]; + if (n.t) { + if (n.t <= u.u) return; + } else n.t = Date.now(); + return u(l.event ? l.event(n) : n); } - function z(n) { + function D(n) { return this.l[n.type + !0](l.event ? l.event(n) : n); } function L(n, u, t, i, o, r, f, e, c, s) { - var a, p, y, d, _, g, m, w, x, $, C, S, A, H, I, T = u.type; + var a, p, y, d, _, m, k, w, x, P, S, $, H, I, T, A = u.type; if (void 0 !== u.constructor) return null; - null != t.__h && (c = t.__h, e = u.__e = t.__e, u.__h = null, r = [ e ]), (a = l.__b) && a(u); - n: if ("function" == typeof T) try { - if (w = u.props, x = (a = T.contextType) && i[a.__c], $ = a ? x ? x.props.value : a.__ : i, - t.__c ? m = (p = u.__c = t.__c).__ = p.__E : ("prototype" in T && T.prototype.render ? u.__c = p = new T(w, $) : (u.__c = p = new b(w, $), - p.constructor = T, p.render = B), x && x.sub(p), p.props = w, p.state || (p.state = {}), - p.context = $, p.__n = i, y = p.__d = !0, p.__h = [], p._sb = []), null == p.__s && (p.__s = p.state), - null != T.getDerivedStateFromProps && (p.__s == p.state && (p.__s = v({}, p.__s)), - v(p.__s, T.getDerivedStateFromProps(w, p.__s))), d = p.props, _ = p.state, p.__v = u, - y) null == T.getDerivedStateFromProps && null != p.componentWillMount && p.componentWillMount(), + 128 & t.__u && (c = !!(32 & t.__u), r = [ e = u.__e = t.__e ]), (a = l.__b) && a(u); + n: if ("function" == typeof A) try { + if (w = u.props, x = (a = A.contextType) && i[a.__c], P = a ? x ? x.props.value : a.__ : i, + t.__c ? k = (p = u.__c = t.__c).__ = p.__E : ("prototype" in A && A.prototype.render ? u.__c = p = new A(w, P) : (u.__c = p = new b(w, P), + p.constructor = A, p.render = O), x && x.sub(p), p.props = w, p.state || (p.state = {}), + p.context = P, p.__n = i, y = p.__d = !0, p.__h = [], p._sb = []), null == p.__s && (p.__s = p.state), + null != A.getDerivedStateFromProps && (p.__s == p.state && (p.__s = v({}, p.__s)), + v(p.__s, A.getDerivedStateFromProps(w, p.__s))), d = p.props, _ = p.state, p.__v = u, + y) null == A.getDerivedStateFromProps && null != p.componentWillMount && p.componentWillMount(), null != p.componentDidMount && p.__h.push(p.componentDidMount); else { - if (null == T.getDerivedStateFromProps && w !== d && null != p.componentWillReceiveProps && p.componentWillReceiveProps(w, $), - !p.__e && (null != p.shouldComponentUpdate && !1 === p.shouldComponentUpdate(w, p.__s, $) || u.__v === t.__v)) { + if (null == A.getDerivedStateFromProps && w !== d && null != p.componentWillReceiveProps && p.componentWillReceiveProps(w, P), + !p.__e && (null != p.shouldComponentUpdate && !1 === p.shouldComponentUpdate(w, p.__s, P) || u.__v === t.__v)) { for (u.__v !== t.__v && (p.props = w, p.state = p.__s, p.__d = !1), u.__e = t.__e, u.__k = t.__k, u.__k.forEach((function(n) { n && (n.__ = u); - })), C = 0; C < p._sb.length; C++) p.__h.push(p._sb[C]); + })), S = 0; S < p._sb.length; S++) p.__h.push(p._sb[S]); p._sb = [], p.__h.length && f.push(p); break n; } - null != p.componentWillUpdate && p.componentWillUpdate(w, p.__s, $), null != p.componentDidUpdate && p.__h.push((function() { - p.componentDidUpdate(d, _, g); + null != p.componentWillUpdate && p.componentWillUpdate(w, p.__s, P), null != p.componentDidUpdate && p.__h.push((function() { + p.componentDidUpdate(d, _, m); })); } - if (p.context = $, p.props = w, p.__P = n, p.__e = !1, S = l.__r, A = 0, "prototype" in T && T.prototype.render) { - for (p.state = p.__s, p.__d = !1, S && S(u), a = p.render(p.props, p.state, p.context), - H = 0; H < p._sb.length; H++) p.__h.push(p._sb[H]); + if (p.context = P, p.props = w, p.__P = n, p.__e = !1, $ = l.__r, H = 0, "prototype" in A && A.prototype.render) { + for (p.state = p.__s, p.__d = !1, $ && $(u), a = p.render(p.props, p.state, p.context), + I = 0; I < p._sb.length; I++) p.__h.push(p._sb[I]); p._sb = []; } else do { - p.__d = !1, S && S(u), a = p.render(p.props, p.state, p.context), p.state = p.__s; - } while (p.__d && ++A < 25); + p.__d = !1, $ && $(u), a = p.render(p.props, p.state, p.context), p.state = p.__s; + } while (p.__d && ++H < 25); p.state = p.__s, null != p.getChildContext && (i = v(v({}, i), p.getChildContext())), - y || null == p.getSnapshotBeforeUpdate || (g = p.getSnapshotBeforeUpdate(d, _)), - P(n, h(I = null != a && a.type === k && null == a.key ? a.props.children : a) ? I : [ I ], u, t, i, o, r, f, e, c, s), - p.base = u.__e, u.__h = null, p.__h.length && f.push(p), m && (p.__E = p.__ = null); + y || null == p.getSnapshotBeforeUpdate || (m = p.getSnapshotBeforeUpdate(d, _)), + C(n, h(T = null != a && a.type === g && null == a.key ? a.props.children : a) ? T : [ T ], u, t, i, o, r, f, e, c, s), + p.base = u.__e, u.__u &= -161, p.__h.length && f.push(p), k && (p.__E = p.__ = null); } catch (n) { - u.__v = null, (c || null != r) && (u.__e = e, u.__h = !!c, r[r.indexOf(e)] = null), - l.__e(n, u, t); - } else null == r && u.__v === t.__v ? (u.__k = t.__k, u.__e = t.__e) : u.__e = N(t.__e, u, t, i, o, r, f, c, s); + u.__v = null, c || null != r ? (u.__e = e, u.__u |= c ? 160 : 32, r[r.indexOf(e)] = null) : (u.__e = t.__e, + u.__k = t.__k), l.__e(n, u, t); + } else null == r && u.__v === t.__v ? (u.__k = t.__k, u.__e = t.__e) : u.__e = j(t.__e, u, t, i, o, r, f, c, s); (a = l.diffed) && a(u); } function M(n, u, t) { - for (var i = 0; i < t.length; i++) O(t[i], t[++i], t[++i]); + u.__d = void 0; + for (var i = 0; i < t.length; i++) z(t[i], t[++i], t[++i]); l.__c && l.__c(u, n), n.some((function(u) { try { n = u.__h, u.__h = [], n.some((function(n) { @@ -773,44 +786,40 @@ } })); } - function N(l, u, t, i, o, r, f, e, s) { - var a, v, y, d = t.props, _ = u.props, k = u.type, b = 0; - if ("svg" === k && (o = !0), null != r) for (;b < r.length; b++) if ((a = r[b]) && "setAttribute" in a == !!k && (k ? a.localName === k : 3 === a.nodeType)) { - l = a, r[b] = null; + function j(l, u, t, i, o, r, f, e, s) { + var a, v, y, d, _, g, b, k = t.props, w = u.props, x = u.type; + if ("svg" === x && (o = !0), null != r) for (a = 0; a < r.length; a++) if ((_ = r[a]) && "setAttribute" in _ == !!x && (x ? _.localName === x : 3 === _.nodeType)) { + l = _, r[a] = null; break; } if (null == l) { - if (null === k) return document.createTextNode(_); - l = o ? document.createElementNS("http://www.w3.org/2000/svg", k) : document.createElement(k, _.is && _), + if (null === x) return document.createTextNode(w); + l = o ? document.createElementNS("http://www.w3.org/2000/svg", x) : document.createElement(x, w.is && w), r = null, e = !1; } - if (null === k) d === _ || e && l.data === _ || (l.data = _); else { - if (r = r && n.call(l.childNodes), v = (d = t.props || c).dangerouslySetInnerHTML, - y = _.dangerouslySetInnerHTML, !e) { - if (null != r) for (d = {}, b = 0; b < l.attributes.length; b++) d[l.attributes[b].name] = l.attributes[b].value; - (y || v) && (y && (v && y.__html == v.__html || y.__html === l.innerHTML) || (l.innerHTML = y && y.__html || "")); - } - if (function(n, l, u, t, i) { - var o; - for (o in u) "children" === o || "key" === o || o in l || T(n, o, null, u[o], t); - for (o in l) i && "function" != typeof l[o] || "children" === o || "key" === o || "value" === o || "checked" === o || u[o] === l[o] || T(n, o, l[o], u[o], t); - }(l, _, d, o, e), y) u.__k = []; else if (P(l, h(b = u.props.children) ? b : [ b ], u, t, i, o && "foreignObject" !== k, r, f, r ? r[0] : t.__k && g(t, 0), e, s), - null != r) for (b = r.length; b--; ) null != r[b] && p(r[b]); - e || ("value" in _ && void 0 !== (b = _.value) && (b !== l.value || "progress" === k && !b || "option" === k && b !== d.value) && T(l, "value", b, d.value, !1), - "checked" in _ && void 0 !== (b = _.checked) && b !== l.checked && T(l, "checked", b, d.checked, !1)); + if (null === x) k === w || e && l.data === w || (l.data = w); else { + if (r = r && n.call(l.childNodes), k = t.props || c, !e && null != r) for (k = {}, + a = 0; a < l.attributes.length; a++) k[(_ = l.attributes[a]).name] = _.value; + for (a in k) _ = k[a], "children" == a || ("dangerouslySetInnerHTML" == a ? y = _ : "key" === a || a in w || T(l, a, null, _, o)); + for (a in w) _ = w[a], "children" == a ? d = _ : "dangerouslySetInnerHTML" == a ? v = _ : "value" == a ? g = _ : "checked" == a ? b = _ : "key" === a || e && "function" != typeof _ || k[a] === _ || T(l, a, _, k[a], o); + if (v) e || y && (v.__html === y.__html || v.__html === l.innerHTML) || (l.innerHTML = v.__html), + u.__k = []; else if (y && (l.innerHTML = ""), C(l, h(d) ? d : [ d ], u, t, i, o && "foreignObject" !== x, r, f, r ? r[0] : t.__k && m(t, 0), e, s), + null != r) for (a = r.length; a--; ) null != r[a] && p(r[a]); + e || (a = "value", void 0 !== g && (g !== l[a] || "progress" === x && !g || "option" === x && g !== k[a]) && T(l, a, g, k[a], !1), + a = "checked", void 0 !== b && b !== l[a] && T(l, a, b, k[a], !1)); } return l; } - function O(n, u, t) { + function z(n, u, t) { try { "function" == typeof n ? n(u) : n.current = u; } catch (n) { l.__e(n, t); } } - function q(n, u, t) { + function N(n, u, t) { var i, o; - if (l.unmount && l.unmount(n), (i = n.ref) && (i.current && i.current !== n.__e || O(i, null, u)), + if (l.unmount && l.unmount(n), (i = n.ref) && (i.current && i.current !== n.__e || z(i, null, u)), null != (i = n.__c)) { if (i.componentWillUnmount) try { i.componentWillUnmount(); @@ -819,10 +828,10 @@ } i.base = i.__P = null, n.__c = void 0; } - if (i = n.__k) for (o = 0; o < i.length; o++) i[o] && q(i[o], u, t || "function" != typeof n.type); + if (i = n.__k) for (o = 0; o < i.length; o++) i[o] && N(i[o], u, t || "function" != typeof n.type); t || null == n.__e || p(n.__e), n.__ = n.__e = n.__d = void 0; } - function B(n, l, u) { + function O(n, l, u) { return this.constructor(n, u); } n = s.slice, l = { @@ -843,7 +852,7 @@ w(this)); }, b.prototype.forceUpdate = function(n) { this.__v && (this.__e = !0, n && this.__h.push(n), w(this)); - }, b.prototype.render = k, preact_module_i = [], preact_module_r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, + }, b.prototype.render = g, preact_module_i = [], preact_module_r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f = function(n, l) { return n.__v.__b - l.__v.__b; }, x.__r = 0; @@ -2182,6 +2191,16 @@ }); })); } + var sendCountMetric = function(_ref) { + var dimensions = _ref.dimensions, _ref$event = _ref.event, event = void 0 === _ref$event ? "unused" : _ref$event, name = _ref.name, _ref$value = _ref.value, value = void 0 === _ref$value ? 1 : _ref$value; + return getLogger().metric({ + dimensions: dimensions, + metricEventName: event, + metricNamespace: name, + metricValue: value, + metricType: "counter" + }); + }; function util_getBody() { var body = document.body; if (!body) throw new Error("Document body not found"); @@ -2473,12 +2492,26 @@ err: message }); if (returnErrorObject) throw errors[0]; + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".error.count", + dimensions: {} + }); throw new Error(message); } if (200 !== status) { getLogger().warn("graphql_" + name + "_status_" + status + "_error"); + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".error.count", + dimensions: { + status: status + } + }); throw new Error("/graphql returned status " + status + "\n\n" + JSON.stringify(body)); } + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.graphql_" + name + ".success.count", + dimensions: {} + }); return body.data; })); } @@ -2506,8 +2539,8 @@ })); })); var _FRAUDNET_URL; - var FRAUDNET_URL = ((_FRAUDNET_URL = {}).local = "https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js", - _FRAUDNET_URL.stage = "https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js", + var FRAUDNET_URL = ((_FRAUDNET_URL = {}).local = "https://www.msmaster.qa.paypal.com/en_US/m/fb-raw.js", + _FRAUDNET_URL.stage = "https://stage2mb044.qa.paypal.com/fraudnetjsnodeweb/automate/develop/stage_raw.js", _FRAUDNET_URL.sandbox = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL.production = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL.test = "https://c.paypal.com/da/r/fb.js", _FRAUDNET_URL); memoize((function(_ref) { @@ -2544,7 +2577,7 @@ })); })); memoize((function(_ref) { - var clientID = _ref.clientID, merchantID = _ref.merchantID, currency = _ref.currency, _ref$amount = _ref.amount, amount = void 0 === _ref$amount ? "0.00" : _ref$amount, clientMetadataID = _ref.clientMetadataID, userIDToken = _ref.userIDToken, _ref$vetted = _ref.vetted, vetted = void 0 === _ref$vetted || _ref$vetted, paymentMethodToken = _ref.paymentMethodToken, branded = _ref.branded, _ref$allowBillingPaym = _ref.allowBillingPayments, allowBillingPayments = void 0 === _ref$allowBillingPaym || _ref$allowBillingPaym, _ref$headers = _ref.headers, headers = void 0 === _ref$headers ? {} : _ref$headers; + var clientID = _ref.clientID, merchantID = _ref.merchantID, currency = _ref.currency, _ref$amount = _ref.amount, amount = void 0 === _ref$amount ? "0" : _ref$amount, clientMetadataID = _ref.clientMetadataID, userIDToken = _ref.userIDToken, _ref$vetted = _ref.vetted, vetted = void 0 === _ref$vetted || _ref$vetted, paymentMethodToken = _ref.paymentMethodToken, branded = _ref.branded, _ref$allowBillingPaym = _ref.allowBillingPayments, allowBillingPayments = void 0 === _ref$allowBillingPaym || _ref$allowBillingPaym, _ref$headers = _ref.headers, headers = void 0 === _ref$headers ? {} : _ref$headers; clientMetadataID && (headers["paypal-client-metadata-id"] = String(clientMetadataID)); return callGraphQL({ name: "GetSmartWallet", @@ -3132,22 +3165,13 @@ logger.error("unhandled_error", { err: stringifyError(err) }); - dimensions = (_ref = { + sendCountMetric({ event: "error", name: "pp.app.paypal_sdk.buttons.unhandled_exception.count", dimensions: { errorType: "payments_sdk_error" } - }).dimensions, event = void 0 === (_ref$event = _ref.event) ? "unused" : _ref$event, - name = _ref.name, value = void 0 === (_ref$value = _ref.value) ? 1 : _ref$value, - getLogger().metric({ - dimensions: dimensions, - metricEventName: event, - metricNamespace: name, - metricValue: value, - metricType: "counter" }); - var _ref, dimensions, _ref$event, event, name, _ref$value, value; logger.flush().catch(src_util_noop); })); }({ @@ -3167,7 +3191,7 @@ logger.addTrackingBuilder((function() { var _ref; return (_ref = {}).state_name = "smart_button", _ref.context_type = "EC-Token", - _ref.context_id = orderID, _ref.button_session_id = buttonSessionID, _ref.button_version = "5.0.151", + _ref.context_id = orderID, _ref.button_session_id = buttonSessionID, _ref.button_version = "5.0.164", _ref.selected_payment_method = fundingSource, _ref; })); (function() { @@ -3434,18 +3458,18 @@ var content = survey.isEnabled && "qr_default" === state ? surveyElement : frontView; var escapePathFooter = !survey.isEnabled && "qr_default" === state && y("p", { className: "escape-path" - }, "Don't have the app? Pay with ", y("span", { + }, "Don't have the app? Pay with", " ", y("span", { className: "escape-path__link", onClick: function() { return handleClick("paypal"); } - }, "PayPal"), " or ", y("span", { + }, "PayPal"), " ", "or", " ", y("span", { className: "escape-path__link", onClick: function() { return handleClick("card"); } }, "Credit/Debit card")); - return y(k, null, y("style", { + return y(g, null, y("style", { nonce: window.xprops.cspNonce }, " ", '\n * {\n box-sizing: border-box;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n text-transform: none;\n }\n html, body {\n display: flex;\n position: fixed;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n align-items: center;\n justify-content: center;\n }\n body {\n flex-direction: column;\n }\n #error-view {\n width: 100%;\n height: 100%;\n padding: 1.5em;\n justify-content: center;\n }\n #error-view .error-message,\n #error-view .reset-button {\n color: #FFFFFF;\n text-align: center;\n line-height: 16px;\n }\n #error-view .error-message {\n margin-bottom: 2em;\n word-break: break-word;\n }\n #error-view .reset-button {\n cursor: pointer;\n border: 0;\n border-radius: 24px;\n padding: 12px;\n background: #3D93CE;\n line-height: 24px;\n font-weight: 700;\n width: 300px;\n }\n .card,\n #error-view {\n display: inline-flex;\n align-items: center;\n flex-direction: column;\n }\n .card {\n border-radius: 8px;\n min-width: 280px;\n min-height: 320px;\n backface-visibility: hidden;\n -webkit-backface-visibility: hidden;\n transition: transform 1s;\n transform-style: preserve-3d;\n }\n .card * {\n box-sizing: content-box;\n }\n #view-boxes {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 100%;\n }\n #view-boxes.qr_scanned #front-view,\n #view-boxes.qr_authorized #front-view {\n transform: rotateY(180deg);\n position: absolute;\n }\n #view-boxes #back-view {width: 320px;}\n #view-boxes.qr_scanned #back-view,\n #view-boxes.qr_authorized #back-view {\n transform: rotateY(0deg);\n position: relative;\n }\n #view-boxes #back-view #success-mark,\n #view-boxes #back-view .success-message {\n opacity: 0;\n }\n #view-boxes.qr_authorized #back-view #success-mark,\n #view-boxes.qr_authorized #back-view .success-message {\n opacity: 1;\n }\n #view-boxes.qr_authorized #back-view #success-mark {\n transform: rotate(720deg);\n }\n #view-boxes.qr_authorized #back-view .auth-message {\n opacity: 0;\n }\n #front-view {\n background-color: white;\n border: 1px solid #888C94;\n z-index: 2;\n transform: rotateY(0deg);\n justify-content: flex-end;\n width: 462px;\n }\n #front-view > svg,\n #front-view > img {\n padding: 16px 16px 0px;\n }\n #front-view > img + img {\n padding-top: 12px;\n padding-bottom: 32px;\n }\n #qr-code {\n min-width: 160px;\n min-height: 160px;\n width: calc(100% - 32px);\n max-width: 325px;\n }\n #instructions {\n background-color: #FFFF;\n border-top-left-radius: 8px;\n border-top-right-radius: 8px;\n box-sizing: border-box;\n margin-top: 16px;\n display: flex;\n align-items: center;\n font-size: 14px;\n line-height: 16px;\n max-width: 250px;\n width: 100%;\n }\n .instruction-icon {\n min-width: 68px;\n min-height: 46px;\n margin-right: 16px;\n }\n #fee-disclaimer{\n margin: 0;\n padding-top: 32px;\n padding-left: 16px;\n padding-right: 16px;\n font-size: 20px;\n color: #2F3033;\n }\n #back-view {\n position: absolute;\n transform: rotateY(-180deg);\n background-color: #3D93CE;\n justify-content: center;\n font-size: 18px;\n line-height: 16px;\n text-align: center;\n color: #FFFFFF;\n }\n #back-view .auth-message,\n #back-view .success-message {\n position: absolute;\n bottom: -30px;\n white-space: nowrap;\n transition: opacity 500ms;\n }\n #back-view .mark {\n position: relative ;\n }\n #venmo-mark{\n width: 50%;\n }\n #success-mark {\n position: absolute;\n left: 50%;\n bottom: -10%;\n transition: transform 500ms, opacity 500ms;\n transition-delay: 350ms;\n }\n #close {\n position: absolute;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n z-index: 10;\n }\n #close:hover {\n opacity: 1;\n }\n #close:before, #close:after {\n position: absolute;\n left: 8px;\n content: \' \';\n height: 20px;\n width: 2px;\n background-color: #FFF;\n }\n #close:before {\n transform: rotate(45deg);\n }\n #close:after {\n transform: rotate(-45deg);\n }\n #survey {\n background: #FFFFFF;\n height: 542px;\n width: 500px;\n border-radius: 8px;\n }\n #survey h1 {\n width: 423px;\n font-weight: 500;\n font-size: 24px;\n line-height: 32px;\n text-align: center;\n margin: auto;\n margin-top: 30px;\n }\n #survey button {\n display: block;\n margin: auto;\n border: none;\n font-family: sans-serif;\n cursor: pointer;\n font-weight: bold;\n }\n #survey button.continue-button {\n margin-top: 40px;\n min-height: 48px;\n width: 335px;\n background: #0074DE;\n height: 24px;\n font-size: 18px;\n line-height: 24px;\n text-align: center;\n color: #FFFFFF;\n border-radius: 24px;\n display: block;\n }\n #survey button.leave-button {\n margin-top: 10px;\n height: 48px;\n width: 335px;\n color: #0074DE;\n background: none;\n font-size: 18px;\n line-height: 24px;\n text-align: center;\n display: block;\n }\n #survey .message {\n width: 333px;\n font-family: sans-serif;\n font-size: 16px;\n line-height: 20px;\n text-align: center;\n margin: auto;\n margin-top: 8px;\n }\n\n #survey .answers {\n width: 400px;\n font-size: 16px;\n line-height: 20px;\n margin: auto;\n cursor: pointer;\n }\n #survey .answers .answer {\n margin-top: 28px;\n display: flex;\n align-items: center;\n }\n #survey label {\n font-family: sans-serif;\n font-size: 16px;\n cursor: pointer;\n display: flex;\n align-items: center;\n }\n #survey .answers svg{\n margin-right: 8px;\n min-width: 40px;\n }\n #survey .answers input{\n display: none;\n }\n #survey .answers input:focus::after {\n content: "";\n min-width: 44px;\n height: 44px;\n position: absolute;\n top: -2px;\n left: -2px;\n border: solid 1px black;\n border-radius: 50%;\n }\n .escape-path {\n background-color: white;\n color: #2F3033;\n width: 100%;\n text-align: center;\n padding: 1rem;\n margin: 0;\n border-bottom-left-radius: 16px;\n border-bottom-right-radius: 16px;\n }\n .escape-path__link {\n font-weight: 600;\n color: #008CFF;\n }\n .escape-path__link:hover {\n cursor: pointer;\n }\n ', " "), y("a", { href: "#", @@ -3483,7 +3507,7 @@ qrcard_logger = setupNativeQRLogger(); !function(u, t, i) { var r, f, e; - l.__ && l.__(u, t), r = !1 ? null : t.__k, f = [], e = [], L(t, u = t.__k = y(k, null, [ u ]), r || c, c, void 0 !== t.ownerSVGElement, r ? null : t.firstChild ? n.call(t.childNodes) : null, f, r ? r.__e : t.firstChild, !1, e), + l.__ && l.__(u, t), r = !1 ? null : t.__k, f = [], e = [], L(t, u = t.__k = y(g, null, [ u ]), r || c, c, void 0 !== t.ownerSVGElement, r ? null : t.firstChild ? n.call(t.childNodes) : null, f, r ? r.__e : t.firstChild, !1, e), M(f, u, e); }(y(QRCard, { svgString: svgString diff --git a/dist/smart-qrcode.min.js b/dist/smart-qrcode.min.js index 562e60ccd1..230d1f69d4 100644 --- a/dist/smart-qrcode.min.js +++ b/dist/smart-qrcode.min.js @@ -1 +1 @@ -!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define("spbQRCode",[],n):"object"==typeof exports?exports.spbQRCode=n():e.spbQRCode=n()}("undefined"!=typeof self?self:this,(function(){return function(e){var n={};function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(n){return e[n]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return{}.hasOwnProperty.call(e,n)},t.p="",t(t.s=2)}([function(e,n,t){e.exports=t(1)},function(e,n,t){"undefined"!=typeof self&&self,e.exports=function(e){var n={};function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(n){return e[n]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return{}.hasOwnProperty.call(e,n)},t.p="",t(t.s=0)}([function(e,n,t){"use strict";t.r(n),t.d(n,"ElementNode",(function(){return i})),t.d(n,"FragmentNode",(function(){return a})),t.d(n,"TextNode",(function(){return c})),t.d(n,"ComponentNode",(function(){return u})),t.d(n,"node",(function(){return p})),t.d(n,"Fragment",(function(){return h})),t.d(n,"text",(function(){return y})),t.d(n,"dom",(function(){return x})),t.d(n,"react",(function(){return T})),t.d(n,"html",(function(){return j})),t.d(n,"preact",(function(){return O})),t.d(n,"regex",(function(){return D})),t.d(n,"NODE_TYPE",(function(){return r})),t.d(n,"Style",(function(){return N})),t.d(n,"Regex",(function(){return A})),t.d(n,"RegexText",(function(){return I})),t.d(n,"RegexWord",(function(){return R})),t.d(n,"RegexCharacters",(function(){return q})),t.d(n,"RegexGroup",(function(){return B})),t.d(n,"RegexUnion",(function(){return W}));var r={ELEMENT:"element",TEXT:"text",COMPONENT:"component",FRAGMENT:"fragment"};function o(e,n){for(var t=[],r=0;r1?new a(n):void 0}(this.component(this.props,this.children));if(n)return n.render(e)},n.render=function(e){return e(this)},n.renderChildren=function(e){return o(this.children,e)},e}();function s(e){for(var n=[],t=0;t2?t-2:0),o=2;o=0||(o[t]=e[t]);return o}var E=["innerHTML","class"];function T(e){var n=(void 0===e?{}:e).React;if(!n)throw new Error("Must pass React library to react renderer");return function e(t){if(t.type===r.COMPONENT)return n.createElement.apply(n,[function(){return t.renderComponent(e)||null},t.props].concat(t.renderChildren(e)));if(t.type===r.ELEMENT)return n.createElement.apply(n,[t.name,(o=t.props,i=o.innerHTML,C({dangerouslySetInnerHTML:i?{__html:i}:null,className:o.class},k(o,E)))].concat(t.renderChildren(e)));var o,i;if(t.type===r.TEXT)return t.text;throw new TypeError("Unhandleable node")}}var M={br:!0};function S(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function j(){return function e(n){if(n.type===r.COMPONENT)return[].concat(n.renderComponent(e)).join("");if(n.type===r.ELEMENT){var t=(i=n.props,(a=Object.keys(i).filter((function(e){var n=i[e];return"innerHTML"!==e&&("string"==typeof n||"number"==typeof n||!0===n)}))).length?" "+a.map((function(e){var n=i[e];if(!0===n)return""+S(e);if("string"!=typeof n&&"number"!=typeof n)throw new TypeError("Unexpected prop type: "+typeof n);return""===n?S(e):S(e)+'="'+S(n.toString())+'"'})).join(" "):"");if(M[n.name])return"<"+n.name+t+" />";var o="string"==typeof n.props.innerHTML?n.props.innerHTML:n.renderChildren(e).join("");return"<"+n.name+t+">"+o+""}var i,a;if(n.type===r.TEXT)return S(n.text);throw new TypeError("Unhandleable node: "+n.type)}}var L=["innerHTML"];function O(e){var n=(void 0===e?{}:e).Preact;if(!n)throw new Error("Must pass Preact library to react renderer");return function e(t){if(t.type===r.COMPONENT)return n.h.apply(n,[function(){return t.renderComponent(e)||null},t.props].concat(t.renderChildren(e)));if(t.type===r.ELEMENT)return n.h.apply(n,[t.name,(o=t.props,i=o.innerHTML,C({dangerouslySetInnerHTML:i?{__html:i}:null},k(o,L)))].concat(t.renderChildren(e)));var o,i;if(t.type===r.TEXT)return t.text;throw new TypeError("Unhandleable node")}}function D(){var e=y();return function(n){return new RegExp(e(n))}}function N(e){var n=e.css,t=e.nonce,r=e.children;return p(h,null,p("style",{innerHTML:"string"==typeof n?n:n._getCss(),nonce:t}),r)}D.node=function(e,n){for(var t=arguments.length,r=new Array(t>2?t-2:0),o=2;o"),v.push.apply(v,n),v.push(")"),_(t)&&("number"==typeof t?v.push("{"+t+"}"):!0===t&&v.push("+")),(_(r)||_(o))&&v.push("{"+(r||"")+","+(o||"")+"}"),u&&v.push("?"),v}function W(e,n){for(var t=[],r=0,o=n=P("RegexGroup",n);r2&&(c.children=arguments.length>3?o.call(arguments,2):t),"function"==typeof e&&null!=e.defaultProps)for(a in e.defaultProps)void 0===c[a]&&(c[a]=e.defaultProps[a]);return m(e,c,r,i,null)}function m(e,n,t,r,o){var c={type:e,props:n,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==o?++a:o};return null==o&&null!=i.vnode&&i.vnode(c),c}function w(e){return e.children}function g(e,n){this.props=e,this.context=n}function b(e,n){if(null==n)return e.__?b(e.__,e.__.__k.indexOf(e)+1):null;for(var t;nn&&c.sort(l));C.__r=0}function k(e,n,t,r,o,i,a,c,u,s,l){var p,y,_,v,g,F,x,C,k,S=0,j=r&&r.__k||f,L=j.length,O=L,N=n.length;for(t.__k=[],p=0;p0?m(v.type,v.props,v.key,v.ref?v.ref:null,v.__v):v)?(v.__=t,v.__b=t.__b+1,-1===(C=M(v,j,x=p+S,O))?_=d:(_=j[C]||d,j[C]=void 0,O--),D(e,v,_,o,i,a,c,u,s,l),g=v.__e,(y=v.ref)&&_.ref!=y&&(_.ref&&P(_.ref,null,v),l.push(y,v.__c||g,v)),null!=g&&(null==F&&(F=g),(k=_===d||null===_.__v)?-1==C&&S--:C!==x&&(C===x+1?S++:C>x?O>N-x?S+=C-x:S--:S=C(null!=u?1:0))for(;a>=0||c=0){if((u=n[a])&&o==u.key&&i===u.type)return a;a--}if(c=t.__.length&&t.__.push({__V:z}),t.__[e]}function Q(e){return V=1,function(e,n,t){var r=J(R++,2);if(r.t=e,!r.__c&&(r.__=[oe(void 0,n),function(e){var n=r.__N?r.__N[0]:r.__[0],t=r.t(n,e);n!==t&&(r.__N=[t,r.__[1]],r.__c.setState({}))}],r.__c=q,!q.u)){var o=function(e,n,t){if(!r.__c.__H)return!0;var o=r.__c.__H.__.filter((function(e){return e.__c}));if(o.every((function(e){return!e.__N})))return!i||i.call(this,e,n,t);var a=!1;return o.forEach((function(e){if(e.__N){var n=e.__[0];e.__=e.__N,e.__N=void 0,n!==e.__[0]&&(a=!0)}})),!(!a&&r.__c.props===e)&&(!i||i.call(this,e,n,t))};q.u=!0;var i=q.shouldComponentUpdate,a=q.componentWillUpdate;q.componentWillUpdate=function(e,n,t){if(this.__e){var r=i;i=void 0,o(e,n,t),i=r}a&&a.call(this,e,n,t)},q.shouldComponentUpdate=o}return r.__N||r.__}(oe,e)}function K(){for(var e;e=U.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(te),e.__H.__h.forEach(re),e.__H.__h=[]}catch(n){e.__H.__h=[],i.__e(n,e.__v)}}i.__b=function(e){q=null,Z&&Z(e)},i.__r=function(e){$&&$(e),R=0;var n=(q=e.__c).__H;n&&(B===q?(n.__h=[],q.__h=[],n.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=z,e.__N=e.i=void 0}))):(n.__h.forEach(te),n.__h.forEach(re),n.__h=[],R=0)),B=q},i.diffed=function(e){G&&G(e);var n=e.__c;n&&n.__H&&(n.__H.__h.length&&(1!==U.push(n)&&W===i.requestAnimationFrame||((W=i.requestAnimationFrame)||ne)(K)),n.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==z&&(e.__=e.__V),e.i=void 0,e.__V=z}))),B=q=null},i.__c=function(e,n){n.some((function(e){try{e.__h.forEach(te),e.__h=e.__h.filter((function(e){return!e.__||re(e)}))}catch(t){n.some((function(e){e.__h&&(e.__h=[])})),n=[],i.__e(t,e.__v)}})),X&&X(e,n)},i.unmount=function(e){Y&&Y(e);var n,t=e.__c;t&&t.__H&&(t.__H.__.forEach((function(e){try{te(e)}catch(e){n=e}})),t.__H=void 0,n&&i.__e(n,t.__v))};var ee="function"==typeof requestAnimationFrame;function ne(e){var n,t=function(){clearTimeout(r),ee&&cancelAnimationFrame(n),setTimeout(e)},r=setTimeout(t,100);ee&&(n=requestAnimationFrame(t))}function te(e){var n=q,t=e.__c;"function"==typeof t&&(e.__c=void 0,t()),q=n}function re(e){var n=q;e.__c=e.__(),q=n}function oe(e,n){return"function"==typeof n?n(e):n}function ie(e){try{if(!e)return!1;if("undefined"!=typeof Promise&&e instanceof Promise)return!0;if("undefined"!=typeof window&&"function"==typeof window.Window&&e instanceof window.Window)return!1;if("undefined"!=typeof window&&"function"==typeof window.constructor&&e instanceof window.constructor)return!1;var n={}.toString;if(n){var t=n.call(e);if("[object Window]"===t||"[object global]"===t||"[object DOMWindow]"===t)return!1}if("function"==typeof e.then)return!0}catch(e){return!1}return!1}var ae,ce=[],ue=[],se=0;function le(){if(!se&&ae){var e=ae;ae=null,e.resolve()}}function de(){se+=1}function fe(){se-=1,le()}var pe=function(){function e(e){var n=this;if(this.resolved=void 0,this.rejected=void 0,this.errorHandled=void 0,this.value=void 0,this.error=void 0,this.handlers=void 0,this.dispatching=void 0,this.stack=void 0,this.resolved=!1,this.rejected=!1,this.errorHandled=!1,this.handlers=[],e){var t,r,o=!1,i=!1,a=!1;de();try{e((function(e){a?n.resolve(e):(o=!0,t=e)}),(function(e){a?n.reject(e):(i=!0,r=e)}))}catch(e){return fe(),void this.reject(e)}fe(),a=!0,o?this.resolve(t):i&&this.reject(r)}}var n=e.prototype;return n.resolve=function(e){if(this.resolved||this.rejected)return this;if(ie(e))throw new Error("Can not resolve promise with another promise");return this.resolved=!0,this.value=e,this.dispatch(),this},n.reject=function(e){var n=this;if(this.resolved||this.rejected)return this;if(ie(e))throw new Error("Can not reject promise with another promise");if(!e){var t=e&&"function"==typeof e.toString?e.toString():{}.toString.call(e);e=new Error("Expected reject to be called with Error, got "+t)}return this.rejected=!0,this.error=e,this.errorHandled||setTimeout((function(){n.errorHandled||function(e,n){if(-1===ce.indexOf(e)){ce.push(e),setTimeout((function(){throw e}),1);for(var t=0;t>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,n={};return Object.freeze(n),e.set(n,"__testvalue__"),"__testvalue__"===e.get(n)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var n=e.prototype;return n._cleanupClosedWindows=function(){for(var e=this.weakmap,n=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var t=e&&e.stack,r=e&&e.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+Ge(e,n+1)}}function Xe(e){return"data:image/svg+xml;base64,"+Re(e)}function Ye(e,n){void 0===n&&(n=Boolean);var t={};for(var r in e)e.hasOwnProperty(r)&&n(e[r],r)&&(t[r]=e[r]);return t}function Je(e){return[].slice.call(e)}ze.clear=function(){Ue=Ve},ze((function(e){if(Object.values)return Object.values(e);var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(e[t]);return n}));var Qe=function(e){function n(n){var t;return(t=e.call(this,n)||this).name=t.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t),t.constructor):t.stack=new Error(n).stack,t}return _e(n,e),n}(Pe(Error));function Ke(){return Boolean(document.body)&&"complete"===document.readyState}function en(){return Boolean(document.body)&&"interactive"===document.readyState}var nn=ze((function(){return new pe((function(e){if(Ke()||en())return e();var n=setInterval((function(){if(Ke()||en())return clearInterval(n),e()}),10)}))}));function tn(){return Ze(tn,(function(){var e=window.performance;if(e&&e.now&&e.timing&&e.timing.connectEnd&&e.timing.navigationStart&&Math.abs(e.now()-Date.now())>1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function rn(){return"undefined"!=typeof window&&void 0!==window.location}var on=function(e){function n(){return e.apply(this,arguments)||this}return _e(n,e),n}(Qe),an="undefined"!=typeof document?document.currentScript:null,cn=ze((function(){if(an)return an;if(an=function(){try{var e=function(){try{throw new Error("_")}catch(e){return e.stack||""}}(),n=/.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(e),t=n&&n[1];if(!t)return;for(var r=0,o=[].slice.call(document.getElementsByTagName("script")).reverse();rpn.indexOf(i))){var r=[n];r.push(t),(t.error||t.warning)&&r.push("\n\n",t.error||t.warning);try{window.console[e]&&window.console[e].apply?window.console[e].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(e){}}}function g(){return pe.try((function(){if(rn()&&"file:"!==window.location.protocol&&(f.length||p.length||h.length)){for(var e={},t=0;t<_.length;t++)hn(e,(0,_[t])(e));for(var r,o={},i=0;i1?new bn(n):void 0}(this.component(this.props,this.children));if(n)return n.render(e)},n.render=function(e){return e(this)},n.renderChildren=function(e){return wn(this.children,e)},e}();function Cn(e){for(var n=[],t=0;t2?t-2:0),o=2;o=0||(o[t]=e[t]);return o}var An,In={br:!0};function Rn(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function qn(e){return Mn("div",{class:"preloader spinner"},Mn("style",{nonce:e.nonce,innerHTML:"\n\n body {\n width: 100%;\n height: 100%;\n overflow: hidden;\n position: fixed;\n top: 0;\n left: 0;\n margin: 0;\n }\n\n .spinner {\n height: 100%;\n width: 100%;\n position: absolute;\n z-index: 10\n }\n\n .spinner .spinWrap {\n width: 200px;\n height: 100px;\n position: absolute;\n top: 50%;\n left: 50%;\n margin-left: -100px;\n margin-top: -50px\n }\n\n .spinner .loader,\n .spinner .spinnerImage {\n height: 100px;\n width: 100px;\n position: absolute;\n top: 0;\n left: 50%;\n opacity: 1;\n filter: alpha(opacity=100)\n }\n\n .spinner .spinnerImage {\n margin: 28px 0 0 -25px;\n background: url(https://www.paypalobjects.com/images/checkout/hermes/icon_ot_spin_lock_skinny.png) no-repeat\n }\n\n .spinner .loader {\n margin: 0 0 0 -55px;\n background-color: transparent;\n animation: rotation .7s infinite linear;\n border-left: 5px solid #cbcbca;\n border-right: 5px solid #cbcbca;\n border-bottom: 5px solid #cbcbca;\n border-top: 5px solid #2380be;\n border-radius: 100%\n }\n\n @keyframes rotation {\n from {\n transform: rotate(0deg)\n }\n to {\n transform: rotate(359deg)\n }\n }\n"}),Mn("div",{class:"spinWrap"},Mn("p",{class:"spinnerImage"}),Mn("p",{class:"loader"})))}function Bn(e,n){var t=e.nonce;return Mn("html",null,Mn("head",null,Mn("title",null,"PayPal"),Mn("meta",{name:"viewport",content:"width=device-width, initial-scale=1"})),Mn("body",null,Mn(qn,{nonce:t}),n))}function Wn(e){var n=e.name,t=e.variables,o=e.headers,i=e.returnErrorObject,a=void 0!==i&&i;return ln({url:"/graphql?"+n,method:"POST",json:{query:e.query,variables:void 0===t?{}:t},headers:r({"x-app-name":"smart-payment-buttons"},void 0===o?{}:o)}).then((function(e){var t=e.status,r=e.body,o=r.errors||[];if(o.length){var i=o[0].message||JSON.stringify(o[0]);if(_n().warn("graphql_"+n+"_error",{err:i}),a)throw o[0];throw new Error(i)}if(200!==t)throw _n().warn("graphql_"+n+"_status_"+t+"_error"),new Error("/graphql returned status "+t+"\n\n"+JSON.stringify(r));return r.data}))}ze((function(e){var n;return Wn({name:"GetCheckoutDetails",query:"\n query GetCheckoutDetails($orderID: String!) {\n checkoutSession(token: $orderID) {\n cart {\n billingType\n intent\n paymentId\n billingToken\n amounts {\n total {\n currencyValue\n currencyCode\n currencyFormatSymbolISOCurrency\n }\n }\n supplementary {\n initiationIntent\n }\n category\n }\n flags {\n isChangeShippingAddressAllowed\n }\n payees {\n merchantId\n email {\n stringValue\n }\n }\n }\n }\n ",variables:{orderID:e},headers:(n={},n["paypal-client-context"]=e,n)})})),ze((function(e){return pe.try((function(){if(!window.firebase||!window.firebase.auth||!window.firebase.database)return mn("https://www.paypalobjects.com/checkout/js/lib/firebase-app.js").then((function(){return pe.all([mn("https://www.paypalobjects.com/checkout/js/lib/firebase-auth.js"),mn("https://www.paypalobjects.com/checkout/js/lib/firebase-database.js")])}))})).then((function(){var n=window.firebase;if(!n)throw new Error("Firebase failed to load");return n.initializeApp(e),n}))}));var Vn=((An={}).local="https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js",An.stage="https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js",An.sandbox="https://c.paypal.com/da/r/fb.js",An.production="https://c.paypal.com/da/r/fb.js",An.test="https://c.paypal.com/da/r/fb.js",An);ze((function(e){var n=e.env,t=e.clientMetadataID,r=e.cspNonce,o=e.timeout,i=void 0===o?1e3:o,a=e.queryStringParams,c=void 0===a?{}:a;return new pe((function(e){var o={f:t,s:"SMART_PAYMENT_BUTTONS",u:window.xprops.buttonLocation,cb1:"fnCallback"};"sandbox"===n&&(o.sandbox=!0);var a=document.createElement("script");a.setAttribute("nonce",r||""),a.setAttribute("type","application/json"),a.setAttribute("id","fconfig"),a.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),a.textContent=JSON.stringify(o);var u=document.createElement("script"),s=Object.keys(c).map((function(e){return e+"="+encodeURIComponent(String(c[e]))})).join("&"),l=s.length?Vn[n]+"?"+s:Vn[n];u.setAttribute("nonce",r||""),u.setAttribute("src",l),u.addEventListener("error",(function(){return e()})),window.fnCallback=e,setTimeout(e,i);var d=vn();d.appendChild(a),d.appendChild(u)}))})),ze((function(e){var n=e.clientID,t=e.merchantID,r=e.currency,o=e.amount,i=void 0===o?"0.00":o,a=e.clientMetadataID,c=e.userIDToken,u=e.vetted,s=void 0===u||u,l=e.paymentMethodToken,d=e.branded,f=e.allowBillingPayments,p=void 0===f||f,h=e.headers,y=void 0===h?{}:h;return a&&(y["paypal-client-metadata-id"]=String(a)),Wn({name:"GetSmartWallet",query:"\n query GetSmartWallet(\n $clientID: String!\n $merchantID: [String!]\n $currency: String\n $amount: String\n $userIDToken: String\n $vetted: Boolean\n $paymentMethodToken: String\n $branded: Boolean,\n $allowBillingPayments: Boolean\n ) {\n smartWallet(\n clientId: $clientID\n merchantId: $merchantID\n currency: $currency\n amount: $amount\n userIdToken: $userIDToken\n vetted: $vetted\n paymentMethodNonce: $paymentMethodToken\n branded: $branded,\n allowBillingPayments: $allowBillingPayments\n ) {\n paypal {\n instruments {\n type\n label\n logoUrl\n instrumentID\n tokenID\n vendor\n oneClick\n accessToken\n }\n }\n credit {\n instruments {\n type\n label\n logoUrl\n instrumentID\n tokenID\n vendor\n oneClick\n accessToken\n }\n }\n card {\n instruments {\n type\n label\n logoUrl\n instrumentID\n tokenID\n vendor\n oneClick\n }\n }\n venmo {\n instruments {\n type\n label\n logoUrl\n instrumentID\n tokenID\n oneClick\n }\n }\n }\n }\n ",variables:{clientID:n,merchantID:t,currency:r,amount:i,userIDToken:c,vetted:s,paymentMethodToken:l,branded:d,allowBillingPayments:p},headers:y}).then((function(e){return e.smartWallet}))}));var Un,zn,Zn,$n,Gn,Xn,Yn,Jn,Qn,Kn,et,nt,tt,rt=t(0),ot=["svg","cdnUrl"],it=["render","name","logoColor"];function at(e){var n=e.svg,t=e.cdnUrl,o=Pn(e,ot);if(t){var i=r({src:t},o);return Mn("img",i)}if(!n)throw new TypeError("Expected svg prop");if("string"!=typeof(n=n.render((function e(n){if("component"===n.type)return[].concat(n.renderComponent(e)).join("");if("element"===n.type){var t=(o=n.props,(i=Object.keys(o).filter((function(e){var n=o[e];return"innerHTML"!==e&&("string"==typeof n||"number"==typeof n||!0===n)}))).length?" "+i.map((function(e){var n=o[e];if(!0===n)return""+Rn(e);if("string"!=typeof n&&"number"!=typeof n)throw new TypeError("Unexpected prop type: "+typeof n);return""===n?Rn(e):Rn(e)+'="'+Rn(n.toString())+'"'})).join(" "):"");if(In[n.name])return"<"+n.name+t+" />";var r="string"==typeof n.props.innerHTML?n.props.innerHTML:n.renderChildren(e).join("");return"<"+n.name+t+">"+r+""}var o,i;if("text"===n.type)return Rn(n.text);throw new TypeError("Unhandleable node: "+n.type)}))))throw new TypeError("Expected svg prop to be a string or jsx node");var a=r({src:Xe(n)},o);return Mn("img",a)}function ct(e){var n=e.render,t=e.name,o=e.logoColor,i=Pn(e,it);return Mn(at,r({},i,{svg:n?n():null,alt:"",class:"paypal-logo paypal-logo-"+t+" "+(o?"paypal-logo-color-"+o:"")}))}(Un={}).default={primary:"#ffffff",secondary:"#ffffff"},Un.white={primary:"#ffffff",secondary:"#ffffff"},Un.black={primary:"#000000",secondary:"#000000"},(zn={}).default={primary:"#FFFFFF",secondary:"#FFFFFF",tertiary:"#FFFFFF",quaternary:"#FFFFFF"},zn.white={primary:"#FFFFFF",secondary:"#FFFFFF",tertiary:"#FFFFFF",quaternary:"#FFFFFF"},zn.black={primary:"#1E3764",secondary:"#005AB9",tertiary:"#FBA900",quaternary:"#FFD800"},(Zn={}).default={primary:"#333030"},Zn.white={primary:"#ffffff"},Zn.black={primary:"#333030"},($n={}).default={primary:"#003087"},$n.blue={primary:"#003087"},$n.white={primary:"#ffffff"},$n.black={primary:"#333030"},(Gn={}).default={primary:"#FFFFFF",secondary:"#FFFFFF"},Gn.white={primary:"#FFFFFF",secondary:"#FFFFFF"},Gn.black={primary:"#C8036F",secondary:"#71706F"},(Xn={}).default={primary:"#FFFFFF",secondary:"#003A7D",tertiary:"#ED1C24",quaternary:"#FFFFFF",quinary:"#FFFFFF"},Xn.white={primary:"#000000",secondary:"#FFFFFF",tertiary:"#FFFFFF",quaternary:"#000000",quinary:"#FFFFFF"},Xn.black={primary:"#FFFFFF",secondary:"#003A7D",tertiary:"#ED1C24",quaternary:"#FFFFFF",quinary:"#003A7D"},(Yn={}).default={primary:"#FFFFFF",secondary:"#CC0066"},Yn.white={primary:"#FFFFFF",secondary:"#CC0066"},Yn.black={primary:"#FFFFFF",secondary:"#CC0066"},(Jn={}).default={primary:"#00C0EE",secondary:"#FFFFFF"},Jn.white={primary:"#FFFFFF",secondary:"#FFFFFF"},Jn.black={primary:"#00C0EE",secondary:"#1A4B67"},(Qn={}).default={primary:"#FFFFFF",secondary:"#FFFFFF"},Qn.white={primary:"#FFFFFF",secondary:"#FFFFFF"},Qn.black={primary:"#B3B1B1",secondary:"#D03238"},(Kn={}).default={primary:"#003087",secondary:"#009cde"},Kn.blue={primary:"#003087",secondary:"#009cde"},Kn.white={primary:"#ffffff",secondary:"#ffffff"},Kn.black={primary:"#333030",secondary:"#636363"},Kn.monochrome={primary:"#000000",secondary:"#000000"},(et={}).default={primary:"#009cde",secondary:"#012169",tertiary:"#003087"},et.blue={primary:"#009cde",secondary:"#012169",tertiary:"#003087"},et.white={primary:"#ffffff",primaryOpacity:"0.7",secondary:"#ffffff",secondaryOpacity:"0.7",tertiary:"#ffffff"},et.black={primary:"#808080",secondary:"#000000",tertiary:"#1a1a1a"},(nt={}).default={main:"#005DA0",card:"#AEB1BC"},nt.white={main:"#FFFFFF",card:"#FFFFFF"},nt.black={main:"#333030",card:"#333030"},(tt={}).default={primary:"#EDEDED",secondary:"#393A41"},tt.white={primary:"#FFFFFF",secondary:"#000000"},tt.black={primary:"#393A41",secondary:"#EDEDED"};var ut,st,lt,dt,ft,pt,ht,yt,_t,vt,mt,wt,gt=["logoColor"],bt=((ut={}).default={primary:"#3D93CE"},ut.blue={primary:"#3D93CE"},ut.white={primary:"#ffffff"},ut.black={primary:"#333030"},ut);function Ft(e){var n=e.resetFunc;return v("div",{id:"error-view"},v("div",{className:"error-message"},e.message||"An issue has occurred"),v("button",{className:"reset-button",type:"button",onClick:n},"Try scanning again"))}function xt(e){return v("img",{id:"qr-code",src:"data:image/svg+xml;base64,"+btoa(e.svgString),alt:"QR Code"})}function Ct(){return(e={logoColor:"default"},t=e.logoColor,o=void 0===t?"default":t,i=Pn(e,gt),n=function(e,n,t){var r;if(t&&(r=n[t]),r||(r=n.default),!r)throw new Error("No "+(t||"default")+" logo available for venmo");return r}(0,bt,o),a=Mn("svg",{width:"101",height:"32",viewBox:"0 0 101 32",xmlns:"http://www.w3.org/2000/svg",preserveAspectRatio:"xMinYMin meet"},Mn("g",{id:"Page-1",stroke:"none","stroke-width":"1",fill:"none","fill-rule":"evenodd"},Mn("g",{id:"Blue",fill:n.primary},Mn("g",{id:"Logo",transform:"translate(0.000000, 6.000000)"},Mn("path",{d:"M16.6660484,0.18 C17.3466626,1.3390991 17.6535069,2.53297297 17.6535069,4.04108108 C17.6535069,8.85117117 13.671346,15.0998198 10.439346,19.4875676 L3.05725952,19.4875676 L0.0966314879,1.23315315 L6.56045675,0.60036036 L8.12578201,13.5895495 C9.58835986,11.1326126 11.3932543,7.27153153 11.3932543,4.6390991 C11.3932543,3.1981982 11.1538599,2.21675676 10.7797405,1.40864865 L16.6660484,0.18 Z M24.9071592,11.6938739 C24.9071592,13.8367568 26.062718,14.6774775 27.5946678,14.6774775 C29.2629152,14.6774775 30.860218,14.2571171 32.9363097,13.1691892 L32.154346,18.6445045 C30.6915934,19.3814414 28.4119291,19.8731532 26.1991903,19.8731532 C20.5863512,19.8731532 18.5775346,16.3632432 18.5775346,11.9753153 C18.5775346,6.28810811 21.8451817,0.249369369 28.5819516,0.249369369 C32.2909931,0.249369369 34.3649879,2.39207207 34.3649879,5.37567568 C34.3653374,10.1855856 28.3783789,11.6590991 24.9071592,11.6938739 Z M25.0434567,8.2181982 C26.2329152,8.2181982 29.2274429,7.65711712 29.2274429,5.90216216 C29.2274429,5.05945946 28.6495761,4.6390991 27.9686125,4.6390991 C26.7772318,4.6390991 25.2138287,6.11225225 25.0434567,8.2181982 Z M53.0187093,4.4636036 C53.0187093,5.16558559 52.9154377,6.18378378 52.8126903,6.84918919 L50.8730709,19.4873874 L44.5790934,19.4873874 L46.3483408,7.90216216 C46.381891,7.58792793 46.4849879,6.95531532 46.4849879,6.60432432 C46.4849879,5.76162162 45.9743962,5.55135135 45.3605329,5.55135135 C44.5451938,5.55135135 43.7279325,5.93711712 43.1836159,6.21873874 L41.1768962,19.4875676 L34.8474464,19.4875676 L37.7390519,0.565945946 L43.2171661,0.565945946 L43.2865381,2.07621622 C44.5789187,1.19873874 46.2807163,0.24972973 48.6952803,0.24972973 C51.8942543,0.249369369 53.0187093,1.93495495 53.0187093,4.4636036 Z M71.7037093,2.32072072 C73.5063322,0.988108108 75.2084792,0.249369369 77.5554187,0.249369369 C80.7872439,0.249369369 81.9113495,1.93495495 81.9113495,4.4636036 C81.9113495,5.16558559 81.8084273,6.18378378 81.7056799,6.84918919 L79.7683322,19.4873874 L73.4726073,19.4873874 L75.2755796,7.6572973 C75.3087803,7.34108108 75.3785017,6.95531532 75.3785017,6.71063063 C75.3785017,5.7618018 74.8677353,5.55135135 74.2540467,5.55135135 C73.4722578,5.55135135 72.6908183,5.90234234 72.1106799,6.21873874 L70.1043097,19.4875676 L63.8101574,19.4875676 L65.6131298,7.65747748 C65.6463304,7.34126126 65.713955,6.9554955 65.713955,6.71081081 C65.713955,5.76198198 65.2030138,5.55153153 64.5914221,5.55153153 C63.7743356,5.55153153 62.9588218,5.9372973 62.4145052,6.21891892 L60.4062128,19.4877477 L54.0788599,19.4877477 L56.9701159,0.566126126 L62.3813045,0.566126126 L62.551327,2.14576577 C63.8101574,1.1990991 65.5105571,0.25009009 67.7900467,0.25009009 C69.7637405,0.249369369 71.0559464,1.12702703 71.7037093,2.32072072 Z M83.55059,11.7998198 C83.55059,5.83279279 86.6120433,0.249369369 93.6558322,0.249369369 C98.9633997,0.249369369 100.903543,3.47981982 100.903543,7.93873874 C100.903543,13.8365766 97.8751159,19.9443243 90.6614792,19.9443243 C85.3196626,19.9443243 83.55059,16.3281081 83.55059,11.7998198 Z M94.4374464,7.83279279 C94.4374464,6.28810811 94.0628028,5.23495495 92.9409689,5.23495495 C90.4570329,5.23495495 89.9469654,9.76306306 89.9469654,12.0794595 C89.9469654,13.8367568 90.4238322,14.9243243 91.5453166,14.9243243 C93.8931298,14.9243243 94.4374464,10.149009 94.4374464,7.83279279 Z"}))))),Mn(ct,r({},i,{name:"venmo",logoColor:o,render:function(){return a}}))).render(Object(rt.preact)({Preact:{h:v}}));var e,n,t,o,i,a}function kt(e){var n=e.stylingClass;return v("svg",{className:void 0===n?"instruction-icon":n,width:"68",height:"47",viewBox:"0 0 68 47",fill:"none",xmlns:"http://www.w3.org/2000/svg"},v("rect",{x:"11.5",y:"6.90039",width:"20.7",height:"29.9",fill:"white"}),v("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M30.82 2.2998H12.88C10.8475 2.2998 9.19995 3.98283 9.19995 6.05894V42.2407C9.19995 44.3168 10.8475 45.9998 12.88 45.9998H30.82C32.8524 45.9998 34.5 44.3168 34.5 42.2407V6.05894C34.5 3.98283 32.8524 2.2998 30.82 2.2998ZM21.8499 42.6635C20.8337 42.6635 20.0099 41.822 20.0099 40.784C20.0099 39.7459 20.8337 38.9044 21.8499 38.9044C22.8661 38.9044 23.6899 39.7459 23.6899 40.784C23.6899 41.822 22.8661 42.6635 21.8499 42.6635ZM11.9599 36.414H31.7399V7.32767H11.9599V36.414Z",fill:"#888C94"}),v("path",{d:"M25.7367 12.4121C26.107 13.0217 26.274 13.6495 26.274 14.4425C26.274 16.9719 24.1071 20.2578 22.3483 22.5651H18.3314L16.7205 12.966L20.2378 12.6333L21.0894 19.4636C21.8853 18.1716 22.8674 16.1412 22.8674 14.757C22.8674 13.9992 22.7371 13.4832 22.5335 13.0582L25.7367 12.4121Z",fill:"#008CFF"}),v("circle",{cx:"14.5",cy:"33.5",r:"1.25",fill:"white",stroke:"#0074DE","stroke-width":"0.5"}),v("circle",{cx:"18.5",cy:"33.5",r:"1.25",fill:"white",stroke:"#0074DE","stroke-width":"0.5"}),v("rect",{x:"21",y:"32",width:"9",height:"3",rx:"1.5",fill:"#0074DE"}),v("circle",{cx:"49",cy:"26",r:"18",fill:"white",stroke:"#2F3033","stroke-width":"2"}),v("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M56.7188 16.5H51.9688C50.985 16.5 50.1875 17.2975 50.1875 18.2812V23.0312C50.1875 24.015 50.985 24.8125 51.9688 24.8125H56.7188C57.7025 24.8125 58.5 24.015 58.5 23.0312V18.2812C58.5 17.2975 57.7025 16.5 56.7188 16.5ZM51.375 18.2812C51.375 17.9533 51.6408 17.6875 51.9688 17.6875H56.7188C57.0467 17.6875 57.3125 17.9533 57.3125 18.2812V23.0312C57.3125 23.3592 57.0467 23.625 56.7188 23.625H51.9688C51.6408 23.625 51.375 23.3592 51.375 23.0312V18.2812ZM41.875 19.5083C41.875 19.1585 42.1585 18.875 42.5083 18.875H44.8042C45.154 18.875 45.4375 19.1585 45.4375 19.5083V21.8042C45.4375 22.154 45.154 22.4375 44.8042 22.4375H42.5083C42.1585 22.4375 41.875 22.154 41.875 21.8042V19.5083ZM52.5625 19.5083C52.5625 19.1585 52.846 18.875 53.1958 18.875H55.4917C55.8415 18.875 56.125 19.1585 56.125 19.5083V21.8042C56.125 22.154 55.8415 22.4375 55.4917 22.4375H53.1958C52.846 22.4375 52.5625 22.154 52.5625 21.8042V19.5083ZM50.8208 27.1875C50.471 27.1875 50.1875 27.471 50.1875 27.8208V28.9292C50.1875 29.279 50.471 29.5625 50.8208 29.5625H51.9292C52.279 29.5625 52.5625 29.279 52.5625 28.9292V27.8208C52.5625 27.471 52.279 27.1875 51.9292 27.1875H50.8208ZM50.1875 33.7583C50.1875 33.4085 50.471 33.125 50.8208 33.125H51.9292C52.279 33.125 52.5625 33.4085 52.5625 33.7583V34.8667C52.5625 35.2165 52.279 35.5 51.9292 35.5H50.8208C50.471 35.5 50.1875 35.2165 50.1875 34.8667V33.7583ZM56.7583 27.1875C56.4085 27.1875 56.125 27.471 56.125 27.8208V28.9292C56.125 29.279 56.4085 29.5625 56.7583 29.5625H57.8667C58.2165 29.5625 58.5 29.279 58.5 28.9292V27.8208C58.5 27.471 58.2165 27.1875 57.8667 27.1875H56.7583ZM56.125 33.7583C56.125 33.4085 56.4085 33.125 56.7583 33.125H57.8667C58.2165 33.125 58.5 33.4085 58.5 33.7583V34.8667C58.5 35.2165 58.2165 35.5 57.8667 35.5H56.7583C56.4085 35.5 56.125 35.2165 56.125 34.8667V33.7583ZM53.7895 30.1562C53.4398 30.1562 53.1562 30.4398 53.1562 30.7895V31.898C53.1562 32.2477 53.4398 32.5312 53.7895 32.5312H54.898C55.2477 32.5312 55.5312 32.2477 55.5312 31.898V30.7895C55.5312 30.4398 55.2477 30.1562 54.898 30.1562H53.7895ZM41.875 30.1958C41.875 29.846 42.1585 29.5625 42.5083 29.5625H44.8042C45.154 29.5625 45.4375 29.846 45.4375 30.1958V32.4917C45.4375 32.8415 45.154 33.125 44.8042 33.125H42.5083C42.1585 33.125 41.875 32.8415 41.875 32.4917V30.1958ZM41.2812 27.1875H46.0312C47.015 27.1875 47.8125 27.985 47.8125 28.9688V33.7188C47.8125 34.7025 47.015 35.5 46.0312 35.5H41.2812C40.2975 35.5 39.5 34.7025 39.5 33.7188V28.9688C39.5 27.985 40.2975 27.1875 41.2812 27.1875ZM41.2812 28.375C40.9533 28.375 40.6875 28.6408 40.6875 28.9688V33.7188C40.6875 34.0467 40.9533 34.3125 41.2812 34.3125H46.0312C46.3592 34.3125 46.625 34.0467 46.625 33.7188V28.9688C46.625 28.6408 46.3592 28.375 46.0312 28.375H41.2812ZM41.2812 16.5H46.0312C47.015 16.5 47.8125 17.2975 47.8125 18.2812V23.0312C47.8125 24.015 47.015 24.8125 46.0312 24.8125H41.2812C40.2975 24.8125 39.5 24.015 39.5 23.0312V18.2812C39.5 17.2975 40.2975 16.5 41.2812 16.5ZM41.2812 17.6875C40.9533 17.6875 40.6875 17.9533 40.6875 18.2812V23.0312C40.6875 23.3592 40.9533 23.625 41.2812 23.625H46.0312C46.3592 23.625 46.625 23.3592 46.625 23.0312V18.2812C46.625 17.9533 46.3592 17.6875 46.0312 17.6875H41.2812Z",fill:"#008CFF"}),v("path",{d:"M36 13.0004L15 33",stroke:"#2F3033"}),v("path",{d:"M43.4999 43.4991L14.4999 32.9995",stroke:"#2F3033"}))}function Et(){return v("svg",{id:"venmo-mark",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48"},v("path",{d:"M42.3 2L28.5 4.8c.8 1.9 1.4 4.1 1.4 7.4 0 6-4.2 14.8-7.7 20.4L18.5 3 3.3 4.5l7 41.5h17.4c7.7-10 17-24.3 17-35.2 0-3.4-.8-6.1-2.4-8.8z",fill:"#fff"}))}function Tt(){return v("svg",{id:"success-mark",width:"59",height:"59",viewBox:"0 0 59 59",fill:"none",xmlns:"http://www.w3.org/2000/svg"},v("rect",{x:"1",y:"1",width:"57",height:"57",rx:"28.5",fill:"#148572",stroke:"#888C94"}),v("g",{"clip-path":"url(#clip0)"},v("path",{d:"M24.0068 40.8397C22.921 39.7538 22.921 37.9933 24.0068 36.9075L39.2933 21.621C40.3791 20.5352 42.1396 20.5352 43.2255 21.621C44.3113 22.7069 44.3113 24.4674 43.2255 25.5532L27.939 40.8397C26.8532 41.9255 25.0927 41.9255 24.0068 40.8397Z",fill:"white"}),v("path",{d:"M27.9763 40.8397C26.8905 41.9255 25.13 41.9255 24.0441 40.8397L17.1628 33.9583C16.0769 32.8725 16.0769 31.112 17.1628 30.0261C18.2486 28.9403 20.0091 28.9403 21.095 30.0261L27.9763 36.9075C29.0622 37.9933 29.0622 39.7538 27.9763 40.8397Z",fill:"white"})),v("defs",null,v("clipPath",{id:"clip0"},v("rect",{width:"27.8049",height:"27.8049",fill:"white",transform:"translate(16.2927 16.293)"}))))}(st={}).default={primary:"#ffffff"},st.blue={primary:"#003087"},st.white={primary:"#ffffff"},st.black={primary:"#333030"},(lt={}).default={primary:"#1AAD19",secondary:"#FFFFFF"},lt.white={primary:"#FFFFFF",secondary:"#FFFFFF"},lt.black={primary:"#1AAD19",secondary:"#4D4D4D"},(dt={}).default={primary:"#A6C307"},dt.white={primary:"#FFFFFF"},dt.black={primary:"#2C2E2F"},(ft={}).default={primary:"#FF0000",secondary:"#E83E49",tertiary:"#FF00FF",quaternary:"#000000",senary:"#FFFFFF"},ft.white={primary:"#000000",secondary:"#000000",tertiary:"#000000",quaternary:"#000000",senary:"#FFFFFF"},ft.black={primary:"#FF0000",secondary:"#E83E49",tertiary:"#FF00FF",quaternary:"#4D4D4F",senary:"#FFFFFF"},(pt={}).default={primary:"#0EE06E"},pt.white={primary:"#FFFFFF"},pt.black={primary:"#000000"},(ht={}).default={primary:"#FFFFFF",secondary:"#FFFFFF"},ht.white={primary:"#FFFFFF",secondary:"#FFFFFF"},ht.black={primary:"#E39E39",secondary:"#D8232A"},(yt={}).default={primary:"#FFFFFF"},yt.white={primary:"#FFFFFF"},yt.black={primary:"#000000"},(_t={}).default={primary:"#009EE3",secondary:"#FFFFFF",tertiary:"#009EE3",quaternary:"#FFFFFF"},_t.white={primary:"#000000",secondary:"#FFFFFF",tertiary:"#000000",quaternary:"#FFFFFF"},_t.black={primary:"#FFFFFF",secondary:"#2D3277",tertiary:"#009EE3",quaternary:"#009EE3"},(vt={}).default={primary:"#FFFFFF",secondary:"#FFFFFF"},vt.white={primary:"#FFFFFF",secondary:"#FFFFFF"},vt.black={primary:"#1866AB",secondary:"#373535"},(mt={}).default={primary:"#FFFFFF"},mt.white={primary:"#FFFFFF"},mt.black={primary:"#2C2E2F"},(wt={}).default={primary:"#FFFFFF",secondary:"#FFFFFF",tertiary:"#FFFFFF"},wt.white={primary:"#FFFFFF",secondary:"#FFFFFF",tertiary:"#FFFFFF"},wt.black={primary:"#A6009C",secondary:"#FF009C",tertiary:"#1C1C1C"};var Mt=new Map([["qr_default","qr_scanned"],["qr_error","qr_default"],["qr_authorized","qr_error"],["qr_scanned","qr_authorized"]]);function St(){var e=window.xprops,n=e.env,t=e.sessionID,r=e.buttonSessionID,o=e.sdkCorrelationID,i=e.clientID,a=e.fundingSource,c=void 0===a?"venmo":a,u=e.locale,s=e.orderID,l=(0,e.getParent)(),d=function(){if(!window.paypal)throw new Error("paypal not found");return window.paypal}().version,f=u.country,p=_n();return p.configure({transport:l&&yn(l)}),function(e){var n=e.env,t=e.sessionID,r=e.clientID,o=e.sdkCorrelationID,i=e.buyerCountry,a=e.locale,c=e.sdkVersion,u=void 0===c?window.paypal.version:c,s=_n();s.addPayloadBuilder((function(){return{referer:window.location.host,sdkCorrelationID:o,sessionID:t,clientID:r,env:n}})),s.addTrackingBuilder((function(){var e,n;return(e={}).feed_name="payments_sdk",e.serverside_data_source="checkout",e.client_id=r,e.page_session_id=t,e.referer_url=window.location.host,e.buyer_cntry=i,e.locale=a.lang+"_"+a.country,e.integration_identifier=r,e.sdk_environment=(void 0===n&&(n=he()),/iPhone|iPod|iPad/.test(n)?"iOS":function(e){return void 0===e&&(e=he()),/Android/.test(e)}()?"android":null),e.sdk_name="payments_sdk",e.sdk_version=u,e.user_agent=window.navigator&&window.navigator.userAgent,e.context_correlation_id=o,e.t=Date.now().toString(),e})),pe.onPossiblyUnhandledException((function(e){var n,t,r,o,i,a,c,u;s.track(((n={}).ext_error_code="payments_sdk_error",n.ext_error_desc=function(e){var n="";return e?e instanceof Error?e.message||n:"string"==typeof e.message&&e.message||n:n}(e),n)),s.error("unhandled_error",{err:Ge(e)}),r=(t={event:"error",name:"pp.app.paypal_sdk.buttons.unhandled_exception.count",dimensions:{errorType:"payments_sdk_error"}}).dimensions,i=void 0===(o=t.event)?"unused":o,a=t.name,u=void 0===(c=t.value)?1:c,_n().metric({dimensions:r,metricEventName:i,metricNamespace:a,metricValue:u,metricType:"counter"}),s.flush().catch($e)}))}({env:n,sessionID:t,clientID:i,sdkCorrelationID:o,locale:u,sdkVersion:d,buyerCountry:f}),p.addPayloadBuilder((function(){return{buttonSessionID:r}})),p.addTrackingBuilder((function(){var e;return(e={}).state_name="smart_button",e.context_type="EC-Token",e.context_id=s,e.button_session_id=r,e.button_version="5.0.151",e.selected_payment_method=c,e})),function(){if(window.document.documentMode)try{var e=window.status;return window.status="testIntranetMode","testIntranetMode"===window.status&&(window.status=e,!0)}catch(e){return!1}return!1}()&&p.warn("button_child_intranet_mode"),pe.hash({pageRenderTime:nn().then((function(){var e=tn();if(e){var n=e.timing;return n.connectEnd&&n.domInteractive?n.domInteractive-n.connectEnd:void 0}}))}).then((function(e){var n,t=e.pageRenderTime;p.track(((n={}).transition_name="qr_load",n.merchant_selected_funding_source=c,n.page_load_time=t?t.toString():"",n)),p.flush()})),p}var jt,Lt=v("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},v("rect",{x:"0.25",y:"0.25",width:"39.5",height:"39.5",rx:"19.75",stroke:"#888C94","stroke-width":"0.5"})),Ot=v("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},v("circle",{cx:"20",cy:"20",r:"12",fill:"#148572"}),v("rect",{x:"0.25",y:"0.25",width:"39.5",height:"39.5",rx:"19.75",stroke:"#148572","stroke-width":"0.5"}));function Dt(e){var n=e.survey,t=e.onCloseClick,r=function(e){e.target.blur(),n.setReason(e.target.value)},o=[{text:"Having trouble scanning the QR code",reason:"having_trouble_scanning_the_qr_code"},{text:"Don’t have the Venmo app on my mobile device",reason:"dont_have_the_venmo_app_on_my_mobile_device"},{text:"I prefer to pay another way",reason:"prefer_to_pay_another_way"},{text:"I prefer not to say",reason:"prefer_not_to_say"}].map((function(e){return v("div",{class:"answer"},v("input",{type:"radio",id:e.reason,value:e.reason,checked:e.reason===n.reason,onChange:r}),v("label",{for:e.reason},e.reason===n.reason?Ot:Lt,e.text))}));return v("div",{id:"survey"},v("h1",null,"We’re sorry to see you leave!"),v("p",{class:"message"},"Please let us know why. Your feedback is important to us."),v("div",{class:"answers"},o),v("button",{type:"button",class:"continue-button",onClick:n.disable},"Continue payment"),v("button",{type:"button",class:"leave-button",onClick:t},"Leave"))}function Nt(e){var n,t,o,a,c,u,s=e.svgString,l=(a=Q(window.xprops),c=a[0],u=a[1],n=function(){return c.onProps((function(e){u(r({},e))}))},t=[],o=J(R++,3),!i.__s&&function(e,n){return!e||e.length!==n.length||n.some((function(n,t){return n!==e[t]}))}(o.__H,t)&&(o.__=n,o.i=t,q.__H.__h.push(o)),r({},c,{setState:function(e){u(r({},c,{state:e}))}})),d=l.state,f=l.errorText,p=l.setState,h=l.close,y=l.onCancel,_=function(){var e=Q({isEnabled:!1,reason:"prefer_not_to_say"}),n=e[0],t=e[1];return r({},n,{enable:function(){return t(r({},n,{isEnabled:!0}))},disable:function(){return t(r({},n,{isEnabled:!1}))},setReason:function(e){return t(r({},n,{reason:e}))}})}(),m=function(e){window.xprops.hide();var n=function(e){var n,t=e.closeOnUnload,o=ke(function(e,n){var t=(n=n||{}).closeOnUnload,o=void 0===t?1:t,i=n.name,a=void 0===i?"":i,c=n.width,u=n.height,s=0,l=0;c&&(window.outerWidth?l=Math.round((window.outerWidth-c)/2)+window.screenX:window.screen.width&&(l=Math.round((window.screen.width-c)/2))),u&&(window.outerHeight?s=Math.round((window.outerHeight-u)/2)+window.screenY:window.screen.height&&(s=Math.round((window.screen.height-u)/2))),delete n.closeOnUnload,delete n.name,c&&u&&(n=r({top:s,left:l,width:c,height:u,status:1,toolbar:0,menubar:0,resizable:1,scrollbars:1},n));var d,f,p=Object.keys(n).map((function(e){if(null!=n[e])return e+"="+("string"==typeof(t=n[e])?t:t&&t.toString&&"function"==typeof t.toString?t.toString():{}.toString.call(t));var t})).filter(Boolean).join(",");try{d=window.open("",a,p)}catch(f){throw new on("Can not open popup window - "+(f.stack||f.message))}if(Me(d))throw new on("Can not open popup window - blocked");return o&&window.addEventListener("unload",(function(){return d.close()})),d}(0,{width:e.width,height:e.height,closeOnUnload:void 0===t?1:t})),i=o.document;return function(e,n){var t=n.tagName.toLowerCase();if("html"!==t)throw new Error("Expected element to be html, got "+t);for(var r=e.document.documentElement,o=0,i=Je(r.children);o svg,\n #front-view > img {\n padding: 16px 16px 0px;\n }\n #front-view > img + img {\n padding-top: 12px;\n padding-bottom: 32px;\n }\n #qr-code {\n min-width: 160px;\n min-height: 160px;\n width: calc(100% - 32px);\n max-width: 325px;\n }\n #instructions {\n background-color: #FFFF;\n border-top-left-radius: 8px;\n border-top-right-radius: 8px;\n box-sizing: border-box;\n margin-top: 16px;\n display: flex;\n align-items: center;\n font-size: 14px;\n line-height: 16px;\n max-width: 250px;\n width: 100%;\n }\n .instruction-icon {\n min-width: 68px;\n min-height: 46px;\n margin-right: 16px;\n }\n #fee-disclaimer{\n margin: 0;\n padding-top: 32px;\n padding-left: 16px;\n padding-right: 16px;\n font-size: 20px;\n color: #2F3033;\n }\n #back-view {\n position: absolute;\n transform: rotateY(-180deg);\n background-color: #3D93CE;\n justify-content: center;\n font-size: 18px;\n line-height: 16px;\n text-align: center;\n color: #FFFFFF;\n }\n #back-view .auth-message,\n #back-view .success-message {\n position: absolute;\n bottom: -30px;\n white-space: nowrap;\n transition: opacity 500ms;\n }\n #back-view .mark {\n position: relative ;\n }\n #venmo-mark{\n width: 50%;\n }\n #success-mark {\n position: absolute;\n left: 50%;\n bottom: -10%;\n transition: transform 500ms, opacity 500ms;\n transition-delay: 350ms;\n }\n #close {\n position: absolute;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n z-index: 10;\n }\n #close:hover {\n opacity: 1;\n }\n #close:before, #close:after {\n position: absolute;\n left: 8px;\n content: \' \';\n height: 20px;\n width: 2px;\n background-color: #FFF;\n }\n #close:before {\n transform: rotate(45deg);\n }\n #close:after {\n transform: rotate(-45deg);\n }\n #survey {\n background: #FFFFFF;\n height: 542px;\n width: 500px;\n border-radius: 8px;\n }\n #survey h1 {\n width: 423px;\n font-weight: 500;\n font-size: 24px;\n line-height: 32px;\n text-align: center;\n margin: auto;\n margin-top: 30px;\n }\n #survey button {\n display: block;\n margin: auto;\n border: none;\n font-family: sans-serif;\n cursor: pointer;\n font-weight: bold;\n }\n #survey button.continue-button {\n margin-top: 40px;\n min-height: 48px;\n width: 335px;\n background: #0074DE;\n height: 24px;\n font-size: 18px;\n line-height: 24px;\n text-align: center;\n color: #FFFFFF;\n border-radius: 24px;\n display: block;\n }\n #survey button.leave-button {\n margin-top: 10px;\n height: 48px;\n width: 335px;\n color: #0074DE;\n background: none;\n font-size: 18px;\n line-height: 24px;\n text-align: center;\n display: block;\n }\n #survey .message {\n width: 333px;\n font-family: sans-serif;\n font-size: 16px;\n line-height: 20px;\n text-align: center;\n margin: auto;\n margin-top: 8px;\n }\n\n #survey .answers {\n width: 400px;\n font-size: 16px;\n line-height: 20px;\n margin: auto;\n cursor: pointer;\n }\n #survey .answers .answer {\n margin-top: 28px;\n display: flex;\n align-items: center;\n }\n #survey label {\n font-family: sans-serif;\n font-size: 16px;\n cursor: pointer;\n display: flex;\n align-items: center;\n }\n #survey .answers svg{\n margin-right: 8px;\n min-width: 40px;\n }\n #survey .answers input{\n display: none;\n }\n #survey .answers input:focus::after {\n content: "";\n min-width: 44px;\n height: 44px;\n position: absolute;\n top: -2px;\n left: -2px;\n border: solid 1px black;\n border-radius: 50%;\n }\n .escape-path {\n background-color: white;\n color: #2F3033;\n width: 100%;\n text-align: center;\n padding: 1rem;\n margin: 0;\n border-bottom-left-radius: 16px;\n border-bottom-right-radius: 16px;\n }\n .escape-path__link {\n font-weight: 600;\n color: #008CFF;\n }\n .escape-path__link:hover {\n cursor: pointer;\n }\n '," "),v("a",{href:"#",id:"close","aria-label":"close",role:"button",onClick:g}),v("div",{id:"view-boxes",className:d},"qr_error"===d?b:C,v("div",{className:"card",id:"back-view"},v("span",{className:"mark"},v(Et,null),v(Tt,null)),v("div",{className:"auth-message"},"Go to your Venmo app and authorize"),v("div",{className:"success-message"},"Venmo account authorized")),window.xprops.debug&&v("button",{type:"button",style:{position:"absolute",bottom:"8px",padding:"4px",right:"8px"},onClick:function(){return p(Mt.get(d))}},"Next State")),k)}function Ht(e){var n=e.svgString;jt=St(),function(e,n,t){var r,a,c;i.__&&i.__(e,n),r=!1?null:n.__k,a=[],c=[],D(n,e=n.__k=v(w,null,[e]),r||d,d,void 0!==n.ownerSVGElement,r?null:n.firstChild?o.call(n.childNodes):null,a,r?r.__e:n.firstChild,!1,c),N(a,e,c)}(v(Nt,{svgString:n}),vn())}}])})); \ No newline at end of file +!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define("spbQRCode",[],n):"object"==typeof exports?exports.spbQRCode=n():e.spbQRCode=n()}("undefined"!=typeof self?self:this,(function(){return function(e){var n={};function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(n){return e[n]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return{}.hasOwnProperty.call(e,n)},t.p="",t(t.s=2)}([function(e,n,t){e.exports=t(1)},function(e,n,t){"undefined"!=typeof self&&self,e.exports=function(e){var n={};function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var o in e)t.d(r,o,function(n){return e[n]}.bind(null,o));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return{}.hasOwnProperty.call(e,n)},t.p="",t(t.s=0)}([function(e,n,t){"use strict";t.r(n),t.d(n,"ElementNode",(function(){return i})),t.d(n,"FragmentNode",(function(){return a})),t.d(n,"TextNode",(function(){return c})),t.d(n,"ComponentNode",(function(){return u})),t.d(n,"node",(function(){return p})),t.d(n,"Fragment",(function(){return h})),t.d(n,"text",(function(){return _})),t.d(n,"dom",(function(){return x})),t.d(n,"react",(function(){return T})),t.d(n,"html",(function(){return j})),t.d(n,"preact",(function(){return O})),t.d(n,"regex",(function(){return D})),t.d(n,"NODE_TYPE",(function(){return r})),t.d(n,"Style",(function(){return N})),t.d(n,"Regex",(function(){return A})),t.d(n,"RegexText",(function(){return I})),t.d(n,"RegexWord",(function(){return q})),t.d(n,"RegexCharacters",(function(){return R})),t.d(n,"RegexGroup",(function(){return B})),t.d(n,"RegexUnion",(function(){return W}));var r={ELEMENT:"element",TEXT:"text",COMPONENT:"component",FRAGMENT:"fragment"};function o(e,n){for(var t=[],r=0;r1?new a(n):void 0}(this.component(this.props,this.children));if(n)return n.render(e)},n.render=function(e){return e(this)},n.renderChildren=function(e){return o(this.children,e)},e}();function s(e){for(var n=[],t=0;t2?t-2:0),o=2;o=0||(o[t]=e[t]);return o}var E=["innerHTML","class"];function T(e){var n=(void 0===e?{}:e).React;if(!n)throw new Error("Must pass React library to react renderer");return function e(t){if(t.type===r.COMPONENT)return n.createElement.apply(n,[function(){return t.renderComponent(e)||null},t.props].concat(t.renderChildren(e)));if(t.type===r.ELEMENT)return n.createElement.apply(n,[t.name,(o=t.props,i=o.innerHTML,C({dangerouslySetInnerHTML:i?{__html:i}:null,className:o.class},k(o,E)))].concat(t.renderChildren(e)));var o,i;if(t.type===r.TEXT)return t.text;throw new TypeError("Unhandleable node")}}var M={br:!0};function S(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function j(){return function e(n){if(n.type===r.COMPONENT)return[].concat(n.renderComponent(e)).join("");if(n.type===r.ELEMENT){var t=(i=n.props,(a=Object.keys(i).filter((function(e){var n=i[e];return"innerHTML"!==e&&("string"==typeof n||"number"==typeof n||!0===n)}))).length?" "+a.map((function(e){var n=i[e];if(!0===n)return""+S(e);if("string"!=typeof n&&"number"!=typeof n)throw new TypeError("Unexpected prop type: "+typeof n);return""===n?S(e):S(e)+'="'+S(n.toString())+'"'})).join(" "):"");if(M[n.name])return"<"+n.name+t+" />";var o="string"==typeof n.props.innerHTML?n.props.innerHTML:n.renderChildren(e).join("");return"<"+n.name+t+">"+o+""}var i,a;if(n.type===r.TEXT)return S(n.text);throw new TypeError("Unhandleable node: "+n.type)}}var L=["innerHTML"];function O(e){var n=(void 0===e?{}:e).Preact;if(!n)throw new Error("Must pass Preact library to react renderer");return function e(t){if(t.type===r.COMPONENT)return n.h.apply(n,[function(){return t.renderComponent(e)||null},t.props].concat(t.renderChildren(e)));if(t.type===r.ELEMENT)return n.h.apply(n,[t.name,(o=t.props,i=o.innerHTML,C({dangerouslySetInnerHTML:i?{__html:i}:null},k(o,L)))].concat(t.renderChildren(e)));var o,i;if(t.type===r.TEXT)return t.text;throw new TypeError("Unhandleable node")}}function D(){var e=_();return function(n){return new RegExp(e(n))}}function N(e){var n=e.css,t=e.nonce,r=e.children;return p(h,null,p("style",{innerHTML:"string"==typeof n?n:n._getCss(),nonce:t}),r)}D.node=function(e,n){for(var t=arguments.length,r=new Array(t>2?t-2:0),o=2;o"),v.push.apply(v,n),v.push(")"),y(t)&&("number"==typeof t?v.push("{"+t+"}"):!0===t&&v.push("+")),(y(r)||y(o))&&v.push("{"+(r||"")+","+(o||"")+"}"),u&&v.push("?"),v}function W(e,n){for(var t=[],r=0,o=n=P("RegexGroup",n);r2&&(c.children=arguments.length>3?o.call(arguments,2):t),"function"==typeof e&&null!=e.defaultProps)for(a in e.defaultProps)void 0===c[a]&&(c[a]=e.defaultProps[a]);return m(e,c,r,i,null)}function m(e,n,t,r,o){var c={type:e,props:n,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:null==o?++a:o,__i:-1,__u:0};return null==o&&null!=i.vnode&&i.vnode(c),c}function w(e){return e.children}function g(e,n){this.props=e,this.context=n}function b(e,n){if(null==n)return e.__?b(e.__,e.__i+1):null;for(var t;nn&&c.sort(l));C.__r=0}function k(e,n,t,r,o,i,a,c,u,s,l){var p,h,_,y,v,m=r&&r.__k||f,w=n.length;for(t.__d=u,E(t,n,m),u=t.__d,p=0;p0?m(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o)?(o.__=e,o.__b=e.__b+1,c=M(o,t,a=r+d,l),o.__i=c,i=null,-1!==c&&(l--,(i=t[c])&&(i.__u|=131072)),null==i||null===i.__v?(-1==c&&d--,"function"!=typeof o.type&&(o.__u|=65536)):c!==a&&(c===a+1?d++:c>a?l>u-a?d+=c-a:d--:d=c(null!=u&&0==(131072&u.__u)?1:0))for(;a>=0||c=0){if((u=n[a])&&0==(131072&u.__u)&&o==u.key&&i===u.type)return a;a--}if(c=t.__.length&&t.__.push({__V:z}),t.__[e]}function Q(e){return U=1,function(e,n,t){var r=J(q++,2);if(r.t=e,!r.__c&&(r.__=[oe(void 0,n),function(e){var n=r.__N?r.__N[0]:r.__[0],t=r.t(n,e);n!==t&&(r.__N=[t,r.__[1]],r.__c.setState({}))}],r.__c=R,!R.u)){var o=function(e,n,t){if(!r.__c.__H)return!0;var o=r.__c.__H.__.filter((function(e){return e.__c}));if(o.every((function(e){return!e.__N})))return!i||i.call(this,e,n,t);var a=!1;return o.forEach((function(e){if(e.__N){var n=e.__[0];e.__=e.__N,e.__N=void 0,n!==e.__[0]&&(a=!0)}})),!(!a&&r.__c.props===e)&&(!i||i.call(this,e,n,t))};R.u=!0;var i=R.shouldComponentUpdate,a=R.componentWillUpdate;R.componentWillUpdate=function(e,n,t){if(this.__e){var r=i;i=void 0,o(e,n,t),i=r}a&&a.call(this,e,n,t)},R.shouldComponentUpdate=o}return r.__N||r.__}(oe,e)}function K(){for(var e;e=V.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(te),e.__H.__h.forEach(re),e.__H.__h=[]}catch(n){e.__H.__h=[],i.__e(n,e.__v)}}i.__b=function(e){R=null,Z&&Z(e)},i.__r=function(e){$&&$(e),q=0;var n=(R=e.__c).__H;n&&(B===R?(n.__h=[],R.__h=[],n.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=z,e.__N=e.i=void 0}))):(n.__h.forEach(te),n.__h.forEach(re),n.__h=[],q=0)),B=R},i.diffed=function(e){G&&G(e);var n=e.__c;n&&n.__H&&(n.__H.__h.length&&(1!==V.push(n)&&W===i.requestAnimationFrame||((W=i.requestAnimationFrame)||ne)(K)),n.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==z&&(e.__=e.__V),e.i=void 0,e.__V=z}))),B=R=null},i.__c=function(e,n){n.some((function(e){try{e.__h.forEach(te),e.__h=e.__h.filter((function(e){return!e.__||re(e)}))}catch(t){n.some((function(e){e.__h&&(e.__h=[])})),n=[],i.__e(t,e.__v)}})),X&&X(e,n)},i.unmount=function(e){Y&&Y(e);var n,t=e.__c;t&&t.__H&&(t.__H.__.forEach((function(e){try{te(e)}catch(e){n=e}})),t.__H=void 0,n&&i.__e(n,t.__v))};var ee="function"==typeof requestAnimationFrame;function ne(e){var n,t=function(){clearTimeout(r),ee&&cancelAnimationFrame(n),setTimeout(e)},r=setTimeout(t,100);ee&&(n=requestAnimationFrame(t))}function te(e){var n=R,t=e.__c;"function"==typeof t&&(e.__c=void 0,t()),R=n}function re(e){var n=R;e.__c=e.__(),R=n}function oe(e,n){return"function"==typeof n?n(e):n}function ie(e){try{if(!e)return!1;if("undefined"!=typeof Promise&&e instanceof Promise)return!0;if("undefined"!=typeof window&&"function"==typeof window.Window&&e instanceof window.Window)return!1;if("undefined"!=typeof window&&"function"==typeof window.constructor&&e instanceof window.constructor)return!1;var n={}.toString;if(n){var t=n.call(e);if("[object Window]"===t||"[object global]"===t||"[object DOMWindow]"===t)return!1}if("function"==typeof e.then)return!0}catch(e){return!1}return!1}var ae,ce=[],ue=[],se=0;function le(){if(!se&&ae){var e=ae;ae=null,e.resolve()}}function de(){se+=1}function fe(){se-=1,le()}var pe=function(){function e(e){var n=this;if(this.resolved=void 0,this.rejected=void 0,this.errorHandled=void 0,this.value=void 0,this.error=void 0,this.handlers=void 0,this.dispatching=void 0,this.stack=void 0,this.resolved=!1,this.rejected=!1,this.errorHandled=!1,this.handlers=[],e){var t,r,o=!1,i=!1,a=!1;de();try{e((function(e){a?n.resolve(e):(o=!0,t=e)}),(function(e){a?n.reject(e):(i=!0,r=e)}))}catch(e){return fe(),void this.reject(e)}fe(),a=!0,o?this.resolve(t):i&&this.reject(r)}}var n=e.prototype;return n.resolve=function(e){if(this.resolved||this.rejected)return this;if(ie(e))throw new Error("Can not resolve promise with another promise");return this.resolved=!0,this.value=e,this.dispatch(),this},n.reject=function(e){var n=this;if(this.resolved||this.rejected)return this;if(ie(e))throw new Error("Can not reject promise with another promise");if(!e){var t=e&&"function"==typeof e.toString?e.toString():{}.toString.call(e);e=new Error("Expected reject to be called with Error, got "+t)}return this.rejected=!0,this.error=e,this.errorHandled||setTimeout((function(){n.errorHandled||function(e,n){if(-1===ce.indexOf(e)){ce.push(e),setTimeout((function(){throw e}),1);for(var t=0;t>>0)+"__",function(){if("undefined"==typeof WeakMap)return!1;if(void 0===Object.freeze)return!1;try{var e=new WeakMap,n={};return Object.freeze(n),e.set(n,"__testvalue__"),"__testvalue__"===e.get(n)}catch(e){return!1}}())try{this.weakmap=new WeakMap}catch(e){}this.keys=[],this.values=[]}var n=e.prototype;return n._cleanupClosedWindows=function(){for(var e=this.weakmap,n=this.keys,t=0;t=3)return"stringifyError stack overflow";try{if(!e)return"";if("string"==typeof e)return e;if(e instanceof Error){var t=e&&e.stack,r=e&&e.message;if(t&&r)return-1!==t.indexOf(r)?t:r+"\n"+t;if(t)return t;if(r)return r}return e&&e.toString&&"function"==typeof e.toString?e.toString():{}.toString.call(e)}catch(e){return"Error while stringifying error: "+Ge(e,n+1)}}function Xe(e){return"data:image/svg+xml;base64,"+qe(e)}function Ye(e,n){void 0===n&&(n=Boolean);var t={};for(var r in e)e.hasOwnProperty(r)&&n(e[r],r)&&(t[r]=e[r]);return t}function Je(e){return[].slice.call(e)}ze.clear=function(){Ve=Ue},ze((function(e){if(Object.values)return Object.values(e);var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(e[t]);return n}));var Qe=function(e){function n(n){var t;return(t=e.call(this,n)||this).name=t.constructor.name,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t),t.constructor):t.stack=new Error(n).stack,t}return ye(n,e),n}(Pe(Error));function Ke(){return Boolean(document.body)&&"complete"===document.readyState}function en(){return Boolean(document.body)&&"interactive"===document.readyState}var nn=ze((function(){return new pe((function(e){if(Ke()||en())return e();var n=setInterval((function(){if(Ke()||en())return clearInterval(n),e()}),10)}))}));function tn(){return Ze(tn,(function(){var e=window.performance;if(e&&e.now&&e.timing&&e.timing.connectEnd&&e.timing.navigationStart&&Math.abs(e.now()-Date.now())>1e3&&e.now()-(e.timing.connectEnd-e.timing.navigationStart)>0)return e}))}function rn(){return"undefined"!=typeof window&&void 0!==window.location}var on=function(e){function n(){return e.apply(this,arguments)||this}return ye(n,e),n}(Qe),an="undefined"!=typeof document?document.currentScript:null,cn=ze((function(){if(an)return an;if(an=function(){try{var e=function(){try{throw new Error("_")}catch(e){return e.stack||""}}(),n=/.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(e),t=n&&n[1];if(!t)return;for(var r=0,o=[].slice.call(document.getElementsByTagName("script")).reverse();rpn.indexOf(i))){var r=[n];r.push(t),(t.error||t.warning)&&r.push("\n\n",t.error||t.warning);try{window.console[e]&&window.console[e].apply?window.console[e].apply(window.console,r):window.console.log&&window.console.log.apply&&window.console.log.apply(window.console,r)}catch(e){}}}function g(){return pe.try((function(){if(rn()&&"file:"!==window.location.protocol&&(f.length||p.length||h.length)){for(var e={},t=0;t1?new Fn(n):void 0}(this.component(this.props,this.children));if(n)return n.render(e)},n.render=function(e){return e(this)},n.renderChildren=function(e){return gn(this.children,e)},e}();function kn(e){for(var n=[],t=0;t2?t-2:0),o=2;o=0||(o[t]=e[t]);return o}var In,qn={br:!0};function Rn(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function Bn(e){return Sn("div",{class:"preloader spinner"},Sn("style",{nonce:e.nonce,innerHTML:"\n\n body {\n width: 100%;\n height: 100%;\n overflow: hidden;\n position: fixed;\n top: 0;\n left: 0;\n margin: 0;\n }\n\n .spinner {\n height: 100%;\n width: 100%;\n position: absolute;\n z-index: 10\n }\n\n .spinner .spinWrap {\n width: 200px;\n height: 100px;\n position: absolute;\n top: 50%;\n left: 50%;\n margin-left: -100px;\n margin-top: -50px\n }\n\n .spinner .loader,\n .spinner .spinnerImage {\n height: 100px;\n width: 100px;\n position: absolute;\n top: 0;\n left: 50%;\n opacity: 1;\n filter: alpha(opacity=100)\n }\n\n .spinner .spinnerImage {\n margin: 28px 0 0 -25px;\n background: url(https://www.paypalobjects.com/images/checkout/hermes/icon_ot_spin_lock_skinny.png) no-repeat\n }\n\n .spinner .loader {\n margin: 0 0 0 -55px;\n background-color: transparent;\n animation: rotation .7s infinite linear;\n border-left: 5px solid #cbcbca;\n border-right: 5px solid #cbcbca;\n border-bottom: 5px solid #cbcbca;\n border-top: 5px solid #2380be;\n border-radius: 100%\n }\n\n @keyframes rotation {\n from {\n transform: rotate(0deg)\n }\n to {\n transform: rotate(359deg)\n }\n }\n"}),Sn("div",{class:"spinWrap"},Sn("p",{class:"spinnerImage"}),Sn("p",{class:"loader"})))}function Wn(e,n){var t=e.nonce;return Sn("html",null,Sn("head",null,Sn("title",null,"PayPal"),Sn("meta",{name:"viewport",content:"width=device-width, initial-scale=1"})),Sn("body",null,Sn(Bn,{nonce:t}),n))}function Un(e){var n=e.name,t=e.variables,o=e.headers,i=e.returnErrorObject,a=void 0!==i&&i;return ln({url:"/graphql?"+n,method:"POST",json:{query:e.query,variables:void 0===t?{}:t},headers:r({"x-app-name":"smart-payment-buttons"},void 0===o?{}:o)}).then((function(e){var t=e.status,r=e.body,o=r.errors||[];if(o.length){var i=o[0].message||JSON.stringify(o[0]);if(yn().warn("graphql_"+n+"_error",{err:i}),a)throw o[0];throw vn({name:"pp.app.paypal_sdk.buttons.graphql_"+n+".error.count",dimensions:{}}),new Error(i)}if(200!==t)throw yn().warn("graphql_"+n+"_status_"+t+"_error"),vn({name:"pp.app.paypal_sdk.buttons.graphql_"+n+".error.count",dimensions:{status:t}}),new Error("/graphql returned status "+t+"\n\n"+JSON.stringify(r));return vn({name:"pp.app.paypal_sdk.buttons.graphql_"+n+".success.count",dimensions:{}}),r.data}))}ze((function(e){var n;return Un({name:"GetCheckoutDetails",query:"\n query GetCheckoutDetails($orderID: String!) {\n checkoutSession(token: $orderID) {\n cart {\n billingType\n intent\n paymentId\n billingToken\n amounts {\n total {\n currencyValue\n currencyCode\n currencyFormatSymbolISOCurrency\n }\n }\n supplementary {\n initiationIntent\n }\n category\n }\n flags {\n isChangeShippingAddressAllowed\n }\n payees {\n merchantId\n email {\n stringValue\n }\n }\n }\n }\n ",variables:{orderID:e},headers:(n={},n["paypal-client-context"]=e,n)})})),ze((function(e){return pe.try((function(){if(!window.firebase||!window.firebase.auth||!window.firebase.database)return wn("https://www.paypalobjects.com/checkout/js/lib/firebase-app.js").then((function(){return pe.all([wn("https://www.paypalobjects.com/checkout/js/lib/firebase-auth.js"),wn("https://www.paypalobjects.com/checkout/js/lib/firebase-database.js")])}))})).then((function(){var n=window.firebase;if(!n)throw new Error("Firebase failed to load");return n.initializeApp(e),n}))}));var Vn=((In={}).local="https://www.msmaster.qa.paypal.com/en_US/m/fb-raw.js",In.stage="https://stage2mb044.qa.paypal.com/fraudnetjsnodeweb/automate/develop/stage_raw.js",In.sandbox="https://c.paypal.com/da/r/fb.js",In.production="https://c.paypal.com/da/r/fb.js",In.test="https://c.paypal.com/da/r/fb.js",In);ze((function(e){var n=e.env,t=e.clientMetadataID,r=e.cspNonce,o=e.timeout,i=void 0===o?1e3:o,a=e.queryStringParams,c=void 0===a?{}:a;return new pe((function(e){var o={f:t,s:"SMART_PAYMENT_BUTTONS",u:window.xprops.buttonLocation,cb1:"fnCallback"};"sandbox"===n&&(o.sandbox=!0);var a=document.createElement("script");a.setAttribute("nonce",r||""),a.setAttribute("type","application/json"),a.setAttribute("id","fconfig"),a.setAttribute("fncls","fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"),a.textContent=JSON.stringify(o);var u=document.createElement("script"),s=Object.keys(c).map((function(e){return e+"="+encodeURIComponent(String(c[e]))})).join("&"),l=s.length?Vn[n]+"?"+s:Vn[n];u.setAttribute("nonce",r||""),u.setAttribute("src",l),u.addEventListener("error",(function(){return e()})),window.fnCallback=e,setTimeout(e,i);var d=mn();d.appendChild(a),d.appendChild(u)}))})),ze((function(e){var n=e.clientID,t=e.merchantID,r=e.currency,o=e.amount,i=void 0===o?"0":o,a=e.clientMetadataID,c=e.userIDToken,u=e.vetted,s=void 0===u||u,l=e.paymentMethodToken,d=e.branded,f=e.allowBillingPayments,p=void 0===f||f,h=e.headers,_=void 0===h?{}:h;return a&&(_["paypal-client-metadata-id"]=String(a)),Un({name:"GetSmartWallet",query:"\n query GetSmartWallet(\n $clientID: String!\n $merchantID: [String!]\n $currency: String\n $amount: String\n $userIDToken: String\n $vetted: Boolean\n $paymentMethodToken: String\n $branded: Boolean,\n $allowBillingPayments: Boolean\n ) {\n smartWallet(\n clientId: $clientID\n merchantId: $merchantID\n currency: $currency\n amount: $amount\n userIdToken: $userIDToken\n vetted: $vetted\n paymentMethodNonce: $paymentMethodToken\n branded: $branded,\n allowBillingPayments: $allowBillingPayments\n ) {\n paypal {\n instruments {\n type\n label\n logoUrl\n instrumentID\n tokenID\n vendor\n oneClick\n accessToken\n }\n }\n credit {\n instruments {\n type\n label\n logoUrl\n instrumentID\n tokenID\n vendor\n oneClick\n accessToken\n }\n }\n card {\n instruments {\n type\n label\n logoUrl\n instrumentID\n tokenID\n vendor\n oneClick\n }\n }\n venmo {\n instruments {\n type\n label\n logoUrl\n instrumentID\n tokenID\n oneClick\n }\n }\n }\n }\n ",variables:{clientID:n,merchantID:t,currency:r,amount:i,userIDToken:c,vetted:s,paymentMethodToken:l,branded:d,allowBillingPayments:p},headers:_}).then((function(e){return e.smartWallet}))}));var zn,Zn,$n,Gn,Xn,Yn,Jn,Qn,Kn,et,nt,tt,rt,ot=t(0),it=["svg","cdnUrl"],at=["render","name","logoColor"];function ct(e){var n=e.svg,t=e.cdnUrl,o=An(e,it);if(t){var i=r({src:t},o);return Sn("img",i)}if(!n)throw new TypeError("Expected svg prop");if("string"!=typeof(n=n.render((function e(n){if("component"===n.type)return[].concat(n.renderComponent(e)).join("");if("element"===n.type){var t=(o=n.props,(i=Object.keys(o).filter((function(e){var n=o[e];return"innerHTML"!==e&&("string"==typeof n||"number"==typeof n||!0===n)}))).length?" "+i.map((function(e){var n=o[e];if(!0===n)return""+Rn(e);if("string"!=typeof n&&"number"!=typeof n)throw new TypeError("Unexpected prop type: "+typeof n);return""===n?Rn(e):Rn(e)+'="'+Rn(n.toString())+'"'})).join(" "):"");if(qn[n.name])return"<"+n.name+t+" />";var r="string"==typeof n.props.innerHTML?n.props.innerHTML:n.renderChildren(e).join("");return"<"+n.name+t+">"+r+""}var o,i;if("text"===n.type)return Rn(n.text);throw new TypeError("Unhandleable node: "+n.type)}))))throw new TypeError("Expected svg prop to be a string or jsx node");var a=r({src:Xe(n)},o);return Sn("img",a)}function ut(e){var n=e.render,t=e.name,o=e.logoColor,i=An(e,at);return Sn(ct,r({},i,{svg:n?n():null,alt:"",class:"paypal-logo paypal-logo-"+t+" "+(o?"paypal-logo-color-"+o:"")}))}(zn={}).default={primary:"#ffffff",secondary:"#ffffff"},zn.white={primary:"#ffffff",secondary:"#ffffff"},zn.black={primary:"#000000",secondary:"#000000"},(Zn={}).default={primary:"#FFFFFF",secondary:"#FFFFFF",tertiary:"#FFFFFF",quaternary:"#FFFFFF"},Zn.white={primary:"#FFFFFF",secondary:"#FFFFFF",tertiary:"#FFFFFF",quaternary:"#FFFFFF"},Zn.black={primary:"#1E3764",secondary:"#005AB9",tertiary:"#FBA900",quaternary:"#FFD800"},($n={}).default={primary:"#333030"},$n.white={primary:"#ffffff"},$n.black={primary:"#333030"},(Gn={}).default={primary:"#003087"},Gn.blue={primary:"#003087"},Gn.white={primary:"#ffffff"},Gn.black={primary:"#333030"},(Xn={}).default={primary:"#FFFFFF",secondary:"#FFFFFF"},Xn.white={primary:"#FFFFFF",secondary:"#FFFFFF"},Xn.black={primary:"#C8036F",secondary:"#71706F"},(Yn={}).default={primary:"#FFFFFF",secondary:"#003A7D",tertiary:"#ED1C24",quaternary:"#FFFFFF",quinary:"#FFFFFF"},Yn.white={primary:"#000000",secondary:"#FFFFFF",tertiary:"#FFFFFF",quaternary:"#000000",quinary:"#FFFFFF"},Yn.black={primary:"#FFFFFF",secondary:"#003A7D",tertiary:"#ED1C24",quaternary:"#FFFFFF",quinary:"#003A7D"},(Jn={}).default={primary:"#FFFFFF",secondary:"#CC0066"},Jn.white={primary:"#FFFFFF",secondary:"#CC0066"},Jn.black={primary:"#FFFFFF",secondary:"#CC0066"},(Qn={}).default={primary:"#00C0EE",secondary:"#FFFFFF"},Qn.white={primary:"#FFFFFF",secondary:"#FFFFFF"},Qn.black={primary:"#00C0EE",secondary:"#1A4B67"},(Kn={}).default={primary:"#FFFFFF",secondary:"#FFFFFF"},Kn.white={primary:"#FFFFFF",secondary:"#FFFFFF"},Kn.black={primary:"#B3B1B1",secondary:"#D03238"},(et={}).default={primary:"#003087",secondary:"#009cde"},et.blue={primary:"#003087",secondary:"#009cde"},et.white={primary:"#ffffff",secondary:"#ffffff"},et.black={primary:"#333030",secondary:"#636363"},et.monochrome={primary:"#000000",secondary:"#000000"},(nt={}).default={primary:"#009cde",secondary:"#012169",tertiary:"#003087"},nt.blue={primary:"#009cde",secondary:"#012169",tertiary:"#003087"},nt.white={primary:"#ffffff",primaryOpacity:"0.7",secondary:"#ffffff",secondaryOpacity:"0.7",tertiary:"#ffffff"},nt.black={primary:"#808080",secondary:"#000000",tertiary:"#1a1a1a"},(tt={}).default={main:"#005DA0",card:"#AEB1BC"},tt.white={main:"#FFFFFF",card:"#FFFFFF"},tt.black={main:"#333030",card:"#333030"},(rt={}).default={primary:"#EDEDED",secondary:"#393A41"},rt.white={primary:"#FFFFFF",secondary:"#000000"},rt.black={primary:"#393A41",secondary:"#EDEDED"};var st,lt,dt,ft,pt,ht,_t,yt,vt,mt,wt,gt,bt=["logoColor"],Ft=((st={}).default={primary:"#3D93CE"},st.blue={primary:"#3D93CE"},st.white={primary:"#ffffff"},st.black={primary:"#333030"},st);function xt(e){var n=e.resetFunc;return v("div",{id:"error-view"},v("div",{className:"error-message"},e.message||"An issue has occurred"),v("button",{className:"reset-button",type:"button",onClick:n},"Try scanning again"))}function Ct(e){return v("img",{id:"qr-code",src:"data:image/svg+xml;base64,"+btoa(e.svgString),alt:"QR Code"})}function kt(){return(e={logoColor:"default"},t=e.logoColor,o=void 0===t?"default":t,i=An(e,bt),n=function(e,n,t){var r;if(t&&(r=n[t]),r||(r=n.default),!r)throw new Error("No "+(t||"default")+" logo available for venmo");return r}(0,Ft,o),a=Sn("svg",{width:"101",height:"32",viewBox:"0 0 101 32",xmlns:"http://www.w3.org/2000/svg",preserveAspectRatio:"xMinYMin meet"},Sn("g",{id:"Page-1",stroke:"none","stroke-width":"1",fill:"none","fill-rule":"evenodd"},Sn("g",{id:"Blue",fill:n.primary},Sn("g",{id:"Logo",transform:"translate(0.000000, 6.000000)"},Sn("path",{d:"M16.6660484,0.18 C17.3466626,1.3390991 17.6535069,2.53297297 17.6535069,4.04108108 C17.6535069,8.85117117 13.671346,15.0998198 10.439346,19.4875676 L3.05725952,19.4875676 L0.0966314879,1.23315315 L6.56045675,0.60036036 L8.12578201,13.5895495 C9.58835986,11.1326126 11.3932543,7.27153153 11.3932543,4.6390991 C11.3932543,3.1981982 11.1538599,2.21675676 10.7797405,1.40864865 L16.6660484,0.18 Z M24.9071592,11.6938739 C24.9071592,13.8367568 26.062718,14.6774775 27.5946678,14.6774775 C29.2629152,14.6774775 30.860218,14.2571171 32.9363097,13.1691892 L32.154346,18.6445045 C30.6915934,19.3814414 28.4119291,19.8731532 26.1991903,19.8731532 C20.5863512,19.8731532 18.5775346,16.3632432 18.5775346,11.9753153 C18.5775346,6.28810811 21.8451817,0.249369369 28.5819516,0.249369369 C32.2909931,0.249369369 34.3649879,2.39207207 34.3649879,5.37567568 C34.3653374,10.1855856 28.3783789,11.6590991 24.9071592,11.6938739 Z M25.0434567,8.2181982 C26.2329152,8.2181982 29.2274429,7.65711712 29.2274429,5.90216216 C29.2274429,5.05945946 28.6495761,4.6390991 27.9686125,4.6390991 C26.7772318,4.6390991 25.2138287,6.11225225 25.0434567,8.2181982 Z M53.0187093,4.4636036 C53.0187093,5.16558559 52.9154377,6.18378378 52.8126903,6.84918919 L50.8730709,19.4873874 L44.5790934,19.4873874 L46.3483408,7.90216216 C46.381891,7.58792793 46.4849879,6.95531532 46.4849879,6.60432432 C46.4849879,5.76162162 45.9743962,5.55135135 45.3605329,5.55135135 C44.5451938,5.55135135 43.7279325,5.93711712 43.1836159,6.21873874 L41.1768962,19.4875676 L34.8474464,19.4875676 L37.7390519,0.565945946 L43.2171661,0.565945946 L43.2865381,2.07621622 C44.5789187,1.19873874 46.2807163,0.24972973 48.6952803,0.24972973 C51.8942543,0.249369369 53.0187093,1.93495495 53.0187093,4.4636036 Z M71.7037093,2.32072072 C73.5063322,0.988108108 75.2084792,0.249369369 77.5554187,0.249369369 C80.7872439,0.249369369 81.9113495,1.93495495 81.9113495,4.4636036 C81.9113495,5.16558559 81.8084273,6.18378378 81.7056799,6.84918919 L79.7683322,19.4873874 L73.4726073,19.4873874 L75.2755796,7.6572973 C75.3087803,7.34108108 75.3785017,6.95531532 75.3785017,6.71063063 C75.3785017,5.7618018 74.8677353,5.55135135 74.2540467,5.55135135 C73.4722578,5.55135135 72.6908183,5.90234234 72.1106799,6.21873874 L70.1043097,19.4875676 L63.8101574,19.4875676 L65.6131298,7.65747748 C65.6463304,7.34126126 65.713955,6.9554955 65.713955,6.71081081 C65.713955,5.76198198 65.2030138,5.55153153 64.5914221,5.55153153 C63.7743356,5.55153153 62.9588218,5.9372973 62.4145052,6.21891892 L60.4062128,19.4877477 L54.0788599,19.4877477 L56.9701159,0.566126126 L62.3813045,0.566126126 L62.551327,2.14576577 C63.8101574,1.1990991 65.5105571,0.25009009 67.7900467,0.25009009 C69.7637405,0.249369369 71.0559464,1.12702703 71.7037093,2.32072072 Z M83.55059,11.7998198 C83.55059,5.83279279 86.6120433,0.249369369 93.6558322,0.249369369 C98.9633997,0.249369369 100.903543,3.47981982 100.903543,7.93873874 C100.903543,13.8365766 97.8751159,19.9443243 90.6614792,19.9443243 C85.3196626,19.9443243 83.55059,16.3281081 83.55059,11.7998198 Z M94.4374464,7.83279279 C94.4374464,6.28810811 94.0628028,5.23495495 92.9409689,5.23495495 C90.4570329,5.23495495 89.9469654,9.76306306 89.9469654,12.0794595 C89.9469654,13.8367568 90.4238322,14.9243243 91.5453166,14.9243243 C93.8931298,14.9243243 94.4374464,10.149009 94.4374464,7.83279279 Z"}))))),Sn(ut,r({},i,{name:"venmo",logoColor:o,render:function(){return a}}))).render(Object(ot.preact)({Preact:{h:v}}));var e,n,t,o,i,a}function Et(e){var n=e.stylingClass;return v("svg",{className:void 0===n?"instruction-icon":n,width:"68",height:"47",viewBox:"0 0 68 47",fill:"none",xmlns:"http://www.w3.org/2000/svg"},v("rect",{x:"11.5",y:"6.90039",width:"20.7",height:"29.9",fill:"white"}),v("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M30.82 2.2998H12.88C10.8475 2.2998 9.19995 3.98283 9.19995 6.05894V42.2407C9.19995 44.3168 10.8475 45.9998 12.88 45.9998H30.82C32.8524 45.9998 34.5 44.3168 34.5 42.2407V6.05894C34.5 3.98283 32.8524 2.2998 30.82 2.2998ZM21.8499 42.6635C20.8337 42.6635 20.0099 41.822 20.0099 40.784C20.0099 39.7459 20.8337 38.9044 21.8499 38.9044C22.8661 38.9044 23.6899 39.7459 23.6899 40.784C23.6899 41.822 22.8661 42.6635 21.8499 42.6635ZM11.9599 36.414H31.7399V7.32767H11.9599V36.414Z",fill:"#888C94"}),v("path",{d:"M25.7367 12.4121C26.107 13.0217 26.274 13.6495 26.274 14.4425C26.274 16.9719 24.1071 20.2578 22.3483 22.5651H18.3314L16.7205 12.966L20.2378 12.6333L21.0894 19.4636C21.8853 18.1716 22.8674 16.1412 22.8674 14.757C22.8674 13.9992 22.7371 13.4832 22.5335 13.0582L25.7367 12.4121Z",fill:"#008CFF"}),v("circle",{cx:"14.5",cy:"33.5",r:"1.25",fill:"white",stroke:"#0074DE","stroke-width":"0.5"}),v("circle",{cx:"18.5",cy:"33.5",r:"1.25",fill:"white",stroke:"#0074DE","stroke-width":"0.5"}),v("rect",{x:"21",y:"32",width:"9",height:"3",rx:"1.5",fill:"#0074DE"}),v("circle",{cx:"49",cy:"26",r:"18",fill:"white",stroke:"#2F3033","stroke-width":"2"}),v("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M56.7188 16.5H51.9688C50.985 16.5 50.1875 17.2975 50.1875 18.2812V23.0312C50.1875 24.015 50.985 24.8125 51.9688 24.8125H56.7188C57.7025 24.8125 58.5 24.015 58.5 23.0312V18.2812C58.5 17.2975 57.7025 16.5 56.7188 16.5ZM51.375 18.2812C51.375 17.9533 51.6408 17.6875 51.9688 17.6875H56.7188C57.0467 17.6875 57.3125 17.9533 57.3125 18.2812V23.0312C57.3125 23.3592 57.0467 23.625 56.7188 23.625H51.9688C51.6408 23.625 51.375 23.3592 51.375 23.0312V18.2812ZM41.875 19.5083C41.875 19.1585 42.1585 18.875 42.5083 18.875H44.8042C45.154 18.875 45.4375 19.1585 45.4375 19.5083V21.8042C45.4375 22.154 45.154 22.4375 44.8042 22.4375H42.5083C42.1585 22.4375 41.875 22.154 41.875 21.8042V19.5083ZM52.5625 19.5083C52.5625 19.1585 52.846 18.875 53.1958 18.875H55.4917C55.8415 18.875 56.125 19.1585 56.125 19.5083V21.8042C56.125 22.154 55.8415 22.4375 55.4917 22.4375H53.1958C52.846 22.4375 52.5625 22.154 52.5625 21.8042V19.5083ZM50.8208 27.1875C50.471 27.1875 50.1875 27.471 50.1875 27.8208V28.9292C50.1875 29.279 50.471 29.5625 50.8208 29.5625H51.9292C52.279 29.5625 52.5625 29.279 52.5625 28.9292V27.8208C52.5625 27.471 52.279 27.1875 51.9292 27.1875H50.8208ZM50.1875 33.7583C50.1875 33.4085 50.471 33.125 50.8208 33.125H51.9292C52.279 33.125 52.5625 33.4085 52.5625 33.7583V34.8667C52.5625 35.2165 52.279 35.5 51.9292 35.5H50.8208C50.471 35.5 50.1875 35.2165 50.1875 34.8667V33.7583ZM56.7583 27.1875C56.4085 27.1875 56.125 27.471 56.125 27.8208V28.9292C56.125 29.279 56.4085 29.5625 56.7583 29.5625H57.8667C58.2165 29.5625 58.5 29.279 58.5 28.9292V27.8208C58.5 27.471 58.2165 27.1875 57.8667 27.1875H56.7583ZM56.125 33.7583C56.125 33.4085 56.4085 33.125 56.7583 33.125H57.8667C58.2165 33.125 58.5 33.4085 58.5 33.7583V34.8667C58.5 35.2165 58.2165 35.5 57.8667 35.5H56.7583C56.4085 35.5 56.125 35.2165 56.125 34.8667V33.7583ZM53.7895 30.1562C53.4398 30.1562 53.1562 30.4398 53.1562 30.7895V31.898C53.1562 32.2477 53.4398 32.5312 53.7895 32.5312H54.898C55.2477 32.5312 55.5312 32.2477 55.5312 31.898V30.7895C55.5312 30.4398 55.2477 30.1562 54.898 30.1562H53.7895ZM41.875 30.1958C41.875 29.846 42.1585 29.5625 42.5083 29.5625H44.8042C45.154 29.5625 45.4375 29.846 45.4375 30.1958V32.4917C45.4375 32.8415 45.154 33.125 44.8042 33.125H42.5083C42.1585 33.125 41.875 32.8415 41.875 32.4917V30.1958ZM41.2812 27.1875H46.0312C47.015 27.1875 47.8125 27.985 47.8125 28.9688V33.7188C47.8125 34.7025 47.015 35.5 46.0312 35.5H41.2812C40.2975 35.5 39.5 34.7025 39.5 33.7188V28.9688C39.5 27.985 40.2975 27.1875 41.2812 27.1875ZM41.2812 28.375C40.9533 28.375 40.6875 28.6408 40.6875 28.9688V33.7188C40.6875 34.0467 40.9533 34.3125 41.2812 34.3125H46.0312C46.3592 34.3125 46.625 34.0467 46.625 33.7188V28.9688C46.625 28.6408 46.3592 28.375 46.0312 28.375H41.2812ZM41.2812 16.5H46.0312C47.015 16.5 47.8125 17.2975 47.8125 18.2812V23.0312C47.8125 24.015 47.015 24.8125 46.0312 24.8125H41.2812C40.2975 24.8125 39.5 24.015 39.5 23.0312V18.2812C39.5 17.2975 40.2975 16.5 41.2812 16.5ZM41.2812 17.6875C40.9533 17.6875 40.6875 17.9533 40.6875 18.2812V23.0312C40.6875 23.3592 40.9533 23.625 41.2812 23.625H46.0312C46.3592 23.625 46.625 23.3592 46.625 23.0312V18.2812C46.625 17.9533 46.3592 17.6875 46.0312 17.6875H41.2812Z",fill:"#008CFF"}),v("path",{d:"M36 13.0004L15 33",stroke:"#2F3033"}),v("path",{d:"M43.4999 43.4991L14.4999 32.9995",stroke:"#2F3033"}))}function Tt(){return v("svg",{id:"venmo-mark",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48"},v("path",{d:"M42.3 2L28.5 4.8c.8 1.9 1.4 4.1 1.4 7.4 0 6-4.2 14.8-7.7 20.4L18.5 3 3.3 4.5l7 41.5h17.4c7.7-10 17-24.3 17-35.2 0-3.4-.8-6.1-2.4-8.8z",fill:"#fff"}))}function Mt(){return v("svg",{id:"success-mark",width:"59",height:"59",viewBox:"0 0 59 59",fill:"none",xmlns:"http://www.w3.org/2000/svg"},v("rect",{x:"1",y:"1",width:"57",height:"57",rx:"28.5",fill:"#148572",stroke:"#888C94"}),v("g",{"clip-path":"url(#clip0)"},v("path",{d:"M24.0068 40.8397C22.921 39.7538 22.921 37.9933 24.0068 36.9075L39.2933 21.621C40.3791 20.5352 42.1396 20.5352 43.2255 21.621C44.3113 22.7069 44.3113 24.4674 43.2255 25.5532L27.939 40.8397C26.8532 41.9255 25.0927 41.9255 24.0068 40.8397Z",fill:"white"}),v("path",{d:"M27.9763 40.8397C26.8905 41.9255 25.13 41.9255 24.0441 40.8397L17.1628 33.9583C16.0769 32.8725 16.0769 31.112 17.1628 30.0261C18.2486 28.9403 20.0091 28.9403 21.095 30.0261L27.9763 36.9075C29.0622 37.9933 29.0622 39.7538 27.9763 40.8397Z",fill:"white"})),v("defs",null,v("clipPath",{id:"clip0"},v("rect",{width:"27.8049",height:"27.8049",fill:"white",transform:"translate(16.2927 16.293)"}))))}(lt={}).default={primary:"#ffffff"},lt.blue={primary:"#003087"},lt.white={primary:"#ffffff"},lt.black={primary:"#333030"},(dt={}).default={primary:"#1AAD19",secondary:"#FFFFFF"},dt.white={primary:"#FFFFFF",secondary:"#FFFFFF"},dt.black={primary:"#1AAD19",secondary:"#4D4D4D"},(ft={}).default={primary:"#A6C307"},ft.white={primary:"#FFFFFF"},ft.black={primary:"#2C2E2F"},(pt={}).default={primary:"#FF0000",secondary:"#E83E49",tertiary:"#FF00FF",quaternary:"#000000",senary:"#FFFFFF"},pt.white={primary:"#000000",secondary:"#000000",tertiary:"#000000",quaternary:"#000000",senary:"#FFFFFF"},pt.black={primary:"#FF0000",secondary:"#E83E49",tertiary:"#FF00FF",quaternary:"#4D4D4F",senary:"#FFFFFF"},(ht={}).default={primary:"#0EE06E"},ht.white={primary:"#FFFFFF"},ht.black={primary:"#000000"},(_t={}).default={primary:"#FFFFFF",secondary:"#FFFFFF"},_t.white={primary:"#FFFFFF",secondary:"#FFFFFF"},_t.black={primary:"#E39E39",secondary:"#D8232A"},(yt={}).default={primary:"#FFFFFF"},yt.white={primary:"#FFFFFF"},yt.black={primary:"#000000"},(vt={}).default={primary:"#009EE3",secondary:"#FFFFFF",tertiary:"#009EE3",quaternary:"#FFFFFF"},vt.white={primary:"#000000",secondary:"#FFFFFF",tertiary:"#000000",quaternary:"#FFFFFF"},vt.black={primary:"#FFFFFF",secondary:"#2D3277",tertiary:"#009EE3",quaternary:"#009EE3"},(mt={}).default={primary:"#FFFFFF",secondary:"#FFFFFF"},mt.white={primary:"#FFFFFF",secondary:"#FFFFFF"},mt.black={primary:"#1866AB",secondary:"#373535"},(wt={}).default={primary:"#FFFFFF"},wt.white={primary:"#FFFFFF"},wt.black={primary:"#2C2E2F"},(gt={}).default={primary:"#FFFFFF",secondary:"#FFFFFF",tertiary:"#FFFFFF"},gt.white={primary:"#FFFFFF",secondary:"#FFFFFF",tertiary:"#FFFFFF"},gt.black={primary:"#A6009C",secondary:"#FF009C",tertiary:"#1C1C1C"};var St=new Map([["qr_default","qr_scanned"],["qr_error","qr_default"],["qr_authorized","qr_error"],["qr_scanned","qr_authorized"]]);function jt(){var e=window.xprops,n=e.env,t=e.sessionID,r=e.buttonSessionID,o=e.sdkCorrelationID,i=e.clientID,a=e.fundingSource,c=void 0===a?"venmo":a,u=e.locale,s=e.orderID,l=(0,e.getParent)(),d=function(){if(!window.paypal)throw new Error("paypal not found");return window.paypal}().version,f=u.country,p=yn();return p.configure({transport:l&&_n(l)}),function(e){var n=e.env,t=e.sessionID,r=e.clientID,o=e.sdkCorrelationID,i=e.buyerCountry,a=e.locale,c=e.sdkVersion,u=void 0===c?window.paypal.version:c,s=yn();s.addPayloadBuilder((function(){return{referer:window.location.host,sdkCorrelationID:o,sessionID:t,clientID:r,env:n}})),s.addTrackingBuilder((function(){var e,n;return(e={}).feed_name="payments_sdk",e.serverside_data_source="checkout",e.client_id=r,e.page_session_id=t,e.referer_url=window.location.host,e.buyer_cntry=i,e.locale=a.lang+"_"+a.country,e.integration_identifier=r,e.sdk_environment=(void 0===n&&(n=he()),/iPhone|iPod|iPad/.test(n)?"iOS":function(e){return void 0===e&&(e=he()),/Android/.test(e)}()?"android":null),e.sdk_name="payments_sdk",e.sdk_version=u,e.user_agent=window.navigator&&window.navigator.userAgent,e.context_correlation_id=o,e.t=Date.now().toString(),e})),pe.onPossiblyUnhandledException((function(e){var n;s.track(((n={}).ext_error_code="payments_sdk_error",n.ext_error_desc=function(e){var n="";return e?e instanceof Error?e.message||n:"string"==typeof e.message&&e.message||n:n}(e),n)),s.error("unhandled_error",{err:Ge(e)}),vn({event:"error",name:"pp.app.paypal_sdk.buttons.unhandled_exception.count",dimensions:{errorType:"payments_sdk_error"}}),s.flush().catch($e)}))}({env:n,sessionID:t,clientID:i,sdkCorrelationID:o,locale:u,sdkVersion:d,buyerCountry:f}),p.addPayloadBuilder((function(){return{buttonSessionID:r}})),p.addTrackingBuilder((function(){var e;return(e={}).state_name="smart_button",e.context_type="EC-Token",e.context_id=s,e.button_session_id=r,e.button_version="5.0.164",e.selected_payment_method=c,e})),function(){if(window.document.documentMode)try{var e=window.status;return window.status="testIntranetMode","testIntranetMode"===window.status&&(window.status=e,!0)}catch(e){return!1}return!1}()&&p.warn("button_child_intranet_mode"),pe.hash({pageRenderTime:nn().then((function(){var e=tn();if(e){var n=e.timing;return n.connectEnd&&n.domInteractive?n.domInteractive-n.connectEnd:void 0}}))}).then((function(e){var n,t=e.pageRenderTime;p.track(((n={}).transition_name="qr_load",n.merchant_selected_funding_source=c,n.page_load_time=t?t.toString():"",n)),p.flush()})),p}var Lt,Ot=v("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},v("rect",{x:"0.25",y:"0.25",width:"39.5",height:"39.5",rx:"19.75",stroke:"#888C94","stroke-width":"0.5"})),Dt=v("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},v("circle",{cx:"20",cy:"20",r:"12",fill:"#148572"}),v("rect",{x:"0.25",y:"0.25",width:"39.5",height:"39.5",rx:"19.75",stroke:"#148572","stroke-width":"0.5"}));function Nt(e){var n=e.survey,t=e.onCloseClick,r=function(e){e.target.blur(),n.setReason(e.target.value)},o=[{text:"Having trouble scanning the QR code",reason:"having_trouble_scanning_the_qr_code"},{text:"Don’t have the Venmo app on my mobile device",reason:"dont_have_the_venmo_app_on_my_mobile_device"},{text:"I prefer to pay another way",reason:"prefer_to_pay_another_way"},{text:"I prefer not to say",reason:"prefer_not_to_say"}].map((function(e){return v("div",{class:"answer"},v("input",{type:"radio",id:e.reason,value:e.reason,checked:e.reason===n.reason,onChange:r}),v("label",{for:e.reason},e.reason===n.reason?Dt:Ot,e.text))}));return v("div",{id:"survey"},v("h1",null,"We’re sorry to see you leave!"),v("p",{class:"message"},"Please let us know why. Your feedback is important to us."),v("div",{class:"answers"},o),v("button",{type:"button",class:"continue-button",onClick:n.disable},"Continue payment"),v("button",{type:"button",class:"leave-button",onClick:t},"Leave"))}function Ht(e){var n,t,o,a,c,u,s=e.svgString,l=(a=Q(window.xprops),c=a[0],u=a[1],n=function(){return c.onProps((function(e){u(r({},e))}))},t=[],o=J(q++,3),!i.__s&&function(e,n){return!e||e.length!==n.length||n.some((function(n,t){return n!==e[t]}))}(o.__H,t)&&(o.__=n,o.i=t,R.__H.__h.push(o)),r({},c,{setState:function(e){u(r({},c,{state:e}))}})),d=l.state,f=l.errorText,p=l.setState,h=l.close,_=l.onCancel,y=function(){var e=Q({isEnabled:!1,reason:"prefer_not_to_say"}),n=e[0],t=e[1];return r({},n,{enable:function(){return t(r({},n,{isEnabled:!0}))},disable:function(){return t(r({},n,{isEnabled:!1}))},setReason:function(e){return t(r({},n,{reason:e}))}})}(),m=function(e){window.xprops.hide();var n=function(e){var n,t=e.closeOnUnload,o=ke(function(e,n){var t=(n=n||{}).closeOnUnload,o=void 0===t?1:t,i=n.name,a=void 0===i?"":i,c=n.width,u=n.height,s=0,l=0;c&&(window.outerWidth?l=Math.round((window.outerWidth-c)/2)+window.screenX:window.screen.width&&(l=Math.round((window.screen.width-c)/2))),u&&(window.outerHeight?s=Math.round((window.outerHeight-u)/2)+window.screenY:window.screen.height&&(s=Math.round((window.screen.height-u)/2))),delete n.closeOnUnload,delete n.name,c&&u&&(n=r({top:s,left:l,width:c,height:u,status:1,toolbar:0,menubar:0,resizable:1,scrollbars:1},n));var d,f,p=Object.keys(n).map((function(e){if(null!=n[e])return e+"="+("string"==typeof(t=n[e])?t:t&&t.toString&&"function"==typeof t.toString?t.toString():{}.toString.call(t));var t})).filter(Boolean).join(",");try{d=window.open("",a,p)}catch(f){throw new on("Can not open popup window - "+(f.stack||f.message))}if(Me(d))throw new on("Can not open popup window - blocked");return o&&window.addEventListener("unload",(function(){return d.close()})),d}(0,{width:e.width,height:e.height,closeOnUnload:void 0===t?1:t})),i=o.document;return function(e,n){var t=n.tagName.toLowerCase();if("html"!==t)throw new Error("Expected element to be html, got "+t);for(var r=e.document.documentElement,o=0,i=Je(r.children);o svg,\n #front-view > img {\n padding: 16px 16px 0px;\n }\n #front-view > img + img {\n padding-top: 12px;\n padding-bottom: 32px;\n }\n #qr-code {\n min-width: 160px;\n min-height: 160px;\n width: calc(100% - 32px);\n max-width: 325px;\n }\n #instructions {\n background-color: #FFFF;\n border-top-left-radius: 8px;\n border-top-right-radius: 8px;\n box-sizing: border-box;\n margin-top: 16px;\n display: flex;\n align-items: center;\n font-size: 14px;\n line-height: 16px;\n max-width: 250px;\n width: 100%;\n }\n .instruction-icon {\n min-width: 68px;\n min-height: 46px;\n margin-right: 16px;\n }\n #fee-disclaimer{\n margin: 0;\n padding-top: 32px;\n padding-left: 16px;\n padding-right: 16px;\n font-size: 20px;\n color: #2F3033;\n }\n #back-view {\n position: absolute;\n transform: rotateY(-180deg);\n background-color: #3D93CE;\n justify-content: center;\n font-size: 18px;\n line-height: 16px;\n text-align: center;\n color: #FFFFFF;\n }\n #back-view .auth-message,\n #back-view .success-message {\n position: absolute;\n bottom: -30px;\n white-space: nowrap;\n transition: opacity 500ms;\n }\n #back-view .mark {\n position: relative ;\n }\n #venmo-mark{\n width: 50%;\n }\n #success-mark {\n position: absolute;\n left: 50%;\n bottom: -10%;\n transition: transform 500ms, opacity 500ms;\n transition-delay: 350ms;\n }\n #close {\n position: absolute;\n right: 16px;\n top: 16px;\n width: 16px;\n height: 16px;\n opacity: 0.6;\n z-index: 10;\n }\n #close:hover {\n opacity: 1;\n }\n #close:before, #close:after {\n position: absolute;\n left: 8px;\n content: \' \';\n height: 20px;\n width: 2px;\n background-color: #FFF;\n }\n #close:before {\n transform: rotate(45deg);\n }\n #close:after {\n transform: rotate(-45deg);\n }\n #survey {\n background: #FFFFFF;\n height: 542px;\n width: 500px;\n border-radius: 8px;\n }\n #survey h1 {\n width: 423px;\n font-weight: 500;\n font-size: 24px;\n line-height: 32px;\n text-align: center;\n margin: auto;\n margin-top: 30px;\n }\n #survey button {\n display: block;\n margin: auto;\n border: none;\n font-family: sans-serif;\n cursor: pointer;\n font-weight: bold;\n }\n #survey button.continue-button {\n margin-top: 40px;\n min-height: 48px;\n width: 335px;\n background: #0074DE;\n height: 24px;\n font-size: 18px;\n line-height: 24px;\n text-align: center;\n color: #FFFFFF;\n border-radius: 24px;\n display: block;\n }\n #survey button.leave-button {\n margin-top: 10px;\n height: 48px;\n width: 335px;\n color: #0074DE;\n background: none;\n font-size: 18px;\n line-height: 24px;\n text-align: center;\n display: block;\n }\n #survey .message {\n width: 333px;\n font-family: sans-serif;\n font-size: 16px;\n line-height: 20px;\n text-align: center;\n margin: auto;\n margin-top: 8px;\n }\n\n #survey .answers {\n width: 400px;\n font-size: 16px;\n line-height: 20px;\n margin: auto;\n cursor: pointer;\n }\n #survey .answers .answer {\n margin-top: 28px;\n display: flex;\n align-items: center;\n }\n #survey label {\n font-family: sans-serif;\n font-size: 16px;\n cursor: pointer;\n display: flex;\n align-items: center;\n }\n #survey .answers svg{\n margin-right: 8px;\n min-width: 40px;\n }\n #survey .answers input{\n display: none;\n }\n #survey .answers input:focus::after {\n content: "";\n min-width: 44px;\n height: 44px;\n position: absolute;\n top: -2px;\n left: -2px;\n border: solid 1px black;\n border-radius: 50%;\n }\n .escape-path {\n background-color: white;\n color: #2F3033;\n width: 100%;\n text-align: center;\n padding: 1rem;\n margin: 0;\n border-bottom-left-radius: 16px;\n border-bottom-right-radius: 16px;\n }\n .escape-path__link {\n font-weight: 600;\n color: #008CFF;\n }\n .escape-path__link:hover {\n cursor: pointer;\n }\n '," "),v("a",{href:"#",id:"close","aria-label":"close",role:"button",onClick:g}),v("div",{id:"view-boxes",className:d},"qr_error"===d?b:C,v("div",{className:"card",id:"back-view"},v("span",{className:"mark"},v(Tt,null),v(Mt,null)),v("div",{className:"auth-message"},"Go to your Venmo app and authorize"),v("div",{className:"success-message"},"Venmo account authorized")),window.xprops.debug&&v("button",{type:"button",style:{position:"absolute",bottom:"8px",padding:"4px",right:"8px"},onClick:function(){return p(St.get(d))}},"Next State")),k)}function Pt(e){var n=e.svgString;Lt=jt(),function(e,n,t){var r,a,c;i.__&&i.__(e,n),r=!1?null:n.__k,a=[],c=[],D(n,e=n.__k=v(w,null,[e]),r||d,d,void 0!==n.ownerSVGElement,r?null:n.firstChild?o.call(n.childNodes):null,a,r?r.__e:n.firstChild,!1,c),N(a,e,c)}(v(Ht,{svgString:n}),mn())}}])})); \ No newline at end of file diff --git a/globals.js b/globals.js index fec723f976..1ebc3edf3e 100644 --- a/globals.js +++ b/globals.js @@ -1,12 +1,12 @@ /* eslint import/no-commonjs: off, flowtype/require-valid-file-annotation: off, flowtype/require-return-type: off */ -import { getNextVersion } from '@krakenjs/grumbler-scripts/config/webpack.config'; +import { getNextVersion } from "@krakenjs/grumbler-scripts/config/webpack.config"; -import pkg from './package.json'; +import pkg from "./package.json"; export const globals = { - __SMART_BUTTONS__: { - __MAJOR_VERSION__: getNextVersion(pkg, 'major').replace(/_/g, '.'), - __MINOR_VERSION__: getNextVersion(pkg, 'patch').replace(/_/g, '.') - } + __SMART_BUTTONS__: { + __MAJOR_VERSION__: getNextVersion(pkg, "major").replace(/_/g, "."), + __MINOR_VERSION__: getNextVersion(pkg, "patch").replace(/_/g, "."), + }, }; diff --git a/index.js b/index.js index b4359c641e..fdc69c6ff6 100644 --- a/index.js +++ b/index.js @@ -2,18 +2,17 @@ /* eslint import/no-unassigned-import: off, import/no-commonjs: off */ // $FlowFixMe -const pkg = require('./package.json'); +const pkg = require("./package.json"); const aliases = pkg.alias || {}; -for (const [ module, alias ] of Object.entries(aliases)) { - const moduleAlias = require('module-alias'); +for (const [module, alias] of Object.entries(aliases)) { + const moduleAlias = require("module-alias"); - if (!alias) { - continue; - } - - // $FlowFixMe - console.info(`Alias: ${ module } -> ${ alias }`); // eslint-disable-line no-console - moduleAlias.addAlias(module, alias); + if (!alias) { + continue; + } + // Alias is interpreted as mixed/any although it is always a string. This comes from Object.entries() not knowing the type the object's value. + console.info(`Alias: ${module} -> ${String(alias)}`); // eslint-disable-line no-console + moduleAlias.addAlias(module, String(alias)); } diff --git a/karma.conf.js b/karma.conf.js index d7eee08c6e..fd591ed2b5 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -3,14 +3,13 @@ import { getKarmaConfig } from "@krakenjs/karma-config-grumbler"; -import { WEBPACK_CONFIG_TEST } from './webpack.config'; +import { WEBPACK_CONFIG_TEST } from "./webpack.config"; -export default function configKarma(karma : Object) { +export default function configKarma(karma: Object) { + const karmaConfig = getKarmaConfig(karma, { + basePath: __dirname, + webpack: WEBPACK_CONFIG_TEST, + }); - const karmaConfig = getKarmaConfig(karma, { - basePath: __dirname, - webpack: WEBPACK_CONFIG_TEST - }); - - karma.set(karmaConfig); + karma.set(karmaConfig); } diff --git a/package.json b/package.json index 79781d3d2e..93c6b70463 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@paypal/smart-payment-buttons", - "version": "5.0.151", + "version": "5.0.164", "publishConfig": { "registry": "https://registry.npmjs.org" }, @@ -35,6 +35,8 @@ "deploy": "npm run cdnify", "flow": "flow", "flow-typed": "rm -rf ./flow-typed && flow-typed install --ignoreDeps peer && flow-typed install jest@24 mocha@4 && flow-typed install express@4.16 && sed -i -e 's/http$IncomingMessage,/http$IncomingMessage<>,/g' ./flow-typed/npm/express_v4.16.x.js", + "format": "prettier --write --ignore-unknown .", + "format:check": "prettier --check .", "karma": "cross-env NODE_ENV=test babel-node --plugins=transform-es2015-modules-commonjs ./node_modules/.bin/karma start", "lint": "eslint --ext .js --ext .jsx src/ test/ *.js", "postactivate": "npm run cdnify -- --commitonly", @@ -47,7 +49,7 @@ "release:dry-run": "DRY_RUN=true grabthar-release", "setup": "npm install && npm run flow-typed", "start": "npm run webpack -- --progress --watch", - "test": "npm run vitest -- run && npm run karma", + "test": "npm run format:check && npm run coverage && npm run karma", "typecheck": "npm run flow-typed && npm run flow -- check", "vitest": "vitest", "webpack": "babel-node --plugins=transform-es2015-modules-commonjs $(npm bin)/webpack", @@ -59,7 +61,7 @@ "alias": {}, "dependencies": { "@krakenjs/beaver-logger": "^5.5.0", - "@krakenjs/belter": "^2.1.0", + "@krakenjs/belter": "^2.3.0", "@krakenjs/cross-domain-utils": "^3.0.0", "@krakenjs/grabthar": "^6.2.0", "@krakenjs/jsx-pragmatic": "^3.0.0", @@ -84,9 +86,11 @@ "@krakenjs/grabthar-release": "^3.0.0", "@krakenjs/grumbler-scripts": "^8.0.4", "@krakenjs/sync-browser-mocks": "^3.0.0", + "@vitest/coverage-v8": "^0.34.3", "@vitest/ui": "^0.25.3", "babel-core": "^7.0.0-bridge.0", "cross-env": "^7.0.3", + "eslint-config-prettier": "^9.0.0", "express": "^4.16.3", "flow-bin": "0.155.0", "flow-typed": "^3.8.0", @@ -94,13 +98,13 @@ "husky": "^8.0.2", "jsdom": "^22.0.0", "lint-staged": "^13.0.4", - "prettier": "^2.8.0", + "prettier": "^3.0.3", "vite": "^3.2.4", - "vitest": "^0.25.3" + "vitest": "^0.32.0" }, "lint-staged": { "vite.config.js": "prettier --write", - "**/{src,tests}/**/*.test.{js,jsx,json}": "prettier --write" + "**/{src,tests}/**/*.test.{js,jsx,json,css,md}": "prettier --write" }, "license": "Apache-2.0" } diff --git a/src/api/api.js b/src/api/api.js index 9e1ce2c585..5d88084541 100644 --- a/src/api/api.js +++ b/src/api/api.js @@ -1,178 +1,272 @@ /* @flow */ -import { FPTI_KEY } from '@paypal/sdk-constants/src'; -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { request } from '@krakenjs/belter/src'; - -import { GRAPHQL_URI } from '../config'; -import { FPTI_CUSTOM_KEY, FPTI_TRANSITION, HEADERS, SMART_PAYMENT_BUTTONS, STATUS_CODES } from '../constants'; -import { getLogger } from '../lib'; +import { FPTI_KEY } from "@paypal/sdk-constants/src"; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { request } from "@krakenjs/belter/src"; + +import { GRAPHQL_URI } from "../config"; +import { + FPTI_CUSTOM_KEY, + FPTI_TRANSITION, + HEADERS, + SMART_PAYMENT_BUTTONS, + STATUS_CODES, +} from "../constants"; +import { getLogger, sendCountMetric } from "../lib"; type RESTAPIParams = {| - accessToken : string, - method? : string, - url : string, - data? : D, - headers? : { [string] : string }, - eventName? : string + accessToken: string, + method?: string, + url: string, + data?: D, + headers?: { [string]: string }, + eventName: string, + metricDimensions?: { + [string]: mixed, + }, |}; -export function callRestAPI({ accessToken, method, url, data, headers, eventName } : RESTAPIParams) : ZalgoPromise { - - if (!accessToken) { - throw new Error(`No access token passed to ${ url }`); +export function callRestAPI({ + accessToken, + method, + url, + data, + headers, + eventName, + metricDimensions = {}, +}: RESTAPIParams): ZalgoPromise { + if (!accessToken) { + throw new Error(`No access token passed to ${url}`); + } + + // $FlowFixMe + const requestHeaders = { + [HEADERS.AUTHORIZATION]: `Bearer ${accessToken}`, + [HEADERS.CONTENT_TYPE]: `application/json`, + ...headers, + }; + + return request({ + method, + url, + headers: requestHeaders, + json: data, + }).then(({ status, body, headers: responseHeaders }): T => { + if (status >= 300) { + const error = new Error( + `${url} returned status ${status} (Corr ID: ${ + responseHeaders[HEADERS.PAYPAL_DEBUG_ID] + }).\n\n${JSON.stringify(body)}`, + ); + + // $FlowFixMe + error.response = { status, headers: responseHeaders, body }; + + if (status === STATUS_CODES.TOO_MANY_REQUESTS) { + getLogger().track({ + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.CALL_REST_API, + [FPTI_CUSTOM_KEY.ERR_DESC]: `Error: ${status} - ${body}`, + [FPTI_CUSTOM_KEY.INFO_MSG]: `URL: ${url}`, + }); + } + + getLogger().warn(`rest_api_${eventName}_status_${status}_error`); + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.rest_api_${eventName}.error.count`, + dimensions: metricDimensions, + }); + throw error; } - // $FlowFixMe - const requestHeaders = { - [ HEADERS.AUTHORIZATION ]: `Bearer ${ accessToken }`, - [ HEADERS.CONTENT_TYPE ]: `application/json`, - ...headers - }; - - return request({ - method, - url, - headers: requestHeaders, - json: data - }).then(({ status, body, headers: responseHeaders }) : T => { - if (status >= 300) { - const error = new Error(`${ url } returned status ${ status } (Corr ID: ${ responseHeaders[HEADERS.PAYPAL_DEBUG_ID] }).\n\n${ JSON.stringify(body) }`); - - // $FlowFixMe - error.response = { status, headers: responseHeaders, body }; - - if (status === STATUS_CODES.TOO_MANY_REQUESTS) { - getLogger().track({ - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.CALL_REST_API, - [FPTI_CUSTOM_KEY.ERR_DESC]: `Error: ${ status } - ${ body }`, - [FPTI_CUSTOM_KEY.INFO_MSG]: `URL: ${ url }` - }); - } - - if (eventName) { - getLogger().warn(`rest_api_${ eventName }_status_${ status }_error`); - } - throw error; - } - - return body; + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.rest_api_${eventName}.success.count`, + dimensions: metricDimensions, }); + + return body; + }); } type SmartAPIRequest = {| - authenticated? : boolean, - accessToken? : ?string, - url : string, - method? : string, - json? : $ReadOnlyArray | Object, - headers? : { [string] : string }, - eventName : string + authenticated?: boolean, + accessToken?: ?string, + url: string, + method?: string, + json?: $ReadOnlyArray | Object, + headers?: { [string]: string }, + eventName: string, + metricDimensions?: { + [string]: mixed, + }, |}; export type APIResponse = {| - data : Object, - headers : {| [$Values] : string |} + data: Object, + headers: {| [$Values]: string |}, |}; -export function callSmartAPI({ accessToken, url, method = 'get', headers: reqHeaders = {}, json, authenticated = true, eventName } : SmartAPIRequest) : ZalgoPromise { - - reqHeaders[HEADERS.REQUESTED_BY] = SMART_PAYMENT_BUTTONS; - - if (authenticated && !accessToken) { - throw new Error(`Buyer access token not present - can not call smart api: ${ url }`); - } - - if (accessToken) { - reqHeaders[HEADERS.ACCESS_TOKEN] = accessToken; - } - - return request({ url, method, headers: reqHeaders, json }) - .then(({ status, body, headers }) => { - if (body.ack === 'contingency') { - const err = new Error(body.contingency); - // $FlowFixMe - err.response = { url, method, headers: reqHeaders, body }; - // $FlowFixMe - err.data = body.data; - - getLogger().warn(`smart_api_${ eventName }_contingency_error`); - throw err; - } - - if (status === STATUS_CODES.TOO_MANY_REQUESTS) { - getLogger().track({ - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.CALL_REST_API, - [FPTI_CUSTOM_KEY.ERR_DESC]: `Error: ${ status } - ${ body }`, - [FPTI_CUSTOM_KEY.INFO_MSG]: `URL: ${ url }` - }); - } - - if (status > 400) { - getLogger().warn(`smart_api_${ eventName }_status_${ status }_error`); - throw new Error(`Api: ${ url } returned status code: ${ status } (Corr ID: ${ headers[HEADERS.PAYPAL_DEBUG_ID] })\n\n${ JSON.stringify(body) }`); - } - - if (body.ack !== 'success') { - getLogger().warn(`smart_api_${ eventName }_ack_error`); - throw new Error(`Api: ${ url } returned ack: ${ body.ack } (Corr ID: ${ headers[HEADERS.PAYPAL_DEBUG_ID] })\n\n${ JSON.stringify(body) }`); - } - - return { data: body.data, headers }; +export function callSmartAPI({ + accessToken, + url, + method = "get", + headers: reqHeaders = {}, + json, + authenticated = true, + eventName, + metricDimensions = {}, +}: SmartAPIRequest): ZalgoPromise { + reqHeaders[HEADERS.REQUESTED_BY] = SMART_PAYMENT_BUTTONS; + + if (authenticated && !accessToken) { + throw new Error( + `Buyer access token not present - can not call smart api: ${url}`, + ); + } + + if (accessToken) { + reqHeaders[HEADERS.ACCESS_TOKEN] = accessToken; + } + + return request({ url, method, headers: reqHeaders, json }).then( + ({ status, body, headers }) => { + if (body.ack === "contingency") { + const err = new Error(body.contingency); + // $FlowFixMe + err.response = { url, method, headers: reqHeaders, body }; + // $FlowFixMe + err.data = body.data; + + getLogger().warn(`smart_api_${eventName}_contingency_error`); + throw err; + } + + if (status === STATUS_CODES.TOO_MANY_REQUESTS) { + getLogger().track({ + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.CALL_REST_API, + [FPTI_CUSTOM_KEY.ERR_DESC]: `Error: ${status} - ${body}`, + [FPTI_CUSTOM_KEY.INFO_MSG]: `URL: ${url}`, + }); + } + + if (status > 400) { + getLogger().warn(`smart_api_${eventName}_status_${status}_error`); + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.smart_api_${eventName}.error.count`, + dimensions: { + status, + ...metricDimensions, + }, }); + throw new Error( + `Api: ${url} returned status code: ${status} (Corr ID: ${ + headers[HEADERS.PAYPAL_DEBUG_ID] + })\n\n${JSON.stringify(body)}`, + ); + } + + if (body.ack !== "success") { + getLogger().warn(`smart_api_${eventName}_ack_error`); + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.smart_api_${eventName}.error.count`, + dimensions: metricDimensions, + }); + throw new Error( + `Api: ${url} returned ack: ${body.ack} (Corr ID: ${ + headers[HEADERS.PAYPAL_DEBUG_ID] + })\n\n${JSON.stringify(body)}`, + ); + } + + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.smart_api_${eventName}.success.count`, + dimensions: metricDimensions, + }); + + return { data: body.data, headers }; + }, + ); } -export function callGraphQL({ name, query, variables = {}, headers = {}, returnErrorObject = false } : {| name : string, query : string, variables? : { [string] : mixed }, headers? : { [string] : string }, returnErrorObject? : boolean |}) : ZalgoPromise { - return request({ - url: `${ GRAPHQL_URI }?${ name }`, - method: 'POST', - json: { - query, - variables - }, - headers: { - 'x-app-name': SMART_PAYMENT_BUTTONS, - ...headers - } - }).then(({ status, body }) => { - const errors = body.errors || []; - - if (errors.length) { - const message = errors[0].message || JSON.stringify(errors[0]); - - getLogger().warn(`graphql_${ name }_error`, { err: message }); - - if (returnErrorObject) { - throw errors[0]; - } - - throw new Error(message); - } +export function callGraphQL({ + name, + query, + variables = {}, + headers = {}, + returnErrorObject = false, +}: {| + name: string, + query: string, + variables?: { [string]: mixed }, + headers?: { [string]: string }, + returnErrorObject?: boolean, +|}): ZalgoPromise { + return request({ + url: `${GRAPHQL_URI}?${name}`, + method: "POST", + json: { + query, + variables, + }, + headers: { + "x-app-name": SMART_PAYMENT_BUTTONS, + ...headers, + }, + }).then(({ status, body }) => { + const errors = body.errors || []; + + if (errors.length) { + const message = errors[0].message || JSON.stringify(errors[0]); + + getLogger().warn(`graphql_${name}_error`, { err: message }); + + if (returnErrorObject) { + throw errors[0]; + } + + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.graphql_${name}.error.count`, + dimensions: {}, + }); + + throw new Error(message); + } - if (status !== 200) { - getLogger().warn(`graphql_${ name }_status_${ status }_error`); - throw new Error(`${ GRAPHQL_URI } returned status ${ status }\n\n${ JSON.stringify(body) }`); - } + if (status !== 200) { + getLogger().warn(`graphql_${name}_status_${status}_error`); + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.graphql_${name}.error.count`, + dimensions: { + status, + }, + }); + throw new Error( + `${GRAPHQL_URI} returned status ${status}\n\n${JSON.stringify(body)}`, + ); + } - return body.data; + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.graphql_${name}.success.count`, + dimensions: {}, }); + return body.data; + }); } export type Response = {| - data : mixed, - headers : {| - [string] : string - |} + data: mixed, + headers: {| + [string]: string, + |}, |}; -export function getResponseCorrelationID(res : Response) : ?string { - return res.headers[HEADERS.PAYPAL_DEBUG_ID]; +export function getResponseCorrelationID(res: Response): ?string { + return res.headers[HEADERS.PAYPAL_DEBUG_ID]; } -export function getErrorResponseCorrelationID(err : mixed) : ?string { - // $FlowFixMe - const res : Response = err?.response; - if (res) { - return getResponseCorrelationID(res); - } +export function getErrorResponseCorrelationID(err: mixed): ?string { + // $FlowFixMe + const res: Response = err?.response; + if (res) { + return getResponseCorrelationID(res); + } } diff --git a/src/api/api.test.js b/src/api/api.test.js index f8d543e568..aa7eb5c7a5 100644 --- a/src/api/api.test.js +++ b/src/api/api.test.js @@ -3,42 +3,37 @@ import { describe, expect, it, vi } from "vitest"; import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -const request = vi.fn(); -const warn = vi.fn(); +import { callRestAPI } from "./api"; vi.mock("@krakenjs/belter/src", async () => ({ ...(await vi.importActual("@krakenjs/belter/src")), - request, + request: vi.fn().mockImplementationOnce(() => + ZalgoPromise.resolve({ + status: 403, + headers: {}, + }), + ), })); +const warn = vi.fn(); vi.mock("../lib", async () => ({ ...(await vi.importActual("../lib")), - getLogger: () => ({ warn }), + getLogger: vi.fn().mockImplementationOnce(() => ({ warn })), })); -// eslint-disable-next-line import/first -import { callRestAPI } from "./api"; - describe("API", () => { describe("callRestAPI", () => { it("logs 403 errors", () => { - request.mockImplementationOnce(() => - ZalgoPromise.resolve({ - status: 403, - headers: {}, - }) - ); - expect( callRestAPI({ accessToken: "accessToken", url: "", eventName: "order_capture", - }) + }), ).rejects.toThrow(); expect(warn).toHaveBeenCalledWith( - "rest_api_order_capture_status_403_error" + "rest_api_order_capture_status_403_error", ); expect.assertions(2); diff --git a/src/api/auth.js b/src/api/auth.js index 75950e72d1..c4f2ee1559 100644 --- a/src/api/auth.js +++ b/src/api/auth.js @@ -1,65 +1,88 @@ /* @flow */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { inlineMemoize, base64encode, request, noop } from '@krakenjs/belter/src'; -import { FUNDING } from '@paypal/sdk-constants/src'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { + inlineMemoize, + base64encode, + request, + noop, +} from "@krakenjs/belter/src"; +import { FUNDING } from "@paypal/sdk-constants/src"; -import type { ConnectOptions } from '../types'; -import { AUTH_API_URL } from '../config'; -import { getLogger } from '../lib'; -import { HEADERS } from '../constants'; +import type { ConnectOptions } from "../types"; +import { AUTH_API_URL } from "../config"; +import { getLogger } from "../lib"; +import { HEADERS } from "../constants"; -import { callGraphQL } from './api'; +import { callGraphQL } from "./api"; type GenerateAccessTokenOptions = {| - targetSubject? : string + targetSubject?: string, |}; -export function createAccessToken(clientID : string, { targetSubject } : GenerateAccessTokenOptions = {}) : ZalgoPromise { - return inlineMemoize(createAccessToken, () => { +export function createAccessToken( + clientID: string, + { targetSubject }: GenerateAccessTokenOptions = {}, +): ZalgoPromise { + return inlineMemoize( + createAccessToken, + () => { + getLogger().info(`rest_api_create_access_token`); - getLogger().info(`rest_api_create_access_token`); + const basicAuth = base64encode(`${clientID || ""}:`); + const data: Object = { + grant_type: `client_credentials`, + }; - const basicAuth = base64encode(`${ clientID || '' }:`); - const data : Object = { - grant_type: `client_credentials` - }; + if (targetSubject) { + data.target_subject = targetSubject; + } - if (targetSubject) { - data.target_subject = targetSubject; - } + return request({ + method: `post`, + url: AUTH_API_URL, + headers: { + Authorization: `Basic ${basicAuth}`, + }, + data, + }).then(({ body }) => { + if (body && body.error === "invalid_client") { + const eventName = "v1_oauth2_token_create"; - return request({ - method: `post`, - url: AUTH_API_URL, - headers: { - Authorization: `Basic ${ basicAuth }` - }, - data - }).then(({ body }) => { - if (body && body.error === 'invalid_client') { - const eventName = 'v1_oauth2_token_create'; - - getLogger().warn(`rest_api_${ eventName }_error`, { err: 'invalid client id' }); - throw new Error(`Auth Api invalid client id: ${ clientID || '' }:\n\n${ JSON.stringify(body, null, 4) }`); - } + getLogger().warn(`rest_api_${eventName}_error`, { + err: "invalid client id", + }); + throw new Error( + `Auth Api invalid client id: ${clientID || ""}:\n\n${JSON.stringify( + body, + null, + 4, + )}`, + ); + } - if (!body || !body.access_token) { - const eventName = 'v1_oauth2_token_create'; + if (!body || !body.access_token) { + const eventName = "v1_oauth2_token_create"; - getLogger().warn(`rest_api_${ eventName }_error`); - throw new Error(`Auth Api response error:\n\n${ JSON.stringify(body, null, 4) }`); - } + getLogger().warn(`rest_api_${eventName}_error`); + throw new Error( + `Auth Api response error:\n\n${JSON.stringify(body, null, 4)}`, + ); + } - return body.access_token; - }); - }, [ clientID, targetSubject ]); + return body.access_token; + }); + }, + [clientID, targetSubject], + ); } -export function getFirebaseSessionToken(sessionUID : string) : ZalgoPromise { - return callGraphQL({ - name: 'GetFireBaseSessionToken', - query: ` +export function getFirebaseSessionToken( + sessionUID: string, +): ZalgoPromise { + return callGraphQL({ + name: "GetFireBaseSessionToken", + query: ` query GetFireBaseSessionToken($sessionUID: String!) { firebase { auth(sessionUID: $sessionUID) { @@ -68,47 +91,63 @@ export function getFirebaseSessionToken(sessionUID : string) : ZalgoPromise { - return res.firebase.auth.sessionToken; - }); + variables: { sessionUID }, + }).then((res) => { + return res.firebase.auth.sessionToken; + }); } -let lsatUpgradeCalled : boolean = false; -let lsatUpgradeError : ?mixed; +let lsatUpgradeCalled: boolean = false; +let lsatUpgradeError: ?mixed; +let lsatUpgradeWithIgnoreCache: boolean = false; export const onLsatUpgradeCalled = () => { - lsatUpgradeCalled = true; + lsatUpgradeCalled = true; +}; + +export const getLsatUpgradeWithIgnoreCache = (): boolean => { + return lsatUpgradeWithIgnoreCache; +}; + +const onLsatUpgradeWithIgnoreCacheCalled = () => { + lsatUpgradeWithIgnoreCache = true; }; -export const getLsatUpgradeCalled = () : boolean => { - return lsatUpgradeCalled; +export const getLsatUpgradeCalled = (): boolean => { + return lsatUpgradeCalled; }; -export const onLsatUpgradeError = (err : mixed) => { - lsatUpgradeError = err; +export const onLsatUpgradeError = (err: mixed) => { + lsatUpgradeError = err; }; -export const getLsatUpgradeError = () : ?mixed => { - return lsatUpgradeError; +export const getLsatUpgradeError = (): ?mixed => { + return lsatUpgradeError; }; export const clearLsatState = () => { - lsatUpgradeCalled = false; - lsatUpgradeError = null; + lsatUpgradeCalled = false; + lsatUpgradeError = null; + lsatUpgradeWithIgnoreCache = false; }; -export function upgradeFacilitatorAccessToken(facilitatorAccessToken : string, { buyerAccessToken, orderID } : {| buyerAccessToken : string, orderID : string |}) : ZalgoPromise { - clearLsatState(); - onLsatUpgradeCalled(); +export function upgradeFacilitatorAccessToken( + facilitatorAccessToken: string, + { + buyerAccessToken, + orderID, + }: {| buyerAccessToken: string, orderID: string |}, +): ZalgoPromise { + clearLsatState(); + onLsatUpgradeCalled(); - return callGraphQL({ - name: 'UpgradeFacilitatorAccessToken', - headers: { - [ HEADERS.ACCESS_TOKEN ]: buyerAccessToken, - [ HEADERS.CLIENT_CONTEXT ]: orderID - }, - query: ` + return callGraphQL({ + name: "UpgradeFacilitatorAccessToken", + headers: { + [HEADERS.ACCESS_TOKEN]: buyerAccessToken, + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + query: ` mutation UpgradeFacilitatorAccessToken( $orderID: String! $buyerAccessToken: String! @@ -121,17 +160,72 @@ export function upgradeFacilitatorAccessToken(facilitatorAccessToken : string, { ) } `, - variables: { facilitatorAccessToken, buyerAccessToken, orderID } - }).then(noop).catch(err => { - onLsatUpgradeError(err); - throw err; + variables: { facilitatorAccessToken, buyerAccessToken, orderID }, + }) + .then(noop) + .catch((err) => { + onLsatUpgradeError(err); + throw err; }); } -export function exchangeAccessTokenForAuthCode(buyerAccessToken : string) : ZalgoPromise { - return callGraphQL({ - name: 'ExchangeAuthCode', +export function upgradeFacilitatorAccessTokenWithIgnoreCache( + facilitatorAccessToken: string, + buyerAccessToken: string, + orderID: string, +): ZalgoPromise { + return inlineMemoize( + upgradeFacilitatorAccessTokenWithIgnoreCache, + () => { + clearLsatState(); + onLsatUpgradeCalled(); + onLsatUpgradeWithIgnoreCacheCalled(); + + return callGraphQL({ + name: "CreateUpgradedLowScopeAccessToken", + headers: { + [HEADERS.ACCESS_TOKEN]: buyerAccessToken, + [HEADERS.CLIENT_CONTEXT]: orderID, + }, query: ` + mutation CreateUpgradedLowScopeAccessToken( + $orderID: String! + $buyerAccessToken: String! + $facilitatorAccessToken: String! + ) { + createUpgradedLowScopeAccessToken( + token: $orderID + buyerAccessToken: $buyerAccessToken + merchantLSAT: $facilitatorAccessToken + ) + } + `, + variables: { facilitatorAccessToken, buyerAccessToken, orderID }, + }) + .then((res) => { + getLogger().info("create_upgraded_low_scope_access_token_success", { + orderID, + }); + return res?.createUpgradedLowScopeAccessToken; + }) + .catch((err) => { + getLogger().warn("create_upgraded_low_scope_access_token_error", { + orderID, + }); + onLsatUpgradeError(err); + return facilitatorAccessToken; + }); + }, + [facilitatorAccessToken, buyerAccessToken, orderID], + ); +} + +export function exchangeAccessTokenForAuthCode( + buyerAccessToken: string, +): ZalgoPromise { + return callGraphQL({ + name: "ExchangeAuthCode", + query: ` query ExchangeAuthCode( $buyerAccessToken: String! ) { @@ -142,26 +236,32 @@ export function exchangeAccessTokenForAuthCode(buyerAccessToken : string) : Zalg } } `, - variables: { buyerAccessToken } - }).then(({ auth }) => { - return auth.authCode; - }); + variables: { buyerAccessToken }, + }).then(({ auth }) => { + return auth.authCode; + }); } type ConnectURLOptions = {| - clientID : string, - orderID : string, - payerID : string, - fundingSource : $Values, - connect : ConnectOptions + clientID: string, + orderID: string, + payerID: string, + fundingSource: $Values, + connect: ConnectOptions, |}; -export function getConnectURL({ clientID, orderID, payerID, fundingSource, connect } : ConnectURLOptions) : ZalgoPromise { - const { scopes } = connect; +export function getConnectURL({ + clientID, + orderID, + payerID, + fundingSource, + connect, +}: ConnectURLOptions): ZalgoPromise { + const { scopes } = connect; - return callGraphQL({ - name: 'GetConnectURL', - query: ` + return callGraphQL({ + name: "GetConnectURL", + query: ` query GetConnectURL( $clientID: String! $orderID: String! @@ -183,8 +283,8 @@ export function getConnectURL({ clientID, orderID, payerID, fundingSource, conne } } `, - variables: { clientID, orderID, payerID, scopes, fundingSource } - }).then(({ auth }) => { - return auth.connectUrl.href; - }); + variables: { clientID, orderID, payerID, scopes, fundingSource }, + }).then(({ auth }) => { + return auth.connectUrl.href; + }); } diff --git a/src/api/auth.test.js b/src/api/auth.test.js new file mode 100644 index 0000000000..ebf0057f06 --- /dev/null +++ b/src/api/auth.test.js @@ -0,0 +1,43 @@ +/* @flow */ +import { describe, test, expect, vi } from "vitest"; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; + +import { upgradeFacilitatorAccessTokenWithIgnoreCache } from "./auth"; +import { callGraphQL } from "./api"; + +vi.mock("./api", async () => { + const actual = await vi.importActual("./api"); + return { + ...actual, + callGraphQL: vi.fn(() => { + return ZalgoPromise.resolve({ + data: { + createUpgradedLowScopeAccessToken: "newToken", + }, + }); + }), + }; +}); + +describe("auth", () => { + test("invoke callGraphQL from upgradeFacilitatorAccessTokenWithIgnoreCache", async () => { + const orderID = "EC-abc123"; + const facilitatorAccessToken = "A21_A.AA"; + const buyerAccessToken = "S23_A.AA"; + + // Call the function that uses callGraphQL + await upgradeFacilitatorAccessTokenWithIgnoreCache( + facilitatorAccessToken, + buyerAccessToken, + orderID, + ); + + expect(callGraphQL).toHaveBeenCalled(); + // $FlowFixMe + expect(callGraphQL()).resolves.toEqual({ + data: { + createUpgradedLowScopeAccessToken: "newToken", + }, + }); + }); +}); diff --git a/src/api/config.js b/src/api/config.js index 04ebbf8a80..954bb3cf3f 100644 --- a/src/api/config.js +++ b/src/api/config.js @@ -1,30 +1,36 @@ /* @flow */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -import { callGraphQL } from './api'; +import { callGraphQL } from "./api"; export type ApplepayConfigResponse = {| - applepayConfig: {| - merchantCountry: string, - supportedNetworks: $ReadOnlyArray - |} + applepayConfig: {| + merchantCountry: string, + supportedNetworks: $ReadOnlyArray, + |}, |}; type GetApplepayConfigPayload = {| - buyerCountry: string, - clientId: string, - merchantId: $ReadOnlyArray, - headers? : { [string] : string } -|} - -export type GetApplepayConfig = (payload: GetApplepayConfigPayload) => ZalgoPromise; + buyerCountry: string, + clientId: string, + merchantId: $ReadOnlyArray, + headers?: { [string]: string }, +|}; -export const getApplepayConfig : GetApplepayConfig = ({ buyerCountry, clientId, merchantId, headers = {} }: GetApplepayConfigPayload) => { +export type GetApplepayConfig = ( + payload: GetApplepayConfigPayload, +) => ZalgoPromise; - return callGraphQL({ - name: 'GetApplepayConfig', - query: ` +export const getApplepayConfig: GetApplepayConfig = ({ + buyerCountry, + clientId, + merchantId, + headers = {}, +}: GetApplepayConfigPayload) => { + return callGraphQL({ + name: "GetApplepayConfig", + query: ` query GetApplepayConfig( $buyerCountry: CountryCodes! $clientId: String! @@ -40,8 +46,7 @@ export const getApplepayConfig : GetApplepayConfig = ({ buyerCountry, clientId, } } `, - variables: { buyerCountry, clientId, merchantId }, - headers - }); - + variables: { buyerCountry, clientId, merchantId }, + headers, + }); }; diff --git a/src/api/eligibility.js b/src/api/eligibility.js index 90a6c7ab5e..f81a7ea9c5 100644 --- a/src/api/eligibility.js +++ b/src/api/eligibility.js @@ -1,30 +1,52 @@ /* @flow */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { CURRENCY, COUNTRY, INTENT, FUNDING, CARD, PLATFORM, type FundingEligibilityType } from '@paypal/sdk-constants/src'; -import { getUserAgent } from '@krakenjs/belter/src'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { + CURRENCY, + COUNTRY, + INTENT, + FUNDING, + CARD, + PLATFORM, + type FundingEligibilityType, +} from "@paypal/sdk-constants/src"; +import { getUserAgent } from "@krakenjs/belter/src"; -import { HEADERS } from '../constants'; +import { HEADERS } from "../constants"; -import { callGraphQL } from './api'; +import { callGraphQL } from "./api"; type GetFundingEligibilityOptions = {| - accessToken? : string, - clientID : string, - merchantID : ?$ReadOnlyArray, - currency : $Values, - buyerCountry : $Values, - intent : $Values, - commit : boolean, - vault : boolean, - disableFunding : ?$ReadOnlyArray<$Values>, - disableCard : ?$ReadOnlyArray<$Values> + accessToken?: string, + clientID: string, + merchantID: ?$ReadOnlyArray, + currency: $Values, + buyerCountry: $Values, + intent: $Values, + commit: boolean, + vault: boolean, + disableFunding: ?$ReadOnlyArray<$Values>, + disableCard: ?$ReadOnlyArray<$Values>, |}; -export function getFundingEligibility(query : string, { accessToken, clientID, merchantID, currency, buyerCountry, intent, commit, vault, disableFunding, disableCard } : GetFundingEligibilityOptions) : ZalgoPromise { - return callGraphQL({ - name: 'GetFundingEligibility', - query: ` +export function getFundingEligibility( + query: string, + { + accessToken, + clientID, + merchantID, + currency, + buyerCountry, + intent, + commit, + vault, + disableFunding, + disableCard, + }: GetFundingEligibilityOptions, +): ZalgoPromise { + return callGraphQL({ + name: "GetFundingEligibility", + query: ` query GetFundingEligibility( $clientID:String, $merchantID:[ String ], @@ -47,36 +69,44 @@ export function getFundingEligibility(query : string, { accessToken, clientID, m disableCard: $disableCard, merchantId: $merchantID ) { - ${ query } + ${query} } } `, - variables: { - clientID, - merchantID, - buyerCountry, - currency, - commit, - vault, - intent: intent ? intent.toUpperCase() : intent, - disableFunding: disableFunding ? disableFunding.map(f => f && f.toUpperCase()) : disableFunding, - disableCard: disableCard ? disableCard.map(f => f && f.toUpperCase()) : disableCard - }, - headers: { - [ HEADERS.ACCESS_TOKEN ]: accessToken || '' - } - }).then((gqlResult) => { - if (!gqlResult || !gqlResult.fundingEligibility) { - throw new Error(`GraphQL fundingEligibility returned no fundingEligibility object`); - } - return gqlResult && gqlResult.fundingEligibility; - }); + variables: { + clientID, + merchantID, + buyerCountry, + currency, + commit, + vault, + intent: intent ? intent.toUpperCase() : intent, + disableFunding: disableFunding + ? disableFunding.map((f) => f && f.toUpperCase()) + : disableFunding, + disableCard: disableCard + ? disableCard.map((f) => f && f.toUpperCase()) + : disableCard, + }, + headers: { + [HEADERS.ACCESS_TOKEN]: accessToken || "", + }, + }).then((gqlResult) => { + if (!gqlResult || !gqlResult.fundingEligibility) { + throw new Error( + `GraphQL fundingEligibility returned no fundingEligibility object`, + ); + } + return gqlResult && gqlResult.fundingEligibility; + }); } -export function getGuestEnabledStatus(merchantID : $ReadOnlyArray) : ZalgoPromise { - return callGraphQL({ - name: 'GetFundingEligibility', - query: ` +export function getGuestEnabledStatus( + merchantID: $ReadOnlyArray, +): ZalgoPromise { + return callGraphQL({ + name: "GetFundingEligibility", + query: ` query GetFundingEligibility( $merchantID:[ String ] ) { @@ -89,48 +119,70 @@ export function getGuestEnabledStatus(merchantID : $ReadOnlyArray) : Zal } } `, - variables: { - merchantID - } - }).then((gqlResult) => { - if (!gqlResult || !gqlResult.fundingEligibility) { - throw new Error(`GraphQL fundingEligibility returned no fundingEligibility object`); - } - return gqlResult && gqlResult.fundingEligibility && gqlResult.fundingEligibility.card && gqlResult.fundingEligibility.card.guestEnabled; - }); + variables: { + merchantID, + }, + }).then((gqlResult) => { + if (!gqlResult || !gqlResult.fundingEligibility) { + throw new Error( + `GraphQL fundingEligibility returned no fundingEligibility object`, + ); + } + return ( + gqlResult && + gqlResult.fundingEligibility && + gqlResult.fundingEligibility.card && + gqlResult.fundingEligibility.card.guestEnabled + ); + }); } type NativeEligibilityOptions = {| - clientID : string, - buyerCountry : ?$Values, - currency : $Values, - vault : boolean, - merchantID : string, - buttonSessionID : string, - shippingCallbackEnabled : boolean, - platform : $Values, - cookies : string, - orderID? : ?string, - enableFunding : ?$ReadOnlyArray<$Values>, - stickinessID? : ?string, - domain : string, - skipElmo? : boolean, - headers? : { [string] : string } + clientID: string, + buyerCountry: ?$Values, + currency: $Values, + vault: boolean, + merchantID: string, + buttonSessionID: string, + shippingCallbackEnabled: boolean, + platform: $Values, + cookies: string, + orderID?: ?string, + enableFunding: ?$ReadOnlyArray<$Values>, + stickinessID?: ?string, + domain: string, + skipElmo?: boolean, + headers?: { [string]: string }, |}; export type NativeEligibility = {| - [ $Values ] : ?{| - eligibility : boolean, - ineligibilityReason : string - |} + [$Values]: ?{| + eligibility: boolean, + ineligibilityReason: string, + |}, |}; -export function getNativeEligibility({ vault, shippingCallbackEnabled, merchantID, clientID, buyerCountry, currency, buttonSessionID, cookies, orderID, enableFunding, stickinessID, domain, headers = {}, skipElmo = false } : NativeEligibilityOptions) : ZalgoPromise { - const userAgent = getUserAgent(); +export function getNativeEligibility({ + vault, + shippingCallbackEnabled, + merchantID, + clientID, + buyerCountry, + currency, + buttonSessionID, + cookies, + orderID, + enableFunding, + stickinessID, + domain, + headers = {}, + skipElmo = false, +}: NativeEligibilityOptions): ZalgoPromise { + const userAgent = getUserAgent(); - return callGraphQL({ - name: 'GetNativeEligibility', - query: ` + return callGraphQL({ + name: "GetNativeEligibility", + query: ` query GetNativeEligibility( $vault : Boolean, $shippingCallbackEnabled : Boolean, @@ -174,38 +226,59 @@ export function getNativeEligibility({ vault, shippingCallbackEnabled, merchantI } } `, - variables: { - vault, shippingCallbackEnabled, merchantID, clientID, - buyerCountry, currency, userAgent, buttonSessionID, - cookies, orderID, enableFunding, stickinessID, domain, skipElmo - }, - headers - }).then((gqlResult) => { - if (!gqlResult || !gqlResult.mobileSDKEligibility) { - throw new Error(`GraphQL GetNativeEligibility returned no mobileSDKEligibility object`); - } + variables: { + vault, + shippingCallbackEnabled, + merchantID, + clientID, + buyerCountry, + currency, + userAgent, + buttonSessionID, + cookies, + orderID, + enableFunding, + stickinessID, + domain, + skipElmo, + }, + headers, + }).then((gqlResult) => { + if (!gqlResult || !gqlResult.mobileSDKEligibility) { + throw new Error( + `GraphQL GetNativeEligibility returned no mobileSDKEligibility object`, + ); + } - return gqlResult.mobileSDKEligibility; - }); + return gqlResult.mobileSDKEligibility; + }); } type ApplePaySession = {| - session : string + session: string, |}; type ValidateMerchantOptions = {| - url : string, - clientID : string, - orderID : string, - merchantDomain : string + url: string, + clientID: string, + orderID: string, + merchantDomain: string, |}; -export function getApplePayMerchantSession({ url, clientID, orderID, merchantDomain } : ValidateMerchantOptions) : ZalgoPromise { - const domain = merchantDomain.indexOf('://') !== -1 ? merchantDomain.split('://')[1] : merchantDomain; +export function getApplePayMerchantSession({ + url, + clientID, + orderID, + merchantDomain, +}: ValidateMerchantOptions): ZalgoPromise { + const domain = + merchantDomain.indexOf("://") !== -1 + ? merchantDomain.split("://")[1] + : merchantDomain; - return callGraphQL({ - name: 'GetApplePayMerchantSession', - query: ` + return callGraphQL({ + name: "GetApplePayMerchantSession", + query: ` query GetApplePayMerchantSession( $url : String! $orderID : String! @@ -222,13 +295,18 @@ export function getApplePayMerchantSession({ url, clientID, orderID, merchantDom } } `, - variables: { - url, clientID, orderID, merchantDomain: domain - } - }).then((gqlResult) => { - if (!gqlResult || !gqlResult.applePayMerchantSession) { - throw new Error(`GraphQL GetApplePayMerchantSession returned no applePayMerchantSession object`); - } - return gqlResult.applePayMerchantSession; - }); + variables: { + url, + clientID, + orderID, + merchantDomain: domain, + }, + }).then((gqlResult) => { + if (!gqlResult || !gqlResult.applePayMerchantSession) { + throw new Error( + `GraphQL GetApplePayMerchantSession returned no applePayMerchantSession object`, + ); + } + return gqlResult.applePayMerchantSession; + }); } diff --git a/src/api/fraudnet.js b/src/api/fraudnet.js index 87f0848cbf..46fd382c26 100644 --- a/src/api/fraudnet.js +++ b/src/api/fraudnet.js @@ -1,77 +1,93 @@ /* @flow */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { ENV } from '@paypal/sdk-constants/src'; -import { memoize, type Memoized } from '@krakenjs/belter/src'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { ENV } from "@paypal/sdk-constants/src"; +import { memoize, type Memoized } from "@krakenjs/belter/src"; -import { getBody } from '../lib'; +import { getBody } from "../lib"; const FRAUDNET_URL = { - [ ENV.LOCAL ]: 'https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js', - [ ENV.STAGE ]: 'https://www.stage2d0107.stage.paypal.com/FDRegression/fb.js', - [ ENV.SANDBOX ]: 'https://c.paypal.com/da/r/fb.js', - [ ENV.PRODUCTION ]: 'https://c.paypal.com/da/r/fb.js', - [ ENV.TEST ]: 'https://c.paypal.com/da/r/fb.js' + [ENV.LOCAL]: "https://www.msmaster.qa.paypal.com/en_US/m/fb-raw.js", + [ENV.STAGE]: + "https://stage2mb044.qa.paypal.com/fraudnetjsnodeweb/automate/develop/stage_raw.js", + [ENV.SANDBOX]: "https://c.paypal.com/da/r/fb.js", + [ENV.PRODUCTION]: "https://c.paypal.com/da/r/fb.js", + [ENV.TEST]: "https://c.paypal.com/da/r/fb.js", }; -export const FRAUDNET_FNCLS = 'fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99'; -export const FRAUDNET_APP_NAME = 'SMART_PAYMENT_BUTTONS'; +export const FRAUDNET_FNCLS = "fnparams-dede7cc5-15fd-4c75-a9f4-36c430ee3a99"; +export const FRAUDNET_APP_NAME = "SMART_PAYMENT_BUTTONS"; type FraudnetOptions = {| - env : $Values, - clientMetadataID : string, - cspNonce? : ?string, - timeout? : number, - queryStringParams? : {[string]: string | boolean} + env: $Values, + clientMetadataID: string, + cspNonce?: ?string, + timeout?: number, + queryStringParams?: { [string]: string | boolean }, |}; type FraudnetConfig = {| - f : string, - s : string, - u : string, - cb1 : string, - sandbox? : boolean + f: string, + s: string, + u: string, + cb1: string, + sandbox?: boolean, |}; type LoadFraudnet = (FraudnetOptions) => ZalgoPromise; -export const loadFraudnet : Memoized = memoize(({ env, clientMetadataID, cspNonce, timeout = 1000, queryStringParams = {} }) => { - return new ZalgoPromise(resolve => { - if (__TEST__) { - return resolve(); - } +export const loadFraudnet: Memoized = memoize( + ({ + env, + clientMetadataID, + cspNonce, + timeout = 1000, + queryStringParams = {}, + }) => { + return new ZalgoPromise((resolve) => { + if (__TEST__) { + return resolve(); + } - const config : FraudnetConfig = { - f: clientMetadataID, - s: FRAUDNET_APP_NAME, - u: window.xprops.buttonLocation, - cb1: 'fnCallback' - }; + const config: FraudnetConfig = { + f: clientMetadataID, + s: FRAUDNET_APP_NAME, + u: window.xprops.buttonLocation, + cb1: "fnCallback", + }; - if (env === ENV.SANDBOX) { - config.sandbox = true; - } + if (env === ENV.SANDBOX) { + config.sandbox = true; + } - const configScript = document.createElement('script'); - configScript.setAttribute('nonce', cspNonce || ''); - configScript.setAttribute('type', 'application/json'); - configScript.setAttribute('id', 'fconfig'); - configScript.setAttribute('fncls', FRAUDNET_FNCLS); - configScript.textContent = JSON.stringify(config); + const configScript = document.createElement("script"); + configScript.setAttribute("nonce", cspNonce || ""); + configScript.setAttribute("type", "application/json"); + configScript.setAttribute("id", "fconfig"); + configScript.setAttribute("fncls", FRAUDNET_FNCLS); + configScript.textContent = JSON.stringify(config); - const fraudnetScript = document.createElement('script'); - const queryString = Object.keys(queryStringParams).map(key => `${key}=${encodeURIComponent(String(queryStringParams[key]))}`).join('&'); - const fraudnetUrl = queryString.length ? `${FRAUDNET_URL[env]}?${queryString}` : FRAUDNET_URL[env]; + const fraudnetScript = document.createElement("script"); + const queryString = Object.keys(queryStringParams) + .map( + (key) => + `${key}=${encodeURIComponent(String(queryStringParams[key]))}`, + ) + .join("&"); + const fraudnetUrl = queryString.length + ? `${FRAUDNET_URL[env]}?${queryString}` + : FRAUDNET_URL[env]; - fraudnetScript.setAttribute('nonce', cspNonce || ''); - fraudnetScript.setAttribute('src', fraudnetUrl); - fraudnetScript.addEventListener('error', () => resolve()); + fraudnetScript.setAttribute("nonce", cspNonce || ""); + fraudnetScript.setAttribute("src", fraudnetUrl); + fraudnetScript.addEventListener("error", () => resolve()); - window.fnCallback = resolve; - setTimeout(resolve, timeout); + window.fnCallback = resolve; + setTimeout(resolve, timeout); - const body = getBody(); - body.appendChild(configScript); - body.appendChild(fraudnetScript); + const body = getBody(); + body.appendChild(configScript); + body.appendChild(fraudnetScript); }); -}); + }, +); diff --git a/src/api/index.js b/src/api/index.js index 50568981d2..c3995265f0 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -1,12 +1,12 @@ /* @flow */ -export * from './auth'; -export * from './order'; -export * from './payment'; -export * from './subscription'; -export * from './socket'; -export * from './fraudnet'; -export * from './wallet'; -export * from './eligibility'; -export * from './api'; -export * from './config'; +export * from "./auth"; +export * from "./order"; +export * from "./payment"; +export * from "./subscription"; +export * from "./socket"; +export * from "./fraudnet"; +export * from "./wallet"; +export * from "./eligibility"; +export * from "./api"; +export * from "./config"; diff --git a/src/api/order.js b/src/api/order.js index bef2ba9967..8cbc8f05df 100644 --- a/src/api/order.js +++ b/src/api/order.js @@ -1,31 +1,61 @@ /* @flow */ /* eslint max-lines: 0 */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { CURRENCY, FPTI_KEY, FUNDING, WALLET_INSTRUMENT, INTENT } from '@paypal/sdk-constants/src'; -import { request, noop, memoize, stringifyError } from '@krakenjs/belter/src'; - -import { SMART_API_URI, ORDERS_API_URL, VALIDATE_PAYMENT_METHOD_API } from '../config'; -import { getClientsideTimestamp, getLogger, setBuyerAccessToken } from '../lib'; -import { FPTI_TRANSITION, FPTI_CONTEXT_TYPE, HEADERS, SMART_PAYMENT_BUTTONS, - INTEGRATION_ARTIFACT, ITEM_CATEGORY, USER_EXPERIENCE_FLOW, PRODUCT_FLOW, PREFER, ORDER_API_ERROR } from '../constants'; -import type { ShippingMethod, ShippingAddress } from '../payment-flows/types'; -import type { FeatureFlags } from '../types'; - -import { callSmartAPI, callGraphQL, callRestAPI, getResponseCorrelationID, getErrorResponseCorrelationID } from './api'; -import { getLsatUpgradeError, getLsatUpgradeCalled } from './auth'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { + CURRENCY, + FPTI_KEY, + FUNDING, + WALLET_INSTRUMENT, + INTENT, +} from "@paypal/sdk-constants/src"; +import { request, noop, memoize, stringifyError } from "@krakenjs/belter/src"; + +import { + SMART_API_URI, + ORDERS_API_URL, + VALIDATE_PAYMENT_METHOD_API, +} from "../config"; +import { getClientsideTimestamp, getLogger, setBuyerAccessToken } from "../lib"; +import { + FPTI_TRANSITION, + FPTI_CONTEXT_TYPE, + HEADERS, + SMART_PAYMENT_BUTTONS, + INTEGRATION_ARTIFACT, + ITEM_CATEGORY, + USER_EXPERIENCE_FLOW, + PRODUCT_FLOW, + PREFER, + ORDER_API_ERROR, +} from "../constants"; +import type { ShippingMethod, ShippingAddress } from "../payment-flows/types"; +import type { FeatureFlags, Experiments } from "../types"; + +import { + callSmartAPI, + callGraphQL, + callRestAPI, + getResponseCorrelationID, + getErrorResponseCorrelationID, +} from "./api"; +import { + getLsatUpgradeError, + getLsatUpgradeCalled, + getLsatUpgradeWithIgnoreCache, +} from "./auth"; export type OrderCreateRequest = {| - intent? : 'CAPTURE' | 'AUTHORIZE', - purchase_units : $ReadOnlyArray<{| - amount : {| - currency_code : string, - value : string - |}, - payee? : {| - merchant_id? : string - |} - |}> + intent?: "CAPTURE" | "AUTHORIZE", + purchase_units: $ReadOnlyArray<{| + amount: {| + currency_code: string, + value: string, + |}, + payee?: {| + merchant_id?: string, + |}, + |}>, |}; export type OrderResponse = {||}; @@ -35,328 +65,640 @@ export type OrderGetResponse = {||}; export type OrderAuthorizeResponse = {||}; export type OrderAPIOptions = {| - facilitatorAccessToken : string, - buyerAccessToken? : ?string, - partnerAttributionID : ?string, - forceRestAPI? : boolean + facilitatorAccessToken: string, + buyerAccessToken?: ?string, + partnerAttributionID: ?string, + forceRestAPI?: boolean, + experiments: Experiments, |}; -export function createOrderID(order : OrderCreateRequest, { facilitatorAccessToken, partnerAttributionID } : OrderAPIOptions) : ZalgoPromise { - getLogger().info(`rest_api_create_order_id`); - return callRestAPI({ - accessToken: facilitatorAccessToken, - method: 'post', - url: `${ ORDERS_API_URL }`, - eventName: 'v2_checkout_orders_create', - data: order, - headers: { - [ HEADERS.PARTNER_ATTRIBUTION_ID ]: partnerAttributionID || '', - [ HEADERS.PREFER ]: PREFER.REPRESENTATION - } - }).then((body) : string => { - - const orderID = body && body.id; - - if (!orderID) { - throw new Error(`Order Api response error:\n\n${ JSON.stringify(body, null, 4) }`); - } - - getLogger().track({ - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.CREATE_ORDER, - [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.ORDER_ID, - [FPTI_KEY.TOKEN]: orderID, - [FPTI_KEY.CONTEXT_ID]: orderID - }); +export function createOrderID( + order: OrderCreateRequest, + { facilitatorAccessToken, partnerAttributionID }: OrderAPIOptions, +): ZalgoPromise { + getLogger().info(`rest_api_create_order_id`); + return callRestAPI({ + accessToken: facilitatorAccessToken, + method: "post", + url: `${ORDERS_API_URL}`, + eventName: "v2_checkout_orders_create", + data: order, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + [HEADERS.PREFER]: PREFER.REPRESENTATION, + }, + }).then((body): string => { + const orderID = body && body.id; + + if (!orderID) { + throw new Error( + `Order Api response error:\n\n${JSON.stringify(body, null, 4)}`, + ); + } - return orderID; + getLogger().track({ + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.CREATE_ORDER, + [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.ORDER_ID, + [FPTI_KEY.TOKEN]: orderID, + [FPTI_KEY.CONTEXT_ID]: orderID, }); + + return orderID; + }); } -export function isInvalidResourceIDError(err: mixed) : boolean { +export function isInvalidResourceIDError(err: mixed): boolean { + return Boolean( // $FlowFixMe - return Boolean(err?.response?.body?.details?.some(detail => { - return detail.issue === ORDER_API_ERROR.INVALID_RESOURCE_ID; - })) + err?.response?.body?.details?.some((detail) => { + return detail.issue === ORDER_API_ERROR.INVALID_RESOURCE_ID; + }), + ); +} +function lsatUpgradeType(): string { + return getLsatUpgradeWithIgnoreCache() + ? "with_ignore_cache_lsat_upgrade" + : "without_ignore_cache_lsat_upgrade"; +} +function lsatUpgradeMetricValue(): string { + const lsatUpgradeCalled = Boolean(getLsatUpgradeCalled()); + const lsatUpgradeIgnoreCache = Boolean(getLsatUpgradeWithIgnoreCache()); + const lsatUpgradeError = Boolean(getLsatUpgradeError()); + const cacheType = lsatUpgradeIgnoreCache + ? "with_ignore_cache" + : "without_ignore_cache"; + + if (lsatUpgradeCalled) { + return lsatUpgradeError ? `${cacheType}_error` : `${cacheType}_success`; + } else { + return `${cacheType}_not_called`; + } +} +function logPayeeInfoForClientSideHelpers( + orderID: string, + method: "get" | "patch" | "capture" | "authorize", +): void { + // eslint-disable-next-line no-use-before-define + getSupplementalOrderInfo(orderID) + .then((order) => { + const payees = order.checkoutSession.payees || []; + const merchantIds = payees.map((p) => p.merchantId); + getLogger().info(`using_client_side_helper_${method}`, { + payee: merchantIds.join(), + orderID, + }); + }) + .catch((err) => { + // no-op + getLogger().warn(`err_getting_payee_client_side_helper_${method}`, { + orderID, + err: stringifyError(err), + }); + }); } -export function getOrder(orderID : string, { facilitatorAccessToken, buyerAccessToken, partnerAttributionID, forceRestAPI = false } : OrderAPIOptions) : ZalgoPromise { - getLogger().info(`get_order_lsat_upgrade_${ getLsatUpgradeCalled() ? 'called' : 'not_called' }`); - getLogger().info(`get_order_lsat_upgrade_${ getLsatUpgradeError() ? 'errored' : 'did_not_error' }`, { err: stringifyError(getLsatUpgradeError()) }); - - if (forceRestAPI && !getLsatUpgradeError()) { - return callRestAPI({ - accessToken: facilitatorAccessToken, - url: `${ ORDERS_API_URL }/${ orderID }`, - eventName: 'v2_checkout_orders_get', - headers: { - [ HEADERS.PARTNER_ATTRIBUTION_ID ]: partnerAttributionID || '', - [ HEADERS.PREFER ]: PREFER.REPRESENTATION - } - }).catch(err => { - const restCorrID = getErrorResponseCorrelationID(err); - getLogger().warn(`get_order_call_rest_api_error`, { restCorrID, orderID, err: stringifyError(err) }); - - if (isInvalidResourceIDError(err)) { - getLogger().warn(`get_order_invalid_resource_id_error`, { restCorrID, orderID, err: stringifyError(err) }) - } - - return callSmartAPI({ - accessToken: buyerAccessToken, - url: `${ SMART_API_URI.ORDER }/${ orderID }`, - eventName: 'order_get', - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID - } - }).then((res) => { - const smartCorrID = getResponseCorrelationID(res); - getLogger().info(`get_order_smart_fallback_success`, { smartCorrID, restCorrID, orderID }); - return res.data; - }).catch(smartErr => { - const smartCorrID = getErrorResponseCorrelationID(err); - getLogger().error(`get_order_smart_fallback_error`, { smartCorrID, restCorrID, orderID, err: stringifyError(smartErr) }); - throw smartErr; - }); +export function getOrder( + orderID: string, + { + facilitatorAccessToken, + buyerAccessToken, + partnerAttributionID, + forceRestAPI = false, + experiments, + }: OrderAPIOptions, +): ZalgoPromise { + getLogger().info( + `get_order_${lsatUpgradeType()}_${ + getLsatUpgradeCalled() ? "called" : "not_called" + }`, + { orderID }, + ); + getLogger().info( + `get_order_${lsatUpgradeType()}_${ + getLsatUpgradeError() ? "errored" : "did_not_error" + }`, + { orderID, err: stringifyError(getLsatUpgradeError()) }, + ); + logPayeeInfoForClientSideHelpers(orderID, "get"); + + if (forceRestAPI && !getLsatUpgradeError()) { + return callRestAPI({ + accessToken: facilitatorAccessToken, + url: `${ORDERS_API_URL}/${orderID}`, + eventName: "v2_checkout_orders_get", + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + [HEADERS.PREFER]: PREFER.REPRESENTATION, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + }, + }) + .catch((err) => { + const restCorrID = getErrorResponseCorrelationID(err); + getLogger().warn(`get_order_${lsatUpgradeType()}_call_rest_api_error`, { + restCorrID, + orderID, + err: stringifyError(err), }); - } - return callSmartAPI({ - accessToken: buyerAccessToken, - url: `${ SMART_API_URI.ORDER }/${ orderID }`, - eventName: 'order_get', - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID + if (isInvalidResourceIDError(err)) { + getLogger().warn( + `get_order_${lsatUpgradeType()}_invalid_resource_id_error`, + { restCorrID, orderID, err: stringifyError(err) }, + ); + } + + if (experiments.disableSmartAPI) { + throw err; } - }).then(({ data }) => { - return data; + + return callSmartAPI({ + accessToken: buyerAccessToken, + url: `${SMART_API_URI.ORDER}/${orderID}`, + eventName: "order_get", + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback", + }, + }) + .then((res) => { + const smartCorrID = getResponseCorrelationID(res); + getLogger().info( + `get_order_${lsatUpgradeType()}_smart_fallback_success`, + { smartCorrID, restCorrID, orderID }, + ); + return res.data; + }) + .catch((smartErr) => { + const smartCorrID = getErrorResponseCorrelationID(err); + getLogger().error( + `get_order_${lsatUpgradeType()}_smart_fallback_error`, + { + smartCorrID, + restCorrID, + orderID, + err: stringifyError(smartErr), + }, + ); + throw smartErr; + }); + }) + .finally(() => { + getLogger().flush(); + }); + } + + return callSmartAPI({ + accessToken: buyerAccessToken, + url: `${SMART_API_URI.ORDER}/${orderID}`, + eventName: "order_get", + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default", + }, + }) + .then(({ data }) => { + return data; + }) + .finally(() => { + getLogger().flush(); }); } -export function isProcessorDeclineError(err : mixed) : boolean { - // $FlowFixMe - const details = err?.response?.body?.data?.details ? err?.response?.body?.data?.details : err?.response?.body?.details; - return Boolean(details?.some(detail => { - return detail.issue === ORDER_API_ERROR.INSTRUMENT_DECLINED || detail.issue === ORDER_API_ERROR.PAYER_ACTION_REQUIRED; - })); +export function isProcessorDeclineError(err: mixed): boolean { + // $FlowFixMe + const details = err?.response?.body?.data?.details + ? err?.response?.body?.data?.details + : // $FlowFixMe + err?.response?.body?.details; + return Boolean( + details?.some((detail) => { + return ( + detail.issue === ORDER_API_ERROR.INSTRUMENT_DECLINED || + detail.issue === ORDER_API_ERROR.PAYER_ACTION_REQUIRED + ); + }), + ); } -export function isUnprocessableEntityError(err : mixed) : boolean { +export function isUnprocessableEntityError(err: mixed): boolean { + return Boolean( // $FlowFixMe - return Boolean(err?.response?.body?.details?.some(detail => { - return detail.issue === ORDER_API_ERROR.DUPLICATE_INVOICE_ID; - })); + err?.response?.body?.details?.some((detail) => { + return detail.issue === ORDER_API_ERROR.DUPLICATE_INVOICE_ID; + }), + ); } -export function captureOrder(orderID : string, { facilitatorAccessToken, buyerAccessToken, partnerAttributionID, forceRestAPI = false } : OrderAPIOptions) : ZalgoPromise { - getLogger().info(`capture_order_lsat_upgrade_${ getLsatUpgradeCalled() ? 'called' : 'not_called' }`); - getLogger().info(`capture_order_lsat_upgrade_${ getLsatUpgradeError() ? 'errored' : 'did_not_error' }`, { err: stringifyError(getLsatUpgradeError()) }); - - if (forceRestAPI && !getLsatUpgradeError()) { - return callRestAPI({ - accessToken: facilitatorAccessToken, - method: 'post', - eventName: 'v2_checkout_orders_capture', - url: `${ ORDERS_API_URL }/${ orderID }/capture`, - headers: { - [ HEADERS.PARTNER_ATTRIBUTION_ID ]: partnerAttributionID || '', - [ HEADERS.PREFER ]: PREFER.REPRESENTATION, - [ HEADERS.PAYPAL_REQUEST_ID ]: orderID - } - }).catch(err => { - const restCorrID = getErrorResponseCorrelationID(err); - getLogger().warn(`capture_order_call_rest_api_error`, { restCorrID, orderID, err: stringifyError(err) }); - - if (isInvalidResourceIDError(err)) { - getLogger().warn(`capture_order_invalid_resource_id_error`, { restCorrID, orderID, err: stringifyError(err) }) - } - - if (isProcessorDeclineError(err) || isUnprocessableEntityError(err)) { - throw err; - } +export function captureOrder( + orderID: string, + { + facilitatorAccessToken, + buyerAccessToken, + partnerAttributionID, + forceRestAPI = false, + experiments, + }: OrderAPIOptions, +): ZalgoPromise { + getLogger().info( + `capture_order_${lsatUpgradeType()}_${ + getLsatUpgradeCalled() ? "called" : "not_called" + }`, + { orderID }, + ); + getLogger().info( + `capture_order_${lsatUpgradeType()}_${ + getLsatUpgradeError() ? "errored" : "did_not_error" + }`, + { orderID, err: stringifyError(getLsatUpgradeError()) }, + ); + logPayeeInfoForClientSideHelpers(orderID, "capture"); + + if (forceRestAPI && !getLsatUpgradeError()) { + return callRestAPI({ + accessToken: facilitatorAccessToken, + method: "post", + eventName: "v2_checkout_orders_capture", + url: `${ORDERS_API_URL}/${orderID}/capture`, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + [HEADERS.PREFER]: PREFER.REPRESENTATION, + [HEADERS.PAYPAL_REQUEST_ID]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + }, + }) + .catch((err) => { + const restCorrID = getErrorResponseCorrelationID(err); + getLogger().warn( + `capture_order_${lsatUpgradeType()}_call_rest_api_error`, + { restCorrID, orderID, err: stringifyError(err) }, + ); + + if (isInvalidResourceIDError(err)) { + getLogger().warn( + `capture_order_${lsatUpgradeType()}_invalid_resource_id_error`, + { restCorrID, orderID, err: stringifyError(err) }, + ); + } - return callSmartAPI({ - accessToken: buyerAccessToken, - method: 'post', - eventName: 'order_capture', - url: `${ SMART_API_URI.ORDER }/${ orderID }/capture`, - json: { data: { facilitatorAccessToken }}, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID - } - }).then((res) => { - const smartCorrID = getResponseCorrelationID(res); - getLogger().info(`capture_order_smart_fallback_success`, { smartCorrID, restCorrID, orderID }); - return res.data; - }).catch(smartErr => { - const smartCorrID = getErrorResponseCorrelationID(err); - getLogger().info(`capture_order_smart_fallback_error`, { smartCorrID, restCorrID, orderID, err: stringifyError(smartErr) }); - throw smartErr; - }); - }); - } + if (isProcessorDeclineError(err) || isUnprocessableEntityError(err)) { + throw err; + } - return callSmartAPI({ - accessToken: buyerAccessToken, - method: 'post', - eventName: 'order_capture', - url: `${ SMART_API_URI.ORDER }/${ orderID }/capture`, - json: { data: { facilitatorAccessToken }}, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID + if (experiments.disableSmartAPI) { + throw err; } - }).then(({ data }) => { - return data; + + return callSmartAPI({ + accessToken: buyerAccessToken, + method: "post", + eventName: "order_capture", + url: `${SMART_API_URI.ORDER}/${orderID}/capture`, + json: { data: { facilitatorAccessToken } }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback", + }, + }) + .then((res) => { + const smartCorrID = getResponseCorrelationID(res); + getLogger().info( + `capture_order_${lsatUpgradeType()}_smart_fallback_success`, + { smartCorrID, restCorrID, orderID }, + ); + return res.data; + }) + .catch((smartErr) => { + const smartCorrID = getErrorResponseCorrelationID(err); + getLogger().info( + `capture_order_${lsatUpgradeType()}_smart_fallback_error`, + { + smartCorrID, + restCorrID, + orderID, + err: stringifyError(smartErr), + }, + ); + throw smartErr; + }); + }) + .finally(() => { + getLogger().flush(); + }); + } + + return callSmartAPI({ + accessToken: buyerAccessToken, + method: "post", + eventName: "order_capture", + url: `${SMART_API_URI.ORDER}/${orderID}/capture`, + json: { data: { facilitatorAccessToken } }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default", + }, + }) + .then(({ data }) => { + return data; + }) + .finally(() => { + getLogger().flush(); }); } -export function authorizeOrder(orderID : string, { facilitatorAccessToken, buyerAccessToken, partnerAttributionID, forceRestAPI = false } : OrderAPIOptions) : ZalgoPromise { - getLogger().info(`authorize_order_lsat_upgrade_${ getLsatUpgradeCalled() ? 'called' : 'not_called' }`); - getLogger().info(`authorize_order_lsat_upgrade_${ getLsatUpgradeError() ? 'errored' : 'did_not_error' }`, { err: stringifyError(getLsatUpgradeError()) }); - - if (forceRestAPI && !getLsatUpgradeError()) { - return callRestAPI({ - accessToken: facilitatorAccessToken, - method: 'post', - eventName: 'v2_checkout_orders_authorize', - url: `${ ORDERS_API_URL }/${ orderID }/authorize`, - headers: { - [ HEADERS.PARTNER_ATTRIBUTION_ID ]: partnerAttributionID || '', - [ HEADERS.PREFER ]: PREFER.REPRESENTATION - } - }).catch(err => { - const restCorrID = getErrorResponseCorrelationID(err); - getLogger().warn(`authorize_order_call_rest_api_error`, { restCorrID, orderID, err: stringifyError(err) }); - - if (isInvalidResourceIDError(err)) { - getLogger().warn(`authorize_order_invalid_resource_id_error`, { restCorrID, orderID, err: stringifyError(err) }) - } - - if (isProcessorDeclineError(err)) { - throw err; - } +export function authorizeOrder( + orderID: string, + { + facilitatorAccessToken, + buyerAccessToken, + partnerAttributionID, + forceRestAPI = false, + experiments, + }: OrderAPIOptions, +): ZalgoPromise { + getLogger().info( + `authorize_order_${lsatUpgradeType()}_${ + getLsatUpgradeCalled() ? "called" : "not_called" + }`, + { orderID }, + ); + getLogger().info( + `authorize_order_${lsatUpgradeType()}_${ + getLsatUpgradeError() ? "errored" : "did_not_error" + }`, + { orderID, err: stringifyError(getLsatUpgradeError()) }, + ); + logPayeeInfoForClientSideHelpers(orderID, "authorize"); + + if (forceRestAPI && !getLsatUpgradeError()) { + return callRestAPI({ + accessToken: facilitatorAccessToken, + method: "post", + eventName: "v2_checkout_orders_authorize", + url: `${ORDERS_API_URL}/${orderID}/authorize`, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + [HEADERS.PREFER]: PREFER.REPRESENTATION, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + }, + }) + .catch((err) => { + const restCorrID = getErrorResponseCorrelationID(err); + getLogger().warn( + `authorize_order_${lsatUpgradeType()}_call_rest_api_error`, + { restCorrID, orderID, err: stringifyError(err) }, + ); + + if (isInvalidResourceIDError(err)) { + getLogger().warn( + `authorize_order_${lsatUpgradeType()}_invalid_resource_id_error`, + { restCorrID, orderID, err: stringifyError(err) }, + ); + } - return callSmartAPI({ - accessToken: buyerAccessToken, - method: 'post', - eventName: 'order_authorize', - url: `${ SMART_API_URI.ORDER }/${ orderID }/authorize`, - json: { data: { facilitatorAccessToken }}, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID - } - }).then((res) => { - const smartCorrID = getResponseCorrelationID(res); - getLogger().info(`authorize_order_smart_fallback_success`, { smartCorrID, restCorrID, orderID }); - return res.data; - }).catch(smartErr => { - const smartCorrID = getErrorResponseCorrelationID(err); - getLogger().info(`authorize_order_smart_fallback_error`, { smartCorrID, restCorrID, orderID, err: stringifyError(smartErr) }); - throw smartErr; - }); - }); - } + if (isProcessorDeclineError(err)) { + throw err; + } - getLogger().info(`lsat_upgrade_false`); - return callSmartAPI({ - accessToken: buyerAccessToken, - method: 'post', - eventName: 'order_authorize', - url: `${ SMART_API_URI.ORDER }/${ orderID }/authorize`, - json: { data: { facilitatorAccessToken }}, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID + if (experiments.disableSmartAPI) { + throw err; } - }).then(({ data }) => { - return data; + + return callSmartAPI({ + accessToken: buyerAccessToken, + method: "post", + eventName: "order_authorize", + url: `${SMART_API_URI.ORDER}/${orderID}/authorize`, + json: { data: { facilitatorAccessToken } }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback", + }, + }) + .then((res) => { + const smartCorrID = getResponseCorrelationID(res); + getLogger().info( + `authorize_order_${lsatUpgradeType()}_smart_fallback_success`, + { smartCorrID, restCorrID, orderID }, + ); + return res.data; + }) + .catch((smartErr) => { + const smartCorrID = getErrorResponseCorrelationID(err); + getLogger().info( + `authorize_order_${lsatUpgradeType()}_smart_fallback_error`, + { + smartCorrID, + restCorrID, + orderID, + err: stringifyError(smartErr), + }, + ); + throw smartErr; + }); + }) + .finally(() => { + getLogger().flush(); + }); + } + + getLogger().info(`lsat_upgrade_false`); + return callSmartAPI({ + accessToken: buyerAccessToken, + method: "post", + eventName: "order_authorize", + url: `${SMART_API_URI.ORDER}/${orderID}/authorize`, + json: { data: { facilitatorAccessToken } }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default", + }, + }) + .then(({ data }) => { + return data; + }) + .finally(() => { + getLogger().flush(); }); } export type PatchData = mixed; -export function patchOrder(orderID : string, data : PatchData, { facilitatorAccessToken, buyerAccessToken, partnerAttributionID, forceRestAPI = false } : OrderAPIOptions) : ZalgoPromise { - getLogger().info(`patch_order_lsat_upgrade_${ getLsatUpgradeCalled() ? 'called' : 'not_called' }`); - getLogger().info(`patch_order_lsat_upgrade_${ getLsatUpgradeError() ? 'errored' : 'did_not_error' }`, { err: stringifyError(getLsatUpgradeError()) }); - - if (forceRestAPI && !getLsatUpgradeError()) { - return callRestAPI({ - accessToken: facilitatorAccessToken, - method: 'PATCH', - eventName: 'v2_checkout_orders_patch', - url: `${ ORDERS_API_URL }/${ orderID }`, - data, - headers: { - [ HEADERS.PARTNER_ATTRIBUTION_ID ]: partnerAttributionID || '', - [ HEADERS.PREFER ]: PREFER.REPRESENTATION - } - }).catch(err => { - const restCorrID = getErrorResponseCorrelationID(err); - getLogger().warn(`patch_order_call_rest_api_error`, { restCorrID, orderID, err: stringifyError(err) }); - - if (isInvalidResourceIDError(err)) { - getLogger().warn(`patch_order_invalid_resource_id_error`, { restCorrID, orderID, err: stringifyError(err) }) - } - - let requestData : PatchData; - - if (Array.isArray(data)) { - requestData = { patch: data, facilitatorAccessToken } - } else { - requestData = { ...data, facilitatorAccessToken } - } - - return callSmartAPI({ - accessToken: buyerAccessToken, - method: 'post', - eventName: 'order_patch', - url: `${ SMART_API_URI.ORDER }/${ orderID }/patch`, - json: { data: requestData }, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID - } - }).then((res) => { - const smartCorrID = getResponseCorrelationID(res); - getLogger().info(`patch_order_smart_fallback_success`, { smartCorrID, restCorrID, orderID }); - return res.data; - }).catch(smartErr => { - const smartCorrID = getErrorResponseCorrelationID(err); - getLogger().info(`patch_order_smart_fallback_error`, { smartCorrID, restCorrID, orderID, err: stringifyError(smartErr) }); - throw smartErr; - }); - }); - } - - getLogger().info(`lsat_upgrade_false`); +export function patchOrder( + orderID: string, + data: PatchData, + { + facilitatorAccessToken, + buyerAccessToken, + partnerAttributionID, + forceRestAPI = false, + experiments, + }: OrderAPIOptions, +): ZalgoPromise { + getLogger().info( + `patch_order_${lsatUpgradeType()}_${ + getLsatUpgradeCalled() ? "called" : "not_called" + }`, + { orderID }, + ); + getLogger().info( + `patch_order_${lsatUpgradeType()}_${ + getLsatUpgradeError() ? "errored" : "did_not_error" + }`, + { orderID, err: stringifyError(getLsatUpgradeError()) }, + ); + logPayeeInfoForClientSideHelpers(orderID, "patch"); + + if (forceRestAPI && !getLsatUpgradeError()) { + return callRestAPI({ + accessToken: facilitatorAccessToken, + method: "PATCH", + eventName: "v2_checkout_orders_patch", + url: `${ORDERS_API_URL}/${orderID}`, + data, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + [HEADERS.PREFER]: PREFER.REPRESENTATION, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + }, + }) + .catch((err) => { + const restCorrID = getErrorResponseCorrelationID(err); + getLogger().warn( + `patch_order_${lsatUpgradeType()}_call_rest_api_error`, + { restCorrID, orderID, err: stringifyError(err) }, + ); + + if (isInvalidResourceIDError(err)) { + getLogger().warn( + `patch_order_${lsatUpgradeType()}_invalid_resource_id_error`, + { restCorrID, orderID, err: stringifyError(err) }, + ); + } - let requestData : PatchData; + if (experiments.disableSmartAPI) { + throw err; + } - if (Array.isArray(data)) { - requestData = { patch: data, facilitatorAccessToken } - } else { - requestData = { ...data, facilitatorAccessToken } - } + let requestData: PatchData; - return callSmartAPI({ - accessToken: buyerAccessToken, - method: 'post', - eventName: 'order_patch', - url: `${ SMART_API_URI.ORDER }/${ orderID }/patch`, - json: { data: requestData }, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID + if (Array.isArray(data)) { + requestData = { patch: data, facilitatorAccessToken }; + } else { + requestData = { ...data, facilitatorAccessToken }; } - }).then(({ data: patchData }) => { - return patchData; + + return callSmartAPI({ + accessToken: buyerAccessToken, + method: "post", + eventName: "order_patch", + url: `${SMART_API_URI.ORDER}/${orderID}/patch`, + json: { data: requestData }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "fallback", + }, + }) + .then((res) => { + const smartCorrID = getResponseCorrelationID(res); + getLogger().info( + `patch_order_${lsatUpgradeType()}_smart_fallback_success`, + { smartCorrID, restCorrID, orderID }, + ); + return res.data; + }) + .catch((smartErr) => { + const smartCorrID = getErrorResponseCorrelationID(err); + getLogger().info( + `patch_order_${lsatUpgradeType()}_smart_fallback_error`, + { + smartCorrID, + restCorrID, + orderID, + err: stringifyError(smartErr), + }, + ); + throw smartErr; + }); + }) + .finally(() => { + getLogger().flush(); + }); + } + + getLogger().info(`lsat_upgrade_false`); + + let requestData: PatchData; + + if (Array.isArray(data)) { + requestData = { patch: data, facilitatorAccessToken }; + } else { + requestData = { ...data, facilitatorAccessToken }; + } + + return callSmartAPI({ + accessToken: buyerAccessToken, + method: "post", + eventName: "order_patch", + url: `${SMART_API_URI.ORDER}/${orderID}/patch`, + json: { data: requestData }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + metricDimensions: { + lsatUpgrade: lsatUpgradeMetricValue(), + smartApiType: "default", + }, + }) + .then(({ data: patchData }) => { + return patchData; + }) + .finally(() => { + getLogger().flush(); }); } export type PatchShippingArgs = {| - clientID: string; - orderID: string; - data: PatchData, -|} + clientID: string, + orderID: string, + data: PatchData, +|}; -export function patchShipping({ clientID, orderID, data } : PatchShippingArgs) : ZalgoPromise { - return callGraphQL({ - name: 'UpdateShipping', - query: ` +export function patchShipping({ + clientID, + orderID, + data, +}: PatchShippingArgs): ZalgoPromise { + return callGraphQL({ + name: "UpdateShipping", + query: ` mutation UpdateShipping( $clientID: String! $patch: [JSON]! @@ -369,178 +711,230 @@ export function patchShipping({ clientID, orderID, data } : PatchShippingArgs) : ) } `, - variables: { - clientID, - patch: data, - token: orderID - } - }); + variables: { + clientID, + patch: data, + token: orderID, + }, + }); } type ConfirmPaymentSource = {| - [$Values] : {| - country_code? : string | null, - name? : string | null, - email? : string | null, - bic? : string | null, - bank_id? : string | null, - type?: string | 'NONCE', - id?: string - |} -|} -type LimitedNonceSource = {| - token : {| - id : string, - type : 'NONCE' + [$Values]: {| + country_code?: string | null, + name?: string | null, + email?: string | null, + bic?: string | null, + bank_id?: string | null, + type?: string | "NONCE", + id?: string, + |}, +|}; + +type SetupTokenSource = {| + [$Values]: {| + vault_id: string, + verification_method?: {| + method?: "SCA_ALWAYS", |}, -|} + |}, +|}; export type ConfirmData = {| - payment_source : ConfirmPaymentSource | LimitedNonceSource + payment_source: ConfirmPaymentSource | SetupTokenSource, |}; -export function confirmOrderAPI(orderID : string, data : ConfirmData, { facilitatorAccessToken, partnerAttributionID } : OrderAPIOptions) : ZalgoPromise { - return callRestAPI({ - accessToken: facilitatorAccessToken, - method: 'post', - eventName: 'order_confirm_payment_source', - url: `${ ORDERS_API_URL }/${ orderID }/confirm-payment-source`, - data, - headers: { - [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || '', - [HEADERS.PREFER]: PREFER.REPRESENTATION - } - }); +export function confirmOrderAPI( + orderID: string, + data: ConfirmData, + { facilitatorAccessToken, partnerAttributionID }: OrderAPIOptions, +): ZalgoPromise { + return callRestAPI({ + accessToken: facilitatorAccessToken, + method: "post", + eventName: "order_confirm_payment_source", + url: `${ORDERS_API_URL}/${orderID}/confirm-payment-source`, + data, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + [HEADERS.PREFER]: PREFER.REPRESENTATION, + }, + }); } export type ValidatePaymentMethodOptions = {| - accessToken : string, - orderID : string, - paymentMethodID : string, - enableThreeDomainSecure : boolean, - partnerAttributionID : ?string, - clientMetadataID : string, - installmentPlan? : {| - term : string, - interval_duration : string - |} | null + accessToken: string, + orderID: string, + paymentMethodID: string, + enableThreeDomainSecure: boolean, + partnerAttributionID: ?string, + clientMetadataID: string, + installmentPlan?: {| + term: string, + interval_duration: string, + |} | null, |}; const VALIDATE_CONTINGENCIES = { - THREE_DOMAIN_SECURE: '3D_SECURE' + THREE_DOMAIN_SECURE: "3D_SECURE", }; export type ValidatePaymentMethodResponse = {| - links? : $ReadOnlyArray<{| - rel : string - |}>, - details? : $ReadOnlyArray<{| - issue? : string, - description? : string - |}> + links?: $ReadOnlyArray<{| + rel: string, + |}>, + details?: $ReadOnlyArray<{| + issue?: string, + description?: string, + |}>, |}; - -export function buildPaymentSource(tokenID: string): LimitedNonceSource { - const paymentSource = { - token: { - id: tokenID, - type: 'NONCE' - } - }; - return paymentSource; +/* eslint-disable flowtype/require-exact-type */ +export function buildPaymentSource({ + paymentMethodID, + fundingSource, + enableThreeDomainSecure, +}: { + paymentMethodID: string, + fundingSource: $Values, + enableThreeDomainSecure?: boolean, +}): SetupTokenSource { + return { + // $FlowFixMe invalid-computed-prop + [fundingSource]: { + vault_id: paymentMethodID, + ...(enableThreeDomainSecure && { + verification_method: { + method: "SCA_ALWAYS", + }, + }), + }, + }; } +/* eslint-enable flowtype/require-exact-type */ type PaymentSource = {| - token : {| - id : string, - type : 'NONCE', - attributes? : {| - installments? : {| - term : string, - interval_duration : string - |} - |} + token: {| + id: string, + type: "NONCE", + attributes?: {| + installments?: {| + term: string, + interval_duration: string, + |}, |}, - contingencies? : $ReadOnlyArray<$Values> + |}, + contingencies?: $ReadOnlyArray<$Values>, |}; -export function validatePaymentMethod({ accessToken, orderID, paymentMethodID, enableThreeDomainSecure, partnerAttributionID, clientMetadataID, installmentPlan } : ValidatePaymentMethodOptions) : ZalgoPromise<{| status : number, body : ValidatePaymentMethodResponse, headers : { [string] : string } |}> { - getLogger().info(`rest_api_create_order_token`); - - const headers : Object = { - [ HEADERS.AUTHORIZATION ]: `Bearer ${ accessToken }`, - [ HEADERS.PARTNER_ATTRIBUTION_ID ]: partnerAttributionID, - [ HEADERS.CLIENT_METADATA_ID ]: clientMetadataID, - [ HEADERS.APP_NAME ]: SMART_PAYMENT_BUTTONS, - [ HEADERS.APP_VERSION ]: __SMART_BUTTONS__.__MINOR_VERSION__ - }; - - const paymentSource : PaymentSource = { - token: { - id: paymentMethodID, - type: 'NONCE' - } - }; - - if (enableThreeDomainSecure) { - paymentSource.contingencies = [ VALIDATE_CONTINGENCIES.THREE_DOMAIN_SECURE ]; - } - - if (installmentPlan) { - paymentSource.token.attributes = { - installments: { - term: installmentPlan.term, - interval_duration: installmentPlan.interval_duration - } - }; - } - - const json = { - payment_source: paymentSource +export function validatePaymentMethod({ + accessToken, + orderID, + paymentMethodID, + enableThreeDomainSecure, + partnerAttributionID, + clientMetadataID, + installmentPlan, +}: ValidatePaymentMethodOptions): ZalgoPromise<{| + status: number, + body: ValidatePaymentMethodResponse, + headers: { [string]: string }, +|}> { + getLogger().info(`rest_api_create_order_token`); + + const headers: Object = { + [HEADERS.AUTHORIZATION]: `Bearer ${accessToken}`, + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID, + [HEADERS.CLIENT_METADATA_ID]: clientMetadataID, + [HEADERS.APP_NAME]: SMART_PAYMENT_BUTTONS, + [HEADERS.APP_VERSION]: __SMART_BUTTONS__.__MINOR_VERSION__, + }; + + const paymentSource: PaymentSource = { + token: { + id: paymentMethodID, + type: "NONCE", + }, + }; + + if (enableThreeDomainSecure) { + paymentSource.contingencies = [VALIDATE_CONTINGENCIES.THREE_DOMAIN_SECURE]; + } + + if (installmentPlan) { + paymentSource.token.attributes = { + installments: { + term: installmentPlan.term, + interval_duration: installmentPlan.interval_duration, + }, }; - - return request({ - method: 'post', - url: `${ ORDERS_API_URL }/${ orderID }/${ VALIDATE_PAYMENT_METHOD_API }`, - headers, - json - }); + } + + const json = { + payment_source: paymentSource, + }; + + return request({ + method: "post", + url: `${ORDERS_API_URL}/${orderID}/${VALIDATE_PAYMENT_METHOD_API}`, + headers, + json, + }); } -export function billingTokenToOrderID(billingToken : string) : ZalgoPromise { - return callSmartAPI({ - authenticated: false, - method: 'post', - eventName: 'payment_ectoken', - url: `${ SMART_API_URI.PAYMENT }/${ billingToken }/ectoken` - }).then(({ data }) => { - return data.token; - }); +export function billingTokenToOrderID( + billingToken: string, +): ZalgoPromise { + return callSmartAPI({ + authenticated: false, + method: "post", + eventName: "payment_ectoken", + url: `${SMART_API_URI.PAYMENT}/${billingToken}/ectoken`, + }).then(({ data }) => { + return data.token; + }); } -export function subscriptionIdToCartId(subscriptionID : string) : ZalgoPromise { - return callSmartAPI({ - authenticated: false, - method: 'post', - eventName: 'billagmt_subscriptions_cartid', - url: `${ SMART_API_URI.SUBSCRIPTION }/${ subscriptionID }/cartid` - }).then(({ data }) => { - return data.token; - }); +export function subscriptionIdToCartId( + subscriptionID: string, +): ZalgoPromise { + return callSmartAPI({ + authenticated: false, + method: "post", + eventName: "billagmt_subscriptions_cartid", + url: `${SMART_API_URI.SUBSCRIPTION}/${subscriptionID}/cartid`, + }).then(({ data }) => { + return data.token; + }); } -export function enableVault({ orderID, clientAccessToken, fundingSource, integrationArtifact, userExperienceFlow, productFlow, buttonSessionID } : {| orderID : string, clientAccessToken : string, fundingSource : string, integrationArtifact : string, userExperienceFlow : string, productFlow : string, buttonSessionID : string |}) : ZalgoPromise { - const clientConfig = { - fundingSource, - integrationArtifact, - userExperienceFlow, - productFlow, - buttonSessionID, - } - return callGraphQL({ - name: 'EnableVault', - query: ` +export function enableVault({ + orderID, + clientAccessToken, + fundingSource, + integrationArtifact, + userExperienceFlow, + productFlow, + buttonSessionID, +}: {| + orderID: string, + clientAccessToken: string, + fundingSource: string, + integrationArtifact: string, + userExperienceFlow: string, + productFlow: string, + buttonSessionID: string, +|}): ZalgoPromise { + const clientConfig = { + fundingSource, + integrationArtifact, + userExperienceFlow, + productFlow, + buttonSessionID, + }; + return callGraphQL({ + name: "EnableVault", + query: ` mutation EnableVault( $orderID : String!, $clientConfig: ClientConfigInput! @@ -551,20 +945,27 @@ export function enableVault({ orderID, clientAccessToken, fundingSource, integra ) } `, - variables: { - orderID, clientConfig - }, - headers: { - [ HEADERS.ACCESS_TOKEN ]: clientAccessToken, - [ HEADERS.CLIENT_CONTEXT ]: orderID - } - }); + variables: { + orderID, + clientConfig, + }, + headers: { + [HEADERS.ACCESS_TOKEN]: clientAccessToken, + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + }); } -export function deleteVault({ paymentMethodID, clientAccessToken } : {| paymentMethodID : string, clientAccessToken : string |}) : ZalgoPromise { - return callGraphQL({ - name: 'DeleteVault', - query: ` +export function deleteVault({ + paymentMethodID, + clientAccessToken, +}: {| + paymentMethodID: string, + clientAccessToken: string, +|}): ZalgoPromise { + return callGraphQL({ + name: "DeleteVault", + query: ` mutation DeleteVault( $paymentMethodID : String! ) { @@ -573,35 +974,51 @@ export function deleteVault({ paymentMethodID, clientAccessToken } : {| paymentM ) } `, - variables: { - paymentMethodID - }, - headers: { - [ HEADERS.ACCESS_TOKEN ]: clientAccessToken - } - }); + variables: { + paymentMethodID, + }, + headers: { + [HEADERS.ACCESS_TOKEN]: clientAccessToken, + }, + }); } type ClientConfig = {| - orderID : string, - fundingSource : $Values, - integrationArtifact : string, - userExperienceFlow : string, - productFlow : string, - buttonSessionID : ?string, - featureFlags?: FeatureFlags + orderID: string, + fundingSource: $Values, + integrationArtifact: string, + userExperienceFlow: string, + productFlow: string, + buttonSessionID: ?string, + featureFlags?: FeatureFlags, |}; -export function updateClientConfig({ orderID, fundingSource, integrationArtifact, userExperienceFlow, productFlow, buttonSessionID, featureFlags } : ClientConfig) : ZalgoPromise { - if (featureFlags && featureFlags.isButtonClientConfigCallBlocking) { - getLogger().info('blocking_cco_call', {time: getClientsideTimestamp(), buttonSessionID, fundingSource}); - } else { - getLogger().info('non_blocking_cco_call', {time: getClientsideTimestamp(), buttonSessionID, fundingSource}); - } +export function updateClientConfig({ + orderID, + fundingSource, + integrationArtifact, + userExperienceFlow, + productFlow, + buttonSessionID, + featureFlags, +}: ClientConfig): ZalgoPromise { + if (featureFlags && featureFlags.isButtonClientConfigCallBlocking) { + getLogger().info("blocking_cco_call", { + time: getClientsideTimestamp(), + buttonSessionID, + fundingSource, + }); + } else { + getLogger().info("non_blocking_cco_call", { + time: getClientsideTimestamp(), + buttonSessionID, + fundingSource, + }); + } - return callGraphQL({ - name: 'UpdateClientConfig', - query: ` + return callGraphQL({ + name: "UpdateClientConfig", + query: ` mutation UpdateClientConfig( $orderID : String!, $fundingSource : ButtonFundingSourceType!, @@ -620,27 +1037,38 @@ export function updateClientConfig({ orderID, fundingSource, integrationArtifact ) } `, - variables: { orderID, fundingSource, integrationArtifact, userExperienceFlow, productFlow, buttonSessionID }, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID - } - }).then(noop); + variables: { + orderID, + fundingSource, + integrationArtifact, + userExperienceFlow, + productFlow, + buttonSessionID, + }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + }).then(noop); } type ApproveOrderOptions = {| - orderID : string, - planID : string, - buyerAccessToken : string + orderID: string, + planID: string, + buyerAccessToken: string, |}; type ApproveData = {| - payerID : string + payerID: string, |}; -export function approveOrder({ orderID, planID, buyerAccessToken } : ApproveOrderOptions) : ZalgoPromise { - return callGraphQL({ - name: 'ApproveOrder', - query: ` +export function approveOrder({ + orderID, + planID, + buyerAccessToken, +}: ApproveOrderOptions): ZalgoPromise { + return callGraphQL({ + name: "ApproveOrder", + query: ` mutation ApproveOrder( $orderID : String! $planID : String! @@ -658,113 +1086,112 @@ export function approveOrder({ orderID, planID, buyerAccessToken } : ApproveOrde } } `, - variables: { orderID, planID }, - headers: { - [ HEADERS.ACCESS_TOKEN ]: buyerAccessToken, - [ HEADERS.CLIENT_CONTEXT ]: orderID - } - }).then(({ approvePayment }) => { - setBuyerAccessToken(approvePayment?.buyer?.auth?.accessToken); - return { - payerID: approvePayment.buyer.userId - }; - }); + variables: { orderID, planID }, + headers: { + [HEADERS.ACCESS_TOKEN]: buyerAccessToken, + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + }).then(({ approvePayment }) => { + setBuyerAccessToken(approvePayment?.buyer?.auth?.accessToken); + return { + payerID: approvePayment.buyer.userId, + }; + }); } type OneClickApproveOrderOptions = {| - orderID : string, - instrumentType : $Values, - instrumentID : string, - buyerAccessToken : string, - clientMetadataID : ?string, - planID? : ?string, - useExistingPlanning? : boolean, - enableOrdersApprovalSmartWallet? : boolean + orderID: string, + instrumentType: $Values, + instrumentID: string, + buyerAccessToken: string, + clientMetadataID: ?string, |}; -export function oneClickApproveOrder({ orderID, instrumentType, instrumentID, buyerAccessToken, clientMetadataID, planID, useExistingPlanning = false, enableOrdersApprovalSmartWallet } : OneClickApproveOrderOptions) : ZalgoPromise { - const accessTokenQuery = `auth { - accessToken - }`; - - return callGraphQL({ - name: 'OneClickApproveOrder', - query: ` +export function oneClickApproveOrder({ + orderID, + instrumentType, + instrumentID, + buyerAccessToken, + clientMetadataID, +}: OneClickApproveOrderOptions): ZalgoPromise { + return callGraphQL({ + name: "OneClickApproveOrder", + query: ` mutation OneClickApproveOrder( $orderID : String! $instrumentType : String! $instrumentID : String! - $planID: String - $useExistingPlanning: Boolean ) { oneClickPayment( token: $orderID selectedInstrumentType : $instrumentType selectedInstrumentId : $instrumentID - selectedPlanId: $planID - useExistingPlanning: $useExistingPlanning ) { userId - ${ !enableOrdersApprovalSmartWallet ? accessTokenQuery : '' } + auth { + accessToken + } } } `, - variables: { orderID, instrumentType, instrumentID, planID, useExistingPlanning }, - headers: { - [HEADERS.ACCESS_TOKEN]: buyerAccessToken, - [HEADERS.CLIENT_CONTEXT]: orderID, - [HEADERS.CLIENT_METADATA_ID]: clientMetadataID || orderID - } - }).then(({ oneClickPayment }) => { - if (oneClickPayment?.auth?.accessToken) { - setBuyerAccessToken(oneClickPayment.auth.accessToken); - } - return { - payerID: oneClickPayment.userId - }; - }); + variables: { orderID, instrumentType, instrumentID }, + headers: { + [HEADERS.ACCESS_TOKEN]: buyerAccessToken, + [HEADERS.CLIENT_CONTEXT]: orderID, + [HEADERS.CLIENT_METADATA_ID]: clientMetadataID || orderID, + }, + }).then(({ oneClickPayment }) => { + if (oneClickPayment?.auth?.accessToken) { + setBuyerAccessToken(oneClickPayment.auth.accessToken); + } + return { + payerID: oneClickPayment.userId, + }; + }); } type SupplementalOrderInfo = {| - checkoutSession : {| - cart : {| - billingType? : string, - intent : $Values, - paymentId? : ?string, - billingToken? : ?string, - amounts : {| - total : {| - currencyFormatSymbolISOCurrency : string, - currencyValue : string, - currencyCode : string - |} - |}, - supplementary? : {| - initiationIntent? : string - |}, - category? : $Values - |}, - buyer? : {| - userId? : string + checkoutSession: {| + cart: {| + billingType?: string, + intent: $Values, + paymentId?: ?string, + billingToken?: ?string, + amounts: {| + total: {| + currencyFormatSymbolISOCurrency: string, + currencyValue: string, + currencyCode: string, |}, - flags : {| - isChangeShippingAddressAllowed? : boolean - |}, - payees? : $ReadOnlyArray<{| - merchantId? : string, - email? : {| - stringValue? : string - |} - |}> - |} + |}, + supplementary?: {| + initiationIntent?: string, + |}, + category?: $Values, + |}, + buyer?: {| + userId?: string, + |}, + flags: {| + isChangeShippingAddressAllowed?: boolean, + |}, + payees?: $ReadOnlyArray<{| + merchantId?: string, + email?: {| + stringValue?: string, + |}, + |}>, + |}, |}; -export type GetSupplementalOrderInfo = (string) => ZalgoPromise; +export type GetSupplementalOrderInfo = + (string) => ZalgoPromise; -export const getSupplementalOrderInfo : GetSupplementalOrderInfo = memoize(orderID => { +export const getSupplementalOrderInfo: GetSupplementalOrderInfo = memoize( + (orderID) => { return callGraphQL({ - name: 'GetCheckoutDetails', - query: ` + name: "GetCheckoutDetails", + query: ` query GetCheckoutDetails($orderID: String!) { checkoutSession(token: $orderID) { cart { @@ -796,40 +1223,41 @@ export const getSupplementalOrderInfo : GetSupplementalOrderInfo = memoize(order } } `, - variables: { orderID }, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID - } + variables: { orderID }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, }); -}); + }, +); type ShippingOrderInfo = {| - checkoutSession : {| - cart : {| - amounts : {| - total : {| - currencyFormatSymbolISOCurrency : string, - currencyValue : string, - currencyCode : string - |} - |}, - shippingAddress? : ShippingAddress, - shippingMethods? : $ReadOnlyArray - |}, - buyer? : {| - userId? : string + checkoutSession: {| + cart: {| + amounts: {| + total: {| + currencyFormatSymbolISOCurrency: string, + currencyValue: string, + currencyCode: string, |}, - flags : {| - isChangeShippingAddressAllowed? : boolean - |} - |} + |}, + shippingAddress?: ShippingAddress, + shippingMethods?: $ReadOnlyArray, + |}, + buyer?: {| + userId?: string, + |}, + flags: {| + isChangeShippingAddressAllowed?: boolean, + |}, + |}, |}; export type GetShippingOrderInfo = (string) => ZalgoPromise; -export const getShippingOrderInfo : GetShippingOrderInfo = orderID => { - return callGraphQL({ - name: 'GetCheckoutDetails', - query: ` +export const getShippingOrderInfo: GetShippingOrderInfo = (orderID) => { + return callGraphQL({ + name: "GetCheckoutDetails", + query: ` query GetCheckoutDetails($orderID: String!) { checkoutSession(token: $orderID) { cart { @@ -881,62 +1309,68 @@ export const getShippingOrderInfo : GetShippingOrderInfo = orderID => { } } `, - variables: { orderID }, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID - } - }); + variables: { orderID }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + }); }; export type DetailedOrderInfo = {| - checkoutSession : {| - merchant : {| - name : string + checkoutSession: {| + merchant: {| + name: string, + |}, + flags: {| + isShippingAddressRequired: boolean, + isDigitalGoodsIntegration: boolean, + isChangeShippingAddressAllowed: boolean, + |}, + allowedCardIssuers: $ReadOnlyArray, + cart: {| + amounts: {| + shippingAndHandling: {| + currencyValue: string, + currencySymbol: string, + currencyFormat: string, |}, - flags : {| - isShippingAddressRequired : boolean, - isDigitalGoodsIntegration : boolean, - isChangeShippingAddressAllowed : boolean + + tax: {| + currencyValue: string, + currencySymbol: string, + currencyFormat: string, |}, - allowedCardIssuers : $ReadOnlyArray, - cart : {| - amounts : {| - shippingAndHandling : {| - currencyValue : string, - currencySymbol : string, - currencyFormat : string - |}, - - tax : {| - currencyValue : string, - currencySymbol : string, - currencyFormat : string - |}, - - subtotal : {| - currencyValue : string, - currencySymbol : string, - currencyFormat : string - |}, - - total : {| - currencyFormatSymbolISOCurrency : string, - currencyValue : string, - currencyCode : $Values - |} - |}, - shippingAddress? : ShippingAddress, - shippingMethods? : $ReadOnlyArray - |} - |} -|}; -export type GetDetailedOrderInfo = (string, string) => ZalgoPromise; + subtotal: {| + currencyValue: string, + currencySymbol: string, + currencyFormat: string, + |}, -export const getDetailedOrderInfo : GetDetailedOrderInfo = (orderID, country) => { - return callGraphQL({ - name: 'GetCheckoutDetails', - query: ` + total: {| + currencyFormatSymbolISOCurrency: string, + currencyValue: string, + currencyCode: $Values, + |}, + |}, + shippingAddress?: ShippingAddress, + shippingMethods?: $ReadOnlyArray, + |}, + |}, +|}; + +export type GetDetailedOrderInfo = ( + string, + string, +) => ZalgoPromise; + +export const getDetailedOrderInfo: GetDetailedOrderInfo = ( + orderID, + country, +) => { + return callGraphQL({ + name: "GetCheckoutDetails", + query: ` query GetCheckoutDetails($orderID: String!, $country: CountryCodes!) { checkoutSession(token: $orderID) { merchant{ @@ -995,54 +1429,70 @@ export const getDetailedOrderInfo : GetDetailedOrderInfo = (orderID, country) => } } `, - variables: { orderID, country }, - headers: { - [HEADERS.CLIENT_CONTEXT]: orderID - } - }); + variables: { orderID, country }, + headers: { + [HEADERS.CLIENT_CONTEXT]: orderID, + }, + }); }; type UpdateButtonClientConfigOptions = {| - orderID : string, - fundingSource : $Values, - inline : boolean | void, - featureFlags: FeatureFlags, - userExperienceFlow? : string, - buttonSessionID? : ?string + orderID: string, + fundingSource: $Values, + inline: boolean | void, + featureFlags: FeatureFlags, + userExperienceFlow?: string, + buttonSessionID?: ?string, |}; -export function updateButtonClientConfig({ orderID, fundingSource, inline = false, userExperienceFlow, buttonSessionID, featureFlags } : UpdateButtonClientConfigOptions) : ZalgoPromise { - const experienceFlow = inline ? USER_EXPERIENCE_FLOW.INLINE : USER_EXPERIENCE_FLOW.INCONTEXT; - return updateClientConfig({ - orderID, - fundingSource, - integrationArtifact: INTEGRATION_ARTIFACT.PAYPAL_JS_SDK, - userExperienceFlow: userExperienceFlow ? userExperienceFlow : experienceFlow, - productFlow: PRODUCT_FLOW.SMART_PAYMENT_BUTTONS, - buttonSessionID, - featureFlags - }); +export function updateButtonClientConfig({ + orderID, + fundingSource, + inline = false, + userExperienceFlow, + buttonSessionID, + featureFlags, +}: UpdateButtonClientConfigOptions): ZalgoPromise { + const experienceFlow = inline + ? USER_EXPERIENCE_FLOW.INLINE + : USER_EXPERIENCE_FLOW.INCONTEXT; + return updateClientConfig({ + orderID, + fundingSource, + integrationArtifact: INTEGRATION_ARTIFACT.PAYPAL_JS_SDK, + userExperienceFlow: userExperienceFlow + ? userExperienceFlow + : experienceFlow, + productFlow: PRODUCT_FLOW.SMART_PAYMENT_BUTTONS, + buttonSessionID, + featureFlags, + }); } type ApproveCardPaymentOptions = {| - orderID : string, - vault : boolean, - branded : boolean, - clientID : string, - card : {| - cardNumber : string, - expirationDate? : string, - securityCode? : string, - postalCode? : string, - name? : string, - billingAddress? : string - |} + orderID: string, + vault: boolean, + branded: boolean, + clientID: string, + card: {| + cardNumber: string, + expirationDate?: string, + securityCode?: string, + postalCode?: string, + name?: string, + billingAddress?: string, + |}, |}; -export function approveCardPayment({ card, orderID, clientID, branded } : ApproveCardPaymentOptions) : ZalgoPromise { - return callGraphQL({ - name: 'ProcessPayment', - query: ` +export function approveCardPayment({ + card, + orderID, + clientID, + branded, +}: ApproveCardPaymentOptions): ZalgoPromise { + return callGraphQL({ + name: "ProcessPayment", + query: ` mutation ProcessPayment( $orderID: String! $clientID: String! @@ -1058,12 +1508,12 @@ export function approveCardPayment({ card, orderID, clientID, branded } : Approv ) } `, - variables: { orderID, clientID, card, branded }, - returnErrorObject: true - }).then((gqlResult) => { - if (!gqlResult) { - throw new Error('Error on GraphQL ProcessPayment mutation'); - } - return gqlResult; - }); + variables: { orderID, clientID, card, branded }, + returnErrorObject: true, + }).then((gqlResult) => { + if (!gqlResult) { + throw new Error("Error on GraphQL ProcessPayment mutation"); + } + return gqlResult; + }); } diff --git a/src/api/order.test.js b/src/api/order.test.js index 93a2021477..ff8864e25d 100644 --- a/src/api/order.test.js +++ b/src/api/order.test.js @@ -3,35 +3,36 @@ import { describe, expect, it, vi } from "vitest"; import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -const callRestAPI = vi.fn(() => - ZalgoPromise.reject({ - response: { - headers: {}, - }, - }) -); -const callSmartAPI = vi.fn(() => - ZalgoPromise.resolve({ - data: {}, - headers: {}, - }) -); - -// eslint-disable-next-line import/first import { getOrder, authorizeOrder, captureOrder, patchOrder } from "./order"; +import { callSmartAPI } from "./api"; vi.mock("./api", async () => { const actual = await vi.importActual("./api"); return { ...actual, - callRestAPI, - callSmartAPI, + callRestAPI: vi.fn(() => + ZalgoPromise.reject({ + message: "*_call_rest_api_error", + response: { + headers: {}, + }, + }), + ), + callSmartAPI: vi.fn(() => + ZalgoPromise.resolve({ + data: {}, + headers: {}, + }), + ), }; }); const orderAPIOptions = { facilitatorAccessToken: "", partnerAttributionID: "", + experiments: { + disableSmartAPI: false, + }, }; const orderID = "abc123"; @@ -41,7 +42,7 @@ describe("actions smart api fallback cases", () => { it("by default", async () => { await getOrder(orderID, orderAPIOptions); expect(callSmartAPI).toHaveBeenCalledWith( - expect.objectContaining({ eventName: "order_get" }) + expect.objectContaining({ eventName: "order_get" }), ); }); it("when forceRestAPI is true and callRestAPI throws", async () => { @@ -50,16 +51,28 @@ describe("actions smart api fallback cases", () => { forceRestAPI: true, }); expect(callSmartAPI).toHaveBeenCalledWith( - expect.objectContaining({ eventName: "order_get" }) + expect.objectContaining({ eventName: "order_get" }), ); }); + it("unless disableSmartApi is true", async () => { + await expect(() => + getOrder(orderID, { + ...orderAPIOptions, + forceRestAPI: true, + experiments: { + disableSmartAPI: true, + }, + }), + ).rejects.toThrowError("*_call_rest_api_error"); + expect(callSmartAPI).not.toHaveBeenCalled(); + }); }); describe("captureOrder calls the smart api", () => { it("by default", async () => { await captureOrder(orderID, orderAPIOptions); expect(callSmartAPI).toHaveBeenCalledWith( - expect.objectContaining({ eventName: "order_capture" }) + expect.objectContaining({ eventName: "order_capture" }), ); }); it("when forceRestAPI is true and callRestAPI throws", async () => { @@ -68,16 +81,28 @@ describe("actions smart api fallback cases", () => { forceRestAPI: true, }); expect(callSmartAPI).toHaveBeenCalledWith( - expect.objectContaining({ eventName: "order_capture" }) + expect.objectContaining({ eventName: "order_capture" }), ); }); + it("unless disableSmartApi is true", async () => { + await expect(() => + captureOrder(orderID, { + ...orderAPIOptions, + forceRestAPI: true, + experiments: { + disableSmartAPI: true, + }, + }), + ).rejects.toThrowError("*_call_rest_api_error"); + expect(callSmartAPI).not.toHaveBeenCalled(); + }); }); describe("authorizeOrder calls the smart api", () => { it("by default", async () => { await authorizeOrder(orderID, orderAPIOptions); expect(callSmartAPI).toHaveBeenCalledWith( - expect.objectContaining({ eventName: "order_authorize" }) + expect.objectContaining({ eventName: "order_authorize" }), ); }); it("when forceRestAPI is true and callRestAPI throws", async () => { @@ -86,16 +111,28 @@ describe("actions smart api fallback cases", () => { forceRestAPI: true, }); expect(callSmartAPI).toHaveBeenCalledWith( - expect.objectContaining({ eventName: "order_authorize" }) + expect.objectContaining({ eventName: "order_authorize" }), ); }); + it("unless disableSmartApi is true", async () => { + await expect(() => + authorizeOrder(orderID, { + ...orderAPIOptions, + forceRestAPI: true, + experiments: { + disableSmartAPI: true, + }, + }), + ).rejects.toThrowError("*_call_rest_api_error"); + expect(callSmartAPI).not.toHaveBeenCalled(); + }); }); describe("patchOrder calls the smart api", () => { it("by default", async () => { await patchOrder(orderID, {}, orderAPIOptions); expect(callSmartAPI).toHaveBeenCalledWith( - expect.objectContaining({ eventName: "order_patch" }) + expect.objectContaining({ eventName: "order_patch" }), ); }); it("when forceRestAPI is true and callRestAPI throws", async () => { @@ -105,11 +142,27 @@ describe("actions smart api fallback cases", () => { { ...orderAPIOptions, forceRestAPI: true, - } + }, ); expect(callSmartAPI).toHaveBeenCalledWith( - expect.objectContaining({ eventName: "order_patch" }) + expect.objectContaining({ eventName: "order_patch" }), ); }); + it("unless disableSmartApi is true", async () => { + await expect(() => + patchOrder( + orderID, + {}, + { + ...orderAPIOptions, + forceRestAPI: true, + experiments: { + disableSmartAPI: true, + }, + }, + ), + ).rejects.toThrowError("*_call_rest_api_error"); + expect(callSmartAPI).not.toHaveBeenCalled(); + }); }); }); diff --git a/src/api/payment.js b/src/api/payment.js index 9b2d3f838c..751cddc899 100644 --- a/src/api/payment.js +++ b/src/api/payment.js @@ -1,145 +1,179 @@ /* @flow */ -import type { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { FPTI_KEY } from '@paypal/sdk-constants/src'; +import type { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { FPTI_KEY } from "@paypal/sdk-constants/src"; -import { PAYMENTS_API_URL } from '../config'; -import { getLogger } from '../lib'; -import { FPTI_TRANSITION, FPTI_CONTEXT_TYPE, HEADERS } from '../constants'; -import type { ApplePayPayment } from '../payment-flows/types'; +import { PAYMENTS_API_URL } from "../config"; +import { getLogger } from "../lib"; +import { + FPTI_TRANSITION, + FPTI_CONTEXT_TYPE, + HEADERS, + PRODUCT_FLOW, +} from "../constants"; +import type { ApplePayPayment } from "../payment-flows/types"; -import { callGraphQL, callRestAPI } from './api'; +import { callGraphQL, callRestAPI } from "./api"; type PaymentAPIOptions = {| - facilitatorAccessToken : string, - buyerAccessToken? : ?string, - partnerAttributionID : ?string + facilitatorAccessToken: string, + buyerAccessToken?: ?string, + partnerAttributionID: ?string, |}; -export type PaymentCreateRequest = {| - -|}; +export type PaymentCreateRequest = {||}; export type PaymentResponse = {| - id : string, - links : $ReadOnlyArray<{| - method : string, - rel : string, - href : string - |}> + id: string, + links: $ReadOnlyArray<{| + method: string, + rel: string, + href: string, + |}>, |}; -export function createPayment(payment : PaymentCreateRequest, { facilitatorAccessToken, partnerAttributionID } : PaymentAPIOptions) : ZalgoPromise { - getLogger().info(`rest_api_create_payment_id`); - - return callRestAPI({ - accessToken: facilitatorAccessToken, - method: 'post', - eventName: 'v1_payments_payment_create', - url: `${ PAYMENTS_API_URL }`, - data: payment, - headers: { - [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || '' - } - }).then(body => { - - const paymentID = body && body.id; - - if (!paymentID) { - throw new Error(`Payment Api response error:\n\n${ JSON.stringify(body, null, 4) }`); - } - - getLogger().track({ - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.CREATE_PAYMENT, - [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.PAYMENT_ID, - [FPTI_KEY.TOKEN]: paymentID, - [FPTI_KEY.CONTEXT_ID]: paymentID - }); - - return body; +export function createPayment( + payment: PaymentCreateRequest, + { facilitatorAccessToken, partnerAttributionID }: PaymentAPIOptions, +): ZalgoPromise { + getLogger().info(`rest_api_create_payment_id`); + + return callRestAPI({ + accessToken: facilitatorAccessToken, + method: "post", + eventName: "v1_payments_payment_create", + url: `${PAYMENTS_API_URL}`, + data: payment, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + }, + }).then((body) => { + const paymentID = body && body.id; + + if (!paymentID) { + throw new Error( + `Payment Api response error:\n\n${JSON.stringify(body, null, 4)}`, + ); + } + + getLogger().track({ + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.CREATE_PAYMENT, + [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.PAYMENT_ID, + [FPTI_KEY.TOKEN]: paymentID, + [FPTI_KEY.CONTEXT_ID]: paymentID, }); -} -export function createPaymentID(payment : PaymentCreateRequest, { facilitatorAccessToken, partnerAttributionID } : PaymentAPIOptions) : ZalgoPromise { - return createPayment(payment, { facilitatorAccessToken, partnerAttributionID }) - .then(res => res.id); + return body; + }); } -export function createPaymentToken(payment : PaymentCreateRequest, { facilitatorAccessToken, partnerAttributionID } : PaymentAPIOptions) : ZalgoPromise { - return createPayment(payment, { facilitatorAccessToken, partnerAttributionID }) - .then(res => { - if (res.links && res.links.length) { - for (let i = 0; i < res.links.length; i++) { - if (res.links[i].method === 'REDIRECT' && res.links[i].rel === 'approval_url') { - const match = res.links[i].href.match(/token=((EC-)?[A-Z0-9]{17})/); - if (match) { - return match[1]; - } - } - } - } - - throw new Error(`Could not find payment token`); - }); +export function createPaymentID( + payment: PaymentCreateRequest, + { facilitatorAccessToken, partnerAttributionID }: PaymentAPIOptions, +): ZalgoPromise { + return createPayment(payment, { + facilitatorAccessToken, + partnerAttributionID, + }).then((res) => res.id); } -export function getPayment(paymentID : string, { facilitatorAccessToken, partnerAttributionID } : PaymentAPIOptions) : ZalgoPromise { - return callRestAPI({ - accessToken: facilitatorAccessToken, - eventName: 'v1_payments_payment_get', - url: `${ PAYMENTS_API_URL }/${ paymentID }`, - headers: { - [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || '' +export function createPaymentToken( + payment: PaymentCreateRequest, + { facilitatorAccessToken, partnerAttributionID }: PaymentAPIOptions, +): ZalgoPromise { + return createPayment(payment, { + facilitatorAccessToken, + partnerAttributionID, + }).then((res) => { + if (res.links && res.links.length) { + for (let i = 0; i < res.links.length; i++) { + if ( + res.links[i].method === "REDIRECT" && + res.links[i].rel === "approval_url" + ) { + const match = res.links[i].href.match(/token=((EC-)?[A-Z0-9]{17})/); + if (match) { + return match[1]; + } } - }); + } + } + + throw new Error(`Could not find payment token`); + }); } -export function executePayment(paymentID : string, payerID : string, { facilitatorAccessToken, partnerAttributionID } : PaymentAPIOptions) : ZalgoPromise { - return callRestAPI({ - accessToken: facilitatorAccessToken, - method: 'post', - eventName: 'v1_payments_payment_execute', - url: `${ PAYMENTS_API_URL }/${ paymentID }/execute`, - headers: { - [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || '' - }, - data: { - payer_id: payerID - } - }); +export function getPayment( + paymentID: string, + { facilitatorAccessToken, partnerAttributionID }: PaymentAPIOptions, +): ZalgoPromise { + return callRestAPI({ + accessToken: facilitatorAccessToken, + eventName: "v1_payments_payment_get", + url: `${PAYMENTS_API_URL}/${paymentID}`, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + }, + }); } -type PatchData = {| - -|}; +export function executePayment( + paymentID: string, + payerID: string, + { facilitatorAccessToken, partnerAttributionID }: PaymentAPIOptions, +): ZalgoPromise { + return callRestAPI({ + accessToken: facilitatorAccessToken, + method: "post", + eventName: "v1_payments_payment_execute", + url: `${PAYMENTS_API_URL}/${paymentID}/execute`, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + }, + data: { + payer_id: payerID, + }, + }); +} -export function patchPayment(paymentID : string, data : PatchData, { facilitatorAccessToken, partnerAttributionID } : PaymentAPIOptions) : ZalgoPromise { - const patchData = Array.isArray(data) ? { patch: data } : data; - - return callRestAPI({ - accessToken: facilitatorAccessToken, - method: 'patch', - eventName: 'v1_payments_payment_patch', - url: `${ PAYMENTS_API_URL }/${ paymentID }`, - data: patchData, - headers: { - [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || '' - } - }); +type PatchData = {||}; + +export function patchPayment( + paymentID: string, + data: PatchData, + { facilitatorAccessToken, partnerAttributionID }: PaymentAPIOptions, +): ZalgoPromise { + const patchData = Array.isArray(data) ? { patch: data } : data; + + return callRestAPI({ + accessToken: facilitatorAccessToken, + method: "patch", + eventName: "v1_payments_payment_patch", + url: `${PAYMENTS_API_URL}/${paymentID}`, + data: patchData, + headers: { + [HEADERS.PARTNER_ATTRIBUTION_ID]: partnerAttributionID || "", + }, + }); } -export function approveApplePayPayment(orderID : string, clientID : string, applePayPayment : ApplePayPayment) : ZalgoPromise { - const { token, billingContact, shippingContact } = applePayPayment; +export function approveApplePayPayment( + orderID: string, + clientID: string, + applePayPayment: ApplePayPayment, +): ZalgoPromise { + const { token, billingContact, shippingContact } = applePayPayment; - return callGraphQL({ - name: 'ApproveApplePayPayment', - query: ` + return callGraphQL({ + name: "ApproveApplePayPayment", + query: ` mutation ApproveApplePayPayment( $token: ApplePayPaymentToken! $orderID: String! $clientID : String! $billingContact: ApplePayPaymentContact! $shippingContact: ApplePayPaymentContact + $productFlow: String ) { approveApplePayPayment( token: $token @@ -147,14 +181,24 @@ export function approveApplePayPayment(orderID : string, clientID : string, appl clientID: $clientID billingContact: $billingContact shippingContact: $shippingContact + productFlow: $productFlow ) } `, - variables: { token, orderID, clientID, billingContact, shippingContact } - }).then((gqlResult) => { - if (!gqlResult || !gqlResult.approveApplePayPayment) { - throw new Error(`GraphQL GetApplePayPayment returned no applePayment object`); - } - return gqlResult.approveApplePayPayment; - }); + variables: { + token, + orderID, + clientID, + billingContact, + shippingContact, + productFlow: PRODUCT_FLOW.SMART_PAYMENT_BUTTONS, + }, + }).then((gqlResult) => { + if (!gqlResult || !gqlResult.approveApplePayPayment) { + throw new Error( + `GraphQL GetApplePayPayment returned no applePayment object`, + ); + } + return gqlResult.approveApplePayPayment; + }); } diff --git a/src/api/socket.js b/src/api/socket.js index 87ea710763..4f0a29a0b3 100644 --- a/src/api/socket.js +++ b/src/api/socket.js @@ -1,599 +1,715 @@ /* @flow */ /* eslint unicorn/prefer-add-event-listener: off, max-lines: off */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { uniqueID, noop, memoize, stringifyError, type Memoized } from '@krakenjs/belter/src'; -import { FPTI_KEY } from '@paypal/sdk-constants/src'; - -import { FIREBASE_SCRIPTS } from '../config'; -import { loadScript } from '../lib/util'; -import { getLogger } from '../lib'; -import { FPTI_CUSTOM_KEY, FPTI_STATE, FPTI_TRANSITION } from '../constants'; - -import { getFirebaseSessionToken } from './auth'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { + uniqueID, + noop, + memoize, + stringifyError, + type Memoized, +} from "@krakenjs/belter/src"; +import { FPTI_KEY } from "@paypal/sdk-constants/src"; + +import { FIREBASE_SCRIPTS } from "../config"; +import { loadScript } from "../lib/util"; +import { getLogger } from "../lib"; +import { FPTI_CUSTOM_KEY, FPTI_STATE, FPTI_TRANSITION } from "../constants"; + +import { getFirebaseSessionToken } from "./auth"; const MESSAGE_TYPE = { - REQUEST: ('request' : 'request'), - RESPONSE: ('response' : 'response') + REQUEST: ("request": "request"), + RESPONSE: ("response": "response"), }; const RESPONSE_STATUS = { - SUCCESS: ('success' : 'success'), - ERROR: ('error' : 'error') + SUCCESS: ("success": "success"), + ERROR: ("error": "error"), }; type RequestMessage = {| - source_app : string, - source_app_version : string, - target_app : string, - message_type : typeof MESSAGE_TYPE.REQUEST, - message_uid : string, - request_uid : string, - session_uid? : string, - message_name : string, - message_data : T + source_app: string, + source_app_version: string, + target_app: string, + message_type: typeof MESSAGE_TYPE.REQUEST, + message_uid: string, + request_uid: string, + session_uid?: string, + message_name: string, + message_data: T, |}; type ResponseMessage = {| - source_app : string, - source_app_version : string, - target_app : string, - message_type : typeof MESSAGE_TYPE.RESPONSE, - message_uid : string, - request_uid : string, - session_uid? : string, - message_name : string, - message_status : string, - message_data : T + source_app: string, + source_app_version: string, + target_app: string, + message_type: typeof MESSAGE_TYPE.RESPONSE, + message_uid: string, + request_uid: string, + session_uid?: string, + message_name: string, + message_status: string, + message_data: T, |}; type MessageSocketDriver = {| - send : (string) => void, - close : () => void, - onMessage : ((string) => void) => void, - onError : ((mixed) => void) => void, - onOpen : (() => void) => void, - onClose : ((Error) => void) => void, - isOpen : () => boolean + send: (string) => void, + close: () => void, + onMessage: ((string) => void) => void, + onError: ((mixed) => void) => void, + onOpen: (() => void) => void, + onClose: ((Error) => void) => void, + isOpen: () => boolean, |}; export type MessageSocketOptions = {| - sessionUID : string, - driver : () => MessageSocketDriver, - sourceApp : string, - sourceAppVersion : string, - targetApp : string, - retry? : boolean + sessionUID: string, + driver: () => MessageSocketDriver, + sourceApp: string, + sourceAppVersion: string, + targetApp: string, + retry?: boolean, |}; export type MessageSocket = {| - on : ( - name : string, - handler : ({| - data : Object - |}) => ZalgoPromise | Object, - opts? : {| - requireSessionUID? : boolean - |} - ) => {| - cancel : () => void + on: ( + name: string, + handler: ({| data: Object |}) => ZalgoPromise | Object, + opts?: {| + requireSessionUID?: boolean, + |}, + ) => {| + cancel: () => void, + |}, + send: ( // eslint-disable-line no-undef + name: string, + data: T, // eslint-disable-line no-undef + opts?: {| + timeout?: number, + requireSessionUID?: boolean, |}, - send : ( // eslint-disable-line no-undef - name : string, - data : T, // eslint-disable-line no-undef - opts? : {| - timeout? : number, - requireSessionUID? : boolean - |} - ) => ZalgoPromise, // eslint-disable-line no-undef - onError : ((mixed) => void) => void, - reconnect : () => ZalgoPromise, - close : () => void + ) => ZalgoPromise, // eslint-disable-line no-undef + onError: ((mixed) => void) => void, + reconnect: () => ZalgoPromise, + close: () => void, |}; -export function messageSocket({ sessionUID, driver, sourceApp, sourceAppVersion, targetApp, retry = true } : MessageSocketOptions) : MessageSocket { - - const receivedMessages = {}; - const responseListeners = {}; - const activeRequests = []; - - let requestListeners = {}; - let errorListeners : Array<(mixed) => void> = []; - - const onError = (handler : (mixed) => void) : void => { - errorListeners.push(handler); +export function messageSocket({ + sessionUID, + driver, + sourceApp, + sourceAppVersion, + targetApp, + retry = true, +}: MessageSocketOptions): MessageSocket { + const receivedMessages = {}; + const responseListeners = {}; + const activeRequests = []; + + let requestListeners = {}; + let errorListeners: Array<(mixed) => void> = []; + + const onError = (handler: (mixed) => void): void => { + errorListeners.push(handler); + }; + + const triggerError = (err: mixed) => { + for (const errorListener of errorListeners) { + errorListener(err); + } + }; + + type SendMessageData = {| + request_uid: string, + message_name: string, + message_status?: $Values, + message_type: $Values, + message_data: Object, + |}; + + const sendMessage = (socket, data: SendMessageData) => { + const messageUID = uniqueID(); + receivedMessages[messageUID] = true; + + const message = { + session_uid: sessionUID, + message_uid: messageUID, + source_app: sourceApp, + source_app_version: sourceAppVersion, + target_app: targetApp, + ...data, }; - const triggerError = (err : mixed) => { - for (const errorListener of errorListeners) { - errorListener(err); - } - }; - - type SendMessageData = {| - request_uid : string, - message_name : string, - message_status? : $Values, - message_type : $Values, - message_data : Object - |}; - - const sendMessage = (socket, data : SendMessageData) => { - const messageUID = uniqueID(); - receivedMessages[messageUID] = true; - - const message = { - session_uid: sessionUID, - message_uid: messageUID, - source_app: sourceApp, - source_app_version: sourceAppVersion, - target_app: targetApp, - ...data - }; + socket.send(JSON.stringify(message)); + }; + + const sendResponse = ( + socket, + { messageName, responseStatus, responseData, requestUID }, + ) => { + if (!socket.isOpen()) { + return; + } + + return sendMessage(socket, { + request_uid: requestUID, + message_name: messageName, + message_status: responseStatus, + message_type: MESSAGE_TYPE.RESPONSE, + message_data: responseData, + }); + }; - socket.send(JSON.stringify(message)); - }; + const onRequest = ( + socket, + { messageSessionUID, requestUID, messageName, messageData }, + ) => { + const activeRequest = new ZalgoPromise(); + activeRequests.push(activeRequest); - const sendResponse = (socket, { messageName, responseStatus, responseData, requestUID }) => { - if (!socket.isOpen()) { - return; - } - - return sendMessage(socket, { - request_uid: requestUID, - message_name: messageName, - message_status: responseStatus, - message_type: MESSAGE_TYPE.RESPONSE, - message_data: responseData + return ZalgoPromise.try(() => { + const requestListener = requestListeners[messageName]; + + if (!requestListener) { + throw new Error(`No listener found for name: ${messageName}`); + } + + const { handler, requireSessionUID } = requestListener; + + if (requireSessionUID && messageSessionUID !== sessionUID) { + throw new Error( + `Incorrect sessionUID: ${messageSessionUID || "undefined"}`, + ); + } + + return handler({ data: messageData }); + }) + .then( + (res) => { + sendResponse(socket, { + responseStatus: RESPONSE_STATUS.SUCCESS, + responseData: res, + messageName, + requestUID, + }); + }, + (err) => { + const res = { + message: err && err.message ? err.message : "Unknown error", + }; + sendResponse(socket, { + responseStatus: RESPONSE_STATUS.ERROR, + responseData: res, + messageName, + messageSessionUID, + requestUID, + }); + }, + ) + .finally(() => { + activeRequest.resolve(); + activeRequests.splice(activeRequests.indexOf(activeRequest), 1); + }); + }; + + const onResponse = ({ + messageName, + requestUID, + messageSessionUID, + responseStatus, + messageData, + }) => { + const { listenerPromise, requireSessionUID } = + responseListeners[requestUID] || {}; + + if (!listenerPromise) { + return triggerError( + new Error( + `Could not find response listener for ${messageName} with id: ${requestUID}`, + ), + ); + } + + if (requireSessionUID && messageSessionUID !== sessionUID) { + return triggerError( + new Error(`Incorrect sessionUID: ${messageSessionUID || "undefined"}`), + ); + } + + delete responseListeners[requestUID]; + + if (responseStatus === RESPONSE_STATUS.SUCCESS) { + listenerPromise.resolve({ data: messageData }); + } else if (responseStatus === RESPONSE_STATUS.ERROR) { + listenerPromise.reject(new Error(messageData.message)); + } else { + listenerPromise.reject( + new Error(`Can not handle response status: ${status || "undefined"}`), + ); + } + }; + + const onMessage = (socket, rawData) => { + let parsedData: RequestMessage | ResponseMessage; + + try { + parsedData = JSON.parse(rawData); + } catch (err) { + throw new Error(`Could not parse socket message: ${rawData}`); + } + + if (!parsedData) { + throw new Error(`No data passed from socket message`); + } + + let { + session_uid: messageSessionUID, + request_uid: requestUID, + message_uid: messageUID, + message_name: messageName, + message_type: messageType, + message_data: messageData, + message_status: responseStatus, + target_app: messageTargetApp, + } = parsedData; + + requestUID = requestUID || parsedData.request_id; + + if (messageUID && receivedMessages[messageUID]) { + return; + } + + if ( + !messageUID || + !requestUID || + !messageName || + !messageType || + !messageTargetApp + ) { + throw new Error(`Incomplete message: ${rawData}`); + } + + receivedMessages[messageUID] = true; + + if (messageType === MESSAGE_TYPE.REQUEST) { + return onRequest(socket, { + messageSessionUID, + requestUID, + messageName, + messageData, + }); + } else if (messageType === MESSAGE_TYPE.RESPONSE) { + return onResponse({ + messageName, + requestUID, + messageSessionUID, + responseStatus, + messageData, + }); + } else { + throw new Error(`Unhandleable message type: ${messageType}`); + } + }; + + let closed = false; + let retryDelay; + + const updateRetryDelay = () => { + if (retry) { + retryDelay = retryDelay ? retryDelay * 2 : 1; + } + }; + + let socketPromise; + let retryPromise; + + const init = () => { + socketPromise = ZalgoPromise.try(() => { + if (retryDelay) { + retryPromise = ZalgoPromise.delay(retryDelay); + return retryPromise; + } + }).then(() => { + retryPromise = null; + const instance = driver(); + + const connectionPromise = new ZalgoPromise((resolve, reject) => { + instance.onOpen(() => { + closed = false; + retryDelay = 0; + resolve(instance); }); - }; - - const onRequest = (socket, { messageSessionUID, requestUID, messageName, messageData }) => { - const activeRequest = new ZalgoPromise(); - activeRequests.push(activeRequest); - return ZalgoPromise.try(() => { - const requestListener = requestListeners[messageName]; - - if (!requestListener) { - throw new Error(`No listener found for name: ${ messageName }`); - } - - const { handler, requireSessionUID } = requestListener; - - if (requireSessionUID && messageSessionUID !== sessionUID) { - throw new Error(`Incorrect sessionUID: ${ messageSessionUID || 'undefined' }`); - } - - return handler({ data: messageData }); - }).then(res => { - sendResponse(socket, { responseStatus: RESPONSE_STATUS.SUCCESS, responseData: res, messageName, requestUID }); - }, err => { - const res = { message: (err && err.message) ? err.message : 'Unknown error' }; - sendResponse(socket, { responseStatus: RESPONSE_STATUS.ERROR, responseData: res, messageName, messageSessionUID, requestUID }); - }).finally(() => { - activeRequest.resolve(); - activeRequests.splice(activeRequests.indexOf(activeRequest), 1); + instance.onClose((err) => { + closed = true; + reject(err || new Error("socket closed")); + if (retry) { + updateRetryDelay(); + init(); + } }); - }; - const onResponse = ({ messageName, requestUID, messageSessionUID, responseStatus, messageData }) => { - const { listenerPromise, requireSessionUID } = responseListeners[requestUID] || {}; - - if (!listenerPromise) { - return triggerError(new Error(`Could not find response listener for ${ messageName } with id: ${ requestUID }`)); - } - - if (requireSessionUID && messageSessionUID !== sessionUID) { - return triggerError(new Error(`Incorrect sessionUID: ${ messageSessionUID || 'undefined' }`)); - } - - delete responseListeners[requestUID]; - - if (responseStatus === RESPONSE_STATUS.SUCCESS) { - listenerPromise.resolve({ data: messageData }); - } else if (responseStatus === RESPONSE_STATUS.ERROR) { - listenerPromise.reject(new Error(messageData.message)); - } else { - listenerPromise.reject(new Error(`Can not handle response status: ${ status || 'undefined' }`)); - } - }; - - const onMessage = (socket, rawData) => { - let parsedData : RequestMessage | ResponseMessage; - - try { - parsedData = JSON.parse(rawData); - } catch (err) { - throw new Error(`Could not parse socket message: ${ rawData }`); - } - - if (!parsedData) { - throw new Error(`No data passed from socket message`); - } - - let { - session_uid: messageSessionUID, - request_uid: requestUID, - message_uid: messageUID, - message_name: messageName, - message_type: messageType, - message_data: messageData, - message_status: responseStatus, - target_app: messageTargetApp - } = parsedData; - - requestUID = requestUID || parsedData.request_id; - - if (messageUID && receivedMessages[messageUID]) { - return; - } - - if (!messageUID || !requestUID || !messageName || !messageType || !messageTargetApp) { - throw new Error(`Incomplete message: ${ rawData }`); - } - - receivedMessages[messageUID] = true; + instance.onError((err) => { + reject(err); + triggerError(err); + }); + }); - if (messageType === MESSAGE_TYPE.REQUEST) { - return onRequest(socket, { messageSessionUID, requestUID, messageName, messageData }); - } else if (messageType === MESSAGE_TYPE.RESPONSE) { - return onResponse({ messageName, requestUID, messageSessionUID, responseStatus, messageData }); - - } else { - throw new Error(`Unhandleable message type: ${ messageType }`); - } - }; + instance.onMessage((rawMessage) => { + connectionPromise.then((socket) => { + return onMessage(socket, rawMessage); + }); + }); - let closed = false; - let retryDelay; + return connectionPromise; + }); - const updateRetryDelay = () => { - if (retry) { - retryDelay = retryDelay ? (retryDelay * 2) : 1; - } - }; + socketPromise.catch(noop); + }; - let socketPromise; - let retryPromise; - - const init = () => { - socketPromise = ZalgoPromise.try(() => { - if (retryDelay) { - retryPromise = ZalgoPromise.delay(retryDelay); - return retryPromise; - } - }).then(() => { - retryPromise = null; - const instance = driver(); - - const connectionPromise = new ZalgoPromise((resolve, reject) => { - instance.onOpen(() => { - closed = false; - retryDelay = 0; - resolve(instance); - }); - - instance.onClose(err => { - closed = true; - reject(err || new Error('socket closed')); - if (retry) { - updateRetryDelay(); - init(); - } - }); - - instance.onError(err => { - reject(err); - triggerError(err); - }); - }); + init(); - instance.onMessage(rawMessage => { - connectionPromise.then(socket => { - return onMessage(socket, rawMessage); - }); - }); + const on = (name, handler, { requireSessionUID = true } = {}) => { + if (requestListeners[name]) { + throw new Error(`Listener already registered for name: ${name}`); + } - return connectionPromise; - }); - - socketPromise.catch(noop); + requestListeners[name] = { + handler, + requireSessionUID, }; - init(); - - const on = (name, handler, { requireSessionUID = true } = {}) => { - if (requestListeners[name]) { - throw new Error(`Listener already registered for name: ${ name }`); - } - - requestListeners[name] = { - handler, - requireSessionUID - }; - - return { - cancel: () => { - delete requestListeners[name]; - } - }; + return { + cancel: () => { + delete requestListeners[name]; + }, }; + }; + + const send = ( + messageName, + messageData: T, + { requireSessionUID = true, timeout = 0 } = {}, + ): ZalgoPromise => { + return socketPromise.then((socket) => { + const requestUID = uniqueID(); + + const listenerPromise = new ZalgoPromise(); + responseListeners[requestUID] = { + listenerPromise, + requireSessionUID, + }; + + sendMessage(socket, { + request_uid: requestUID, + message_name: messageName, + message_type: MESSAGE_TYPE.REQUEST, + message_data: messageData, + }); + + if (timeout) { + setTimeout(() => { + listenerPromise.reject( + new Error( + `Timeoued out waiting for ${messageName} response after ${timeout}ms`, + ), + ); + }, timeout); + } + + return listenerPromise; + }); + }; - const send = (messageName, messageData : T, { requireSessionUID = true, timeout = 0 } = {}) : ZalgoPromise => { - return socketPromise.then(socket => { - const requestUID = uniqueID(); - - const listenerPromise = new ZalgoPromise(); - responseListeners[requestUID] = { - listenerPromise, - requireSessionUID - }; - - sendMessage(socket, { - request_uid: requestUID, - message_name: messageName, - message_type: MESSAGE_TYPE.REQUEST, - message_data: messageData - }); + const reconnect = () => { + return ZalgoPromise.try(() => { + if (!closed) { + return socketPromise; + } - if (timeout) { - setTimeout(() => { - listenerPromise.reject(new Error(`Timeoued out waiting for ${ messageName } response after ${ timeout }ms`)); - }, timeout); - } + if (retryPromise) { + retryPromise.resolve(); + return socketPromise; + } - return listenerPromise; - }); - }; + retryDelay = 0; + return init(); + }).then(noop); + }; - const reconnect = () => { - return ZalgoPromise.try(() => { - if (!closed) { - return socketPromise; - } - - if (retryPromise) { - retryPromise.resolve(); - return socketPromise; - } - - retryDelay = 0; - return init(); - }).then(noop); - }; + const close = () => { + retry = false; - const close = () => { - retry = false; + requestListeners = {}; + errorListeners = []; - requestListeners = {}; - errorListeners = []; + for (const requestUID of Object.keys(responseListeners)) { + const { listenerPromise } = responseListeners[requestUID]; + listenerPromise.asyncReject(new Error(`Socket closed`)); + } - for (const requestUID of Object.keys(responseListeners)) { - const { listenerPromise } = responseListeners[requestUID]; - listenerPromise.asyncReject(new Error(`Socket closed`)); - } + ZalgoPromise.all(activeRequests).then(() => { + return socketPromise.then((socket) => socket.close(), noop); + }); + }; - ZalgoPromise.all(activeRequests).then(() => { - return socketPromise.then( - socket => socket.close(), - noop - ); - }); - }; - - return { on, send, onError, reconnect, close }; + return { on, send, onError, reconnect, close }; } type WebSocketOptions = {| - sessionUID : string, - url : string, - sourceApp : string, - sourceAppVersion : string, - targetApp : string + sessionUID: string, + url: string, + sourceApp: string, + sourceAppVersion: string, + targetApp: string, |}; - -export function webSocket({ sessionUID, url, sourceApp, sourceAppVersion, targetApp } : WebSocketOptions) : MessageSocket { - const driver = () => { - const socket = new WebSocket(url); - - return { - send: (data) => { - socket.send(data); - }, - close: () => { - socket.close(); - }, - onMessage: (handler) => { - socket.onmessage = (event) => { - const data = event.data; - - if (typeof data !== 'string' || !data) { - throw new TypeError(`Expected string data from web socket`); - } - - handler(data); - }; - }, - onError: (handler) => { - socket.onerror = () => { - handler(new Error(`The socket encountered an error`)); - }; - }, - onOpen: (handler) => { - socket.onopen = () => handler(); - }, - onClose: (handler) => { - socket.onclose = () => handler(new Error(`Websocket connection closed`)); - }, - isOpen: () => { - return socket.readyState === WebSocket.OPEN; - } + +export function webSocket({ + sessionUID, + url, + sourceApp, + sourceAppVersion, + targetApp, +}: WebSocketOptions): MessageSocket { + const driver = () => { + const socket = new WebSocket(url); + + return { + send: (data) => { + socket.send(data); + }, + close: () => { + socket.close(); + }, + onMessage: (handler) => { + socket.onmessage = (event) => { + const data = event.data; + + if (typeof data !== "string" || !data) { + throw new TypeError(`Expected string data from web socket`); + } + + handler(data); + }; + }, + onError: (handler) => { + socket.onerror = () => { + handler(new Error(`The socket encountered an error`)); }; + }, + onOpen: (handler) => { + socket.onopen = () => handler(); + }, + onClose: (handler) => { + socket.onclose = () => + handler(new Error(`Websocket connection closed`)); + }, + isOpen: () => { + return socket.readyState === WebSocket.OPEN; + }, }; - - return messageSocket({ sessionUID, driver, sourceApp, sourceAppVersion, targetApp }); + }; + + return messageSocket({ + sessionUID, + driver, + sourceApp, + sourceAppVersion, + targetApp, + }); } export type FirebaseConfig = {| - apiKey : string, - authDomain : string, - databaseURL : string, - projectId : string, - storageBucket : string, - messagingSenderId : string, - appId : string, - measurementId : string + apiKey: string, + authDomain: string, + databaseURL: string, + projectId: string, + storageBucket: string, + messagingSenderId: string, + appId: string, + measurementId: string, |}; export type FirebaseSocketOptions = {| - sessionUID : string, - config : FirebaseConfig, - sourceApp : string, - sourceAppVersion : string, - targetApp : string + sessionUID: string, + config: FirebaseConfig, + sourceApp: string, + sourceAppVersion: string, + targetApp: string, |}; type FirebaseSDK = {| - initializeApp : (FirebaseConfig) => void, - auth : () => {| - signInWithCustomToken : (string) => ZalgoPromise + initializeApp: (FirebaseConfig) => void, + auth: () => {| + signInWithCustomToken: (string) => ZalgoPromise, + |}, + database: {| + INTERNAL: {| + forceWebSockets: () => void, + |}, + (): {| + ref: (string) => {| + // eslint-disable-next-line no-undef + set: (T) => void, + // eslint-disable-next-line no-undef + on: ("value", (T) => void, (Error) => void) => void, + |}, + goOnline: () => void, + goOffline: () => void, |}, - database : {| - INTERNAL : {| - forceWebSockets : () => void - |}, - () : {| - ref : (string) => {| - // eslint-disable-next-line no-undef - set : (T) => void, - // eslint-disable-next-line no-undef - on : ('value', (T) => void, (Error) => void) => void - |}, - goOnline : () => void, - goOffline : () => void - |} - |} + |}, |}; type LoadFirebaseSDK = (FirebaseConfig) => ZalgoPromise; - -export const loadFirebaseSDK : Memoized = memoize(config => { - return ZalgoPromise.try(() => { - if (!window.firebase || !window.firebase.auth || !window.firebase.database) { - return loadScript(FIREBASE_SCRIPTS.APP).then(() => { - return ZalgoPromise.all([ - loadScript(FIREBASE_SCRIPTS.AUTH), - loadScript(FIREBASE_SCRIPTS.DATABASE) - ]); - }); - } - }).then(() => { - const firebase = window.firebase; - if (!firebase) { - throw new Error(`Firebase failed to load`); - } - - firebase.initializeApp(config); - return firebase; - }); +export const loadFirebaseSDK: Memoized = memoize((config) => { + return ZalgoPromise.try(() => { + if ( + !window.firebase || + !window.firebase.auth || + !window.firebase.database + ) { + return loadScript(FIREBASE_SCRIPTS.APP).then(() => { + return ZalgoPromise.all([ + loadScript(FIREBASE_SCRIPTS.AUTH), + loadScript(FIREBASE_SCRIPTS.DATABASE), + ]); + }); + } + }).then(() => { + const firebase = window.firebase; + + if (!firebase) { + throw new Error(`Firebase failed to load`); + } + + firebase.initializeApp(config); + return firebase; + }); }); - -export function firebaseSocket({ sessionUID, config, sourceApp, sourceAppVersion, targetApp } : FirebaseSocketOptions) : MessageSocket { - const driver = () => { - let open = false; - - const onMessageHandlers = []; - const onErrorHandlers = []; - const onCloseHandlers = []; - const onOpenHandlers = []; - - const error = (err) => { - for (const handler of onErrorHandlers) { - handler(err); - } - }; - const databasePromise = ZalgoPromise.hash({ - firebase: loadFirebaseSDK(config), - sessionToken: getFirebaseSessionToken(sessionUID) - }).then(({ firebase, sessionToken }) => { - const valueCallback = (res) => { - const messages = res.val() || {}; - - for (const messageID of Object.keys(messages)) { - const message = messages[messageID]; - for (const handler of onMessageHandlers) { - handler(message); - } - } - }; - - return firebase.auth().signInWithCustomToken(sessionToken).then(() => { - const database = firebase.database(); - firebase.database.INTERNAL.forceWebSockets(); - - open = true; - - getLogger().info('firebase_connection_opened').track({ - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.FIREBASE_CONNECTION_OPENED - }).flush(); - - for (const handler of onOpenHandlers) { - handler(); - } - - database.ref(`users/${ sessionUID }/messages`).on('value', valueCallback, err => { - error(err); - }); - - database.goOnline(); - return database; +export function firebaseSocket({ + sessionUID, + config, + sourceApp, + sourceAppVersion, + targetApp, +}: FirebaseSocketOptions): MessageSocket { + const driver = () => { + let open = false; + + const onMessageHandlers = []; + const onErrorHandlers = []; + const onCloseHandlers = []; + const onOpenHandlers = []; + + const error = (err) => { + for (const handler of onErrorHandlers) { + handler(err); + } + }; + + const databasePromise = ZalgoPromise.hash({ + firebase: loadFirebaseSDK(config), + sessionToken: getFirebaseSessionToken(sessionUID), + }).then(({ firebase, sessionToken }) => { + const valueCallback = (res) => { + const messages = res.val() || {}; + + for (const messageID of Object.keys(messages)) { + const message = messages[messageID]; + for (const handler of onMessageHandlers) { + handler(message); + } + } + }; + + return firebase + .auth() + .signInWithCustomToken(sessionToken) + .then(() => { + const database = firebase.database(); + firebase.database.INTERNAL.forceWebSockets(); + + open = true; + + getLogger() + .info("firebase_connection_opened") + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.FIREBASE_CONNECTION_OPENED, + }) + .flush(); + + for (const handler of onOpenHandlers) { + handler(); + } + + database + .ref(`users/${sessionUID}/messages`) + .on("value", valueCallback, (err) => { + error(err); }); - }); - databasePromise.catch(err => { - getLogger().warn('firebase_connection_errored', { err: stringifyError(err) }).track({ - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.FIREBASE_CONNECTION_ERRORED, - [FPTI_CUSTOM_KEY.ERR_DESC]: stringifyError(err) - }).flush(); + database.goOnline(); + return database; }); + }); - return { - send: (data) => { - databasePromise.then(database => { - return database.ref(`users/${ sessionUID }/messages/${ uniqueID() }`).set(data); - }).catch(error); - }, - close: () => { - databasePromise.then(database => { - database.goOffline(); - }); - }, - onMessage: (handler) => { - onMessageHandlers.push(handler); - }, - onError: (handler) => { - onErrorHandlers.push(handler); - }, - onOpen: (handler) => { - if (open) { - handler(); - } else { - onOpenHandlers.push(handler); - } - }, - onClose: (handler) => { - onCloseHandlers.push(handler); - }, - isOpen: () => { - return open; - } - }; - }; + databasePromise.catch((err) => { + getLogger() + .warn("firebase_connection_errored", { err: stringifyError(err) }) + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.FIREBASE_CONNECTION_ERRORED, + [FPTI_CUSTOM_KEY.ERR_DESC]: stringifyError(err), + }) + .flush(); + }); - return messageSocket({ sessionUID, driver, sourceApp, sourceAppVersion, targetApp }); + return { + send: (data) => { + databasePromise + .then((database) => { + return database + .ref(`users/${sessionUID}/messages/${uniqueID()}`) + .set(data); + }) + .catch(error); + }, + close: () => { + databasePromise.then((database) => { + database.goOffline(); + }); + }, + onMessage: (handler) => { + onMessageHandlers.push(handler); + }, + onError: (handler) => { + onErrorHandlers.push(handler); + }, + onOpen: (handler) => { + if (open) { + handler(); + } else { + onOpenHandlers.push(handler); + } + }, + onClose: (handler) => { + onCloseHandlers.push(handler); + }, + isOpen: () => { + return open; + }, + }; + }; + + return messageSocket({ + sessionUID, + driver, + sourceApp, + sourceAppVersion, + targetApp, + }); } diff --git a/src/api/subscription.js b/src/api/subscription.js index f792d56768..4a64eef107 100644 --- a/src/api/subscription.js +++ b/src/api/subscription.js @@ -1,158 +1,221 @@ /* @flow */ -import type { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { request } from '@krakenjs/belter/src'; +import type { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { request } from "@krakenjs/belter/src"; -import { CREATE_SUBSCRIPTIONS_API_URL, SMART_API_URI } from '../config'; -import { getLogger } from '../lib'; +import { CREATE_SUBSCRIPTIONS_API_URL, SMART_API_URI } from "../config"; +import { getLogger } from "../lib"; -import { callSmartAPI } from './api'; -import { createAccessToken } from './auth'; +import { callSmartAPI } from "./api"; +import { createAccessToken } from "./auth"; export type SubscriptionCreateRequest = {| - plan_id : string, - start_time? : string, - quantity? : string, - shipping_amount? : {| - currency_code : string, - value : string - |}, - auto_renewal? : boolean, - application_context? : {| - brand_name? : string, - locale? : string, - shipping_preference? : string, - user_action? : string - |} + plan_id: string, + start_time?: string, + quantity?: string, + shipping_amount?: {| + currency_code: string, + value: string, + |}, + auto_renewal?: boolean, + application_context?: {| + brand_name?: string, + locale?: string, + shipping_preference?: string, + user_action?: string, + |}, |}; type SubscriptionOptions = {| - clientID : string, - merchantID? : $ReadOnlyArray, - partnerAttributionID? : ?string + clientID: string, + merchantID?: $ReadOnlyArray, + partnerAttributionID?: ?string, |}; - // Create Subscription Request method -function createRequest(accessToken : string, subscriptionPayload : SubscriptionCreateRequest, partnerAttributionID? : ?string, eventName : string) : ZalgoPromise { - const headers : Object = { - 'Authorization': `Bearer ${ accessToken }`, - 'PayPal-Partner-Attribution-Id': partnerAttributionID || '' - }; - - return request({ - method: `post`, - url: CREATE_SUBSCRIPTIONS_API_URL, - headers, - json: subscriptionPayload - }).then(({ body }) : string => { - - if (!body || !body.id) { - getLogger().warn(`rest_api_${ eventName }_error`); - throw new Error(`Create Subscription Api response error:\n\n${ JSON.stringify(body, null, 4) }`); - } - return body.id; - }); -} - -export function createSubscription(accessToken : string, subscriptionPayload : SubscriptionCreateRequest, { partnerAttributionID, merchantID, clientID } : SubscriptionOptions) : ZalgoPromise { - getLogger().info(`rest_api_create_subscription_id`); - - if (!subscriptionPayload) { - throw new Error(`Expected subscription payload to be passed`); +function createRequest( + accessToken: string, + subscriptionPayload: SubscriptionCreateRequest, + partnerAttributionID?: ?string, + eventName: string, +): ZalgoPromise { + const headers: Object = { + Authorization: `Bearer ${accessToken}`, + "PayPal-Partner-Attribution-Id": partnerAttributionID || "", + }; + + return request({ + method: `post`, + url: CREATE_SUBSCRIPTIONS_API_URL, + headers, + json: subscriptionPayload, + }).then(({ body }): string => { + if (!body || !body.id) { + getLogger().warn(`rest_api_${eventName}_error`); + throw new Error( + `Create Subscription Api response error:\n\n${JSON.stringify( + body, + null, + 4, + )}`, + ); } - - if (merchantID && merchantID[0]) { - getLogger().info(`rest_api_subscriptions_recreate_access_token`); - const eventName = 'v1_billing_subscriptions_recreate'; - - return createAccessToken(clientID, { targetSubject: merchantID[0] }).then((thirdPartyAccessToken) : ZalgoPromise => { - return createRequest(thirdPartyAccessToken, subscriptionPayload, partnerAttributionID, eventName); - }); - } - - if (!accessToken) { - throw new Error(`Access token not passed`); - } - - const eventName = 'v1_billing_subscriptions_create'; - return createRequest(accessToken, subscriptionPayload, partnerAttributionID, eventName); + return body.id; + }); } -// Revise Subscription API request -function reviseRequest(accessToken : string, subscriptionID : string, subscriptionPayload : ?SubscriptionCreateRequest, partnerAttributionID? : ?string, eventName : string) : ZalgoPromise { - const headers : Object = { - 'Authorization': `Bearer ${ accessToken }`, - 'PayPal-Partner-Attribution-Id': partnerAttributionID || '' - }; - - return request({ - method: `post`, - url: `${ CREATE_SUBSCRIPTIONS_API_URL }/${ subscriptionID }/revise`, - headers, - json: subscriptionPayload - }).then(({ body, status }) : string => { - - if (status !== 200) { - getLogger().warn(`rest_api_${ eventName }_error`); - throw new Error(`Revise Subscription Api HTTP-${ status } response: error:\n\n${ JSON.stringify(body, null, 4) }`); - } - // for revision flow the same subscription id is returned - return subscriptionID; - }); +export function createSubscription( + accessToken: string, + subscriptionPayload: SubscriptionCreateRequest, + { partnerAttributionID, merchantID, clientID }: SubscriptionOptions, +): ZalgoPromise { + getLogger().info(`rest_api_create_subscription_id`); + + if (!subscriptionPayload) { + throw new Error(`Expected subscription payload to be passed`); + } + + if (merchantID && merchantID[0]) { + getLogger().info(`rest_api_subscriptions_recreate_access_token`); + const eventName = "v1_billing_subscriptions_recreate"; + + return createAccessToken(clientID, { targetSubject: merchantID[0] }).then( + (thirdPartyAccessToken): ZalgoPromise => { + return createRequest( + thirdPartyAccessToken, + subscriptionPayload, + partnerAttributionID, + eventName, + ); + }, + ); + } + + if (!accessToken) { + throw new Error(`Access token not passed`); + } + + const eventName = "v1_billing_subscriptions_create"; + return createRequest( + accessToken, + subscriptionPayload, + partnerAttributionID, + eventName, + ); } -export function reviseSubscription(accessToken : string, subscriptionID : string, subscriptionPayload : ?SubscriptionCreateRequest, { partnerAttributionID, merchantID, clientID } : SubscriptionOptions) : ZalgoPromise { - getLogger().info(`rest_api_create_subscription_id`); - - if (!subscriptionID) { - throw new Error(`Expected subscription id to be passed as first argument to revise subscription api`); - } - - if (!subscriptionPayload) { - throw new Error(`Expected subscription payload to be passed`); - } - - if (merchantID && merchantID[0]) { - getLogger().info(`rest_api_subscriptions_recreate_access_token`); - const eventName = 'v1_billing_subscriptions_revise_recreate'; - - return createAccessToken(clientID, { targetSubject: merchantID[0] }).then((thirdPartyAccessToken) : ZalgoPromise => { - return reviseRequest(thirdPartyAccessToken, subscriptionID, subscriptionPayload, partnerAttributionID, eventName); - }); - } - - if (!accessToken) { - throw new Error(`Access token not passed`); +// Revise Subscription API request +function reviseRequest( + accessToken: string, + subscriptionID: string, + subscriptionPayload: ?SubscriptionCreateRequest, + partnerAttributionID?: ?string, + eventName: string, +): ZalgoPromise { + const headers: Object = { + Authorization: `Bearer ${accessToken}`, + "PayPal-Partner-Attribution-Id": partnerAttributionID || "", + }; + + return request({ + method: `post`, + url: `${CREATE_SUBSCRIPTIONS_API_URL}/${subscriptionID}/revise`, + headers, + json: subscriptionPayload, + }).then(({ body, status }): string => { + if (status !== 200) { + getLogger().warn(`rest_api_${eventName}_error`); + throw new Error( + `Revise Subscription Api HTTP-${status} response: error:\n\n${JSON.stringify( + body, + null, + 4, + )}`, + ); } + // for revision flow the same subscription id is returned + return subscriptionID; + }); +} - const eventName = 'v1_billing_subscriptions_revise_create'; - return reviseRequest(accessToken, subscriptionID, subscriptionPayload, partnerAttributionID, eventName); +export function reviseSubscription( + accessToken: string, + subscriptionID: string, + subscriptionPayload: ?SubscriptionCreateRequest, + { partnerAttributionID, merchantID, clientID }: SubscriptionOptions, +): ZalgoPromise { + getLogger().info(`rest_api_create_subscription_id`); + + if (!subscriptionID) { + throw new Error( + `Expected subscription id to be passed as first argument to revise subscription api`, + ); + } + + if (!subscriptionPayload) { + throw new Error(`Expected subscription payload to be passed`); + } + + if (merchantID && merchantID[0]) { + getLogger().info(`rest_api_subscriptions_recreate_access_token`); + const eventName = "v1_billing_subscriptions_revise_recreate"; + + return createAccessToken(clientID, { targetSubject: merchantID[0] }).then( + (thirdPartyAccessToken): ZalgoPromise => { + return reviseRequest( + thirdPartyAccessToken, + subscriptionID, + subscriptionPayload, + partnerAttributionID, + eventName, + ); + }, + ); + } + + if (!accessToken) { + throw new Error(`Access token not passed`); + } + + const eventName = "v1_billing_subscriptions_revise_create"; + return reviseRequest( + accessToken, + subscriptionID, + subscriptionPayload, + partnerAttributionID, + eventName, + ); } type SubscriptionAPICredentials = {| - buyerAccessToken : ?string + buyerAccessToken: ?string, |}; export type SubscriptionResponse = {||}; -export function activateSubscription(subscriptionID : string, { buyerAccessToken } : SubscriptionAPICredentials) : ZalgoPromise { - return callSmartAPI({ - accessToken: buyerAccessToken, - method: 'post', - eventName: 'billagmt_subscriptions_activate', - url: `${ SMART_API_URI.SUBSCRIPTION }/${ subscriptionID }/activate` - }).then(({ data }) => { - return data; - }); +export function activateSubscription( + subscriptionID: string, + { buyerAccessToken }: SubscriptionAPICredentials, +): ZalgoPromise { + return callSmartAPI({ + accessToken: buyerAccessToken, + method: "post", + eventName: "billagmt_subscriptions_activate", + url: `${SMART_API_URI.SUBSCRIPTION}/${subscriptionID}/activate`, + }).then(({ data }) => { + return data; + }); } -export function getSubscription(subscriptionID : string, { buyerAccessToken } : SubscriptionAPICredentials) : ZalgoPromise { - return callSmartAPI({ - accessToken: buyerAccessToken, - eventName: 'billagmt_subscriptions_get', - url: `${ SMART_API_URI.SUBSCRIPTION }/${ subscriptionID }` - }).then(({ data }) => { - return data; - }); +export function getSubscription( + subscriptionID: string, + { buyerAccessToken }: SubscriptionAPICredentials, +): ZalgoPromise { + return callSmartAPI({ + accessToken: buyerAccessToken, + eventName: "billagmt_subscriptions_get", + url: `${SMART_API_URI.SUBSCRIPTION}/${subscriptionID}`, + }).then(({ data }) => { + return data; + }); } diff --git a/src/api/vault.js b/src/api/vault.js index a03238722b..0ad7f8c027 100644 --- a/src/api/vault.js +++ b/src/api/vault.js @@ -94,7 +94,7 @@ export type PaymentSourceInput = {| addressLine2?: string, adminArea1?: string, adminArea2?: string, - countryCode: string + countryCode: string, |}, |}, |}; @@ -103,10 +103,12 @@ export const updateVaultSetupToken = ({ clientID, vaultSetupToken, paymentSource, + idToken, }: {| clientID: string, vaultSetupToken: string, paymentSource: PaymentSourceInput, + idToken: string, |}): ZalgoPromise<{| id: string, status: VaultTokenStatus |}> => callGraphQL<{| id: string, status: VaultTokenStatus |}>({ name: "UpdateVaultSetupToken", @@ -115,11 +117,13 @@ export const updateVaultSetupToken = ({ $clientID: String! $vaultSetupToken: String! $paymentSource: PaymentSource + $idToken: String ) { updateVaultSetupToken( clientId: $clientID vaultSetupToken: $vaultSetupToken paymentSource: $paymentSource + idToken: $idToken ) { id, status, @@ -132,13 +136,13 @@ export const updateVaultSetupToken = ({ clientID, vaultSetupToken, paymentSource, + idToken, }, }); export function vaultApprovalSessionIdToOrderId( - approvalSessionId: string + approvalSessionId: string, ): ZalgoPromise { - return callSmartAPI({ authenticated: false, method: "post", @@ -146,6 +150,5 @@ export function vaultApprovalSessionIdToOrderId( url: `${SMART_API_URI.VAULT}/${approvalSessionId}/ectoken`, }).then(({ data }) => { return data.token; - }) - + }); } diff --git a/src/api/wallet.js b/src/api/wallet.js index 8a2a1db55c..e984e6ef15 100644 --- a/src/api/wallet.js +++ b/src/api/wallet.js @@ -1,39 +1,52 @@ /* @flow */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { CURRENCY } from '@paypal/sdk-constants/src'; -import { memoize } from '@krakenjs/belter/src'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { CURRENCY } from "@paypal/sdk-constants/src"; +import { memoize } from "@krakenjs/belter/src"; -import type { Wallet } from '../types'; -import { HEADERS } from '../constants'; +import type { Wallet } from "../types"; +import { HEADERS } from "../constants"; -import { callGraphQL } from './api'; +import { callGraphQL } from "./api"; type GetSmartWalletOptions = {| - clientID : string, - merchantID : ?$ReadOnlyArray, - currency : $Values, - amount : ?string, - clientMetadataID : string, - userIDToken : string, - vetted? : boolean, - paymentMethodToken? : ?string, - branded? : ?boolean, - allowBillingPayments? : ?boolean, - headers? : { [string] : string } + clientID: string, + merchantID: ?$ReadOnlyArray, + currency: $Values, + amount: ?string, + clientMetadataID: string, + userIDToken: string, + vetted?: boolean, + paymentMethodToken?: ?string, + branded?: ?boolean, + allowBillingPayments?: ?boolean, + headers?: { [string]: string }, |}; -const DEFAULT_AMOUNT = '0.00'; +const DEFAULT_AMOUNT = "0"; type GetSmartWallet = (GetSmartWalletOptions) => ZalgoPromise; -export const getSmartWallet : GetSmartWallet = memoize(({ clientID, merchantID, currency, amount = DEFAULT_AMOUNT, clientMetadataID, userIDToken, vetted = true, paymentMethodToken, branded, allowBillingPayments = true, headers={} }) => { +export const getSmartWallet: GetSmartWallet = memoize( + ({ + clientID, + merchantID, + currency, + amount = DEFAULT_AMOUNT, + clientMetadataID, + userIDToken, + vetted = true, + paymentMethodToken, + branded, + allowBillingPayments = true, + headers = {}, + }) => { if (clientMetadataID) { - headers[HEADERS.CLIENT_METADATA_ID] = String(clientMetadataID) + headers[HEADERS.CLIENT_METADATA_ID] = String(clientMetadataID); } return callGraphQL({ - name: 'GetSmartWallet', - query: ` + name: "GetSmartWallet", + query: ` query GetSmartWallet( $clientID: String! $merchantID: [String!] @@ -104,9 +117,20 @@ export const getSmartWallet : GetSmartWallet = memoize(({ clientID, merchantID, } } `, - variables: { clientID, merchantID, currency, amount, userIDToken, vetted, paymentMethodToken, branded, allowBillingPayments }, - headers + variables: { + clientID, + merchantID, + currency, + amount, + userIDToken, + vetted, + paymentMethodToken, + branded, + allowBillingPayments, + }, + headers, }).then(({ smartWallet }) => { - return smartWallet; + return smartWallet; }); -}); + }, +); diff --git a/src/babel.config.js b/src/babel.config.js index 5df4c258fc..b62d5f4cf7 100644 --- a/src/babel.config.js +++ b/src/babel.config.js @@ -2,5 +2,5 @@ /* eslint import/no-commonjs: off */ module.exports = { - extends: '@krakenjs/babel-config-grumbler/babelrc-browser' + extends: "@krakenjs/babel-config-grumbler/babelrc-browser", }; diff --git a/src/button/button.js b/src/button/button.js index c3160bd5a0..9111eb82b1 100644 --- a/src/button/button.js +++ b/src/button/button.js @@ -1,333 +1,508 @@ /* @flow */ -import { onClick as onElementClick, querySelectorAll, noop, stringifyErrorMessage, stringifyError, preventClickFocus } from '@krakenjs/belter/src'; -import { FUNDING, COUNTRY, FPTI_KEY, type FundingEligibilityType } from '@paypal/sdk-constants/src'; -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; - -import type { ContentType, Wallet, PersonalizationType, Experiments, FeatureFlags, InlinePaymentFieldsEligibility } from '../types'; -import { sendCountMetric, getLogger, getSmartFieldsByFundingSource, setBuyerAccessToken, registerServiceWorker, unregisterServiceWorker } from '../lib'; -import { type FirebaseConfig } from '../api'; -import { DATA_ATTRIBUTES, BUYER_INTENT, FPTI_STATE, FPTI_CUSTOM_KEY, ORDER_CREATED_BY } from '../constants'; -import { type Payment } from '../payment-flows'; - -import { getButtonProps, getConfig, getComponents, getServiceData, type ButtonProps } from './props'; -import { getSelectedFunding, getButtons, getMenuButton } from './dom'; -import { setupButtonLogger } from './logger'; -import { setupRemember } from './remember'; -import { setupPaymentFlows, initiatePaymentFlow, initiateMenuFlow } from './pay'; -import { prerenderButtonSmartMenu, clearButtonSmartMenu } from './menu'; -import { validateProps } from './validation'; -import { setupExports } from './exports'; +import { + onClick as onElementClick, + querySelectorAll, + noop, + stringifyErrorMessage, + stringifyError, + preventClickFocus, +} from "@krakenjs/belter/src"; +import { + COUNTRY, + FPTI_KEY, + type FundingEligibilityType, +} from "@paypal/sdk-constants/src"; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; + +import type { + ContentType, + Wallet, + PersonalizationType, + Experiments, + FeatureFlags, + InlinePaymentFieldsEligibility, +} from "../types"; +import { + sendCountMetric, + getLogger, + getSmartFieldsByFundingSource, + registerServiceWorker, + unregisterServiceWorker, +} from "../lib"; +import { type FirebaseConfig } from "../api"; +import { + DATA_ATTRIBUTES, + BUYER_INTENT, + FPTI_STATE, + FPTI_CUSTOM_KEY, + ORDER_CREATED_BY, +} from "../constants"; +import { type Payment } from "../payment-flows"; + +import { + getButtonProps, + getConfig, + getComponents, + getServiceData, + type ButtonProps, +} from "./props"; +import { getSelectedFunding, getButtons, getMenuButton } from "./dom"; +import { setupButtonLogger } from "./logger"; +import { setupRemember } from "./remember"; +import { + setupPaymentFlows, + initiatePaymentFlow, + initiateMenuFlow, +} from "./pay"; +import { prerenderButtonSmartMenu, clearButtonSmartMenu } from "./menu"; +import { validateProps } from "./validation"; +import { setupExports } from "./exports"; export type SetupButtonOptions = {| - fundingEligibility : FundingEligibilityType, - buyerCountry : $Values, - cspNonce? : string, - merchantID : $ReadOnlyArray, - firebaseConfig? : FirebaseConfig, - facilitatorAccessToken : string, - content : $Shape, - sdkMeta : string, - wallet : ?Wallet, - buyerAccessToken : ?string, - eligibility : $Shape<{| - cardFields : boolean, - inlinePaymentFields: InlinePaymentFieldsEligibility, - isServiceWorkerEligible : boolean, - venmoEnableOnShippingChange: boolean, - |}>, - correlationID? : string, - cookies : string, - personalization : PersonalizationType, - brandedDefault? : boolean | null, - experiments?: Experiments; - featureFlags: FeatureFlags, - smartWalletOrderID? : string, - enableOrdersApprovalSmartWallet? : boolean, - product? : string, - dumbledoreCurrentReleaseHash? : string, - dumbledoreServiceWorker? : string, + fundingEligibility: FundingEligibilityType, + buyerCountry: $Values, + cspNonce?: string, + merchantID: $ReadOnlyArray, + firebaseConfig?: FirebaseConfig, + facilitatorAccessToken: string, + content: $Shape, + sdkMeta: string, + wallet: ?Wallet, + buyerAccessToken: ?string, + eligibility: $Shape<{| + cardFields: boolean, + inlinePaymentFields: InlinePaymentFieldsEligibility, + isServiceWorkerEligible: boolean, + venmoEnableOnShippingChange: boolean, + |}>, + correlationID?: string, + cookies: string, + personalization: PersonalizationType, + brandedDefault?: boolean | null, + experiments?: Experiments, + featureFlags: FeatureFlags, + product?: string, + dumbledoreCurrentReleaseHash?: string, + dumbledoreServiceWorker?: string, |}; try { - if (!window.paypal) { - const script = querySelectorAll('script').find(el => el.getAttribute('data-namespace')); + if (!window.paypal) { + const script = querySelectorAll("script").find((el) => + el.getAttribute("data-namespace"), + ); - if (script) { - window.paypal = window[script.getAttribute('data-namespace')]; - } + if (script) { + window.paypal = window[script.getAttribute("data-namespace")]; } + } } catch (err) { - // pass + // pass } export function setupButton({ - facilitatorAccessToken, + facilitatorAccessToken, + eligibility, + fundingEligibility, + buyerCountry: buyerGeoCountry, + sdkMeta, + buyerAccessToken, + wallet, + cookies, + cspNonce: serverCSPNonce, + merchantID: serverMerchantID, + firebaseConfig, + content, + personalization, + correlationID: buttonCorrelationID = "", + brandedDefault = null, + experiments = {}, + featureFlags, + product, + dumbledoreCurrentReleaseHash, + dumbledoreServiceWorker, +}: SetupButtonOptions): ZalgoPromise { + if (!window.paypal) { + throw new Error(`PayPal SDK not loaded`); + } + + const clientID = window.xprops.clientID; + + const serviceData = getServiceData({ eligibility, + facilitatorAccessToken, + buyerGeoCountry, + serverMerchantID, fundingEligibility, - buyerCountry: buyerGeoCountry, + cookies, sdkMeta, buyerAccessToken, wallet, - cookies, - cspNonce: serverCSPNonce, - merchantID: serverMerchantID, - firebaseConfig, content, personalization, - correlationID: buttonCorrelationID = '', - brandedDefault = null, - experiments = {}, featureFlags, - smartWalletOrderID, - enableOrdersApprovalSmartWallet, - product, - dumbledoreCurrentReleaseHash, - dumbledoreServiceWorker -}: SetupButtonOptions) : ZalgoPromise { - if (!window.paypal) { - throw new Error(`PayPal SDK not loaded`); - } + }); - const clientID = window.xprops.clientID; + const { merchantID, buyerCountry } = serviceData; - if (buyerAccessToken && smartWalletOrderID) { - setBuyerAccessToken(buyerAccessToken); - } - - const serviceData = getServiceData({ - eligibility, - facilitatorAccessToken, - buyerGeoCountry, - serverMerchantID, - fundingEligibility, - cookies, - sdkMeta, - buyerAccessToken, - wallet, - content, - personalization, - featureFlags + const props = getButtonProps({ + facilitatorAccessToken, + brandedDefault, + paymentSource: null, + featureFlags, + experiments, + }); + const { + env, + sessionID, + partnerAttributionID, + commit, + sdkCorrelationID, + locale, + onShippingChange, + buttonSessionID, + merchantDomain, + onInit, + getPrerenderDetails, + rememberFunding, + getQueriedEligibleFunding, + style, + fundingSource, + intent, + createBillingAgreement, + createSubscription, + stickinessID, + } = props; + + const config = getConfig({ serverCSPNonce, firebaseConfig }); + const { sdkVersion } = config; + + const components = getComponents(); + + const { initPromise, isEnabled } = onInit({ + correlationID: buttonCorrelationID, + }); + + let paymentProcessing = false; + + function initiatePayment({ + payment, + props: paymentProps, + }: {| + props: ButtonProps, + payment: Payment, + |}): ZalgoPromise { + return ZalgoPromise.try(() => { + if (paymentProcessing) { + return; + } + + const { win, fundingSource: paymentFundingSource } = payment; + const { onClick } = paymentProps; + const smartFields = getSmartFieldsByFundingSource(paymentFundingSource); + + if (smartFields) { + if (!smartFields.isValid()) { + if (win) { + win.close(); + } + return; + } + } + + if (onClick) { + onClick({ fundingSource: paymentFundingSource }); + } + + if (isEnabled()) { + paymentProcessing = true; + + return initiatePaymentFlow({ + payment, + config, + serviceData, + components, + props: paymentProps, + experiments, + }).finally(() => { + paymentProcessing = false; + }); + } else { + if (win) { + win.close(); + } + } + }).catch((err) => { + // we don't think this code path is actually hit but we + // are too afraid to remove it right now + // if you, brave soul, wish to remove this entire catch statement one day, do the following: + // 1. delete this catch statement + // 2. throw an error inside initiatePaymentFlow + // 3. make sure payPromise.catch(...) still catches the error + getLogger().info("smart_buttons_payment_error", { + err: stringifyError(err), + }); + + throw err; }); - - const { merchantID, buyerCountry } = serviceData; - - const paymentSource = enableOrdersApprovalSmartWallet ? FUNDING.PAYPAL : null; - - const props = getButtonProps({ facilitatorAccessToken, brandedDefault, paymentSource, featureFlags, enableOrdersApprovalSmartWallet, smartWalletOrderID, experiments}); - const { env, sessionID, partnerAttributionID, commit, sdkCorrelationID, locale, onShippingChange, - buttonSessionID, merchantDomain, onInit, - getPrerenderDetails, rememberFunding, getQueriedEligibleFunding, style, fundingSource, - intent, createBillingAgreement, createSubscription, stickinessID } = props; - - const config = getConfig({ serverCSPNonce, firebaseConfig }); - const { sdkVersion } = config; - - const components = getComponents(); - - const { initPromise, isEnabled } = onInit({ correlationID: buttonCorrelationID }); - - let paymentProcessing = false; - - function initiatePayment({ payment, props: paymentProps } : {| props : ButtonProps, payment : Payment |}) : ZalgoPromise { - return ZalgoPromise.try(() => { - if (paymentProcessing) { - return; - } - - const { win, fundingSource: paymentFundingSource } = payment; - const { onClick } = paymentProps; - const smartFields = getSmartFieldsByFundingSource(paymentFundingSource); - - if (smartFields) { - if (!smartFields.isValid()) { - if (win) { - win.close(); - } - return; - } - } - - if (onClick) { - onClick({ fundingSource: paymentFundingSource }); - } - - if (isEnabled()) { - paymentProcessing = true; - - return initiatePaymentFlow({ payment, config, serviceData, components, props: paymentProps, experiments }).finally(() => { - paymentProcessing = false; - }); - } else { - if (win) { - win.close(); - } - } - }).catch(err => { - // we don't think this code path is actually hit but we - // are too afraid to remove it right now - // if you, brave soul, wish to remove this entire catch statement one day, do the following: - // 1. delete this catch statement - // 2. throw an error inside initiatePaymentFlow - // 3. make sure payPromise.catch(...) still catches the error - getLogger().info('smart_buttons_payment_error', { err: stringifyError(err) }); - - throw err; + } + + function initiateMenu({ + payment, + }: {| + payment: Payment, + |}): ZalgoPromise { + return ZalgoPromise.try(() => { + if (paymentProcessing) { + return; + } + + if (isEnabled()) { + return initiateMenuFlow({ + payment, + config, + serviceData, + components, + props, + experiments, }); - } - - function initiateMenu({ payment } : {| payment : Payment |}) : ZalgoPromise { - return ZalgoPromise.try(() => { - if (paymentProcessing) { - return; - } - - if (isEnabled()) { - return initiateMenuFlow({ payment, config, serviceData, components, props, experiments }); - } - }).catch(err => { - getLogger() - .info('smart_buttons_payment_error', { err: stringifyError(err) }) - .track({ - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.ERROR_CODE]: 'smart_buttons_payment_error', - [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(err) - }); - - throw err; + } + }).catch((err) => { + getLogger() + .info("smart_buttons_payment_error", { err: stringifyError(err) }) + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.ERROR_CODE]: "smart_buttons_payment_error", + [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(err), }); - } - clearButtonSmartMenu(); - - getButtons().forEach(button => { - const menuToggle = getMenuButton(button); - const { fundingSource: paymentFundingSource, card, paymentMethodID, instrumentID, instrumentType } = getSelectedFunding(button); - - const payment = { button, menuToggle, fundingSource: paymentFundingSource, card, paymentMethodID, instrumentID, instrumentType, isClick: true, buyerIntent: BUYER_INTENT.PAY }; - - preventClickFocus(button); - onElementClick(button, event => { - event.preventDefault(); - event.stopPropagation(); - - - getLogger().addTrackingBuilder(() => ({ - [FPTI_CUSTOM_KEY.ORDER_CREATED_BY]: ORDER_CREATED_BY.BUTTON_CLICK - })) - - if (eligibility.isServiceWorkerEligible) { - getLogger().info('SERVICE_WORKER_ELMO_TREATMENT'); - registerServiceWorker({ dumbledoreCurrentReleaseHash, dumbledoreServiceWorker}); - } else { - getLogger().info('SERVICE_WORKER_ELMO_CONTROL').track({ - [FPTI_KEY.EVENT_NAME]: 'SERVICE_WORKER_NOT_ELIGIBLE', - }); - unregisterServiceWorker(); - } - - const paymentProps = getButtonProps({ facilitatorAccessToken, brandedDefault, paymentSource: paymentFundingSource, featureFlags, enableOrdersApprovalSmartWallet, smartWalletOrderID, experiments }); - - const payPromise = initiatePayment({ payment, props: paymentProps }); - const { onError } = paymentProps; - - payPromise.catch(err => { - sendCountMetric({ - name: "pp.app.paypal_sdk.buttons.click.error.count", - dimensions: { - errorName: 'payment_flow_error', - fundingSource: paymentFundingSource, - prerender: false - } - }) - - getLogger() - .warn('click_initiate_payment_reject', { err: stringifyError(err) }) - .track({ - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.ERROR_CODE]: 'smart_buttons_payment_error', - [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(err) - }) - .flush(); - onError(err); - }); - - // $FlowFixMe - button.payPromise = payPromise; + throw err; + }); + } + + clearButtonSmartMenu(); + + getButtons().forEach((button) => { + const menuToggle = getMenuButton(button); + const { + fundingSource: paymentFundingSource, + card, + paymentMethodID, + instrumentID, + instrumentType, + } = getSelectedFunding(button); + + const payment = { + button, + menuToggle, + fundingSource: paymentFundingSource, + card, + paymentMethodID, + instrumentID, + instrumentType, + isClick: true, + buyerIntent: BUYER_INTENT.PAY, + }; + + preventClickFocus(button); + onElementClick(button, (event) => { + event.preventDefault(); + event.stopPropagation(); + + getLogger().addTrackingBuilder(() => ({ + [FPTI_CUSTOM_KEY.ORDER_CREATED_BY]: ORDER_CREATED_BY.BUTTON_CLICK, + })); + + if (eligibility.isServiceWorkerEligible) { + getLogger().info("SERVICE_WORKER_ELMO_TREATMENT"); + registerServiceWorker({ + dumbledoreCurrentReleaseHash, + dumbledoreServiceWorker, + }); + } else { + getLogger() + .info("SERVICE_WORKER_ELMO_CONTROL") + .track({ + [FPTI_KEY.EVENT_NAME]: "SERVICE_WORKER_NOT_ELIGIBLE", + }); + unregisterServiceWorker(); + } + + const paymentProps = getButtonProps({ + facilitatorAccessToken, + brandedDefault, + paymentSource: paymentFundingSource, + featureFlags, + experiments, + }); + + const payPromise = initiatePayment({ payment, props: paymentProps }); + const { onError } = paymentProps; + + payPromise.catch((err) => { + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.click.error.count", + dimensions: { + errorName: "payment_flow_error", + fundingSource: paymentFundingSource, + prerender: false, + }, }); - if (menuToggle) { - prerenderButtonSmartMenu({ props, components }); + getLogger() + .warn("click_initiate_payment_reject", { err: stringifyError(err) }) + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.ERROR_CODE]: "smart_buttons_payment_error", + [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(err), + }) + .flush(); + onError(err); + }); + + // $FlowFixMe + button.payPromise = payPromise; + }); - onElementClick(menuToggle, (event) => { - event.preventDefault(); - event.stopPropagation(); + if (menuToggle) { + prerenderButtonSmartMenu({ props, components }); - const menuPromise = initiateMenu({ payment }); + onElementClick(menuToggle, (event) => { + event.preventDefault(); + event.stopPropagation(); - // $FlowFixMe - button.menuPromise = menuPromise; - }); - } - }); + const menuPromise = initiateMenu({ payment }); - const setupPrerenderTask = initPromise.then(() => { - return ZalgoPromise.hash({ prerenderDetails: getPrerenderDetails(), initPromise }).then(({ prerenderDetails }) => { - if (!prerenderDetails) { - return; - } - - const { win, fundingSource: paymentFundingSource, card } = prerenderDetails; - const button = document.querySelector(`[${ DATA_ATTRIBUTES.FUNDING_SOURCE }=${ paymentFundingSource }]`); - - if (!button) { - throw new Error(`Can not find button element`); - } - - const paymentProps = getButtonProps({ facilitatorAccessToken, brandedDefault, paymentSource: paymentFundingSource, featureFlags, enableOrdersApprovalSmartWallet, smartWalletOrderID, experiments }); - const payment = { win, button, fundingSource: paymentFundingSource, card, buyerIntent: BUYER_INTENT.PAY }; - const payPromise = initiatePayment({ payment, props: paymentProps }); - const { onError } = paymentProps; - - payPromise.catch(err => { - sendCountMetric({ - name: "pp.app.paypal_sdk.buttons.click.error.count", - dimensions: { - fundingSource: paymentFundingSource, - prerender: true - } - }) - - getLogger() - .error('prerender_initiate_payment_reject', { err: stringifyError(err) }) - .track({ - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.ERROR_CODE]: 'smart_buttons_prerender_payment_error', - [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(err) - }) - .flush(); - onError(err); - }); - - // $FlowFixMe - button.payPromise = payPromise; - }); - }); + // $FlowFixMe + button.menuPromise = menuPromise; + }); + } + }); - const setupRememberTask = setupRemember({ rememberFunding, fundingEligibility }); + const setupPrerenderTask = initPromise.then(() => { + return ZalgoPromise.hash({ + prerenderDetails: getPrerenderDetails(), + initPromise, + }).then(({ prerenderDetails }) => { + if (!prerenderDetails) { + return; + } + + const { + win, + fundingSource: paymentFundingSource, + card, + } = prerenderDetails; + const button = document.querySelector( + `[${DATA_ATTRIBUTES.FUNDING_SOURCE}=${paymentFundingSource}]`, + ); + + if (!button) { + throw new Error(`Can not find button element`); + } + + const paymentProps = getButtonProps({ + facilitatorAccessToken, + brandedDefault, + paymentSource: paymentFundingSource, + featureFlags, + experiments, + }); + const payment = { + win, + button, + fundingSource: paymentFundingSource, + card, + buyerIntent: BUYER_INTENT.PAY, + }; + const payPromise = initiatePayment({ payment, props: paymentProps }); + const { onError } = paymentProps; + + payPromise.catch((err) => { + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.click.error.count", + dimensions: { + fundingSource: paymentFundingSource, + prerender: true, + }, + }); - const setupButtonLogsTask = setupButtonLogger({ - style, env, sdkVersion, sessionID, clientID, partnerAttributionID, commit, sdkCorrelationID, - stickinessID, buttonCorrelationID, locale, merchantID, buttonSessionID, merchantDomain, - fundingSource, getQueriedEligibleFunding, buyerCountry, onShippingChange, wallet, smartWalletOrderID, enableOrdersApprovalSmartWallet, product }); - const setupPaymentFlowsTask = setupPaymentFlows({ props, config, serviceData, components }); - const setupExportsTask = setupExports({ props, isEnabled, facilitatorAccessToken, fundingEligibility, merchantID }); + getLogger() + .error("prerender_initiate_payment_reject", { + err: stringifyError(err), + }) + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.ERROR_CODE]: "smart_buttons_prerender_payment_error", + [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(err), + }) + .flush(); + onError(err); + }); + + // $FlowFixMe + button.payPromise = payPromise; + }); + }); - const validatePropsTask = setupButtonLogsTask.then(() => validateProps({ intent, createBillingAgreement, createSubscription, featureFlags })); - - return ZalgoPromise.hash({ - initPromise, facilitatorAccessToken, - setupButtonLogsTask, setupPrerenderTask, setupRememberTask, - setupPaymentFlowsTask, validatePropsTask, setupExportsTask - }).then(noop); + const setupRememberTask = setupRemember({ + rememberFunding, + fundingEligibility, + }); + + const setupButtonLogsTask = setupButtonLogger({ + style, + env, + sdkVersion, + sessionID, + clientID, + partnerAttributionID, + commit, + sdkCorrelationID, + stickinessID, + buttonCorrelationID, + locale, + merchantID, + buttonSessionID, + merchantDomain, + fundingSource, + getQueriedEligibleFunding, + buyerCountry, + onShippingChange, + product, + }); + const setupPaymentFlowsTask = setupPaymentFlows({ + props, + config, + serviceData, + components, + }); + const setupExportsTask = setupExports({ + props, + isEnabled, + facilitatorAccessToken, + fundingEligibility, + merchantID, + }); + + const validatePropsTask = setupButtonLogsTask.then(() => + validateProps({ + intent, + createBillingAgreement, + createSubscription, + featureFlags, + }), + ); + + return ZalgoPromise.hash({ + initPromise, + facilitatorAccessToken, + setupButtonLogsTask, + setupPrerenderTask, + setupRememberTask, + setupPaymentFlowsTask, + validatePropsTask, + setupExportsTask, + }).then(noop); } diff --git a/src/button/dom.js b/src/button/dom.js index 345f125d7c..de7ded158c 100644 --- a/src/button/dom.js +++ b/src/button/dom.js @@ -1,47 +1,55 @@ /* @flow */ -import { FUNDING, CARD, WALLET_INSTRUMENT } from '@paypal/sdk-constants/src'; -import { querySelectorAll } from '@krakenjs/belter/src'; +import { FUNDING, CARD, WALLET_INSTRUMENT } from "@paypal/sdk-constants/src"; +import { querySelectorAll } from "@krakenjs/belter/src"; -import { DATA_ATTRIBUTES, CLASS } from '../constants'; +import { DATA_ATTRIBUTES, CLASS } from "../constants"; -export function getButtons() : $ReadOnlyArray { - return querySelectorAll(`[ ${ DATA_ATTRIBUTES.FUNDING_SOURCE } ]`); +export function getButtons(): $ReadOnlyArray { + return querySelectorAll(`[ ${DATA_ATTRIBUTES.FUNDING_SOURCE} ]`); } -export function getMenuButton(button : HTMLElement) : ?HTMLElement { - let menu = button.querySelector(`[${ DATA_ATTRIBUTES.MENU }]`); +export function getMenuButton(button: HTMLElement): ?HTMLElement { + let menu = button.querySelector(`[${DATA_ATTRIBUTES.MENU}]`); - if (menu) { - return menu; - } + if (menu) { + return menu; + } - const parent = button.parentNode; - if (parent) { - // $FlowFixMe - menu = parent.querySelector(`[${ DATA_ATTRIBUTES.MENU }]`); - } + const parent = button.parentNode; + if (parent) { + // $FlowFixMe + menu = parent.querySelector(`[${DATA_ATTRIBUTES.MENU}]`); + } - if (menu) { - return menu; - } + if (menu) { + return menu; + } } -export function getSelectedFunding(button : HTMLElement) : {| fundingSource : $Values, card : $Values, paymentMethodID : ?string, instrumentID : ?string, instrumentType : ?$Values |} { - const fundingSource = button.getAttribute(DATA_ATTRIBUTES.FUNDING_SOURCE); - const paymentMethodID = button.getAttribute(DATA_ATTRIBUTES.PAYMENT_METHOD_ID); - const instrumentID = button.getAttribute(DATA_ATTRIBUTES.INSTRUMENT_ID); - const instrumentType = button.getAttribute(DATA_ATTRIBUTES.INSTRUMENT_TYPE); - const card = button.getAttribute(DATA_ATTRIBUTES.CARD); - - // $FlowFixMe - return { fundingSource, card, paymentMethodID, instrumentID, instrumentType }; +export function getSelectedFunding(button: HTMLElement): {| + fundingSource: $Values, + card: $Values, + paymentMethodID: ?string, + instrumentID: ?string, + instrumentType: ?$Values, +|} { + const fundingSource = button.getAttribute(DATA_ATTRIBUTES.FUNDING_SOURCE); + const paymentMethodID = button.getAttribute( + DATA_ATTRIBUTES.PAYMENT_METHOD_ID, + ); + const instrumentID = button.getAttribute(DATA_ATTRIBUTES.INSTRUMENT_ID); + const instrumentType = button.getAttribute(DATA_ATTRIBUTES.INSTRUMENT_TYPE); + const card = button.getAttribute(DATA_ATTRIBUTES.CARD); + + // $FlowFixMe + return { fundingSource, card, paymentMethodID, instrumentID, instrumentType }; } -export function enableLoadingSpinner(button : HTMLElement) { - button.classList.add(CLASS.LOADING); +export function enableLoadingSpinner(button: HTMLElement) { + button.classList.add(CLASS.LOADING); } -export function disableLoadingSpinner(button : HTMLElement) { - button.classList.remove(CLASS.LOADING); +export function disableLoadingSpinner(button: HTMLElement) { + button.classList.remove(CLASS.LOADING); } diff --git a/src/button/exports.js b/src/button/exports.js index 8a6b639052..af67f23f78 100644 --- a/src/button/exports.js +++ b/src/button/exports.js @@ -1,114 +1,145 @@ /* @flow */ +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { querySelectorAll } from "@krakenjs/belter/src"; -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { querySelectorAll } from '@krakenjs/belter/src'; +import { + DATA_ATTRIBUTES, + FPTI_CUSTOM_KEY, + ORDER_CREATED_BY, +} from "../constants"; +import { upgradeFacilitatorAccessToken, getGuestEnabledStatus } from "../api"; +import { getLogger, getBuyerAccessToken } from "../lib"; -import { DATA_ATTRIBUTES, FPTI_CUSTOM_KEY, ORDER_CREATED_BY } from '../constants'; -import { upgradeFacilitatorAccessToken, getGuestEnabledStatus } from '../api'; -import { getLogger, getBuyerAccessToken } from '../lib'; - -import type { ButtonProps } from './props'; +import type { ButtonProps } from "./props"; type ExportsProps = {| - props : ButtonProps, - isEnabled : () => boolean, - facilitatorAccessToken : string, - fundingEligibility : Object, - merchantID : $ReadOnlyArray + props: ButtonProps, + isEnabled: () => boolean, + facilitatorAccessToken: string, + fundingEligibility: Object, + merchantID: $ReadOnlyArray, |}; -export function setupExports({ props, isEnabled, facilitatorAccessToken, fundingEligibility, merchantID } : ExportsProps) { - const { createOrder, onApprove, onError, onCancel, onClick, onShippingChange, commit, intent, fundingSource, currency } = props; - - const fundingSources = querySelectorAll(`[${ DATA_ATTRIBUTES.FUNDING_SOURCE }]`).map(el => { - return el.getAttribute(DATA_ATTRIBUTES.FUNDING_SOURCE); - }).filter(Boolean); - - window.exports = { - name: 'smart-payment-buttons', - commit: { - commit, - currency, - intent +export function setupExports({ + props, + isEnabled, + facilitatorAccessToken, + fundingEligibility, + merchantID, +}: ExportsProps) { + const { + createOrder, + onApprove, + onError, + onCancel, + onClick, + onShippingChange, + commit, + intent, + fundingSource, + currency, + } = props; + + const fundingSources = querySelectorAll(`[${DATA_ATTRIBUTES.FUNDING_SOURCE}]`) + .map((el) => { + return el.getAttribute(DATA_ATTRIBUTES.FUNDING_SOURCE); + }) + .filter(Boolean); + + window.exports = { + name: "smart-payment-buttons", + commit: { + commit, + currency, + intent, + }, + currency, + intent, + isGuestEnabled: () => { + return fundingEligibility?.card?.hasOwnProperty("guestEnabled") + ? fundingEligibility.card.guestEnabled + : getGuestEnabledStatus(merchantID); + }, + isShippingChangeEnabled: () => { + return typeof onShippingChange === "function"; + }, + paymentSession: () => { + return { + getAvailableFundingSources: () => fundingSources, + createOrder: (data) => { + const { eventSource = ORDER_CREATED_BY.UNKNOWN_EVENT } = data || {}; + + getLogger().addTrackingBuilder(() => ({ + [FPTI_CUSTOM_KEY.ORDER_CREATED_BY]: eventSource, + })); + + if (!isEnabled()) { + throw new Error("Error occurred. Button not enabled."); + } + + return ZalgoPromise.hash({ + valid: onClick && fundingSource ? onClick({ fundingSource }) : true, + }).then(({ valid }) => { + if (!valid) { + throw new Error("Error occurred during async validation"); + } else { + return createOrder(); + } + }); }, - currency, - intent, - isGuestEnabled: () => { return fundingEligibility?.card?.hasOwnProperty('guestEnabled') ? fundingEligibility.card.guestEnabled : getGuestEnabledStatus(merchantID); }, - isShippingChangeEnabled: () => { return (typeof onShippingChange === 'function'); }, - paymentSession: () => { - return { - getAvailableFundingSources: () => fundingSources, - createOrder: (data) => { - const { eventSource = ORDER_CREATED_BY.UNKNOWN_EVENT } = data || {} - - getLogger().addTrackingBuilder(() => ({ - [FPTI_CUSTOM_KEY.ORDER_CREATED_BY]: eventSource - })) - - if (!isEnabled()) { - throw new Error('Error occurred. Button not enabled.'); - } - - return ZalgoPromise.hash({ - valid: onClick && fundingSource ? onClick({ fundingSource }) : true - }).then(({ valid }) => { - if (!valid) { - throw new Error('Error occurred during async validation'); - } else { - return createOrder(); - } - }); - - - }, - onApprove: (merchantData) => { - const data = { - payerID: merchantData.payerID, - forceRestAPI: true - }; - - const actions = { - restart: () => { - throw new Error('Action unimplemented'); - } - }; - - return onApprove(data, actions); - }, - onCancel, - onError, - upgradeFacilitatorAccessToken: ({ facilitatorAccessToken: merchantAccessToken, orderID }) => { - const buyerAccessToken = getBuyerAccessToken(); - - if (!buyerAccessToken) { - getLogger().error('lsat_upgrade_error', { err: 'buyer access token not found' }); - throw new Error('Buyer access token not found'); - } - - return upgradeFacilitatorAccessToken(merchantAccessToken, { buyerAccessToken, orderID }); - }, - getFacilitatorAccessToken: () => { - return facilitatorAccessToken; - }, - onShippingChange: (data) => { - if (onShippingChange) { - const actions = { - resolve: () => { - throw new Error('Action unimplemented'); - }, - reject: () => { - throw new Error('Action unimplemented'); - } - }; - - return onShippingChange(data, actions); - } - } + onApprove: (merchantData) => { + const data = { + payerID: merchantData.payerID, + forceRestAPI: true, + }; + + const actions = { + restart: () => { + throw new Error("Action unimplemented"); + }, + }; + + return onApprove(data, actions); + }, + onCancel, + onError, + upgradeFacilitatorAccessToken: ({ + facilitatorAccessToken: merchantAccessToken, + orderID, + }) => { + const buyerAccessToken = getBuyerAccessToken(); + + if (!buyerAccessToken) { + getLogger().error("lsat_upgrade_error", { + err: "buyer access token not found", + }); + throw new Error("Buyer access token not found"); + } + + return upgradeFacilitatorAccessToken(merchantAccessToken, { + buyerAccessToken, + orderID, + }); + }, + getFacilitatorAccessToken: () => { + return facilitatorAccessToken; + }, + onShippingChange: (data) => { + if (onShippingChange) { + const actions = { + resolve: () => { + throw new Error("Action unimplemented"); + }, + reject: () => { + throw new Error("Action unimplemented"); + }, }; - } - }; - -} - + return onShippingChange(data, actions); + } + }, + }; + }, + }; +} diff --git a/src/button/index.js b/src/button/index.js index 6e84009f07..08a8eb0389 100644 --- a/src/button/index.js +++ b/src/button/index.js @@ -1,4 +1,4 @@ /* @flow */ -export * from './button'; -export * from './props'; +export * from "./button"; +export * from "./props"; diff --git a/src/button/logger.js b/src/button/logger.js index c3c746837a..75fca79a18 100644 --- a/src/button/logger.js +++ b/src/button/logger.js @@ -1,230 +1,281 @@ /* @flow */ -import { isIEIntranet, getPageRenderTime, querySelectorAll } from '@krakenjs/belter/src'; -import { FPTI_KEY, ENV, FUNDING, FPTI_USER_ACTION, COUNTRY } from '@paypal/sdk-constants/src'; -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; +import { + isIEIntranet, + getPageRenderTime, + querySelectorAll, +} from "@krakenjs/belter/src"; +import { + FPTI_KEY, + ENV, + FUNDING, + FPTI_USER_ACTION, + COUNTRY, +} from "@paypal/sdk-constants/src"; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -import type { LocaleType, Wallet } from '../types'; +import type { LocaleType } from "../types"; import { - getLogger, - setupLogger, - isStorageStateFresh, - isIOSSafari, - isAndroidChrome, - prepareLatencyInstrumentationPayload, - getNavigationTimeOrigin, - sendCountMetric, - sendGaugeMetric -} from '../lib'; + getLogger, + setupLogger, + isStorageStateFresh, + isIOSSafari, + isAndroidChrome, + prepareLatencyInstrumentationPayload, + getNavigationTimeOrigin, + sendCountMetric, +} from "../lib"; import { - DATA_ATTRIBUTES, FPTI_TRANSITION, FPTI_BUTTON_TYPE, FPTI_BUTTON_KEY, - FPTI_STATE, FPTI_CONTEXT_TYPE, FPTI_CUSTOM_KEY -} from '../constants'; -import type { GetQueriedEligibleFunding, OnShippingChange } from '../props'; + DATA_ATTRIBUTES, + FPTI_TRANSITION, + FPTI_BUTTON_TYPE, + FPTI_BUTTON_KEY, + FPTI_STATE, + FPTI_CONTEXT_TYPE, + FPTI_CUSTOM_KEY, +} from "../constants"; +import type { GetQueriedEligibleFunding, OnShippingChange } from "../props"; -import type { ButtonStyle } from './props'; +import type { ButtonStyle } from "./props"; -function getTemplateVersion() : string { - const templateVersion = document.body && document.body.getAttribute(`${ DATA_ATTRIBUTES.RENDER_VERSION }`); - return (templateVersion || 'unknown').replace(/[^a-zA-Z0-9]+/g, '_'); +function getTemplateVersion(): string { + const templateVersion = + document.body && + document.body.getAttribute(`${DATA_ATTRIBUTES.RENDER_VERSION}`); + return (templateVersion || "unknown").replace(/[^a-zA-Z0-9]+/g, "_"); } -function getClientVersion() : string { - const clientVersion = document.body && document.body.getAttribute(`${ DATA_ATTRIBUTES.CLIENT_VERSION }`); - return (clientVersion || 'unknown').replace(/[^a-zA-Z0-9]+/g, '_'); +function getClientVersion(): string { + const clientVersion = + document.body && + document.body.getAttribute(`${DATA_ATTRIBUTES.CLIENT_VERSION}`); + return (clientVersion || "unknown").replace(/[^a-zA-Z0-9]+/g, "_"); } -function getResponseStartTime() : number { - const startTime = document.body && document.body.getAttribute(DATA_ATTRIBUTES.RESPONSE_START_TIME); - return Number(startTime); +function getResponseStartTime(): number { + const startTime = + document.body && + document.body.getAttribute(DATA_ATTRIBUTES.RESPONSE_START_TIME); + return Number(startTime); } type ButtonLoggerOptions = {| - env : $Values, - sessionID : string, - clientID : string, - partnerAttributionID : ?string, - commit : boolean, - sdkCorrelationID : string, - buttonCorrelationID : string, - locale : LocaleType, - buttonSessionID : string, - merchantID : $ReadOnlyArray, - merchantDomain : string, - sdkVersion : string, - style : ButtonStyle, - fundingSource : ?$Values, - getQueriedEligibleFunding : GetQueriedEligibleFunding, - stickinessID : string, - buyerCountry : $Values, - onShippingChange : ?OnShippingChange, - wallet? : ?Wallet, - smartWalletOrderID? : string, - enableOrdersApprovalSmartWallet? : boolean, - product? : string + env: $Values, + sessionID: string, + clientID: string, + partnerAttributionID: ?string, + commit: boolean, + sdkCorrelationID: string, + buttonCorrelationID: string, + locale: LocaleType, + buttonSessionID: string, + merchantID: $ReadOnlyArray, + merchantDomain: string, + sdkVersion: string, + style: ButtonStyle, + fundingSource: ?$Values, + getQueriedEligibleFunding: GetQueriedEligibleFunding, + stickinessID: string, + buyerCountry: $Values, + onShippingChange: ?OnShippingChange, + product?: string, |}; -export function setupButtonLogger({ env, sessionID, buttonSessionID, clientID, partnerAttributionID, commit, sdkCorrelationID, buttonCorrelationID, locale, - merchantID, merchantDomain, sdkVersion, style, fundingSource, getQueriedEligibleFunding, stickinessID, buyerCountry, onShippingChange, wallet, smartWalletOrderID, product } : ButtonLoggerOptions) : ZalgoPromise { +export function setupButtonLogger({ + env, + sessionID, + buttonSessionID, + clientID, + partnerAttributionID, + commit, + sdkCorrelationID, + buttonCorrelationID, + locale, + merchantID, + merchantDomain, + sdkVersion, + style, + fundingSource, + getQueriedEligibleFunding, + stickinessID, + buyerCountry, + onShippingChange, + product, +}: ButtonLoggerOptions): ZalgoPromise { + const logger = getLogger(); - const logger = getLogger(); + setupLogger({ + env, + sessionID, + clientID, + sdkCorrelationID, + locale, + sdkVersion, + buyerCountry, + }); - setupLogger({ env, sessionID, clientID, sdkCorrelationID, locale, sdkVersion, buyerCountry }); + logger.addPayloadBuilder(() => { + return { + buttonSessionID, + buttonCorrelationID, + }; + }); - logger.addPayloadBuilder(() => { - return { - buttonSessionID, - buttonCorrelationID, - }; - }); + logger.addTrackingBuilder(() => { + return { + [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.BUTTON_SESSION_ID, + [FPTI_KEY.CONTEXT_ID]: buttonSessionID, + [FPTI_KEY.BUTTON_SESSION_UID]: buttonSessionID, + [FPTI_KEY.BUTTON_VERSION]: __SMART_BUTTONS__.__MINOR_VERSION__, + [FPTI_BUTTON_KEY.BUTTON_CORRELATION_ID]: buttonCorrelationID, + [FPTI_KEY.STICKINESS_ID]: isAndroidChrome() ? stickinessID : null, + [FPTI_KEY.PARTNER_ATTRIBUTION_ID]: partnerAttributionID, + [FPTI_KEY.USER_ACTION]: commit + ? FPTI_USER_ACTION.COMMIT + : FPTI_USER_ACTION.CONTINUE, + [FPTI_KEY.SELLER_ID]: merchantID[0], + [FPTI_KEY.MERCHANT_DOMAIN]: merchantDomain, + [FPTI_KEY.CHOSEN_FUNDING]: fundingSource, + [FPTI_KEY.PRODUCT]: product, + [FPTI_KEY.TIMESTAMP]: Date.now().toString(), + }; + }); - logger.addTrackingBuilder(() => { - return { - [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.BUTTON_SESSION_ID, - [FPTI_KEY.CONTEXT_ID]: buttonSessionID, - [FPTI_KEY.BUTTON_SESSION_UID]: buttonSessionID, - [FPTI_KEY.BUTTON_VERSION]: __SMART_BUTTONS__.__MINOR_VERSION__, - [FPTI_BUTTON_KEY.BUTTON_CORRELATION_ID]: buttonCorrelationID, - [FPTI_KEY.STICKINESS_ID]: isAndroidChrome() ? stickinessID : null, - [FPTI_KEY.PARTNER_ATTRIBUTION_ID]: partnerAttributionID, - [FPTI_KEY.USER_ACTION]: commit ? FPTI_USER_ACTION.COMMIT : FPTI_USER_ACTION.CONTINUE, - [FPTI_KEY.SELLER_ID]: merchantID[0], - [FPTI_KEY.MERCHANT_DOMAIN]: merchantDomain, - [FPTI_KEY.CHOSEN_FUNDING]: fundingSource, - [FPTI_KEY.PRODUCT]: product, - [FPTI_KEY.TOKEN]: smartWalletOrderID, - [FPTI_KEY.TIMESTAMP]: Date.now().toString() - }; - }); + if (isIEIntranet()) { + logger.warn("button_child_intranet_mode"); + } + + return ZalgoPromise.hash({ + pageRenderTime: getPageRenderTime(), + queriedEligibleFunding: getQueriedEligibleFunding(), + }).then(({ pageRenderTime, queriedEligibleFunding }) => { + const fundingSources = querySelectorAll( + `[${DATA_ATTRIBUTES.FUNDING_SOURCE}]`, + ) + .map((el) => { + return el.getAttribute(DATA_ATTRIBUTES.FUNDING_SOURCE); + }) + .filter(Boolean); + + const walletInstruments = querySelectorAll( + `[${DATA_ATTRIBUTES.INSTRUMENT_TYPE}]`, + ) + .flatMap((el) => { + const dataInstrumentType = el.getAttribute( + DATA_ATTRIBUTES.INSTRUMENT_TYPE, + ); + const dataSecondaryInstrumentType = el.getAttribute( + DATA_ATTRIBUTES.SECONDARY_INSTRUMENT_TYPE, + ); + const instrumentTypes = [ + dataInstrumentType, + dataSecondaryInstrumentType, + ]; + + return instrumentTypes; + }) + .filter(Boolean); + + const payNow = querySelectorAll(`[${DATA_ATTRIBUTES.FUNDING_SOURCE}]`) + .map((el) => { + return el.getAttribute(DATA_ATTRIBUTES.PAY_NOW); + }) + .some(Boolean); + + const { layout, color, shape, label, tagline = true } = style; - if (isIEIntranet()) { - logger.warn('button_child_intranet_mode'); + let nativeDevice = "non_native"; + if (isIOSSafari()) { + nativeDevice = "ios_safari"; + } else if (isAndroidChrome()) { + nativeDevice = "android_chrome"; } - return ZalgoPromise.hash({ - pageRenderTime: getPageRenderTime(), - queriedEligibleFunding: getQueriedEligibleFunding() - }).then(({ pageRenderTime, queriedEligibleFunding }) => { - - const fundingSources = querySelectorAll(`[${ DATA_ATTRIBUTES.FUNDING_SOURCE }]`).map(el => { - return el.getAttribute(DATA_ATTRIBUTES.FUNDING_SOURCE); - }).filter(Boolean); - - const walletInstruments = querySelectorAll(`[${ DATA_ATTRIBUTES.INSTRUMENT_TYPE }]`).flatMap(el => { - const dataInstrumentType = el.getAttribute(DATA_ATTRIBUTES.INSTRUMENT_TYPE); - const dataSecondaryInstrumentType = el.getAttribute(DATA_ATTRIBUTES.SECONDARY_INSTRUMENT_TYPE); - const instrumentTypes = [dataInstrumentType, dataSecondaryInstrumentType]; - - return instrumentTypes; - }).filter(Boolean); - - const payNow = querySelectorAll(`[${ DATA_ATTRIBUTES.FUNDING_SOURCE }]`).map(el => { - return el.getAttribute(DATA_ATTRIBUTES.PAY_NOW); - }).some(Boolean); - - const { layout, color, shape, label, tagline = true } = style; - - let nativeDevice = 'non_native'; - if (isIOSSafari()) { - nativeDevice = 'ios_safari'; - } else if (isAndroidChrome()) { - nativeDevice = 'android_chrome'; - } - - const serverRenderVersion = getTemplateVersion(); - const dotSeparatedRenderVersion = serverRenderVersion.split('_').join('.'); - - if (dotSeparatedRenderVersion !== sdkVersion) { - logger.warn('server_render_version_mismatch', {sdkVersion, serverRenderVersion}) - sendCountMetric({ - name: 'pp.app.paypal_sdk.buttons.server_render_version_mismatch', - dimensions: {} - }); - } - - logger.info("smart_payment_buttons_render_options", { - color, - label, - layout, - nativeDevice, - shape, - fundingInstruments: fundingSources.join(","), - fundingInstrumentsCount: fundingSources.length.toString(), - js_sdk_version: getClientVersion() , - storageState: isStorageStateFresh() ? 'fresh' : 'not_fresh', - tagline: tagline.toString(), - version: serverRenderVersion, - walletInstruments: walletInstruments.join(","), - walletInstrumentsCount: walletInstruments.length.toString(), - }); + const serverRenderVersion = getTemplateVersion(); + const dotSeparatedRenderVersion = serverRenderVersion.split("_").join("."); + + if (dotSeparatedRenderVersion !== sdkVersion) { + logger.info("server_render_version_mismatch", { + sdkVersion, + serverRenderVersion, + }); + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.server_render_version_mismatch", + dimensions: {}, + }); + } - sendGaugeMetric({ - name: 'pp.app.paypal_sdk.buttons', - event: 'load', - value: 1, - dimensions: { - js_sdk_version: getClientVersion(), - spb_version: serverRenderVersion - } - }) - - if (window.performance) { - try { - const responseStartTime = getResponseStartTime(); - const responseEndTime = getNavigationTimeOrigin() + performance.getEntriesByName('buttons-response-received').pop().startTime; - const cplPhases = prepareLatencyInstrumentationPayload(responseStartTime, responseEndTime); - logger.info('CPL_LATENCY_METRICS_SECOND_RENDER'); - logger.track({ - [FPTI_KEY.STATE]: 'CPL_LATENCY_METRICS', - [FPTI_KEY.TRANSITION]: 'process_client_metrics', - [FPTI_KEY.PAGE]: 'main:xo:paypal-components:smart-payment-buttons', - [FPTI_KEY.CPL_COMP_METRICS]: JSON.stringify(cplPhases?.comp || {}) - }); - } catch (error) { - logger.info(`button_render_CPL_instrumentation_log_error`, error); - } - } else { - logger.info(`button_render_CPL_instrumentation_not_executed`); - } - - const getFundingInstrumentId = function (): ?string { - if (wallet?.paypal?.instruments[0]?.secondaryInstruments && wallet.paypal.instruments[0].instrumentID) { - return `${ wallet.paypal.instruments[0].instrumentID },${ wallet.paypal.instruments[0].secondaryInstruments[0].instrumentID }`; - } else if (wallet?.paypal?.instruments[0]?.instrumentID) { - return `${ wallet.paypal.instruments[0].instrumentID }`; - } - } - - const tracking = { - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.BUTTON_LOAD, - [FPTI_KEY.EVENT_NAME]: FPTI_TRANSITION.BUTTON_LOAD, - [FPTI_KEY.FUNDING_LIST]: fundingSources.join(':'), - [FPTI_KEY.FI_LIST]: walletInstruments.join(':'), - [FPTI_KEY.SELECTED_FI]: fundingSource, - [FPTI_KEY.FUNDING_COUNT]: fundingSources.length.toString(), - [FPTI_KEY.PAGE_LOAD_TIME]: pageRenderTime ? pageRenderTime.toString() : '', - [FPTI_KEY.POTENTIAL_PAYMENT_METHODS]: Array.isArray(queriedEligibleFunding) ? queriedEligibleFunding.join(':') : '', - [FPTI_KEY.PAY_NOW]: payNow.toString(), - [FPTI_BUTTON_KEY.BUTTON_LAYOUT]: layout, - [FPTI_BUTTON_KEY.BUTTON_COLOR]: color, - [FPTI_BUTTON_KEY.BUTTON_SIZE]: 'responsive', - [FPTI_BUTTON_KEY.BUTTON_SHAPE]: shape, - [FPTI_BUTTON_KEY.BUTTON_LABEL]: label, - [FPTI_BUTTON_KEY.BUTTON_WIDTH]: window.innerWidth, - [FPTI_BUTTON_KEY.BUTTON_TYPE]: FPTI_BUTTON_TYPE.IFRAME, - [FPTI_BUTTON_KEY.BUTTON_TAGLINE_ENABLED]: tagline ? '1' : '0', - [FPTI_CUSTOM_KEY.SHIPPING_CALLBACK_PASSED]: onShippingChange ? '1' : '0' - } - - const fundingInstrumentId = getFundingInstrumentId(); - - if (fundingInstrumentId) { - tracking[`${ FPTI_KEY.FI_ID }`] = fundingInstrumentId; - } - - logger.track(tracking); - - logger.flush(); + logger.info("smart_payment_buttons_render_options", { + color, + label, + layout, + nativeDevice, + shape, + fundingInstruments: fundingSources.join(","), + fundingInstrumentsCount: fundingSources.length.toString(), + js_sdk_version: getClientVersion(), + storageState: isStorageStateFresh() ? "fresh" : "not_fresh", + tagline: tagline.toString(), + version: serverRenderVersion, + walletInstruments: walletInstruments.join(","), + walletInstrumentsCount: walletInstruments.length.toString(), }); + + if (window.performance) { + try { + const responseStartTime = getResponseStartTime(); + const responseEndTime = + getNavigationTimeOrigin() + + performance.getEntriesByName("buttons-response-received").pop() + .startTime; + const cplPhases = prepareLatencyInstrumentationPayload( + responseStartTime, + responseEndTime, + ); + logger.info("CPL_LATENCY_METRICS_SECOND_RENDER"); + logger.track({ + [FPTI_KEY.STATE]: "CPL_LATENCY_METRICS", + [FPTI_KEY.TRANSITION]: "process_client_metrics", + [FPTI_KEY.PAGE]: "main:xo:paypal-components:smart-payment-buttons", + [FPTI_KEY.CPL_COMP_METRICS]: JSON.stringify(cplPhases?.comp || {}), + }); + } catch (error) { + logger.info(`button_render_CPL_instrumentation_log_error`, error); + } + } else { + logger.info(`button_render_CPL_instrumentation_not_executed`); + } + + const tracking = { + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.BUTTON_LOAD, + [FPTI_KEY.EVENT_NAME]: FPTI_TRANSITION.BUTTON_LOAD, + [FPTI_KEY.FUNDING_LIST]: fundingSources.join(":"), + [FPTI_KEY.FI_LIST]: walletInstruments.join(":"), + [FPTI_KEY.SELECTED_FI]: fundingSource, + [FPTI_KEY.FUNDING_COUNT]: fundingSources.length.toString(), + [FPTI_KEY.PAGE_LOAD_TIME]: pageRenderTime + ? pageRenderTime.toString() + : "", + [FPTI_KEY.POTENTIAL_PAYMENT_METHODS]: Array.isArray( + queriedEligibleFunding, + ) + ? queriedEligibleFunding.join(":") + : "", + [FPTI_KEY.PAY_NOW]: payNow.toString(), + [FPTI_BUTTON_KEY.BUTTON_LAYOUT]: layout, + [FPTI_BUTTON_KEY.BUTTON_COLOR]: color, + [FPTI_BUTTON_KEY.BUTTON_SIZE]: "responsive", + [FPTI_BUTTON_KEY.BUTTON_SHAPE]: shape, + [FPTI_BUTTON_KEY.BUTTON_LABEL]: label, + [FPTI_BUTTON_KEY.BUTTON_WIDTH]: window.innerWidth, + [FPTI_BUTTON_KEY.BUTTON_TYPE]: FPTI_BUTTON_TYPE.IFRAME, + [FPTI_BUTTON_KEY.BUTTON_TAGLINE_ENABLED]: tagline ? "1" : "0", + [FPTI_CUSTOM_KEY.SHIPPING_CALLBACK_PASSED]: onShippingChange ? "1" : "0", + }; + + logger.track(tracking); + + logger.flush(); + }); } diff --git a/src/button/logger.test.js b/src/button/logger.test.js index a823b5628f..d6f68db665 100644 --- a/src/button/logger.test.js +++ b/src/button/logger.test.js @@ -43,7 +43,7 @@ const buttonLoggerProps = { const findEventInMockLogs = (event, mock) => // mockCallback.mock.calls[0][0] mock.mock.calls.some((mockArgs) => - mockArgs.some((mockEvent) => mockEvent === event) + mockArgs.some((mockEvent) => mockEvent === event), ); describe("setupButtonLogger", () => { @@ -92,7 +92,7 @@ describe("setupButtonLogger", () => { await setupButtonLogger(buttonLoggerProps); expect( - findEventInMockLogs("CPL_LATENCY_METRICS_SECOND_RENDER", infoMock) + findEventInMockLogs("CPL_LATENCY_METRICS_SECOND_RENDER", infoMock), ).toEqual(true); expect(trackMock).toHaveBeenNthCalledWith(1, { @@ -109,13 +109,13 @@ describe("setupButtonLogger", () => { await setupButtonLogger(buttonLoggerProps); expect( - findEventInMockLogs("CPL_LATENCY_METRICS_SECOND_RENDER", infoMock) + findEventInMockLogs("CPL_LATENCY_METRICS_SECOND_RENDER", infoMock), ).toEqual(false); expect( findEventInMockLogs( "button_render_CPL_instrumentation_log_error", - infoMock - ) + infoMock, + ), ).toEqual(true); }); @@ -124,13 +124,13 @@ describe("setupButtonLogger", () => { await setupButtonLogger(buttonLoggerProps); expect( - findEventInMockLogs("CPL_LATENCY_METRICS_SECOND_RENDER", infoMock) + findEventInMockLogs("CPL_LATENCY_METRICS_SECOND_RENDER", infoMock), ).toEqual(false); expect( findEventInMockLogs( "button_render_CPL_instrumentation_not_executed", - infoMock - ) + infoMock, + ), ).toEqual(true); }); }); diff --git a/src/button/menu.js b/src/button/menu.js index 554302ecc7..bfa8ff72f1 100644 --- a/src/button/menu.js +++ b/src/button/menu.js @@ -1,111 +1,133 @@ /* @flow */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -import type { MenuChoices, MenuFlowType, MenuComponentInstance } from '../types'; -import type { Payment } from '../payment-flows'; +import type { + MenuChoices, + MenuFlowType, + MenuComponentInstance, +} from "../types"; +import type { Payment } from "../payment-flows"; -import type { ButtonProps, Components } from './props'; -import { enableLoadingSpinner, disableLoadingSpinner } from './dom'; +import type { ButtonProps, Components } from "./props"; +import { enableLoadingSpinner, disableLoadingSpinner } from "./dom"; type SmartMenuProps = {| - containerUID : string, - clientID : string, - Menu : MenuFlowType, - onFocus? : () => void, - onFocusFail? : () => void + containerUID: string, + clientID: string, + Menu: MenuFlowType, + onFocus?: () => void, + onFocusFail?: () => void, |}; let menu; -export function renderButtonSmartMenu({ containerUID, clientID, Menu } : SmartMenuProps) : MenuComponentInstance { - if (menu) { - return menu; - } +export function renderButtonSmartMenu({ + containerUID, + clientID, + Menu, +}: SmartMenuProps): MenuComponentInstance { + if (menu) { + return menu; + } - const newMenu = Menu({ clientID }); + const newMenu = Menu({ clientID }); - newMenu.hide(); - newMenu.renderTo(window.xprops.getParent(), `#${ containerUID } #smart-menu`); + newMenu.hide(); + newMenu.renderTo(window.xprops.getParent(), `#${containerUID} #smart-menu`); - menu = newMenu; + menu = newMenu; - return menu; + return menu; } -export function prerenderButtonSmartMenu({ props, components } : {| props : ButtonProps, components : Components |}) { - const { clientID, uid: containerUID } = props; - const { Menu } = components; - - if (!clientID) { - return; - } - - renderButtonSmartMenu({ containerUID, clientID, Menu }); +export function prerenderButtonSmartMenu({ + props, + components, +}: {| + props: ButtonProps, + components: Components, +|}) { + const { clientID, uid: containerUID } = props; + const { Menu } = components; + + if (!clientID) { + return; + } + + renderButtonSmartMenu({ containerUID, clientID, Menu }); } export function clearButtonSmartMenu() { - menu = null; + menu = null; } type ButtonMenuProps = {| - payment : Payment, - props : ButtonProps, - components : Components, - choices : MenuChoices + payment: Payment, + props: ButtonProps, + components: Components, + choices: MenuChoices, |}; -export function showButtonSmartMenu({ props, payment, components, choices } : ButtonMenuProps) : ZalgoPromise { - const { clientID, uid: containerUID } = props; - const { button, menuToggle } = payment; - const { Menu } = components; +export function showButtonSmartMenu({ + props, + payment, + components, + choices, +}: ButtonMenuProps): ZalgoPromise { + const { clientID, uid: containerUID } = props; + const { button, menuToggle } = payment; + const { Menu } = components; + + if (!clientID) { + throw new Error(`Can not render menu without client id`); + } + + const smartMenu = + menu || renderButtonSmartMenu({ containerUID, clientID, Menu }); + menu = smartMenu; + + const getVerticalOffset = () => button.getBoundingClientRect().bottom; + const loadingTimeout = setTimeout(() => enableLoadingSpinner(button), 50); + + const updateProps = () => { + return smartMenu.updateProps({ + clientID, + choices, + verticalOffset: getVerticalOffset(), + // eslint-disable-next-line no-use-before-define + onFocusFail, + // eslint-disable-next-line no-use-before-define + onBlur, + }); + }; - if (!clientID) { - throw new Error(`Can not render menu without client id`); - } + window.addEventListener("resize", updateProps); + + const onBlur = () => { + smartMenu.hide(); + window.removeEventListener("resize", updateProps); + }; + + const onFocusFail = () => { + if (menuToggle) { + const blur = () => { + menuToggle.removeEventListener("blur", blur); + onBlur(); + }; - const smartMenu = menu || renderButtonSmartMenu({ containerUID, clientID, Menu }); - menu = smartMenu; - - const getVerticalOffset = () => button.getBoundingClientRect().bottom; - const loadingTimeout = setTimeout(() => enableLoadingSpinner(button), 50); - - const updateProps = () => { - return smartMenu.updateProps({ - clientID, - choices, - verticalOffset: getVerticalOffset(), - // eslint-disable-next-line no-use-before-define - onFocusFail, - // eslint-disable-next-line no-use-before-define - onBlur - }); - }; - - window.addEventListener('resize', updateProps); - - const onBlur = () => { - smartMenu.hide(); - window.removeEventListener('resize', updateProps); - }; - - const onFocusFail = () => { - if (menuToggle) { - const blur = () => { - menuToggle.removeEventListener('blur', blur); - onBlur(); - }; - - menuToggle.addEventListener('blur', blur); - } - }; - - return updateProps().then(() => { - return smartMenu.show(); - }).then(() => { - disableLoadingSpinner(button); - }).finally(() => { - clearTimeout(loadingTimeout); + menuToggle.addEventListener("blur", blur); + } + }; + + return updateProps() + .then(() => { + return smartMenu.show(); + }) + .then(() => { + disableLoadingSpinner(button); + }) + .finally(() => { + clearTimeout(loadingTimeout); }); } - diff --git a/src/button/pay.js b/src/button/pay.js index a10f94c309..da4464a76e 100644 --- a/src/button/pay.js +++ b/src/button/pay.js @@ -1,300 +1,517 @@ /* @flow */ -import { noop, stringifyError, isCrossSiteTrackingEnabled } from '@krakenjs/belter/src'; -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { FPTI_KEY } from '@paypal/sdk-constants/src'; - -import { applepay, checkout, cardField, cardForm, paymentFields, native, vaultCapture, walletCapture, popupBridge, type Payment, type PaymentFlow } from '../payment-flows'; -import { getClientsideTimestamp, getLogger, sendBeacon, sendCountMetric } from '../lib'; -import { FPTI_TRANSITION, BUYER_INTENT, FPTI_CONTEXT_TYPE, FPTI_CUSTOM_KEY, FPTI_STATE } from '../constants'; -import { updateButtonClientConfig } from '../api'; -import { getConfirmOrder } from '../props/confirmOrder'; -import { enableVaultSetup } from '../middleware'; -import { type Experiments } from '../types'; - -import { type ButtonProps, type Config, type ServiceData, type Components } from './props'; -import { enableLoadingSpinner, disableLoadingSpinner } from './dom'; -import { validateOrder } from './validation'; -import { showButtonSmartMenu } from './menu'; - -const PAYMENT_FLOWS : $ReadOnlyArray = [ - vaultCapture, - walletCapture, - cardField, - cardForm, - paymentFields, - popupBridge, - applepay, - native, - checkout +import { + noop, + stringifyError, + isCrossSiteTrackingEnabled, +} from "@krakenjs/belter/src"; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { FPTI_KEY } from "@paypal/sdk-constants/src"; + +import { + applepay, + checkout, + cardField, + cardForm, + paymentFields, + native, + vaultCapture, + walletCapture, + popupBridge, + type Payment, + type PaymentFlow, +} from "../payment-flows"; +import { + getClientsideTimestamp, + getLogger, + sendBeacon, + sendCountMetric, +} from "../lib"; +import { + FPTI_TRANSITION, + BUYER_INTENT, + FPTI_CONTEXT_TYPE, + FPTI_CUSTOM_KEY, + FPTI_STATE, +} from "../constants"; +import { updateButtonClientConfig } from "../api"; +import { getConfirmOrder } from "../props/confirmOrder"; +import { enableVaultSetup } from "../middleware"; +import { type Experiments } from "../types"; + +import { + type ButtonProps, + type Config, + type ServiceData, + type Components, +} from "./props"; +import { enableLoadingSpinner, disableLoadingSpinner } from "./dom"; +import { validateOrder } from "./validation"; +import { showButtonSmartMenu } from "./menu"; + +const PAYMENT_FLOWS: $ReadOnlyArray = [ + vaultCapture, + walletCapture, + cardField, + cardForm, + paymentFields, + popupBridge, + applepay, + native, + checkout, ]; -export function setupPaymentFlows({ props, config, serviceData, components } : {| props : ButtonProps, config : Config, serviceData : ServiceData, components : Components |}) : ZalgoPromise { - return ZalgoPromise.all(PAYMENT_FLOWS.map(flow => { - return flow.isEligible({ props, config, serviceData }) - ? flow.setup({ props, config, serviceData, components }) - : null; - })).then(noop); +export function setupPaymentFlows({ + props, + config, + serviceData, + components, +}: {| + props: ButtonProps, + config: Config, + serviceData: ServiceData, + components: Components, +|}): ZalgoPromise { + return ZalgoPromise.all( + PAYMENT_FLOWS.map((flow) => { + return flow.isEligible({ props, config, serviceData }) + ? flow.setup({ props, config, serviceData, components }) + : null; + }), + ).then(noop); } -export function getPaymentFlow({ props, payment, config, serviceData } : {| props : ButtonProps, payment : Payment, config : Config, components : Components, serviceData : ServiceData |}) : PaymentFlow { - if (!props.fundingSource && payment.fundingSource) { - props.fundingSource = payment.fundingSource; +export function getPaymentFlow({ + props, + payment, + config, + serviceData, +}: {| + props: ButtonProps, + payment: Payment, + config: Config, + components: Components, + serviceData: ServiceData, +|}): PaymentFlow { + if (!props.fundingSource && payment.fundingSource) { + props.fundingSource = payment.fundingSource; + } + + for (const flow of PAYMENT_FLOWS) { + if ( + flow.isEligible({ props, config, serviceData }) && + flow.isPaymentEligible({ props, payment, config, serviceData }) + ) { + return flow; } + } - for (const flow of PAYMENT_FLOWS) { - if (flow.isEligible({ props, config, serviceData }) && flow.isPaymentEligible({ props, payment, config, serviceData })) { - return flow; - } - } - - throw new Error(`Could not find eligible payment flow`); + throw new Error(`Could not find eligible payment flow`); } const sendPersonalizationBeacons = (personalization) => { - if (personalization && personalization.tagline && personalization.tagline.tracking) { - sendBeacon(personalization.tagline.tracking.click); - } - if (personalization && personalization.buttonText && personalization.buttonText.tracking) { - sendBeacon(personalization.buttonText.tracking.click); - } + if ( + personalization && + personalization.tagline && + personalization.tagline.tracking + ) { + sendBeacon(personalization.tagline.tracking.click); + } + if ( + personalization && + personalization.buttonText && + personalization.buttonText.tracking + ) { + sendBeacon(personalization.buttonText.tracking.click); + } }; type InitiatePaymentOptions = {| - payment : Payment, - props : ButtonProps, - serviceData : ServiceData, - config : Config, - components : Components, - experiments? : Experiments + payment: Payment, + props: ButtonProps, + serviceData: ServiceData, + config: Config, + components: Components, + experiments: Experiments, |}; -export function initiatePaymentFlow({ payment, serviceData, config, components, props, experiments } : InitiatePaymentOptions) : ZalgoPromise { - const { button, fundingSource, instrumentType, buyerIntent } = payment; - const buttonLabel = props.style?.label; +export function initiatePaymentFlow({ + payment, + serviceData, + config, + components, + props, + experiments, +}: InitiatePaymentOptions): ZalgoPromise { + const { button, fundingSource, instrumentType, buyerIntent } = payment; + const buttonLabel = props.style?.label; + + return ZalgoPromise.try(() => { + const { + merchantID, + personalization, + fundingEligibility, + buyerCountry, + featureFlags, + } = serviceData; + const { + clientID, + onClick, + createOrder, + env, + vault, + partnerAttributionID, + userExperienceFlow, + buttonSessionID, + intent, + currency, + clientAccessToken, + createBillingAgreement, + createSubscription, + commit, + disableFunding, + disableCard, + userIDToken, + enableNativeCheckout, + } = props; + + sendPersonalizationBeacons(personalization); + + const restart = ({ payment: restartPayment }) => + initiatePaymentFlow({ + payment: restartPayment, + serviceData, + config, + components, + props, + experiments, + }); + + const { name, init, inline, spinner, updateFlowClientConfig } = + getPaymentFlow({ props, payment, config, components, serviceData }); + const { click, start, close } = init({ + props, + config, + serviceData, + components, + payment, + restart, + experiments, + }); - return ZalgoPromise.try(() => { - const { merchantID, personalization, fundingEligibility, buyerCountry, featureFlags } = serviceData; - const { clientID, onClick, createOrder, env, vault, partnerAttributionID, userExperienceFlow, buttonSessionID, intent, currency, - clientAccessToken, createBillingAgreement, createSubscription, commit, disableFunding, disableCard, userIDToken, enableNativeCheckout } = props; + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.click.count", + dimensions: { + fundingSource, + spbPaymentFlow: name, + }, + }); - sendPersonalizationBeacons(personalization); + getLogger() + .addPayloadBuilder(() => { + return { token: null }; + }) + .addTrackingBuilder(() => { + return { + [FPTI_KEY.CHOSEN_FUNDING]: fundingSource, + [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.BUTTON_SESSION_ID, + [FPTI_KEY.CONTEXT_ID]: buttonSessionID, + [FPTI_KEY.BUTTON_SESSION_UID]: buttonSessionID, + }; + }) + .info(`button_click_pay_flow_${name}`) + .info(`button_click_fundingsource_${fundingSource}`) + .info(`button_click_instrument_${instrumentType || "default"}`) + .info( + `cross_site_tracking_${ + isCrossSiteTrackingEnabled("enforce_policy") ? "enabled" : "disabled" + }`, + ) + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.BUTTON_CLICK, + [FPTI_KEY.EVENT_NAME]: FPTI_TRANSITION.BUTTON_CLICK, + [FPTI_KEY.CHOSEN_FI_TYPE]: instrumentType, + [FPTI_KEY.PAYMENT_FLOW]: name, + [FPTI_KEY.IS_VAULT]: instrumentType ? "1" : "0", + [FPTI_CUSTOM_KEY.INFO_MSG]: enableNativeCheckout ? "tester" : "", + client_time: getClientsideTimestamp(), + }) + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.TRANSITION]: `cross_site_tracking_${ + isCrossSiteTrackingEnabled("enforce_policy") ? "enabled" : "disabled" + }`, + }) + .flush(); + + const loggingPromise = ZalgoPromise.try(() => { + return window.xprops.sessionState + .get(`__confirm_${fundingSource}_payload__`) + .then((confirmPayload) => { + const fieldsSessionID = confirmPayload + ? confirmPayload.payment_source[fundingSource].metadata + .fieldsSessionID + : ""; + getLogger().addTrackingBuilder(() => { + return { + [FPTI_KEY.FIELDS_COMPONENT_SESSION_ID]: fieldsSessionID, + }; + }); + }); + }); - const restart = ({ payment: restartPayment }) => - initiatePaymentFlow({ payment: restartPayment, serviceData, config, components, props }); + const clickPromise = click + ? ZalgoPromise.try(click) + : ZalgoPromise.resolve(); + clickPromise.catch(noop); - const { name, init, inline, spinner, updateFlowClientConfig } = getPaymentFlow({ props, payment, config, components, serviceData }); - const { click, start, close } = init({ props, config, serviceData, components, payment, restart, experiments }); + return ZalgoPromise.try(() => { + return onClick ? onClick({ fundingSource }) : true; + }) + .then((valid) => { + return valid ? clickPromise : false; + }) + .then((valid) => { + if (valid === false) { + return; + } - sendCountMetric({ - name: 'pp.app.paypal_sdk.buttons.click.count', - dimensions: { - fundingSource, - spbPaymentFlow: name, - }}); - - getLogger() - .addPayloadBuilder(() => { - return { token: null }; - }) - .addTrackingBuilder(() => { - return { - [FPTI_KEY.CHOSEN_FUNDING]: fundingSource, - [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.BUTTON_SESSION_ID, - [FPTI_KEY.CONTEXT_ID]: buttonSessionID, - [FPTI_KEY.BUTTON_SESSION_UID]: buttonSessionID, - }; - }) - .info(`button_click_pay_flow_${ name }`) - .info(`button_click_fundingsource_${ fundingSource }`) - .info(`button_click_instrument_${ instrumentType || 'default' }`) - .info(`cross_site_tracking_${ isCrossSiteTrackingEnabled('enforce_policy') ? 'enabled' : 'disabled' }`) - .track({ - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.BUTTON_CLICK, - [FPTI_KEY.EVENT_NAME]: FPTI_TRANSITION.BUTTON_CLICK, - [FPTI_KEY.CHOSEN_FI_TYPE]: instrumentType, - [FPTI_KEY.PAYMENT_FLOW]: name, - [FPTI_KEY.IS_VAULT]: instrumentType ? '1' : '0', - [FPTI_CUSTOM_KEY.INFO_MSG]: enableNativeCheckout ? 'tester' : '', - client_time: getClientsideTimestamp() - }) - .track({ - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.TRANSITION]: `cross_site_tracking_${ isCrossSiteTrackingEnabled('enforce_policy') ? 'enabled' : 'disabled' }` - }) - .flush(); - - const loggingPromise = ZalgoPromise.try(() => { - return window.xprops.sessionState.get(`__confirm_${ fundingSource }_payload__`).then(confirmPayload => { - const fieldsSessionID = confirmPayload ? confirmPayload.payment_source[fundingSource].metadata.fieldsSessionID : ''; - getLogger() - .addTrackingBuilder(() => { - return { - [FPTI_KEY.FIELDS_COMPONENT_SESSION_ID]: fieldsSessionID - }; - }); - }); - }); + if (spinner) { + enableLoadingSpinner(button); + } - const clickPromise = click ? ZalgoPromise.try(click) : ZalgoPromise.resolve(); - clickPromise.catch(noop); + const updateClientConfigPromise = createOrder() + .then((orderID) => { + if (updateFlowClientConfig) { + return updateFlowClientConfig({ + orderID, + payment, + userExperienceFlow, + buttonSessionID, + featureFlags, + }); + } - return ZalgoPromise.try(() => { - return onClick ? onClick({ fundingSource }) : true; - }).then(valid => { - return valid ? clickPromise : false; - }).then(valid => { - if (valid === false) { - return; + function updateButtonClientConfigWrapper(): ZalgoPromise { + return updateButtonClientConfig({ + orderID, + fundingSource, + inline, + userExperienceFlow, + featureFlags, + }).catch((err) => { + getLogger().error("update_client_config_error", { + err: stringifyError(err), + }); + }); } - if (spinner) { - enableLoadingSpinner(button); + // feature flag to control blocking/non-blocking behavior + if (featureFlags.isButtonClientConfigCallBlocking) { + return updateButtonClientConfigWrapper(); + } else { + // non-blocking call by default + updateButtonClientConfigWrapper(); + } + }) + .catch(noop); + + const vaultPromise = createOrder().then((orderID) => { + return ZalgoPromise.try(() => { + if (clientID && buyerIntent === BUYER_INTENT.PAY) { + return enableVaultSetup({ + orderID, + vault, + clientAccessToken, + fundingEligibility, + fundingSource, + createBillingAgreement, + createSubscription, + clientID, + merchantID, + buyerCountry, + currency, + commit, + intent, + disableFunding, + disableCard, + userIDToken, + userExperienceFlow, + buttonSessionID, + inline, + }); } + }); + }); - const updateClientConfigPromise = createOrder().then(orderID => { - if (updateFlowClientConfig) { - return updateFlowClientConfig({ orderID, payment, userExperienceFlow, buttonSessionID, featureFlags }); - } - - function updateButtonClientConfigWrapper() : ZalgoPromise { - return updateButtonClientConfig({ orderID, fundingSource, inline, userExperienceFlow, featureFlags }).catch(err => { - getLogger().error('update_client_config_error', { err: stringifyError(err) }); - }); - } - - // feature flag to control blocking/non-blocking behavior - if (featureFlags.isButtonClientConfigCallBlocking) { - return updateButtonClientConfigWrapper(); - } else { - // non-blocking call by default - updateButtonClientConfigWrapper(); - } - }).catch(noop); - - const vaultPromise = createOrder().then(orderID => { - return ZalgoPromise.try(() => { - if (clientID && buyerIntent === BUYER_INTENT.PAY) { - return enableVaultSetup({ orderID, vault, clientAccessToken, fundingEligibility, fundingSource, createBillingAgreement, createSubscription, - clientID, merchantID, buyerCountry, currency, commit, intent, disableFunding, disableCard, userIDToken, userExperienceFlow, buttonSessionID, inline }); - } - }); + const startPromise = updateClientConfigPromise.then(() => { + if (featureFlags.isButtonClientConfigCallBlocking) { + getLogger().info("blocking_cco_call_resolved", { + time: getClientsideTimestamp(), + fundingSource, + buttonSessionID, }); - - const startPromise = updateClientConfigPromise.then(() => { - if (featureFlags.isButtonClientConfigCallBlocking) { - getLogger().info('blocking_cco_call_resolved', {time: getClientsideTimestamp(), fundingSource, buttonSessionID}); - } else { - getLogger().info('non_blocking_cco_call_resolved', {time: getClientsideTimestamp(), fundingSource, buttonSessionID}); - } - - return start(); + } else { + getLogger().info("non_blocking_cco_call_resolved", { + time: getClientsideTimestamp(), + fundingSource, + buttonSessionID, }); + } - const validateOrderPromise = createOrder().then(orderID => { - return validateOrder(orderID, { - env, - merchantID, - intent, - currency, - vault, - buttonLabel, - featureFlags: serviceData.featureFlags - }); - }); + return start(); + }); - const confirmOrderPromise = createOrder().then((orderID) => { - return window.xprops.sessionState.get( - `__confirm_${ fundingSource }_payload__` - ).then(confirmOrderPayload => { - if (!confirmOrderPayload) { - // skip the confirm call when there is no confirm payload (regular flow). - return; - } - - return getConfirmOrder({ - orderID, payload: confirmOrderPayload, partnerAttributionID - }, { - facilitatorAccessToken: serviceData.facilitatorAccessToken - }); - }); - }); + const validateOrderPromise = createOrder().then((orderID) => { + return validateOrder(orderID, { + env, + merchantID, + intent, + currency, + vault, + buttonLabel, + featureFlags: serviceData.featureFlags, + }); + }); - return ZalgoPromise.all([ - loggingPromise, - updateClientConfigPromise, - clickPromise, - vaultPromise, - validateOrderPromise, - startPromise, - confirmOrderPromise - ]).catch(err => { - return ZalgoPromise.try(close).then(() => { - throw err; - }); - }).then(() => { - if (featureFlags.isButtonClientConfigCallBlocking) { - getLogger().info('redirect_to_xorouter_blocking_cco', {time: getClientsideTimestamp(), fundingSource, buttonSessionID}); - } else { - getLogger().info('redirect_to_xorouter_non_blocking_cco', {time: getClientsideTimestamp(), fundingSource, buttonSessionID}); - } - }) + const confirmOrderPromise = createOrder().then((orderID) => { + return window.xprops.sessionState + .get(`__confirm_${fundingSource}_payload__`) + .then((confirmOrderPayload) => { + if (!confirmOrderPayload) { + // skip the confirm call when there is no confirm payload (regular flow). + return; + } + + return getConfirmOrder( + { + orderID, + payload: confirmOrderPayload, + partnerAttributionID, + }, + { + facilitatorAccessToken: serviceData.facilitatorAccessToken, + }, + ); + }); }); - }).finally(() => { - disableLoadingSpinner(button); - }); + return ZalgoPromise.all([ + loggingPromise, + updateClientConfigPromise, + clickPromise, + vaultPromise, + validateOrderPromise, + startPromise, + confirmOrderPromise, + ]) + .catch((err) => { + return ZalgoPromise.try(close).then(() => { + throw err; + }); + }) + .then(() => { + if (featureFlags.isButtonClientConfigCallBlocking) { + getLogger().info("redirect_to_xorouter_blocking_cco", { + time: getClientsideTimestamp(), + fundingSource, + buttonSessionID, + }); + } else { + getLogger().info("redirect_to_xorouter_non_blocking_cco", { + time: getClientsideTimestamp(), + fundingSource, + buttonSessionID, + }); + } + }); + }); + }).finally(() => { + disableLoadingSpinner(button); + }); } type InitiateMenuOptions = {| - payment : Payment, - props : ButtonProps, - serviceData : ServiceData, - config : Config, - components : Components, - experiments? : Experiments + payment: Payment, + props: ButtonProps, + serviceData: ServiceData, + config: Config, + components: Components, + experiments: Experiments, |}; -export function initiateMenuFlow({ payment, serviceData, config, components, props, experiments } : InitiateMenuOptions) : ZalgoPromise { - return ZalgoPromise.try(() => { - const { fundingSource, button } = payment; - - const { name, setupMenu } = getPaymentFlow({ props, payment, config, components, serviceData }); - - if (!setupMenu) { - throw new Error(`${ name } does not support menu`); - } - - getLogger().info(`menu_click`).info(`pay_flow_${ name }`).track({ - [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.MENU_CLICK, - [FPTI_KEY.CHOSEN_FUNDING]: fundingSource, - [FPTI_KEY.PAYMENT_FLOW]: name - }).flush(); - - const restart = ({ payment: restartPayment }) => - initiatePaymentFlow({ payment: restartPayment, serviceData, config, components, props }); +export function initiateMenuFlow({ + payment, + serviceData, + config, + components, + props, + experiments, +}: InitiateMenuOptions): ZalgoPromise { + return ZalgoPromise.try(() => { + const { fundingSource, button } = payment; + + const { name, setupMenu } = getPaymentFlow({ + props, + payment, + config, + components, + serviceData, + }); - const choices = setupMenu({ props, payment, serviceData, components, config, restart, experiments }).map(choice => { - return { - ...choice, - onSelect: (...args) => { - if (choice.spinner) { - enableLoadingSpinner(button); - } - - return ZalgoPromise.try(() => { - return choice.onSelect(...args); - }).then(() => { - if (choice.spinner) { - disableLoadingSpinner(button); - } - }); - } - }; - }); + if (!setupMenu) { + throw new Error(`${name} does not support menu`); + } - return showButtonSmartMenu({ props, payment, components, choices }); + getLogger() + .info(`menu_click`) + .info(`pay_flow_${name}`) + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.MENU_CLICK, + [FPTI_KEY.CHOSEN_FUNDING]: fundingSource, + [FPTI_KEY.PAYMENT_FLOW]: name, + }) + .flush(); + + const restart = ({ payment: restartPayment }) => + initiatePaymentFlow({ + payment: restartPayment, + serviceData, + config, + components, + props, + experiments, + }); + + const choices = setupMenu({ + props, + payment, + serviceData, + components, + config, + restart, + experiments, + }).map((choice) => { + return { + ...choice, + onSelect: (...args) => { + if (choice.spinner) { + enableLoadingSpinner(button); + } + + return ZalgoPromise.try(() => { + return choice.onSelect(...args); + }).then(() => { + if (choice.spinner) { + disableLoadingSpinner(button); + } + }); + }, + }; }); + + return showButtonSmartMenu({ props, payment, components, choices }); + }); } diff --git a/src/button/props.js b/src/button/props.js index 6b1b04e6c8..e76514708a 100644 --- a/src/button/props.js +++ b/src/button/props.js @@ -1,282 +1,336 @@ /* @flow */ -import { COUNTRY, FUNDING, CARD, INTENT, type FundingEligibilityType } from '@paypal/sdk-constants/src'; -import type { InstallmentsFlowType } from '@paypal/installments/src/types'; - -import type { ContentType, ProxyWindow, Wallet, CheckoutFlowType, CardFormFlowType, - ThreeDomainSecureFlowType, MenuFlowType, PersonalizationType, QRCodeType, VenmoWebType, PaymentFieldsFlowType, InlinePaymentFieldsEligibility, Experiments, FeatureFlags } from '../types'; -import { type FirebaseConfig } from '../api'; -import { getNonce } from '../lib'; -import { getProps, type XProps, type Props } from '../props/props'; -import { getCallbackProps, type CallbackProps, type CallbackPropsOptions } from '../props/callbackProps'; +import { + COUNTRY, + FUNDING, + CARD, + INTENT, + type FundingEligibilityType, +} from "@paypal/sdk-constants/src"; +import type { InstallmentsFlowType } from "@paypal/installments/src/types"; + +import type { + ContentType, + ProxyWindow, + Wallet, + CheckoutFlowType, + CardFormFlowType, + ThreeDomainSecureFlowType, + MenuFlowType, + PersonalizationType, + QRCodeType, + VenmoWebType, + PaymentFieldsFlowType, + InlinePaymentFieldsEligibility, + Experiments, + FeatureFlags, +} from "../types"; +import { type FirebaseConfig } from "../api"; +import { getNonce } from "../lib"; +import { getProps, type XProps, type Props } from "../props/props"; +import { + getCallbackProps, + type CallbackProps, + type CallbackPropsOptions, +} from "../props/callbackProps"; // export something to force webpack to see this as an ES module export const TYPES = true; - export type PrerenderDetailsType = {| - win ? : ? ProxyWindow, - fundingSource : $Values, - card ? : ? $Values + win?: ?ProxyWindow, + fundingSource: $Values, + card?: ?$Values, |}; export type ButtonStyle = {| - layout : string, - color : string, - shape : string, - label : string, - tagline : boolean | void + layout: string, + color: string, + shape: string, + label: string, + tagline: boolean | void, |}; export type ButtonXProps = {| - ...XProps, - ...CallbackPropsOptions, - style : ButtonStyle, - buttonSessionID : string + ...XProps, + ...CallbackPropsOptions, + style: ButtonStyle, + buttonSessionID: string, |}; export type ButtonProps = {| - ...Props, - ...CallbackProps, - style : ButtonStyle, - buttonSessionID : string + ...Props, + ...CallbackProps, + style: ButtonStyle, + buttonSessionID: string, |}; export function getButtonProps({ - facilitatorAccessToken, - brandedDefault, - paymentSource, - experiments, - featureFlags, - enableOrdersApprovalSmartWallet, - smartWalletOrderID -} : {| - facilitatorAccessToken : string, - brandedDefault : boolean | null, - paymentSource : $Values | null, - experiments: Experiments; - featureFlags: FeatureFlags, - enableOrdersApprovalSmartWallet? : boolean, - smartWalletOrderID? : string -|}) : ButtonProps { - const xprops : ButtonXProps = window.xprops; - - let { - buttonSessionID, - style, - branded, - intent, - partnerAttributionID, - merchantID, - clientID, - clientAccessToken, - vault = false, - currency, - flow - } = xprops; - - branded = branded ?? brandedDefault; - - if (xprops.createVaultSetupToken) { - if (experiments.payPalWalletVaultWithoutPurchase){ - if (xprops.createOrder) { - throw new Error(`Do not pass both createVaultSetupToken and createOrder`); - } - } else { - throw new Error(`You are not currently eligible to save a PayPal wallet without purchase.`) + facilitatorAccessToken, + brandedDefault, + paymentSource, + experiments, + featureFlags, +}: {| + facilitatorAccessToken: string, + brandedDefault: boolean | null, + paymentSource: $Values | null, + experiments: Experiments, + featureFlags: FeatureFlags, +|}): ButtonProps { + const xprops: ButtonXProps = window.xprops; + + let { + buttonSessionID, + style, + branded, + intent, + partnerAttributionID, + merchantID, + clientID, + clientAccessToken, + vault = false, + currency, + flow, + } = xprops; + + branded = branded ?? brandedDefault; + + if (xprops.createVaultSetupToken) { + if (experiments.payPalWalletVaultWithoutPurchase) { + if (xprops.createOrder) { + throw new Error( + `Do not pass both createVaultSetupToken and createOrder`, + ); } + } else { + throw new Error( + `You are not currently eligible to save a PayPal wallet without purchase.`, + ); } + } - if (xprops.createBillingAgreement) { - if (xprops.createOrder) { - throw new Error(`Do not pass both createBillingAgreement and createOrder`); - } + if (xprops.createBillingAgreement) { + if (xprops.createOrder) { + throw new Error( + `Do not pass both createBillingAgreement and createOrder`, + ); + } - if (!xprops.vault) { - throw new Error(`Must pass vault=true to sdk to use createBillingAgreement`); - } + if (!xprops.vault) { + throw new Error( + `Must pass vault=true to sdk to use createBillingAgreement`, + ); } + } - if (xprops.createSubscription) { - if (xprops.createOrder) { - throw new Error(`Do not pass both createSubscription and createOrder`); - } + if (xprops.createSubscription) { + if (xprops.createOrder) { + throw new Error(`Do not pass both createSubscription and createOrder`); + } - if (xprops.createBillingAgreement) { - throw new Error(`Do not pass both createSubscription and createBillingAgreement`); - } + if (xprops.createBillingAgreement) { + throw new Error( + `Do not pass both createSubscription and createBillingAgreement`, + ); + } - if (!xprops.vault) { - throw new Error(`Must pass vault=true to sdk to use createSubscription`); - } + if (!xprops.vault) { + throw new Error(`Must pass vault=true to sdk to use createSubscription`); } + } - if (intent === INTENT.TOKENIZE) { - if (!xprops.createBillingAgreement) { - throw new Error(`Must pass createBillingAgreement with intent=tokenize`); - } + if (intent === INTENT.TOKENIZE) { + if (!xprops.createBillingAgreement) { + throw new Error(`Must pass createBillingAgreement with intent=tokenize`); + } - if (xprops.createOrder || xprops.createSubscription) { - throw new Error(`Must not pass createOrder or createSubscription with intent=tokenize`); - } + if (xprops.createOrder || xprops.createSubscription) { + throw new Error( + `Must not pass createOrder or createSubscription with intent=tokenize`, + ); } + } - if (intent === INTENT.SUBSCRIPTION) { - if (!xprops.createSubscription) { - throw new Error(`Must pass createSubscription with intent=subscription`); - } + if (intent === INTENT.SUBSCRIPTION) { + if (!xprops.createSubscription) { + throw new Error(`Must pass createSubscription with intent=subscription`); + } - if (xprops.createOrder || xprops.createBillingAgreement) { - throw new Error(`Must not pass createOrder or createBillingAgreement with intent=tokenize`); - } + if (xprops.createOrder || xprops.createBillingAgreement) { + throw new Error( + `Must not pass createOrder or createBillingAgreement with intent=tokenize`, + ); } + } - const props = getProps({ branded, enableOrdersApprovalSmartWallet, smartWalletOrderID }) + const props = getProps({ branded }); - // TODO: This is a lot...maybe we consider just passing in `xprops` and having the function handle splitting things off. - const callbackProps = getCallbackProps({ - paymentSource, - partnerAttributionID, - merchantID, - clientID, - facilitatorAccessToken, - currency, - intent, - enableOrdersApprovalSmartWallet, - smartWalletOrderID, - branded, - clientAccessToken, - vault, - experiments, - featureFlags, - createBillingAgreement: xprops.createBillingAgreement, - createSubscription: xprops.createSubscription, - createOrder: xprops.createOrder, - onError: props.onError, - onApprove: xprops.onApprove, - onComplete: xprops.onComplete, - onCancel: xprops.onCancel, - onShippingChange: xprops.onShippingChange, - onShippingAddressChange: xprops.onShippingAddressChange, - onShippingOptionsChange: xprops.onShippingOptionsChange, - createVaultSetupToken: xprops.createVaultSetupToken, - flow - }) - return { - ...props, - ...callbackProps, - style, - buttonSessionID, - branded - }; + // TODO: This is a lot...maybe we consider just passing in `xprops` and having the function handle splitting things off. + const callbackProps = getCallbackProps({ + paymentSource, + partnerAttributionID, + merchantID, + clientID, + facilitatorAccessToken, + currency, + intent, + branded, + clientAccessToken, + vault, + experiments, + featureFlags, + createBillingAgreement: xprops.createBillingAgreement, + createSubscription: xprops.createSubscription, + createOrder: xprops.createOrder, + onError: props.onError, + onApprove: xprops.onApprove, + onComplete: xprops.onComplete, + onCancel: xprops.onCancel, + onShippingChange: xprops.onShippingChange, + onShippingAddressChange: xprops.onShippingAddressChange, + onShippingOptionsChange: xprops.onShippingOptionsChange, + createVaultSetupToken: xprops.createVaultSetupToken, + flow, + }); + return { + ...props, + ...callbackProps, + style, + buttonSessionID, + branded, + }; } export type Components = {| - Checkout : CheckoutFlowType, - CardForm : CardFormFlowType, - ThreeDomainSecure : ThreeDomainSecureFlowType, - Menu : MenuFlowType, - Installments : InstallmentsFlowType, - QRCode : QRCodeType, - PaymentFields : PaymentFieldsFlowType, - Venmo : VenmoWebType, + Checkout: CheckoutFlowType, + CardForm: CardFormFlowType, + ThreeDomainSecure: ThreeDomainSecureFlowType, + Menu: MenuFlowType, + Installments: InstallmentsFlowType, + QRCode: QRCodeType, + PaymentFields: PaymentFieldsFlowType, + Venmo: VenmoWebType, |}; -export function getComponents() : Components { - const { Checkout, CardForm, ThreeDomainSecure, Menu, Installments, QRCode, PaymentFields, Venmo } = paypal; - return { Checkout, CardForm, ThreeDomainSecure, Menu, Installments, QRCode, PaymentFields, Venmo }; +export function getComponents(): Components { + const { + Checkout, + CardForm, + ThreeDomainSecure, + Menu, + Installments, + QRCode, + PaymentFields, + Venmo, + } = paypal; + return { + Checkout, + CardForm, + ThreeDomainSecure, + Menu, + Installments, + QRCode, + PaymentFields, + Venmo, + }; } export type Config = {| - sdkVersion : string, - cspNonce : ?string, - firebase : ?FirebaseConfig + sdkVersion: string, + cspNonce: ?string, + firebase: ?FirebaseConfig, |}; -export function getConfig({ serverCSPNonce, firebaseConfig } : {| serverCSPNonce : ?string, firebaseConfig : ?FirebaseConfig |}) : Config { - const cspNonce = serverCSPNonce || getNonce(); - const { version: sdkVersion } = paypal; - - return { - sdkVersion, - cspNonce, - firebase: firebaseConfig - }; +export function getConfig({ + serverCSPNonce, + firebaseConfig, +}: {| + serverCSPNonce: ?string, + firebaseConfig: ?FirebaseConfig, +|}): Config { + const cspNonce = serverCSPNonce || getNonce(); + const { version: sdkVersion } = paypal; + + return { + sdkVersion, + cspNonce, + firebase: firebaseConfig, + }; } export type ServiceData = {| - merchantID : $ReadOnlyArray, - buyerCountry : $Values, - fundingEligibility : FundingEligibilityType, - wallet : ?Wallet, - facilitatorAccessToken : string, - sdkMeta : string, - buyerAccessToken : ?string, - content : ContentType, - eligibility : {| - cardForm : boolean, - paymentFields : InlinePaymentFieldsEligibility, - venmoWebEnabled: boolean, - |}, - cookies : string, - personalization : PersonalizationType, - featureFlags: FeatureFlags + merchantID: $ReadOnlyArray, + buyerCountry: $Values, + fundingEligibility: FundingEligibilityType, + wallet: ?Wallet, + facilitatorAccessToken: string, + sdkMeta: string, + buyerAccessToken: ?string, + content: ContentType, + eligibility: {| + cardForm: boolean, + paymentFields: InlinePaymentFieldsEligibility, + venmoWebEnabled: boolean, + |}, + cookies: string, + personalization: PersonalizationType, + featureFlags: FeatureFlags, |}; type ServiceDataOptions = {| - facilitatorAccessToken : string, - buyerGeoCountry : $Values, - fundingEligibility : FundingEligibilityType, - wallet : ?Wallet, - buyerAccessToken : ?string, - serverMerchantID : $ReadOnlyArray, - sdkMeta : string, - content : ContentType, - eligibility : {| - cardFields : boolean, - inlinePaymentFields : InlinePaymentFieldsEligibility, - isServiceWorkerEligible : boolean, - venmoEnableOnShippingChange: boolean, - |}, - cookies : string, - personalization : PersonalizationType, - featureFlags: FeatureFlags + facilitatorAccessToken: string, + buyerGeoCountry: $Values, + fundingEligibility: FundingEligibilityType, + wallet: ?Wallet, + buyerAccessToken: ?string, + serverMerchantID: $ReadOnlyArray, + sdkMeta: string, + content: ContentType, + eligibility: {| + cardFields: boolean, + inlinePaymentFields: InlinePaymentFieldsEligibility, + isServiceWorkerEligible: boolean, + venmoEnableOnShippingChange: boolean, + |}, + cookies: string, + personalization: PersonalizationType, + featureFlags: FeatureFlags, |}; export function getServiceData({ - facilitatorAccessToken, - sdkMeta, - content, - buyerGeoCountry, + facilitatorAccessToken, + sdkMeta, + content, + buyerGeoCountry, + fundingEligibility, + wallet, + buyerAccessToken, + serverMerchantID, + eligibility, + cookies, + personalization, + featureFlags, +}: ServiceDataOptions): ServiceData { + return { + merchantID: serverMerchantID, + buyerCountry: buyerGeoCountry || COUNTRY.US, fundingEligibility, wallet, + sdkMeta, + content, buyerAccessToken, - serverMerchantID, - eligibility, + facilitatorAccessToken, + eligibility: { + cardForm: eligibility.cardFields || false, + paymentFields: eligibility.inlinePaymentFields || { + inlineEligibleAPMs: [], + isInlineEnabled: false, + }, + venmoWebEnabled: eligibility.venmoEnableOnShippingChange, + }, cookies, personalization, - featureFlags -} : ServiceDataOptions) : ServiceData { - - return { - merchantID: serverMerchantID, - buyerCountry: buyerGeoCountry || COUNTRY.US, - fundingEligibility, - wallet, - sdkMeta, - content, - buyerAccessToken, - facilitatorAccessToken, - eligibility: { - cardForm: eligibility.cardFields || false, - paymentFields: eligibility.inlinePaymentFields || { - inlineEligibleAPMs : [], - isInlineEnabled : false - }, - venmoWebEnabled: eligibility.venmoEnableOnShippingChange, - }, - cookies, - personalization, - featureFlags - }; + featureFlags, + }; } diff --git a/src/button/props.test.js b/src/button/props.test.js index bd92d8d3d2..5d192d6d31 100644 --- a/src/button/props.test.js +++ b/src/button/props.test.js @@ -41,7 +41,7 @@ describe("getButtonProps", () => { it("should retrieve callbackProps", () => { const callbackPropsSpy = vi.spyOn( getCallbackPropsStuff, - "getCallbackProps" + "getCallbackProps", ); window.xprops.intent = INTENT.CAPTURE; @@ -64,14 +64,14 @@ describe("getButtonProps", () => { window.xprops.createBillingAgreement = vi.fn(); window.xprops.createOrder = vi.fn(); expect(() => getButtonProps(defaultArgs)).toThrowError( - "Do not pass both createBillingAgreement and createOrder" + "Do not pass both createBillingAgreement and createOrder", ); }); it("should fail if createBillingAgreement is passed in but not vault", () => { window.xprops.createBillingAgreement = vi.fn(); expect(() => getButtonProps(defaultArgs)).toThrowError( - "Must pass vault=true to sdk to use createBillingAgreement" + "Must pass vault=true to sdk to use createBillingAgreement", ); }); @@ -79,21 +79,21 @@ describe("getButtonProps", () => { window.xprops.createSubscription = vi.fn(); window.xprops.createOrder = vi.fn(); expect(() => getButtonProps(defaultArgs)).toThrowError( - "Do not pass both createSubscription and createOrder" + "Do not pass both createSubscription and createOrder", ); }); it("should fail if createSubscription but not vault", () => { window.xprops.createSubscription = vi.fn(); expect(() => getButtonProps(defaultArgs)).toThrowError( - "Must pass vault=true to sdk to use createSubscription" + "Must pass vault=true to sdk to use createSubscription", ); }); it("should fail if intent is tokenize but no createBillingAgreement", () => { window.xprops.intent = INTENT.TOKENIZE; expect(() => getButtonProps(defaultArgs)).toThrowError( - "Must pass createBillingAgreement with intent=tokenize" + "Must pass createBillingAgreement with intent=tokenize", ); }); @@ -102,7 +102,7 @@ describe("getButtonProps", () => { window.xprops.createBillingAgreement = vi.fn(); window.xprops.createOrder = () => "ok"; expect(() => getButtonProps(defaultArgs)).toThrowError( - "Do not pass both createBillingAgreement and createOrder" + "Do not pass both createBillingAgreement and createOrder", ); }); @@ -111,7 +111,7 @@ describe("getButtonProps", () => { window.xprops.createBillingAgreement = vi.fn(); window.xprops.createSubscription = vi.fn(); expect(() => getButtonProps(defaultArgs)).toThrowError( - "Must pass vault=true to sdk to use createBillingAgreement" + "Must pass vault=true to sdk to use createBillingAgreement", ); }); @@ -119,7 +119,7 @@ describe("getButtonProps", () => { window.xprops.intent = INTENT.SUBSCRIPTION; window.xprops.vault = true; expect(() => getButtonProps(defaultArgs)).toThrowError( - "Must pass createSubscription with intent=subscription" + "Must pass createSubscription with intent=subscription", ); }); @@ -129,7 +129,7 @@ describe("getButtonProps", () => { window.xprops.createSubscription = vi.fn(); window.xprops.createOrder = vi.fn(); expect(() => getButtonProps(defaultArgs)).toThrowError( - "Do not pass both createSubscription and createOrder" + "Do not pass both createSubscription and createOrder", ); }); @@ -139,18 +139,7 @@ describe("getButtonProps", () => { window.xprops.createSubscription = vi.fn(); window.xprops.createBillingAgreement = vi.fn(); expect(() => getButtonProps(defaultArgs)).toThrowError( - "Do not pass both createSubscription and createBillingAgreement" + "Do not pass both createSubscription and createBillingAgreement", ); }); - - it("passes through enableOrdersApprovalSmartWallet and smartWalletOrderID to props", () => { - window.xprops.intent = INTENT.CAPTURE; - const props = getButtonProps({ - ...defaultArgs, - enableOrdersApprovalSmartWallet: true, - smartWalletOrderID: "abc", - }); - expect(props.enableOrdersApprovalSmartWallet).toBe(true); - expect(props.smartWalletOrderID).toEqual("abc"); - }); }); diff --git a/src/button/remember.js b/src/button/remember.js index ad5153be9e..3d2013087e 100644 --- a/src/button/remember.js +++ b/src/button/remember.js @@ -1,14 +1,27 @@ /* @flow */ -import { FUNDING, type FundingEligibilityType } from '@paypal/sdk-constants/src'; -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; +import { + FUNDING, + type FundingEligibilityType, +} from "@paypal/sdk-constants/src"; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -import type { RememberFunding } from '../props'; +import type { RememberFunding } from "../props"; -export function setupRemember({ rememberFunding, fundingEligibility } : {| rememberFunding : RememberFunding, fundingEligibility : FundingEligibilityType |}) : ZalgoPromise { - return ZalgoPromise.try(() => { - if (fundingEligibility && fundingEligibility.venmo && fundingEligibility.venmo.eligible) { - return rememberFunding([ FUNDING.VENMO ]); - } - }); +export function setupRemember({ + rememberFunding, + fundingEligibility, +}: {| + rememberFunding: RememberFunding, + fundingEligibility: FundingEligibilityType, +|}): ZalgoPromise { + return ZalgoPromise.try(() => { + if ( + fundingEligibility && + fundingEligibility.venmo && + fundingEligibility.venmo.eligible + ) { + return rememberFunding([FUNDING.VENMO]); + } + }); } diff --git a/src/button/remember.test.js b/src/button/remember.test.js new file mode 100644 index 0000000000..71b84dc05a --- /dev/null +++ b/src/button/remember.test.js @@ -0,0 +1,20 @@ +/* @flow */ + +import { describe, it, expect, vi } from "vitest"; +import { FUNDING } from "@paypal/sdk-constants/src"; + +import { setupRemember } from "./remember"; + +const rememberMock = vi.fn(); + +describe("setupRemember", () => { + it("should call xprops.remember with venmo if venmo is eligible", () => { + setupRemember({ + rememberFunding: rememberMock, + fundingEligibility: { + [FUNDING.VENMO]: { eligible: true, branded: false }, + }, + }); + expect(rememberMock).toHaveBeenCalledWith([FUNDING.VENMO]); + }); +}); diff --git a/src/button/validation.js b/src/button/validation.js index b354509e74..54e1059597 100644 --- a/src/button/validation.js +++ b/src/button/validation.js @@ -1,373 +1,487 @@ /* @flow */ /* eslint no-console: off */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { INTENT, SDK_QUERY_KEYS, CURRENCY, ENV, FPTI_KEY, SDK_SETTINGS, VAULT } from '@paypal/sdk-constants/src'; - -import type {FeatureFlags} from '../types' -import type { CreateBillingAgreement, CreateSubscription } from '../props'; -import { BUTTON_LABEL, FPTI_CONTEXT_TYPE, FPTI_CUSTOM_KEY, ITEM_CATEGORY, FPTI_TRANSITION, FPTI_STATE } from '../constants'; -import { getSupplementalOrderInfo } from '../api'; -import { isEmailAddress } from '../lib'; -import { getLogger } from '../lib/logger' +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { + INTENT, + SDK_QUERY_KEYS, + CURRENCY, + ENV, + FPTI_KEY, + SDK_SETTINGS, + VAULT, +} from "@paypal/sdk-constants/src"; + +import type { FeatureFlags } from "../types"; +import type { CreateBillingAgreement, CreateSubscription } from "../props"; +import { + BUTTON_LABEL, + FPTI_CONTEXT_TYPE, + FPTI_CUSTOM_KEY, + ITEM_CATEGORY, + FPTI_TRANSITION, + FPTI_STATE, +} from "../constants"; +import { getSupplementalOrderInfo } from "../api"; +import { isEmailAddress } from "../lib"; +import { getLogger } from "../lib/logger"; type Payee = {| - merchantId? : string, - email? : {| - stringValue? : string - |} + merchantId?: string, + email?: {| + stringValue?: string, + |}, |}; // check whether each merchantIdsOrEmails is in payees and each payee is in merchantIds // merchantIdsOrEmails is an arry of mixed merchant id and emails // payees is an array of payee object {merchant_id, email} -function isValidMerchantIDs(merchantIDs : $ReadOnlyArray, payees : $ReadOnlyArray) : boolean { - if (merchantIDs.length !== payees.length) { - return false; +function isValidMerchantIDs( + merchantIDs: $ReadOnlyArray, + payees: $ReadOnlyArray, +): boolean { + if (merchantIDs.length !== payees.length) { + return false; + } + + // split merchantIds into 2 arrays, one for emails and one for merchant ids + const merchantEmails = []; + const merchantIds = []; + + merchantIDs.forEach((id) => { + if (isEmailAddress(id)) { + merchantEmails.push(id.toLowerCase()); + } else { + merchantIds.push(id); } - - // split merchantIds into 2 arrays, one for emails and one for merchant ids - const merchantEmails = []; - const merchantIds = []; - - merchantIDs.forEach(id => { - if (isEmailAddress(id)) { - merchantEmails.push(id.toLowerCase()); - } else { - merchantIds.push(id); - } - }); - - const foundEmail = merchantEmails.every(email => { - return payees.some(payee => { - return email === (payee.email && payee.email.stringValue && payee.email.stringValue.toLowerCase()); - }); - }); - - const foundMerchantId = merchantIds.every(id => { - return payees.some(payee => { - return (id === payee.merchantId); - }); + }); + + const foundEmail = merchantEmails.every((email) => { + return payees.some((payee) => { + return ( + email === + (payee.email && + payee.email.stringValue && + payee.email.stringValue.toLowerCase()) + ); }); + }); - // if the id or email is not in payees - if (!foundEmail || !foundMerchantId) { - return false; - } - - // now check payees - // each payer should either has merchant_id in merchantIds or has email in merchantEmails - const foundPayee = payees.every(payee => { - return (merchantIds.indexOf(payee.merchantId) > -1 || merchantEmails.indexOf(payee.email && payee.email.stringValue && payee.email.stringValue.toLowerCase()) > -1); + const foundMerchantId = merchantIds.every((id) => { + return payees.some((payee) => { + return id === payee.merchantId; }); - return foundPayee; + }); + + // if the id or email is not in payees + if (!foundEmail || !foundMerchantId) { + return false; + } + + // now check payees + // each payer should either has merchant_id in merchantIds or has email in merchantEmails + const foundPayee = payees.every((payee) => { + return ( + merchantIds.indexOf(payee.merchantId) > -1 || + merchantEmails.indexOf( + payee.email && + payee.email.stringValue && + payee.email.stringValue.toLowerCase(), + ) > -1 + ); + }); + return foundPayee; } type TriggerIntegrationErrorOptions = {| - error : string, - message? : string, - orderID? : string, - loggerPayload? : {| - [string] : mixed - |}, - throwError? : boolean, - featureFlags: FeatureFlags + error: string, + message?: string, + orderID?: string, + loggerPayload?: {| + [string]: mixed, + |}, + throwError?: boolean, + featureFlags: FeatureFlags, |}; -function triggerIntegrationError({ error, message = error, orderID, loggerPayload = {}, throwError = true, featureFlags } : TriggerIntegrationErrorOptions) { - const shouldThrowError = throwError && featureFlags.shouldThrowIntegrationError; - - getLogger() - .warn(error, loggerPayload) - .track({ - [ FPTI_KEY.STATE ]: FPTI_STATE.BUTTON, - [ FPTI_KEY.TRANSITION ]: FPTI_TRANSITION.ORDER_VALIDATE, - [ FPTI_KEY.CONTEXT_TYPE ]: FPTI_CONTEXT_TYPE.ORDER_ID, - [ FPTI_KEY.TOKEN ]: orderID, - [ FPTI_KEY.CONTEXT_ID ]: orderID, - [ FPTI_CUSTOM_KEY.INTEGRATION_ISSUE ]: error, - [ FPTI_CUSTOM_KEY.INTEGRATION_WHITELIST ]: shouldThrowError ? 'false' : 'true', - [ FPTI_KEY.ERROR_DESC ]: message - }).flush(); - - if (shouldThrowError) { - console.error(message); - throw new Error(message); - } else { - console.warn(message); - } +function triggerIntegrationError({ + error, + message = error, + orderID, + loggerPayload = {}, + throwError = true, + featureFlags, +}: TriggerIntegrationErrorOptions) { + const shouldThrowError = + throwError && featureFlags.shouldThrowIntegrationError; + + getLogger() + .warn(error, loggerPayload) + .track({ + [FPTI_KEY.STATE]: FPTI_STATE.BUTTON, + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.ORDER_VALIDATE, + [FPTI_KEY.CONTEXT_TYPE]: FPTI_CONTEXT_TYPE.ORDER_ID, + [FPTI_KEY.TOKEN]: orderID, + [FPTI_KEY.CONTEXT_ID]: orderID, + [FPTI_CUSTOM_KEY.INTEGRATION_ISSUE]: error, + [FPTI_CUSTOM_KEY.INTEGRATION_WHITELIST]: shouldThrowError + ? "false" + : "true", + [FPTI_KEY.ERROR_DESC]: message, + }) + .flush(); + + if (shouldThrowError) { + console.error(message); + throw new Error(message); + } else { + console.warn(message); + } } type ValidatePropsOptions = {| - intent : $Values, - createBillingAgreement : ?CreateBillingAgreement, - createSubscription : ?CreateSubscription, - featureFlags: FeatureFlags + intent: $Values, + createBillingAgreement: ?CreateBillingAgreement, + createSubscription: ?CreateSubscription, + featureFlags: FeatureFlags, |}; -export function validateProps({ intent, createBillingAgreement, createSubscription, featureFlags } : ValidatePropsOptions) { - const logger = getLogger(); +export function validateProps({ + intent, + createBillingAgreement, + createSubscription, + featureFlags, +}: ValidatePropsOptions) { + const logger = getLogger(); + + if (createBillingAgreement && intent !== INTENT.TOKENIZE) { + triggerIntegrationError({ + error: `smart_button_validation_error_expected_intent_tokenize`, + message: `Expected intent=${INTENT.TOKENIZE} to be passed to SDK with createBillingAgreement, but got intent=${intent}`, + featureFlags, + loggerPayload: { intent }, + throwError: false, + }); + } + + if (createSubscription && intent !== INTENT.SUBSCRIPTION) { + triggerIntegrationError({ + error: `smart_button_validation_error_expected_intent_subscription`, + message: `Expected intent=${INTENT.SUBSCRIPTION} to be passed to SDK with createSubscription, but got intent=${intent}`, + featureFlags, + loggerPayload: { intent }, + throwError: false, + }); + } - if (createBillingAgreement && intent !== INTENT.TOKENIZE) { - triggerIntegrationError({ - error: `smart_button_validation_error_expected_intent_tokenize`, - message: `Expected intent=${ INTENT.TOKENIZE } to be passed to SDK with createBillingAgreement, but got intent=${ intent }`, - featureFlags, - loggerPayload: { intent }, - throwError: false - }); + logger.flush(); +} + +const VALIDATE_INTENTS = [INTENT.CAPTURE, INTENT.AUTHORIZE, INTENT.ORDER]; + +type OrderValidateOptions = {| + env: $Values, + merchantID: $ReadOnlyArray, + intent: $Values, + currency: $Values, + vault: boolean, + buttonLabel: ?string, + featureFlags: FeatureFlags, +|}; + +export function validateOrder( + orderID: string, + { + env, + merchantID, + currency, + intent, + vault, + buttonLabel, + featureFlags, + }: OrderValidateOptions, +): ZalgoPromise { + const logger = getLogger(); + + // eslint-disable-next-line complexity + return getSupplementalOrderInfo(orderID).then((order) => { + const cart = order.checkoutSession.cart; + const cartIntent = + cart.intent.toLowerCase() === "sale" + ? INTENT.CAPTURE + : cart.intent.toLowerCase(); + const initiationIntent = + cart.supplementary?.initiationIntent?.toLowerCase() === "authorization" + ? INTENT.AUTHORIZE + : cart.supplementary?.initiationIntent?.toLowerCase(); + const cartCurrency = cart.amounts && cart.amounts.total.currencyCode; + const cartAmount = cart.amounts && cart.amounts.total.currencyValue; + const cartBillingType = cart.billingType; + const intentMatch = cartIntent === intent || initiationIntent === intent; + + if (!intentMatch && VALIDATE_INTENTS.indexOf(intent) !== -1) { + triggerIntegrationError({ + error: "smart_button_validation_error_incorrect_intent", + message: `Expected intent from order api call to be ${intent}, got ${cartIntent}. Please ensure you are passing ${ + SDK_QUERY_KEYS.INTENT + }=${ + initiationIntent || cartIntent + } to the sdk url. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, + featureFlags, + loggerPayload: { cartIntent, intent }, + orderID, + }); } - if (createSubscription && intent !== INTENT.SUBSCRIPTION) { + if ( + !window.xprops.createBillingAgreement && + buttonLabel === BUTTON_LABEL.DONATE + ) { + const category = ITEM_CATEGORY.DONATION; + const itemCategory = cart.category || ""; + + if (!itemCategory || itemCategory !== category) { triggerIntegrationError({ - error: `smart_button_validation_error_expected_intent_subscription`, - message: `Expected intent=${ INTENT.SUBSCRIPTION } to be passed to SDK with createSubscription, but got intent=${ intent }`, - featureFlags, - loggerPayload: { intent }, - throwError: false + error: "smart_button_validation_error_incorrect_item_category", + message: `Expected item category from order api call to be ${category}, got ${itemCategory}. Please ensure you are passing category=${category} for all items in the order payload. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, + featureFlags, + loggerPayload: { itemCategory, category }, + orderID, }); + } } - logger.flush(); -} + if (cartCurrency && cartCurrency !== currency) { + triggerIntegrationError({ + error: "smart_button_validation_error_incorrect_currency", + message: `Expected currency from order api call to be ${currency}, got ${cartCurrency}. Please ensure you are passing ${SDK_QUERY_KEYS.CURRENCY}=${cartCurrency} to the sdk url. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, + featureFlags, + loggerPayload: { cartCurrency, currency }, + orderID, + }); + } -const VALIDATE_INTENTS = [ - INTENT.CAPTURE, - INTENT.AUTHORIZE, - INTENT.ORDER -]; + if (!merchantID || merchantID.length === 0) { + triggerIntegrationError({ + error: "smart_button_validation_error_no_merchant_id", + message: `Could not determine correct merchant id`, + featureFlags, + orderID, + }); + } -type OrderValidateOptions = {| - env : $Values, - merchantID : $ReadOnlyArray, - intent : $Values, - currency : $Values, - vault : boolean, - buttonLabel : ?string, - featureFlags: FeatureFlags -|}; + if (cartBillingType && !vault && !window.xprops.createVaultSetupToken) { + triggerIntegrationError({ + error: `smart_button_validation_error_billing_${ + cartAmount ? "with" : "without" + }_purchase_no_vault`, + message: `Expected ${ + SDK_QUERY_KEYS.VAULT + }=${VAULT.TRUE.toString()} for a billing transaction`, + featureFlags, + orderID, + loggerPayload: { cartBillingType, vault }, + throwError: false, + }); + } -export function validateOrder(orderID : string, { env, merchantID, currency, intent, vault, buttonLabel, featureFlags } : OrderValidateOptions) : ZalgoPromise { - const logger = getLogger(); - - // eslint-disable-next-line complexity - return getSupplementalOrderInfo(orderID).then(order => { - const cart = order.checkoutSession.cart; - const cartIntent = (cart.intent.toLowerCase() === 'sale') - ? INTENT.CAPTURE - : cart.intent.toLowerCase(); - const initiationIntent = cart.supplementary?.initiationIntent?.toLowerCase() === 'authorization' - ? INTENT.AUTHORIZE - : cart.supplementary?.initiationIntent?.toLowerCase(); - const cartCurrency = cart.amounts && cart.amounts.total.currencyCode; - const cartAmount = cart.amounts && cart.amounts.total.currencyValue; - const cartBillingType = cart.billingType; - const intentMatch = cartIntent === intent || initiationIntent === intent; - - if (!intentMatch && VALIDATE_INTENTS.indexOf(intent) !== -1) { - triggerIntegrationError({ - error: 'smart_button_validation_error_incorrect_intent', - message: `Expected intent from order api call to be ${ intent }, got ${ cartIntent }. Please ensure you are passing ${ SDK_QUERY_KEYS.INTENT }=${ initiationIntent || cartIntent } to the sdk url. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, - featureFlags, - loggerPayload: { cartIntent, intent }, - orderID - }); - } + if (vault && window.xprops.createVaultSetupToken) { + triggerIntegrationError({ + error: + "smart_button_validation_error_vault_passed_with_create_vault_setup_token", + message: `Query parameter ${SDK_QUERY_KEYS.VAULT} is not needed when using createVaultSetupToken`, + featureFlags, + orderID, + loggerPayload: { vault, cartBillingType }, + throwError: false, + }); + } else if ( + vault && + !cartBillingType && + !window.xprops.createBillingAgreement && + !window.xprops.createSubscription && + !window.xprops.clientAccessToken && + !window.xprops.userIDToken + ) { + triggerIntegrationError({ + error: `smart_button_validation_error_vault_passed_not_needed`, + message: `Expected ${ + SDK_QUERY_KEYS.VAULT + }=${VAULT.FALSE.toString()} for a non-billing, non-subscription transaction`, + featureFlags, + orderID, + loggerPayload: { vault, cartBillingType }, + throwError: false, + }); + } - if (!window.xprops.createBillingAgreement && buttonLabel === BUTTON_LABEL.DONATE) { - const category = ITEM_CATEGORY.DONATION; - const itemCategory = cart.category || ''; - - if (!itemCategory || itemCategory !== category) { - triggerIntegrationError({ - error: 'smart_button_validation_error_incorrect_item_category', - message: `Expected item category from order api call to be ${ category }, got ${ itemCategory }. Please ensure you are passing category=${ category } for all items in the order payload. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, - featureFlags, - loggerPayload: { itemCategory, category }, - orderID - }); - } - } + if ( + cartBillingType && + !cartAmount && + intent !== INTENT.TOKENIZE && + !window.xprops.createVaultSetupToken && + !window.xprops.createSubscription + ) { + triggerIntegrationError({ + error: `smart_button_validation_error_billing_without_purchase_intent_tokenize_not_passed`, + message: `Expected ${SDK_QUERY_KEYS.INTENT}=${INTENT.TOKENIZE} for a billing-without-purchase transaction`, + featureFlags, + orderID, + loggerPayload: { vault, cartBillingType, cartAmount }, + throwError: false, + }); + } - if (cartCurrency && cartCurrency !== currency) { - triggerIntegrationError({ - error: 'smart_button_validation_error_incorrect_currency', - message: `Expected currency from order api call to be ${ currency }, got ${ cartCurrency }. Please ensure you are passing ${ SDK_QUERY_KEYS.CURRENCY }=${ cartCurrency } to the sdk url. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, - featureFlags, - loggerPayload: { cartCurrency, currency }, - orderID - }); - } + const payees = order.checkoutSession.payees; - if (!merchantID || merchantID.length === 0) { - triggerIntegrationError({ - error: 'smart_button_validation_error_no_merchant_id', - message: `Could not determine correct merchant id`, - featureFlags, - orderID - }); - } + if (!payees) { + return triggerIntegrationError({ + error: + "smart_button_validation_error_supplemental_order_missing_payees", + featureFlags, + orderID, + throwError: false, + }); + } - if (cartBillingType && !vault && !window.xprops.createVaultSetupToken) { - triggerIntegrationError({ - error: `smart_button_validation_error_billing_${ cartAmount ? 'with' : 'without' }_purchase_no_vault`, - message: `Expected ${ SDK_QUERY_KEYS.VAULT }=${ VAULT.TRUE.toString() } for a billing transaction`, - featureFlags, - orderID, - loggerPayload: { cartBillingType, vault }, - throwError: false - }); - } + if (!payees.length) { + return triggerIntegrationError({ + error: "smart_button_validation_error_supplemental_order_no_payees", + featureFlags, + orderID, + throwError: false, + }); + } - if (vault && window.xprops.createVaultSetupToken) { - triggerIntegrationError({ - error: "smart_button_validation_error_vault_passed_with_create_vault_setup_token", - message: `Query parameter ${ SDK_QUERY_KEYS.VAULT } is not needed when using createVaultSetupToken`, - featureFlags, - orderID, - loggerPayload: { vault, cartBillingType }, - throwError: false - }); - } else if (vault && !cartBillingType && !window.xprops.createBillingAgreement && !window.xprops.createSubscription && !window.xprops.clientAccessToken && !window.xprops.userIDToken) { - triggerIntegrationError({ - error: `smart_button_validation_error_vault_passed_not_needed`, - message: `Expected ${ SDK_QUERY_KEYS.VAULT }=${ VAULT.FALSE.toString() } for a non-billing, non-subscription transaction`, - featureFlags, - orderID, - loggerPayload: { vault, cartBillingType }, - throwError: false - }); - } + // find and remove duplicated payees + const dict = {}; + const uniquePayees = []; + + for (const payee of payees) { + if (!payee.merchantId && (!payee.email || !payee.email.stringValue)) { + return triggerIntegrationError({ + error: + "smart_button_validation_error_supplemental_order_missing_values", + featureFlags, + orderID, + loggerPayload: { payees: JSON.stringify(payees) }, + throwError: false, + }); + } - if (cartBillingType && !cartAmount && intent !== INTENT.TOKENIZE && !window.xprops.createVaultSetupToken) { - triggerIntegrationError({ - error: `smart_button_validation_error_billing_without_purchase_intent_tokenize_not_passed`, - message: `Expected ${ SDK_QUERY_KEYS.INTENT }=${ INTENT.TOKENIZE } for a billing-without-purchase transaction`, - featureFlags, - orderID, - loggerPayload: { vault, cartBillingType, cartAmount }, - throwError: false - }); + if (payee.merchantId) { + if (!dict[payee.merchantId]) { + dict[payee.merchantId] = 1; + uniquePayees.push(payee); } + } else if (payee.email && payee.email.stringValue) { + if (!dict[payee.email.stringValue]) { + dict[payee.email.stringValue] = 1; + uniquePayees.push(payee); + } + } + } - const payees = order.checkoutSession.payees; - - if (!payees) { - return triggerIntegrationError({ - error: 'smart_button_validation_error_supplemental_order_missing_payees', - featureFlags, - orderID, - throwError: false - }); + const payeesStr = uniquePayees + .map((payee) => { + if (payee.merchantId) { + return payee.merchantId; } - if (!payees.length) { - return triggerIntegrationError({ - error: 'smart_button_validation_error_supplemental_order_no_payees', - featureFlags, - orderID, - throwError: false - }); + if (payee.email && payee.email.stringValue) { + return payee.email.stringValue; } - // find and remove duplicated payees - const dict = {}; - const uniquePayees = []; - - for (const payee of payees) { - if (!payee.merchantId && (!payee.email || !payee.email.stringValue)) { - return triggerIntegrationError({ - error: 'smart_button_validation_error_supplemental_order_missing_values', - featureFlags, - orderID, - loggerPayload: { payees: JSON.stringify(payees) }, - throwError: false - }); - } + triggerIntegrationError({ + error: "smart_button_validation_error_invalid_payee_state", + message: `Invalid payee state: ${JSON.stringify(uniquePayees)}`, + featureFlags, + loggerPayload: { uniquePayees: JSON.stringify(uniquePayees) }, + orderID, + }); - if (payee.merchantId) { - if (!dict[payee.merchantId]) { - dict[payee.merchantId] = 1; - uniquePayees.push(payee); - } - } else if (payee.email && payee.email.stringValue) { - if (!dict[payee.email.stringValue]) { - dict[payee.email.stringValue] = 1; - uniquePayees.push(payee); - } - } - } + throw new Error("Payees Incorrect"); + }) + .join(","); - const payeesStr = uniquePayees.map(payee => { - if (payee.merchantId) { - return payee.merchantId; - } + const xpropMerchantID = window.xprops.merchantID; + const payeesShouldMatch = !window.xprops.createVaultSetupToken; - if (payee.email && payee.email.stringValue) { - return payee.email.stringValue; + if (payeesShouldMatch) { + if (xpropMerchantID && xpropMerchantID.length) { + // Validate merchant-id value(s) passed explicitly to SDK + if (!isValidMerchantIDs(xpropMerchantID, uniquePayees)) { + if (uniquePayees.length === 1) { + triggerIntegrationError({ + error: "smart_button_validation_error_payee_no_match", + message: `Payee(s) passed in transaction does not match expected merchant id. Please ensure you are passing ${ + SDK_QUERY_KEYS.MERCHANT_ID + }=${payeesStr} or ${SDK_QUERY_KEYS.MERCHANT_ID}=${ + uniquePayees[0] && + uniquePayees[0].email && + uniquePayees[0].email.stringValue + ? uniquePayees[0].email.stringValue + : "payee@merchant.com" + } to the sdk url. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, + featureFlags, + orderID, + }); + } else { + triggerIntegrationError({ + error: "smart_button_validation_error_payee_no_match", + message: `Payee(s) passed in transaction does not match expected merchant id. Please ensure you are passing ${SDK_QUERY_KEYS.MERCHANT_ID}=* to the sdk url and ${SDK_SETTINGS.MERCHANT_ID}="${payeesStr}" in the sdk script tag. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, + featureFlags, + orderID, + }); + } + } + } else { + // Validate merchant-id value derived from client id + if (!isValidMerchantIDs(merchantID, uniquePayees)) { + logger.warn( + `smart_button_validation_error_derived_payee_transaction_mismatch`, + { + payees: JSON.stringify(uniquePayees), + merchantID: JSON.stringify(merchantID), + }, + ); + + if (uniquePayees.length === 1) { + if (env === ENV.SANDBOX) { + logger.warn( + `smart_button_validation_error_derived_payee_transaction_mismatch_sandbox`, + { + payees: JSON.stringify(payees), + merchantID: JSON.stringify(merchantID), + }, + ); } triggerIntegrationError({ - error: 'smart_button_validation_error_invalid_payee_state', - message: `Invalid payee state: ${ JSON.stringify(uniquePayees) }`, - featureFlags, - loggerPayload: { uniquePayees: JSON.stringify(uniquePayees) }, - orderID + error: "smart_button_validation_error_payee_no_match", + message: `Payee(s) passed in transaction does not match expected merchant id. Please ensure you are passing ${ + SDK_QUERY_KEYS.MERCHANT_ID + }=${payeesStr} or ${SDK_QUERY_KEYS.MERCHANT_ID}=${ + uniquePayees[0] && + uniquePayees[0].email && + uniquePayees[0].email.stringValue + ? uniquePayees[0].email.stringValue + : "payee@merchant.com" + } to the sdk url. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, + featureFlags, + orderID, + throwError: false, }); - - throw new Error('Payees Incorrect'); - }).join(','); - - const xpropMerchantID = window.xprops.merchantID; - const payeesShouldMatch = !window.xprops.createVaultSetupToken; - - if (payeesShouldMatch) { - if (xpropMerchantID && xpropMerchantID.length) { - // Validate merchant-id value(s) passed explicitly to SDK - if (!isValidMerchantIDs(xpropMerchantID, uniquePayees)) { - if (uniquePayees.length === 1) { - triggerIntegrationError({ - error: 'smart_button_validation_error_payee_no_match', - message: `Payee(s) passed in transaction does not match expected merchant id. Please ensure you are passing ${ SDK_QUERY_KEYS.MERCHANT_ID }=${ payeesStr } or ${ SDK_QUERY_KEYS.MERCHANT_ID }=${ (uniquePayees[0] && uniquePayees[0].email && uniquePayees[0].email.stringValue) ? uniquePayees[0].email.stringValue : 'payee@merchant.com' } to the sdk url. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, - featureFlags, - orderID - }); - } else { - triggerIntegrationError({ - error: 'smart_button_validation_error_payee_no_match', - message: `Payee(s) passed in transaction does not match expected merchant id. Please ensure you are passing ${ SDK_QUERY_KEYS.MERCHANT_ID }=* to the sdk url and ${ SDK_SETTINGS.MERCHANT_ID }="${ payeesStr }" in the sdk script tag. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, - featureFlags, - orderID - }); - } - } - } else { - // Validate merchant-id value derived from client id - if (!isValidMerchantIDs(merchantID, uniquePayees)) { - logger.warn(`smart_button_validation_error_derived_payee_transaction_mismatch`, { payees: JSON.stringify(uniquePayees), merchantID: JSON.stringify(merchantID) }); - - if (uniquePayees.length === 1) { - if (env === ENV.SANDBOX) { - logger.warn(`smart_button_validation_error_derived_payee_transaction_mismatch_sandbox`, { payees: JSON.stringify(payees), merchantID: JSON.stringify(merchantID) }); - } - - triggerIntegrationError({ - error: 'smart_button_validation_error_payee_no_match', - message: `Payee(s) passed in transaction does not match expected merchant id. Please ensure you are passing ${ SDK_QUERY_KEYS.MERCHANT_ID }=${ payeesStr } or ${ SDK_QUERY_KEYS.MERCHANT_ID }=${ (uniquePayees[0] && uniquePayees[0].email && uniquePayees[0].email.stringValue) ? uniquePayees[0].email.stringValue : 'payee@merchant.com' } to the sdk url. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, - featureFlags, - orderID, - throwError: false - }); - } else { - triggerIntegrationError({ - error: 'smart_button_validation_error_payee_no_match', - message: `Payee(s) passed in transaction does not match expected merchant id. Please ensure you are passing ${ SDK_QUERY_KEYS.MERCHANT_ID }=* to the sdk url and ${ SDK_SETTINGS.MERCHANT_ID }="${ payeesStr }" in the sdk script tag. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, - featureFlags, - orderID - }); - } - } - } + } else { + triggerIntegrationError({ + error: "smart_button_validation_error_payee_no_match", + message: `Payee(s) passed in transaction does not match expected merchant id. Please ensure you are passing ${SDK_QUERY_KEYS.MERCHANT_ID}=* to the sdk url and ${SDK_SETTINGS.MERCHANT_ID}="${payeesStr}" in the sdk script tag. https://developer.paypal.com/docs/checkout/reference/customize-sdk/`, + featureFlags, + orderID, + }); + } } - }); + } + } + }); } diff --git a/src/button/validation.test.js b/src/button/validation.test.js index ba47ac091c..78c7283bd5 100644 --- a/src/button/validation.test.js +++ b/src/button/validation.test.js @@ -89,7 +89,7 @@ describe("validate order", () => { expect(logger.warn).toBeCalledWith( "smart_button_validation_error_vault_passed_with_create_vault_setup_token", - expect.any(Object) + expect.any(Object), ); }); }); diff --git a/src/card/components/AriaMessage.jsx b/src/card/components/AriaMessage.jsx index e9fda8e001..2e5a0b9b82 100644 --- a/src/card/components/AriaMessage.jsx +++ b/src/card/components/AriaMessage.jsx @@ -1,7 +1,7 @@ /* @flow */ /** @jsx h */ -import { h } from 'preact'; +import { h } from "preact"; type MessageProps = {| ariaMessageId: string, @@ -12,10 +12,9 @@ export function AriaMessage({ ariaMessageId, ariaMessageRef, }: MessageProps): mixed { - return (
diff --git a/src/card/components/CardCVV.jsx b/src/card/components/CardCVV.jsx index de561cfbbb..643ae017b2 100644 --- a/src/card/components/CardCVV.jsx +++ b/src/card/components/CardCVV.jsx @@ -1,179 +1,200 @@ /* @flow */ /** @jsx h */ -import { h, Fragment } from 'preact'; -import { useState, useEffect, useRef } from 'preact/hooks'; -import cardValidator from 'card-validator'; - -import { getPostRobot } from '../../lib'; -import { DEFAULT_CARD_TYPE } from '../constants'; -import { removeNonDigits, defaultNavigation, defaultInputState, navigateOnKeyDown, exportMethods, getContext } from '../lib'; -import type { CardType, CardCvvChangeEvent, CardNavigation, FieldValidity, InputState, InputEvent } from '../types'; - -import { AriaMessage } from './AriaMessage' +import { h, Fragment } from "preact"; +import { useState, useEffect, useRef } from "preact/hooks"; +import cardValidator from "card-validator"; + +import { getPostRobot } from "../../lib"; +import { DEFAULT_CARD_TYPE } from "../constants"; +import { + removeNonDigits, + defaultNavigation, + defaultInputState, + navigateOnKeyDown, + exportMethods, + getContext, +} from "../lib"; +import type { + CardType, + CardCvvChangeEvent, + CardNavigation, + FieldValidity, + InputState, + InputEvent, +} from "../types"; + +import { AriaMessage } from "./AriaMessage"; type CardCvvProps = {| - name : string, - autocomplete? : string, - type : string, - state? : InputState, - placeholder : string, - style : Object, - navigation : CardNavigation, - onChange : (cvvEvent : CardCvvChangeEvent) => void, - onFocus : (event : InputEvent) => void, - onBlur : (event : InputEvent) => void, - onKeyDown? : (keyDown : boolean) => void, - allowNavigation : boolean, - onValidityChange? : (numberValidity : FieldValidity) => void + name: string, + autocomplete?: string, + type: string, + state?: InputState, + placeholder: string, + style: Object, + navigation: CardNavigation, + onChange: (cvvEvent: CardCvvChangeEvent) => void, + onFocus: (event: InputEvent) => void, + onBlur: (event: InputEvent) => void, + onKeyDown?: (keyDown: boolean) => void, + allowNavigation: boolean, + onValidityChange?: (numberValidity: FieldValidity) => void, |}; - -export function CardCVV( - { - name = 'cvv', - autocomplete = 'cc-csc', - navigation = defaultNavigation, - allowNavigation = false, - state, - type, - placeholder, - style, - onChange, - onFocus, - onBlur, - onKeyDown, - onValidityChange - } : CardCvvProps -) : mixed { - const [ attributes, setAttributes ] : [ Object, (Object) => Object ] = useState({ placeholder }); - const [ inputState, setInputState ] : [ InputState, (InputState | InputState => InputState) => InputState ] = useState({ ...defaultInputState, ...state }); - const [ cardType, setCardType ] : [ CardType, (CardType) => CardType ] = useState(DEFAULT_CARD_TYPE); - const [ touched, setTouched ] = useState(false); - const { inputValue, keyStrokeCount, isValid, isPotentiallyValid } = inputState; - - const cvvRef = useRef() - const ariaMessageRef = useRef() - - useEffect(() => { - if (!allowNavigation) { - exportMethods(cvvRef, setAttributes, setInputState, ariaMessageRef); - } - // listen for card type changes - const postRobot = getPostRobot(); - if (postRobot) { - const context = getContext(window); - postRobot.on('cardTypeChange', { - domain: window.location.origin - }, (event) => { - const messageContext = getContext(event.source); - if (messageContext === context) { - setCardType(event.data); - } - }); - } - }, []); - - useEffect(() => { - onChange({cardCvv: inputState.inputValue}); - }, [ inputState ]); - - useEffect(() => { - const validity = cardValidator.cvv(inputValue, cardType?.code?.size); - if (touched) { - validity.isPotentiallyValid = false; - } - setInputState(newState => ({ ...newState, ...validity })); - }, [ cardType ]); - - useEffect(() => { - const validity = cardValidator.cvv(inputValue, cardType?.code?.size); - if (touched) { - validity.isPotentiallyValid = false; - } - setInputState(newState => ({ ...newState, ...validity })); - }, [ cardType ]); - - useEffect(() => { - if (typeof onValidityChange === 'function') { - onValidityChange({ isValid, isPotentiallyValid }); - } - if (allowNavigation && inputValue && isValid) { - navigation.next(); - } - }, [ isValid, isPotentiallyValid ]); - - const setCvvValue : (InputEvent) => void = (event : InputEvent) : void => { - const { value : rawValue } = event.target; - const value = removeNonDigits(rawValue); - const validity = cardValidator.cvv(value, cardType?.code?.size); - - setInputState({ - ...inputState, - ...validity, - inputValue: value, - maskedInputValue: value, - keyStrokeCount: keyStrokeCount + 1 - }); - - }; - - const onKeyDownEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onKeyDown === 'function') { - if(event.key === "Enter"){ - onKeyDown(true) - } else { - onKeyDown(false) - } - } - - if (allowNavigation) { - navigateOnKeyDown(event, navigation); - } - }; - - const onFocusEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (!touched) { - setTouched(true); - } - if (typeof onFocus === 'function') { - onFocus(event); - } - }; - - const onBlurEvent : (InputEvent) => void = (event : InputEvent) : void => { - if ( typeof onBlur === 'function') { - onBlur(event); - } - if ( typeof onKeyDown === 'function') { - onKeyDown(false) - } - }; - - return ( - - - - - ); +export function CardCVV({ + name = "cvv", + autocomplete = "cc-csc", + navigation = defaultNavigation, + allowNavigation = false, + state, + type, + placeholder, + style, + onChange, + onFocus, + onBlur, + onKeyDown, + onValidityChange, +}: CardCvvProps): mixed { + const [attributes, setAttributes]: [Object, (Object) => Object] = useState({ + placeholder, + }); + const [inputState, setInputState]: [ + InputState, + (InputState | ((InputState) => InputState)) => InputState, + ] = useState({ ...defaultInputState, ...state }); + const [cardType, setCardType]: [CardType, (CardType) => CardType] = + useState(DEFAULT_CARD_TYPE); + const [touched, setTouched] = useState(false); + const { inputValue, keyStrokeCount, isValid, isPotentiallyValid } = + inputState; + + const cvvRef = useRef(); + const ariaMessageRef = useRef(); + + useEffect(() => { + if (!allowNavigation) { + exportMethods(cvvRef, setAttributes, setInputState, ariaMessageRef); + } + // listen for card type changes + const postRobot = getPostRobot(); + if (postRobot) { + const context = getContext(window); + postRobot.on( + "cardTypeChange", + { + domain: window.location.origin, + }, + (event) => { + const messageContext = getContext(event.source); + if (messageContext === context) { + setCardType(event.data); + } + }, + ); + } + }, []); + + useEffect(() => { + onChange({ cardCvv: inputState.inputValue }); + }, [inputState]); + + useEffect(() => { + const validity = cardValidator.cvv(inputValue, cardType?.code?.size); + if (touched) { + validity.isPotentiallyValid = false; + } + setInputState((newState) => ({ ...newState, ...validity })); + }, [cardType]); + + useEffect(() => { + const validity = cardValidator.cvv(inputValue, cardType?.code?.size); + if (touched) { + validity.isPotentiallyValid = false; + } + setInputState((newState) => ({ ...newState, ...validity })); + }, [cardType]); + + useEffect(() => { + if (typeof onValidityChange === "function") { + onValidityChange({ isValid, isPotentiallyValid }); + } + if (allowNavigation && inputValue && isValid) { + navigation.next(); + } + }, [isValid, isPotentiallyValid]); + + const setCvvValue: (InputEvent) => void = (event: InputEvent): void => { + const { value: rawValue } = event.target; + const value = removeNonDigits(rawValue); + const validity = cardValidator.cvv(value, cardType?.code?.size); + + setInputState({ + ...inputState, + ...validity, + inputValue: value, + maskedInputValue: value, + keyStrokeCount: keyStrokeCount + 1, + }); + }; + + const onKeyDownEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onKeyDown === "function") { + if (event.key === "Enter") { + onKeyDown(true); + } else { + onKeyDown(false); + } + } + + if (allowNavigation) { + navigateOnKeyDown(event, navigation); + } + }; + + const onFocusEvent: (InputEvent) => void = (event: InputEvent): void => { + if (!touched) { + setTouched(true); + } + if (typeof onFocus === "function") { + onFocus(event); + } + }; + + const onBlurEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onBlur === "function") { + onBlur(event); + } + if (typeof onKeyDown === "function") { + onKeyDown(false); + } + }; + + return ( + + + + + ); } diff --git a/src/card/components/CardExpiry.jsx b/src/card/components/CardExpiry.jsx index 0d329db2cd..53fac29a90 100644 --- a/src/card/components/CardExpiry.jsx +++ b/src/card/components/CardExpiry.jsx @@ -1,168 +1,181 @@ /* @flow */ /** @jsx h */ -import { h, Fragment } from 'preact'; -import { useState, useEffect, useRef } from 'preact/hooks'; -import cardValidator from 'card-validator'; -import RestrictedInput from 'restricted-input'; +import { h, Fragment } from "preact"; +import { useState, useEffect, useRef } from "preact/hooks"; +import cardValidator from "card-validator"; +import RestrictedInput from "restricted-input"; import { - defaultNavigation, - defaultInputState, - navigateOnKeyDown, - exportMethods, - shouldUseZeroPaddedExpiryPattern -} from '../lib'; -import type { CardExpiryChangeEvent, CardNavigation, FieldValidity, InputState, InputEvent } from '../types'; -import { DEFAULT_EXPIRY_PATTERN, ZERO_PADDED_EXPIRY_PATTERN } from '../constants'; + defaultNavigation, + defaultInputState, + navigateOnKeyDown, + exportMethods, + shouldUseZeroPaddedExpiryPattern, +} from "../lib"; +import type { + CardExpiryChangeEvent, + CardNavigation, + FieldValidity, + InputState, + InputEvent, +} from "../types"; +import { + DEFAULT_EXPIRY_PATTERN, + ZERO_PADDED_EXPIRY_PATTERN, +} from "../constants"; -import { AriaMessage } from './AriaMessage' +import { AriaMessage } from "./AriaMessage"; type CardExpiryProps = {| - name : string, - autocomplete? : string, - type : string, - state? : InputState, - placeholder : string, - style : Object, - maxLength : string, - navigation : CardNavigation, - allowNavigation : boolean, - onChange : (expiryEvent : CardExpiryChangeEvent) => void, - onFocus? : (event : InputEvent) => void, - onKeyDown? : (keyDown : boolean) => void, - onBlur? : (event : InputEvent) => void, - onValidityChange? : (numberValidity : FieldValidity) => void + name: string, + autocomplete?: string, + type: string, + state?: InputState, + placeholder: string, + style: Object, + maxLength: string, + navigation: CardNavigation, + allowNavigation: boolean, + onChange: (expiryEvent: CardExpiryChangeEvent) => void, + onFocus?: (event: InputEvent) => void, + onKeyDown?: (keyDown: boolean) => void, + onBlur?: (event: InputEvent) => void, + onValidityChange?: (numberValidity: FieldValidity) => void, |}; +export function CardExpiry({ + name = "expiry", + autocomplete = "cc-exp", + navigation = defaultNavigation, + state, + type, + placeholder, + style, + maxLength, + onChange, + onFocus, + onBlur, + onKeyDown, + onValidityChange, + allowNavigation = false, +}: CardExpiryProps): mixed { + const [attributes, setAttributes]: [Object, (Object) => Object] = useState({ + placeholder, + }); + const [inputState, setInputState]: [ + InputState, + (InputState | ((InputState) => InputState)) => InputState, + ] = useState({ ...defaultInputState, ...state }); + const { maskedInputValue, isValid, isPotentiallyValid } = inputState; + const [restrictedInput, setRestrictedInput]: [Object, (Object) => Object] = + useState({}); + + const expiryRef = useRef(); + const ariaMessageRef = useRef(); + + useEffect(() => { + if (!allowNavigation) { + exportMethods(expiryRef, setAttributes, setInputState, ariaMessageRef); + } + const element = expiryRef?.current; + if (element) { + const initialRestrictedInput = new RestrictedInput({ + element, + pattern: DEFAULT_EXPIRY_PATTERN, + }); + setRestrictedInput(initialRestrictedInput); + } + }, []); + + useEffect(() => { + onChange({ maskedDate: inputState.maskedInputValue }); + }, [inputState]); + + useEffect(() => { + if (typeof onValidityChange === "function") { + onValidityChange({ isValid, isPotentiallyValid }); + } + + if (allowNavigation && maskedInputValue && isValid) { + navigation.next(); + } + }, [isValid, isPotentiallyValid]); + + const formatExpiryDate: (InputEvent) => void = (event: InputEvent): void => { + const value = event.target.value; + const validity = cardValidator.expirationDate(value); + if (!value.includes("/")) { + if (shouldUseZeroPaddedExpiryPattern(value, event.key)) { + restrictedInput.setPattern(ZERO_PADDED_EXPIRY_PATTERN); + } else { + restrictedInput.setPattern(DEFAULT_EXPIRY_PATTERN); + } + } + setInputState({ + ...inputState, + ...validity, + inputValue: restrictedInput.getUnformattedValue(), + maskedInputValue: expiryRef.current.value, + }); + }; + + const onKeyDownEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onKeyDown === "function") { + if (event.key === "Enter") { + onKeyDown(true); + } else { + onKeyDown(false); + } + if (allowNavigation) { + navigateOnKeyDown(event, navigation); + } + } + }; -export function CardExpiry( - { - name = 'expiry', - autocomplete = 'cc-exp', - navigation = defaultNavigation, - state, - type, - placeholder, - style, - maxLength, - onChange, - onFocus, - onBlur, - onKeyDown, - onValidityChange, - allowNavigation = false - } : CardExpiryProps -) : mixed { - const [ attributes, setAttributes ] : [ Object, (Object) => Object ] = useState({ placeholder }); - const [ inputState, setInputState ] : [ InputState, (InputState | (InputState) => InputState) => InputState ] = useState({ ...defaultInputState, ...state }); - const { maskedInputValue, isValid, isPotentiallyValid } = inputState; - const [restrictedInput, setRestrictedInput] : [Object, (Object) => Object] = useState({}) - - const expiryRef = useRef() - const ariaMessageRef = useRef() - - useEffect(() => { - if (!allowNavigation) { - exportMethods(expiryRef, setAttributes, setInputState, ariaMessageRef); - } - const element = expiryRef?.current - if (element) { - const initialRestrictedInput = new RestrictedInput({ - element, - pattern: DEFAULT_EXPIRY_PATTERN - }) ; - setRestrictedInput(initialRestrictedInput) - } - }, []); - - useEffect(() => { - onChange({maskedDate: inputState.maskedInputValue}); - }, [ inputState ]); - - useEffect(() => { - if (typeof onValidityChange === 'function') { - onValidityChange({ isValid, isPotentiallyValid }); - } - - if (allowNavigation && maskedInputValue && isValid) { - navigation.next(); - } - }, [ isValid, isPotentiallyValid ]); - - const formatExpiryDate : (InputEvent) => void = (event: InputEvent) : void => { - const value = event.target.value - const validity = cardValidator.expirationDate(value); - if(!value.includes("/")) { - if (shouldUseZeroPaddedExpiryPattern(value, event.key)) { - restrictedInput.setPattern(ZERO_PADDED_EXPIRY_PATTERN) - } else { - restrictedInput.setPattern(DEFAULT_EXPIRY_PATTERN) - } - } - setInputState({ - ...inputState, - ...validity, - inputValue: restrictedInput.getUnformattedValue(), - maskedInputValue: expiryRef.current.value - }); + const onFocusEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onFocus === "function") { + onFocus(event); } + }; - const onKeyDownEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onKeyDown === 'function') { - if(event.key === "Enter"){ - onKeyDown(true) - } else { - onKeyDown(false) - } - if (allowNavigation) { - navigateOnKeyDown(event, navigation); - } - } - }; - - const onFocusEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onFocus === 'function') { - onFocus(event); - } - }; - - const onBlurEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onBlur === 'function') { - onBlur(event); - } - if ( typeof onKeyDown === 'function') { - onKeyDown(false) - } - }; - - const onPasteEvent : (InputEvent) => void = () : void => { - setInputState((newState) => ({ ...newState, contentPasted: true })); - }; - - return ( - - - - - ); + const onBlurEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onBlur === "function") { + onBlur(event); + } + if (typeof onKeyDown === "function") { + onKeyDown(false); + } + }; + + const onPasteEvent: (InputEvent) => void = (): void => { + setInputState((newState) => ({ ...newState, contentPasted: true })); + }; + + return ( + + + + + ); } diff --git a/src/card/components/CardName.jsx b/src/card/components/CardName.jsx index 5e2f3bc988..a0fb461709 100644 --- a/src/card/components/CardName.jsx +++ b/src/card/components/CardName.jsx @@ -1,138 +1,151 @@ /* @flow */ /** @jsx h */ -import { h, Fragment } from 'preact'; -import { useState, useEffect, useRef } from 'preact/hooks'; -import cardValidator from 'card-validator'; - -import { defaultNavigation, defaultInputState, navigateOnKeyDown, exportMethods } from '../lib'; -import type { CardNameChangeEvent, CardNavigation, FieldValidity, InputState, InputEvent } from '../types'; - -import { AriaMessage } from './AriaMessage' +import { h, Fragment } from "preact"; +import { useState, useEffect, useRef } from "preact/hooks"; +import cardValidator from "card-validator"; + +import { + defaultNavigation, + defaultInputState, + navigateOnKeyDown, + exportMethods, +} from "../lib"; +import type { + CardNameChangeEvent, + CardNavigation, + FieldValidity, + InputState, + InputEvent, +} from "../types"; + +import { AriaMessage } from "./AriaMessage"; type CardNameProps = {| - name : string, - type : string, - state? : InputState, - placeholder : string, - style : Object, - maxLength : string, - navigation : CardNavigation, - onChange : (nameEvent : CardNameChangeEvent) => void, - onFocus : (event : InputEvent) => void, - onBlur : (event : InputEvent) => void, - onKeyDown? : (keyDown : boolean) => void, - allowNavigation : boolean, - onValidityChange? : (numberValidity : FieldValidity) => void + name: string, + type: string, + state?: InputState, + placeholder: string, + style: Object, + maxLength: string, + navigation: CardNavigation, + onChange: (nameEvent: CardNameChangeEvent) => void, + onFocus: (event: InputEvent) => void, + onBlur: (event: InputEvent) => void, + onKeyDown?: (keyDown: boolean) => void, + allowNavigation: boolean, + onValidityChange?: (numberValidity: FieldValidity) => void, |}; - -export function CardName( - { - name = 'name', - navigation = defaultNavigation, - allowNavigation = false, - state, - type, - placeholder, - style, - maxLength, - onChange, - onFocus, - onBlur, - onKeyDown, - onValidityChange - } : CardNameProps -) : mixed { - const [ attributes, setAttributes ] : [ Object, (Object) => Object ] = useState({ placeholder }); - const [ inputState, setInputState ] : [ InputState, (InputState | InputState => InputState) => InputState ] = useState({ ...defaultInputState, ...state }); - const { inputValue, keyStrokeCount, isValid, isPotentiallyValid } = inputState; - - const nameRef = useRef() - const ariaMessageRef = useRef() - - useEffect(() => { - exportMethods(nameRef, setAttributes, setInputState, ariaMessageRef); - }, []); - - useEffect(() => { - onChange({ cardName: inputState.inputValue}); - }, [inputState]) - - useEffect(() => { - if (typeof onValidityChange === 'function') { - onValidityChange({ isValid, isPotentiallyValid }); - } - if (allowNavigation && inputValue && isValid) { - navigation.next(); - } - }, [ isValid, isPotentiallyValid ]); - - const setNameValue : (InputEvent) => void = (event : InputEvent) : void => { - const { value } = event.target; - const validity = cardValidator.cardholderName(value); - - setInputState({ - ...inputState, - ...validity, - inputValue: value, - maskedInputValue: value, - keyStrokeCount: keyStrokeCount + 1 - }); - - }; - - const onKeyDownEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onKeyDown === 'function') { - if(event.key === "Enter"){ - onKeyDown(true) - } else { - onKeyDown(false) - } - } - - if (allowNavigation) { - navigateOnKeyDown(event, navigation); - } - }; - - const onFocusEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onFocus === 'function') { - onFocus(event); - } - }; - - const onBlurEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onBlur === 'function') { - onBlur(event); - } - if ( typeof onKeyDown === 'function') { - onKeyDown(false) - } - }; - - return ( - - - - - ); +export function CardName({ + name = "name", + navigation = defaultNavigation, + allowNavigation = false, + state, + type, + placeholder, + style, + maxLength, + onChange, + onFocus, + onBlur, + onKeyDown, + onValidityChange, +}: CardNameProps): mixed { + const [attributes, setAttributes]: [Object, (Object) => Object] = useState({ + placeholder, + }); + const [inputState, setInputState]: [ + InputState, + (InputState | ((InputState) => InputState)) => InputState, + ] = useState({ ...defaultInputState, ...state }); + const { inputValue, keyStrokeCount, isValid, isPotentiallyValid } = + inputState; + + const nameRef = useRef(); + const ariaMessageRef = useRef(); + + useEffect(() => { + exportMethods(nameRef, setAttributes, setInputState, ariaMessageRef); + }, []); + + useEffect(() => { + onChange({ cardName: inputState.inputValue }); + }, [inputState]); + + useEffect(() => { + if (typeof onValidityChange === "function") { + onValidityChange({ isValid, isPotentiallyValid }); + } + if (allowNavigation && inputValue && isValid) { + navigation.next(); + } + }, [isValid, isPotentiallyValid]); + + const setNameValue: (InputEvent) => void = (event: InputEvent): void => { + const { value } = event.target; + const validity = cardValidator.cardholderName(value); + + setInputState({ + ...inputState, + ...validity, + inputValue: value, + maskedInputValue: value, + keyStrokeCount: keyStrokeCount + 1, + }); + }; + + const onKeyDownEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onKeyDown === "function") { + if (event.key === "Enter") { + onKeyDown(true); + } else { + onKeyDown(false); + } + } + + if (allowNavigation) { + navigateOnKeyDown(event, navigation); + } + }; + + const onFocusEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onFocus === "function") { + onFocus(event); + } + }; + + const onBlurEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onBlur === "function") { + onBlur(event); + } + if (typeof onKeyDown === "function") { + onKeyDown(false); + } + }; + + return ( + + + + + ); } diff --git a/src/card/components/CardNumber.jsx b/src/card/components/CardNumber.jsx index 2cd3a1552d..362ea25e37 100644 --- a/src/card/components/CardNumber.jsx +++ b/src/card/components/CardNumber.jsx @@ -1,274 +1,329 @@ /* @flow */ /** @jsx h */ -import { h, Fragment } from 'preact'; -import { useState, useEffect, useRef } from 'preact/hooks'; -import cardValidator from 'card-validator'; +import { h, Fragment } from "preact"; +import { useState, useEffect, useRef } from "preact/hooks"; +import cardValidator from "card-validator"; -import { getPostRobot } from '../../lib'; +import { getPostRobot } from "../../lib"; import { - addGapsToCardNumber, - checkForNonDigits, - removeNonDigits, - detectCardType, - checkCardEligibility, - moveCursor, - defaultNavigation, - defaultInputState, - navigateOnKeyDown, - maskValidCard, - exportMethods -} from '../lib'; + addGapsToCardNumber, + checkForNonDigits, + removeNonDigits, + detectCardType, + checkCardEligibility, + moveCursor, + defaultNavigation, + defaultInputState, + navigateOnKeyDown, + maskValidCard, + exportMethods, +} from "../lib"; import type { - CardNumberChangeEvent, - FieldValidity, - CardNavigation, - InputState, - CardType, - InputEvent -} from '../types'; -import { DEFAULT_CARD_TYPE } from '../constants'; - -import { Icon } from './Icons'; -import { AriaMessage } from './AriaMessage' + CardNumberChangeEvent, + FieldValidity, + CardNavigation, + InputState, + CardType, + InputEvent, +} from "../types"; +import { DEFAULT_CARD_TYPE } from "../constants"; + +import { Icon } from "./Icons"; +import { AriaMessage } from "./AriaMessage"; // Helper method to check if navigation to next field should be allowed -function validateNavigation({ allowNavigation, inputState } : {| allowNavigation : boolean, inputState : InputState |}) : boolean { - const { inputValue, isValid, maskedInputValue, cursorStart, contentPasted } = inputState; - return Boolean(allowNavigation && inputValue && isValid && (maskedInputValue.length === cursorStart || contentPasted)); +function validateNavigation({ + allowNavigation, + inputState, +}: {| + allowNavigation: boolean, + inputState: InputState, +|}): boolean { + const { inputValue, isValid, maskedInputValue, cursorStart, contentPasted } = + inputState; + return Boolean( + allowNavigation && + inputValue && + isValid && + (maskedInputValue.length === cursorStart || contentPasted), + ); } -function getIconId(type) : string { - const iconId = `icon-${type}`; - const element = document.getElementById(iconId); - if (element) { - return iconId; - } - return 'icon-unknown'; +function getIconId(type): string { + const iconId = `icon-${type}`; + const element = document.getElementById(iconId); + if (element) { + return iconId; + } + return "icon-unknown"; } type CardNumberProps = {| - name : string, - autocomplete? : string, - type : string, - state? : InputState, - placeholder : string, - style : Object, - navigation? : CardNavigation, - allowNavigation? : boolean, - onChange : (numberEvent : CardNumberChangeEvent) => void, - onFocus? : (event : InputEvent) => void, - onBlur? : (event : InputEvent) => void, - onKeyDown? : (keyDown : boolean) => void, - onValidityChange? : (numberValidity : FieldValidity) => void, - onEligibilityChange? : (isCardEligible : boolean) => void, + name: string, + autocomplete?: string, + type: string, + state?: InputState, + placeholder: string, + style: Object, + navigation?: CardNavigation, + allowNavigation?: boolean, + onChange: (numberEvent: CardNumberChangeEvent) => void, + onFocus?: (event: InputEvent) => void, + onBlur?: (event: InputEvent) => void, + onKeyDown?: (keyDown: boolean) => void, + onValidityChange?: (numberValidity: FieldValidity) => void, + onEligibilityChange?: (isCardEligible: boolean) => void, |}; -export function CardNumber( - { - name = 'number', - autocomplete = 'cc-number', - navigation = defaultNavigation, - allowNavigation = false, - state, - type, - placeholder, - style, - onChange, - onFocus, - onBlur, - onKeyDown, - onValidityChange, - onEligibilityChange, - } : CardNumberProps -) : mixed { - const [ attributes, setAttributes ] : [ Object, (Object) => Object ] = useState({ placeholder }); - const [ cardTypes, setCardTypes ] : [ CardType, ($ReadOnlyArray) => $ReadOnlyArray ] = useState([DEFAULT_CARD_TYPE]); - const [ maxLength, setMaxLength ] : [ number, (number) => number ] = useState(24); - const [ inputState, setInputState ] : [ InputState, (InputState | InputState => InputState) => InputState ] = useState({ ...defaultInputState, ...state }); - const { inputValue, maskedInputValue, cursorStart, cursorEnd, keyStrokeCount, isValid, isPotentiallyValid, contentPasted } = inputState; - const [ cardType, setCardType ] : [ CardType, (CardType) => CardType ] = useState(DEFAULT_CARD_TYPE); - - const numberRef = useRef() - const ariaMessageRef = useRef() - - useEffect(() => { - if (!allowNavigation) { - exportMethods(numberRef, setAttributes, setInputState, ariaMessageRef); - } - }, []); - - useEffect(() => { - setCardType(cardTypes[0]) - }, [cardTypes]) - - useEffect(() => { - onChange({ cardNumber: inputState.inputValue, potentialCardTypes: cardTypes}); - }, [ inputState ]); - - useEffect(() => { - if (typeof onEligibilityChange === 'function') { - onEligibilityChange(checkCardEligibility(inputValue, cardType)); - } - - if (cardType && cardType.lengths) { - // get the maximum card length for the given card type - const cardMaxLength = cardType.lengths.reduce((previousValue, currentValue) => { - return Math.max(previousValue, currentValue); - }); - if (cardMaxLength) { - // set maxLength to the maximum card length, plus the number of spaces for the gaps - setMaxLength(cardMaxLength + (cardType.gaps?.length ?? 0)); - } - } - // communicate card type change to sibling components - const postRobot = getPostRobot(); - if (postRobot) { - const frames = window.parent.frames; - for (const frame of frames) { - postRobot.send(frame, 'cardTypeChange', cardType, { - domain: window.location.origin, - fireAndForget: true - }); - } - } - }, [ cardType ]); - - useEffect(() => { - if (typeof onValidityChange === 'function') { - onValidityChange({ isValid, isPotentiallyValid }); - } - - if (validateNavigation({ allowNavigation, inputState })) { - navigation.next(); - } - - }, [ isValid, isPotentiallyValid ]); - - const setValueAndCursor : (InputEvent) => void = (event : InputEvent) : void => { - const { value: rawValue, selectionStart, selectionEnd } = event.target; - const value = removeNonDigits(rawValue); - const detectedCardType = detectCardType(value); - const validity = cardValidator.number(value); - const maskedValue = addGapsToCardNumber(value); - let startCursorPosition = selectionStart; - let endCursorPosition = selectionEnd; - - if (checkForNonDigits(rawValue)) { - startCursorPosition = cursorStart; - endCursorPosition = cursorEnd; - } - - if (contentPasted) { - startCursorPosition = maskedValue.length; - endCursorPosition = maskedValue.length; - } else if (maskedValue.length > maskedInputValue.length && maskedValue[selectionStart - 1] === ' ') { - startCursorPosition += 1; - endCursorPosition += 1; - } - - moveCursor(event.target, startCursorPosition, endCursorPosition); - - setCardTypes(detectedCardType); - setInputState({ - ...inputState, - ...validity, - inputValue: value, - maskedInputValue: maskedValue, - cursorStart: startCursorPosition, - cursorEnd: endCursorPosition, - contentPasted: false, - keyStrokeCount: keyStrokeCount + 1 - }); +export function CardNumber({ + name = "number", + autocomplete = "cc-number", + navigation = defaultNavigation, + allowNavigation = false, + state, + type, + placeholder, + style, + onChange, + onFocus, + onBlur, + onKeyDown, + onValidityChange, + onEligibilityChange, +}: CardNumberProps): mixed { + const [attributes, setAttributes]: [Object, (Object) => Object] = useState({ + placeholder, + }); + const [cardTypes, setCardTypes]: [ + CardType, + ($ReadOnlyArray) => $ReadOnlyArray, + ] = useState([DEFAULT_CARD_TYPE]); + const [maxLength, setMaxLength]: [number, (number) => number] = useState(24); + const [inputState, setInputState]: [ + InputState, + (InputState | ((InputState) => InputState)) => InputState, + ] = useState({ ...defaultInputState, ...state }); + const { + inputValue, + maskedInputValue, + cursorStart, + cursorEnd, + keyStrokeCount, + isValid, + isPotentiallyValid, + contentPasted, + } = inputState; + const [cardType, setCardType]: [CardType, (CardType) => CardType] = + useState(DEFAULT_CARD_TYPE); + + const numberRef = useRef(); + const ariaMessageRef = useRef(); + + const resetDefaultCardType = ( + element: HTMLElement, + isFocused: boolean, + ): boolean => { + return element && !isFocused && inputState.inputValue.length === 0; + }; + + useEffect(() => { + if (!allowNavigation) { + exportMethods(numberRef, setAttributes, setInputState, ariaMessageRef); + } + }, []); - }; + useEffect(() => { + setCardType(cardTypes[0]); + }, [cardTypes]); - const onFocusEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onFocus === 'function') { - onFocus(event); - } + useEffect(() => { + onChange({ + cardNumber: inputState.inputValue, + potentialCardTypes: cardTypes, + }); - const element = numberRef?.current; - if (element) { - element.classList.add('display-icon'); - } - const maskedValue = addGapsToCardNumber(inputValue); - const updatedState = { ...inputState, maskedInputValue: maskedValue, displayCardIcon: true }; + const element = numberRef?.current; + const isFocused = document.activeElement === element; - setInputState((newState) => ({ ...newState, ...updatedState })); - }; + if (resetDefaultCardType(element, isFocused)) { + setCardType(DEFAULT_CARD_TYPE); + } + }, [inputState]); - const onBlurEvent : (InputEvent) => void = (event : InputEvent) : void => { - const updatedState = { maskedInputValue, isPotentiallyValid, contentPasted: false, displayCardIcon: inputState.inputValue.length > 0 }; + useEffect(() => { + if (typeof onEligibilityChange === "function") { + onEligibilityChange(checkCardEligibility(inputValue, cardType)); + } - const element = numberRef?.current; - if (element) { - if (inputState.inputValue.length > 0) { - element.classList.add('display-icon'); - } else { - element.classList.remove('display-icon'); - } - } + if (cardType && cardType.lengths) { + // get the maximum card length for the given card type + const cardMaxLength = cardType.lengths.reduce( + (previousValue, currentValue) => { + return Math.max(previousValue, currentValue); + }, + ); + if (cardMaxLength) { + // set maxLength to the maximum card length, plus the number of spaces for the gaps + setMaxLength(cardMaxLength + (cardType.gaps?.length ?? 0)); + } + } + // communicate card type change to sibling components + const postRobot = getPostRobot(); + if (postRobot) { + const frames = window.parent.frames; + for (const frame of frames) { + postRobot.send(frame, "cardTypeChange", cardType, { + domain: window.location.origin, + fireAndForget: true, + }); + } + } + }, [cardType]); - if (isValid) { - updatedState.maskedInputValue = maskValidCard(maskedInputValue); - } + useEffect(() => { + if (typeof onValidityChange === "function") { + onValidityChange({ isValid, isPotentiallyValid }); + } - if (typeof onBlur === 'function') { - onBlur(event); - } - if ( typeof onKeyDown === 'function') { - onKeyDown(false) - } + if (validateNavigation({ allowNavigation, inputState })) { + navigation.next(); + } + }, [isValid, isPotentiallyValid]); + + const setValueAndCursor: (InputEvent) => void = (event: InputEvent): void => { + const { value: rawValue, selectionStart, selectionEnd } = event.target; + const value = removeNonDigits(rawValue); + const detectedCardType = detectCardType(value); + const validity = cardValidator.number(value); + const maskedValue = addGapsToCardNumber(value); + let startCursorPosition = selectionStart; + let endCursorPosition = selectionEnd; + + if (checkForNonDigits(rawValue)) { + startCursorPosition = cursorStart; + endCursorPosition = cursorEnd; + } - setInputState((newState) => ({ ...newState, ...updatedState })); - + if (contentPasted) { + startCursorPosition = maskedValue.length; + endCursorPosition = maskedValue.length; + } else if ( + maskedValue.length > maskedInputValue.length && + maskedValue[selectionStart - 1] === " " + ) { + startCursorPosition += 1; + endCursorPosition += 1; + } - }; + moveCursor(event.target, startCursorPosition, endCursorPosition); + + setCardTypes(detectedCardType); + setInputState({ + ...inputState, + ...validity, + inputValue: value, + maskedInputValue: maskedValue, + cursorStart: startCursorPosition, + cursorEnd: endCursorPosition, + contentPasted: false, + keyStrokeCount: keyStrokeCount + 1, + }); + }; + + const onFocusEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onFocus === "function") { + onFocus(event); + } - const onKeyDownEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onKeyDown === 'function') { - if(event.key === "Enter"){ - onKeyDown(true) - } else { - onKeyDown(false) - } - } - - if (allowNavigation) { - navigateOnKeyDown(event, navigation); - } + const element = numberRef?.current; + if (element) { + element.classList.add("display-icon"); + } + const maskedValue = addGapsToCardNumber(inputValue); + const updatedState = { + ...inputState, + maskedInputValue: maskedValue, + displayCardIcon: true, }; - const onPasteEvent : (InputEvent) => void = () : void => { - setInputState((newState) => ({ ...newState, contentPasted: true })); + setInputState((newState) => ({ ...newState, ...updatedState })); + }; + + const onBlurEvent: (InputEvent) => void = (event: InputEvent): void => { + const updatedState = { + maskedInputValue, + isPotentiallyValid, + contentPasted: false, + displayCardIcon: inputState.inputValue.length > 0, }; - return ( - - - - - - ); + const element = numberRef?.current; + if (element) { + if (inputState.inputValue.length > 0) { + element.classList.add("display-icon"); + } else { + element.classList.remove("display-icon"); + } + } + + if (isValid) { + updatedState.maskedInputValue = maskValidCard(maskedInputValue); + } + + if (typeof onBlur === "function") { + onBlur(event); + } + if (typeof onKeyDown === "function") { + onKeyDown(false); + } + + setInputState((newState) => ({ ...newState, ...updatedState })); + }; + + const onKeyDownEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onKeyDown === "function") { + if (event.key === "Enter") { + onKeyDown(true); + } else { + onKeyDown(false); + } + } + + if (allowNavigation) { + navigateOnKeyDown(event, navigation); + } + }; + + const onPasteEvent: (InputEvent) => void = (): void => { + setInputState((newState) => ({ ...newState, contentPasted: true })); + }; + + return ( + + + + + + ); } diff --git a/src/card/components/CardPostalCode.jsx b/src/card/components/CardPostalCode.jsx index 0bcfced1a0..275019186e 100644 --- a/src/card/components/CardPostalCode.jsx +++ b/src/card/components/CardPostalCode.jsx @@ -1,138 +1,155 @@ /* @flow */ /** @jsx h */ -import { h, Fragment } from 'preact'; -import { useState, useEffect, useRef } from 'preact/hooks'; -import cardValidator from 'card-validator'; - -import { defaultNavigation, defaultInputState, navigateOnKeyDown, exportMethods } from '../lib'; -import type { CardPostalCodeChangeEvent, CardNavigation, FieldValidity, InputState, InputEvent } from '../types'; - -import { AriaMessage } from './AriaMessage' +import { h, Fragment } from "preact"; +import { useState, useEffect, useRef } from "preact/hooks"; +import cardValidator from "card-validator"; + +import { + defaultNavigation, + defaultInputState, + navigateOnKeyDown, + exportMethods, +} from "../lib"; +import type { + CardPostalCodeChangeEvent, + CardNavigation, + FieldValidity, + InputState, + InputEvent, +} from "../types"; + +import { AriaMessage } from "./AriaMessage"; type CardPostalCodeProps = {| - name : string, - type : string, - state? : InputState, - placeholder : string, - style : Object, - maxLength : number, - navigation : CardNavigation, - onChange : (expiryEvent : CardPostalCodeChangeEvent) => void, - onFocus? : (event : InputEvent) => void, - onBlur? : (event : InputEvent) => void, - onKeyDown? : (keyDown : boolean) => void, - allowNavigation : boolean, - onValidityChange? : (numberValidity : FieldValidity) => void, - minLength: number + name: string, + type: string, + state?: InputState, + placeholder: string, + style: Object, + maxLength: number, + navigation: CardNavigation, + onChange: (expiryEvent: CardPostalCodeChangeEvent) => void, + onFocus?: (event: InputEvent) => void, + onBlur?: (event: InputEvent) => void, + onKeyDown?: (keyDown: boolean) => void, + allowNavigation: boolean, + onValidityChange?: (numberValidity: FieldValidity) => void, + minLength: number, |}; -export function CardPostalCode( - { - name = 'postal', - navigation = defaultNavigation, - allowNavigation = false, - state, - type, - placeholder, - style, - maxLength, - onChange, - onFocus, - onBlur, - onKeyDown, - onValidityChange, - minLength - } : CardPostalCodeProps -) : mixed { - const [ attributes, setAttributes ] : [ Object, (Object) => Object ] = useState({ placeholder }); - const [ inputState, setInputState ] : [ InputState, (InputState | InputState => InputState) => InputState ] = useState({ ...defaultInputState, ...state }); - const { inputValue, keyStrokeCount, isValid, isPotentiallyValid } = inputState; - - const postalCodeRef = useRef(); - const ariaMessageRef = useRef() - - useEffect(() => { - exportMethods(postalCodeRef, setAttributes, setInputState, ariaMessageRef); - }, []); - - useEffect(() => { - onChange({ cardPostalCode: inputState.inputValue }); - }, [ inputState ]); - - useEffect(() => { - if (typeof onValidityChange === 'function') { - onValidityChange({ isValid, isPotentiallyValid }); - } - if (allowNavigation && inputValue && isValid) { - navigation.next(); - } - }, [ isValid, isPotentiallyValid ]); - - const setPostalCodeValue : (InputEvent) => void = (event : InputEvent) : void => { - const { value } = event.target; - const validity = cardValidator.postalCode(value, { minLength }); - - setInputState({ - ...inputState, - ...validity, - inputValue: value, - keyStrokeCount: keyStrokeCount + 1 - }); - }; - - const onKeyDownEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onKeyDown === 'function') { - if(event.key === "Enter"){ - onKeyDown(true) - } else { - onKeyDown(false) - } - } - - if (allowNavigation) { - navigateOnKeyDown(event, navigation); - } - }; - - const onFocusEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onFocus === 'function') { - onFocus(event); - } - }; - - const onBlurEvent : (InputEvent) => void = (event : InputEvent) : void => { - if (typeof onBlur === 'function') { - onBlur(event); - } - if ( typeof onKeyDown === 'function') { - onKeyDown(false) - } - }; - - return ( - - - - - ) +export function CardPostalCode({ + name = "postal", + navigation = defaultNavigation, + allowNavigation = false, + state, + type, + placeholder, + style, + maxLength, + onChange, + onFocus, + onBlur, + onKeyDown, + onValidityChange, + minLength, +}: CardPostalCodeProps): mixed { + const [attributes, setAttributes]: [Object, (Object) => Object] = useState({ + placeholder, + }); + const [inputState, setInputState]: [ + InputState, + (InputState | ((InputState) => InputState)) => InputState, + ] = useState({ ...defaultInputState, ...state }); + const { inputValue, keyStrokeCount, isValid, isPotentiallyValid } = + inputState; + + const postalCodeRef = useRef(); + const ariaMessageRef = useRef(); + + useEffect(() => { + exportMethods(postalCodeRef, setAttributes, setInputState, ariaMessageRef); + }, []); + + useEffect(() => { + onChange({ cardPostalCode: inputState.inputValue }); + }, [inputState]); + + useEffect(() => { + if (typeof onValidityChange === "function") { + onValidityChange({ isValid, isPotentiallyValid }); + } + if (allowNavigation && inputValue && isValid) { + navigation.next(); + } + }, [isValid, isPotentiallyValid]); + + const setPostalCodeValue: (InputEvent) => void = ( + event: InputEvent, + ): void => { + const { value } = event.target; + const validity = cardValidator.postalCode(value, { minLength }); + + setInputState({ + ...inputState, + ...validity, + inputValue: value, + keyStrokeCount: keyStrokeCount + 1, + }); + }; + + const onKeyDownEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onKeyDown === "function") { + if (event.key === "Enter") { + onKeyDown(true); + } else { + onKeyDown(false); + } + } + + if (allowNavigation) { + navigateOnKeyDown(event, navigation); + } + }; + + const onFocusEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onFocus === "function") { + onFocus(event); + } + }; + + const onBlurEvent: (InputEvent) => void = (event: InputEvent): void => { + if (typeof onBlur === "function") { + onBlur(event); + } + if (typeof onKeyDown === "function") { + onKeyDown(false); + } + }; + + return ( + + + + + ); } diff --git a/src/card/components/Icons.jsx b/src/card/components/Icons.jsx index 41ecfee435..8cadeaa202 100644 --- a/src/card/components/Icons.jsx +++ b/src/card/components/Icons.jsx @@ -1,102 +1,219 @@ /* @flow */ /** @jsx h */ -import { h } from 'preact'; +import { h } from "preact"; -export function Icons() : mixed { - return ( - - +export function Icons(): mixed { + return ( + + + + Visa + + - - Visa - - + + MasterCard + + + + + + - - MasterCard - - - - - - - - - Union Pay - - - - - - - - - - + + Union Pay + + + + + + + + + + - - American Express - - - - + + American Express + + + + - - JCB - - - - - + + JCB + + + + + - - Discover - - - - - + + Discover + + + + + - - Diners Club - - - - - + + Diners Club + + + + + - - Maestro - - - - - - + + Maestro + + + + + + - - - - - - - - + + + + + + + + - - - - - - - ) -}; + + + + + + ); +} -export function Icon({ iconId, iconClass } : Object) : mixed { - return ( - - - - ); +export function Icon({ iconId, iconClass }: Object): mixed { + return ( + + + + ); } diff --git a/src/card/components/fields.jsx b/src/card/components/fields.jsx index 51a58ba9bb..f23f1603f4 100644 --- a/src/card/components/fields.jsx +++ b/src/card/components/fields.jsx @@ -2,608 +2,830 @@ /** @jsx h */ /* eslint-disable flowtype/require-exact-type */ -import { h, Fragment } from 'preact'; -import { noop } from '@krakenjs/belter'; -import { useState, useEffect, useRef } from 'preact/hooks'; - -import { setErrors, initFieldValidity, goToNextField, goToPreviousField, convertDateFormat, getCSSText, markValidity, exportMethods } from '../lib'; -import type { CardStyle, Card, CardNumberChangeEvent, CardExpiryChangeEvent, CardCvvChangeEvent, CardNameChangeEvent, CardPostalCodeChangeEvent, FieldValidity, CardNavigation, CardType } from '../types'; -import { CARD_ERRORS, DEFAULT_STYLE_MULTI_CARD, DEFAULT_STYLE_SINGLE_CARD, DEFAULT_PLACEHOLDERS, CARD_FIELD_TYPE } from '../constants'; - -import { CardNumber } from './CardNumber'; -import { CardExpiry } from './CardExpiry'; -import { CardCVV } from './CardCVV'; -import { CardName } from './CardName'; -import { CardPostalCode } from './CardPostalCode'; -import { Icons, Icon } from './Icons'; +import { h, Fragment } from "preact"; +import { noop } from "@krakenjs/belter"; +import { useState, useEffect, useRef } from "preact/hooks"; + +import { + setErrors, + initFieldValidity, + goToNextField, + goToPreviousField, + convertDateFormat, + getCSSText, + markValidity, + exportMethods, +} from "../lib"; +import type { + CardStyle, + Card, + CardNumberChangeEvent, + CardExpiryChangeEvent, + CardCvvChangeEvent, + CardNameChangeEvent, + CardPostalCodeChangeEvent, + FieldValidity, + CardNavigation, + CardType, +} from "../types"; +import { + CARD_ERRORS, + DEFAULT_STYLE_MULTI_CARD, + DEFAULT_STYLE_SINGLE_CARD, + DEFAULT_PLACEHOLDERS, + CARD_FIELD_TYPE, +} from "../constants"; + +import { CardNumber } from "./CardNumber"; +import { CardExpiry } from "./CardExpiry"; +import { CardCVV } from "./CardCVV"; +import { CardName } from "./CardName"; +import { CardPostalCode } from "./CardPostalCode"; +import { Icons, Icon } from "./Icons"; type CardFieldProps = {| - cspNonce : string, - onChange : ({ value : Card, valid : boolean, errors : [$Values] | [] }) => void, - styleObject : CardStyle, - placeholder : {| number? : string, expiry? : string, cvv? : string |}, - autoFocusRef : (mixed) => void, - autocomplete? : string, - gqlErrorsObject : {| field : string, errors : [] |} + cspNonce: string, + onChange: ({ + value: Card, + valid: boolean, + errors: [$Values] | [], + }) => void, + styleObject: CardStyle, + placeholder: {| number?: string, expiry?: string, cvv?: string |}, + autoFocusRef: (mixed) => void, + autocomplete?: string, + gqlErrorsObject: {| field: string, errors: [] |}, |}; -export function CardField({ cspNonce, onChange, styleObject = {}, placeholder = {}, gqlErrorsObject = {}, autoFocusRef, autocomplete } : CardFieldProps) : mixed { - const [ attributes, setAttributes ] : [ Object, (Object) => Object ] = useState({}); - const [ cssText, setCSSText ] : [ string, (string) => string ] = useState(''); - const [ number, setNumber ] : [ string, (string) => string ] = useState(''); - const [ cvv, setCvv ] : [ string, (string) => string ] = useState(''); - const [ expiry, setExpiry ] : [ string, (string) => string ] = useState(''); - const [ isValid, setIsValid ] : [ boolean, (boolean) => boolean ] = useState(true); - const [ validationMessage, setValidationMessage ] : [ string, (string) => string ] = useState(''); - const [ isCardEligible, setIsCardEligible ] : [ boolean, (boolean) => boolean ] = useState(true); - const [ numberValidity, setNumberValidity ] : [ FieldValidity, (FieldValidity) => FieldValidity ] = useState(initFieldValidity); - const [ expiryValidity, setExpiryValidity ] : [ FieldValidity, (FieldValidity) => FieldValidity ] = useState(initFieldValidity); - const [ cvvValidity, setCvvValidity ] : [ FieldValidity, (FieldValidity) => FieldValidity ] = useState(initFieldValidity); - const [ touched, setTouched ] = useState(false) - // TODO: change the focus boolean flag to an object to avoid a race condition when either of number/expiry or cvv - // fields have been focused instantaneously. Eg: {cvvHasFocus: true, expiryHasFocus: false, ...}, if any of these - // fields has focus, hasFocus should be true since this block is for Single Card Fields - const [ hasFocus, setHasFocus ] : [ boolean, (boolean) => boolean ] = useState(false); - const numberRef = useRef(); - const expiryRef = useRef(); - const cvvRef = useRef(); - const cardFieldRef = useRef(); - - const cardNumberNavivation : CardNavigation = { next: goToNextField(expiryRef), previous: () => noop }; - const cardExpiryNavivation : CardNavigation = { next: goToNextField(cvvRef), previous: goToPreviousField(numberRef) }; - const cardCvvNavivation : CardNavigation = { next: () => noop, previous: goToPreviousField(expiryRef) }; - - function getValidationMessage() : string { - if (!isCardEligible) { - return 'This card vendor is not eligible.'; - } - if (!numberValidity.isPotentiallyValid && !numberValidity.isValid) { - return 'This card number is not valid.'; - } - if (!expiryValidity.isPotentiallyValid && !expiryValidity.isValid) { - return 'This expiration date is not valid.'; - } - if (!cvvValidity.isPotentiallyValid && !cvvValidity.isValid) { - return 'This security code is not valid.'; - } - return ''; +export function CardField({ + cspNonce, + onChange, + styleObject = {}, + placeholder = {}, + gqlErrorsObject = {}, + autoFocusRef, + autocomplete, +}: CardFieldProps): mixed { + const [attributes, setAttributes]: [Object, (Object) => Object] = useState( + {}, + ); + const [cssText, setCSSText]: [string, (string) => string] = useState(""); + const [number, setNumber]: [string, (string) => string] = useState(""); + const [cvv, setCvv]: [string, (string) => string] = useState(""); + const [expiry, setExpiry]: [string, (string) => string] = useState(""); + const [isValid, setIsValid]: [boolean, (boolean) => boolean] = useState(true); + const [validationMessage, setValidationMessage]: [ + string, + (string) => string, + ] = useState(""); + const [isCardEligible, setIsCardEligible]: [boolean, (boolean) => boolean] = + useState(true); + const [numberValidity, setNumberValidity]: [ + FieldValidity, + (FieldValidity) => FieldValidity, + ] = useState(initFieldValidity); + const [expiryValidity, setExpiryValidity]: [ + FieldValidity, + (FieldValidity) => FieldValidity, + ] = useState(initFieldValidity); + const [cvvValidity, setCvvValidity]: [ + FieldValidity, + (FieldValidity) => FieldValidity, + ] = useState(initFieldValidity); + const [touched, setTouched] = useState(false); + // TODO: change the focus boolean flag to an object to avoid a race condition when either of number/expiry or cvv + // fields have been focused instantaneously. Eg: {cvvHasFocus: true, expiryHasFocus: false, ...}, if any of these + // fields has focus, hasFocus should be true since this block is for Single Card Fields + const [hasFocus, setHasFocus]: [boolean, (boolean) => boolean] = + useState(false); + const numberRef = useRef(); + const expiryRef = useRef(); + const cvvRef = useRef(); + const cardFieldRef = useRef(); + + const cardNumberNavivation: CardNavigation = { + next: goToNextField(expiryRef), + previous: () => noop, + }; + const cardExpiryNavivation: CardNavigation = { + next: goToNextField(cvvRef), + previous: goToPreviousField(numberRef), + }; + const cardCvvNavivation: CardNavigation = { + next: () => noop, + previous: goToPreviousField(expiryRef), + }; + + function getValidationMessage(): string { + if (!isCardEligible) { + return "This card vendor is not eligible."; + } + if (!numberValidity.isPotentiallyValid && !numberValidity.isValid) { + return "This card number is not valid."; + } + if (!expiryValidity.isPotentiallyValid && !expiryValidity.isValid) { + return "This expiration date is not valid."; + } + if (!cvvValidity.isPotentiallyValid && !cvvValidity.isValid) { + return "This security code is not valid."; + } + return ""; + } + + useEffect(() => { + autoFocusRef(numberRef); + exportMethods(cardFieldRef, setAttributes); + }, []); + + useEffect(() => { + setCSSText(getCSSText(DEFAULT_STYLE_SINGLE_CARD, styleObject)); + }, [styleObject]); + + useEffect(() => { + const { field, errors } = gqlErrorsObject; + + if (field === CARD_FIELD_TYPE.NUMBER) { + const hasGQLErrors = errors.length > 0; + if (hasGQLErrors) { + setNumberValidity({ isPotentiallyValid: false, isValid: false }); + } } - useEffect(() => { - autoFocusRef(numberRef); - exportMethods(cardFieldRef, setAttributes); - }, []); - - useEffect(() => { - setCSSText(getCSSText(DEFAULT_STYLE_SINGLE_CARD, styleObject)); - }, [ styleObject ]); - - useEffect(() => { - const { field, errors } = gqlErrorsObject; - - if (field === CARD_FIELD_TYPE.NUMBER) { - const hasGQLErrors = errors.length > 0; - if (hasGQLErrors) { - setNumberValidity({ isPotentiallyValid: false, isValid: false }); - } - } + if (field === CARD_FIELD_TYPE.EXPIRY) { + const hasGQLErrors = errors.length > 0; + if (hasGQLErrors) { + setExpiryValidity({ isPotentiallyValid: false, isValid: false }); + } + } - if (field === CARD_FIELD_TYPE.EXPIRY) { - const hasGQLErrors = errors.length > 0; - if (hasGQLErrors) { - setExpiryValidity({ isPotentiallyValid: false, isValid: false }); - } - } + if (field === CARD_FIELD_TYPE.CVV) { + const hasGQLErrors = errors.length > 0; + if (hasGQLErrors) { + setCvvValidity({ isPotentiallyValid: false, isValid: false }); + } + } + }, [gqlErrorsObject]); - if (field === CARD_FIELD_TYPE.CVV) { - const hasGQLErrors = errors.length > 0; - if (hasGQLErrors) { - setCvvValidity({ isPotentiallyValid: false, isValid: false }); - } - } - }, [ gqlErrorsObject ]); - - useEffect(() => { - - setValidationMessage(getValidationMessage()); - - const valid = Boolean(numberValidity.isValid && cvvValidity.isValid && expiryValidity.isValid); - - setIsValid(valid); - - const errors = setErrors({ isCardEligible, isNumberValid: numberValidity.isValid, isCvvValid: cvvValidity.isValid, isExpiryValid: expiryValidity.isValid, gqlErrorsObject }); - - markValidity(numberRef, numberValidity, hasFocus, touched); - markValidity(expiryRef, expiryValidity, hasFocus, touched); - markValidity(cvvRef, cvvValidity, hasFocus, touched); - - onChange({ value: { number, cvv, expiry }, valid, errors }); - - }, [ - number, - cvv, - expiry, - isValid, - numberValidity, - isCardEligible, - cvvValidity, - expiryValidity - ]); - - useEffect(() => { - const element = cardFieldRef?.current; - if (element) { - if (hasFocus) { - element.classList.add('focus'); - } else { - element.classList.remove('focus'); - } - if (validationMessage.length > 0) { - element.classList.add('invalid'); - } else { - element.classList.remove('invalid'); - } - } - }, [ hasFocus, validationMessage ]); + useEffect(() => { + setValidationMessage(getValidationMessage()); - const onChangeNumber : (CardNumberChangeEvent) => void = ({ cardNumber } : CardNumberChangeEvent) : void => { - setNumber(cardNumber); - }; + const valid = Boolean( + numberValidity.isValid && cvvValidity.isValid && expiryValidity.isValid, + ); - const handleFocus = () => { - setTouched(true) - setHasFocus(true) + setIsValid(valid); + + const errors = setErrors({ + isCardEligible, + isNumberValid: numberValidity.isValid, + isCvvValid: cvvValidity.isValid, + isExpiryValid: expiryValidity.isValid, + gqlErrorsObject, + }); + + markValidity(numberRef, numberValidity, hasFocus, touched); + markValidity(expiryRef, expiryValidity, hasFocus, touched); + markValidity(cvvRef, cvvValidity, hasFocus, touched); + + onChange({ value: { number, cvv, expiry }, valid, errors }); + }, [ + number, + cvv, + expiry, + isValid, + numberValidity, + isCardEligible, + cvvValidity, + expiryValidity, + ]); + + useEffect(() => { + const element = cardFieldRef?.current; + if (element) { + if (hasFocus) { + element.classList.add("focus"); + } else { + element.classList.remove("focus"); + } + if (validationMessage.length > 0) { + element.classList.add("invalid"); + } else { + element.classList.remove("invalid"); + } } - - return ( - - - -
- setIsCardEligible(eligibility) } - onValidityChange={ (validity : FieldValidity) => setNumberValidity({ ...validity }) } - onFocus={ handleFocus } - onBlur={ () => setHasFocus(false) } - /> - setExpiry(convertDateFormat(maskedDate)) } - onValidityChange={ (validity : FieldValidity) => setExpiryValidity({ ...validity }) } - onFocus={ handleFocus } - onBlur={ () => setHasFocus(false) } - /> - setCvv(cardCvv) } - onValidityChange={ (validity : FieldValidity) => setCvvValidity({ ...validity }) } - onFocus={ handleFocus } - onBlur={ () => setHasFocus(false) } - /> -
- -
- ); + }, [hasFocus, validationMessage]); + + const onChangeNumber: (CardNumberChangeEvent) => void = ({ + cardNumber, + }: CardNumberChangeEvent): void => { + setNumber(cardNumber); + }; + + const handleFocus = () => { + setTouched(true); + setHasFocus(true); + }; + + return ( + + + +
+ + setIsCardEligible(eligibility) + } + onValidityChange={(validity: FieldValidity) => + setNumberValidity({ ...validity }) + } + onFocus={handleFocus} + onBlur={() => setHasFocus(false)} + /> + + setExpiry(convertDateFormat(maskedDate)) + } + onValidityChange={(validity: FieldValidity) => + setExpiryValidity({ ...validity }) + } + onFocus={handleFocus} + onBlur={() => setHasFocus(false)} + /> + setCvv(cardCvv)} + onValidityChange={(validity: FieldValidity) => + setCvvValidity({ ...validity }) + } + onFocus={handleFocus} + onBlur={() => setHasFocus(false)} + /> +
+ +
+ ); } -export function ValidationMessage({ message } : Object) : mixed { - return ( -
- - { message } -
- ); +export function ValidationMessage({ message }: Object): mixed { + return ( +
+ + {message} +
+ ); } type CardNumberFieldProps = {| - cspNonce : string, - onChange : ({| value : string, valid : boolean, isFocused: boolean, potentiallyValid: boolean, potentialCardTypes: $ReadOnlyArray | [] |}) => void, - onFocus : ({ isFocused: boolean }) => void, - onKeyDown : ({isInputSubmitRequest: boolean}) => void, - styleObject : CardStyle, - placeholder : string, - autoFocusRef : (mixed) => void, - autocomplete? : string, - gqlErrors : [] + cspNonce: string, + onChange: ({| + value: string, + valid: boolean, + isFocused: boolean, + potentiallyValid: boolean, + potentialCardTypes: $ReadOnlyArray | [], + |}) => void, + onFocus: ({ isFocused: boolean }) => void, + onKeyDown: ({ isInputSubmitRequest: boolean }) => void, + styleObject: CardStyle, + placeholder: string, + autoFocusRef: (mixed) => void, + autocomplete?: string, + gqlErrors: [], |}; -export function CardNumberField({ cspNonce, onChange, onFocus, styleObject = {}, placeholder, autoFocusRef, autocomplete, onKeyDown, gqlErrors = [] } : CardNumberFieldProps) : mixed { - const [ cssText, setCSSText ] : [ string, (string) => string ] = useState(''); - const [ number, setNumber ] : [ string, (string) => string ] = useState(''); - const [ isCardEligible, setIsCardEligible ] : [ boolean, (boolean) => boolean ] = useState(true); - const [ numberValidity, setNumberValidity ] : [ FieldValidity, (FieldValidity) => FieldValidity ] = useState(initFieldValidity); - const [ cards, setCards ] : [$ReadOnlyArray, (CardType) => $ReadOnlyArray] = useState([]) - const [ hasFocus, setHasFocus ] : [ boolean, (boolean) => boolean ] = useState(false); - const [ touched, setTouched ] = useState(false) - const [ isSubmitRequest, setIsSubmitRequest ] : [ boolean, (boolean) => boolean ] = useState(false); - const numberRef = useRef(); - - const { isValid, isPotentiallyValid } = numberValidity; - - useEffect(() => { - autoFocusRef(numberRef); - }, []); - - useEffect(() => { - setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); - }, [ styleObject ]); - - useEffect(() => { - const hasGQLErrors = gqlErrors.length > 0; - if (hasGQLErrors) { - setNumberValidity({ isPotentiallyValid: false, isValid: false }); - } - }, [ gqlErrors ]); - - useEffect(() => { - markValidity(numberRef, numberValidity, hasFocus, touched); - onChange({ value: number, valid: numberValidity.isValid, isFocused: hasFocus, potentiallyValid: numberValidity.isPotentiallyValid, potentialCardTypes: cards }); - }, [ number, isCardEligible, isValid, hasFocus, isPotentiallyValid, cards ]); - - const handleInputChange = (cardNumber, potentialCardTypes) => { - setNumber(cardNumber) - setCards(potentialCardTypes) - } - useEffect(() => { - onFocus({isFocused: hasFocus}) - }, [hasFocus]); - - useEffect(()=> { - onKeyDown({isInputSubmitRequest: isSubmitRequest}) - }, [isSubmitRequest]); - - const handleFocus = () => { - setTouched(true) - setHasFocus(true) +export function CardNumberField({ + cspNonce, + onChange, + onFocus, + styleObject = {}, + placeholder, + autoFocusRef, + autocomplete, + onKeyDown, + gqlErrors = [], +}: CardNumberFieldProps): mixed { + const [cssText, setCSSText]: [string, (string) => string] = useState(""); + const [number, setNumber]: [string, (string) => string] = useState(""); + const [isCardEligible, setIsCardEligible]: [boolean, (boolean) => boolean] = + useState(true); + const [numberValidity, setNumberValidity]: [ + FieldValidity, + (FieldValidity) => FieldValidity, + ] = useState(initFieldValidity); + const [cards, setCards]: [ + $ReadOnlyArray, + (CardType) => $ReadOnlyArray, + ] = useState([]); + const [hasFocus, setHasFocus]: [boolean, (boolean) => boolean] = + useState(false); + const [touched, setTouched] = useState(false); + const [isSubmitRequest, setIsSubmitRequest]: [boolean, (boolean) => boolean] = + useState(false); + const numberRef = useRef(); + + const { isValid, isPotentiallyValid } = numberValidity; + + useEffect(() => { + autoFocusRef(numberRef); + }, []); + + useEffect(() => { + setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); + }, [styleObject]); + + useEffect(() => { + const hasGQLErrors = gqlErrors.length > 0; + if (hasGQLErrors) { + setNumberValidity({ isPotentiallyValid: false, isValid: false }); } - - return ( - - - - handleInputChange(cardNumber, potentialCardTypes) } - onEligibilityChange={ (eligibility : boolean) => setIsCardEligible(eligibility) } - onValidityChange={ (validity : FieldValidity) => setNumberValidity(validity) } - onFocus={ handleFocus } - onBlur={ () => setHasFocus(false) } - onKeyDown={ (keyDown: boolean) => setIsSubmitRequest(keyDown) } - /> - - ); + }, [gqlErrors]); + + useEffect(() => { + markValidity(numberRef, numberValidity, hasFocus, touched); + onChange({ + value: number, + valid: numberValidity.isValid, + isFocused: hasFocus, + potentiallyValid: numberValidity.isPotentiallyValid, + potentialCardTypes: cards, + }); + }, [number, isCardEligible, isValid, hasFocus, isPotentiallyValid, cards]); + + const handleInputChange = (cardNumber, potentialCardTypes) => { + setNumber(cardNumber); + setCards(potentialCardTypes); + }; + useEffect(() => { + onFocus({ isFocused: hasFocus }); + }, [hasFocus]); + + useEffect(() => { + onKeyDown({ isInputSubmitRequest: isSubmitRequest }); + }, [isSubmitRequest]); + + const handleFocus = () => { + setTouched(true); + setHasFocus(true); + }; + + return ( + + + + + handleInputChange(cardNumber, potentialCardTypes) + } + onEligibilityChange={(eligibility: boolean) => + setIsCardEligible(eligibility) + } + onValidityChange={(validity: FieldValidity) => + setNumberValidity(validity) + } + onFocus={handleFocus} + onBlur={() => setHasFocus(false)} + onKeyDown={(keyDown: boolean) => setIsSubmitRequest(keyDown)} + /> + + ); } type CardExpiryFieldProps = {| - cspNonce : string, - onChange : ({| value : string, valid : boolean, isFocused: boolean, potentiallyValid: boolean |}) => void, - onFocus : ({ isFocused: boolean }) => void, - onKeyDown : ({isInputSubmitRequest: boolean}) => void, - styleObject : CardStyle, - placeholder : string, - autoFocusRef : (mixed) => void, - autocomplete? : string, - gqlErrors : [] + cspNonce: string, + onChange: ({| + value: string, + valid: boolean, + isFocused: boolean, + potentiallyValid: boolean, + |}) => void, + onFocus: ({ isFocused: boolean }) => void, + onKeyDown: ({ isInputSubmitRequest: boolean }) => void, + styleObject: CardStyle, + placeholder: string, + autoFocusRef: (mixed) => void, + autocomplete?: string, + gqlErrors: [], |}; -export function CardExpiryField({ cspNonce, onChange, onFocus, onKeyDown, styleObject = {}, placeholder, autoFocusRef, autocomplete, gqlErrors = [] } : CardExpiryFieldProps) : mixed { - const [ cssText, setCSSText ] : [ string, (string) => string ] = useState(''); - const [ expiry, setExpiry ] : [ string, (string) => string ] = useState(''); - const [ expiryValidity, setExpiryValidity ] : [ FieldValidity, (FieldValidity) => FieldValidity ] = useState(initFieldValidity); - const expiryRef = useRef(); - const [ hasFocus, setHasFocus ] : [ boolean, (boolean) => boolean ] = useState(false); - const [ touched, setTouched ] = useState(false) - const [ isSubmitRequest, setIsSubmitRequest ] : [ boolean, (boolean) => boolean ] = useState(false); - - const { isValid, isPotentiallyValid } = expiryValidity; - - useEffect(() => { - autoFocusRef(expiryRef); - }, []); - - useEffect(() => { - setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); - }, [ styleObject ]); - - useEffect(() => { - const hasGQLErrors = gqlErrors.length > 0; - if (hasGQLErrors) { - setExpiryValidity({ isPotentiallyValid: false, isValid: false }); - } - }, [ gqlErrors ]); - - useEffect(() => { - markValidity(expiryRef, expiryValidity, hasFocus, touched); - onChange({ value: expiry, valid: expiryValidity.isValid, isFocused: hasFocus, potentiallyValid: expiryValidity.isPotentiallyValid }); - }, [ expiry, isValid, hasFocus, isPotentiallyValid ]); - - useEffect(() => { - onFocus({isFocused: hasFocus}) - }, [hasFocus]); - - useEffect(() => { - onKeyDown({isInputSubmitRequest: isSubmitRequest}) - }, [isSubmitRequest]) - - const handleFocus = () => { - setTouched(true) - setHasFocus(true) +export function CardExpiryField({ + cspNonce, + onChange, + onFocus, + onKeyDown, + styleObject = {}, + placeholder, + autoFocusRef, + autocomplete, + gqlErrors = [], +}: CardExpiryFieldProps): mixed { + const [cssText, setCSSText]: [string, (string) => string] = useState(""); + const [expiry, setExpiry]: [string, (string) => string] = useState(""); + const [expiryValidity, setExpiryValidity]: [ + FieldValidity, + (FieldValidity) => FieldValidity, + ] = useState(initFieldValidity); + const expiryRef = useRef(); + const [hasFocus, setHasFocus]: [boolean, (boolean) => boolean] = + useState(false); + const [touched, setTouched] = useState(false); + const [isSubmitRequest, setIsSubmitRequest]: [boolean, (boolean) => boolean] = + useState(false); + + const { isValid, isPotentiallyValid } = expiryValidity; + + useEffect(() => { + autoFocusRef(expiryRef); + }, []); + + useEffect(() => { + setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); + }, [styleObject]); + + useEffect(() => { + const hasGQLErrors = gqlErrors.length > 0; + if (hasGQLErrors) { + setExpiryValidity({ isPotentiallyValid: false, isValid: false }); } - - return ( - - - setExpiry(convertDateFormat(maskedDate)) } - onValidityChange={ (validity : FieldValidity) => setExpiryValidity(validity) } - onFocus={ handleFocus } - onBlur={ () => setHasFocus(false) } - onKeyDown={ (value: boolean) => setIsSubmitRequest(value) } - /> - - ); + }, [gqlErrors]); + + useEffect(() => { + markValidity(expiryRef, expiryValidity, hasFocus, touched); + onChange({ + value: expiry, + valid: expiryValidity.isValid, + isFocused: hasFocus, + potentiallyValid: expiryValidity.isPotentiallyValid, + }); + }, [expiry, isValid, hasFocus, isPotentiallyValid]); + + useEffect(() => { + onFocus({ isFocused: hasFocus }); + }, [hasFocus]); + + useEffect(() => { + onKeyDown({ isInputSubmitRequest: isSubmitRequest }); + }, [isSubmitRequest]); + + const handleFocus = () => { + setTouched(true); + setHasFocus(true); + }; + + return ( + + + + setExpiry(convertDateFormat(maskedDate)) + } + onValidityChange={(validity: FieldValidity) => + setExpiryValidity(validity) + } + onFocus={handleFocus} + onBlur={() => setHasFocus(false)} + onKeyDown={(value: boolean) => setIsSubmitRequest(value)} + /> + + ); } type CardCvvFieldProps = {| - cspNonce : string, - onChange : ({| value : string, valid : boolean, isFocused: boolean, potentiallyValid: boolean |}) => void, - onFocus : ({ isFocused: boolean }) => void, - onKeyDown : ({isInputSubmitRequest: boolean}) => void, - styleObject : CardStyle, - placeholder : string, - autoFocusRef : (mixed) => void, - autocomplete? : string, - gqlErrors : [] + cspNonce: string, + onChange: ({| + value: string, + valid: boolean, + isFocused: boolean, + potentiallyValid: boolean, + |}) => void, + onFocus: ({ isFocused: boolean }) => void, + onKeyDown: ({ isInputSubmitRequest: boolean }) => void, + styleObject: CardStyle, + placeholder: string, + autoFocusRef: (mixed) => void, + autocomplete?: string, + gqlErrors: [], |}; -export function CardCVVField({ cspNonce, onChange, onFocus, onKeyDown, styleObject = {}, placeholder, autoFocusRef, autocomplete, gqlErrors = [] } : CardCvvFieldProps) : mixed { - const [ cssText, setCSSText ] : [ string, (string) => string ] = useState(''); - const [ cvv, setCvv ] : [ string, (string) => string ] = useState(''); - const [ cvvValidity, setCvvValidity ] : [ FieldValidity, (FieldValidity) => FieldValidity ] = useState(initFieldValidity); - const cvvRef = useRef(); - const [ hasFocus, setHasFocus ] : [ boolean, (boolean) => boolean ] = useState(false); - const [ touched, setTouched ] = useState(false) - const [ isSubmitRequest, setIsSubmitRequest ] : [ boolean, (boolean) => boolean ] = useState(false); - - const { isValid, isPotentiallyValid } = cvvValidity; - - useEffect(() => { - autoFocusRef(cvvRef); - }, []); - - useEffect(() => { - setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); - }, [ styleObject ]); - - useEffect(() => { - const hasGQLErrors = gqlErrors.length > 0; - if (hasGQLErrors) { - setCvvValidity({ isPotentiallyValid: false, isValid: false }); - } - }, [ gqlErrors ]); - - useEffect(() => { - markValidity(cvvRef, cvvValidity, hasFocus, touched); - onChange({ value: cvv, valid: cvvValidity.isValid, isFocused: hasFocus, potentiallyValid: cvvValidity.isPotentiallyValid }); - }, [ cvv, isValid, hasFocus, isPotentiallyValid ]); - - useEffect(() => { - onFocus({isFocused: hasFocus}) - }, [hasFocus]); - - useEffect(() => { - onKeyDown({isInputSubmitRequest: isSubmitRequest}) - }, [isSubmitRequest]) - - const handleFocus = () => { - setTouched(true) - setHasFocus(true) +export function CardCVVField({ + cspNonce, + onChange, + onFocus, + onKeyDown, + styleObject = {}, + placeholder, + autoFocusRef, + autocomplete, + gqlErrors = [], +}: CardCvvFieldProps): mixed { + const [cssText, setCSSText]: [string, (string) => string] = useState(""); + const [cvv, setCvv]: [string, (string) => string] = useState(""); + const [cvvValidity, setCvvValidity]: [ + FieldValidity, + (FieldValidity) => FieldValidity, + ] = useState(initFieldValidity); + const cvvRef = useRef(); + const [hasFocus, setHasFocus]: [boolean, (boolean) => boolean] = + useState(false); + const [touched, setTouched] = useState(false); + const [isSubmitRequest, setIsSubmitRequest]: [boolean, (boolean) => boolean] = + useState(false); + + const { isValid, isPotentiallyValid } = cvvValidity; + + useEffect(() => { + autoFocusRef(cvvRef); + }, []); + + useEffect(() => { + setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); + }, [styleObject]); + + useEffect(() => { + const hasGQLErrors = gqlErrors.length > 0; + if (hasGQLErrors) { + setCvvValidity({ isPotentiallyValid: false, isValid: false }); } - - return ( - - - setCvv(cardCvv) } - onValidityChange={ (validity : FieldValidity) => setCvvValidity(validity) } - onFocus={ handleFocus } - onBlur={ () => setHasFocus(false) } - onKeyDown={ (value: boolean) => setIsSubmitRequest(value) } - /> - - ); + }, [gqlErrors]); + + useEffect(() => { + markValidity(cvvRef, cvvValidity, hasFocus, touched); + onChange({ + value: cvv, + valid: cvvValidity.isValid, + isFocused: hasFocus, + potentiallyValid: cvvValidity.isPotentiallyValid, + }); + }, [cvv, isValid, hasFocus, isPotentiallyValid]); + + useEffect(() => { + onFocus({ isFocused: hasFocus }); + }, [hasFocus]); + + useEffect(() => { + onKeyDown({ isInputSubmitRequest: isSubmitRequest }); + }, [isSubmitRequest]); + + const handleFocus = () => { + setTouched(true); + setHasFocus(true); + }; + + return ( + + + setCvv(cardCvv)} + onValidityChange={(validity: FieldValidity) => setCvvValidity(validity)} + onFocus={handleFocus} + onBlur={() => setHasFocus(false)} + onKeyDown={(value: boolean) => setIsSubmitRequest(value)} + /> + + ); } type CardNameFieldProps = {| - cspNonce : string, - onChange : ({| value : string, valid : boolean, isFocused: boolean, potentiallyValid: boolean |}) => void, - onFocus : ({ isFocused : boolean }) => void, - onKeyDown : ({isInputSubmitRequest: boolean}) => void, - styleObject : CardStyle, - placeholder : string, - autoFocusRef : (mixed) => void, - gqlErrors : [] + cspNonce: string, + onChange: ({| + value: string, + valid: boolean, + isFocused: boolean, + potentiallyValid: boolean, + |}) => void, + onFocus: ({ isFocused: boolean }) => void, + onKeyDown: ({ isInputSubmitRequest: boolean }) => void, + styleObject: CardStyle, + placeholder: string, + autoFocusRef: (mixed) => void, + gqlErrors: [], |}; -export function CardNameField({ cspNonce, onChange, onFocus, onKeyDown, styleObject = {}, placeholder, autoFocusRef, gqlErrors = [] } : CardNameFieldProps) : mixed { - const [ cssText, setCSSText ] : [ string, (string) => string ] = useState(''); - const [ name, setName ] : [ string, (string) => string ] = useState(''); - const [ nameValidity, setNameValidity ] : [ FieldValidity, (FieldValidity) => FieldValidity ] = useState(initFieldValidity); - const nameRef = useRef(); - const [touched, setTouched] = useState(false) - const [ hasFocus, setHasFocus ] : [ boolean, (boolean) => boolean ] = useState(false); - const [ isSubmitRequest, setIsSubmitRequest ] : [ boolean, (boolean) => boolean ] = useState(false); - - const { isValid, isPotentiallyValid } = nameValidity; - - useEffect(() => { - autoFocusRef(nameRef); - }, []); - - useEffect(() => { - setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); - }, [ styleObject ]); - - useEffect(() => { - const hasGQLErrors = gqlErrors.length > 0; - if (hasGQLErrors) { - setNameValidity({ isPotentiallyValid: false, isValid: false }); - } - }, [ gqlErrors ]); - - useEffect(() => { - markValidity(nameRef, nameValidity, hasFocus, touched); - onChange({ value: name, valid: nameValidity.isValid, isFocused: hasFocus, potentiallyValid: nameValidity.isPotentiallyValid }); - }, [ name, isValid, hasFocus, isPotentiallyValid ]); - - useEffect(() => { - onFocus({isFocused: hasFocus}) - }, [hasFocus]); - - useEffect(() => { - onKeyDown({isInputSubmitRequest: isSubmitRequest}) - }, [isSubmitRequest]) - - const handleFocus = () => { - setHasFocus(true) - setTouched(true) +export function CardNameField({ + cspNonce, + onChange, + onFocus, + onKeyDown, + styleObject = {}, + placeholder, + autoFocusRef, + gqlErrors = [], +}: CardNameFieldProps): mixed { + const [cssText, setCSSText]: [string, (string) => string] = useState(""); + const [name, setName]: [string, (string) => string] = useState(""); + const [nameValidity, setNameValidity]: [ + FieldValidity, + (FieldValidity) => FieldValidity, + ] = useState(initFieldValidity); + const nameRef = useRef(); + const [touched, setTouched] = useState(false); + const [hasFocus, setHasFocus]: [boolean, (boolean) => boolean] = + useState(false); + const [isSubmitRequest, setIsSubmitRequest]: [boolean, (boolean) => boolean] = + useState(false); + + const { isValid, isPotentiallyValid } = nameValidity; + + useEffect(() => { + autoFocusRef(nameRef); + }, []); + + useEffect(() => { + setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); + }, [styleObject]); + + useEffect(() => { + const hasGQLErrors = gqlErrors.length > 0; + if (hasGQLErrors) { + setNameValidity({ isPotentiallyValid: false, isValid: false }); } - - return ( - - - setName(cardName) } - onValidityChange={ (validity : FieldValidity) => setNameValidity(validity) } - onFocus={ handleFocus } - onBlur={ () => setHasFocus(false) } - onKeyDown={ (value: boolean) => setIsSubmitRequest(value) } - /> - - ); + }, [gqlErrors]); + + useEffect(() => { + markValidity(nameRef, nameValidity, hasFocus, touched); + onChange({ + value: name, + valid: nameValidity.isValid, + isFocused: hasFocus, + potentiallyValid: nameValidity.isPotentiallyValid, + }); + }, [name, isValid, hasFocus, isPotentiallyValid]); + + useEffect(() => { + onFocus({ isFocused: hasFocus }); + }, [hasFocus]); + + useEffect(() => { + onKeyDown({ isInputSubmitRequest: isSubmitRequest }); + }, [isSubmitRequest]); + + const handleFocus = () => { + setHasFocus(true); + setTouched(true); + }; + + return ( + + + setName(cardName)} + onValidityChange={(validity: FieldValidity) => + setNameValidity(validity) + } + onFocus={handleFocus} + onBlur={() => setHasFocus(false)} + onKeyDown={(value: boolean) => setIsSubmitRequest(value)} + /> + + ); } type CardPostalFieldProps = {| - cspNonce : string, - onChange : ({| value : string, valid : boolean, isFocused: boolean, potentiallyValid: boolean|}) => void, - onFocus : ({ isFocused: boolean }) => void, - onKeyDown : ({isInputSubmitRequest: boolean}) => void, - styleObject : CardStyle, - placeholder : string, - minLength : number, - maxLength: number, - autoFocusRef : (mixed) => void, - autocomplete? : string, - gqlErrors : [] + cspNonce: string, + onChange: ({| + value: string, + valid: boolean, + isFocused: boolean, + potentiallyValid: boolean, + |}) => void, + onFocus: ({ isFocused: boolean }) => void, + onKeyDown: ({ isInputSubmitRequest: boolean }) => void, + styleObject: CardStyle, + placeholder: string, + minLength: number, + maxLength: number, + autoFocusRef: (mixed) => void, + autocomplete?: string, + gqlErrors: [], |}; -export function CardPostalCodeField({ cspNonce, onChange, onFocus, onKeyDown, styleObject = {}, placeholder, minLength, maxLength, autoFocusRef, autocomplete, gqlErrors = [] } : CardPostalFieldProps) : mixed { - const [ cssText, setCSSText ] : [ string, (string) => string ] = useState(''); - const [ postalCode, setPostalCode ] : [ string, (string) => string ] = useState(''); - const [ postalCodeValidity, setPostalCodeValidity ] : [ FieldValidity, (FieldValidity) => FieldValidity ] = useState(initFieldValidity); - const postalRef = useRef(); - const [ hasFocus, setHasFocus ] : [ boolean, (boolean) => boolean ] = useState(false); - const [ touched, setTouched ] = useState(false) - const [ isSubmitRequest, setIsSubmitRequest ] : [ boolean, (boolean) => boolean ] = useState(false); - - const { isValid, isPotentiallyValid } = postalCodeValidity; - - useEffect(() => { - autoFocusRef(postalRef); - }, []); - - useEffect(() => { - setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); - }, [ styleObject ]); - - useEffect(() => { - const hasGQLErrors = gqlErrors.length > 0; - if (hasGQLErrors) { - setPostalCodeValidity({ isPotentiallyValid: false, isValid: false }); - } - }, [ gqlErrors ]); - - useEffect(() => { - markValidity(postalRef, postalCodeValidity, hasFocus, touched); - onChange({ value: postalCode, valid: postalCodeValidity.isValid, isFocused: hasFocus, potentiallyValid: postalCodeValidity.isPotentiallyValid }); - }, [ postalCode, isValid, hasFocus, isPotentiallyValid ]); - - useEffect(() => { - onFocus({isFocused: hasFocus}) - }, [hasFocus]); - - useEffect(() => { - onKeyDown({isInputSubmitRequest: isSubmitRequest}) - }, [isSubmitRequest]) - - const handleFocus = () => { - setTouched(true) - setHasFocus(true) +export function CardPostalCodeField({ + cspNonce, + onChange, + onFocus, + onKeyDown, + styleObject = {}, + placeholder, + minLength, + maxLength, + autoFocusRef, + autocomplete, + gqlErrors = [], +}: CardPostalFieldProps): mixed { + const [cssText, setCSSText]: [string, (string) => string] = useState(""); + const [postalCode, setPostalCode]: [string, (string) => string] = + useState(""); + const [postalCodeValidity, setPostalCodeValidity]: [ + FieldValidity, + (FieldValidity) => FieldValidity, + ] = useState(initFieldValidity); + const postalRef = useRef(); + const [hasFocus, setHasFocus]: [boolean, (boolean) => boolean] = + useState(false); + const [touched, setTouched] = useState(false); + const [isSubmitRequest, setIsSubmitRequest]: [boolean, (boolean) => boolean] = + useState(false); + + const { isValid, isPotentiallyValid } = postalCodeValidity; + + useEffect(() => { + autoFocusRef(postalRef); + }, []); + + useEffect(() => { + setCSSText(getCSSText(DEFAULT_STYLE_MULTI_CARD, styleObject)); + }, [styleObject]); + + useEffect(() => { + const hasGQLErrors = gqlErrors.length > 0; + if (hasGQLErrors) { + setPostalCodeValidity({ isPotentiallyValid: false, isValid: false }); } - - return ( - - - setPostalCode(cardPostalCode) } - onValidityChange={ (validity : FieldValidity) => setPostalCodeValidity(validity) } - onFocus={ handleFocus } - onBlur={ () => setHasFocus(false) } - onKeyDown={ (value: boolean) => setIsSubmitRequest(value) } - /> - - ) + }, [gqlErrors]); + + useEffect(() => { + markValidity(postalRef, postalCodeValidity, hasFocus, touched); + onChange({ + value: postalCode, + valid: postalCodeValidity.isValid, + isFocused: hasFocus, + potentiallyValid: postalCodeValidity.isPotentiallyValid, + }); + }, [postalCode, isValid, hasFocus, isPotentiallyValid]); + + useEffect(() => { + onFocus({ isFocused: hasFocus }); + }, [hasFocus]); + + useEffect(() => { + onKeyDown({ isInputSubmitRequest: isSubmitRequest }); + }, [isSubmitRequest]); + + const handleFocus = () => { + setTouched(true); + setHasFocus(true); + }; + + return ( + + + + setPostalCode(cardPostalCode) + } + onValidityChange={(validity: FieldValidity) => + setPostalCodeValidity(validity) + } + onFocus={handleFocus} + onBlur={() => setHasFocus(false)} + onKeyDown={(value: boolean) => setIsSubmitRequest(value)} + /> + + ); } -/* eslint-enable flowtype/require-exact-type */ \ No newline at end of file +/* eslint-enable flowtype/require-exact-type */ diff --git a/src/card/components/index.js b/src/card/components/index.js index 8c06da1a14..110d5d4c45 100644 --- a/src/card/components/index.js +++ b/src/card/components/index.js @@ -1,4 +1,4 @@ /* @flow */ -export * from './page'; -export * from './fields'; +export * from "./page"; +export * from "./fields"; diff --git a/src/card/components/page.jsx b/src/card/components/page.jsx index 9bdd1a0c4b..194aa95c7f 100644 --- a/src/card/components/page.jsx +++ b/src/card/components/page.jsx @@ -1,373 +1,444 @@ /* @flow */ /** @jsx h */ -import { h, render, Fragment } from 'preact'; -import { useState, useEffect, useRef } from 'preact/hooks'; - -import { getBody } from '../../lib'; -import { setupExports, autoFocusOnFirstInput, filterExtraFields, kebabToCamelCase, parsedCardType} from '../lib'; -import { CARD_FIELD_TYPE_TO_FRAME_NAME, CARD_FIELD_TYPE } from '../constants'; -import { submitCardFields, getCardFieldState, getFieldErrors, isEmpty } from '../interface'; -import { getCardProps, type CardProps } from '../props'; -import type { SetupCardOptions} from '../types'; -import type {FeatureFlags } from '../../types' -import { setupCardLogger } from '../logger'; - -import { CardField, CardNumberField, CardCVVField, CardExpiryField, CardNameField, CardPostalCodeField } from './fields'; +import { h, render, Fragment } from "preact"; +import { useState, useEffect, useRef } from "preact/hooks"; +import { noop } from "@krakenjs/belter/src"; + +import { getBody } from "../../lib"; +import { + setupExports, + autoFocusOnFirstInput, + filterExtraFields, + kebabToCamelCase, + parsedCardType, +} from "../lib"; +import { CARD_FIELD_TYPE_TO_FRAME_NAME, CARD_FIELD_TYPE } from "../constants"; +import { + submitCardFields, + getCardFieldState, + getFieldErrors, + isEmpty, +} from "../interface"; +import { getCardProps, type CardProps } from "../props"; +import type { SetupCardOptions } from "../types"; +import type { FeatureFlags } from "../../types"; +import { setupCardLogger } from "../logger"; +import { loadFraudnet } from "../../api"; + +import { + CardField, + CardNumberField, + CardCVVField, + CardExpiryField, + CardNameField, + CardPostalCodeField, +} from "./fields"; type PageProps = {| - cspNonce : string, - props : CardProps, - featureFlags: FeatureFlags, - experiments: {| - hostedCardFields: boolean - |} + cspNonce: string, + props: CardProps, + featureFlags: FeatureFlags, + experiments: {| + hostedCardFields: boolean, + useIDToken: boolean, + |}, |}; -function Page({ cspNonce, props, featureFlags, experiments } : PageProps) : mixed { - const { facilitatorAccessToken, style, disableAutocomplete, placeholder, type, export: xport, inputEvents, minLength, maxLength } = props; - const { onChange, onFocus, onBlur, onInputSubmitRequest } = inputEvents || {}; - const [ fieldValue, setFieldValue ] = useState(); - const [ fieldValid, setFieldValid ] = useState(false); - const [ fieldPotentiallyValid, setFieldPotentiallyValid] = useState(true); - const [ cardTypes, setCardTypes ] = useState([]); - const [ fieldFocus, setFieldFocus ] = useState(false); - const [ inputSubmit, setInputSubmit ] = useState(false); - const [ mainRef, setRef ] = useState(); - const [ fieldGQLErrors, setFieldGQLErrors ] = useState({ singleField: {}, numberField: [], expiryField: [], cvvField: [], nameField: [], postalCodeField: [] }); - const initialRender = useRef(true) - - let autocomplete; - if (disableAutocomplete) { - autocomplete = 'off'; +function Page({ + cspNonce, + props, + featureFlags, + experiments, +}: PageProps): mixed { + const { + facilitatorAccessToken, + style, + disableAutocomplete, + placeholder, + type, + export: xport, + inputEvents, + minLength, + maxLength, + } = props; + const { onChange, onFocus, onBlur, onInputSubmitRequest } = inputEvents || {}; + const [fieldValue, setFieldValue] = useState(); + const [fieldValid, setFieldValid] = useState(false); + const [fieldPotentiallyValid, setFieldPotentiallyValid] = useState(true); + const [cardTypes, setCardTypes] = useState([]); + const [fieldFocus, setFieldFocus] = useState(false); + const [inputSubmit, setInputSubmit] = useState(false); + const [mainRef, setRef] = useState(); + const [fieldGQLErrors, setFieldGQLErrors] = useState({ + singleField: {}, + numberField: [], + expiryField: [], + cvvField: [], + nameField: [], + postalCodeField: [], + }); + const initialRender = useRef(true); + + let autocomplete; + if (disableAutocomplete) { + autocomplete = "off"; + } + + const getFieldValue = () => { + return fieldValue; + }; + + const isFieldValid = () => { + return fieldValid; + }; + + const isFieldPotentiallyValid = () => { + return fieldPotentiallyValid; + }; + + const isFieldFocused = () => { + return fieldFocus; + }; + + const getPotentialCardTypes = () => { + return cardTypes; + }; + + const setGqlErrors = (errorData: {| field: string, errors: [] |}) => { + const { errors } = errorData; + + const errorObject = { ...fieldGQLErrors }; + + if (type === CARD_FIELD_TYPE.SINGLE) { + errorObject.singleField = { ...errorData }; + } else if (errors && errors.length) { + switch (type) { + case CARD_FIELD_TYPE.NUMBER: + errorObject.numberField = [...errors]; + break; + case CARD_FIELD_TYPE.EXPIRY: + errorObject.expiryField = [...errors]; + break; + case CARD_FIELD_TYPE.CVV: + errorObject.cvvField = [...errors]; + break; + case CARD_FIELD_TYPE.NAME: + errorObject.nameField = [...errors]; + break; + case CARD_FIELD_TYPE.POSTAL: + errorObject.postalCodeField = [...errors]; + break; + default: + break; + } } - const getFieldValue = () => { - return fieldValue; - }; - - const isFieldValid = () => { - return fieldValid; + setFieldGQLErrors(errorObject); + }; + + const resetGQLErrors = () => { + setFieldGQLErrors({ + singleField: {}, + numberField: [], + expiryField: [], + cvvField: [], + nameField: [], + postalCodeField: [], + }); + }; + + const getStateObject = () => { + const { cards, fields } = getCardFieldState(); + const currentField = kebabToCamelCase(CARD_FIELD_TYPE_TO_FRAME_NAME[type]); + let potentialCardTypes; + fields[currentField] = { + isEmpty: isEmpty(fieldValue), + isFocused: fieldFocus, + isPotentiallyValid: fieldPotentiallyValid, + isValid: fieldValid, }; - - const isFieldPotentiallyValid = () => { - return fieldPotentiallyValid + if (currentField === "cardNumberField") { + potentialCardTypes = parsedCardType(cardTypes); + } else { + potentialCardTypes = cards; } - - const isFieldFocused = () => { - return fieldFocus; + return { fields, potentialCardTypes }; + }; + + useEffect(() => { + // useEffect is fired on first render as well as when + // any value in the depenency array has changed. We + // only want to fire off the onChange event if the + // validity changes after the first render. So in + // order to do that we add this guard to not noop + // when the component first renders. We leverage + // useRef to store the value of initialRender as + // we want that to persist across re-renders. + // See: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables + if (initialRender.current && fieldValue === "") { + initialRender.current = false; + } else if (!initialRender.current && typeof onChange === "function") { + const { fields, potentialCardTypes } = getStateObject(); + const errors = getFieldErrors(fields); + onChange({ + fields, + cards: potentialCardTypes, + emittedBy: type, + isFormValid: errors.length === 0, + errors, + }); } - - const getPotentialCardTypes = () => { - return cardTypes + }, [fieldValue]); + useEffect(() => { + if (initialRender.current && fieldValue === "") { + initialRender.current = false; + } else if (!initialRender.current && typeof onFocus === "function") { + const { fields, potentialCardTypes } = getStateObject(); + const errors = getFieldErrors(fields); + const fieldStateObject = { + fields, + cards: potentialCardTypes, + emittedBy: type, + isFormValid: errors.length === 0, + errors, + }; + + if (fieldFocus) { + onFocus({ ...fieldStateObject }); + } else if (typeof onBlur === "function" && !fieldFocus) { + onBlur({ ...fieldStateObject }); + } } - - const setGqlErrors = (errorData : {| field : string, errors : [] |}) => { - const { errors } = errorData; - - const errorObject = { ...fieldGQLErrors }; - - if (type === CARD_FIELD_TYPE.SINGLE) { - errorObject.singleField = { ...errorData }; - } else if (errors && errors.length) { - switch (type) { - case CARD_FIELD_TYPE.NUMBER: - errorObject.numberField = [ ...errors ]; - break; - case CARD_FIELD_TYPE.EXPIRY: - errorObject.expiryField = [ ...errors ]; - break; - case CARD_FIELD_TYPE.CVV: - errorObject.cvvField = [ ...errors ]; - break; - case CARD_FIELD_TYPE.NAME: - errorObject.nameField = [ ...errors ]; - break; - case CARD_FIELD_TYPE.POSTAL: - errorObject.postalCodeField = [ ...errors ]; - break; - default: - break; - } - } - - setFieldGQLErrors(errorObject); - }; - - const resetGQLErrors = () => { - setFieldGQLErrors({ singleField: {}, numberField: [], expiryField: [], cvvField: [], nameField: [], postalCodeField: [] }); - }; - - const getStateObject = () => { - const { cards, fields } = getCardFieldState() - const currentField = kebabToCamelCase(CARD_FIELD_TYPE_TO_FRAME_NAME[type]) - let potentialCardTypes - fields[currentField] = { - isEmpty: isEmpty(fieldValue), - isFocused: fieldFocus, - isPotentiallyValid: fieldPotentiallyValid, - isValid: fieldValid - } - if (currentField === 'cardNumberField') { - potentialCardTypes = parsedCardType(cardTypes) - } else { - potentialCardTypes = cards - } - return { fields, potentialCardTypes } + }, [fieldFocus]); + + // fire the handler when key code is 13 + // + useEffect(() => { + if (inputSubmit && typeof onInputSubmitRequest === "function") { + const { fields, potentialCardTypes } = getStateObject(); + const errors = getFieldErrors(fields); + const fieldStateObject = { + fields, + cards: potentialCardTypes, + emittedBy: type, + isFormValid: errors.length === 0, + errors, + }; + + onInputSubmitRequest({ ...fieldStateObject }); + setInputSubmit(false); } + }, [inputSubmit]); + + useEffect(() => { + autoFocusOnFirstInput(mainRef); + }, [mainRef]); + + useEffect(() => { + setupExports({ + name: CARD_FIELD_TYPE_TO_FRAME_NAME[type], + isFieldPotentiallyValid, + getPotentialCardTypes, + isFieldValid, + isFieldFocused, + getFieldValue, + setGqlErrors, + resetGQLErrors, + }); - useEffect(() => { - // useEffect is fired on first render as well as when - // any value in the depenency array has changed. We - // only want to fire off the onChange event if the - // validity changes after the first render. So in - // order to do that we add this guard to not noop - // when the component first renders. We leverage - // useRef to store the value of initialRender as - // we want that to persist across re-renders. - // See: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables - if ( initialRender.current && fieldValue === '') { - initialRender.current = false - } else if( !initialRender.current && typeof onChange === 'function' ) { - const {fields, potentialCardTypes} = getStateObject(); - const errors = getFieldErrors(fields) - onChange({ - fields, - cards: potentialCardTypes, - emittedBy: type, - isFormValid: errors.length === 0, - errors - }); - } - }, [ fieldValue ]); - useEffect(() => { - if ( initialRender.current && fieldValue === '') { - initialRender.current = false - } else if(!initialRender.current && typeof onFocus === 'function'){ - const {fields, potentialCardTypes} = getStateObject(); - const errors = getFieldErrors(fields) - const fieldStateObject = { - fields, - cards: potentialCardTypes, - emittedBy: type, - isFormValid: errors.length === 0, - errors - } - - if(fieldFocus) { - onFocus({...fieldStateObject}); - } else if(typeof onBlur === 'function' && !fieldFocus) { - onBlur({...fieldStateObject}) - } - } - },[fieldFocus]) - - // fire the handler when key code is 13 - // - useEffect(() => { - if(inputSubmit && typeof onInputSubmitRequest === 'function') { - const {fields, potentialCardTypes} = getStateObject(); - const errors = getFieldErrors(fields) - const fieldStateObject = { - fields, - cards: potentialCardTypes, - emittedBy: type, - isFormValid: errors.length === 0, - errors - } - - onInputSubmitRequest({...fieldStateObject}) - setInputSubmit(false) - } - - }, [inputSubmit]) - - - useEffect(() => { - autoFocusOnFirstInput(mainRef); - }, [ mainRef ]); - - useEffect(() => { - setupExports({ - name: CARD_FIELD_TYPE_TO_FRAME_NAME[type], - isFieldPotentiallyValid, - getPotentialCardTypes, - isFieldValid, - isFieldFocused, - getFieldValue, - setGqlErrors, - resetGQLErrors - }); - - xport({ - submit: (extraData) => { - const extraFields = filterExtraFields(extraData); - return submitCardFields({ facilitatorAccessToken, extraFields, featureFlags, experiments }); - }, - getState: () => { - const cardFieldState = getCardFieldState() - const { fields } = cardFieldState - const errors = getFieldErrors(fields) - - return {...cardFieldState, - isFormValid: errors.length === 0, - errors} - } + xport({ + submit: (extraData) => { + const extraFields = filterExtraFields(extraData); + return submitCardFields({ + facilitatorAccessToken, + extraFields, + featureFlags, + experiments, }); - }, [ fieldValid, fieldValue, fieldFocus, fieldPotentiallyValid, cardTypes ]); - - const onFieldChange = ({ value, valid, isFocused, potentiallyValid, potentialCardTypes }) => { - setFieldValue(value); - setFieldFocus(isFocused) - setFieldValid(valid); - setFieldPotentiallyValid(potentiallyValid); - resetGQLErrors(); - setCardTypes(potentialCardTypes); - }; - - const onFieldFocus = ({isFocused}) => { - setFieldFocus(isFocused) - } - - const onInputSubmit = ({isInputSubmitRequest}) => { - setInputSubmit(isInputSubmitRequest) - } - - return ( - - { - (type === CARD_FIELD_TYPE.SINGLE) - ? setRef(ref.current.base) } - /> : null - } - - { - (type === CARD_FIELD_TYPE.NUMBER) - ? setRef(ref.current.base) } - /> : null - } - - { - (type === CARD_FIELD_TYPE.CVV) - ? setRef(ref.current.base) } - /> : null - } - - { - (type === CARD_FIELD_TYPE.EXPIRY) - ? setRef(ref.current.base) } - /> : null - } - - { - (type === CARD_FIELD_TYPE.NAME) - ? setRef(ref.current.base) } - /> : null - } - - { - (type === CARD_FIELD_TYPE.POSTAL) - ? setRef(ref.current.base) } - /> : null - } - - ); + }, + getState: () => { + const cardFieldState = getCardFieldState(); + const { fields } = cardFieldState; + const errors = getFieldErrors(fields); + + return { ...cardFieldState, isFormValid: errors.length === 0, errors }; + }, + }); + }, [fieldValid, fieldValue, fieldFocus, fieldPotentiallyValid, cardTypes]); + + const onFieldChange = ({ + value, + valid, + isFocused, + potentiallyValid, + potentialCardTypes, + }) => { + setFieldValue(value); + setFieldFocus(isFocused); + setFieldValid(valid); + setFieldPotentiallyValid(potentiallyValid); + resetGQLErrors(); + setCardTypes(potentialCardTypes); + }; + + const onFieldFocus = ({ isFocused }) => { + setFieldFocus(isFocused); + }; + + const onInputSubmit = ({ isInputSubmitRequest }) => { + setInputSubmit(isInputSubmitRequest); + }; + + return ( + + {type === CARD_FIELD_TYPE.SINGLE ? ( + setRef(ref.current.base)} + /> + ) : null} + + {type === CARD_FIELD_TYPE.NUMBER ? ( + setRef(ref.current.base)} + /> + ) : null} + + {type === CARD_FIELD_TYPE.CVV ? ( + setRef(ref.current.base)} + /> + ) : null} + + {type === CARD_FIELD_TYPE.EXPIRY ? ( + setRef(ref.current.base)} + /> + ) : null} + + {type === CARD_FIELD_TYPE.NAME ? ( + setRef(ref.current.base)} + /> + ) : null} + + {type === CARD_FIELD_TYPE.POSTAL ? ( + setRef(ref.current.base)} + /> + ) : null} + + ); } -export function setupCard({ cspNonce, facilitatorAccessToken, featureFlags, experiments, buyerCountry, metadata } : SetupCardOptions) { - const props = getCardProps({ - facilitatorAccessToken, - featureFlags, - experiments, +export function setupCard({ + cspNonce, + facilitatorAccessToken, + featureFlags, + experiments, + buyerCountry, + metadata, +}: SetupCardOptions) { + const props = getCardProps({ + facilitatorAccessToken, + featureFlags, + experiments, + }); + + const { + env, + sessionID, + clientID, + partnerAttributionID, + sdkCorrelationID, + locale, + merchantID, + merchantDomain, + cardSessionID, + type, + hcfSessionID, + clientMetadataID, + } = props; + + setupCardLogger({ + env, + sessionID, + cardSessionID, + clientID, + partnerAttributionID, + sdkCorrelationID, + cardCorrelationID: metadata?.correlationID, + locale, + merchantID, + merchantDomain, + buyerCountry, + type, + hcfSessionID, + productAction: props.productAction, + }); + + loadFraudnet({ env, clientMetadataID, cspNonce }) + .catch(noop) + .then(() => { + render( + , + getBody(), + ); }); - - const { - env, - sessionID, - clientID, - partnerAttributionID, - sdkCorrelationID, - locale, - merchantID, - merchantDomain, - cardSessionID, - type, - hcfSessionID - } = props; - - setupCardLogger({ - env, - sessionID, - cardSessionID, - clientID, - partnerAttributionID, - sdkCorrelationID, - cardCorrelationID: metadata?.correlationID, - locale, - merchantID, - merchantDomain, - buyerCountry, - type, - hcfSessionID, - productAction: props.productAction - }) - - render(, getBody()); } diff --git a/src/card/components/page.test.js b/src/card/components/page.test.js new file mode 100644 index 0000000000..27445f16f0 --- /dev/null +++ b/src/card/components/page.test.js @@ -0,0 +1,109 @@ +/* @flow */ +import { describe, test, expect, vi } from "vitest"; + +import { loadFraudnet } from "../../api"; +import { getCardProps } from "../props"; + +import { setupCard } from "./page"; + +window.xprops = { + createOrder: vi.fn(), + clientMetadataID: "test-id", + env: "local", + xport: vi.fn(), + locale: { + country: "US", + lang: "en", + }, +}; + +const mockSetupCardOptions = { + cspNonce: "nonce", + facilitatorAccessToken: "token", + featureFlags: {}, + buyerCountry: "US", + metadata: { + correlationID: "ABCXYZ", + spbVersion: "v3", + }, + experiments: { + hostedCardFields: true, + useIDToken: true, + }, +}; + +vi.mock("../logger", () => ({ + setupCardLogger: vi.fn().mockResolvedValue(), +})); + +vi.mock("../props", () => { + return { + getCardProps: vi.fn(() => { + return { + env: "local", + clientMetadataID: "test-id", + cspNonce: mockSetupCardOptions.cspNonce, + xport: vi.fn(), + }; + }), + }; +}); + +vi.mock("../../api", () => ({ + // $FlowIssue jest mock + loadFraudnet: vi.fn().mockResolvedValue(), +})); + +describe.skip("setupCard", () => { + test("renders the Page component with the correct props", async () => { + const getBodyMock = vi.fn(); + getBodyMock.mockReturnValue(document.createElement("div")); + + await setupCard(mockSetupCardOptions); + + /* Add assertion for render*/ + }); + + test("should load fraudnet before render", async () => { + await setupCard(mockSetupCardOptions); + + expect(getCardProps).toHaveBeenCalledWith({ + facilitatorAccessToken: "token", + featureFlags: {}, + experiments: { + hostedCardFields: true, + }, + }); + + expect(loadFraudnet).toBeCalledWith({ + env: "local", + clientMetadataID: "test-id", + cspNonce: mockSetupCardOptions.cspNonce, + }); + + /* Add assertion for render*/ + }); + test("calls loadFraudnet and renders even if loadFraudnet fails", async () => { + // $FlowIssue jest mock + loadFraudnet.mockRejectedValueOnce(new Error("Fake error")); + const getBodyMock = vi.fn(); + getBodyMock.mockReturnValue(document.createElement("div")); + + await setupCard(mockSetupCardOptions); + + expect(loadFraudnet).toBeCalledTimes(1); + expect(loadFraudnet).toBeCalledWith({ + env: "local", + clientMetadataID: "test-id", + cspNonce: "nonce", + }); + expect(getCardProps).toHaveBeenCalledWith({ + facilitatorAccessToken: "token", + featureFlags: {}, + experiments: { + hostedCardFields: true, + }, + }); + /* Add assertion for render*/ + }); +}); diff --git a/src/card/constants.js b/src/card/constants.js index 2035ee454c..4d9e3dcebc 100644 --- a/src/card/constants.js +++ b/src/card/constants.js @@ -1,318 +1,329 @@ /* @flow */ -import cardValidator from 'card-validator'; -import { CARD } from '@paypal/sdk-constants/src'; +import cardValidator from "card-validator"; +import { CARD } from "@paypal/sdk-constants/src"; -import { FRAME_NAME } from '../constants'; +import { FRAME_NAME } from "../constants"; -import type { FieldStyle, CardType, CardPlaceholder } from './types'; +import type { FieldStyle, CardType, CardPlaceholder } from "./types"; const { types } = cardValidator.creditCardType; export const CARD_FIELD_TYPE = { - SINGLE: 'single', - NUMBER: 'number', - CVV: 'cvv', - EXPIRY: 'expiry', - NAME: 'name', - POSTAL: 'postal' + SINGLE: "single", + NUMBER: "number", + CVV: "cvv", + EXPIRY: "expiry", + NAME: "name", + POSTAL: "postal", }; export const GQL_ERRORS = { - '/payment_source/card/number': { - 'VALIDATION_ERROR': ('INVALID_NUMBER' : 'INVALID_NUMBER'), - 'MISSING_REQUIRED_PARAMETER': ('MISSING_NUMBER' : 'MISSING_NUMBER') - }, - '/payment_source/card/expiry': { - 'INVALID_PARAMETER_SYNTAX': ('INVALID_EXPIRATION_DATE_FORMAT' : 'INVALID_EXPIRATION_DATE_FORMAT'), - 'INVALID_STRING_LENGTH': ('INVALID_EXPIRATION_DATE_LENGTH' : 'INVALID_EXPIRATION_DATE_LENGTH'), - 'CARD_EXPIRED': ('CARD_EXPIRED' : 'CARD_EXPIRED'), - 'MISSING_REQUIRED_PARAMETER': ('MISSING_EXPIRATION_DATE' : 'MISSING_EXPIRATION_DATE') - }, - '/payment_source/card/security_code': { - 'VALIDATION_ERROR': ('INVALID_SECURITY_CODE' : 'INVALID_SECURITY_CODE') - }, - 'TRANSACTION_REFUSED': ('TRANSACTION_REJECTED' : 'TRANSACTION_REJECTED') + "/payment_source/card/number": { + VALIDATION_ERROR: ("INVALID_NUMBER": "INVALID_NUMBER"), + MISSING_REQUIRED_PARAMETER: ("MISSING_NUMBER": "MISSING_NUMBER"), + }, + "/payment_source/card/expiry": { + INVALID_PARAMETER_SYNTAX: + ("INVALID_EXPIRATION_DATE_FORMAT": "INVALID_EXPIRATION_DATE_FORMAT"), + INVALID_STRING_LENGTH: + ("INVALID_EXPIRATION_DATE_LENGTH": "INVALID_EXPIRATION_DATE_LENGTH"), + CARD_EXPIRED: ("CARD_EXPIRED": "CARD_EXPIRED"), + MISSING_REQUIRED_PARAMETER: + ("MISSING_EXPIRATION_DATE": "MISSING_EXPIRATION_DATE"), + }, + "/payment_source/card/security_code": { + VALIDATION_ERROR: ("INVALID_SECURITY_CODE": "INVALID_SECURITY_CODE"), + }, + TRANSACTION_REFUSED: ("TRANSACTION_REJECTED": "TRANSACTION_REJECTED"), }; export const CARD_ERRORS = { - INELIGIBLE_CARD_VENDOR: ('INELIGIBLE_CARD_VENDOR': 'INELIGIBLE_CARD_VENDOR'), - INVALID_NUMBER: ('INVALID_NUMBER' : 'INVALID_NUMBER'), - INVALID_EXPIRY: ('INVALID_EXPIRY' : 'INVALID_EXPIRY'), - INVALID_CVV: ('INVALID_CVV' : 'INVALID_CVV'), - INVALID_NAME: ('INVALID_NAME' : 'INVALID_NAME'), - INVALID_POSTAL: ('INVALID_POSTAL' : 'INVALID_POSTAL') + INELIGIBLE_CARD_VENDOR: ("INELIGIBLE_CARD_VENDOR": "INELIGIBLE_CARD_VENDOR"), + INVALID_NUMBER: ("INVALID_NUMBER": "INVALID_NUMBER"), + INVALID_EXPIRY: ("INVALID_EXPIRY": "INVALID_EXPIRY"), + INVALID_CVV: ("INVALID_CVV": "INVALID_CVV"), + INVALID_NAME: ("INVALID_NAME": "INVALID_NAME"), + INVALID_POSTAL: ("INVALID_POSTAL": "INVALID_POSTAL"), }; export const SUBMIT_ERRORS = { - UNABLE_TO_SUBMIT: ('Card fields not available to submit' : 'Card fields not available to submit'), - ORDER_ID_TYPE_ERROR: ('Expected createOrder to return a promise that resolves with the order ID as a string' : 'Expected createOrder to return a promise that resolves with the order ID as a string'), - VAULT_TOKEN_TYPE_ERROR: ('Expected createVaultSetupToken to return a promise that resolves with vaultSetupToken as a string' : 'Expected createVaultSetupToken to return a promise that resolves with vaultSetupToken as a string'), - PASSING_BOTH_FUNCTIONS: ('Cannot pass both createVaultSetupToken and createOrder' : 'Cannot pass both createVaultSetupToken and createOrder'), - MISSING_BOTH_FUNCTIONS: ('Must pass either createVaultSetupToken or createOrder' : 'Must pass either createVaultSetupToken or createOrder'), - MISSING_ONAPPROVE: ('onApprove is required when saving card fields' : 'onApprove is required when saving card fields'), - MISSING_CREATE_VAULT_SETUP: ('createVaultSetupToken is required when saving card fields' : 'createVaultSetupToken is required when saving card fields'), - NOT_FEATURE_FLAGGED: ('Not feature flagged to use CardFields' : 'Not feature flagged to use CardFields') -} + UNABLE_TO_SUBMIT: + ("Card fields not available to submit": "Card fields not available to submit"), + ORDER_ID_TYPE_ERROR: + ("Expected createOrder to return a promise that resolves with the order ID as a string": "Expected createOrder to return a promise that resolves with the order ID as a string"), + VAULT_TOKEN_TYPE_ERROR: + ("Expected createVaultSetupToken to return a promise that resolves with vaultSetupToken as a string": "Expected createVaultSetupToken to return a promise that resolves with vaultSetupToken as a string"), + PASSING_BOTH_FUNCTIONS: + ("Cannot pass both createVaultSetupToken and createOrder": "Cannot pass both createVaultSetupToken and createOrder"), + MISSING_BOTH_FUNCTIONS: + ("Must pass either createVaultSetupToken or createOrder": "Must pass either createVaultSetupToken or createOrder"), + MISSING_ONAPPROVE: + ("onApprove is required when saving card fields": "onApprove is required when saving card fields"), + MISSING_CREATE_VAULT_SETUP: + ("createVaultSetupToken is required when saving card fields": "createVaultSetupToken is required when saving card fields"), + NOT_FEATURE_FLAGGED: + ("Not feature flagged to use CardFields": "Not feature flagged to use CardFields"), +}; -export const CARD_FIELD_TYPE_TO_FRAME_NAME : {| [$Values] : $Values |} = { - [ CARD_FIELD_TYPE.SINGLE ]: FRAME_NAME.CARD_FIELD, - [ CARD_FIELD_TYPE.NUMBER ]: FRAME_NAME.CARD_NUMBER_FIELD, - [ CARD_FIELD_TYPE.CVV ]: FRAME_NAME.CARD_CVV_FIELD, - [ CARD_FIELD_TYPE.EXPIRY ]: FRAME_NAME.CARD_EXPIRY_FIELD, - [ CARD_FIELD_TYPE.NAME ]: FRAME_NAME.CARD_NAME_FIELD, - [ CARD_FIELD_TYPE.POSTAL ]: FRAME_NAME.CARD_POSTAL_FIELD +export const CARD_FIELD_TYPE_TO_FRAME_NAME: {| + [$Values]: $Values, +|} = { + [CARD_FIELD_TYPE.SINGLE]: FRAME_NAME.CARD_FIELD, + [CARD_FIELD_TYPE.NUMBER]: FRAME_NAME.CARD_NUMBER_FIELD, + [CARD_FIELD_TYPE.CVV]: FRAME_NAME.CARD_CVV_FIELD, + [CARD_FIELD_TYPE.EXPIRY]: FRAME_NAME.CARD_EXPIRY_FIELD, + [CARD_FIELD_TYPE.NAME]: FRAME_NAME.CARD_NAME_FIELD, + [CARD_FIELD_TYPE.POSTAL]: FRAME_NAME.CARD_POSTAL_FIELD, }; -export const OPTIONAL_CARD_FIELDS: $ReadOnlyArray = ['name']; +export const OPTIONAL_CARD_FIELDS: $ReadOnlyArray = ["name"]; -export const FIELD_STYLE : FieldStyle = { - appearance: 'appearance', - color: 'color', - direction: 'direction', - font: 'font', - fontFamily: 'font-family', - fontSizeAdjust: 'font-size-adjust', - fontSize: 'font-size', - fontStretch: 'font-stretch', - fontStyle: 'font-style', - fontVariantAlternates: 'font-variant-alternates', - fontVariantCaps: 'font-variant-caps', - fontVariantEastAsian: 'font-variant-east-asian', - fontVariantLigatures: 'font-variant-ligatures', - fontVariantNumeric: 'font-variant-numeric', - fontVariant: 'font-variant', - fontWeight: 'font-weight', - letterSpacing: 'letter-spacing', - lineHeight: 'line-height', - opacity: 'opacity', - outline: 'outline', - padding: 'padding', - paddingTop: 'padding-top', - paddingRight: 'padding-right', - paddingBottom: 'padding-bottom', - paddingLeft: 'padding-left', - textShadow: 'text-shadow', - transition: 'transition', - MozApperance: '-moz-appearance', - MozOsxFontSmoothing: '-moz-osx-font-smoothing', - MozTapHighlightColor: '-moz-tap-highlight-color', - MozTransition: '-moz-transition', - WebkitAppearance: '-webkit-appearance', - WebkitOsxFontSmoothing: '-webkit-osx-font-smoothing', - WebkitTapHighlightColor: '-webkit-tap-highlight-color', - WebkitTransition: '-webkit-transition' +export const FIELD_STYLE: FieldStyle = { + appearance: "appearance", + color: "color", + direction: "direction", + font: "font", + fontFamily: "font-family", + fontSizeAdjust: "font-size-adjust", + fontSize: "font-size", + fontStretch: "font-stretch", + fontStyle: "font-style", + fontVariantAlternates: "font-variant-alternates", + fontVariantCaps: "font-variant-caps", + fontVariantEastAsian: "font-variant-east-asian", + fontVariantLigatures: "font-variant-ligatures", + fontVariantNumeric: "font-variant-numeric", + fontVariant: "font-variant", + fontWeight: "font-weight", + letterSpacing: "letter-spacing", + lineHeight: "line-height", + opacity: "opacity", + outline: "outline", + padding: "padding", + paddingTop: "padding-top", + paddingRight: "padding-right", + paddingBottom: "padding-bottom", + paddingLeft: "padding-left", + textShadow: "text-shadow", + transition: "transition", + MozApperance: "-moz-appearance", + MozOsxFontSmoothing: "-moz-osx-font-smoothing", + MozTapHighlightColor: "-moz-tap-highlight-color", + MozTransition: "-moz-transition", + WebkitAppearance: "-webkit-appearance", + WebkitOsxFontSmoothing: "-webkit-osx-font-smoothing", + WebkitTapHighlightColor: "-webkit-tap-highlight-color", + WebkitTransition: "-webkit-transition", }; // from https://github.com/braintree/inject-stylesheet/blob/main/src/lib/filter-style-values.ts -export const FILTER_CSS_VALUES : $ReadOnlyArray = [ - // prevent injecting additional rules - /;/, - // prevent injecting script tags - /[<>]/, - // prevent hexadecimal characters - // (could allow an exploiter to get around the url/expression/javascript rules) - /\\/, - /@import/i, - /expression/i, - /javascript/i, - /url/i +export const FILTER_CSS_VALUES: $ReadOnlyArray = [ + // prevent injecting additional rules + /;/, + // prevent injecting script tags + /[<>]/, + // prevent hexadecimal characters + // (could allow an exploiter to get around the url/expression/javascript rules) + /\\/, + /@import/i, + /expression/i, + /javascript/i, + /url/i, ]; // from https://github.com/braintree/inject-stylesheet/blob/main/src/lib/validate-selector.ts -export const FILTER_CSS_SELECTORS : $ReadOnlyArray = [ - /^\s*$/, - /supports/i, - /import/i, - /[{}]/, - / = [ + /^\s*$/, + /supports/i, + /import/i, + /[{}]/, + / svg': { - 'color': '#d9360b', - 'width': '24px', - 'height': '24px', - 'margin-right': '0.25rem' - }, - '.card-field-validation-error.hidden': { - 'visibility': 'hidden' - } - + input: { + background: "transparent", + border: "none", + "border-radius": "unset", + "box-sizing": "content-box", + margin: "0", + }, + "input, input:focus": { + border: "none", + "box-shadow": "none", + outline: "none", + }, + "input.invalid": { + border: "none", + "box-shadow": "none", + }, + "input.card-field-number": { + flex: "1", + "min-width": "4ch", + "padding-right": "0.375rem", + }, + "input.card-field-expiry": { + "padding-left": "0.375rem", + "padding-right": "0.375rem", + "text-align": "center", + width: "7ch", + }, + "input.card-field-cvv": { + "padding-left": "0.375rem", + "text-align": "center", + width: "4ch", + }, + ".card-field-validation-error": { + "align-items": "center", + color: "#515354", + display: "flex", + "font-size": "0.875rem", + "margin-top": "0.375rem", + }, + ".card-field-validation-error > svg": { + color: "#d9360b", + width: "24px", + height: "24px", + "margin-right": "0.25rem", + }, + ".card-field-validation-error.hidden": { + visibility: "hidden", + }, }; -export const DEFAULT_PLACEHOLDERS : CardPlaceholder = { - number: 'Card number', - expiry: 'MM / YY', - cvv: 'CVV', - name: 'Cardholder Name (optional)', - postal: 'Postal code' +export const DEFAULT_PLACEHOLDERS: CardPlaceholder = { + number: "Card number", + expiry: "MM / YY", + cvv: "CVV", + name: "Cardholder Name (optional)", + postal: "Postal code", }; -export const VALID_EXTRA_FIELDS = [ - 'billingAddress' -]; +export const VALID_EXTRA_FIELDS = ["billingAddress"]; export const ALLOWED_ATTRIBUTES = [ - "aria-invalid", - "aria-required", - "disabled", - "placeholder", + "aria-invalid", + "aria-required", + "disabled", + "placeholder", ]; export const DEFAULT_EXPIRY_PATTERN = "{{99}} / {{9999}}"; @@ -326,6 +337,6 @@ export const FPTI_HCF_KEYS = { HCF_VERSION: ("hcf_version": "hcf_version"), SDK_CORRELATION_ID: ("sdk_correlation_id": "sdk_correlation_id"), VAULT_TOKEN: ("vault_token": "vault_token"), - HCF_ORDER_ID: ("order_id" : "order_id"), - THREEDS_AUTH_STATUS: ("3ds_auth_status" : "3ds_auth_status") -} + HCF_ORDER_ID: ("order_id": "order_id"), + THREEDS_AUTH_STATUS: ("3ds_auth_status": "3ds_auth_status"), +}; diff --git a/src/card/docs/Initialization/README.md b/src/card/docs/Initialization/README.md index c99f5f6cf6..ab19448890 100644 --- a/src/card/docs/Initialization/README.md +++ b/src/card/docs/Initialization/README.md @@ -2,15 +2,14 @@ ## Script Tag -* Load the SDK from `paypal.com/sdk/js?client-id=xyz` -* This provides the `window.paypal` namespace - +- Load the SDK from `paypal.com/sdk/js?client-id=xyz` +- This provides the `window.paypal` namespace ```html ``` @@ -20,8 +19,9 @@ Initialization Parameters can be passed via the script url query, and/or via dat ```html + src="https://www.paypal.com/sdk/js?client-id=test&components=card-fields" + data-user-id-token="xyz" +> ``` - **URL Query Paramers** shall be used where: @@ -164,7 +164,10 @@ Use a different global namespace on the page to export the PayPal SDK. Example: ```html - + + ``` ##### data-user-id-token @@ -197,7 +203,10 @@ Used to pass buyer identity through the SDK. Requires id-token in JWT format. Ca Example: ```html - + ``` ##### data-page-type @@ -216,7 +225,10 @@ Identify the page type the SDK is loaded on, for tracking purposes. Example: ```html - + ``` ##### data-partner-attribution-id @@ -229,7 +241,10 @@ Used to attribute transactions to a particular partner account. Example: ```html - + ``` ##### data-client-metadata-id @@ -242,7 +257,10 @@ Used for risk tracking. Unique per transaction Example: ```html - + ``` ##### data-enable-3ds @@ -262,12 +280,12 @@ npm install @paypal/paypal-js import { loadScript } from "paypal"; const configuration = { - clientID: '', + clientID: "", }; try { - await loadScript(configuration) -} catch(error) { + await loadScript(configuration); +} catch (error) { console.error(error); } ``` diff --git a/src/card/docs/Initialization/support/README.md b/src/card/docs/Initialization/support/README.md index c6ca3f8efa..3f12d8a498 100644 --- a/src/card/docs/Initialization/support/README.md +++ b/src/card/docs/Initialization/support/README.md @@ -4,4 +4,4 @@ - [Languages](./languages.md) - [Currencies](./currencies.md) - [Funding Sources](./funding-sources.md) -- [Card Types](./card-types.md) \ No newline at end of file +- [Card Types](./card-types.md) diff --git a/src/card/docs/Initialization/support/card-types.md b/src/card/docs/Initialization/support/card-types.md index 91fe1e0e30..17928583b4 100644 --- a/src/card/docs/Initialization/support/card-types.md +++ b/src/card/docs/Initialization/support/card-types.md @@ -7,4 +7,4 @@ - `hiper` - `elo` - `jcb` -- `cup` \ No newline at end of file +- `cup` diff --git a/src/card/docs/Initialization/support/countries.md b/src/card/docs/Initialization/support/countries.md index 10864ebb01..fe2c1972df 100644 --- a/src/card/docs/Initialization/support/countries.md +++ b/src/card/docs/Initialization/support/countries.md @@ -202,4 +202,4 @@ - `YT` - `ZA` - `ZM` -- `ZW` \ No newline at end of file +- `ZW` diff --git a/src/card/docs/Initialization/support/currencies.md b/src/card/docs/Initialization/support/currencies.md index eb99892008..3a95892af5 100644 --- a/src/card/docs/Initialization/support/currencies.md +++ b/src/card/docs/Initialization/support/currencies.md @@ -101,4 +101,4 @@ - `WST` - `XAF` - `XCD` -- `YER` \ No newline at end of file +- `YER` diff --git a/src/card/docs/Initialization/support/funding-sources.md b/src/card/docs/Initialization/support/funding-sources.md index debd55835e..1a0933a51b 100644 --- a/src/card/docs/Initialization/support/funding-sources.md +++ b/src/card/docs/Initialization/support/funding-sources.md @@ -21,4 +21,4 @@ - `oxxo` - `boleto` - `wechatpay` -- `mercadopago` \ No newline at end of file +- `mercadopago` diff --git a/src/card/docs/Initialization/support/languages.md b/src/card/docs/Initialization/support/languages.md index 94dcef2c45..b395a40e2a 100644 --- a/src/card/docs/Initialization/support/languages.md +++ b/src/card/docs/Initialization/support/languages.md @@ -202,4 +202,4 @@ - `YT`: `en`, `fr`, `es`, `zh` - `ZA`: `en`, `fr`, `es`, `zh` - `ZM`: `en`, `fr`, `es`, `zh` -- `ZW`: `en` \ No newline at end of file +- `ZW`: `en` diff --git a/src/card/docs/MultiCardFields/README.md b/src/card/docs/MultiCardFields/README.md index af8cc9ebf7..e47921d461 100644 --- a/src/card/docs/MultiCardFields/README.md +++ b/src/card/docs/MultiCardFields/README.md @@ -1,21 +1,21 @@ # Multi Card Fields -* [Rendering](#rendering) -* [Styling](#styling) -* [Eligibility](#eligibility) -* [Input Events](#input-events) -* [Validation](#validation) -* [Methods](#methods) +- [Rendering](#rendering) +- [Styling](#styling) +- [Eligibility](#eligibility) +- [Input Events](#input-events) +- [Validation](#validation) +- [Methods](#methods) ### Rendering -Render the card fields component on your website, by creating an instance of paypal `CardFields` as below: +Render the card fields component on your website, by creating an instance of paypal `CardFields` as below: ```js const cardFields = paypal.CardFields({ - style, - createOrder, - onApprove + style, + createOrder, + onApprove, }); ``` @@ -37,20 +37,24 @@ This callback will be invoked whenever the user takes an action to submit the ca ```javascript const createOrder = (data, actions) => { - return fetch('/api/paypal/order', { - method: 'POST' - }).then(res => { - return res.json(); - }).then(json => { - return json.orderID; + return fetch("/api/paypal/order", { + method: "POST", + }) + .then((res) => { + return res.json(); + }) + .then((json) => { + return json.orderID; }); }; ``` Setup your server to invoke the [Creat Order API](https://developer.paypal.com/docs/api/orders/v2/#orders_create). The button pressed on the client side will determine the "payment_source" that is sent in the below sample which presumes that in this case it was "Card". -#### Request +#### Request + **Create Order with Card as a Payment Source** + ``` curl -v -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders -H "Content-Type: application/json" \ @@ -67,8 +71,10 @@ curl -v -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders ], } ``` + #### Response -Pass the order.id to the PayPal JS SDK and it will update the order with the number, cvv, expiry date entered in a way such that the PCI burden in taken on by PayPal. + +Pass the order.id to the PayPal JS SDK and it will update the order with the number, cvv, expiry date entered in a way such that the PCI burden in taken on by PayPal. ```json { @@ -122,15 +128,17 @@ Callback used to signal buyer approval of a purchase, e.g. ```js const onApprove = (data, actions) => { - return fetch('/api/paypal/order/capture', { - method: 'POST', - body: JSON.stringify({ - orderID: data.orderID - }) - }).then(res => { - return res.json(); - }).then(json => { - // Show a success page + return fetch("/api/paypal/order/capture", { + method: "POST", + body: JSON.stringify({ + orderID: data.orderID, + }), + }) + .then((res) => { + return res.json(); + }) + .then((json) => { + // Show a success page }); }; ``` @@ -152,11 +160,11 @@ curl -v -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders//c "id": "some_id", "status": "COMPLETED", "payment_source": { - "card": { - "brand": "VISA", - "last_digits": "1111", - "type": "CREDIT" - } + "card": { + "brand": "VISA", + "last_digits": "1111", + "type": "CREDIT" + } }, "purchase_units": [ { @@ -233,14 +241,17 @@ Render an optional name field. const cardNameContainer = document.getElementById("card-name-field-container"); const nameField = cardField.NameField(); -nameField.render(cardNameContainer); +nameField.render(cardNameContainer); ``` + #### Card Number Field Render a card number field. This field is required to capture a payment. ```js -const cardNumberContainer = document.getElementById("card-number-field-container"); +const cardNumberContainer = document.getElementById( + "card-number-field-container", +); const numberField = cardField.NumberField(); numberField.render(cardNumberContainer); @@ -251,7 +262,9 @@ numberField.render(cardNumberContainer); Render a card expiry date field. This field is required to capture a payment. ```js -const cardExpiryContainer = document.getElementById("card-expiry-field-container"); +const cardExpiryContainer = document.getElementById( + "card-expiry-field-container", +); const expiryField = cardField.ExpiryField(); expiryField.render(cardExpiryContainer); @@ -274,7 +287,7 @@ Each card field has a default placeholder text. You can override this text by pa ```js const nameField = cardField.NameField({ - placeholder: 'Enter your full name as it appears on your card' + placeholder: "Enter your full name as it appears on your card", }); ``` @@ -329,20 +342,22 @@ Style objects can be passed into the parent `CardFields` component to apply the ```js const cardStyle = { - 'input': { - 'font-size': '16px', - 'font-family': 'courier, monospace', - 'font-weight': 'lighter', - 'color': '#ccc', - }, - '.invalid': { - 'color': 'purple', - }, -} + input: { + "font-size": "16px", + "font-family": "courier, monospace", + "font-weight": "lighter", + color: "#ccc", + }, + ".invalid": { + color: "purple", + }, +}; -paypal.CardFields({ - style: cardStyle -}).render('#card-field-container'); +paypal + .CardFields({ + style: cardStyle, + }) + .render("#card-field-container"); ``` ##### Passing the style object to an individual field @@ -366,12 +381,14 @@ const nameField = cardField.NameField({ ##### Detect Eligibility ```js -const cardFields = paypal.CardFields({/* options */}); +const cardFields = paypal.CardFields({ + /* options */ +}); if (cardFields.isEligible()) { - cardFields.NumberField().render('#card-number-field-container'); - cardFields.CVVField().render('#card-cvv-field-container'); - cardFields.ExpiryField().render('#card-expiry-field-container'); + cardFields.NumberField().render("#card-number-field-container"); + cardFields.CVVField().render("#card-cvv-field-container"); + cardFields.ExpiryField().render("#card-expiry-field-container"); } ``` @@ -412,6 +429,7 @@ const cardField = paypal.CardFields({ } }) ``` + ##### Passing the `inputEvents` object into each individual field component ```js @@ -435,7 +453,7 @@ const nameField = cardField.NameField({ // inform buyer that some field(s) are not yet valid } } - } + } }); ``` @@ -482,33 +500,35 @@ data: { ##### Validate Individual Fields ```js -const cardFields = paypal.CardFields({/* options */}); +const cardFields = paypal.CardFields({ + /* options */ +}); -const cardContainer = document.getElementById("#card-number-field-container") +const cardContainer = document.getElementById("#card-number-field-container"); const cardNumberField = cardFields.NumberField({ - // add valid or invalid class when the validation changes on the field - inputEvents: { - - onChange: (data) => { - cardContainer.className = data.fields.cardNumberField.isValid ? 'valid' : 'invalid'; - } - } -}) - + // add valid or invalid class when the validation changes on the field + inputEvents: { + onChange: (data) => { + cardContainer.className = data.fields.cardNumberField.isValid + ? "valid" + : "invalid"; + }, + }, +}); ``` #### Validate Entire Card Form ```js -const formContainer = document.getElementById("form-container") +const formContainer = document.getElementById("form-container"); const cardFields = paypal.CardFields({ - inputEvents: { - onChange: (data) => { - formContainer.className = data.isFormValid ? 'valid' : 'invalid' - } - } + inputEvents: { + onChange: (data) => { + formContainer.className = data.isFormValid ? "valid" : "invalid"; + }, + }, }); ``` @@ -518,12 +538,12 @@ const cardFields = paypal.CardFields({ Add a class to a field. Useful for updating field styles when events occur elsewhere in your checkout -| Parameters | Type | Description | -|------------|------|-------------| -|classname | string | The class to be added. | +| Parameters | Type | Description | +| ---------- | ------ | ---------------------- | +| classname | string | The class to be added. | ```js -const cardField = paypal.CardFields(/* options */) +const cardField = paypal.CardFields(/* options */); const numberField = cardField.NumberField(/* options */); numberField.render(cardNumberContainer); numberField.addClass("purple"); @@ -534,7 +554,7 @@ numberField.addClass("purple"); Clears the value of a field. ```js -const cardField = paypal.CardFields(/* options */) +const cardField = paypal.CardFields(/* options */); const nameField = cardField.NameField(/* options */); nameField.render(cardNameContainer); nameField.clear(); @@ -545,7 +565,7 @@ nameField.clear(); Programmatically focus a field. ```js -const cardField = paypal.CardFields(/* options */) +const cardField = paypal.CardFields(/* options */); const nameField = cardField.NameField(/* options */); nameField.render(cardNameContainer); nameField.focus(); @@ -556,23 +576,23 @@ nameField.focus(); Returns a promise that resolves into [state object](#state-object). It includes the state of all fields and possible card types #### Example + ```js -const cardField = paypal.CardFields(/* options */) +const cardField = paypal.CardFields(/* options */); const nameField = cardField.NameField(/* options */); nameField.render(cardNameContainer); -cardField.getState() - .then((res) => { - //checking if each field is empty - const emptyField = Object.keys(res.fields).forEach((field) => { - return res.fields[field].isEmpty; - }); - }) - .catch(err => { - console.log(err); -}) - - +cardField + .getState() + .then((res) => { + //checking if each field is empty + const emptyField = Object.keys(res.fields).forEach((field) => { + return res.fields[field].isEmpty; + }); + }) + .catch((err) => { + console.log(err); + }); var formValid = Object.keys(state.fields).every(function (key) { return state.fields[key].isValid; @@ -583,12 +603,12 @@ var formValid = Object.keys(state.fields).every(function (key) { Removes a supported attribute from a field. -| Parameters | Type | Description | -|------------|------|-------------| -|attribute | string | The name of the attribute you wish to remove from the field.| +| Parameters | Type | Description | +| ---------- | ------ | ------------------------------------------------------------ | +| attribute | string | The name of the attribute you wish to remove from the field. | ```js -const cardField = paypal.CardFields(/* options */) +const cardField = paypal.CardFields(/* options */); const numberField = cardField.NumberField(/* options */); numberField.render(cardNumberContainer); numberField.removeAttribute("placeholder"); @@ -598,12 +618,12 @@ numberField.removeAttribute("placeholder"); Removes a class from a field. Useful for updating field styles when events occur elsewhere in your checkout. -| Parameters | Type | Description | -|------------|------|-------------| -|classname | string | The class to be removed. | +| Parameters | Type | Description | +| ---------- | ------ | ------------------------ | +| classname | string | The class to be removed. | ```js -const cardField = paypal.CardFields(/* options */) +const cardField = paypal.CardFields(/* options */); const numberField = cardField.NumberField(/* options */); numberField.render(cardNumberContainer); numberField.removeClass("purple"); @@ -613,13 +633,13 @@ numberField.removeClass("purple"); Sets an attribute of a field. Supported attributes are `aria-invalid`, `aria-required`, `disabled`, and `placeholder`. -| Parameters | Type | Description | -|------------|------|-------------| -|attribute | string | The attribute to be added to the field. | -|value | string | The value for the attribute | +| Parameters | Type | Description | +| ---------- | ------ | --------------------------------------- | +| attribute | string | The attribute to be added to the field. | +| value | string | The value for the attribute | ```js -const cardField = paypal.CardFields(/* options */) +const cardField = paypal.CardFields(/* options */); const nameField = cardField.NameField(/* options */); nameField.render(cardNameContainer); nameField.setAttribute("placeholder", "Enter your full name"); @@ -629,12 +649,12 @@ nameField.setAttribute("placeholder", "Enter your full name"); Sets a visually hidden message for screen readers on a field -| Parameters | Type | Description | -|------------|------|-------------| -|message | string | The message to set for screen readers. | +| Parameters | Type | Description | +| ---------- | ------ | -------------------------------------- | +| message | string | The message to set for screen readers. | ```js -const cardField = paypal.CardFields(/* options */) +const cardField = paypal.CardFields(/* options */); const nameField = cardField.NameField(/* options */); nameField.render(cardNameContainer); nameField.setMessage("Please type your name as it appears on your credit card"); @@ -646,16 +666,16 @@ Submit the payment information ```js // Add click listener to merchant-supplied submit button and call the submit function on the CardField component - multiCardFieldButton.addEventListener("click", () => { - cardField - .submit() - .then(() => { - console.log("multi card fields submit"); - }) - .catch((err) => { - console.log("There was an error with multi card fields: ", err); - }); - }); +multiCardFieldButton.addEventListener("click", () => { + cardField + .submit() + .then(() => { + console.log("multi card fields submit"); + }) + .catch((err) => { + console.log("There was an error with multi card fields: ", err); + }); +}); ``` ## Full Example diff --git a/src/card/docs/MultiCardFields/full-example.md b/src/card/docs/MultiCardFields/full-example.md index f591e07fe5..cd163461fc 100644 --- a/src/card/docs/MultiCardFields/full-example.md +++ b/src/card/docs/MultiCardFields/full-example.md @@ -1,119 +1,130 @@ # Full Multi-Card Field Example ```html - + - - - Checkout Page - - -
-
-
-
-
- -
- - - + + // Add click listener to submit button and call the submit function on the CardField component + multiCardFieldButton.addEventListener("click", () => { + cardField + .submit() + .then(() => { + // Handle a successful payment + }) + .catch((err) => { + // Handle an unsuccessful payment + }); + }); + } + -``` \ No newline at end of file +``` diff --git a/src/card/docs/README.md b/src/card/docs/README.md index d7eaaa2844..7550c764bb 100644 --- a/src/card/docs/README.md +++ b/src/card/docs/README.md @@ -1,5 +1,5 @@ # Hosted Card Fields -* [Initializing the SDK](Initialization) -* [Multi Card Fields](MultiCardFields) -* [Vaulting](Vaulting) \ No newline at end of file +- [Initializing the SDK](Initialization) +- [Multi Card Fields](MultiCardFields) +- [Vaulting](Vaulting) diff --git a/src/card/docs/Vaulting/README.md b/src/card/docs/Vaulting/README.md index 1480d4556c..e86054336d 100644 --- a/src/card/docs/Vaulting/README.md +++ b/src/card/docs/Vaulting/README.md @@ -1,9 +1,13 @@ # Vaulting with HCF -* [Vault with Purchase](#vault-with-purchase) -* [Vault without Purchase](#vault-without-purchase) -* [Error states](#error-states) + +- [Vault with Purchase](#vault-with-purchase) +- [Vault without Purchase](#vault-without-purchase) +- [Error states](#error-states) + ## Vault with Purchase + ### General Flow + 1. Define the `CardFields` `createOrder` callback to pass relevant payment information (excluding card details) and desire to vault payment method to server-side API. 2. API calls `POST v2/checkout/orders` with `vault` field. 3. The order is successfully created and the `orderId` is returned. @@ -15,6 +19,7 @@ In order to vault the card, an indicator needs to be set inside of `createOrder` to pass through to the `POST v2/checkout/orders` call; for example, a checkbox on a page that, when checked, includes the vault parameter in the body passed to the server-side API. (A general overview of the `createOrder` function can be found in the [Multi Card Fields documentation](../MultiCardFields/README.md#createOrder).) `vault.store_in_vault`: indicates desire to vault purchase method. A value of `"ON_SUCCESS"` indicates the vault will occur only upon successful order capture. + ```js let vaulting = vaultCheckbox.checked; if (vaulting) { @@ -31,9 +36,11 @@ if (vaulting) { ``` ### Modifications to `onApprove` + After the order is successfully created via `createOrder`, the order needs to be captured. This is done by defining the `CardFields.onApprove` callback to pass the orderId to a server-side API that calls `POST v2/checkout/orders/${orderId}/capture`. No vault specific data is required in the body of the call. Once the order is successfully captured, the response will include the vaulting data. (A general overview of the `onApprove` callback can be found in the [Multi Card Fields documentation](../MultiCardFields/README.md#onApprove).) Depending on the type of card being used, several different responses may be returned to indicate the vaulting status. Generally, if vaulting occurred successfully, you will see the `payment_source.card.attributes.vault` field populated with an `id` field. This is the id of the vaulted payment method that can be stored and used to retrieve the vaulted payment method for subsequent transactions. Additionally, a `customer.id` will be generated if this is a first time buyer. The merchant will need to store this `customer.id` to use for future calls to retrieve existing vaulted payment methods. Example response: + ```json { "id": "5O190127TN364715T", @@ -75,15 +82,19 @@ Depending on the type of card being used, several different responses may be ret ### Card Specific Requirements #### Visa & Mastercard + No special considerations required for Visa or Mastercard vault implementation. #### American Express + Vaulting with American Express requires the merchant to be subscribed to the American Express OptBlue feature. ### Examples of vaulting modifications: + In this example you can see the `createOrder` callback defining a payload to include a customer id and the vault command, and then included in the `fetch()` call. #### First Time Buyer + ```js const cardField = paypal.CardFields({ style: styleObject, @@ -145,10 +156,15 @@ const cardField = paypal.CardFields({ }, }); ``` + #### Return Buyer + // todo + ## Vault without Purchase + // todo ## Error States + // todo diff --git a/src/card/index.js b/src/card/index.js index 44a8e39323..3836dc7183 100644 --- a/src/card/index.js +++ b/src/card/index.js @@ -1,4 +1,4 @@ /* @flow */ -export * from './components'; -export * from './interface'; +export * from "./components"; +export * from "./interface"; diff --git a/src/card/interface/getCardFieldState.js b/src/card/interface/getCardFieldState.js index 59169fa945..07c8e58672 100644 --- a/src/card/interface/getCardFieldState.js +++ b/src/card/interface/getCardFieldState.js @@ -12,20 +12,20 @@ export function getCardFieldState(): CardFieldsState { cardNumberFrame, cardCVVFrame, cardExpiryFrame, - cardPostalFrame + cardPostalFrame, } = getCardFrames(); const optionalFields = {}; // Optional frames: the idea is to keep the optional frames separate and add the field // state as needed const cardFrameFields = [cardNameFrame, cardPostalFrame]; - cardFrameFields.forEach(cardFrame => { + cardFrameFields.forEach((cardFrame) => { if (cardFrame) { optionalFields[kebabToCamelCase(cardFrame.name)] = { isEmpty: isEmpty(cardFrame?.getFieldValue()), isValid: cardFrame?.isFieldValid(), isPotentiallyValid: cardFrame.isFieldPotentiallyValid(), - isFocused: cardFrame.isFieldFocused() + isFocused: cardFrame.isFieldFocused(), }; } }); @@ -38,21 +38,21 @@ export function getCardFieldState(): CardFieldsState { isEmpty: isEmpty(cardNumberFrame.getFieldValue()), isValid: cardNumberFrame.isFieldValid(), isPotentiallyValid: cardNumberFrame.isFieldPotentiallyValid(), - isFocused: cardNumberFrame.isFieldFocused() + isFocused: cardNumberFrame.isFieldFocused(), }, cardExpiryField: { isEmpty: isEmpty(cardExpiryFrame.getFieldValue()), isValid: cardExpiryFrame.isFieldValid(), isPotentiallyValid: cardExpiryFrame.isFieldPotentiallyValid(), - isFocused: cardExpiryFrame.isFieldFocused() + isFocused: cardExpiryFrame.isFieldFocused(), }, cardCvvField: { isEmpty: isEmpty(cardCVVFrame.getFieldValue()), isValid: cardCVVFrame.isFieldValid(), isPotentiallyValid: cardCVVFrame.isFieldPotentiallyValid(), - isFocused: cardCVVFrame.isFieldFocused() - } - } + isFocused: cardCVVFrame.isFieldFocused(), + }, + }, }; return cardFieldsState; -} \ No newline at end of file +} diff --git a/src/card/interface/getCardFields.js b/src/card/interface/getCardFields.js index efe0028c5c..b2d40a153d 100644 --- a/src/card/interface/getCardFields.js +++ b/src/card/interface/getCardFields.js @@ -1,12 +1,12 @@ /* @flow */ -import { FRAME_NAME } from '../../constants'; -import { CARD_ERRORS } from '../constants'; -import type { Card, CardType } from '../types'; -import { checkCardEligibility } from '../lib'; +import { FRAME_NAME } from "../../constants"; +import { CARD_ERRORS } from "../constants"; +import type { Card, CardType } from "../types"; +import { checkCardEligibility } from "../lib"; -import { getExportsByFrameName } from './getExportsByFrameName'; -import { getCardFrames } from './getCardFrames'; +import { getExportsByFrameName } from "./getExportsByFrameName"; +import { getCardFrames } from "./getCardFrames"; export function getCardFields(productAction: string): Card { const card = {}; @@ -21,7 +21,7 @@ export function getCardFields(productAction: string): Card { cardCVVFrame, cardExpiryFrame, cardNameFrame, - cardPostalFrame + cardPostalFrame, } = getCardFrames(); // 3 Required fields for HCFs purchase diff --git a/src/card/interface/getCardFrames.js b/src/card/interface/getCardFrames.js index df7723d046..f93d527f14 100644 --- a/src/card/interface/getCardFrames.js +++ b/src/card/interface/getCardFrames.js @@ -9,14 +9,14 @@ import { getExportsByFrameName } from "./getExportsByFrameName"; So adding a flowIgnore to pass the typecheck failures*/ // $FlowIgnore -export function getCardFrames(): { // eslint-disable-line flowtype/require-exact-type +export function getCardFrames(): {| cardFrame: ?ExportsOptions, cardNumberFrame: ExportsOptions, cardCVVFrame: ExportsOptions, cardExpiryFrame: ExportsOptions, cardNameFrame?: ?ExportsOptions, - cardPostalFrame?: ?ExportsOptions -} { + cardPostalFrame?: ?ExportsOptions, +|} { const cardFrame = getExportsByFrameName(FRAME_NAME.CARD_FIELD); const cardNumberFrame = getExportsByFrameName(FRAME_NAME.CARD_NUMBER_FIELD); const cardCVVFrame = getExportsByFrameName(FRAME_NAME.CARD_CVV_FIELD); @@ -24,16 +24,15 @@ export function getCardFrames(): { // eslint-disable-line flowtype/require-exact const cardNameFrame = getExportsByFrameName(FRAME_NAME.CARD_NAME_FIELD); const cardPostalFrame = getExportsByFrameName(FRAME_NAME.CARD_POSTAL_FIELD); - return { cardFrame, - // $FlowIgnore + // $FlowIgnore cardNumberFrame, - // $FlowIgnore + // $FlowIgnore cardCVVFrame, - // $FlowIgnore + // $FlowIgnore cardExpiryFrame, cardNameFrame, - cardPostalFrame + cardPostalFrame, }; -} \ No newline at end of file +} diff --git a/src/card/interface/getExportsByFrameName.js b/src/card/interface/getExportsByFrameName.js index b4ceb7e5e9..c1957549e5 100644 --- a/src/card/interface/getExportsByFrameName.js +++ b/src/card/interface/getExportsByFrameName.js @@ -1,12 +1,15 @@ /* @flow */ -import { getAllFramesInWindow, isSameDomain } from "@krakenjs/cross-domain-utils/src"; +import { + getAllFramesInWindow, + isSameDomain, +} from "@krakenjs/cross-domain-utils/src"; import { FRAME_NAME } from "../../constants"; import type { CardExports } from "../lib"; export function getExportsByFrameName( - name: $Values + name: $Values, ): ?CardExports { try { for (const win of getAllFramesInWindow(window)) { @@ -22,4 +25,4 @@ export function getExportsByFrameName( } catch (err) { // pass } -} \ No newline at end of file +} diff --git a/src/card/interface/getFieldErrors.js b/src/card/interface/getFieldErrors.js index ed181134ef..a603c2632b 100644 --- a/src/card/interface/getFieldErrors.js +++ b/src/card/interface/getFieldErrors.js @@ -5,30 +5,32 @@ import { CARD_ERRORS } from "../constants"; import { kebabToCamelCase } from "../lib"; import type { FieldsState } from "../types"; -export const getFieldErrors = (fields : FieldsState ) : [$Values] | [] => { +export const getFieldErrors = ( + fields: FieldsState, +): [$Values] | [] => { const errors = []; - Object.keys(fields).forEach(field => { - if(fields[field] && !fields[field].isValid){ - switch(field) { + Object.keys(fields).forEach((field) => { + if (fields[field] && !fields[field].isValid) { + switch (field) { case kebabToCamelCase(FRAME_NAME.CARD_NAME_FIELD): - errors.push(CARD_ERRORS.INVALID_NAME) + errors.push(CARD_ERRORS.INVALID_NAME); break; case kebabToCamelCase(FRAME_NAME.CARD_NUMBER_FIELD): - errors.push(CARD_ERRORS.INVALID_NUMBER) + errors.push(CARD_ERRORS.INVALID_NUMBER); break; case kebabToCamelCase(FRAME_NAME.CARD_EXPIRY_FIELD): - errors.push(CARD_ERRORS.INVALID_EXPIRY) + errors.push(CARD_ERRORS.INVALID_EXPIRY); break; case kebabToCamelCase(FRAME_NAME.CARD_CVV_FIELD): - errors.push(CARD_ERRORS.INVALID_CVV) + errors.push(CARD_ERRORS.INVALID_CVV); break; case kebabToCamelCase(FRAME_NAME.CARD_POSTAL_FIELD): - errors.push(CARD_ERRORS.INVALID_POSTAL) + errors.push(CARD_ERRORS.INVALID_POSTAL); break; default: - // noop + // noop } } - }) + }); return errors; -} \ No newline at end of file +}; diff --git a/src/card/interface/getFieldErrors.test.js b/src/card/interface/getFieldErrors.test.js index 9589842800..339e377cda 100644 --- a/src/card/interface/getFieldErrors.test.js +++ b/src/card/interface/getFieldErrors.test.js @@ -50,7 +50,7 @@ describe("getFieldErrors", () => { "INVALID_EXPIRY", "INVALID_NAME", "INVALID_POSTAL", - ].sort() + ].sort(), ); }); @@ -67,7 +67,7 @@ describe("getFieldErrors", () => { fields.cardCvvField.isValid = true; // $FlowFixMe expect(getFieldErrors(fields).sort()).toEqual( - ["INVALID_NUMBER", "INVALID_NAME", "INVALID_POSTAL"].sort() + ["INVALID_NUMBER", "INVALID_NAME", "INVALID_POSTAL"].sort(), ); }); }); diff --git a/src/card/interface/gql.js b/src/card/interface/gql.js index d7f7870657..ebb46e6c24 100644 --- a/src/card/interface/gql.js +++ b/src/card/interface/gql.js @@ -3,12 +3,8 @@ import { getCardFrames } from "./getCardFrames"; export function resetGQLErrors(): void { - const { - cardFrame, - cardNumberFrame, - cardExpiryFrame, - cardCVVFrame - } = getCardFrames(); + const { cardFrame, cardNumberFrame, cardExpiryFrame, cardCVVFrame } = + getCardFrames(); if (cardFrame) { cardFrame.resetGQLErrors(); @@ -28,12 +24,8 @@ export function resetGQLErrors(): void { } export function emitGqlErrors(errorsMap: Object): void { - const { - cardFrame, - cardNumberFrame, - cardExpiryFrame, - cardCVVFrame - } = getCardFrames(); + const { cardFrame, cardNumberFrame, cardExpiryFrame, cardCVVFrame } = + getCardFrames(); const { number, expiry, security_code } = errorsMap; @@ -66,4 +58,4 @@ export function emitGqlErrors(errorsMap: Object): void { if (cardCVVFrame && security_code) { cardCVVFrame.setGqlErrors({ field: "cvv", errors: security_code }); } -} \ No newline at end of file +} diff --git a/src/card/interface/hasCardFields.js b/src/card/interface/hasCardFields.js index 48184a8f9b..083e4ebbff 100644 --- a/src/card/interface/hasCardFields.js +++ b/src/card/interface/hasCardFields.js @@ -3,12 +3,10 @@ import { getCardFrames } from "./getCardFrames"; export function hasCardFields(): boolean { - const { - cardFrame, - cardNumberFrame, - cardCVVFrame, - cardExpiryFrame, - } = getCardFrames(); + const { cardFrame, cardNumberFrame, cardCVVFrame, cardExpiryFrame } = + getCardFrames(); - return Boolean(cardFrame || (cardNumberFrame && cardCVVFrame && cardExpiryFrame)) + return Boolean( + cardFrame || (cardNumberFrame && cardCVVFrame && cardExpiryFrame), + ); } diff --git a/src/card/interface/index.js b/src/card/interface/index.js index ed610c73e2..0ba2f458e2 100644 --- a/src/card/interface/index.js +++ b/src/card/interface/index.js @@ -1,10 +1,10 @@ /* @flow */ -export * from './getCardFields'; -export * from './getCardFieldState'; -export * from './getFieldErrors'; -export * from './gql'; -export * from './hasCardFields'; -export * from './isEmpty'; -export * from './submitCardFields'; -export * from './vault-without-purchase'; +export * from "./getCardFields"; +export * from "./getCardFieldState"; +export * from "./getFieldErrors"; +export * from "./gql"; +export * from "./hasCardFields"; +export * from "./isEmpty"; +export * from "./submitCardFields"; +export * from "./vault-without-purchase"; diff --git a/src/card/interface/isEmpty.js b/src/card/interface/isEmpty.js index 50585f37f8..231c4b2c57 100644 --- a/src/card/interface/isEmpty.js +++ b/src/card/interface/isEmpty.js @@ -1,5 +1,5 @@ /* @flow */ export function isEmpty(value: string): boolean { - return value.length === 0 -} \ No newline at end of file + return value.length === 0; +} diff --git a/src/card/interface/submitCardFields.js b/src/card/interface/submitCardFields.js index 5f3eea6ecf..b2f40a21af 100644 --- a/src/card/interface/submitCardFields.js +++ b/src/card/interface/submitCardFields.js @@ -2,14 +2,24 @@ import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -import { getCardProps, getComponents, type PurchaseFlowCardProps, type VaultWithoutPurchaseFlowCardProps } from "../props" -import { confirmOrderAPI } from "../../api" -import { hcfTransactionError, hcfTransactionSuccess, hcfFieldsSubmit } from "../logger" -import type { FeatureFlags } from "../../types" -import type { BillingAddress, Card, ExtraFields } from '../types' -import {convertCardToPaymentSource, reformatPaymentSource} from '../lib' -import { SUBMIT_ERRORS } from "../constants" -import { handleThreeDomainSecureContingency } from "../../lib/3ds" +import { + getCardProps, + getComponents, + type PurchaseFlowCardProps, + type VaultWithoutPurchaseFlowCardProps, +} from "../props"; +import { confirmOrderAPI } from "../../api"; +import { + hcfTransactionError, + hcfTransactionSuccess, + hcfFieldsSubmit, +} from "../logger"; +import type { FeatureFlags } from "../../types"; +import type { BillingAddress, Card, ExtraFields } from "../types"; +import { convertCardToPaymentSource, reformatPaymentSource } from "../lib"; +import { getLogger } from "../../lib/logger"; +import { SUBMIT_ERRORS } from "../constants"; +import { handleThreeDomainSecureContingency } from "../../lib/3ds"; import { PAYMENT_FLOWS } from "../../constants"; import { resetGQLErrors } from "./gql"; @@ -25,22 +35,37 @@ type SubmitCardFieldsOptions = {| |}, experiments: {| hostedCardFields: boolean, + useIDToken: boolean, |}, |}; -function handleVaultWithoutPurchaseFlow(cardProps: VaultWithoutPurchaseFlowCardProps, card: Card, extraFields?: ExtraFields): ZalgoPromise { +function handleVaultWithoutPurchaseFlow( + cardProps: VaultWithoutPurchaseFlowCardProps, + card: Card, + extraFields?: ExtraFields, +): ZalgoPromise { const { ThreeDomainSecure } = getComponents(); - const { getParent, createVaultSetupToken, onError,clientID, onApprove } = cardProps; + const { + getParent, + createVaultSetupToken, + onError, + clientID, + onApprove, + userIDToken, + productAction, + } = cardProps; return savePaymentSource({ onApprove, - // $FlowFixMe need to rethink how to pass down these props + // $FlowFixMe need to rethink how to pass down these props createVaultSetupToken, onError, getParent, ThreeDomainSecure, clientID, paymentSource: convertCardToPaymentSource(card, extraFields), + idToken: userIDToken, + productAction, }); } @@ -48,53 +73,67 @@ function handlePurchaseFlow( cardProps: PurchaseFlowCardProps, card: Card, extraFields: ?ExtraFields, - facilitatorAccessToken: string + facilitatorAccessToken: string, ): ZalgoPromise { let orderID; const { ThreeDomainSecure } = getComponents(); - const { createOrder, getParent } = cardProps; + const { createOrder, getParent, productAction } = cardProps; - return cardProps - // $FlowFixMe need to rethink how to pass down these props - .createOrder() - .then((id) => { - const payment_source = convertCardToPaymentSource(card, extraFields); - // eslint-disable-next-line flowtype/no-weak-types - const data: any = { - payment_source: { - // $FlowIssue - card: reformatPaymentSource(payment_source.card), - }, - }; - orderID = id; - return confirmOrderAPI(orderID, data, { - facilitatorAccessToken, - partnerAttributionID: "", + return ( + cardProps + // $FlowFixMe need to rethink how to pass down these props + .createOrder() + .then((id) => { + const payment_source = convertCardToPaymentSource(card, extraFields); + // eslint-disable-next-line flowtype/no-weak-types + const data: any = { + payment_source: { + // $FlowIssue + card: reformatPaymentSource(payment_source.card), + }, + }; + orderID = id; + return confirmOrderAPI(orderID, data, { + facilitatorAccessToken, + partnerAttributionID: "", + experiments: {}, + }); }) - }) - .then((res) => { - // $FlowFixMe - const { status, links } = res; - return handleThreeDomainSecureContingency({status, links, ThreeDomainSecure, createOrder, getParent }); - }) - .then((threeDsResponse) => { - // $FlowFixMe - return cardProps.onApprove({ orderID, liabilityShift: threeDsResponse?.liability_shift }, {}); - }) - .then(() => { - hcfTransactionSuccess({ orderID }); - }) - .catch((error) => { - if (typeof error === "string") { - error = new Error(error); - } - hcfTransactionError({ error, orderID }); - if (cardProps.onError) { - cardProps.onError(error); - } + .then((res) => { + // $FlowFixMe + const { status, links } = res; + return handleThreeDomainSecureContingency({ + status, + links, + ThreeDomainSecure, + createOrder, + getParent, + paymentFlow: productAction, + }); + }) + .then((threeDsResponse) => { + return cardProps.onApprove( + // $FlowFixMe + { orderID, liabilityShift: threeDsResponse?.liability_shift }, + // $FlowFixMe + {}, + ); + }) + .then(() => { + hcfTransactionSuccess({ orderID }); + }) + .catch((error) => { + if (typeof error === "string") { + error = new Error(error); + } + hcfTransactionError({ error, orderID }); + if (cardProps.onError) { + cardProps.onError(error); + } - throw error; - }); + throw error; + }) + ); } export function submitCardFields({ @@ -109,6 +148,14 @@ export function submitCardFields({ experiments, }); + if (experiments.useIDToken) { + // CP4 merchants will use the `userIDToken` to auth to associate the transaction with a merchant + if (cardProps.userIDToken) { + facilitatorAccessToken = cardProps.userIDToken; + } else { + getLogger().info(`hcf_userIDToken_present_false`); + } + } hcfFieldsSubmit({ cardFlowType: cardProps.productAction, hcfSessionID: cardProps.hcfSessionID, @@ -124,11 +171,11 @@ export function submitCardFields({ switch (cardProps.productAction) { case PAYMENT_FLOWS.WITH_PURCHASE: { return handlePurchaseFlow( - // $FlowIssue need to work on card props with the different production actions + // $FlowIssue need to work on card props with the different production actions cardProps, card, extraFields, - facilitatorAccessToken + facilitatorAccessToken, ); } case PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE: { diff --git a/src/card/interface/submitCardFields.test.js b/src/card/interface/submitCardFields.test.js index 6e379b0131..4a0e243fa6 100644 --- a/src/card/interface/submitCardFields.test.js +++ b/src/card/interface/submitCardFields.test.js @@ -1,5 +1,5 @@ /* @flow */ -import { describe, test, expect, beforeEach, vi } from "vitest"; +import { describe, test, expect, afterEach, vi } from "vitest"; import { INTENT } from "@paypal/sdk-constants"; import { getCardProps } from "../props"; @@ -8,6 +8,7 @@ import { PAYMENT_FLOWS } from "../../constants"; import { hcfTransactionSuccess, hcfTransactionError } from "../logger"; import { SUBMIT_ERRORS } from "../constants"; import { handleThreeDomainSecureContingency } from "../../lib/3ds"; +import { getLogger } from "../../lib/logger"; import { savePaymentSource } from "./vault-without-purchase"; import { resetGQLErrors } from "./gql"; @@ -24,6 +25,19 @@ vi.mock("../props", () => { vi.mock("../../lib/3ds"); +vi.mock("../logger"); +vi.mock("../../lib/logger", async () => { + const actual = await vi.importActual("../../lib/logger"); + return { + ...actual, + getLogger: vi.fn(() => { + return { + info: vi.fn().mockReturnThis(), + }; + }), + }; +}); + vi.mock("./hasCardFields", () => { return { hasCardFields: vi.fn(() => true), @@ -38,7 +52,6 @@ const mockGetCardFieldsReturn = { postalCode: "91210", }; -vi.mock("../logger"); vi.mock("./getCardFields", () => { return { getCardFields: vi.fn(() => mockGetCardFieldsReturn), @@ -64,7 +77,7 @@ vi.mock("../../api", () => ({ })); describe("submitCardFields", () => { - beforeEach(() => { + afterEach(() => { vi.restoreAllMocks(); }); @@ -74,6 +87,7 @@ describe("submitCardFields", () => { featureFlags: {}, experiments: { hostedCardFields: true, + useIDToken: false, }, }; @@ -84,7 +98,7 @@ describe("submitCardFields", () => { expect.assertions(1); expect(submitCardFields(defaultOptions)).rejects.toThrowError( - SUBMIT_ERRORS.UNABLE_TO_SUBMIT + SUBMIT_ERRORS.UNABLE_TO_SUBMIT, ); }); @@ -99,11 +113,11 @@ describe("submitCardFields", () => { getParent: vi.fn(), ThreeDomainSecure: {}, clientID: "client-id", + productAction: PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, }; // $FlowIssue getCardProps.mockReturnValue({ ...mockGetCardPropsReturn, - productAction: PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, }); await submitCardFields(defaultOptions); @@ -157,13 +171,14 @@ describe("submitCardFields", () => { { facilitatorAccessToken: "test-access-token", partnerAttributionID: "", - } + experiments: {}, + }, ); expect(mockGetCardPropsReturn.onApprove).toHaveBeenCalledWith( { orderID: "test-order-id", }, - {} + {}, ); expect(hcfTransactionSuccess).toHaveBeenCalledWith({ orderID: "test-order-id", @@ -182,7 +197,7 @@ describe("submitCardFields", () => { // $FlowIssue getCardProps.mockReturnValue(mockGetCardPropsReturn); await expect(submitCardFields(defaultOptions)).rejects.toThrow( - "error with on approve" + "error with on approve", ); expect(mockGetCardPropsReturn.createOrder).toHaveBeenCalled(); expect(mockGetCardPropsReturn.onApprove).toHaveBeenCalled(); @@ -210,7 +225,7 @@ describe("submitCardFields", () => { // $FlowIssue getCardProps.mockReturnValue(mockGetCardPropsReturn); await expect(submitCardFields(defaultOptions)).rejects.toThrow( - "confirm order api failure test" + "confirm order api failure test", ); expect(mockGetCardPropsReturn.createOrder).toHaveBeenCalled(); // $FlowIssue @@ -235,7 +250,7 @@ describe("submitCardFields", () => { // $FlowIssue getCardProps.mockReturnValue(mockGetCardPropsReturn); await expect(submitCardFields(defaultOptions)).rejects.toThrow( - expectedError + expectedError, ); expect(mockGetCardPropsReturn.createOrder).toHaveBeenCalled(); // $FlowIssue @@ -248,13 +263,79 @@ describe("submitCardFields", () => { }); describe("handlePurchaseFlow()", () => { + test("uses id token for the bearer token if experiment is enabled", async () => { + const mockOrderId = "12345"; + const mockIdToken = "13orqiehfknwjs"; + const options = { + ...defaultOptions, + experiments: { + hostedCardFields: true, + useIDToken: true, + }, + }; + const mockCardProps = { + // eslint-disable-next-line compat/compat, promise/no-native, no-restricted-globals + createOrder: vi.fn(() => Promise.resolve(mockOrderId)), + // eslint-disable-next-line compat/compat, promise/no-native, no-restricted-globals + onApprove: vi.fn(() => Promise.resolve()), + // eslint-disable-next-line no-empty-function + getParent: () => {}, + productAction: PAYMENT_FLOWS.WITH_PURCHASE, + userIDToken: mockIdToken, + }; + // $FlowIssue + getCardProps.mockReturnValue(mockCardProps); + + await submitCardFields(options); + + expect(confirmOrderAPI).toBeCalledWith( + expect.any(String), + expect.any(Object), + expect.objectContaining({ facilitatorAccessToken: mockIdToken }), + ); + }); + + test("uses id token for the bearer token if experiment is enabled && userIDToken is present", async () => { + const mockOrderId = "12345"; + const options = { + ...defaultOptions, + experiments: { + hostedCardFields: true, + useIDToken: true, + }, + }; + const mockCardProps = { + // eslint-disable-next-line compat/compat, promise/no-native, no-restricted-globals + createOrder: vi.fn(() => Promise.resolve(mockOrderId)), + // eslint-disable-next-line compat/compat, promise/no-native, no-restricted-globals + onApprove: vi.fn(() => Promise.resolve()), + // eslint-disable-next-line no-empty-function + getParent: () => {}, + productAction: PAYMENT_FLOWS.WITH_PURCHASE, + }; + const infoMock = vi.fn().mockReturnThis(); + // $FlowIssue + getLogger.mockReturnValue({ info: infoMock }); + // $FlowIssue + getCardProps.mockReturnValue(mockCardProps); + + await submitCardFields(options); + + expect(confirmOrderAPI).toBeCalledWith( + expect.any(String), + expect.any(Object), + expect.any(Object), + ); + expect(infoMock).toHaveBeenCalledWith("hcf_userIDToken_present_false"); + }); + test("should handle 3DS contingency for vault with purchase", async () => { const mockOrderId = "12345"; const mock3dsResponse = { liability_shift: "some-value" }; // $FlowIssue handleThreeDomainSecureContingency.mockResolvedValue( // eslint-disable-next-line compat/compat, promise/no-native, no-restricted-globals - Promise.resolve(mock3dsResponse) + Promise.resolve(mock3dsResponse), ); const inputOpts = { facilitatorAccessToken: "test-access-token", @@ -262,6 +343,7 @@ describe("submitCardFields", () => { featureFlags: {}, experiments: { hostedCardFields: true, + useIDToken: false, }, }; const mockCardProps = { @@ -289,13 +371,14 @@ describe("submitCardFields", () => { ThreeDomainSecure: mockThreeDomainSecure, createOrder: mockCardProps.createOrder, getParent: mockCardProps.getParent, + paymentFlow: PAYMENT_FLOWS.WITH_PURCHASE, }); expect(mockCardProps.onApprove).toBeCalledWith( { liabilityShift: mock3dsResponse.liability_shift, orderID: mockOrderId, }, - {} + {}, ); }); }); diff --git a/src/card/interface/vault-without-purchase.js b/src/card/interface/vault-without-purchase.js index 180b0c8647..7c92b98c54 100644 --- a/src/card/interface/vault-without-purchase.js +++ b/src/card/interface/vault-without-purchase.js @@ -1,9 +1,9 @@ /* @flow */ import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -import type { CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src'; +import type { CrossDomainWindowType } from "@krakenjs/cross-domain-utils/src"; -import type { ThreeDomainSecureFlowType } from '../../types'; +import type { ThreeDomainSecureFlowType } from "../../types"; import { updateVaultSetupToken, type PaymentSourceInput, @@ -26,8 +26,10 @@ type VaultPaymenSourceOptions = {| onError: XOnError, clientID: string, paymentSource: PaymentSourceInput, - getParent : () => CrossDomainWindowType, - ThreeDomainSecure : ThreeDomainSecureFlowType, + getParent: () => CrossDomainWindowType, + ThreeDomainSecure: ThreeDomainSecureFlowType, + idToken: string, + productAction: string, |}; export const savePaymentSource = ({ @@ -38,6 +40,8 @@ export const savePaymentSource = ({ paymentSource, getParent, ThreeDomainSecure, + idToken, + productAction, }: VaultPaymenSourceOptions): ZalgoPromise => { let vaultToken; return createVaultSetupToken() @@ -50,18 +54,27 @@ export const savePaymentSource = ({ vaultSetupToken, clientID, paymentSource, + idToken, }); }) .then((res) => { // $FlowFixMe const { status, links } = res?.updateVaultSetupToken || {}; - return handleThreeDomainSecureContingency({ status, links, + return handleThreeDomainSecureContingency({ + status, + links, getParent, ThreeDomainSecure, + paymentFlow: productAction, + }); }) - }) - .then((threeDsResponse) => onApprove({ vaultSetupToken: vaultToken, liabilityShift: threeDsResponse?.liability_shift })) + .then((threeDsResponse) => + onApprove({ + vaultSetupToken: vaultToken, + liabilityShift: threeDsResponse?.liability_shift, + }), + ) .then(() => vaultWithoutPurchaseSuccess({ vaultToken })) .catch((error) => { if (typeof error === "string") { diff --git a/src/card/interface/vault-without-purchase.test.js b/src/card/interface/vault-without-purchase.test.js index 478789e921..a06c1bdf90 100644 --- a/src/card/interface/vault-without-purchase.test.js +++ b/src/card/interface/vault-without-purchase.test.js @@ -48,7 +48,7 @@ describe("savePaymentSource", () => { test("should handle failure from merchant-supplied createVaultSetupToken", async () => { const createVaultSetupTokenError = new Error( - "error with create vault setup token" + "error with create vault setup token", ); const rejectCreateVaultSetupToken = vi .fn() @@ -59,7 +59,7 @@ describe("savePaymentSource", () => { savePaymentSource({ ...defaultOptions, ...defaultSave({ createVaultSetupToken: rejectCreateVaultSetupToken }), - }) + }), ).rejects.toThrow(createVaultSetupTokenError); expect(vaultWithoutPurchaseSuccess).not.toHaveBeenCalled(); expect(vaultWithoutPurchaseFailure).toHaveBeenCalledWith({ @@ -70,7 +70,7 @@ describe("savePaymentSource", () => { test("should handle failure from performing POST on a setup vault token", async () => { const updateVaultSetupTokenError = new Error( - "error with update vault setup token" + "error with update vault setup token", ); // $FlowIssue @@ -78,7 +78,7 @@ describe("savePaymentSource", () => { expect.assertions(4); await expect(savePaymentSource(defaultOptions)).rejects.toBe( - updateVaultSetupTokenError + updateVaultSetupTokenError, ); expect(vaultWithoutPurchaseSuccess).not.toHaveBeenCalled(); expect(vaultWithoutPurchaseFailure).toHaveBeenCalledWith({ @@ -101,7 +101,7 @@ describe("savePaymentSource", () => { savePaymentSource({ ...defaultOptions, ...defaultSave({ onApprove: rejectOnApprove }), - }) + }), ).rejects.toThrow(onApproveError); expect(vaultWithoutPurchaseSuccess).not.toHaveBeenCalled(); expect(vaultWithoutPurchaseFailure).toHaveBeenCalledWith({ @@ -141,4 +141,39 @@ describe("savePaymentSource", () => { vaultToken: defaultVaultSetupToken, }); }); + + test("should handle successful vault without purchase with an ID token passed", async () => { + const idToken = "eyja1234567"; + const updateVaultSetupTokenResult = { + updateVaultSetupToken: { status: "SOME_VALID_STATUS", links: {} }, + }; + + defaultOptions.idToken = idToken; + // $FlowIssue + updateVaultSetupToken.mockResolvedValue(updateVaultSetupTokenResult); + + await savePaymentSource(defaultOptions); + + expect.assertions(4); + expect(defaultOptions.createVaultSetupToken).toHaveBeenCalled(); + expect(updateVaultSetupToken).toHaveBeenCalledWith({ + vaultSetupToken: "vault-setup-token", + clientID: "client-id", + idToken: "eyja1234567", + paymentSource: { + card: { + expiry: "01/24", + name: "John Doe", + number: "4111111111111111", + securityCode: "123", + }, + }, + }); + expect(defaultOptions.onApprove).toHaveBeenCalledWith({ + vaultSetupToken: "vault-setup-token", + }); + expect(vaultWithoutPurchaseSuccess).toHaveBeenCalledWith({ + vaultToken: defaultVaultSetupToken, + }); + }); }); diff --git a/src/card/lib/card-checks.js b/src/card/lib/card-checks.js index dad71ddb3b..dc8940fd9c 100644 --- a/src/card/lib/card-checks.js +++ b/src/card/lib/card-checks.js @@ -1,118 +1,132 @@ /* @flow */ -import cardValidator from 'card-validator'; +import cardValidator from "card-validator"; -import type { CardType } from '../types'; -import { PAYMENT_FLOWS } from '../../constants'; -import { DEFAULT_CARD_TYPE, VALIDATOR_TO_TYPE_MAP } from '../constants'; +import type { CardType } from "../types"; +import { PAYMENT_FLOWS } from "../../constants"; +import { DEFAULT_CARD_TYPE, VALIDATOR_TO_TYPE_MAP } from "../constants"; -import { assertString, splice } from './card-utils'; +import { assertString, splice } from "./card-utils"; // Add additional supported card types cardValidator.creditCardType.addCard({ - code: { - name: 'CVV', - size: 3 - }, - gaps: [ 4, 8, 12 ], - lengths: [ 16, 18, 19 ], - niceType: 'Carte Bancaire', - patterns: [], - type: 'cb-nationale' + code: { + name: "CVV", + size: 3, + }, + gaps: [4, 8, 12], + lengths: [16, 18, 19], + niceType: "Carte Bancaire", + patterns: [], + type: "cb-nationale", }); cardValidator.creditCardType.addCard({ - code: { - name: 'CVV', - size: 3 - }, - gaps: [ 4, 8, 12, 16 ], - lengths: [ 19 ], - niceType: 'Carte Aurore', - patterns: [], - type: 'cetelem' + code: { + name: "CVV", + size: 3, + }, + gaps: [4, 8, 12, 16], + lengths: [19], + niceType: "Carte Aurore", + patterns: [], + type: "cetelem", }); cardValidator.creditCardType.addCard({ - code: { - name: '', - size: 0 - }, - gaps: [ 4, 8, 12, 16 ], - lengths: [ 17 ], - niceType: 'Cofinoga ou Privilège', - patterns: [], - type: 'cofinoga' + code: { + name: "", + size: 0, + }, + gaps: [4, 8, 12, 16], + lengths: [17], + niceType: "Cofinoga ou Privilège", + patterns: [], + type: "cofinoga", }); cardValidator.creditCardType.addCard({ - code: { - name: '', - size: 0 - }, - gaps: [ 4, 8 ], - lengths: [ 8, 9 ], - niceType: '4 étoiles', - patterns: [], - type: 'cofidis' + code: { + name: "", + size: 0, + }, + gaps: [4, 8], + lengths: [8, 9], + niceType: "4 étoiles", + patterns: [], + type: "cofidis", }); // Detect the card type metadata for a card number -export function detectCardType(cardNumber : string) : $ReadOnlyArray { - if (cardNumber.length > 0) { - const cardTypes = cardValidator.creditCardType.default(cardNumber); - if (cardTypes.length > 0) { - return cardTypes; - } +export function detectCardType(cardNumber: string): $ReadOnlyArray { + if (cardNumber.length > 0) { + const cardTypes = cardValidator.creditCardType.default(cardNumber); + if (cardTypes.length > 0) { + return cardTypes; } - return [ DEFAULT_CARD_TYPE ]; + } + return [DEFAULT_CARD_TYPE]; } // Add gaps to a card number for display given a card type. If a card type is // not provided, attempt to detect it and add gaps based on that type. -export function addGapsToCardNumber(cardNumber : string, cardType? : CardType) : string { - assertString(cardNumber); +export function addGapsToCardNumber( + cardNumber: string, + cardType?: CardType, +): string { + assertString(cardNumber); - // Remove all non-digits and all whitespaces - cardNumber = cardNumber.trim().replace(/[^0-9]/g, '').replace(/\s/g, ''); - // $FlowFixMe - const gaps = cardType?.gaps || detectCardType(cardNumber)[0]?.gaps; + // Remove all non-digits and all whitespaces + cardNumber = cardNumber + .trim() + .replace(/[^0-9]/g, "") + .replace(/\s/g, ""); + // $FlowFixMe + const gaps = cardType?.gaps || detectCardType(cardNumber)[0]?.gaps; - // The gaps indicate where a space is inserted into the card number for display - if (gaps) { - for (let idx = 0; idx < gaps.length; idx++) { - const splicePoint = gaps[idx] + idx; - if (splicePoint > cardNumber.length - 1) { - // We're beyond the end of the number - break; - } + // The gaps indicate where a space is inserted into the card number for display + if (gaps) { + for (let idx = 0; idx < gaps.length; idx++) { + const splicePoint = gaps[idx] + idx; + if (splicePoint > cardNumber.length - 1) { + // We're beyond the end of the number + break; + } - cardNumber = splice(cardNumber, splicePoint, ' '); - } + cardNumber = splice(cardNumber, splicePoint, " "); } - return cardNumber; + } + return cardNumber; } -export function checkCardEligibility(cardNumber : string, cardType : CardType, productAction?: string) : boolean { - // check if the card type is eligible - const fundingEligibility = window.xprops.fundingEligibility; - const type = VALIDATOR_TO_TYPE_MAP[cardType.type]; - const isVaultFlow = productAction === PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE +export function checkCardEligibility( + cardNumber: string, + cardType: CardType, + productAction?: string, +): boolean { + // check if the card type is eligible + const fundingEligibility = window.xprops.fundingEligibility; + const type = VALIDATOR_TO_TYPE_MAP[cardType.type]; + const isVaultFlow = productAction === PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE; - if (cardNumber.length === 0) { - return true; + if (cardNumber.length === 0) { + return true; + } + if ( + fundingEligibility?.card?.eligible && + type && + fundingEligibility.card.vendors && + !fundingEligibility.card.branded + ) { + // mark as eligible if the card vendor is explicitly set to be eligible + const vendor = fundingEligibility.card.vendors[type]; + // We're only allowing cards to be vaulted if they're both vaultable and eligible for purchase + if (isVaultFlow && vendor?.vaultable && vendor?.eligible) { + return true; + } else if (!isVaultFlow && vendor?.eligible) { + return true; } - if (fundingEligibility?.card?.eligible && type && fundingEligibility.card.vendors && !fundingEligibility.card.branded) { - // mark as eligible if the card vendor is explicitly set to be eligible - const vendor = fundingEligibility.card.vendors[type]; - // We're only allowing cards to be vaulted if they're both vaultable and eligible for purchase - if (isVaultFlow && vendor?.vaultable && vendor?.eligible) { - return true; - } - else if (!isVaultFlow && vendor?.eligible) { - return true; - } - } - // otherwise default to be not eligible - return false; + } + // otherwise default to be not eligible + return false; } diff --git a/src/card/lib/card-checks.test.js b/src/card/lib/card-checks.test.js index baadf736d6..0eea709605 100644 --- a/src/card/lib/card-checks.test.js +++ b/src/card/lib/card-checks.test.js @@ -153,7 +153,7 @@ describe("card-checks", () => { const cardNumber = "4111111111111111"; const cardType = detectCardType(cardNumber)[0]; expect( - checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE) + checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE), ).toBe(true); }); @@ -171,7 +171,7 @@ describe("card-checks", () => { const cardNumber = "4111111111111111"; const cardType = detectCardType(cardNumber)[0]; expect( - checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE) + checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE), ).toBe(false); }); @@ -193,8 +193,8 @@ describe("card-checks", () => { checkCardEligibility( cardNumber, cardType, - PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE - ) + PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + ), ).toBe(true); }); @@ -216,8 +216,8 @@ describe("card-checks", () => { checkCardEligibility( cardNumber, cardType, - PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE - ) + PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + ), ).toBe(false); }); @@ -238,8 +238,8 @@ describe("card-checks", () => { checkCardEligibility( cardNumber, cardType, - PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE - ) + PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + ), ).toBe(false); }); @@ -255,11 +255,11 @@ describe("card-checks", () => { checkCardEligibility( cardNumber, cardType, - PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE - ) + PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + ), ).toBe(false); expect( - checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE) + checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE), ).toBe(false); }); @@ -275,11 +275,11 @@ describe("card-checks", () => { checkCardEligibility( cardNumber, cardType, - PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE - ) + PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + ), ).toBe(false); expect( - checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE) + checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE), ).toBe(false); }); @@ -290,11 +290,11 @@ describe("card-checks", () => { checkCardEligibility( cardNumber, cardType, - PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE - ) + PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + ), ).toBe(false); expect( - checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE) + checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE), ).toBe(false); }); @@ -305,11 +305,11 @@ describe("card-checks", () => { checkCardEligibility( cardNumber, cardType, - PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE - ) + PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + ), ).toBe(true); expect( - checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE) + checkCardEligibility(cardNumber, cardType, PAYMENT_FLOWS.WITH_PURCHASE), ).toBe(true); }); }); diff --git a/src/card/lib/card-focus.js b/src/card/lib/card-focus.js index 89c5288a3b..b7d570a10e 100644 --- a/src/card/lib/card-focus.js +++ b/src/card/lib/card-focus.js @@ -1,54 +1,72 @@ /* @flow */ -import { noop } from '@krakenjs/belter'; +import { noop } from "@krakenjs/belter"; -import type { CardNavigation, InputEvent } from '../types'; +import type { CardNavigation, InputEvent } from "../types"; -export const defaultNavigation : CardNavigation = { - next: () => noop, - previous: () => noop +export const defaultNavigation: CardNavigation = { + next: () => noop, + previous: () => noop, }; // Move cursor within a field -export function moveCursor(element : HTMLInputElement, start : number, end? : number) : void { - window.requestAnimationFrame(() => { - element.selectionStart = start; - element.selectionEnd = end ?? start; - }); +export function moveCursor( + element: HTMLInputElement, + start: number, + end?: number, +): void { + window.requestAnimationFrame(() => { + element.selectionStart = start; + element.selectionEnd = end ?? start; + }); } // Navigation helper to go to the next field putting the cursor at the start -export function goToNextField(ref : {| current : {| base : HTMLInputElement |} |}) : () => void { - return () => { - moveCursor(ref.current.base, 0); - setTimeout(() => ref.current.base.focus()); - }; +export function goToNextField(ref: {| + current: {| base: HTMLInputElement |}, +|}): () => void { + return () => { + moveCursor(ref.current.base, 0); + setTimeout(() => ref.current.base.focus()); + }; } // Navigation helper to go to the previous field putting the curser at the end -export function goToPreviousField(ref : {| current : {| base : HTMLInputElement |} |}) : () => void { - return () => { - const { value } = ref.current.base; - - if (value) { - const valueLength = value.length; - moveCursor(ref.current.base, valueLength); - } - setTimeout(() => ref.current.base.focus()); - }; +export function goToPreviousField(ref: {| + current: {| base: HTMLInputElement |}, +|}): () => void { + return () => { + const { value } = ref.current.base; + + if (value) { + const valueLength = value.length; + moveCursor(ref.current.base, valueLength); + } + setTimeout(() => ref.current.base.focus()); + }; } // Navigate between fields using the arrow keys and/or the backspace -export function navigateOnKeyDown(event : InputEvent, navigation : CardNavigation) : void { - const { target: { value, selectionStart, selectionEnd }, key } = event; - - if (selectionStart === 0 && (value.length === 0 || value.length !== selectionEnd) && [ 'Backspace', 'ArrowLeft' ].includes(key)) { - navigation.previous(); - } - - if (selectionStart === value.length && [ 'ArrowRight' ].includes(key)) { - navigation.next(); - } +export function navigateOnKeyDown( + event: InputEvent, + navigation: CardNavigation, +): void { + const { + target: { value, selectionStart, selectionEnd }, + key, + } = event; + + if ( + selectionStart === 0 && + (value.length === 0 || value.length !== selectionEnd) && + ["Backspace", "ArrowLeft"].includes(key) + ) { + navigation.previous(); + } + + if (selectionStart === value.length && ["ArrowRight"].includes(key)) { + navigation.next(); + } } // Safari (both iOS and Desktop) has an unconvential behavior, @@ -57,59 +75,59 @@ export function navigateOnKeyDown(event : InputEvent, navigation : CardNavigatio // Big props to the devs at Stripe that figured out // you run this selection range hack to force the focus back // onto the input. -function applyFocusWorkaroundForSafari (input : HTMLInputElement) { - const inputIsEmptyInitially = input.value === ''; +function applyFocusWorkaroundForSafari(input: HTMLInputElement) { + const inputIsEmptyInitially = input.value === ""; - // Safari can't set selection if the input is empty - if (inputIsEmptyInitially) { - input.value = ' '; - } + // Safari can't set selection if the input is empty + if (inputIsEmptyInitially) { + input.value = " "; + } - const start = input.selectionStart; - const end = input.selectionEnd; + const start = input.selectionStart; + const end = input.selectionEnd; - input.setSelectionRange(0, 0); - input.setSelectionRange(start, end); + input.setSelectionRange(0, 0); + input.setSelectionRange(start, end); - if (inputIsEmptyInitially) { - input.value = ''; - } + if (inputIsEmptyInitially) { + input.value = ""; + } } // With some browsers, when the focus transitions to the iframe, // the browser will pass the focus on to the first input field. // This is to handle the case when that doesn't happen. // In this case the iframe itself will receive focus and this will need to shift the focus to the input field. -export function autoFocusOnFirstInput(input? : HTMLInputElement) { - if (!input) { - return; - } - - let timeoutID = null; - - // Listen for when the iframe gets focus. - window.addEventListener('focus', () => { - // If the iframe gets focus, then wait for the next event loop to set the focus on the input field. - // This allows the below focusin listener to prevent shifting the focus if the input already has the focus. - timeoutID = setTimeout(() => { - timeoutID = null; - - applyFocusWorkaroundForSafari(input); - - // for Safari, setting the selection range is enough to give - // it focus, but Firefox requires an explicit focus call. - // Also, just calling `focus` on Safari does not work at all - input.focus(); - }); - }); - - // Listen for when the input field gets focus. - window.addEventListener('focusin', (event) => { - // If there is a set timeout waiting to happen, then clear the timeout. - // This will prevent the above from unnecessarily setting the focus. - if (timeoutID && event.target instanceof HTMLInputElement) { - clearTimeout(timeoutID); - timeoutID = null; - } +export function autoFocusOnFirstInput(input?: HTMLInputElement) { + if (!input) { + return; + } + + let timeoutID = null; + + // Listen for when the iframe gets focus. + window.addEventListener("focus", () => { + // If the iframe gets focus, then wait for the next event loop to set the focus on the input field. + // This allows the below focusin listener to prevent shifting the focus if the input already has the focus. + timeoutID = setTimeout(() => { + timeoutID = null; + + applyFocusWorkaroundForSafari(input); + + // for Safari, setting the selection range is enough to give + // it focus, but Firefox requires an explicit focus call. + // Also, just calling `focus` on Safari does not work at all + input.focus(); }); + }); + + // Listen for when the input field gets focus. + window.addEventListener("focusin", (event) => { + // If there is a set timeout waiting to happen, then clear the timeout. + // This will prevent the above from unnecessarily setting the focus. + if (timeoutID && event.target instanceof HTMLInputElement) { + clearTimeout(timeoutID); + timeoutID = null; + } + }); } diff --git a/src/card/lib/card-focus.test.js b/src/card/lib/card-focus.test.js index 197f958436..795e083ae2 100644 --- a/src/card/lib/card-focus.test.js +++ b/src/card/lib/card-focus.test.js @@ -46,11 +46,11 @@ describe("autoFocusOnFirstInput", () => { expect(window.addEventListener).toBeCalledTimes(2); expect(window.addEventListener).toBeCalledWith( "focus", - expect.any(Function) + expect.any(Function), ); expect(window.addEventListener).toBeCalledWith( "focusin", - expect.any(Function) + expect.any(Function), ); }); diff --git a/src/card/lib/card-utils.js b/src/card/lib/card-utils.js index cb18a4ad63..48537a364b 100644 --- a/src/card/lib/card-utils.js +++ b/src/card/lib/card-utils.js @@ -1,424 +1,487 @@ /* eslint-disable flowtype/require-exact-type */ /* @flow */ -import { values } from '@krakenjs/belter'; +import { values } from "@krakenjs/belter"; import type { PaymentSourceInput } from "../../api/vault"; -import type { InputState, FieldValidity, Card, ExtraFields, CardType, ParsedCardType, PaymentSourceCardInput, ReformattedPaymentSourceCardInput } from '../types'; +import type { + InputState, + FieldValidity, + Card, + ExtraFields, + CardType, + ParsedCardType, + PaymentSourceCardInput, + ReformattedPaymentSourceCardInput, +} from "../types"; import { - CARD_ERRORS, - CARD_FIELD_TYPE, - DEFAULT_STYLE, - FIELD_STYLE, - FILTER_CSS_SELECTORS, - FILTER_CSS_VALUES, - GQL_ERRORS, - VALID_EXTRA_FIELDS, - ALLOWED_ATTRIBUTES, - OPTIONAL_CARD_FIELDS -} from '../constants'; -import { getLogger } from '../../lib'; - -export const defaultInputState : InputState = { - inputValue: '', - maskedInputValue: '', - cursorStart: 0, - cursorEnd: 0, - isFocused: false, - keyStrokeCount: 0, - isPotentiallyValid: true, - isValid: false + CARD_ERRORS, + CARD_FIELD_TYPE, + DEFAULT_STYLE, + FIELD_STYLE, + FILTER_CSS_SELECTORS, + FILTER_CSS_VALUES, + GQL_ERRORS, + VALID_EXTRA_FIELDS, + ALLOWED_ATTRIBUTES, + OPTIONAL_CARD_FIELDS, +} from "../constants"; +import { getLogger } from "../../lib"; + +export const defaultInputState: InputState = { + inputValue: "", + maskedInputValue: "", + cursorStart: 0, + cursorEnd: 0, + isFocused: false, + keyStrokeCount: 0, + isPotentiallyValid: true, + isValid: false, }; -export const initFieldValidity : FieldValidity = { isValid: false, isPotentiallyValid: true }; +export const initFieldValidity: FieldValidity = { + isValid: false, + isPotentiallyValid: true, +}; -export function splice(str : string, idx : number, insert : string) : string { - return str.slice(0, idx) + insert + str.slice(idx); +export function splice(str: string, idx: number, insert: string): string { + return str.slice(0, idx) + insert + str.slice(idx); } -export function assertType(assertion : () => void, errorMsg : string) : void | TypeError { - if (!assertion) { - throw new TypeError(errorMsg); - } +export function assertType( + assertion: () => void, + errorMsg: string, +): void | TypeError { + if (!assertion) { + throw new TypeError(errorMsg); + } } -export function assertString(...args : T) : void | TypeError { +export function assertString(...args: T): void | TypeError { + assertType( // $FlowFixMe - assertType(args.every((s) => typeof s === 'string'), 'Expected a string'); + args.every((s) => typeof s === "string"), + "Expected a string", + ); } -export function removeSpaces(value : string) : string { - return value.replace(/\s/g, ''); +export function removeSpaces(value: string): string { + return value.replace(/\s/g, ""); } // Return the last 4 digits of a valid card number -export function maskValidCard(number : string) : string { - const trimmedValue = removeSpaces(number); - const lastFour = trimmedValue.slice(-4); - const maskedNumber = number.replace(/\d/g, '•').slice(0, -4); +export function maskValidCard(number: string): string { + const trimmedValue = removeSpaces(number); + const lastFour = trimmedValue.slice(-4); + const maskedNumber = number.replace(/\d/g, "•").slice(0, -4); - return maskedNumber + lastFour; + return maskedNumber + lastFour; } -export function shouldUseZeroPaddedExpiryPattern(value: string, key: string) : boolean { - if (value.length === 0) { - return false; - } - if (value[0] === "1" && key === "/") { - return true; - } - if (value[0] !== "1" && value[0] !== "0") { - return true; - } - if (value[0] === "1") { - return false; - } +export function shouldUseZeroPaddedExpiryPattern( + value: string, + key: string, +): boolean { + if (value.length === 0) { return false; + } + if (value[0] === "1" && key === "/") { + return true; + } + if (value[0] !== "1" && value[0] !== "0") { + return true; + } + if (value[0] === "1") { + return false; + } + return false; } // from https://github.com/braintree/inject-stylesheet/blob/main/src/lib/filter-style-values.ts -function isValidValue(value : string | number) : boolean { - return !FILTER_CSS_VALUES.some((regex) => regex.test(String(value))); +function isValidValue(value: string | number): boolean { + return !FILTER_CSS_VALUES.some((regex) => regex.test(String(value))); } // from https://github.com/braintree/inject-stylesheet/blob/main/src/lib/validate-selector.ts -function isValidSelector(selector : string) : boolean { - return !FILTER_CSS_SELECTORS.some((regex) => regex.test(selector)); +function isValidSelector(selector: string): boolean { + return !FILTER_CSS_SELECTORS.some((regex) => regex.test(selector)); } -export function isValidAttribute(attribute: string) : boolean { - if(!ALLOWED_ATTRIBUTES.includes(attribute.toLocaleLowerCase())) { - getLogger().warn('attribute_warning', { warn: `HTML Attribute "${attribute}" was ignored. See allowed attribute list.`}) - return false - }; +export function isValidAttribute(attribute: string): boolean { + if (!ALLOWED_ATTRIBUTES.includes(attribute.toLocaleLowerCase())) { + getLogger().warn("attribute_warning", { + warn: `HTML Attribute "${attribute}" was ignored. See allowed attribute list.`, + }); + return false; + } - return true + return true; } -export function filterStyle(style : Object) : Object { - const result = {}; - Object.keys(style).forEach((key) => { - const value = style[key]; - // if the key is pointing to a string or a number, it must be a CSS property - if (typeof value === 'string' || typeof value === 'number') { - // so normalize the property name and filter based on FIELD_STYLE (allow list) - let property; - if (FIELD_STYLE[key]) { - // normalize from camelCase to kebab-case - property = FIELD_STYLE[key]; - if (isValidValue(value)) { - result[property] = value; - } - } else if (values(FIELD_STYLE).includes(key.toLowerCase())) { - // normalize to lower case - property = key.toLowerCase(); - if (isValidValue(value)) { - result[property] = value; - } - } else { - getLogger().warn('style_warning', { warn: `CSS property "${key}" was ignored. See allowed CSS property list.`}); - } - // if the key is pointing to an object, it must be a CSS selector - } else if (typeof value === 'object') { - if (isValidSelector(key)) { - // so normalize the object it's pointing to - result[key] = filterStyle(value); - } +export function filterStyle(style: Object): Object { + const result = {}; + Object.keys(style).forEach((key) => { + const value = style[key]; + // if the key is pointing to a string or a number, it must be a CSS property + if (typeof value === "string" || typeof value === "number") { + // so normalize the property name and filter based on FIELD_STYLE (allow list) + let property; + if (FIELD_STYLE[key]) { + // normalize from camelCase to kebab-case + property = FIELD_STYLE[key]; + if (isValidValue(value)) { + result[property] = value; } - }); - return result; + } else if (values(FIELD_STYLE).includes(key.toLowerCase())) { + // normalize to lower case + property = key.toLowerCase(); + if (isValidValue(value)) { + result[property] = value; + } + } else { + getLogger().warn("style_warning", { + warn: `CSS property "${key}" was ignored. See allowed CSS property list.`, + }); + } + // if the key is pointing to an object, it must be a CSS selector + } else if (typeof value === "object") { + if (isValidSelector(key)) { + // so normalize the object it's pointing to + result[key] = filterStyle(value); + } + } + }); + return result; } // Converts style object to valid style string -export function styleToString(style : Object = { }) : string { - const s = []; - Object.keys(style).forEach((key) => { - const value = style[key]; - if (typeof value === 'string' || typeof value === 'number') { - s.push(` ${ key }: ${ value };`); - } else if (typeof value === 'object') { - s.push(`${ key } {`); - s.push(styleToString(value)); - s.push('}'); - } - }); - return s.join('\n'); +export function styleToString(style: Object = {}): string { + const s = []; + Object.keys(style).forEach((key) => { + const value = style[key]; + if (typeof value === "string" || typeof value === "number") { + s.push(` ${key}: ${value};`); + } else if (typeof value === "object") { + s.push(`${key} {`); + s.push(styleToString(value)); + s.push("}"); + } + }); + return s.join("\n"); } // convert default and custom styles to CSS text -export function getCSSText(cardFieldStyle : Object, customStyle : Object) : string { - const s = []; - s.push('/* default style */'); - s.push(styleToString(DEFAULT_STYLE)); - s.push(styleToString(cardFieldStyle)); - s.push('/* custom style */'); - s.push(styleToString(filterStyle(customStyle))); - return s.join('\n'); +export function getCSSText( + cardFieldStyle: Object, + customStyle: Object, +): string { + const s = []; + s.push("/* default style */"); + s.push(styleToString(DEFAULT_STYLE)); + s.push(styleToString(cardFieldStyle)); + s.push("/* custom style */"); + s.push(styleToString(filterStyle(customStyle))); + return s.join("\n"); } export function isFieldOptional(element: HTMLInputElement): boolean { - return OPTIONAL_CARD_FIELDS.includes(element.name); + return OPTIONAL_CARD_FIELDS.includes(element.name); } // mark the ref's HTMLElement as valid or invalid -export function markValidity(ref : Object, validity : FieldValidity, hasFocus?: boolean, touched?: boolean) { - const element: HTMLInputElement = ref?.current?.base; - if (element) { - if (isFieldOptional(element) && element.value.length === 0) { - element.classList.remove('valid'); - element.classList.remove('invalid'); - } else if (validity.isValid || (validity.isPotentiallyValid && hasFocus)) { - element.classList.add('valid'); - element.classList.remove('invalid'); - } else if(touched){ - element.classList.add('invalid'); - element.classList.remove('valid'); - } +export function markValidity( + ref: Object, + validity: FieldValidity, + hasFocus?: boolean, + touched?: boolean, +) { + const element: HTMLInputElement = ref?.current?.base; + if (element) { + if (isFieldOptional(element) && element.value.length === 0) { + element.classList.remove("valid"); + element.classList.remove("invalid"); + } else if (validity.isValid || (validity.isPotentiallyValid && hasFocus)) { + element.classList.add("valid"); + element.classList.remove("invalid"); + } else if (touched) { + element.classList.add("invalid"); + element.classList.remove("valid"); } + } } -export function removeNonDigits(value : string) : string { - const trimmedValue = removeSpaces(value); - return trimmedValue.replace(/\D/g, ''); +export function removeNonDigits(value: string): string { + const trimmedValue = removeSpaces(value); + return trimmedValue.replace(/\D/g, ""); } -export function checkForNonDigits(value : string) : boolean { - return (/\D/g).test(removeSpaces(value)); +export function checkForNonDigits(value: string): boolean { + return /\D/g.test(removeSpaces(value)); } -export function setErrors({ isCardEligible, isNumberValid, isCvvValid, isExpiryValid, isNameValid, isPostalCodeValid, gqlErrorsObject = {} } : {| isCardEligible? : boolean, isNumberValid? : boolean, isCvvValid? : boolean, isExpiryValid? : boolean, isNameValid? : boolean, isPostalCodeValid? : boolean, gqlErrorsObject? : {| field : string, errors : [] |} |}) : [$Values] | [] { - const errors = []; - const { field, errors: gqlErrors } = gqlErrorsObject; - - if (isCardEligible === false) { - if (field === CARD_FIELD_TYPE.NUMBER && gqlErrors.length) { - errors.push(...gqlErrors); - } else { - errors.push(CARD_ERRORS.INELIGIBLE_CARD_VENDOR); - } +export function setErrors({ + isCardEligible, + isNumberValid, + isCvvValid, + isExpiryValid, + isNameValid, + isPostalCodeValid, + gqlErrorsObject = {}, +}: {| + isCardEligible?: boolean, + isNumberValid?: boolean, + isCvvValid?: boolean, + isExpiryValid?: boolean, + isNameValid?: boolean, + isPostalCodeValid?: boolean, + gqlErrorsObject?: {| field: string, errors: [] |}, +|}): [$Values] | [] { + const errors = []; + const { field, errors: gqlErrors } = gqlErrorsObject; + + if (isCardEligible === false) { + if (field === CARD_FIELD_TYPE.NUMBER && gqlErrors.length) { + errors.push(...gqlErrors); + } else { + errors.push(CARD_ERRORS.INELIGIBLE_CARD_VENDOR); } + } - if (isNumberValid === false) { - if (field === CARD_FIELD_TYPE.NUMBER && gqlErrors.length) { - errors.push(...gqlErrors); - } else { - errors.push(CARD_ERRORS.INVALID_NUMBER); - } + if (isNumberValid === false) { + if (field === CARD_FIELD_TYPE.NUMBER && gqlErrors.length) { + errors.push(...gqlErrors); + } else { + errors.push(CARD_ERRORS.INVALID_NUMBER); } + } - if (isExpiryValid === false) { - if (field === CARD_FIELD_TYPE.EXPIRY && gqlErrors.length) { - errors.push(...gqlErrors); - } else { - errors.push(CARD_ERRORS.INVALID_EXPIRY); - } + if (isExpiryValid === false) { + if (field === CARD_FIELD_TYPE.EXPIRY && gqlErrors.length) { + errors.push(...gqlErrors); + } else { + errors.push(CARD_ERRORS.INVALID_EXPIRY); } + } - if (isCvvValid === false) { - if (field === CARD_FIELD_TYPE.CVV && gqlErrors.length) { - errors.push(...gqlErrors); - } else { - errors.push(CARD_ERRORS.INVALID_CVV); - } + if (isCvvValid === false) { + if (field === CARD_FIELD_TYPE.CVV && gqlErrors.length) { + errors.push(...gqlErrors); + } else { + errors.push(CARD_ERRORS.INVALID_CVV); } + } - if (isNameValid === false) { - if (field === CARD_FIELD_TYPE.NAME && gqlErrors.length) { - errors.push(...gqlErrors); - } else { - errors.push(CARD_ERRORS.INVALID_NAME); - } + if (isNameValid === false) { + if (field === CARD_FIELD_TYPE.NAME && gqlErrors.length) { + errors.push(...gqlErrors); + } else { + errors.push(CARD_ERRORS.INVALID_NAME); } + } - if (isPostalCodeValid === false) { - if (field === CARD_FIELD_TYPE.POSTAL && gqlErrors.length) { - errors.push(...gqlErrors); - } else { - errors.push(CARD_ERRORS.INVALID_POSTAL); - } + if (isPostalCodeValid === false) { + if (field === CARD_FIELD_TYPE.POSTAL && gqlErrors.length) { + errors.push(...gqlErrors); + } else { + errors.push(CARD_ERRORS.INVALID_POSTAL); } + } - return errors; + return errors; } // Format expity date to MM/YYYY -export function convertDateFormat(date : string) : string { - const trimmedDate = removeSpaces(date); - const splittedDate = trimmedDate.split('/'); - let formattedDate = trimmedDate; - - if (splittedDate[1] && splittedDate[1].length === 2) { - splittedDate[1] = `20${ splittedDate[1] }`; - formattedDate = splittedDate.join('/'); - } +export function convertDateFormat(date: string): string { + const trimmedDate = removeSpaces(date); + const splittedDate = trimmedDate.split("/"); + let formattedDate = trimmedDate; + + if (splittedDate[1] && splittedDate[1].length === 2) { + splittedDate[1] = `20${splittedDate[1]}`; + formattedDate = splittedDate.join("/"); + } - return formattedDate; + return formattedDate; } // Parse errors from ProcessPayment GQL mutation -export function parseGQLErrors(errorsObject : Object) : {| parsedErrors : $ReadOnlyArray, errors : $ReadOnlyArray, errorsMap : Object |} { - const { data } = errorsObject; - - const parsedErrors = []; - const errors = []; - const errorsMap = {}; - - if (Array.isArray(data) && data.length) { - data.forEach(e => { - const { details } = e; - - if (Array.isArray(details) && details.length) { - details.forEach(d => { - errors.push(d); - - let parsedError; - if (d.field && d.issue && d.description) { - parsedError = GQL_ERRORS[d.field][d.issue] ?? `${ d.issue }: ${ d.description }`; - const field = d.field.split('/').pop(); - - if (!errorsMap[field]) { - errorsMap[field] = []; - } - - errorsMap[field].push(parsedError); - - } else if (d.issue && d.description) { - parsedError = GQL_ERRORS[d.issue] ?? `${ d.issue }: ${ d.description }`; - } - - if (parsedError) { - parsedErrors.push(parsedError); - } - - }); +export function parseGQLErrors(errorsObject: Object): {| + parsedErrors: $ReadOnlyArray, + errors: $ReadOnlyArray, + errorsMap: Object, +|} { + const { data } = errorsObject; + + const parsedErrors = []; + const errors = []; + const errorsMap = {}; + + if (Array.isArray(data) && data.length) { + data.forEach((e) => { + const { details } = e; + + if (Array.isArray(details) && details.length) { + details.forEach((d) => { + errors.push(d); + + let parsedError; + if (d.field && d.issue && d.description) { + parsedError = + GQL_ERRORS[d.field][d.issue] ?? `${d.issue}: ${d.description}`; + const field = d.field.split("/").pop(); + + if (!errorsMap[field]) { + errorsMap[field] = []; } + + errorsMap[field].push(parsedError); + } else if (d.issue && d.description) { + parsedError = GQL_ERRORS[d.issue] ?? `${d.issue}: ${d.description}`; + } + + if (parsedError) { + parsedErrors.push(parsedError); + } }); - } + } + }); + } - return { - errors, - parsedErrors, - errorsMap - }; + return { + errors, + parsedErrors, + errorsMap, + }; } -export function filterExtraFields(extraData : Object) : ExtraFields | Object { - if (!extraData || typeof extraData !== 'object' || Array.isArray(extraData)) { - return {}; - } +export function filterExtraFields(extraData: Object): ExtraFields | Object { + if (!extraData || typeof extraData !== "object" || Array.isArray(extraData)) { + return {}; + } - return Object.keys(extraData).reduce((acc, key) => { - if (VALID_EXTRA_FIELDS.includes(key)) { - acc[key] = extraData[key]; - } - return acc; - }, {}); + return Object.keys(extraData).reduce((acc, key) => { + if (VALID_EXTRA_FIELDS.includes(key)) { + acc[key] = extraData[key]; + } + return acc; + }, {}); } - -export function parsedCardType(potentialCardTypes: $ReadOnlyArray) : $ReadOnlyArray { - - return potentialCardTypes.map(({ type, niceType, code }) => ({ - type, niceType, code - })); - +export function parsedCardType( + potentialCardTypes: $ReadOnlyArray, +): $ReadOnlyArray { + return potentialCardTypes.map(({ type, niceType, code }) => ({ + type, + niceType, + code, + })); } -export function getContext(win : Object) : string { - return win.xprops?.parent?.uid || win.xprops?.uid; +export function getContext(win: Object): string { + return win.xprops?.parent?.uid || win.xprops?.uid; } export function cardExpiryToPaymentSourceExpiry(dateString: string): string { - if (!dateString || typeof dateString !== "string") { - throw new Error(`can not convert invalid expiry date: ${dateString}`); - } - - // "2020-12" - const YYYYmmRegex = "^[0-9]{4}-([1-9]|0[1-9]|1[0-2])$"; - // 12/20 OR 12/2020 - const mmYYYYRegex = "^([1-9]|0[1-9]|1[0-2])/?([0-9]{4}|[0-9]{2})$"; - - if (dateString.match(YYYYmmRegex)) { - return dateString; - } - - if (dateString.match(mmYYYYRegex)) { - const [monthString, yearString] = dateString.split("/"); + if (!dateString || typeof dateString !== "string") { + throw new Error(`can not convert invalid expiry date: ${dateString}`); + } - const formattedYearString = - yearString.length === 2 ? `20${yearString}` : yearString; - const formattedMonthString = - monthString.length === 1 ? `0${monthString}` : monthString; + // "2020-12" + const YYYYmmRegex = "^[0-9]{4}-([1-9]|0[1-9]|1[0-2])$"; + // 12/20 OR 12/2020 + const mmYYYYRegex = "^([1-9]|0[1-9]|1[0-2])/?([0-9]{4}|[0-9]{2})$"; - return `${formattedYearString}-${formattedMonthString}`; - } + if (dateString.match(YYYYmmRegex)) { + return dateString; + } - throw new Error(`can not convert invalid expiry date: ${dateString}`); -}; + if (dateString.match(mmYYYYRegex)) { + const [monthString, yearString] = dateString.split("/"); -export function convertCardToPaymentSource(card: Card, extraFields: ?ExtraFields): PaymentSourceInput { - const paymentSource = { - card: { - number: card.number, - securityCode: card.cvv, - expiry: cardExpiryToPaymentSourceExpiry(card.expiry), - }, - }; - - if (extraFields && Object.keys(extraFields).length !== 0) { - // $FlowIssue - paymentSource.card.billingAddress = extraFields.billingAddress; - } + const formattedYearString = + yearString.length === 2 ? `20${yearString}` : yearString; + const formattedMonthString = + monthString.length === 1 ? `0${monthString}` : monthString; - if (card.name) { - // $FlowIssue - paymentSource.card.name = card.name; - } + return `${formattedYearString}-${formattedMonthString}`; + } - if (card.postalCode) { - // $FlowIssue - paymentSource.card.billingAddress = { postalCode: card.postalCode }; - } + throw new Error(`can not convert invalid expiry date: ${dateString}`); +} - return paymentSource; -}; +export function convertCardToPaymentSource( + card: Card, + extraFields: ?ExtraFields, +): PaymentSourceInput { + const paymentSource = { + card: { + number: card.number, + securityCode: card.cvv, + expiry: cardExpiryToPaymentSourceExpiry(card.expiry), + }, + }; + + if (extraFields && Object.keys(extraFields).length !== 0) { + // $FlowIssue + paymentSource.card.billingAddress = extraFields.billingAddress; + } + + if (card.name) { + // $FlowIssue + paymentSource.card.name = card.name; + } + + if (card.postalCode) { + // $FlowIssue + paymentSource.card.billingAddress = { postalCode: card.postalCode }; + } + + return paymentSource; +} export function kebabToCamelCase(field: string): string { - const camelCase = field.split("-"); - camelCase.forEach((word, i) => { - camelCase[i] = i !== 0 ? word.toLowerCase().replace(/^\w/, c => c.toUpperCase()) : word.toLowerCase(); - - }) - return camelCase.join(""); + const camelCase = field.split("-"); + camelCase.forEach((word, i) => { + camelCase[i] = + i !== 0 + ? word.toLowerCase().replace(/^\w/, (c) => c.toUpperCase()) + : word.toLowerCase(); + }); + return camelCase.join(""); } // Taken from https://github.com/braintree/braintree-web/blob/main/src/lib/camel-case-to-snake-case.js -export function reformatBillingKeys(str : string): string { - return str +export function reformatBillingKeys(str: string): string { + return str .replace(/([a-z\d])([A-Z])/g, "$1_$2") .replace(/([a-z\d])(\d)/g, "$1_$2") - .toLowerCase() + .toLowerCase(); } -export function reformatPaymentSource(paymentSource: PaymentSourceCardInput) : ReformattedPaymentSourceCardInput | {} { - - return Object.keys(paymentSource).reduce((newObj, key) => { - const transformedKey = reformatBillingKeys(key) - - if (key === 'billingAddress') { - if (paymentSource.billingAddress && Object.keys(paymentSource.billingAddress).length !== 0) { - newObj.billing_address = {}; - Object.keys(paymentSource.billingAddress).forEach((billingKey) => { - const snakeCaseBillingKey = reformatBillingKeys(billingKey); - // $FlowIssue - newObj.billing_address[snakeCaseBillingKey] = paymentSource.billingAddress[billingKey]; - }); - } - } else { - newObj[transformedKey] = paymentSource[key]; - } +export function reformatPaymentSource( + paymentSource: PaymentSourceCardInput, +): ReformattedPaymentSourceCardInput | {} { + return Object.keys(paymentSource).reduce((newObj, key) => { + const transformedKey = reformatBillingKeys(key); + + if (key === "billingAddress") { + if ( + paymentSource.billingAddress && + Object.keys(paymentSource.billingAddress).length !== 0 + ) { + newObj.billing_address = {}; + Object.keys(paymentSource.billingAddress).forEach((billingKey) => { + const snakeCaseBillingKey = reformatBillingKeys(billingKey); + newObj.billing_address[snakeCaseBillingKey] = + // $FlowIssue + paymentSource.billingAddress[billingKey]; + }); + } + } else { + newObj[transformedKey] = paymentSource[key]; + } - return newObj - }, {}) + return newObj; + }, {}); } /* eslint-enable flowtype/require-exact-type */ diff --git a/src/card/lib/card-utils.test.js b/src/card/lib/card-utils.test.js index 89c6b0d5b6..769d382a69 100644 --- a/src/card/lib/card-utils.test.js +++ b/src/card/lib/card-utils.test.js @@ -130,7 +130,7 @@ describe("card utils", () => { "should convert card object to payment source: %s", (_, card, paymentSource) => { expect(convertCardToPaymentSource(card)).toEqual(paymentSource); - } + }, ); test("should throw error for bad date", () => { @@ -139,7 +139,7 @@ describe("card utils", () => { number: testCard, expiry: badDate, cvv: testSecurityCode, - }) + }), ).toThrowError(`can not convert invalid expiry date: ${badDate}`); }); }); @@ -371,7 +371,7 @@ describe("card utils", () => { expect(parsedErrors.length).toBe(1); expect(parsedErrors[0]).toBe( - "PERMISSION_DENIED: You do not have permission to access or perform operations on this resource." + "PERMISSION_DENIED: You do not have permission to access or perform operations on this resource.", ); expect(errors.length).toBe(1); @@ -623,7 +623,7 @@ describe("card utils", () => { expect(parsedErrors.length).toBe(1); expect(parsedErrors[0]).toBe( - "PERMISSION_DENIED: You do not have permission to access or perform operations on this resource." + "PERMISSION_DENIED: You do not have permission to access or perform operations on this resource.", ); expect(errors.length).toBe(1); @@ -725,7 +725,7 @@ describe("card utils", () => { expect(parsedErrors.length).toBe(1); expect(parsedErrors[0]).toBe( - "PERMISSION_DENIED: You do not have permission to access or perform operations on this resource." + "PERMISSION_DENIED: You do not have permission to access or perform operations on this resource.", ); expect(errors.length).toBe(1); @@ -748,7 +748,7 @@ describe("styleToString", () => { // $FlowIssue doesn't know about replaceAll expect(stringStyle.trim().replaceAll("\n", "")).toEqual( - 'height: 60px; padding: 10px; fontSize: 18px; fontFamily: "Open Sans", sans-serif; transition: all 0.5s ease-out;'.trim() + 'height: 60px; padding: 10px; fontSize: 18px; fontFamily: "Open Sans", sans-serif; transition: all 0.5s ease-out;'.trim(), ); }); }); @@ -1151,7 +1151,7 @@ describe("filterExtraFields", () => { }; expect(reformatPaymentSource(paymentSource)).toStrictEqual( - reformatted_payment_source + reformatted_payment_source, ); }); @@ -1172,7 +1172,7 @@ describe("filterExtraFields", () => { }; expect(reformatPaymentSource(paymentSource)).toStrictEqual( - reformatted_payment_source + reformatted_payment_source, ); }); @@ -1193,7 +1193,7 @@ describe("filterExtraFields", () => { }; // $FlowIssue expect(reformatPaymentSource(paymentSource)).toStrictEqual( - reformatted_payment_source + reformatted_payment_source, ); }); }); diff --git a/src/card/lib/exports.js b/src/card/lib/exports.js index 3c8fed3cc3..f028fef14c 100644 --- a/src/card/lib/exports.js +++ b/src/card/lib/exports.js @@ -1,42 +1,51 @@ /* @flow */ -import { FRAME_NAME } from '../../constants'; -import { type CardType } from '../types'; +import { FRAME_NAME } from "../../constants"; +import { type CardType } from "../types"; export type ExportsOptions = {| - name : $Values, - isFieldValid : () => boolean, - isFieldPotentiallyValid : () => boolean, - getPotentialCardTypes : () => $ReadOnlyArray, - isFieldFocused : () => boolean, - // eslint-disable-next-line no-undef - getFieldValue : () => T, - setGqlErrors : ({| field : string, errors : [] |}) => void, - resetGQLErrors : () => void + name: $Values, + isFieldValid: () => boolean, + isFieldPotentiallyValid: () => boolean, + getPotentialCardTypes: () => $ReadOnlyArray, + isFieldFocused: () => boolean, + // eslint-disable-next-line no-undef + getFieldValue: () => T, + setGqlErrors: ({| field: string, errors: [] |}) => void, + resetGQLErrors: () => void, |}; export type CardExports = {| - name : $Values, - isFieldValid : () => boolean, - isFieldPotentiallyValid : () => boolean, - getPotentialCardTypes : () => $ReadOnlyArray, - isFieldFocused: () => boolean, - getFieldValue : () => V, - setGqlErrors : ({| field : string, errors : [] |}) => void, - resetGQLErrors : () => void + name: $Values, + isFieldValid: () => boolean, + isFieldPotentiallyValid: () => boolean, + getPotentialCardTypes: () => $ReadOnlyArray, + isFieldFocused: () => boolean, + getFieldValue: () => V, + setGqlErrors: ({| field: string, errors: [] |}) => void, + resetGQLErrors: () => void, |}; -export function setupExports({ name, isFieldValid, isFieldFocused, isFieldPotentiallyValid, getFieldValue, setGqlErrors, resetGQLErrors, getPotentialCardTypes } : ExportsOptions) { - const xports : CardExports = { - name, - isFieldValid, - isFieldPotentiallyValid, - getPotentialCardTypes, - isFieldFocused, - getFieldValue, - setGqlErrors, - resetGQLErrors - }; +export function setupExports({ + name, + isFieldValid, + isFieldFocused, + isFieldPotentiallyValid, + getFieldValue, + setGqlErrors, + resetGQLErrors, + getPotentialCardTypes, +}: ExportsOptions) { + const xports: CardExports = { + name, + isFieldValid, + isFieldPotentiallyValid, + getPotentialCardTypes, + isFieldFocused, + getFieldValue, + setGqlErrors, + resetGQLErrors, + }; - window.exports = xports; + window.exports = xports; } diff --git a/src/card/lib/methods.js b/src/card/lib/methods.js index 579ef60b61..c3fff425d5 100644 --- a/src/card/lib/methods.js +++ b/src/card/lib/methods.js @@ -1,50 +1,61 @@ /* @flow */ -import { isValidAttribute } from './card-utils'; +import { isValidAttribute } from "./card-utils"; -export function exportMethods(ref : Object, setAttributes : Function, setInputState? : Function, ariaMessageRef: Object) : void { - window.xprops.export({ - setAttribute: (name, value) => { - if (isValidAttribute(name)) { - setAttributes((currentAttributes) => { - return { - ...currentAttributes, - [name]: value - } - }); - } - }, - removeAttribute: (name) => { - if (isValidAttribute(name)) { - setAttributes((currentAttributes) => { - return { - ...currentAttributes, - [name]: '' - } - }); - } - }, - addClass: (name) => { - ref?.current?.classList.add(name); - }, - removeClass: (name) => { - ref?.current?.classList.remove(name); - }, - clear: () => { - if (ref && ref.current && typeof setInputState === 'function') { - setInputState((currentInputState) => { - return { - ...currentInputState, - inputValue: '' - } - }) - } - }, - focus: () => { - ref?.current?.focus(); - }, - setMessage: (message) => { - ariaMessageRef.current.innerText = message - } - }); -}; +export function exportMethods( + ref: Object, + setAttributes: Function, + setInputState?: Function, + ariaMessageRef: Object, +): void { + window.xprops.export({ + setAttribute: (name, value) => { + if (isValidAttribute(name)) { + setAttributes((currentAttributes) => { + return { + ...currentAttributes, + [name]: value, + }; + }); + } + }, + removeAttribute: (name) => { + if (isValidAttribute(name)) { + setAttributes((currentAttributes) => { + return { + ...currentAttributes, + [name]: "", + }; + }); + } + }, + addClass: (name) => { + ref?.current?.classList.add(name); + }, + removeClass: (name) => { + ref?.current?.classList.remove(name); + }, + clear: () => { + if (ref && ref.current && typeof setInputState === "function") { + setInputState((currentInputState) => { + return { + ...currentInputState, + inputValue: "", + maskedInputValue: "", + displayCardIcon: false, + cursorStart: 0, + cursorEnd: 0, + isFocused: false, + keyStrokeCount: 0, + }; + }); + } + }, + focus: () => { + ref?.current?.focus(); + }, + setMessage: (message) => { + ariaMessageRef.current.innerText = message; + }, + }); +} diff --git a/src/card/lib/methods.test.js b/src/card/lib/methods.test.js new file mode 100644 index 0000000000..97e8c4bd35 --- /dev/null +++ b/src/card/lib/methods.test.js @@ -0,0 +1,34 @@ +/* @flow */ +import { describe, test, expect, vi } from "vitest"; + +import { exportMethods } from "./methods"; + +describe("methods", () => { + describe("exportMethods", () => { + let exported; + window.xprops = { + export(methods) { + exported = methods; + }, + }; + test("clear() calls setInputState with empty values", () => { + let state; + const setInputState = (callback) => { + state = callback({}); + }; + const setAttributes = vi.fn(); + const ref = { current: 1 }; + exportMethods(ref, setAttributes, setInputState); + exported.clear(); + expect(state).toEqual({ + inputValue: "", + maskedInputValue: "", + displayCardIcon: false, + cursorStart: 0, + cursorEnd: 0, + isFocused: false, + keyStrokeCount: 0, + }); + }); + }); +}); diff --git a/src/card/logger.js b/src/card/logger.js index 93dcbbbae7..c2f0c11353 100644 --- a/src/card/logger.js +++ b/src/card/logger.js @@ -1,6 +1,6 @@ /* @flow */ -import { getPageRenderTime, stringifyErrorMessage } from "@krakenjs/belter/src"; +import { getPageRenderTime, stringifyErrorMessage } from "@krakenjs/belter/src"; import { FPTI_KEY, ENV, @@ -94,128 +94,133 @@ export function setupCardLogger({ }); } -export const hcfTransactionSuccess = ({ - orderID -}: {|orderID: string|}) => { - +export const hcfTransactionSuccess = ({ orderID }: {| orderID: string |}) => { sendCountMetric({ name: "pp.app.paypal_sdk.card_fields.submit.success.count", dimensions: { cardFieldsFlow: PAYMENT_FLOWS.WITH_PURCHASE, - } - }) + }, + }); - getLogger().track({ - [FPTI_KEY.TRANSITION]: "hcf_transaction_success", - [FPTI_KEY.EVENT_NAME]: "hcf_transaction_success", - [FPTI_HCF_KEYS.HCF_ORDER_ID]: orderID, - [FPTI_KEY.PAYMENT_FLOW]: PAYMENT_FLOWS.WITH_PURCHASE, - [FPTI_KEY.CONTEXT_TYPE]: FPTI_HCF_KEYS.HCF_ORDER_ID, - [FPTI_KEY.CONTEXT_ID]: orderID - }).flush(); -} + getLogger() + .track({ + [FPTI_KEY.TRANSITION]: "hcf_transaction_success", + [FPTI_KEY.EVENT_NAME]: "hcf_transaction_success", + [FPTI_HCF_KEYS.HCF_ORDER_ID]: orderID, + [FPTI_KEY.PAYMENT_FLOW]: PAYMENT_FLOWS.WITH_PURCHASE, + [FPTI_KEY.CONTEXT_TYPE]: FPTI_HCF_KEYS.HCF_ORDER_ID, + [FPTI_KEY.CONTEXT_ID]: orderID, + }) + .flush(); +}; export const hcfTransactionError = ({ - orderID, error + orderID, + error, }: {| orderID?: string, // should be Error but other apis are constraining this type - error: mixed + error: mixed, |}) => { - sendCountMetric({ name: "pp.app.paypal_sdk.card_fields.submit.error.count", dimensions: { cardFieldsFlow: PAYMENT_FLOWS.WITH_PURCHASE, - } - }) - getLogger().track({ - [FPTI_KEY.ERROR_CODE]: "hcf_transaction_error", - [FPTI_KEY.EVENT_NAME]: "hcf_transaction_error", - [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(error), - [FPTI_KEY.PAYMENT_FLOW]: PAYMENT_FLOWS.WITH_PURCHASE, - [FPTI_HCF_KEYS.HCF_ORDER_ID]: orderID, - [FPTI_KEY.CONTEXT_TYPE]: FPTI_HCF_KEYS.HCF_ORDER_ID, - [FPTI_KEY.CONTEXT_ID]: orderID - }).flush(); -} + }, + }); + getLogger() + .track({ + [FPTI_KEY.ERROR_CODE]: "hcf_transaction_error", + [FPTI_KEY.EVENT_NAME]: "hcf_transaction_error", + [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(error), + [FPTI_KEY.PAYMENT_FLOW]: PAYMENT_FLOWS.WITH_PURCHASE, + [FPTI_HCF_KEYS.HCF_ORDER_ID]: orderID, + [FPTI_KEY.CONTEXT_TYPE]: FPTI_HCF_KEYS.HCF_ORDER_ID, + [FPTI_KEY.CONTEXT_ID]: orderID, + }) + .flush(); +}; export const vaultWithoutPurchaseSuccess = ({ vaultToken, -}: {|vaultToken: string|}) => { - +}: {| + vaultToken: string, +|}) => { sendCountMetric({ name: "pp.app.paypal_sdk.card_fields.submit.success.count", dimensions: { cardFieldsFlow: PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, - } - }) + }, + }); - getLogger().track({ - [FPTI_KEY.TRANSITION]: "hcf_transaction_success", - [FPTI_KEY.EVENT_NAME]: "hcf_transaction_success", - [FPTI_HCF_KEYS.VAULT_TOKEN]: vaultToken, - [FPTI_KEY.PAYMENT_FLOW]: PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, - [FPTI_KEY.CONTEXT_TYPE]: `vault_setup_token`, - [FPTI_KEY.CONTEXT_ID]: vaultToken - }).flush(); -} + getLogger() + .track({ + [FPTI_KEY.TRANSITION]: "hcf_transaction_success", + [FPTI_KEY.EVENT_NAME]: "hcf_transaction_success", + [FPTI_HCF_KEYS.VAULT_TOKEN]: vaultToken, + [FPTI_KEY.PAYMENT_FLOW]: PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + [FPTI_KEY.CONTEXT_TYPE]: `vault_setup_token`, + [FPTI_KEY.CONTEXT_ID]: vaultToken, + }) + .flush(); +}; export const vaultWithoutPurchaseFailure = ({ - vaultToken, error + vaultToken, + error, }: {| vaultToken?: string, // should be Error but other apis are constraining this type - error: mixed + error: mixed, |}) => { - sendCountMetric({ name: "pp.app.paypal_sdk.card_fields.submit.error.count", dimensions: { cardFieldsFlow: PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, - } - }) - getLogger().track({ - [FPTI_KEY.ERROR_CODE]: "hcf_transaction_error", - [FPTI_KEY.EVENT_NAME]: "hcf_transaction_error", - [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(error), - [FPTI_HCF_KEYS.VAULT_TOKEN]: vaultToken, - [FPTI_KEY.PAYMENT_FLOW]: PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, - [FPTI_KEY.CONTEXT_TYPE]: `vault_setup_token`, - [FPTI_KEY.CONTEXT_ID]: vaultToken - }).flush(); -} + }, + }); + getLogger() + .track({ + [FPTI_KEY.ERROR_CODE]: "hcf_transaction_error", + [FPTI_KEY.EVENT_NAME]: "hcf_transaction_error", + [FPTI_KEY.ERROR_DESC]: stringifyErrorMessage(error), + [FPTI_HCF_KEYS.VAULT_TOKEN]: vaultToken, + [FPTI_KEY.PAYMENT_FLOW]: PAYMENT_FLOWS.VAULT_WITHOUT_PURCHASE, + [FPTI_KEY.CONTEXT_TYPE]: `vault_setup_token`, + [FPTI_KEY.CONTEXT_ID]: vaultToken, + }) + .flush(); +}; // $FlowFixMe export const threeDsAuthStatus = ({ authStatus, // $FlowFixMe }): {| - authStatus: string - |} => { + authStatus: string, +|} => { getLogger().addTrackingBuilder(() => ({ [FPTI_HCF_KEYS.THREEDS_AUTH_STATUS]: authStatus, - })) - } + })); +}; export const hcfFieldsSubmit = ({ cardFlowType, - hcfSessionID + hcfSessionID, }: {| cardFlowType: string, - hcfSessionID: string + hcfSessionID: string, |}) => { - sendCountMetric({ name: "pp.app.paypal_sdk.card_fields.submit.count", dimensions: { cardFieldsFlow: cardFlowType, - } - }) + }, + }); getLogger().track({ - [FPTI_KEY.TRANSITION]: "hcf_fields_submit", - [FPTI_KEY.EVENT_NAME]: "hcf_fields_submit", + [FPTI_KEY.TRANSITION]: "hcf_fields_submit", + [FPTI_KEY.EVENT_NAME]: "hcf_fields_submit", [FPTI_KEY.CONTEXT_TYPE]: FPTI_HCF_KEYS.HOSTED_SESSION_ID, [FPTI_KEY.PAYMENT_FLOW]: cardFlowType, - [FPTI_KEY.CONTEXT_ID]: hcfSessionID - }) -} + [FPTI_KEY.CONTEXT_ID]: hcfSessionID, + }); +}; diff --git a/src/card/logger.test.js b/src/card/logger.test.js index 553a57e3c3..bf26eecf5b 100644 --- a/src/card/logger.test.js +++ b/src/card/logger.test.js @@ -66,7 +66,7 @@ describe("card logger", () => { expect.objectContaining({ event_name: "hcf_name_field_rendered", transition_name: "hcf_name_field_rendered", - }) + }), ); }); @@ -78,7 +78,7 @@ describe("card logger", () => { hcf_version: "v2", seller_id: "XYZ12345", merchant_domain: "mock://www.paypal.com", - }) + }), ); }); @@ -89,7 +89,7 @@ describe("card logger", () => { expect.objectContaining({ ext_error_code: "hcf_transaction_error", ext_error_desc: "testing hcf transaction error", - }) + }), ); expect(sendCountMetric).toBeCalledWith({ name: "pp.app.paypal_sdk.card_fields.submit.error.count", @@ -106,7 +106,7 @@ describe("card logger", () => { event_name: "hcf_transaction_success", transition_name: "hcf_transaction_success", order_id: "ABCD123", - }) + }), ); expect(sendCountMetric).toBeCalledWith({ name: "pp.app.paypal_sdk.card_fields.submit.success.count", @@ -123,7 +123,7 @@ describe("card logger", () => { event_name: "hcf_transaction_success", transition_name: "hcf_transaction_success", vault_token: "ABCD123efgh", - }) + }), ); expect(sendCountMetric).toBeCalledWith({ name: "pp.app.paypal_sdk.card_fields.submit.success.count", @@ -140,7 +140,7 @@ describe("card logger", () => { expect.objectContaining({ ext_error_code: "hcf_transaction_error", ext_error_desc: "testing vault without purchase error", - }) + }), ); expect(sendCountMetric).toBeCalledWith({ name: "pp.app.paypal_sdk.card_fields.submit.error.count", diff --git a/src/card/props.test.js b/src/card/props.test.js index 6af2261141..25e496843d 100644 --- a/src/card/props.test.js +++ b/src/card/props.test.js @@ -17,6 +17,7 @@ describe("getCardProps", () => { featureFlags: {}, experiments: { hostedCardFields: true, + useIDToken: true, }, }; @@ -33,8 +34,8 @@ describe("getCardProps", () => { expect(() => getCardProps({ ...inputs, - experiments: { hostedCardFields: false }, - }) + experiments: { hostedCardFields: false, useIDToken: false }, + }), ).toThrowError(SUBMIT_ERRORS.NOT_FEATURE_FLAGGED); }); @@ -45,7 +46,7 @@ describe("getCardProps", () => { // $FlowIssue window.xprops.createVaultSetupToken = undefined; expect(() => getCardProps(inputs)).toThrowError( - SUBMIT_ERRORS.MISSING_BOTH_FUNCTIONS + SUBMIT_ERRORS.MISSING_BOTH_FUNCTIONS, ); }); @@ -56,7 +57,7 @@ describe("getCardProps", () => { }; expect(() => getCardProps(inputs)).toThrowError( - SUBMIT_ERRORS.MISSING_ONAPPROVE + SUBMIT_ERRORS.MISSING_ONAPPROVE, ); }); @@ -69,7 +70,7 @@ describe("getCardProps", () => { }; expect(() => getCardProps(inputs)).toThrow( - SUBMIT_ERRORS.PASSING_BOTH_FUNCTIONS + SUBMIT_ERRORS.PASSING_BOTH_FUNCTIONS, ); }); @@ -82,7 +83,7 @@ describe("getCardProps", () => { expect.objectContaining({ createVaultSetupToken: expect.any(Function), onApprove: expect.any(Function), - }) + }), ); }); }); diff --git a/src/card/props/createOrder.js b/src/card/props/createOrder.js index b4d818e280..18c17ec53e 100644 --- a/src/card/props/createOrder.js +++ b/src/card/props/createOrder.js @@ -26,7 +26,7 @@ export function getCreateOrder({ return memoize(() => { return ZalgoPromise.try(() => { - return createOrder({paymentSource: FUNDING.CARD}); + return createOrder({ paymentSource: FUNDING.CARD }); }).then((orderID) => { if (!orderID || typeof orderID !== "string") { throw new Error(`Expected an order id to be passed`); @@ -34,7 +34,7 @@ export function getCreateOrder({ if (orderID.includes("PAY-") || orderID.includes("PAYID-")) { throw new Error( - `Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead` + `Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead`, ); } diff --git a/src/card/props/createOrder.test.js b/src/card/props/createOrder.test.js index 2262107ab8..38ccf6b6c6 100644 --- a/src/card/props/createOrder.test.js +++ b/src/card/props/createOrder.test.js @@ -41,7 +41,7 @@ describe("decorate createOrder", () => { // $FlowIssue expect(decoratedCreateOrder()).rejects.toThrowError( - "Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead" + "Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead", ); }); @@ -53,7 +53,7 @@ describe("decorate createOrder", () => { // $FlowIssue expect(decoratedCreateOrder()).rejects.toThrowError( - "Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead" + "Do not pass PAY-XXX or PAYID-XXX directly into createOrder. Pass the EC-XXX token instead", ); }); @@ -71,7 +71,7 @@ describe("decorate createOrder", () => { // $FlowIssue expect(decoratedCreateOrder()).rejects.toThrowError( - "Expected an order id to be passed" + "Expected an order id to be passed", ); }); diff --git a/src/card/props/createVaultSetupToken.js b/src/card/props/createVaultSetupToken.js index e9466977c2..89c414f214 100644 --- a/src/card/props/createVaultSetupToken.js +++ b/src/card/props/createVaultSetupToken.js @@ -16,7 +16,9 @@ export type XCreateVaultSetupTokenDataType = {| // Create... is the internal version of the function passed by the merchant. // We decorate Create... with our own config, pass through specific options needed, // and sometimes making additional API or logging calls. -export type XCreateVaultSetupToken = ?(XCreateVaultSetupTokenDataType) => ZalgoPromise; +export type XCreateVaultSetupToken = ?( + XCreateVaultSetupTokenDataType, +) => ZalgoPromise; export type CreateVaultSetupToken = () => ZalgoPromise; export const getCreateVaultSetupToken = ({ @@ -29,13 +31,15 @@ export const getCreateVaultSetupToken = ({ } return memoize(() => { - return createVaultSetupToken({paymentSource: FUNDING.CARD}).then((vaultSetupToken) => { - if (!vaultSetupToken || typeof vaultSetupToken !== "string") { - throw new Error( - `Expected a vault setup token to be returned from createVaultSetupToken` - ); - } - return vaultSetupToken; - }); + return createVaultSetupToken({ paymentSource: FUNDING.CARD }).then( + (vaultSetupToken) => { + if (!vaultSetupToken || typeof vaultSetupToken !== "string") { + throw new Error( + `Expected a vault setup token to be returned from createVaultSetupToken`, + ); + } + return vaultSetupToken; + }, + ); }); }; diff --git a/src/card/props/createVaultSetupToken.test.js b/src/card/props/createVaultSetupToken.test.js index c7c8f2327b..5e59b6b5d6 100644 --- a/src/card/props/createVaultSetupToken.test.js +++ b/src/card/props/createVaultSetupToken.test.js @@ -49,7 +49,7 @@ describe("decorate createVaultSetupToken", () => { // $FlowIssue expect(decoratedCreateVaultSetupToken()).rejects.toThrowError( - "Expected a vault setup token to be returned from createVaultSetupToken" + "Expected a vault setup token to be returned from createVaultSetupToken", ); }); @@ -63,7 +63,7 @@ describe("decorate createVaultSetupToken", () => { // $FlowIssue expect(decoratedCreateVaultSetupToken()).resolves.toEqual( - "vault_setup_token" + "vault_setup_token", ); }); }); diff --git a/src/card/props/index.js b/src/card/props/index.js index 74663b95c1..8e3fc607f0 100644 --- a/src/card/props/index.js +++ b/src/card/props/index.js @@ -8,7 +8,11 @@ import { type FundingEligibilityType, } from "@paypal/sdk-constants/src"; -import type { ProxyWindow, FeatureFlags, ThreeDomainSecureFlowType } from "../../types"; +import type { + ProxyWindow, + FeatureFlags, + ThreeDomainSecureFlowType, +} from "../../types"; import { PAYMENT_FLOWS } from "../../constants"; import { getProps, @@ -61,9 +65,7 @@ export type InputEventState = {| isFormValid: boolean, |}; -export type OnChange = ({| - ...InputEventState, -|}) => ZalgoPromise; +export type OnChange = ({| ...InputEventState |}) => ZalgoPromise; export type OnBlur = (InputEventState) => ZalgoPromise; @@ -98,6 +100,8 @@ export type CardXProps = {| createOrder?: XCreateOrder, createVaultSetupToken: XCreateVaultSetupToken, hcfSessionID: string, + clientMetadataID: string, + userIDToken: string, |}; export type CardProps = {| @@ -120,6 +124,8 @@ export type CardProps = {| onApprove: SaveActionOnApprove, onError: OnError, productAction: string, + clientMetadataID: string, + userIDToken: string, |}; export type PurchaseFlowCardProps = {| @@ -137,14 +143,15 @@ type GetCardPropsOptions = {| featureFlags: FeatureFlags, experiments: { hostedCardFields: boolean, + useIDToken: boolean, }, |}; export type Components = {| -ThreeDomainSecure : ThreeDomainSecureFlowType -|} + ThreeDomainSecure: ThreeDomainSecureFlowType, +|}; -export function getComponents() : Components { +export function getComponents(): Components { const { ThreeDomainSecure } = paypal; return { ThreeDomainSecure }; } @@ -197,6 +204,7 @@ export function getCardProps({ sdkCorrelationID, partnerAttributionID, hcfSessionID, + userIDToken, } = xprops; const returnData = { @@ -214,6 +222,7 @@ export function getCardProps({ sdkCorrelationID, partnerAttributionID, hcfSessionID, + userIDToken, }; const baseProps = getProps({ branded }); diff --git a/src/card/types.js b/src/card/types.js index 7baf525d73..9b057b8a7e 100644 --- a/src/card/types.js +++ b/src/card/types.js @@ -1,216 +1,215 @@ /* eslint-disable flowtype/require-exact-type */ /* @flow */ -import { COUNTRY } from '@paypal/sdk-constants/src'; +import { COUNTRY } from "@paypal/sdk-constants/src"; -import type { FeatureFlags } from "../types" +import type { FeatureFlags } from "../types"; export type SetupCardOptions = {| - cspNonce : string, - facilitatorAccessToken : string, - featureFlags: FeatureFlags, - buyerCountry : $Values, - metadata: {| - correlationID: string, - spbVersion: string - |}, - experiments: {| - hostedCardFields: boolean - |} + cspNonce: string, + facilitatorAccessToken: string, + featureFlags: FeatureFlags, + buyerCountry: $Values, + metadata: {| + correlationID: string, + spbVersion: string, + |}, + experiments: {| + hostedCardFields: boolean, + useIDToken: boolean, + |}, |}; export type BillingAddress = {| - addressLine1?: string, - addressLine2?: string, - adminArea2?: string, - adminArea1?: string, - postalCode?: string, - countryCode: string, -|} + addressLine1?: string, + addressLine2?: string, + adminArea2?: string, + adminArea1?: string, + postalCode?: string, + countryCode: string, +|}; export type ReformattedBillingAddress = {| - address_line_1?: string, - address_line_2?: string, - admin_area_2?: string, - admin_area_1?: string, - postal_code?: string, - country_code: string, -|} + address_line_1?: string, + address_line_2?: string, + admin_area_2?: string, + admin_area_1?: string, + postal_code?: string, + country_code: string, +|}; export type Card = { - number: string, - cvv: string, - expiry: string, - name?: string, - postalCode?: string, - billingAddress?: BillingAddress + number: string, + cvv: string, + expiry: string, + name?: string, + postalCode?: string, + billingAddress?: BillingAddress, }; export type FieldStyle = {| - appearance? : string, - color? : string, - direction? : string, - font? : string, - fontFamily? : string, - fontSizeAdjust? : string, - fontSize? : string, - fontStretch? : string, - fontStyle? : string, - fontVariantAlternates? : string, - fontVariantCaps? : string, - fontVariantEastAsian? : string, - fontVariantLigatures? : string, - fontVariantNumeric? : string, - fontVariant? : string, - fontWeight? : string, - letterSpacing? : string, - lineHeight? : string, - opacity? : string, - outline? : string, - padding? : string, - paddingTop? : string, - paddingRight? : string, - paddingBottom? : string, - paddingLeft? : string, - textShadow? : string, - transition? : string, - MozApperance?: string, - MozOsxFontSmoothing?: string, - MozTapHighlightColor?: string, - MozTransition?: string, - WebkitAppearance?: string, - WebkitOsxFontSmoothing?: string, - WebkitTapHighlightColor?: string, - WebkitTransition?: string -|}; - -export type CardStyle = {| |}; + appearance?: string, + color?: string, + direction?: string, + font?: string, + fontFamily?: string, + fontSizeAdjust?: string, + fontSize?: string, + fontStretch?: string, + fontStyle?: string, + fontVariantAlternates?: string, + fontVariantCaps?: string, + fontVariantEastAsian?: string, + fontVariantLigatures?: string, + fontVariantNumeric?: string, + fontVariant?: string, + fontWeight?: string, + letterSpacing?: string, + lineHeight?: string, + opacity?: string, + outline?: string, + padding?: string, + paddingTop?: string, + paddingRight?: string, + paddingBottom?: string, + paddingLeft?: string, + textShadow?: string, + transition?: string, + MozApperance?: string, + MozOsxFontSmoothing?: string, + MozTapHighlightColor?: string, + MozTransition?: string, + WebkitAppearance?: string, + WebkitOsxFontSmoothing?: string, + WebkitTapHighlightColor?: string, + WebkitTransition?: string, +|}; + +export type CardStyle = {||}; export type CardPlaceholder = {| - number? : string, - expiry? : string, - cvv? : string, - name? : string, - postal?: string + number?: string, + expiry?: string, + cvv?: string, + name?: string, + postal?: string, |}; export type CardTypeCode = {| - name : string, - size : number - |} + name: string, + size: number, +|}; export type CardType = {| - gaps : $ReadOnlyArray, - lengths : $ReadOnlyArray, - patterns : $ReadOnlyArray, - matchStrength? : number, - type : string, - niceType : string, - code : CardTypeCode + gaps: $ReadOnlyArray, + lengths: $ReadOnlyArray, + patterns: $ReadOnlyArray, + matchStrength?: number, + type: string, + niceType: string, + code: CardTypeCode, |}; export type ParsedCardType = {| - type: string, - niceType: string, - code : CardTypeCode + type: string, + niceType: string, + code: CardTypeCode, |}; export type CardFieldState = {| - isEmpty: boolean, - isValid: boolean, - isPotentiallyValid: boolean, - isFocused: boolean -|} + isEmpty: boolean, + isValid: boolean, + isPotentiallyValid: boolean, + isFocused: boolean, +|}; export type FieldsState = { - cardNameField? : CardFieldState, - cardNumberField : CardFieldState, - cardExpiryField : CardFieldState, - cardCvvField : CardFieldState, - cardPostalCodeField? : CardFieldState -} + cardNameField?: CardFieldState, + cardNumberField: CardFieldState, + cardExpiryField: CardFieldState, + cardCvvField: CardFieldState, + cardPostalCodeField?: CardFieldState, +}; export type CardFieldsState = { - cards : $ReadOnlyArray, - fields: FieldsState + cards: $ReadOnlyArray, + fields: FieldsState, }; export type InputEvent = {| - key : string, - target : HTMLInputElement, - type? : string, - keyCode? : number + key: string, + target: HTMLInputElement, + type?: string, + keyCode?: number, |}; export type CardNumberChangeEvent = {| - cardNumber : string, - potentialCardTypes : CardType, + cardNumber: string, + potentialCardTypes: CardType, |}; export type CardExpiryChangeEvent = {| - maskedDate : string, + maskedDate: string, |}; export type CardCvvChangeEvent = {| - cardCvv : string + cardCvv: string, |}; export type CardNameChangeEvent = {| - cardName : string + cardName: string, |}; export type CardPostalCodeChangeEvent = {| - event? : InputEvent, - cardPostalCode : string + event?: InputEvent, + cardPostalCode: string, |}; export type FieldValidity = {| - isValid : boolean, - isPotentiallyValid : boolean + isValid: boolean, + isPotentiallyValid: boolean, |}; export type CardNavigation = {| - next : () => void, - previous : () => void + next: () => void, + previous: () => void, |}; export type InputState = {| - inputValue : string, - maskedInputValue : string, - cursorStart : number, - cursorEnd : number, - keyStrokeCount : number, - isPotentiallyValid : boolean, - isFocused : boolean, - isValid : boolean, - contentPasted? : boolean, - displayCardIcon?: boolean + inputValue: string, + maskedInputValue: string, + cursorStart: number, + cursorEnd: number, + keyStrokeCount: number, + isPotentiallyValid: boolean, + isFocused: boolean, + isValid: boolean, + contentPasted?: boolean, + displayCardIcon?: boolean, |}; export type InputOptions = {| - inputState : InputState, - validationFn : () => mixed + inputState: InputState, + validationFn: () => mixed, |}; export type ExtraFields = {| - billingAddress? : BillingAddress + billingAddress?: BillingAddress, |}; - export type PaymentSourceCardInput = {| - number: string, - expiry: string, - name?: string, - securityCode: string, - billingAddress?: BillingAddress + number: string, + expiry: string, + name?: string, + securityCode: string, + billingAddress?: BillingAddress, |}; - export type ReformattedPaymentSourceCardInput = {| - number: string, - expiry: string, - name?: string, - security_code: string, - billing_address?: ReformattedBillingAddress + number: string, + expiry: string, + name?: string, + security_code: string, + billing_address?: ReformattedBillingAddress, |}; /* eslint-enable flowtype/require-exact-type */ diff --git a/src/config.js b/src/config.js index 11a89cf45f..d910441cc1 100644 --- a/src/config.js +++ b/src/config.js @@ -1,43 +1,46 @@ /* @flow */ /* eslint max-lines: off */ -import { FUNDING } from '@paypal/sdk-constants/src'; - -export const LOGGER_URL = '/xoplatform/logger/api/logger'; -export const AUTH_API_URL = '/v1/oauth2/token'; -export const ORDERS_API_URL = '/v2/checkout/orders'; -export const PAYMENTS_API_URL = '/v1/payments/payment'; -export const CREATE_SUBSCRIPTIONS_API_URL = '/v1/billing/subscriptions'; -export const VALIDATE_PAYMENT_METHOD_API = 'validate-payment-method'; -export const VAULT_API_URL = '/v3/vault' -export const VAULT_SETUP_TOKENS_API_URL = `${VAULT_API_URL}/setup-tokens` - -export const BASE_SMART_API_URL = '/smart/api'; +import { FUNDING } from "@paypal/sdk-constants/src"; + +export const LOGGER_URL = "/xoplatform/logger/api/logger"; +export const AUTH_API_URL = "/v1/oauth2/token"; +export const ORDERS_API_URL = "/v2/checkout/orders"; +export const PAYMENTS_API_URL = "/v1/payments/payment"; +export const CREATE_SUBSCRIPTIONS_API_URL = "/v1/billing/subscriptions"; +export const VALIDATE_PAYMENT_METHOD_API = "validate-payment-method"; +export const VAULT_API_URL = "/v3/vault"; +export const VAULT_SETUP_TOKENS_API_URL = `${VAULT_API_URL}/setup-tokens`; + +export const BASE_SMART_API_URL = "/smart/api"; export const SMART_API_URI = { - AUTH: `${ BASE_SMART_API_URL }/auth`, - CHECKOUT: `${ BASE_SMART_API_URL }/checkout`, - ORDER: `${ BASE_SMART_API_URL }/order`, - PAYMENT: `${ BASE_SMART_API_URL }/payment`, - SUBSCRIPTION: `${ BASE_SMART_API_URL }/billagmt/subscriptions`, - VAULT: `${ BASE_SMART_API_URL }/vault`, + AUTH: `${BASE_SMART_API_URL}/auth`, + CHECKOUT: `${BASE_SMART_API_URL}/checkout`, + ORDER: `${BASE_SMART_API_URL}/order`, + PAYMENT: `${BASE_SMART_API_URL}/payment`, + SUBSCRIPTION: `${BASE_SMART_API_URL}/billagmt/subscriptions`, + VAULT: `${BASE_SMART_API_URL}/vault`, }; -export const GRAPHQL_URI = '/graphql'; +export const GRAPHQL_URI = "/graphql"; -export const WEB_CHECKOUT_URI = '/checkoutnow'; +export const WEB_CHECKOUT_URI = "/checkoutnow"; -export const FUNDING_SKIP_LOGIN : { [$Values] : $Values } = { - [ FUNDING.PAYPAL ]: FUNDING.PAYPAL, - [ FUNDING.PAYLATER ]: FUNDING.PAYPAL, - [ FUNDING.CREDIT ]: FUNDING.PAYPAL +export const FUNDING_SKIP_LOGIN: { + [$Values]: $Values, +} = { + [FUNDING.PAYPAL]: FUNDING.PAYPAL, + [FUNDING.PAYLATER]: FUNDING.PAYPAL, + [FUNDING.CREDIT]: FUNDING.PAYPAL, }; -export const NATIVE_DETECTION_URL = 'http://127.0.0.1:8765/hello'; +export const NATIVE_DETECTION_URL = "http://127.0.0.1:8765/hello"; export const FIREBASE_SCRIPTS = { - APP: 'https://www.paypalobjects.com/checkout/js/lib/firebase-app.js', - AUTH: 'https://www.paypalobjects.com/checkout/js/lib/firebase-auth.js', - DATABASE: 'https://www.paypalobjects.com/checkout/js/lib/firebase-database.js' + APP: "https://www.paypalobjects.com/checkout/js/lib/firebase-app.js", + AUTH: "https://www.paypalobjects.com/checkout/js/lib/firebase-auth.js", + DATABASE: + "https://www.paypalobjects.com/checkout/js/lib/firebase-database.js", }; export const ENABLE_PAYMENT_API = false; diff --git a/src/constants.js b/src/constants.js index caa496f350..51aaf1cbf2 100644 --- a/src/constants.js +++ b/src/constants.js @@ -1,301 +1,334 @@ /* @flow */ -export const SMART_PAYMENT_BUTTONS = 'smart-payment-buttons'; +export const SMART_PAYMENT_BUTTONS = "smart-payment-buttons"; export const BUYER_INTENT = { - PAY: 'pay', - PAY_WITH_DIFFERENT_ACCOUNT: 'pay_with_different_account', - PAY_WITH_DIFFERENT_FUNDING_SHIPPING: 'pay_with_different_funding_shipping' + PAY: "pay", + PAY_WITH_DIFFERENT_ACCOUNT: "pay_with_different_account", + PAY_WITH_DIFFERENT_FUNDING_SHIPPING: "pay_with_different_funding_shipping", }; export const HEADERS = { - AUTHORIZATION: 'authorization', - CONTENT_TYPE: 'content-type', - PREFER: 'prefer', - - ACCESS_TOKEN: 'x-paypal-internal-euat', - CSRF_TOKEN: 'x-csrf-jwt', - SOURCE: 'x-source', - REQUESTED_BY: 'x-requested-by', - APP_NAME: 'x-app-name', - APP_VERSION: 'x-app-version', - CLIENT_CONTEXT: 'paypal-client-context', - - PARTNER_ATTRIBUTION_ID: 'paypal-partner-attribution-id', - CLIENT_METADATA_ID: 'paypal-client-metadata-id', - PAYPAL_DEBUG_ID: 'paypal-debug-id', - PAYPAL_REQUEST_ID: 'paypal-request-id', - DISABLE_SET_COOKIE: 'disable-set-cookie' + AUTHORIZATION: "authorization", + CONTENT_TYPE: "content-type", + PREFER: "prefer", + + ACCESS_TOKEN: "x-paypal-internal-euat", + CSRF_TOKEN: "x-csrf-jwt", + SOURCE: "x-source", + REQUESTED_BY: "x-requested-by", + APP_NAME: "x-app-name", + APP_VERSION: "x-app-version", + CLIENT_CONTEXT: "paypal-client-context", + + PARTNER_ATTRIBUTION_ID: "paypal-partner-attribution-id", + CLIENT_METADATA_ID: "paypal-client-metadata-id", + PAYPAL_DEBUG_ID: "paypal-debug-id", + PAYPAL_REQUEST_ID: "paypal-request-id", + DISABLE_SET_COOKIE: "disable-set-cookie", }; export const DATA_ATTRIBUTES = { - FUNDING_SOURCE: 'data-funding-source', - CARD: 'data-card', - PAYMENT_METHOD_ID: 'data-payment-method-id', - INSTRUMENT_ID: 'data-instrument-id', - INSTRUMENT_TYPE: 'data-instrument-type', - SECONDARY_INSTRUMENT_TYPE: 'data-secondary-instrument-type', - MENU: 'data-menu', - NONCE: 'data-nonce', - RENDER_VERSION: 'data-render-version', - CLIENT_VERSION: 'data-client-version', - PAY_NOW: 'data-pay-now', - RESPONSE_START_TIME: 'data-response-start-time' + FUNDING_SOURCE: "data-funding-source", + CARD: "data-card", + PAYMENT_METHOD_ID: "data-payment-method-id", + INSTRUMENT_ID: "data-instrument-id", + INSTRUMENT_TYPE: "data-instrument-type", + SECONDARY_INSTRUMENT_TYPE: "data-secondary-instrument-type", + MENU: "data-menu", + NONCE: "data-nonce", + RENDER_VERSION: "data-render-version", + CLIENT_VERSION: "data-client-version", + PAY_NOW: "data-pay-now", + RESPONSE_START_TIME: "data-response-start-time", }; export const CLASS = { - LOADING: 'paypal-button-loading', - CLICKED: 'paypal-button-clicked', - BUTTON: 'paypal-button', + LOADING: "paypal-button-loading", + CLICKED: "paypal-button-clicked", + BUTTON: "paypal-button", }; export const PREFER = { - REPRESENTATION: 'return=representation' + REPRESENTATION: "return=representation", }; export const ORDER_API_ERROR = { - INSTRUMENT_DECLINED: 'INSTRUMENT_DECLINED', - PAYER_ACTION_REQUIRED: 'PAYER_ACTION_REQUIRED', - DUPLICATE_INVOICE_ID: 'DUPLICATE_INVOICE_ID', - INVALID_RESOURCE_ID: 'INVALID_RESOURCE_ID' + INSTRUMENT_DECLINED: "INSTRUMENT_DECLINED", + PAYER_ACTION_REQUIRED: "PAYER_ACTION_REQUIRED", + DUPLICATE_INVOICE_ID: "DUPLICATE_INVOICE_ID", + INVALID_RESOURCE_ID: "INVALID_RESOURCE_ID", }; export const CONTEXT = { - IFRAME: 'iframe', - POPUP: 'popup' + IFRAME: "iframe", + POPUP: "popup", }; export const TARGET_ELEMENT = { - BODY: 'body' + BODY: "body", }; export const INTEGRATION_ARTIFACT = { - PAYPAL_JS_SDK: 'PAYPAL_JS_SDK' + PAYPAL_JS_SDK: "PAYPAL_JS_SDK", }; export const USER_EXPERIENCE_FLOW = { - INCONTEXT: 'INCONTEXT', - INLINE: 'INLINE' + INCONTEXT: "INCONTEXT", + INLINE: "INLINE", }; export const PRODUCT_FLOW = { - SMART_PAYMENT_BUTTONS: 'SMART_PAYMENT_BUTTONS' + SMART_PAYMENT_BUTTONS: "SMART_PAYMENT_BUTTONS", }; export const FPTI_CONTEXT_TYPE = { - BUTTON_SESSION_ID: ('button_session_id' : 'button_session_id'), - WALLET_SESSION_ID: ('wallet_session_id' : 'wallet_session_id'), - ORDER_ID: ('EC-Token' : 'EC-Token'), - PAYMENT_ID: ('Pay-ID' : 'Pay-ID') + BUTTON_SESSION_ID: ("button_session_id": "button_session_id"), + WALLET_SESSION_ID: ("wallet_session_id": "wallet_session_id"), + ORDER_ID: ("EC-Token": "EC-Token"), + PAYMENT_ID: ("Pay-ID": "Pay-ID"), + VAULT_SETUP_TOKEN: ("vault_setup_token": "vault_setup_token"), }; export const FPTI_STATE = { - BUTTON: ('smart_button' : 'smart_button'), - CARD: ('card_field': 'card_field'), - WALLET: ('smart_wallet' : 'smart_wallet'), - PXP: ('PXP_CHECK' : 'PXP_CHECK'), - ELIGIBILITY_CHECK: ('eligibility_check' : 'eligibility_check') + BUTTON: ("smart_button": "smart_button"), + CARD: ("card_field": "card_field"), + WALLET: ("smart_wallet": "smart_wallet"), + PXP: ("PXP_CHECK": "PXP_CHECK"), + ELIGIBILITY_CHECK: ("eligibility_check": "eligibility_check"), }; export const FPTI_TRANSITION = { - BUTTON_LOAD: ('process_button_load' : 'process_button_load'), - BUTTON_CLICK: ('process_button_click' : 'process_button_click'), - PXP: ('process_pxp_check' : 'process_pxp_check'), - - WALLET_LOAD: ('process_wallet_load' : 'process_wallet_load'), - - MENU_CLICK: ('process_menu_click' : 'process_menu_click'), - CLICK_CHOOSE_FUNDING: ('process_click_pay_with_different_payment_method' : 'process_click_pay_with_different_payment_method'), - CLICK_CHOOSE_ACCOUNT: ('process_click_pay_with_different_account' : 'process_click_pay_with_different_account'), - CLICK_UNLINK_ACCOUNT: ('process_click_unlink_account' : 'process_click_unlink_account'), - - INSTALLMENTS_ELIGIBLE: ('installments_eligible' : 'installments_eligible'), - INSTALLMENTS_INELIGIBLE: ('installments_ineligible' : 'installments_ineligible'), - - CREATE_ORDER: ('process_create_order' : 'process_create_order'), - CONFIRM_ORDER: ('process_confirm_order' : 'process_confirm_order'), - RECEIVE_ORDER: ('process_receive_order' : 'process_receive_order'), - CREATE_PAYMENT: ('process_create_payment' : 'process_create_payment'), - CAPTURE_AUTHORIZATION: ('process_capture_authorization' : 'process_capture_authorization'), - - CHECKOUT_SHIPPING_CHANGE: ('process_checkout_shipping_change' : 'process_checkout_shipping_change'), - CHECKOUT_SHIPPING_ADDRESS_CHANGE: ('process_checkout_shipping_address_change' : 'process_checkout_shipping_address_change'), - CHECKOUT_SHIPPING_OPTIONS_CHANGE: ('process_checkout_shipping_options_change' : 'process_checkout_shipping_options_change'), - CHECKOUT_APPROVE: ('process_checkout_approve' : 'process_checkout_approve'), - CHECKOUT_COMPLETE: ('process_checkout_complete' : 'process_checkout_complete'), - CHECKOUT_CANCEL: ('process_checkout_cancel' : 'process_checkout_cancel'), - CHECKOUT_ERROR: ('process_checkout_error' : 'process_checkout_error'), - - TOKENIZE_APPROVE: ('process_tokenize_approve' : 'process_tokenize_approve'), - - CONNECT_REDIRECT: ('process_connect_redirect' : 'process_connect_redirect'), - - FIREBASE_CONNECTION_OPENED: ('firebase_connection_opened' : 'firebase_connection_opened'), - FIREBASE_CONNECTION_ERRORED: ('firebase_connection_errored' : 'firebase_connection_errored'), - - APPLEPAY_EVENT: ('applepay_event' : 'applepay_event'), - APPLEPAY_FLOW_ERROR: ('applepay_flow_error' : 'applepay_flow_error'), - APPLEPAY_ON_CLICK_INVALID: ('applepay_onclick_invalid' : 'applepay_onclick_invalid'), - APPLEPAY_MERCHANT_VALIDATION_COMPLETION_ERROR: ('applepay_merchant_validation_completion_error' : 'applepay_merchant_validation_completion_error'), - APPLEPAY_MERCHANT_VALIDATION_ERROR: ('applepay_merchant_validation_error' : 'applepay_merchant_validation_error'), - APPLEPAY_CREATE_ORDER_ERROR: ('applepay_create_order_error' : 'applepay_create_order_error'), - APPLEPAY_GET_DETAILS_ERROR: ('applepay_get_details_error' : 'applepay_get_details_error'), - APPLEPAY_PAYMENT_ERROR: ('applepay_payment_error' : 'applepay_payment_error'), - APPLEPAY_CONFIG_ERROR: ('applepay_config_error' : 'applepay_config_error'), - - NATIVE_DETECT_POSSIBLE_APP_SWITCH: ('native_detect_possible_app_switch' : 'native_detect_possible_app_switch'), - NATIVE_DETECT_APP_SWITCH: ('native_detect_app_switch' : 'native_detect_app_switch'), - NATIVE_DETECT_WEB_SWITCH: ('native_detect_web_switch' : 'native_detect_web_switch'), - NATIVE_APP_SWITCH_ACK: ('native_app_switch_ack' : 'native_app_switch_ack'), - NATIVE_ERROR: ('native_app_switch_ack' : 'native_app_switch_ack'), - NATIVE_APP_INSTALLED: ('native_app_installed' : 'native_app_installed'), - NATIVE_APP_SWITCH_INELIGIBLE: ('app_switch_ineligible' : 'app_switch_ineligible'), - NATIVE_ATTEMPT_APP_SWITCH: ('app_switch_attempted' : 'app_switch_attempted'), - NATIVE_ATTEMPT_APP_SWITCH_ERRORED: ('app_switch_attempted_errored' : 'app_switch_attempted_errored'), - NATIVE_CLOSING_POPUP: ('native_closing_popup' : 'native_closing_popup'), - NATIVE_POPUP_CLOSED: ('popup_closed' : 'popup_closed'), - NATIVE_POPUP_HASHCHANGE: ('popup_hashchange' : 'popup_hashchange'), - NATIVE_POPUP_NO_OPENER: ('popup_no_opener' : 'popup_no_opener'), - NATIVE_POPUP_ANDROID_APP_ERROR: ('native_popup_android_app_installed_error' : 'native_popup_android_app_installed_error'), - NATIVE_POPUP_FALLBACK: ('popup_fallback' : 'popup_fallback'), - NATIVE_FALLBACK_RETRY_VENMO_APP_SWITCH: ('native_fallback_retry_venmo_app_switch', 'native_fallback_retry_venmo_app_switch'), - NATIVE_POPUP_SHOWN: ('popup_shown' : 'popup_shown'), - NATIVE_ON_APPROVE: ('native_onapprove' : 'native_onapprove'), - NATIVE_ON_APPROVE_ERROR: ('native_onapprove_error' : 'native_onapprove_error'), - NATIVE_ON_CANCEL: ('native_oncancel' : 'native_oncancel'), - NATIVE_ON_CLICK_INVALID: ('native_onclick_invalid' : 'native_onclick_invalid'), - NATIVE_ON_COMPLETE: ('native_oncomplete' : 'native_oncomplete'), - NATIVE_ON_ERROR: ('native_onerror' : 'native_onerror'), - NATIVE_ON_SHIPPING_CHANGE: ('native_onshippingchange' : 'native_onshippingchange'), - NATIVE_ON_FALLBACK: ('native_onfallback' : 'native_onfallback'), - NATIVE_POPUP_INIT: ('native_popup_init' : 'native_popup_init'), - NATIVE_POPUP_UNLOAD: ('native_popup_unload' : 'native_popup_unload'), - NATIVE_POPUP_BEFORE_UNLOAD: ('native_popup_beforeunload' : 'native_popup_beforeunload'), - NATIVE_POPUP_PAGEHIDE: ('native_popup_pagehide' : 'native_popup_pagehide'), - NATIVE_POPUP_OPENER_DETECT_CLOSE: ('native_popup_opener_detect_close' : 'native_popup_opener_detect_close'), - NATIVE_OPT_OUT: ('native_opt_out' : 'native_opt_out'), - NATIVE_FALLBACK: ('native_fallback' : 'native_fallback'), - NATIVE_FALLBACK_VENMO: ('native_fallback_venmo' : 'native_fallback_venmo'), - NATIVE_VENMO_WEB: ('native_venmo_web' : 'native_venmo_web'), - NATIVE_VENMO_WEB_REDIRECT: ('native_venmo_web_redirect' : 'native_venmo_web_redirect'), - - QR_LOAD: ('qr_load' : 'qr_load'), - QR_SHOWN: ('qr_shown' : 'qr_shown'), - QR_CLOSING: ('qr_closing' : 'qr_closing'), - QR_SURVEY: ('desktop_exit_survey_selection_submitted' : 'desktop_exit_survey_selection_submitted'), - QR_PREPARE_PAY: ('qr_prepare_pay' : 'qr_prepare_pay'), - QR_PROCESS_PAY_WITH: ('qr_process_pay_with' : 'qr_process_pay_with'), - - HONEY_IDENTIFY: ('honey_identify' : 'honey_identify'), - - CALL_REST_API: ('call_rest_api' : 'call_rest_api'), - - ORDER_VALIDATE: ('process_order_validate', 'process_order_validate') + BUTTON_LOAD: ("process_button_load": "process_button_load"), + BUTTON_CLICK: ("process_button_click": "process_button_click"), + PXP: ("process_pxp_check": "process_pxp_check"), + + WALLET_LOAD: ("process_wallet_load": "process_wallet_load"), + + MENU_CLICK: ("process_menu_click": "process_menu_click"), + CLICK_CHOOSE_FUNDING: + ("process_click_pay_with_different_payment_method": "process_click_pay_with_different_payment_method"), + CLICK_CHOOSE_ACCOUNT: + ("process_click_pay_with_different_account": "process_click_pay_with_different_account"), + CLICK_UNLINK_ACCOUNT: + ("process_click_unlink_account": "process_click_unlink_account"), + + INSTALLMENTS_ELIGIBLE: ("installments_eligible": "installments_eligible"), + INSTALLMENTS_INELIGIBLE: + ("installments_ineligible": "installments_ineligible"), + + CREATE_ORDER: ("process_create_order": "process_create_order"), + CONFIRM_ORDER: ("process_confirm_order": "process_confirm_order"), + RECEIVE_ORDER: ("process_receive_order": "process_receive_order"), + RECEIVE_VAULT_SETUP_TOKEN: + ("process_receive_vault_setup_token": "process_receive_vault_setup_token"), + CREATE_PAYMENT: ("process_create_payment": "process_create_payment"), + CAPTURE_AUTHORIZATION: + ("process_capture_authorization": "process_capture_authorization"), + + CHECKOUT_SHIPPING_CHANGE: + ("process_checkout_shipping_change": "process_checkout_shipping_change"), + CHECKOUT_SHIPPING_ADDRESS_CHANGE: + ("process_checkout_shipping_address_change": "process_checkout_shipping_address_change"), + CHECKOUT_SHIPPING_OPTIONS_CHANGE: + ("process_checkout_shipping_options_change": "process_checkout_shipping_options_change"), + CHECKOUT_APPROVE: ("process_checkout_approve": "process_checkout_approve"), + CHECKOUT_COMPLETE: ("process_checkout_complete": "process_checkout_complete"), + CHECKOUT_CANCEL: ("process_checkout_cancel": "process_checkout_cancel"), + CHECKOUT_ERROR: ("process_checkout_error": "process_checkout_error"), + + TOKENIZE_APPROVE: ("process_tokenize_approve": "process_tokenize_approve"), + + CONNECT_REDIRECT: ("process_connect_redirect": "process_connect_redirect"), + + FIREBASE_CONNECTION_OPENED: + ("firebase_connection_opened": "firebase_connection_opened"), + FIREBASE_CONNECTION_ERRORED: + ("firebase_connection_errored": "firebase_connection_errored"), + + APPLEPAY_EVENT: ("applepay_event": "applepay_event"), + APPLEPAY_FLOW_ERROR: ("applepay_flow_error": "applepay_flow_error"), + APPLEPAY_ON_CLICK_INVALID: + ("applepay_onclick_invalid": "applepay_onclick_invalid"), + APPLEPAY_MERCHANT_VALIDATION_COMPLETION_ERROR: + ("applepay_merchant_validation_completion_error": "applepay_merchant_validation_completion_error"), + APPLEPAY_MERCHANT_VALIDATION_ERROR: + ("applepay_merchant_validation_error": "applepay_merchant_validation_error"), + APPLEPAY_CREATE_ORDER_ERROR: + ("applepay_create_order_error": "applepay_create_order_error"), + APPLEPAY_GET_DETAILS_ERROR: + ("applepay_get_details_error": "applepay_get_details_error"), + APPLEPAY_PAYMENT_ERROR: ("applepay_payment_error": "applepay_payment_error"), + APPLEPAY_CONFIG_ERROR: ("applepay_config_error": "applepay_config_error"), + + NATIVE_DETECT_POSSIBLE_APP_SWITCH: + ("native_detect_possible_app_switch": "native_detect_possible_app_switch"), + NATIVE_DETECT_APP_SWITCH: + ("native_detect_app_switch": "native_detect_app_switch"), + NATIVE_DETECT_WEB_SWITCH: + ("native_detect_web_switch": "native_detect_web_switch"), + NATIVE_APP_SWITCH_ACK: ("native_app_switch_ack": "native_app_switch_ack"), + NATIVE_ERROR: ("native_app_switch_ack": "native_app_switch_ack"), + NATIVE_APP_INSTALLED: ("native_app_installed": "native_app_installed"), + NATIVE_APP_SWITCH_INELIGIBLE: + ("app_switch_ineligible": "app_switch_ineligible"), + NATIVE_ATTEMPT_APP_SWITCH: ("app_switch_attempted": "app_switch_attempted"), + NATIVE_ATTEMPT_APP_SWITCH_ERRORED: + ("app_switch_attempted_errored": "app_switch_attempted_errored"), + NATIVE_CLOSING_POPUP: ("native_closing_popup": "native_closing_popup"), + NATIVE_POPUP_CLOSED: ("popup_closed": "popup_closed"), + NATIVE_POPUP_HASHCHANGE: ("popup_hashchange": "popup_hashchange"), + NATIVE_POPUP_NO_OPENER: ("popup_no_opener": "popup_no_opener"), + NATIVE_POPUP_ANDROID_APP_ERROR: + ("native_popup_android_app_installed_error": "native_popup_android_app_installed_error"), + NATIVE_POPUP_FALLBACK: ("popup_fallback": "popup_fallback"), + NATIVE_FALLBACK_RETRY_VENMO_APP_SWITCH: + ("native_fallback_retry_venmo_app_switch", + "native_fallback_retry_venmo_app_switch"), + NATIVE_POPUP_SHOWN: ("popup_shown": "popup_shown"), + NATIVE_ON_APPROVE: ("native_onapprove": "native_onapprove"), + NATIVE_ON_APPROVE_ERROR: ("native_onapprove_error": "native_onapprove_error"), + NATIVE_ON_CANCEL: ("native_oncancel": "native_oncancel"), + NATIVE_ON_CLICK_INVALID: ("native_onclick_invalid": "native_onclick_invalid"), + NATIVE_ON_COMPLETE: ("native_oncomplete": "native_oncomplete"), + NATIVE_ON_ERROR: ("native_onerror": "native_onerror"), + NATIVE_ON_SHIPPING_CHANGE: + ("native_onshippingchange": "native_onshippingchange"), + NATIVE_ON_FALLBACK: ("native_onfallback": "native_onfallback"), + NATIVE_POPUP_INIT: ("native_popup_init": "native_popup_init"), + NATIVE_POPUP_UNLOAD: ("native_popup_unload": "native_popup_unload"), + NATIVE_POPUP_BEFORE_UNLOAD: + ("native_popup_beforeunload": "native_popup_beforeunload"), + NATIVE_POPUP_PAGEHIDE: ("native_popup_pagehide": "native_popup_pagehide"), + NATIVE_POPUP_OPENER_DETECT_CLOSE: + ("native_popup_opener_detect_close": "native_popup_opener_detect_close"), + NATIVE_OPT_OUT: ("native_opt_out": "native_opt_out"), + NATIVE_FALLBACK: ("native_fallback": "native_fallback"), + NATIVE_FALLBACK_VENMO: ("native_fallback_venmo": "native_fallback_venmo"), + NATIVE_VENMO_WEB: ("native_venmo_web": "native_venmo_web"), + NATIVE_VENMO_WEB_REDIRECT: + ("native_venmo_web_redirect": "native_venmo_web_redirect"), + + QR_LOAD: ("qr_load": "qr_load"), + QR_SHOWN: ("qr_shown": "qr_shown"), + QR_CLOSING: ("qr_closing": "qr_closing"), + QR_SURVEY: + ("desktop_exit_survey_selection_submitted": "desktop_exit_survey_selection_submitted"), + QR_PREPARE_PAY: ("qr_prepare_pay": "qr_prepare_pay"), + QR_PROCESS_PAY_WITH: ("qr_process_pay_with": "qr_process_pay_with"), + + HONEY_IDENTIFY: ("honey_identify": "honey_identify"), + + CALL_REST_API: ("call_rest_api": "call_rest_api"), + + ORDER_VALIDATE: ("process_order_validate", "process_order_validate"), }; export const FPTI_MENU_OPTION = { - CHOOSE_FUNDING: ('pay_with_different_payment_method' : 'pay_with_different_payment_method'), - CHOOSE_ACCOUNT: ('pay_with_different_account' : 'pay_with_different_account'), - UNLINK_ACCOUNT: ('unlink_account' : 'unlink_account') + CHOOSE_FUNDING: + ("pay_with_different_payment_method": "pay_with_different_payment_method"), + CHOOSE_ACCOUNT: ("pay_with_different_account": "pay_with_different_account"), + UNLINK_ACCOUNT: ("unlink_account": "unlink_account"), }; export const FPTI_BUTTON_TYPE = { - IFRAME: ('iframe' : 'iframe') + IFRAME: ("iframe": "iframe"), }; export const FPTI_CUSTOM_KEY = { - ERR_DESC: ('int_error_desc' : 'int_error_desc'), - HONEY_DEVICE_ID: ('honey_device_id' : 'honey_device_id'), - HONEY_SESSION_ID: ('honey_session_id' : 'honey_session_id'), - INTEGRATION_ISSUE: ('integration_issue' : 'integration_issue'), - INTEGRATION_WHITELIST: ('whitelist' : 'whitelist'), - INFO_MSG: ('info_msg' : 'info_msg'), - PMT_TOKEN: ('pmt_token' : 'pmt_token'), - TRANSITION_TYPE: ('transition_type' : 'transition_type'), - TRANSITION_REASON: ('transition_reason' : 'transition_reason'), - SHIPPING_CALLBACK_PASSED: ('shipping_callback_passed' : 'shipping_callback_passed'), - SHIPPING_CALLBACK_INVOKED: ('shipping_callback_invoked' : 'shipping_callback_invoked'), - DESKTOP_EXIT_SURVEY_REASON: ('desktop_exit_survey_reason' : 'desktop_exit_survey_reason'), - ORDER_CREATED_BY: ('order_created_by' : 'order_created_by') + ERR_DESC: ("int_error_desc": "int_error_desc"), + HONEY_DEVICE_ID: ("honey_device_id": "honey_device_id"), + HONEY_SESSION_ID: ("honey_session_id": "honey_session_id"), + INTEGRATION_ISSUE: ("integration_issue": "integration_issue"), + INTEGRATION_WHITELIST: ("whitelist": "whitelist"), + INFO_MSG: ("info_msg": "info_msg"), + PMT_TOKEN: ("pmt_token": "pmt_token"), + TRANSITION_TYPE: ("transition_type": "transition_type"), + TRANSITION_REASON: ("transition_reason": "transition_reason"), + SHIPPING_CALLBACK_PASSED: + ("shipping_callback_passed": "shipping_callback_passed"), + SHIPPING_CALLBACK_INVOKED: + ("shipping_callback_invoked": "shipping_callback_invoked"), + DESKTOP_EXIT_SURVEY_REASON: + ("desktop_exit_survey_reason": "desktop_exit_survey_reason"), + ORDER_CREATED_BY: ("order_created_by": "order_created_by"), }; export const FPTI_BUTTON_KEY = { - BUTTON_LAYOUT: ('button_layout' : 'button_layout'), - BUTTON_COLOR: ('button_color' : 'button_color'), - BUTTON_SIZE: ('button_size' : 'button_size'), - BUTTON_SHAPE: ('button_shape' : 'button_shape'), - BUTTON_LABEL: ('button_label' : 'button_label'), - BUTTON_WIDTH: ('button_width' : 'button_width'), - BUTTON_TYPE: ('button_type' : 'button_type'), - BUTTON_TAGLINE_ENABLED: ('button_tagline_enabled' : 'button_tagline_enabled'), - BUTTON_CORRELATION_ID: ('button_correlation_id' : 'button_correlation_id') + BUTTON_LAYOUT: ("button_layout": "button_layout"), + BUTTON_COLOR: ("button_color": "button_color"), + BUTTON_SIZE: ("button_size": "button_size"), + BUTTON_SHAPE: ("button_shape": "button_shape"), + BUTTON_LABEL: ("button_label": "button_label"), + BUTTON_WIDTH: ("button_width": "button_width"), + BUTTON_TYPE: ("button_type": "button_type"), + BUTTON_TAGLINE_ENABLED: ("button_tagline_enabled": "button_tagline_enabled"), + BUTTON_CORRELATION_ID: ("button_correlation_id": "button_correlation_id"), }; export const FTPI_WALLET_KEY = { - WALLET_SESSION_UID: ('wallet_session_id' : 'wallet_session_id'), - WALLET_VERSION: ('wallet_version' : 'wallet_version') + WALLET_SESSION_UID: ("wallet_session_id": "wallet_session_id"), + WALLET_VERSION: ("wallet_version": "wallet_version"), }; export const USER_ACTION = { - COMMIT: 'commit', - CONTINUE: 'continue' + COMMIT: "commit", + CONTINUE: "continue", }; export const UPGRADE_LSAT_RAMP = { - EXP_NAME: 'UPGRADE_LSAT_EXPERIMENT', - RAMP: 100 + EXP_NAME: "UPGRADE_LSAT_EXPERIMENT", + RAMP: 100, }; export const FRAME_NAME = { - SMART_FIELDS: 'smart-fields', - CARD_FIELD: 'card-field', - CARD_NUMBER_FIELD: 'card-number-field', - CARD_CVV_FIELD: 'card-cvv-field', - CARD_EXPIRY_FIELD: 'card-expiry-field', - CARD_NAME_FIELD: 'card-name-field', - CARD_POSTAL_FIELD: 'card-postal-field' + SMART_FIELDS: "smart-fields", + CARD_FIELD: "card-field", + CARD_NUMBER_FIELD: "card-number-field", + CARD_CVV_FIELD: "card-cvv-field", + CARD_EXPIRY_FIELD: "card-expiry-field", + CARD_NAME_FIELD: "card-name-field", + CARD_POSTAL_FIELD: "card-postal-field", }; -export const VENMO_BLUE : string = '#3D93CE'; +export const VENMO_BLUE: string = "#3D93CE"; export const QRCODE_STATE = { - ERROR: 'qr_error', - SCANNED: 'qr_scanned', - AUTHORIZED: 'qr_authorized', - DEFAULT: 'qr_default' + ERROR: "qr_error", + SCANNED: "qr_scanned", + AUTHORIZED: "qr_authorized", + DEFAULT: "qr_default", }; - - export const ITEM_CATEGORY = { - DIGITAL: 'DIGITAL', - DONATION: 'DONATION', - PHYSICAL: 'PHYSICAL' + DIGITAL: "DIGITAL", + DONATION: "DONATION", + PHYSICAL: "PHYSICAL", }; export const BUTTON_LABEL = { - DONATE: 'donate' + DONATE: "donate", }; export const STATUS_CODES = { - TOO_MANY_REQUESTS: 429 + TOO_MANY_REQUESTS: 429, }; export const SERVICE_WORKER = { - SERVICE_WORKER_URL: 'https://www.paypal.com/checkout-sw', - SW_SCOPE: '/webapps/hermes', - GET_SW_LOGS_EVENT_NAME: 'GET_SW_LOGS', - LOGS_CHANNEL_NAME: 'logs-channel', - GET_SW_LOGS_RESPONSE_EVENT_NAME: 'GET_SW_LOGS_RESPONSE' + SERVICE_WORKER_URL: "https://www.paypal.com/checkout-sw", + SW_SCOPE: "/webapps/hermes", + GET_SW_LOGS_EVENT_NAME: "GET_SW_LOGS", + LOGS_CHANNEL_NAME: "logs-channel", + GET_SW_LOGS_RESPONSE_EVENT_NAME: "GET_SW_LOGS_RESPONSE", }; export const PAYMENT_FLOWS = { - WITH_PURCHASE: 'with_purchase', - VAULT_WITHOUT_PURCHASE: `vault_without_purchase` -} + WITH_PURCHASE: "with_purchase", + VAULT_WITHOUT_PURCHASE: `vault_without_purchase`, +}; export const ORDER_CREATED_BY = { - HONEY: ('honey': 'honey'), - UNKNOWN_EVENT: ('unknown_event': 'unknown_event'), - BUTTON_CLICK: ('button_click': 'button_click'), -} + HONEY: ("honey": "honey"), + UNKNOWN_EVENT: ("unknown_event": "unknown_event"), + BUTTON_CLICK: ("button_click": "button_click"), +}; diff --git a/src/declarations.js b/src/declarations.js index 31a809d440..7e36ea3208 100644 --- a/src/declarations.js +++ b/src/declarations.js @@ -1,18 +1,16 @@ /* @flow */ // $FlowFixMe[toplevel-library-import] -import type { PayPal } from './types'; +import type { PayPal } from "./types"; -declare var __SMART_BUTTONS__ : {| - __MAJOR_VERSION__ : string, - __MINOR_VERSION__ : string +declare var __SMART_BUTTONS__: {| + __MAJOR_VERSION__: string, + __MINOR_VERSION__: string, |}; // $FlowFixMe[value-as-type] -declare var paypal : PayPal; +declare var paypal: PayPal; declare module CSSModule { - declare var exports: {| - - |}; + declare var exports: {||}; } diff --git a/src/index.js b/src/index.js index c2ab322205..b5f31fa785 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,5 @@ /* @flow */ -export * from './button'; -export * from './menu'; -export * from './card'; +export * from "./button"; +export * from "./menu"; +export * from "./card"; diff --git a/src/lib/3ds.js b/src/lib/3ds.js index d8f7c4c973..844b8f0472 100644 --- a/src/lib/3ds.js +++ b/src/lib/3ds.js @@ -1,107 +1,183 @@ /* eslint-disable compat/compat */ /* @flow */ -import type { CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src'; -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; +import type { CrossDomainWindowType } from "@krakenjs/cross-domain-utils/src"; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; -import { type ValidatePaymentMethodResponse } from '../api'; -import type { ThreeDomainSecureFlowType } from '../types'; -import { TARGET_ELEMENT } from '../constants'; -import { threeDsAuthStatus } from '../card/logger' +import { type ValidatePaymentMethodResponse } from "../api"; +import type { ThreeDomainSecureFlowType } from "../types"; +import { TARGET_ELEMENT } from "../constants"; +import { threeDsAuthStatus } from "../card/logger"; + +import { sendCountMetric } from "./logger"; type CreateOrder = () => ZalgoPromise; type ThreeDomainSecureProps = {| - ThreeDomainSecure : ThreeDomainSecureFlowType, - createOrder : CreateOrder|void, - getParent : () => CrossDomainWindowType, - vaultToken? : string|null , - action ? : string | null, + ThreeDomainSecure: ThreeDomainSecureFlowType, + createOrder: CreateOrder | void, + getParent: () => CrossDomainWindowType, + vaultToken?: string | null, + action?: string | null, |}; type ThreeDomainSecureContingencyProps = {| - ThreeDomainSecure : ThreeDomainSecureFlowType, - createOrder? : CreateOrder, - getParent : () => CrossDomainWindowType, - status : string, - links : $ReadOnlyArray < {| - method : string, - rel : string, - href : string - |}> + ThreeDomainSecure: ThreeDomainSecureFlowType, + createOrder?: CreateOrder, + getParent: () => CrossDomainWindowType, + status: string, + links: $ReadOnlyArray<{| + method: string, + rel: string, + href: string, + |}>, + paymentFlow: string, + fundingSource?: string, |}; -function handleThreeDomainSecureRedirect({ ThreeDomainSecure, vaultToken, createOrder, action, getParent }: ThreeDomainSecureProps): ZalgoPromise { - const promise = new ZalgoPromise(); - const instance = ThreeDomainSecure({ - vaultToken, - createOrder, - action, - onSuccess: (data) => { - threeDsAuthStatus({authStatus: "success"}) - return promise.resolve(data) - }, - onCancel: () => { - threeDsAuthStatus({ authStatus: "cancelled" }) - return promise.reject(new Error(`3DS cancelled`)) - }, - onError: (err) => { - threeDsAuthStatus({ authStatus: "failure" }) - return promise.reject(err) - } - }); +function handleThreeDomainSecureRedirect({ + ThreeDomainSecure, + vaultToken, + createOrder, + action, + getParent, +}: ThreeDomainSecureProps): ZalgoPromise { + const promise = new ZalgoPromise(); + const instance = ThreeDomainSecure({ + vaultToken, + createOrder, + action, + onSuccess: (data) => { + threeDsAuthStatus({ authStatus: "success" }); + return promise.resolve(data); + }, + onCancel: () => { + threeDsAuthStatus({ authStatus: "cancelled" }); + return promise.reject(new Error(`3DS cancelled`)); + }, + onError: (err) => { + threeDsAuthStatus({ authStatus: "failure" }); + return promise.reject(err); + }, + }); - return instance.renderTo(getParent(), TARGET_ELEMENT.BODY) + return instance + .renderTo(getParent(), TARGET_ELEMENT.BODY) .then(() => promise) - .finally(instance.close); + .finally(instance.close); } const getThreeDSParams = (links) => { - const helioslink = links.find(link => link.href.includes("helios")); - // $FlowIssue, eslint-disable-next-line compat/compat - const linkUrl = new URL(helioslink?.href); - const vaultToken = linkUrl.searchParams.get("token"); - const action = linkUrl.searchParams.get("action"); - return { vaultToken, action }; -} + const helioslink = links.find((link) => link.href.includes("helios")); + // $FlowIssue, eslint-disable-next-line compat/compat + const linkUrl = new URL(helioslink?.href); + const vaultToken = linkUrl.searchParams.get("token"); + const action = linkUrl.searchParams.get("action"); + return { vaultToken, action }; +}; + +export function handleThreeDomainSecureContingency({ + status, + links, + ThreeDomainSecure, + createOrder, + getParent, + paymentFlow, + fundingSource, +}: ThreeDomainSecureContingencyProps): ZalgoPromise | void { + const isWithPurchase = (link) => + link.rel === "payer-action" && link.href && link.href.includes("flow=3ds"); + const isWithoutPurchase = (link) => + link.rel === "approve" && link.href.includes("helios"); -export function handleThreeDomainSecureContingency({ status, links, ThreeDomainSecure, createOrder, getParent }: ThreeDomainSecureContingencyProps): ZalgoPromise | void { - const isWithPurchase = (link) => link.rel === "payer-action" && link.href && link.href.includes("flow=3ds"); - const isWithoutPurchase = (link) => (link.rel === "approve" && link.href.includes("helios")); + return ZalgoPromise.try(() => { + if ( + status === "PAYER_ACTION_REQUIRED" && + links.some((link) => isWithPurchase(link) || isWithoutPurchase(link)) + ) { + const contingency = "confirm_payment_source_three_ds_contingency"; - return ZalgoPromise.try(() => { - if (status === "PAYER_ACTION_REQUIRED" && links.some(link => isWithPurchase(link) || isWithoutPurchase(link))) - { - const {vaultToken, action } = getThreeDSParams(links); + if (paymentFlow === "vault-capture") { + sendCountMetric({ + name: `pp.app.paypal_sdk.buttons.vault_capture.contingency.count`, + dimensions: { + fundingSource, + contingency, + }, + }); + } else { + sendCountMetric({ + name: `pp.app.paypal_sdk.card_fields.submit.contingency.count`, + dimensions: { + paymentFlow, + contingency, + }, + }); + } - return handleThreeDomainSecureRedirect({ ThreeDomainSecure, createOrder, vaultToken, getParent, action}); - } - }); + const { vaultToken, action } = getThreeDSParams(links); + return handleThreeDomainSecureRedirect({ + ThreeDomainSecure, + createOrder, + vaultToken, + getParent, + action, + }); + } + }); } type HandleValidatePaymentMethodResponse = {| - ThreeDomainSecure : ThreeDomainSecureFlowType, - status : number, - body : ValidatePaymentMethodResponse, - createOrder : CreateOrder, - getParent : () => CrossDomainWindowType + ThreeDomainSecure: ThreeDomainSecureFlowType, + status: number, + body: ValidatePaymentMethodResponse, + createOrder: CreateOrder, + getParent: () => CrossDomainWindowType, |}; -export function handleValidatePaymentMethodResponse({ ThreeDomainSecure, status, body, createOrder, getParent }: HandleValidatePaymentMethodResponse): ZalgoPromise { - return ZalgoPromise.try(() => { - if (status === 422 && body.links && body.links.some(link => link.rel === '3ds-contingency-resolution')) { - return handleThreeDomainSecureRedirect({ ThreeDomainSecure, createOrder, getParent }); - } +export function handleValidatePaymentMethodResponse({ + ThreeDomainSecure, + status, + body, + createOrder, + getParent, +}: HandleValidatePaymentMethodResponse): ZalgoPromise { + return ZalgoPromise.try(() => { + if ( + status === 422 && + body.links && + body.links.some((link) => link.rel === "3ds-contingency-resolution") + ) { + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.vault_capture.contingency.count", + dimensions: { + contingency: "validate_payment_method_three_ds_contingency", + }, + }); - if (status !== 200) { + return handleThreeDomainSecureRedirect({ + ThreeDomainSecure, + createOrder, + getParent, + }); + } - const hasDescriptiveErrorCode = Array.isArray(body.details); - if (hasDescriptiveErrorCode) { - const details = body.details && body.details[0]; - const { issue = '' } = details || {}; - if (issue.trim().length !== 0) { - throw new Error(`Validate payment failed with issue: ${issue}`); - } - } + if (status !== 200) { + sendCountMetric({ + name: "pp.app.paypal_sdk.buttons.vault_capture.error.count", + event: "error", + dimensions: { + errorName: "validate_payment_method_failure", + }, + }); - throw new Error(`Validate payment failed with status: ${status}`); + const hasDescriptiveErrorCode = Array.isArray(body.details); + if (hasDescriptiveErrorCode) { + const details = body.details && body.details[0]; + const { issue = "" } = details || {}; + if (issue.trim().length !== 0) { + throw new Error(`Validate payment failed with issue: ${issue}`); } - }); + } + + throw new Error(`Validate payment failed with status: ${status}`); + } + }); } -/* eslint-enable compat/compat */ \ No newline at end of file +/* eslint-enable compat/compat */ diff --git a/src/lib/comms.js b/src/lib/comms.js index 03661c1e87..b6f7c4a620 100644 --- a/src/lib/comms.js +++ b/src/lib/comms.js @@ -1,25 +1,28 @@ /* @flow */ -import { getAllFramesInWindow, isSameDomain } from '@krakenjs/cross-domain-utils/src'; +import { + getAllFramesInWindow, + isSameDomain, +} from "@krakenjs/cross-domain-utils/src"; -import type { SmartFields } from '../types'; -import { FRAME_NAME } from '../constants'; +import type { SmartFields } from "../types"; +import { FRAME_NAME } from "../constants"; -export function getSmartFieldsByFundingSource(fundingSource : string) : ?SmartFields { - - try { - for (const win of getAllFramesInWindow(window)) { - - if ( - isSameDomain(win) && - // $FlowFixMe - win.exports && - win.exports.name === FRAME_NAME.SMART_FIELDS && - win.exports.fundingSource === fundingSource - ) { - return win.exports; - } - } - } catch (err) { - // pass +export function getSmartFieldsByFundingSource( + fundingSource: string, +): ?SmartFields { + try { + for (const win of getAllFramesInWindow(window)) { + if ( + isSameDomain(win) && + // $FlowFixMe + win.exports && + win.exports.name === FRAME_NAME.SMART_FIELDS && + win.exports.fundingSource === fundingSource + ) { + return win.exports; + } } + } catch (err) { + // pass + } } diff --git a/src/lib/dom.js b/src/lib/dom.js index 26cc79dfc7..6b7e71b87e 100644 --- a/src/lib/dom.js +++ b/src/lib/dom.js @@ -1,13 +1,13 @@ /* @flow */ -import { DATA_ATTRIBUTES } from '../constants'; +import { DATA_ATTRIBUTES } from "../constants"; -export function getNonce() : string { - let nonce = ''; - if (document.body) { - nonce = document.body.getAttribute(`${ DATA_ATTRIBUTES.NONCE }`) || ''; - } - return nonce; +export function getNonce(): string { + let nonce = ""; + if (document.body) { + nonce = document.body.getAttribute(`${DATA_ATTRIBUTES.NONCE}`) || ""; + } + return nonce; } // this is admittedly a bit silly, but it makes testing @@ -15,6 +15,6 @@ export function getNonce() : string { // since we can just mock this function instead of // overriding properties on the document and polluting // other tests -export function getActiveElement () : null | HTMLElement { - return document.activeElement; +export function getActiveElement(): null | HTMLElement { + return document.activeElement; } diff --git a/src/lib/index.js b/src/lib/index.js index 44f69b4635..d3cb42cfd9 100644 --- a/src/lib/index.js +++ b/src/lib/index.js @@ -1,10 +1,10 @@ /* @flow */ -export * from './util'; -export * from './logger'; -export * from './dom'; -export * from './comms'; -export * from './session'; -export * from './sdk'; -export * from './perceived-latency-instrumentation'; -export * from './register-service-worker'; +export * from "./util"; +export * from "./logger"; +export * from "./dom"; +export * from "./comms"; +export * from "./session"; +export * from "./sdk"; +export * from "./perceived-latency-instrumentation"; +export * from "./register-service-worker"; diff --git a/src/lib/logger.js b/src/lib/logger.js index b6b4aa5b68..e94ce0ede6 100644 --- a/src/lib/logger.js +++ b/src/lib/logger.js @@ -25,22 +25,25 @@ import { LOGGER_URL } from "../config"; export function getLogger(): LoggerType { const disableSetCookieQuery = "disableSetCookie=true"; - - const loggerUrl = window && typeof window.xprops === "object" && window.xprops.disableSetCookie - ? `${LOGGER_URL}?${disableSetCookieQuery}` - : LOGGER_URL; - + + const loggerUrl = + window && + typeof window.xprops === "object" && + window.xprops.disableSetCookie + ? `${LOGGER_URL}?${disableSetCookieQuery}` + : LOGGER_URL; + return inlineMemoize(getLogger, () => Logger({ url: loggerUrl, enableSendBeacon: true, - }) + }), ); } export const sendCountMetric = ({ dimensions, - event = 'unused', + event = "unused", name, value = 1, }: {| @@ -48,37 +51,39 @@ export const sendCountMetric = ({ name: string, value?: number, dimensions: { - [string]: mixed + [string]: mixed, }, // $FlowIssue return type -|}) => getLogger().metric({ +|}) => + getLogger().metric({ dimensions, metricEventName: event, metricNamespace: name, metricValue: value, - metricType: "counter" - }) + metricType: "counter", + }); - export const sendGaugeMetric = ({ - dimensions, - event = 'unused', - name, - value, - }: {| - event?: string, - name: string, - value: number, - dimensions: { - [string]: mixed - }, +export const sendGaugeMetric = ({ + dimensions, + event = "unused", + name, + value, +}: {| + event?: string, + name: string, + value: number, + dimensions: { + [string]: mixed, + }, // $FlowIssue return type - |}) => getLogger().metric({ - dimensions, - metricEventName: event, - metricNamespace: name, - metricValue: value, - metricType: "gauge" - }) +|}) => + getLogger().metric({ + dimensions, + metricEventName: event, + metricNamespace: name, + metricValue: value, + metricType: "gauge", + }); type MobileEnvironment = $Values; @@ -148,11 +153,11 @@ export function setupLogger({ }); sendCountMetric({ - event: 'error', - name: 'pp.app.paypal_sdk.buttons.unhandled_exception.count', + event: "error", + name: "pp.app.paypal_sdk.buttons.unhandled_exception.count", dimensions: { - errorType: "payments_sdk_error" - } + errorType: "payments_sdk_error", + }, }); // eslint-disable-next-line promise/no-promise-in-callback diff --git a/src/lib/logger.test.js b/src/lib/logger.test.js index 8606361b7d..5c9cada393 100644 --- a/src/lib/logger.test.js +++ b/src/lib/logger.test.js @@ -43,14 +43,14 @@ describe("setupLogger", () => { it("logs unhandled errors", () => { vi.spyOn( ZalgoPromise, - "onPossiblyUnhandledException" + "onPossiblyUnhandledException", ).mockImplementationOnce((d) => d()); const mockError = vi.fn(); vi.spyOn(getLogger(), "error").mockImplementationOnce(mockError); setupLogger(loggerProps); expect(mockError).toHaveBeenCalledWith( "unhandled_error", - expect.any(Object) + expect.any(Object), ); }); }); diff --git a/src/lib/perceived-latency-instrumentation.js b/src/lib/perceived-latency-instrumentation.js index 462848ca72..376dfffc21 100644 --- a/src/lib/perceived-latency-instrumentation.js +++ b/src/lib/perceived-latency-instrumentation.js @@ -1,27 +1,30 @@ /* @flow */ type InstrumentationPayload = {| - comp? : mixed, - chunk? : mixed, - query? : mixed + comp?: mixed, + chunk?: mixed, + query?: mixed, |}; /** * Prepare instrumentation Payload to be sent to logger * @param responseStartTime * @param responseEndTime */ -export function prepareLatencyInstrumentationPayload (responseStartTime : number, responseEndTime : number) : InstrumentationPayload { - const epochNow = Date.now(); - return { - comp: { - 'second-render-response': { - start: responseStartTime, - tt: responseEndTime - responseStartTime - }, - 'second-render-body': { - start: responseEndTime, - tt: epochNow - responseEndTime - } - } - }; +export function prepareLatencyInstrumentationPayload( + responseStartTime: number, + responseEndTime: number, +): InstrumentationPayload { + const epochNow = Date.now(); + return { + comp: { + "second-render-response": { + start: responseStartTime, + tt: responseEndTime - responseStartTime, + }, + "second-render-body": { + start: responseEndTime, + tt: epochNow - responseEndTime, + }, + }, + }; } diff --git a/src/lib/perceived-latency-instrumentation.test.js b/src/lib/perceived-latency-instrumentation.test.js index cd2aacf74c..a0f7718229 100644 --- a/src/lib/perceived-latency-instrumentation.test.js +++ b/src/lib/perceived-latency-instrumentation.test.js @@ -22,7 +22,10 @@ describe("customer perceived latency instrumentation utils", () => { }, }; expect( - prepareLatencyInstrumentationPayload(responseStartTime, responseEndTime) + prepareLatencyInstrumentationPayload( + responseStartTime, + responseEndTime, + ), ).toEqual(preparedPayload); }); }); diff --git a/src/lib/register-service-worker.js b/src/lib/register-service-worker.js index dc19b0ab46..6f4b82823e 100644 --- a/src/lib/register-service-worker.js +++ b/src/lib/register-service-worker.js @@ -9,154 +9,174 @@ // To learn more about the benefits of this model, read https://goo.gl/KwvDNy. // This link also includes instructions on opting out of this behavior. -import { stringifyError } from '@krakenjs/belter/src'; +import { stringifyError } from "@krakenjs/belter/src"; import { FPTI_KEY } from "@paypal/sdk-constants/src"; -import { SERVICE_WORKER, CLASS } from '../constants'; +import { SERVICE_WORKER, CLASS } from "../constants"; -import { getLogger } from './logger'; +import { getLogger } from "./logger"; const { - SERVICE_WORKER_URL, - SW_SCOPE, - GET_SW_LOGS_EVENT_NAME, - LOGS_CHANNEL_NAME, - GET_SW_LOGS_RESPONSE_EVENT_NAME + SERVICE_WORKER_URL, + SW_SCOPE, + GET_SW_LOGS_EVENT_NAME, + LOGS_CHANNEL_NAME, + GET_SW_LOGS_RESPONSE_EVENT_NAME, } = SERVICE_WORKER; -const LOG_PREFIX = 'SERVICE_WORKER_'; +const LOG_PREFIX = "SERVICE_WORKER_"; let broadcastChannel = {}; type RegisterServiceWorkerParams = {| - dumbledoreCurrentReleaseHash? : string, - dumbledoreServiceWorker? : string, + dumbledoreCurrentReleaseHash?: string, + dumbledoreServiceWorker?: string, |}; const requestSwLogs = () => { - broadcastChannel.postMessage({ - type: GET_SW_LOGS_EVENT_NAME - }); + broadcastChannel.postMessage({ + type: GET_SW_LOGS_EVENT_NAME, + }); }; const startBroadCastChannel = () => { - broadcastChannel = new BroadcastChannel(LOGS_CHANNEL_NAME); + broadcastChannel = new BroadcastChannel(LOGS_CHANNEL_NAME); }; const listenBroadCastChannelEvents = () => { - // Listen SW flush logs event - broadcastChannel.addEventListener('message', (event : Event) => { - // $FlowFixMe - const { payload = [], eventName } = event.data; - if (payload && eventName === GET_SW_LOGS_RESPONSE_EVENT_NAME) { - getLogger().info(`${ LOG_PREFIX }LOGS`, { - logs: JSON.stringify(payload) - }); - } - }); + // Listen SW flush logs event + broadcastChannel.addEventListener("message", (event: Event) => { + // $FlowFixMe + const { payload = [], eventName } = event.data; + if (payload && eventName === GET_SW_LOGS_RESPONSE_EVENT_NAME) { + getLogger().info(`${LOG_PREFIX}LOGS`, { + logs: JSON.stringify(payload), + }); + } + }); }; const registerButtonHandlers = () => { - const paypalButtons = document.getElementsByClassName(CLASS.BUTTON); - for (let i = 0; i < paypalButtons.length; i++) { - paypalButtons[i].addEventListener('click', requestSwLogs); - } -} + const paypalButtons = document.getElementsByClassName(CLASS.BUTTON); + for (let i = 0; i < paypalButtons.length; i++) { + paypalButtons[i].addEventListener("click", requestSwLogs); + } +}; const unRegisterButtonHandlers = () => { - const paypalButtons = document.getElementsByClassName(CLASS.BUTTON); - for (let i = 0; i < paypalButtons.length; i++) { - paypalButtons[i].removeEventListener('click', requestSwLogs); - } -} + const paypalButtons = document.getElementsByClassName(CLASS.BUTTON); + for (let i = 0; i < paypalButtons.length; i++) { + paypalButtons[i].removeEventListener("click", requestSwLogs); + } +}; const startRegistration = (swUrl) => { - // eslint-disable-next-line compat/compat - navigator.serviceWorker - ?.register(swUrl, { scope: SW_SCOPE }) - .then((registration) => { - - getLogger().info(`${ LOG_PREFIX }REGISTERED`); - - registration.addEventListener('updatefound', () => { - const installingWorker = registration.installing; - - if (installingWorker) { - installingWorker.addEventListener('statechange', () => { - const state = installingWorker.state; - if (state === 'activated') { - requestSwLogs(); - } - getLogger().info(`${ LOG_PREFIX }REGISTERING: ${ installingWorker.state }`); - }); - } - - }); - }) - .catch((err) => { - getLogger().error(`${ LOG_PREFIX }ERROR_REGISTERING`, { err: stringifyError(err) }); - unRegisterButtonHandlers(); - }); -} + // eslint-disable-next-line compat/compat + navigator.serviceWorker + ?.register(swUrl, { scope: SW_SCOPE }) + .then((registration) => { + getLogger().info(`${LOG_PREFIX}REGISTERED`); + + registration.addEventListener("updatefound", () => { + const installingWorker = registration.installing; + + if (installingWorker) { + installingWorker.addEventListener("statechange", () => { + const state = installingWorker.state; + if (state === "activated") { + requestSwLogs(); + } + getLogger().info( + `${LOG_PREFIX}REGISTERING: ${installingWorker.state}`, + ); + }); + } + }); + }) + .catch((err) => { + getLogger().error(`${LOG_PREFIX}ERROR_REGISTERING`, { + err: stringifyError(err), + }); + unRegisterButtonHandlers(); + }); +}; -export function getSanitizedUrl (releaseHash: string, serviceWorker: string): string { - const clearedHash = releaseHash.replace(/[^0-9a-z]/gi, ''); - // eslint-disable-next-line compat/compat - const sanitizedUrl = new URL(`${SERVICE_WORKER_URL}/${serviceWorker}?releaseHash=${clearedHash}`); - return sanitizedUrl.toString(); +export function getSanitizedUrl( + releaseHash: string, + serviceWorker: string, +): string { + const clearedHash = releaseHash.replace(/[^0-9a-z]/gi, ""); + // eslint-disable-next-line compat/compat + const sanitizedUrl = new URL( + `${SERVICE_WORKER_URL}/${serviceWorker}?releaseHash=${clearedHash}`, + ); + return sanitizedUrl.toString(); } const executeServiceWorker = (releaseHash: string, serviceWorker: string) => { - const swUrl = getSanitizedUrl(releaseHash, serviceWorker); - - getLogger().info(`${ LOG_PREFIX }REGISTER_START`, { - url: swUrl - }); - if(swUrl){ - startRegistration(swUrl); - } - else { - getLogger().error(`${ LOG_PREFIX }ERROR_DURING_SWURL_GENERATION`); - } -} + const swUrl = getSanitizedUrl(releaseHash, serviceWorker); + + getLogger().info(`${LOG_PREFIX}REGISTER_START`, { + url: swUrl, + }); + if (swUrl) { + startRegistration(swUrl); + } else { + getLogger().error(`${LOG_PREFIX}ERROR_DURING_SWURL_GENERATION`); + } +}; -export function registerServiceWorker({ dumbledoreCurrentReleaseHash, dumbledoreServiceWorker }: RegisterServiceWorkerParams) { - // Browser eligibility criteria for SW registration - if ('serviceWorker' in navigator === false || 'BroadcastChannel' in window === false) { - getLogger().info(`${ LOG_PREFIX }NOT_SUPPORTED`, { - serviceWorker: Boolean('serviceWorker' in navigator), - BroadcastChannel: Boolean('BroadcastChannel' in window), - }).track({ - [FPTI_KEY.EVENT_NAME]: `${ LOG_PREFIX }NOT_ELIGIBILE`, - }); - return; - } - getLogger().track({ - [FPTI_KEY.EVENT_NAME]: `${ LOG_PREFIX }ELIGIBILE`, +export function registerServiceWorker({ + dumbledoreCurrentReleaseHash, + dumbledoreServiceWorker, +}: RegisterServiceWorkerParams) { + // Browser eligibility criteria for SW registration + if ( + "serviceWorker" in navigator === false || + "BroadcastChannel" in window === false + ) { + getLogger() + .info(`${LOG_PREFIX}NOT_SUPPORTED`, { + serviceWorker: Boolean("serviceWorker" in navigator), + BroadcastChannel: Boolean("BroadcastChannel" in window), + }) + .track({ + [FPTI_KEY.EVENT_NAME]: `${LOG_PREFIX}NOT_ELIGIBILE`, + }); + return; + } + getLogger().track({ + [FPTI_KEY.EVENT_NAME]: `${LOG_PREFIX}ELIGIBILE`, + }); + if (!dumbledoreCurrentReleaseHash) { + getLogger().error(`${LOG_PREFIX}RELEASE_HASH_NOT_PROVIDED`, { + releaseHash: dumbledoreCurrentReleaseHash, }); - if (!dumbledoreCurrentReleaseHash) { - getLogger().error(`${ LOG_PREFIX }RELEASE_HASH_NOT_PROVIDED`, { releaseHash: dumbledoreCurrentReleaseHash }); - return; - } - if (!dumbledoreServiceWorker) { - getLogger().error(`${ LOG_PREFIX }SERVICE_WORKER_URL_NOT_PROVIDED`, { serviceWorker: dumbledoreServiceWorker }); - return; - } - try { - registerButtonHandlers(); - startBroadCastChannel(); - listenBroadCastChannelEvents(); - executeServiceWorker(dumbledoreCurrentReleaseHash, dumbledoreServiceWorker); - } catch (err) { - getLogger().error(`${ LOG_PREFIX }ERROR_DURING_INITIALIZATION`, { err: stringifyError(err) }); - } + return; + } + if (!dumbledoreServiceWorker) { + getLogger().error(`${LOG_PREFIX}SERVICE_WORKER_URL_NOT_PROVIDED`, { + serviceWorker: dumbledoreServiceWorker, + }); + return; + } + try { + registerButtonHandlers(); + startBroadCastChannel(); + listenBroadCastChannelEvents(); + executeServiceWorker(dumbledoreCurrentReleaseHash, dumbledoreServiceWorker); + } catch (err) { + getLogger().error(`${LOG_PREFIX}ERROR_DURING_INITIALIZATION`, { + err: stringifyError(err), + }); + } } export function unregisterServiceWorker() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker?.ready.then((registration) => { - getLogger().info(`${ LOG_PREFIX }UNREGISTER`); - registration.unregister(); - unRegisterButtonHandlers(); - }); - } + if ("serviceWorker" in navigator) { + navigator.serviceWorker?.ready.then((registration) => { + getLogger().info(`${LOG_PREFIX}UNREGISTER`); + registration.unregister(); + unRegisterButtonHandlers(); + }); + } } diff --git a/src/lib/register-service-worker.test.js b/src/lib/register-service-worker.test.js index 987d61ae9c..4c848453fb 100644 --- a/src/lib/register-service-worker.test.js +++ b/src/lib/register-service-worker.test.js @@ -15,7 +15,7 @@ const { SERVICE_WORKER_URL } = SERVICE_WORKER; const waitForExpect = function waitForExpect( expectation: () => void | Promise, timeout = 4500, - interval = 50 + interval = 50, // eslint-disable-next-line flowtype/no-weak-types ): Promise { if (interval < 1) { @@ -92,7 +92,7 @@ describe("Test service worker url generation", () => { "service-worker.d13e6de5a39aafd6b06bd1d18d165c8d.js"; const sanitizedUrl = getSanitizedUrl( invalidReleaseHash, - dumbledoreServiceWorker + dumbledoreServiceWorker, ); const expectedUrl = "https://www.paypal.com/checkout-sw/service-worker.d13e6de5a39aafd6b06bd1d18d165c8d.js?releaseHash=b6cc430fb82802fb9363767b8a7c38187fa4a9d7"; @@ -106,7 +106,7 @@ describe("Test service worker url generation", () => { "service-worker.d13e6de5a39aafd6b06bd1d18d165c8d.js"; const sanitizedUrl = getSanitizedUrl( invalidReleaseHash, - dumbledoreServiceWorker + dumbledoreServiceWorker, ); const expectedUrl = "https://www.paypal.com/checkout-sw/service-worker.d13e6de5a39aafd6b06bd1d18d165c8d.js?releaseHash=b6cc430fb82802fb9363767b8a7c38187fa4a9d7"; diff --git a/src/lib/sdk.js b/src/lib/sdk.js index ec6f6f2378..72e1a1a534 100644 --- a/src/lib/sdk.js +++ b/src/lib/sdk.js @@ -1,68 +1,76 @@ /* @flow */ -import type { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import type { ProxyWindow } from '@krakenjs/post-robot/src'; +import type { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import type { ProxyWindow } from "@krakenjs/post-robot/src"; // eslint-disable-next-line no-duplicate-imports -import typeof { send, once, on, toProxyWindow as toProxyWindowType } from '@krakenjs/post-robot/src'; -import type { CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src'; +import typeof { + send, + once, + on, + toProxyWindow as toProxyWindowType, +} from "@krakenjs/post-robot/src"; +import type { CrossDomainWindowType } from "@krakenjs/cross-domain-utils/src"; type PostRobot = {| - send : send, - once : once, - on : on, - toProxyWindow : toProxyWindowType + send: send, + once: once, + on: on, + toProxyWindow: toProxyWindowType, |}; type PayPal = {| - postRobot : PostRobot, - version : string + postRobot: PostRobot, + version: string, |}; -export function getPayPal() : PayPal { - if (!window.paypal) { - throw new Error(`paypal not found`); - } +export function getPayPal(): PayPal { + if (!window.paypal) { + throw new Error(`paypal not found`); + } - return window.paypal; + return window.paypal; } -export function getPostRobot() : PostRobot { - const paypal = getPayPal(); +export function getPostRobot(): PostRobot { + const paypal = getPayPal(); - if (!paypal.postRobot) { - throw new Error(`paypal.postRobot not found`); - } + if (!paypal.postRobot) { + throw new Error(`paypal.postRobot not found`); + } - return paypal.postRobot; + return paypal.postRobot; } -export function toProxyWindow(win : CrossDomainWindowType | ProxyWindow) : ProxyWindow { - return getPostRobot().toProxyWindow(win); +export function toProxyWindow( + win: CrossDomainWindowType | ProxyWindow, +): ProxyWindow { + return getPostRobot().toProxyWindow(win); } export function postRobotOnceProxy( - event : string, - { proxyWin, domain } : {| proxyWin : ProxyWindow, domain : string |}, - handler : ({| data : T |}) => ZalgoPromise | D -) : {| cancel : () => void |} { + event: string, + { proxyWin, domain }: {| proxyWin: ProxyWindow, domain: string |}, + handler: ({| data: T |}) => ZalgoPromise | D, +): {| cancel: () => void |} { + let cancelled = false; - let cancelled = false; + let cancel = () => { + cancelled = true; + }; - let cancel = () => { - cancelled = true; - }; - - proxyWin.awaitWindow().then(win => { - if (!cancelled) { - cancel = getPostRobot().once(event, { window: win, domain }, ({ data }) => handler({ data })).cancel; - } - }); + proxyWin.awaitWindow().then((win) => { + if (!cancelled) { + cancel = getPostRobot().once(event, { window: win, domain }, ({ data }) => + handler({ data }), + ).cancel; + } + }); - return { - cancel - }; + return { + cancel, + }; } -export function getSDKVersion() : string { - return getPayPal().version; +export function getSDKVersion(): string { + return getPayPal().version; } diff --git a/src/lib/session.js b/src/lib/session.js index 3ddd2bcbc3..0c7b1cb65a 100644 --- a/src/lib/session.js +++ b/src/lib/session.js @@ -1,44 +1,44 @@ /* @flow */ -import { hashStr, getStorage, type Storage } from '@krakenjs/belter/src'; -import getBrowserFingerprint from 'get-browser-fingerprint'; +import { hashStr, getStorage, type Storage } from "@krakenjs/belter/src"; +import getBrowserFingerprint from "get-browser-fingerprint"; -function getSDKStorage() : Storage { - const STORAGE_LIFETIME_1_HOUR = 60 * 60 * 1000; - return getStorage({ - name: 'paypal', - lifetime: STORAGE_LIFETIME_1_HOUR - }); +function getSDKStorage(): Storage { + const STORAGE_LIFETIME_1_HOUR = 60 * 60 * 1000; + return getStorage({ + name: "paypal", + lifetime: STORAGE_LIFETIME_1_HOUR, + }); } -export function getSessionID() : string { - return getSDKStorage().getSessionID(); +export function getSessionID(): string { + return getSDKStorage().getSessionID(); } -export function getStorageState(handler : (storage : Object) => T) : T { - return getSDKStorage().getState(handler); +export function getStorageState(handler: (storage: Object) => T): T { + return getSDKStorage().getState(handler); } -export function getStorageID() : string { - return getSDKStorage().getID(); +export function getStorageID(): string { + return getSDKStorage().getID(); } -export function isStorageStateFresh() : boolean { - return getSDKStorage().isStateFresh(); +export function isStorageStateFresh(): boolean { + return getSDKStorage().isStateFresh(); } -export function getSessionState(handler : (state : Object) => T) : T { - return getSDKStorage().getSessionState(handler); +export function getSessionState(handler: (state: Object) => T): T { + return getSDKStorage().getSessionState(handler); } -export function getStickinessID() : string { - return (hashStr(getBrowserFingerprint().toString()) % 100).toString(); +export function getStickinessID(): string { + return (hashStr(getBrowserFingerprint().toString()) % 100).toString(); } let buyerAccessToken; -export function getBuyerAccessToken() : ?string { - return buyerAccessToken; +export function getBuyerAccessToken(): ?string { + return buyerAccessToken; } -export function setBuyerAccessToken(token : ?string) : void { - buyerAccessToken = token; +export function setBuyerAccessToken(token: ?string): void { + buyerAccessToken = token; } diff --git a/src/lib/session.test.js b/src/lib/session.test.js index fc57358112..488a12df3d 100644 --- a/src/lib/session.test.js +++ b/src/lib/session.test.js @@ -35,7 +35,7 @@ describe("getStorageState", () => { expect(mockFn).toHaveBeenCalledWith( expect.objectContaining({ __session__: expect.any(Object), - }) + }), ); }); }); diff --git a/src/lib/util.js b/src/lib/util.js index e380113860..df5ad3bd3a 100644 --- a/src/lib/util.js +++ b/src/lib/util.js @@ -1,172 +1,196 @@ /* @flow */ -import { ZalgoPromise } from '@krakenjs/zalgo-promise/src'; -import { noop, experiment, isAndroid, isIos, isChrome, isSafari, type Experiment } from '@krakenjs/belter/src'; -import { FPTI_KEY } from '@paypal/sdk-constants/src'; -import type { ProxyWindow } from '@krakenjs/post-robot/src'; -import { onCloseWindow } from '@krakenjs/cross-domain-utils/src'; +import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; +import { + noop, + experiment, + isAndroid, + isIos, + isChrome, + isSafari, + type Experiment, +} from "@krakenjs/belter/src"; +import { FPTI_KEY } from "@paypal/sdk-constants/src"; +import type { ProxyWindow } from "@krakenjs/post-robot/src"; +import { onCloseWindow } from "@krakenjs/cross-domain-utils/src"; -import { FPTI_STATE, FPTI_TRANSITION } from '../constants'; +import { FPTI_STATE, FPTI_TRANSITION } from "../constants"; -import { getLogger } from './logger'; +import { getLogger } from "./logger"; - -export function unresolvedPromise() : ZalgoPromise { - return new ZalgoPromise(noop); +export function unresolvedPromise(): ZalgoPromise { + return new ZalgoPromise(noop); } -export function promiseNoop(...args : $ReadOnlyArray) : ZalgoPromise { // eslint-disable-line no-unused-vars - return ZalgoPromise.resolve(); +// eslint-disable-next-line no-unused-vars +export function promiseNoop(...args: $ReadOnlyArray): ZalgoPromise { + return ZalgoPromise.resolve(); } -export function getBody() : HTMLBodyElement { - const body = document.body; +export function getBody(): HTMLBodyElement { + const body = document.body; - if (!body) { - throw new Error(`Document body not found`); - } + if (!body) { + throw new Error(`Document body not found`); + } - return body; + return body; } -export function sendBeacon(url : string) { - const img = document.createElement('img'); - img.src = url; - img.style.visibility = 'hidden'; - img.style.position = 'absolute'; - if (document.body) { - document.body.appendChild(img); - } +export function sendBeacon(url: string) { + const img = document.createElement("img"); + img.src = url; + img.style.visibility = "hidden"; + img.style.position = "absolute"; + if (document.body) { + document.body.appendChild(img); + } } -export function sleep(time : number) : ZalgoPromise { - return new ZalgoPromise(resolve => { - setTimeout(resolve, time); - }); +export function sleep(time: number): ZalgoPromise { + return new ZalgoPromise((resolve) => { + setTimeout(resolve, time); + }); } -export function redirectTop(url : string) { - if (__TEST__) { - window.location.hash = url; - } else { - window.top.location = url; - } +export function redirectTop(url: string) { + if (__TEST__) { + window.location.hash = url; + } else { + window.top.location = url; + } } -export function loadScript(url : string) : ZalgoPromise { - return new ZalgoPromise((resolve, reject) => { - const container = document.body || document.head; - - if (!container) { - return reject(new Error(`Can not find container for script: ${ url }`)); - } +export function loadScript(url: string): ZalgoPromise { + return new ZalgoPromise((resolve, reject) => { + const container = document.body || document.head; - const script = document.createElement('script'); - script.setAttribute('src', url); - script.addEventListener('load', () => resolve(script)); - // $FlowFixMe - script.addEventListener('error', (err) => reject(err)); - container.appendChild(script); - }); -} + if (!container) { + return reject(new Error(`Can not find container for script: ${url}`)); + } -export function promiseOne(promises : $ReadOnlyArray>) : ZalgoPromise { - return new ZalgoPromise((resolve, reject) => { - for (const promise of promises) { - promise.then(resolve, reject); - } - }); + const script = document.createElement("script"); + script.setAttribute("src", url); + script.addEventListener("load", () => resolve(script)); + // $FlowFixMe + script.addEventListener("error", (err) => reject(err)); + container.appendChild(script); + }); +} + +export function promiseOne( + promises: $ReadOnlyArray>, +): ZalgoPromise { + return new ZalgoPromise((resolve, reject) => { + for (const promise of promises) { + promise.then(resolve, reject); + } + }); } -export function isServer() : boolean { - return (typeof window === 'undefined'); +export function isServer(): boolean { + return typeof window === "undefined"; } -export function isClient() : boolean { - return (typeof window !== 'undefined'); +export function isClient(): boolean { + return typeof window !== "undefined"; } -export function isEmailAddress(str : string) : boolean { - return Boolean(str.match(/^.+@.+\..+$/)); +export function isEmailAddress(str: string): boolean { + return Boolean(str.match(/^.+@.+\..+$/)); } type CreateExperimentOptions = {| - sample : number, - sticky? : boolean + sample: number, + sticky?: boolean, |}; -export function createExperiment(name : string, { sample, sticky = true } : CreateExperimentOptions) : Experiment { - const logger = getLogger(); - - return experiment({ - name, - sample, - - logTreatment({ treatment, payload }) { - - // $FlowFixMe - const fullPayload = { - [FPTI_KEY.STATE]: FPTI_STATE.PXP, - [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.PXP, - [FPTI_KEY.EXPERIMENT_NAME]: name, - [FPTI_KEY.TREATMENT_NAME]: treatment, - ...payload - }; - - logger.track(fullPayload); - logger.flush(); - }, - - logCheckpoint({ treatment, checkpoint, payload, throttle }) { - // $FlowIssue payload type mismatch - logger.info(`${ treatment }_${ checkpoint }`, { ...payload, throttle: throttle.toString() }); - logger.flush(); - }, - - sticky - }); -} - -export function isIOSSafari() : boolean { - return isIos() && isSafari(); -} - -export function isAndroidChrome() : boolean { - return isAndroid() && isChrome(); -} - -export function onCloseProxyWindow(proxyWin : ProxyWindow, callback : Function, delay : number = 1000, maxtime : number = Infinity) : {| cancel : () => void |} { - let cancelled = false; - - let cancel = () => { - cancelled = true; - }; - - proxyWin.awaitWindow().then(win => { - if (!cancelled) { - cancel = onCloseWindow(win, callback, delay, maxtime).cancel; - } - }); - - return { - cancel - }; -} - -export function getNavigationTimeOrigin() : number { - if (window.performance) { - const hrSyncPoint = window.performance.now(); - const unixSyncPoint = new Date().getTime(); - return window.performance.timeOrigin || window.performance.timing.navigationStart || (unixSyncPoint - hrSyncPoint); - } else { - throw new Error('window.performance not supported'); +export function createExperiment( + name: string, + { sample, sticky = true }: CreateExperimentOptions, +): Experiment { + const logger = getLogger(); + + return experiment({ + name, + sample, + + logTreatment({ treatment, payload }) { + // $FlowFixMe + const fullPayload = { + [FPTI_KEY.STATE]: FPTI_STATE.PXP, + [FPTI_KEY.TRANSITION]: FPTI_TRANSITION.PXP, + [FPTI_KEY.EXPERIMENT_NAME]: name, + [FPTI_KEY.TREATMENT_NAME]: treatment, + ...payload, + }; + + logger.track(fullPayload); + logger.flush(); + }, + + logCheckpoint({ treatment, checkpoint, payload, throttle }) { + // $FlowIssue payload type mismatch + logger.info(`${treatment}_${checkpoint}`, { + ...payload, + throttle: throttle.toString(), + }); + logger.flush(); + }, + + sticky, + }); +} + +export function isIOSSafari(): boolean { + return isIos() && isSafari(); +} + +export function isAndroidChrome(): boolean { + return isAndroid() && isChrome(); +} + +export function onCloseProxyWindow( + proxyWin: ProxyWindow, + callback: Function, + delay: number = 1000, + maxtime: number = Infinity, +): {| cancel: () => void |} { + let cancelled = false; + + let cancel = () => { + cancelled = true; + }; + + proxyWin.awaitWindow().then((win) => { + if (!cancelled) { + cancel = onCloseWindow(win, callback, delay, maxtime).cancel; } + }); + + return { + cancel, + }; +} + +export function getNavigationTimeOrigin(): number { + if (window.performance) { + const hrSyncPoint = window.performance.now(); + const unixSyncPoint = new Date().getTime(); + return ( + window.performance.timeOrigin || + window.performance.timing.navigationStart || + unixSyncPoint - hrSyncPoint + ); + } else { + throw new Error("window.performance not supported"); + } } -export function getClientsideTimestamp() : string { +export function getClientsideTimestamp(): string { try { return String(new Date().getTime()); } catch { - return "invalid_timestamp" + return "invalid_timestamp"; } } diff --git a/src/lib/util.test.js b/src/lib/util.test.js index 92925d5e0c..92fb9cfe4c 100644 --- a/src/lib/util.test.js +++ b/src/lib/util.test.js @@ -144,7 +144,7 @@ describe("utils", () => { value: false, }); expect(() => getNavigationTimeOrigin()).toThrowError( - "window.performance not supported" + "window.performance not supported", ); }); @@ -169,7 +169,7 @@ describe("utils", () => { await onCloseProxyWindow( // $FlowFixMe { awaitWindow: () => ZalgoPromise.resolve(window) }, - mockFn + mockFn, ).cancel(); // $FlowFixMe onCloseProxyWindow({ diff --git a/src/menu/hooks.js b/src/menu/hooks.js index 267aa45bf9..1ce70bdd1d 100644 --- a/src/menu/hooks.js +++ b/src/menu/hooks.js @@ -1,34 +1,41 @@ /* @flow */ -import { useState, useEffect, useRef } from 'preact/hooks'; -import { noop } from '@krakenjs/belter/src'; +import { useState, useEffect, useRef } from "preact/hooks"; +import { noop } from "@krakenjs/belter/src"; -export function useXProps() : T { - const [ xprops, setXProps ] = useState(window.xprops); - useEffect(() => xprops.onProps(newProps => { +export function useXProps(): T { + const [xprops, setXProps] = useState(window.xprops); + useEffect( + () => + xprops.onProps((newProps) => { setXProps({ ...newProps }); - }), []); - return { ...xprops }; + }), + [], + ); + return { ...xprops }; } type UseAutoFocusOptions = {| - onFocus? : () => void, - onFocusFail? : () => void + onFocus?: () => void, + onFocusFail?: () => void, |}; -export function useAutoFocus({ onFocus = noop, onFocusFail = noop } : UseAutoFocusOptions = {}) : Object { - const ref = useRef(); +export function useAutoFocus({ + onFocus = noop, + onFocusFail = noop, +}: UseAutoFocusOptions = {}): Object { + const ref = useRef(); - useEffect(() => { - if (ref.current) { - ref.current.focus(); - if (document.activeElement === ref.current) { - onFocus(); - } else { - onFocusFail(); - } - } - }); + useEffect(() => { + if (ref.current) { + ref.current.focus(); + if (document.activeElement === ref.current) { + onFocus(); + } else { + onFocusFail(); + } + } + }); - return ref; + return ref; } diff --git a/src/menu/index.js b/src/menu/index.js index 12db06186c..84a7bb3af9 100644 --- a/src/menu/index.js +++ b/src/menu/index.js @@ -1,3 +1,3 @@ /* @flow */ -export * from './page'; +export * from "./page"; diff --git a/src/menu/menu.jsx b/src/menu/menu.jsx index 6c4110b847..3c6f555ea0 100644 --- a/src/menu/menu.jsx +++ b/src/menu/menu.jsx @@ -1,56 +1,62 @@ /* @flow */ /** @jsx h */ -import type { CrossDomainWindowType } from '@krakenjs/cross-domain-utils/src'; -import { h, Fragment } from 'preact'; -import { stringifyError } from '@krakenjs/belter/src'; +import type { CrossDomainWindowType } from "@krakenjs/cross-domain-utils/src"; +import { h, Fragment } from "preact"; +import { stringifyError } from "@krakenjs/belter/src"; -import { openPopup } from '../ui'; -import { getLogger } from '../lib'; +import { openPopup } from "../ui"; +import { getLogger } from "../lib"; -import { useAutoFocus } from './hooks'; +import { useAutoFocus } from "./hooks"; type MenuProps = {| - cspNonce : string, - verticalOffset : number, - choices : $ReadOnlyArray<{| - label : string, - popup? : {| - width : number, - height : number - |}, - onSelect : ({| win? : ?CrossDomainWindowType |}) => void - |}>, - onBlur : () => void, - onFocus : () => void, - onFocusFail : () => void + cspNonce: string, + verticalOffset: number, + choices: $ReadOnlyArray<{| + label: string, + popup?: {| + width: number, + height: number, + |}, + onSelect: ({| win?: ?CrossDomainWindowType |}) => void, + |}>, + onBlur: () => void, + onFocus: () => void, + onFocusFail: () => void, |}; -export function Menu({ choices, onBlur, cspNonce, verticalOffset, onFocus, onFocusFail } : MenuProps) : mixed { - - const autoFocus = useAutoFocus({ onFocus, onFocusFail }); - - const selectChoice = (choice) => { - let win; - - if (choice.popup) { - try { - win = openPopup({ - width: choice.popup.width, - height: choice.popup.height - }); - } catch (err) { - getLogger().warn('menu_popup_open_error', { err: stringifyError(err) }); - } - } - - return choice.onSelect({ win }); - }; - - return ( - - - -