@power-elements/stripe-elements
Advanced tools
Comparing version 2.3.5 to 2.3.6
@@ -0,1 +1,8 @@ | ||
## [2.3.6](https://github.com/bennypowers/stripe-elements/compare/v2.3.5...v2.3.6) (2020-04-22) | ||
### Bug Fixes | ||
* migrate to typescript ([1b63924](https://github.com/bennypowers/stripe-elements/commit/1b6392418739a065984e431689dccb632b816819)) | ||
## [2.3.5](https://github.com/bennypowers/stripe-elements/compare/v2.3.4...v2.3.5) (2020-02-25) | ||
@@ -2,0 +9,0 @@ |
@@ -1,11 +0,7 @@ | ||
import '@babel/runtime/helpers/esm/toArray'; | ||
import '@babel/runtime/helpers/esm/getPrototypeOf'; | ||
import '@babel/runtime/helpers/esm/get'; | ||
import '@morbidick/lit-element-notify'; | ||
import 'lit-element'; | ||
import './shared.js'; | ||
import '@morbidick/lit-element-notify'; | ||
import 'lit-html/directives/if-defined'; | ||
import '@babel/runtime/helpers/esm/defineProperty'; | ||
import 'lit-html'; | ||
import '@typed/curry'; | ||
import 'lit-html'; | ||
import '@lavadrop/kebab-case'; | ||
@@ -12,0 +8,0 @@ import '@lavadrop/camel-case'; |
@@ -1,33 +0,50 @@ | ||
/* eslint-disable valid-jsdoc */ | ||
const { createDefaultConfig } = require('@open-wc/testing-karma'); | ||
const merge = require('deepmerge'); | ||
/** | ||
* @param {import('@types/karma').Config} config | ||
* @return {import('@types/karma').Config} | ||
*/ | ||
module.exports = config => { | ||
config.set(merge(createDefaultConfig(config), { | ||
...config.autoWatch ? { mochaReporter: { output: 'autowatch' } } : {}, | ||
files: [ | ||
{ pattern: config.grep ? config.grep : 'src/**/*.test.js', type: 'module' }, | ||
{ pattern: config.grep ? config.grep : 'test/*.test.js', type: 'module' }, | ||
], | ||
esm: { | ||
nodeResolve: true, | ||
babel: true, | ||
}, | ||
coverageIstanbulReporter: { | ||
thresholds: { | ||
global: { | ||
statements: 100, | ||
lines: 100, | ||
branches: 100, | ||
functions: 100, | ||
config.set( | ||
merge(createDefaultConfig(config), { | ||
files: [ | ||
{ pattern: 'test/**/*.test.js', type: 'module' }, | ||
], | ||
esm: { | ||
babel: true, | ||
nodeResolve: true, | ||
fileExtensions: ['.js', '.css'], | ||
responseTransformers: [ | ||
function resolveJSON({ url, body }) { | ||
if (url.endsWith('.json')) { | ||
return { | ||
body: `export default ${body}`, | ||
contentType: 'application/javascript', | ||
}; | ||
} | ||
}, | ||
function importCSS({ url, body }) { | ||
if (url.endsWith('.css')) { | ||
return { | ||
contentType: 'application/javascript', | ||
body: `import { css } from 'lit-element'; export default css\`${body}\``, | ||
}; | ||
} | ||
}, | ||
], | ||
}, | ||
coverageIstanbulReporter: { | ||
thresholds: { | ||
global: { | ||
statements: 100, | ||
lines: 100, | ||
branches: 100, | ||
functions: 100, | ||
}, | ||
}, | ||
}, | ||
}, | ||
})); | ||
}), | ||
); | ||
return config; | ||
}; |
{ | ||
"name": "@power-elements/stripe-elements", | ||
"version": "2.3.5", | ||
"version": "2.3.6", | ||
"description": "Web Component wrapper for stripe elements", | ||
@@ -14,9 +14,9 @@ "main": "index.js", | ||
"build": "run-s build:**", | ||
"build:compile": "tsc", | ||
"build:rollup": "rollup -c", | ||
"build:types": "tsc && sh scripts/finish-declarations.sh", | ||
"build:analyze:json": "wca analyze src/*.js --outFile custom-elements.json", | ||
"build:analyze:markdown": "cp src/README.template.md README.md && wca analyze src/*.js --silent --markdown.headerLevel 3 >> README.md", | ||
"lint": "eslint src/**/*", | ||
"build:analyze:json": "wca analyze src/*.ts --outFile custom-elements.json", | ||
"build:analyze:markdown": "cp src/README.template.md README.md && wca analyze src/*.ts --silent --markdown.headerLevel 3 >> README.md", | ||
"lint": "eslint src/**/*.ts", | ||
"test": "karma start --coverage", | ||
"test:watch": "npm t -- --auto-watch=true --single-run=false --reporters mocha,osx", | ||
"test:watch": "karma start --auto-watch=true --single-run=false --reporters mocha,osx", | ||
"test:update-snapshots": "karma start --update-snapshots", | ||
@@ -27,3 +27,6 @@ "test:prune-snapshots": "karma start --prune-snapshots", | ||
"storybook:build": "mv .babelrc bak && build-storybook && mv bak .babelrc", | ||
"watch": "rollup -cw" | ||
"update": "npm-check -u", | ||
"watch": "run-p watch:*", | ||
"watch:compile": "tsc -w", | ||
"watch:build": "rollup -cw" | ||
}, | ||
@@ -60,22 +63,26 @@ "repository": { | ||
"devDependencies": { | ||
"@babel/core": "^7.8.4", | ||
"@babel/core": "^7.9.0", | ||
"@babel/plugin-proposal-class-properties": "^7.8.0", | ||
"@babel/plugin-proposal-decorators": "^7.8.0", | ||
"@babel/plugin-proposal-dynamic-import": "^7.8.0", | ||
"@babel/plugin-proposal-optional-chaining": "^7.8.3", | ||
"@babel/plugin-proposal-optional-chaining": "^7.9.0", | ||
"@babel/plugin-proposal-private-methods": "^7.8.3", | ||
"@babel/plugin-syntax-dynamic-import": "^7.8.0", | ||
"@babel/plugin-transform-runtime": "^7.8.3", | ||
"@babel/preset-env": "^7.8.4", | ||
"@material/mwc-button": "^0.13.0", | ||
"@material/mwc-textfield": "^0.13.0", | ||
"@open-wc/demoing-storybook": "^1.10.5", | ||
"@open-wc/testing": "^2.5.4", | ||
"@open-wc/testing-karma": "^3.2.43", | ||
"@babel/plugin-transform-runtime": "^7.9.0", | ||
"@babel/preset-env": "^7.9.5", | ||
"@material/mwc-button": "^0.14.1", | ||
"@material/mwc-textfield": "^0.14.1", | ||
"@open-wc/demoing-storybook": "^2.0.6", | ||
"@open-wc/lit-helpers": "^0.3.9", | ||
"@open-wc/testing": "^2.5.13", | ||
"@open-wc/testing-karma": "^3.3.15", | ||
"@power-elements/codesandbox-button": "0.0.2", | ||
"@power-elements/json-viewer": "^1.1.1", | ||
"@pwrs/eslint-config": "0.0.5", | ||
"@rollup/plugin-commonjs": "^11.0.2", | ||
"@rollup/plugin-node-resolve": "^7.1.1", | ||
"@types/karma": "^4.4.0", | ||
"babel-eslint": "^10.0.3", | ||
"@pwrs/eslint-config": "0.0.7", | ||
"@rollup/plugin-commonjs": "^11.1.0", | ||
"@rollup/plugin-node-resolve": "^7.1.3", | ||
"@rollup/plugin-typescript": "^4.1.1", | ||
"@types/karma": "^5.0.0", | ||
"babel-eslint": "^10.1.0", | ||
"bind-decorator": "^1.0.11", | ||
"bound-decorator": "^1.1.0", | ||
@@ -87,3 +94,3 @@ "chai-things": "^0.2.0", | ||
"eslint": "^6.8.0", | ||
"husky": "^4.2.3", | ||
"husky": "^4.2.5", | ||
"karma-helpful-reporter": "^0.3.4", | ||
@@ -94,10 +101,12 @@ "karma-osx-reporter": "^0.2.1", | ||
"luhn-js": "^1.1.2", | ||
"npm-check": "^5.9.2", | ||
"npm-run-all": "^4.1.5", | ||
"rollup": "^1.31.0", | ||
"rollup-plugin-babel": "^4.3.3", | ||
"rollup-plugin-lit-css": "^2.0.1", | ||
"sinon": "^9.0.0", | ||
"sinon-chai": "^3.4.0", | ||
"query-selector-shadow-dom": "^0.4.6", | ||
"rollup": "^2.7.1", | ||
"rollup-plugin-babel": "^4.4.0", | ||
"rollup-plugin-lit-css": "^2.0.3", | ||
"sinon": "^9.0.2", | ||
"sinon-chai": "^3.5.0", | ||
"stylelint-config-standard": "^20.0.0", | ||
"typescript": "^3.7.4", | ||
"typescript": "^3.8.3", | ||
"typescript-lit-html-plugin": "^0.9.0", | ||
@@ -107,14 +116,14 @@ "web-component-analyzer": "^1.0.3" | ||
"dependencies": { | ||
"@babel/runtime": "^7.8.4", | ||
"@babel/runtime": "^7.9.2", | ||
"@lavadrop/camel-case": "^0.4.0", | ||
"@lavadrop/kebab-case": "^3.0.0", | ||
"@lavadrop/pick": "^0.8.0", | ||
"@morbidick/lit-element-notify": "^1.1.0", | ||
"@open-wc/lit-helpers": "^0.3.1", | ||
"@pacote/memoize": "^1.1.1", | ||
"@morbidick/lit-element-notify": "^1.1.1", | ||
"@pacote/memoize": "^1.1.2", | ||
"@typed/curry": "^1.0.1", | ||
"@types/stripe-v3": "^3.1.16", | ||
"lit-element": "^2.2.1", | ||
"patch-package": "^6.2.0" | ||
"@types/stripe-v3": "^3.1.17", | ||
"lit-element": "^2.3.1", | ||
"patch-package": "^6.2.2", | ||
"tslib": "^1.11.1" | ||
} | ||
} |
import commonjs from '@rollup/plugin-commonjs'; | ||
import litcss from 'rollup-plugin-lit-css'; | ||
import resolve from '@rollup/plugin-node-resolve'; | ||
import babel from 'rollup-plugin-babel'; | ||
import pkg from './package.json'; | ||
@@ -28,7 +27,6 @@ | ||
plugins: [ | ||
babel({ externalHelpers: true, runtimeHelpers: true, babelrc: true }), | ||
resolve({ extensions: ['.js', '.css', '.html'], dedupe: id => id.includes('lit') }), | ||
litcss(), | ||
commonjs(), | ||
resolve(), | ||
], | ||
}; |
1531
shared.js
@@ -1,10 +0,6 @@ | ||
import _toArray from '@babel/runtime/helpers/esm/toArray'; | ||
import _getPrototypeOf from '@babel/runtime/helpers/esm/getPrototypeOf'; | ||
import _get from '@babel/runtime/helpers/esm/get'; | ||
import { LitElement, html, property, css } from 'lit-element'; | ||
import { LitNotify } from '@morbidick/lit-element-notify'; | ||
import { LitElement, property, html, css } from 'lit-element'; | ||
import { ifDefined } from 'lit-html/directives/if-defined'; | ||
import _defineProperty from '@babel/runtime/helpers/esm/defineProperty'; | ||
import { render } from 'lit-html'; | ||
import { curry } from '@typed/curry'; | ||
import { render } from 'lit-html'; | ||
import eagerDash from '@lavadrop/kebab-case'; | ||
@@ -14,66 +10,38 @@ import eagerCamel from '@lavadrop/camel-case'; | ||
function bound(elementDescriptor) { | ||
const { | ||
kind, | ||
key, | ||
descriptor | ||
} = elementDescriptor; | ||
if (kind !== 'method') { | ||
throw Error('@bound decorator can only be used on methods'); | ||
} | ||
const method = descriptor.value; | ||
const initializer = // check for private method | ||
typeof key === 'object' ? function () { | ||
return method.bind(this); | ||
} : // For public and symbol-keyed methods (which are technically public), | ||
// we defer method lookup until construction to respect the prototype chain. | ||
function () { | ||
return this[key].bind(this); | ||
}; // Return both the original method and a bound function field that calls the method. | ||
// (That way the original method will still exist on the prototype, avoiding | ||
// confusing side-effects.) | ||
elementDescriptor.extras = [{ | ||
kind: 'field', | ||
key, | ||
placement: 'own', | ||
initializer, | ||
descriptor: { ...descriptor, | ||
value: undefined | ||
var constants; | ||
(function (constants) { | ||
constants.typeOfFunction = 'function'; | ||
constants.boolTrue = true; | ||
})(constants || (constants = {})); | ||
function bind(target, propertyKey, descriptor) { | ||
if (!descriptor || (typeof descriptor.value !== constants.typeOfFunction)) { | ||
throw new TypeError("Only methods can be decorated with @bind. <" + propertyKey + "> is not a method!"); | ||
} | ||
}]; | ||
return elementDescriptor; | ||
return { | ||
configurable: constants.boolTrue, | ||
get: function () { | ||
var bound = descriptor.value.bind(this); | ||
// Credits to https://github.com/andreypopp/autobind-decorator for memoizing the result of bind against a symbol on the instance. | ||
Object.defineProperty(this, propertyKey, { | ||
value: bound, | ||
configurable: constants.boolTrue, | ||
writable: constants.boolTrue | ||
}); | ||
return bound; | ||
} | ||
}; | ||
} | ||
/** @typedef {import('lit-element').PropertyDeclaration & { readOnly: Boolean }} AugmentedPropertyDeclaration */ | ||
/** | ||
* @template TBase | ||
* @typedef {new (...args: any[]) => import('lit-element').LitElement & TBase} Constructor | ||
*/ | ||
// eslint-disable-next-line valid-jsdoc | ||
/** | ||
* Enables the nofity option for properties to fire change notification events | ||
* | ||
* @template TBase | ||
* @param {Constructor<TBase>} superclass | ||
*/ | ||
const ReadOnlyPropertiesMixin = superclass => { | ||
var _temp; | ||
/** | ||
* @type {Map<string, symbol>} | ||
* @private | ||
*/ | ||
function ReadOnlyPropertiesMixin(superclass) { | ||
const _readOnlyPropertyNamesMap = new Map(); | ||
return _temp = class ReadOnlyPropertiesClass extends superclass { | ||
/** | ||
* @inheritdoc | ||
* @param {string} name property name | ||
* @param {AugmentedPropertyDeclaration} options augmented property declaration with optional `readOnly` boolean. | ||
*/ | ||
return class ReadOnlyPropertiesClass extends superclass { | ||
constructor() { | ||
super(); | ||
this._readOnlyPropertyInitializedMap = new Map(); | ||
} | ||
static createProperty(name, options) { | ||
@@ -94,96 +62,52 @@ let finalOptions = options; | ||
// allow for class field initialization | ||
/* istanbul ignore if */ | ||
if (this._readOnlyPropertyInitializedMap.get(name)) return; | ||
this[privateName] = value; | ||
this._readOnlyPropertyInitializedMap.set(name, true); | ||
} | ||
}, | ||
}); | ||
}); | ||
finalOptions = { ...options, | ||
noAccessor: true | ||
}; | ||
finalOptions = { ...options, noAccessor: true }; | ||
} | ||
// It seems like there's really no good way to extend a class and its | ||
// static members in typescript | ||
// @ts-ignore | ||
super.createProperty(name, finalOptions); | ||
} | ||
/** | ||
* @type {Map<string, boolean>} | ||
* @private | ||
*/ | ||
constructor() { | ||
super(); | ||
_defineProperty(this, "_readOnlyPropertyInitializedMap", new Map()); | ||
this._setPropEntry = this._setPropEntry.bind(this); | ||
} | ||
/** | ||
* Set read-only properties | ||
* @param {Object<string, unknown>} props | ||
* @private | ||
*/ | ||
async set(props) { | ||
await Promise.all(Object.entries(props).map(this._setPropEntry)); | ||
async setReadOnlyProperties(props) { | ||
await Promise.all( | ||
Object.entries(props).map(([name, newVal]) => { | ||
const privateName = _readOnlyPropertyNamesMap.get(name); | ||
const oldVal = this[privateName]; | ||
this[privateName] = newVal; | ||
return this.requestUpdate(name, oldVal); | ||
}), | ||
); | ||
} | ||
/** | ||
* @param {[string, unknown]} entry | ||
* @return {Promise<unknown>} | ||
* @private | ||
*/ | ||
}; | ||
} | ||
_setPropEntry([name, newVal]) { | ||
// typescript... https://github.com/microsoft/TypeScript/issues/1863 | ||
/** @type {any} */ | ||
const privateName = _readOnlyPropertyNamesMap.get(name); | ||
const oldVal = this[privateName]; | ||
this[privateName] = newVal; | ||
return this.requestUpdate(name, oldVal); | ||
} | ||
}, _temp; | ||
}; | ||
/** | ||
* Remove an element from the DOM | ||
* @param {ChildNode} el | ||
* @return {void} | ||
* @param el element to remove | ||
*/ | ||
/* istanbul ignore next */ | ||
const remove = el => el === null || el === void 0 ? void 0 : el.remove(); | ||
const remove = (el) => el === null || el === void 0 ? void 0 : el.remove(); | ||
const appendTemplate = curry(function appendTemplate(template, target) { | ||
const tmp = document.createElement('div'); | ||
render(template, tmp); | ||
const { | ||
firstElementChild | ||
} = tmp; | ||
target.appendChild(firstElementChild); | ||
tmp.remove(); | ||
return firstElementChild; | ||
const tmp = document.createElement('div'); | ||
render(template, tmp); | ||
const { firstElementChild } = tmp; | ||
target.appendChild(firstElementChild); | ||
tmp.remove(); | ||
return firstElementChild; | ||
}); | ||
const mapPropEntry = mapping => ([key, value]) => key in mapping && typeof mapping[key] === 'function' ? [key, mapping[key](value)] : [key, value]; | ||
const mapProps = mapping => obj => Object.fromEntries(Object.entries(obj).map(mapPropEntry(mapping))); | ||
const mapDataset = f => ({ | ||
dataset | ||
}) => f(dataset); | ||
const identity = x => x; | ||
/** camelCase a string */ | ||
const camel = memoize(identity, eagerCamel); | ||
/** dash-case a string */ | ||
const dash = memoize(identity, eagerDash); | ||
@@ -196,5 +120,4 @@ /** | ||
*/ | ||
function generateRandomMountElementId(tagName) { | ||
return `${tagName.toLowerCase()}-mount-point-${(Date.now() + Math.random() * 1000).toString(36).substr(0, 8)}`; | ||
return `${tagName.toLowerCase()}-mount-point-${(Date.now() + (Math.random() * 1000)).toString(36).substr(0, 8)}`; | ||
} | ||
@@ -207,53 +130,37 @@ | ||
* Throws an error if the response is not OK.) | ||
* @param {Response} response | ||
* @resolves {Response} | ||
* @rejects {Error} | ||
*/ | ||
async function throwBadResponse(response) { | ||
const { | ||
ok, | ||
statusText | ||
} = response; | ||
if (!ok) throw new Error(statusText); | ||
return response; | ||
const { ok, statusText } = response; | ||
if (!ok) | ||
throw new Error(statusText); | ||
return response; | ||
} | ||
function _decorate(decorators, factory, superClass, mixins) { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); } | ||
function _getDecoratorsApi() { _getDecoratorsApi = function () { return api; }; var api = { elementsDefinitionOrder: [["method"], ["field"]], initializeInstanceElements: function (O, elements) { ["method", "field"].forEach(function (kind) { elements.forEach(function (element) { if (element.kind === kind && element.placement === "own") { this.defineClassElement(O, element); } }, this); }, this); }, initializeClassElements: function (F, elements) { var proto = F.prototype; ["method", "field"].forEach(function (kind) { elements.forEach(function (element) { var placement = element.placement; if (element.kind === kind && (placement === "static" || placement === "prototype")) { var receiver = placement === "static" ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, defineClassElement: function (receiver, element) { var descriptor = element.descriptor; if (element.kind === "field") { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver) }; } Object.defineProperty(receiver, element.key, descriptor); }, decorateClass: function (elements, decorators) { var newElements = []; var finishers = []; var placements = { static: [], prototype: [], own: [] }; elements.forEach(function (element) { this.addElementPlacement(element, placements); }, this); elements.forEach(function (element) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras = this.decorateElement(element, placements); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers }; } var result = this.decorateConstructor(newElements, decorators); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, addElementPlacement: function (element, placements, silent) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError("Duplicated element (" + element.key + ")"); } keys.push(element.key); }, decorateElement: function (element, placements) { var extras = []; var finishers = []; for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject = this.fromElementDescriptor(element); var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras }; }, decorateConstructor: function (elements, decorators) { var finishers = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj = this.fromClassDescriptor(elements); var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { throw new TypeError("Duplicated element (" + elements[j].key + ")"); } } } } } return { elements: elements, finishers: finishers }; }, fromElementDescriptor: function (element) { var obj = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === "field") obj.initializer = element.initializer; return obj; }, toElementDescriptors: function (elementObjects) { if (elementObjects === undefined) return; return _toArray(elementObjects).map(function (elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, "finisher", "An element descriptor"); this.disallowProperty(elementObject, "extras", "An element descriptor"); return element; }, this); }, toElementDescriptor: function (elementObject) { var kind = String(elementObject.kind); if (kind !== "method" && kind !== "field") { throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); } var key = _toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if (placement !== "static" && placement !== "prototype" && placement !== "own") { throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); } var descriptor = elementObject.descriptor; this.disallowProperty(elementObject, "elements", "An element descriptor"); var element = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor) }; if (kind !== "field") { this.disallowProperty(elementObject, "initializer", "A method descriptor"); } else { this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function (elementObject) { var element = this.toElementDescriptor(elementObject); var finisher = _optionalCallableProperty(elementObject, "finisher"); var extras = this.toElementDescriptors(elementObject.extras); return { element: element, finisher: finisher, extras: extras }; }, fromClassDescriptor: function (elements) { var obj = { kind: "class", elements: elements.map(this.fromElementDescriptor, this) }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, toClassDescriptor: function (obj) { var kind = String(obj.kind); if (kind !== "class") { throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); } this.disallowProperty(obj, "key", "A class descriptor"); this.disallowProperty(obj, "placement", "A class descriptor"); this.disallowProperty(obj, "descriptor", "A class descriptor"); this.disallowProperty(obj, "initializer", "A class descriptor"); this.disallowProperty(obj, "extras", "A class descriptor"); var finisher = _optionalCallableProperty(obj, "finisher"); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher }; }, runClassFinishers: function (constructor, finishers) { for (var i = 0; i < finishers.length; i++) { var newConstructor = (0, finishers[i])(constructor); if (newConstructor !== undefined) { if (typeof newConstructor !== "function") { throw new TypeError("Finishers must return a constructor."); } constructor = newConstructor; } } return constructor; }, disallowProperty: function (obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + " property."); } } }; return api; } | ||
function _createElementDescriptor(def) { var key = _toPropertyKey(def.key); var descriptor; if (def.kind === "method") { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false }; } else if (def.kind === "get") { descriptor = { get: def.value, configurable: true, enumerable: false }; } else if (def.kind === "set") { descriptor = { set: def.value, configurable: true, enumerable: false }; } else if (def.kind === "field") { descriptor = { configurable: true, writable: true, enumerable: true }; } var element = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor }; if (def.decorators) element.decorators = def.decorators; if (def.kind === "field") element.initializer = def.value; return element; } | ||
function _coalesceGetterSetter(element, other) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } } | ||
function _coalesceClassElements(elements) { var newElements = []; var isSameElement = function (other) { return other.kind === "method" && other.key === element.key && other.placement === element.placement; }; for (var i = 0; i < elements.length; i++) { var element = elements[i]; var other; if (element.kind === "method" && (other = newElements.find(isSameElement))) { if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; } | ||
function _hasDecorators(element) { return element.decorators && element.decorators.length; } | ||
function _isDataDescriptor(desc) { return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); } | ||
function _optionalCallableProperty(obj, name) { var value = obj[name]; if (value !== undefined && typeof value !== "function") { throw new TypeError("Expected '" + name + "' to be a function"); } return value; } | ||
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } | ||
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } | ||
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { | ||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; | ||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); | ||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; | ||
return c > 3 && r && Object.defineProperty(target, key, r), r; | ||
}; | ||
var __metadata = (undefined && undefined.__metadata) || function (k, v) { | ||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); | ||
}; | ||
class StripeElementsError extends Error { | ||
constructor(tag, message) { | ||
super(`<${tag}>: ${message}`); | ||
this.originalMessage = message; | ||
} | ||
constructor(tag, message) { | ||
super(`<${tag}>: ${message}`); | ||
this.originalMessage = message; | ||
} | ||
} | ||
function isStripeElementsError(error) { | ||
return !!error && error instanceof StripeElementsError; | ||
} | ||
/* istanbul ignore next */ | ||
const removeAllMounts = slotName => host => host.querySelectorAll(`[slot="${slotName}"][name="${slotName}"]`).forEach(remove); | ||
const slotTemplate = slotName => html`<slot slot="${slotName}" name="${slotName}"></slot>`; | ||
const mountPointTemplate = ({ | ||
stripeMountId, | ||
tagName | ||
}) => html`<div id="${ifDefined(stripeMountId)}" class="${tagName.toLowerCase()}-mount"></div>`; | ||
const removeAllMounts = (slotName) => (host) => host.querySelectorAll(`[slot="${slotName}"][name="${slotName}"]`) | ||
.forEach(remove); | ||
const slotTemplate = (slotName) => html `<slot slot="${slotName}" name="${slotName}"></slot>`; | ||
const errorConverter = { | ||
toAttribute: (error) => !error ? null | ||
: isStripeElementsError(error) ? error.originalMessage | ||
: error.message || '', | ||
}; | ||
/** | ||
@@ -276,449 +183,83 @@ * @fires 'error' - The validation error, or the error returned from stripe.com | ||
*/ | ||
let StripeBase = _decorate(null, function (_initialize, _ReadOnlyPropertiesMi) { | ||
class StripeBase extends _ReadOnlyPropertiesMi { | ||
/* PAYMENT CONFIGURATION */ | ||
class StripeBase extends ReadOnlyPropertiesMixin(LitNotify(LitElement)) { | ||
constructor() { | ||
super(); | ||
/** | ||
* Type of payment representation to generate. | ||
*/ | ||
this.generate = 'source'; | ||
/** Whether to display the error message */ | ||
this.showError = false; | ||
/* READ-ONLY FIELDS */ | ||
/* PAYMENT REPRESENTATIONS */ | ||
/** | ||
* Stripe PaymentMethod | ||
*/ | ||
this.paymentMethod = null; | ||
/** | ||
* Stripe Source | ||
*/ | ||
this.source = null; | ||
/** | ||
* Stripe Token | ||
*/ | ||
this.token = null; | ||
/** | ||
* Stripe element instance | ||
*/ | ||
this.element = null; | ||
/** | ||
* Stripe Elements instance | ||
*/ | ||
this.elements = null; | ||
/** | ||
* Stripe or validation error | ||
*/ | ||
this.error = null; | ||
/** | ||
* If the element is focused. | ||
*/ | ||
this.focused = false; | ||
/** | ||
* Whether the stripe element is ready to receive focus. | ||
*/ | ||
this.ready = false; | ||
/** | ||
* Stripe instance | ||
*/ | ||
this.stripe = null; | ||
// DEPRECATED | ||
/** | ||
* Whether the element has an error | ||
* **DEPRECATED**. Will be removed in a future version. Use `error` instead | ||
* @deprecated | ||
*/ | ||
this.hasError = false; | ||
/** | ||
* Whether the stripe element is ready to receive focus. | ||
* **DEPRECATED**. Will be removed in a future version. use `ready` instead. | ||
* @deprecated | ||
*/ | ||
this.stripeReady = false; | ||
/* PRIVATE FIELDS */ | ||
/** | ||
* Breadcrumbs back up to the document. | ||
*/ | ||
this.shadowHosts = []; | ||
const slotName = this.tagName === 'STRIPE-ELEMENTS' ? 'stripe-elements-slot' | ||
: this.tagName === 'STRIPE-PAYMENT-REQUEST' ? 'stripe-payment-request-slot' | ||
/* istanbul ignore next */ | ||
: null; | ||
this.slotName = slotName; | ||
} | ||
/** | ||
* billing_details object sent to create the payment representation. (optional) | ||
* @type {stripe.BillingDetails} | ||
*/ | ||
/** | ||
* Data passed to stripe.createPaymentMethod. (optional) | ||
* @type {stripe.PaymentMethodData} | ||
*/ | ||
/** | ||
* Data passed to stripe.createSource. (optional) | ||
* @type {SourceData} | ||
*/ | ||
/** | ||
* Data passed to stripe.createToken. (optional) | ||
* @type {stripe.TokenOptions} | ||
*/ | ||
/* PAYMENT REPRESENTATIONS */ | ||
/** | ||
* Stripe PaymentMethod | ||
* @type {stripe.paymentMethod.PaymentMethod} | ||
* @readonly | ||
*/ | ||
/** | ||
* Stripe Source | ||
* @type {stripe.Source} | ||
* @readonly | ||
*/ | ||
/** | ||
* Stripe Token | ||
* @type {stripe.Token} | ||
* @readonly | ||
*/ | ||
/* SETTINGS */ | ||
/** | ||
* If set, when Stripe returns the payment info (PaymentMethod, Source, or Token), | ||
* the element will POST JSON data to this URL with an object containing | ||
* a key equal to the value of the `generate` property. | ||
* @example | ||
* ```html | ||
* <stripe-elements | ||
* publishable-key="pk_test_XXXXXXXXXXXXX" | ||
* generate="token" | ||
* action="/payment" | ||
* ></stripe-elements> | ||
* ``` | ||
* will POST to `/payment` with JSON body `{ "token": { ... } }` | ||
* ```js | ||
* stripeElements.submit(); | ||
* ``` | ||
* @type {string} | ||
*/ | ||
/** | ||
* The `client_secret` part of a Stripe `PaymentIntent` | ||
* @type {string} | ||
*/ | ||
/** | ||
* Type of payment representation to generate. | ||
* @type {'payment-method'|'source'|'token'} | ||
* @required | ||
*/ | ||
/** | ||
* Stripe Publishable Key. EG. `pk_test_XXXXXXXXXXXXXXXXXXXXXXXX` | ||
* @type {string} | ||
*/ | ||
/** Whether to display the error message */ | ||
/* READ-ONLY FIELDS */ | ||
/** | ||
* Stripe element instance | ||
* @type {stripe.elements.Element} | ||
* @readonly | ||
*/ | ||
/** | ||
* Stripe Elements instance | ||
* @type {stripe.elements.Elements} | ||
* @readonly | ||
*/ | ||
/** | ||
* Stripe or validation error | ||
* @type {Error|stripe.Error} | ||
* @readonly | ||
*/ | ||
/** | ||
* If the element is focused. | ||
* @type {boolean} | ||
* @readonly | ||
*/ | ||
/** | ||
* Whether the stripe element is ready to receive focus. | ||
* @type {boolean} | ||
* @readonly | ||
*/ | ||
/** | ||
* Stripe instance | ||
* @type {stripe.Stripe} | ||
* @readonly | ||
*/ | ||
// DEPRECATED | ||
/** | ||
* Whether the element has an error | ||
* **DEPRECATED**. Will be removed in a future version. Use `error` instead | ||
* @type {boolean} | ||
* @readonly | ||
* @deprecated | ||
*/ | ||
/** | ||
* Whether the stripe element is ready to receive focus. | ||
* **DEPRECATED**. Will be removed in a future version. use `ready` instead. | ||
* @deprecated | ||
* @type {boolean} | ||
*/ | ||
/* PRIVATE FIELDS */ | ||
/** | ||
* Breadcrumbs back up to the document. | ||
* @type {Node[]} | ||
* @private | ||
*/ | ||
/** | ||
* Stripe.js mount point element. Due to limitations in the Stripe.js library, this element must be connected to the document. | ||
* @type {Element} | ||
* @protected | ||
*/ | ||
/** | ||
* Stripe.js mount point element id. Due to limitations in the Stripe.js library, this element must be connected to the document. | ||
* @type {string} | ||
* @protected | ||
*/ | ||
/** | ||
* Name for breadcrumb slots. Derived from tagName | ||
* @protected | ||
* @type {string} | ||
*/ | ||
get stripeMount() { return document.getElementById(this.stripeMountId); } | ||
/* LIFECYCLE */ | ||
/** @inheritdoc */ | ||
constructor() { | ||
super(); | ||
_initialize(this); | ||
this.slotName = `${this.tagName.toLowerCase()}-slot`; | ||
} | ||
/** @inheritdoc */ | ||
} | ||
return { | ||
F: StripeBase, | ||
d: [{ | ||
kind: "field", | ||
key: "billingDetails", | ||
value() { | ||
return {}; | ||
} | ||
}, { | ||
kind: "field", | ||
key: "paymentMethodData", | ||
value() { | ||
return {}; | ||
} | ||
}, { | ||
kind: "field", | ||
key: "sourceData", | ||
value() { | ||
return {}; | ||
} | ||
}, { | ||
kind: "field", | ||
key: "tokenData", | ||
value() { | ||
return {}; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true, | ||
attribute: 'payment-method' | ||
})], | ||
key: "paymentMethod", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "source", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "token", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String | ||
})], | ||
key: "action", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String, | ||
attribute: 'client-secret' | ||
})], | ||
key: "clientSecret", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String | ||
})], | ||
key: "generate", | ||
value() { | ||
return 'source'; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String, | ||
attribute: 'publishable-key', | ||
reflect: true, | ||
notify: true | ||
})], | ||
key: "publishableKey", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'show-error', | ||
reflect: true | ||
})], | ||
key: "showError", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
readOnly: true | ||
})], | ||
key: "element", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
readOnly: true | ||
})], | ||
key: "elements", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true, | ||
reflect: true, | ||
converter: { | ||
toAttribute: error => !error ? null : error.originalMessage || error.message || '' | ||
} | ||
})], | ||
key: "error", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "focused", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "ready", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
readOnly: true | ||
})], | ||
key: "stripe", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'has-error', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "hasError", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'stripe-ready', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "stripeReady", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
key: "shadowHosts", | ||
value() { | ||
return []; | ||
} | ||
}, { | ||
kind: "get", | ||
key: "stripeMount", | ||
value: function stripeMount() { | ||
return document.getElementById(this.stripeMountId); | ||
} | ||
}, { | ||
kind: "field", | ||
key: "stripeMountId", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
key: "slotName", | ||
value: void 0 | ||
}, { | ||
kind: "method", | ||
key: "render", | ||
value: function render() { | ||
const { | ||
error, | ||
showError, | ||
slotName | ||
} = this; | ||
const errorMessage = (error === null || error === void 0 ? void 0 : error.originalMessage) || (error === null || error === void 0 ? void 0 : error.message); | ||
return html` | ||
render() { | ||
const { error, showError, slotName } = this; | ||
const errorMessage = isStripeElementsError(error) ? error.originalMessage : error === null || error === void 0 ? void 0 : error.message; | ||
return html ` | ||
<div id="stripe" part="stripe"> | ||
@@ -735,202 +276,126 @@ <slot id="stripe-slot" name="${slotName}"></slot> | ||
`; | ||
} | ||
}, { | ||
kind: "method", | ||
key: "firstUpdated", | ||
value: function firstUpdated() { | ||
} | ||
/** @inheritdoc */ | ||
firstUpdated() { | ||
this.destroyMountPoints(); | ||
this.initMountPoints(); | ||
} | ||
/** @inheritdoc */ | ||
}, { | ||
kind: "method", | ||
key: "updated", | ||
value: function updated(changed) { | ||
var _get2; | ||
(_get2 = _get(_getPrototypeOf(StripeBase.prototype), "updated", this)) === null || _get2 === void 0 ? void 0 : _get2(changed); | ||
if (changed.has('error')) this.errorChanged(); | ||
if (changed.has('publishableKey')) this.init(); | ||
} | ||
/** @inheritdoc */ | ||
updated(changed) { | ||
var _a; | ||
/* istanbul ignore next */ | ||
(_a = super.updated) === null || _a === void 0 ? void 0 : _a.call(this, changed); | ||
if (changed.has('error')) | ||
this.errorChanged(); | ||
if (changed.has('publishableKey')) | ||
this.init(); | ||
[...changed.keys()].forEach(this.representationChanged); | ||
} | ||
/** @inheritdoc */ | ||
}, { | ||
kind: "method", | ||
key: "disconnectedCallback", | ||
value: async function disconnectedCallback() { | ||
_get(_getPrototypeOf(StripeBase.prototype), "disconnectedCallback", this).call(this); | ||
await this.unmount(); | ||
} | ||
/** @inheritdoc */ | ||
async disconnectedCallback() { | ||
var _a; | ||
super.disconnectedCallback(); | ||
/* istanbul ignore next */ | ||
await ((_a = this.unmount) === null || _a === void 0 ? void 0 : _a.call(this)); | ||
this.destroyMountPoints(); | ||
} | ||
/* PUBLIC API */ | ||
/** | ||
* Resets and clears the stripe element. | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "reset", | ||
value: function reset() { | ||
var _this$element, _this$element$clear; | ||
(_this$element = this.element) === null || _this$element === void 0 ? void 0 : (_this$element$clear = _this$element.clear) === null || _this$element$clear === void 0 ? void 0 : _this$element$clear.call(_this$element); | ||
} | ||
/* PUBLIC API */ | ||
/** | ||
* Resets and clears the stripe element. | ||
*/ | ||
reset() { | ||
var _a, _b; | ||
/* istanbul ignore next */ | ||
(_b = (_a = this.element) === null || _a === void 0 ? void 0 : _a.clear) === null || _b === void 0 ? void 0 : _b.call(_a); | ||
this.resetRepresentations(); | ||
this.set({ | ||
error: null | ||
}); | ||
} | ||
/** Blurs the element. */ | ||
}, { | ||
kind: "method", | ||
key: "blur", | ||
value: function blur() { | ||
var _this$element2; | ||
(_this$element2 = this.element) === null || _this$element2 === void 0 ? void 0 : _this$element2.blur(); | ||
} | ||
/** Focuses the element. */ | ||
}, { | ||
kind: "method", | ||
key: "focus", | ||
value: function focus() { | ||
var _this$element3; | ||
(_this$element3 = this.element) === null || _this$element3 === void 0 ? void 0 : _this$element3.focus(); | ||
} | ||
/* PRIVATE API */ | ||
/** | ||
* Creates a new StripeElementsError | ||
* @param {string} message | ||
* @return {StripeElementsError} | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "createError", | ||
value: function createError(message) { | ||
this.setReadOnlyProperties({ error: null }); | ||
} | ||
/** Blurs the element. */ | ||
blur() { | ||
var _a; | ||
/* istanbul ignore next */ | ||
(_a = this.element) === null || _a === void 0 ? void 0 : _a.blur(); | ||
} | ||
/** Focuses the element. */ | ||
focus() { | ||
var _a; | ||
/* istanbul ignore next */ | ||
(_a = this.element) === null || _a === void 0 ? void 0 : _a.focus(); | ||
} | ||
/* PRIVATE API */ | ||
/** | ||
* Creates a new StripeElementsError | ||
*/ | ||
createError(message) { | ||
return new StripeElementsError(this.constructor.is, message); | ||
} | ||
/** | ||
* Clears the Payment Representation and fires an error event | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "errorChanged", | ||
value: async function errorChanged() { | ||
} | ||
/** | ||
* Clears the Payment Representation and fires an error event | ||
*/ | ||
async errorChanged() { | ||
// DEPRECATED | ||
const hasError = !!this.error; | ||
await this.set({ | ||
hasError | ||
}); // END DEPRECATED | ||
await this.setReadOnlyProperties({ hasError }); | ||
// END DEPRECATED | ||
this.resetRepresentations(); | ||
this.fireError(this.error); | ||
} | ||
/** | ||
* Fires an event. | ||
* @param {string} type event type | ||
* @param {any} detail detail value | ||
* @param {EventInit} [opts={}] | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "fire", | ||
value: function fire(type, detail, opts = {}) { | ||
this.dispatchEvent(new CustomEvent(type, { | ||
detail, | ||
...opts | ||
})); | ||
} | ||
/** | ||
* Fires an Error Event | ||
* @param {Error} error | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "fireError", | ||
value: function fireError(error) { | ||
this.dispatchEvent(new ErrorEvent('error', { | ||
error | ||
})); // DEPRECATED | ||
this.dispatchEvent(new ErrorEvent('stripe-error', { | ||
bubbles: true, | ||
error | ||
})); | ||
} | ||
/** | ||
* Gets a CSS Custom Property value, respecting ShadyCSS. | ||
* @param {string} propertyName CSS Custom Property | ||
* @param {CSSStyleDeclaration} [precomputedStyle] pre-computed style declaration | ||
* @return {any} | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "getCSSCustomPropertyValue", | ||
value: function getCSSCustomPropertyValue(propertyName, precomputedStyle) { | ||
if (window.ShadyCSS) return ShadyCSS.getComputedStyleValue(this, propertyName);else return precomputedStyle.getPropertyValue(propertyName); | ||
} | ||
/** | ||
* Sets the token or error from the response. | ||
* @param {PaymentResponse} response Stripe Response | ||
* @return {PaymentResponse} | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "handleResponse", | ||
value: async function handleResponse(response) { | ||
const { | ||
error = null, | ||
paymentMethod = null, | ||
source = null, | ||
token = null | ||
} = response; | ||
await this.set({ | ||
error, | ||
paymentMethod, | ||
source, | ||
token | ||
}); | ||
if (error) throw error;else return response; | ||
} | ||
/** | ||
* Removes all mount points from the DOM | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "destroyMountPoints", | ||
value: function destroyMountPoints() { | ||
} | ||
/** | ||
* Fires an event. | ||
* @param type event type | ||
* @param detail detail value | ||
* @param [opts={}] | ||
*/ | ||
fire(type, detail, opts) { | ||
this.dispatchEvent(new CustomEvent(type, { detail, ...opts })); | ||
} | ||
/** | ||
* Fires an Error Event | ||
*/ | ||
fireError(error) { | ||
this.dispatchEvent(new ErrorEvent('error', { error })); | ||
// DEPRECATED | ||
this.dispatchEvent(new ErrorEvent('stripe-error', { bubbles: true, error })); | ||
} | ||
/** | ||
* Gets a CSS Custom Property value, respecting ShadyCSS. | ||
* @param propertyName CSS Custom Property | ||
* @param precomputedStyle pre-computed style declaration | ||
*/ | ||
getCSSCustomPropertyValue(propertyName, precomputedStyle) { | ||
if (window.ShadyCSS) | ||
return window.ShadyCSS.getComputedStyleValue(this, propertyName); | ||
else | ||
return precomputedStyle.getPropertyValue(propertyName); | ||
} | ||
/** | ||
* Sets the token or error from the response. | ||
* @param response Stripe Response | ||
* @return | ||
*/ | ||
async handleResponse(response) { | ||
const { error = null, paymentMethod = null, source = null, token = null } = { ...response }; | ||
await this.setReadOnlyProperties({ error, paymentMethod, source, token }); | ||
if (error) | ||
throw error; | ||
else | ||
return response; | ||
} | ||
/** | ||
* Removes all mount points from the DOM | ||
*/ | ||
destroyMountPoints() { | ||
this.shadowHosts.forEach(removeAllMounts(this.slotName)); | ||
if (this.stripeMount) this.stripeMount.remove(); | ||
} | ||
/** | ||
* Reinitializes Stripe and mounts the element. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "init", | ||
value: async function init() { | ||
if (this.stripeMount) | ||
this.stripeMount.remove(); | ||
} | ||
/** @abstract */ | ||
/* istanbul ignore next */ | ||
initElement() { | ||
'abstract'; | ||
} | ||
/** | ||
* Reinitializes Stripe and mounts the element. | ||
*/ | ||
async init() { | ||
await this.unmount(); | ||
@@ -943,249 +408,259 @@ await this.initStripe(); | ||
this.mount(); | ||
} | ||
/** | ||
* Adds `ready`, `focus`, and `blur` listeners to the Stripe Element | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initElementListeners", | ||
value: function initElementListeners() { | ||
if (!this.element) return; | ||
} | ||
/** | ||
* Adds `ready`, `focus`, and `blur` listeners to the Stripe Element | ||
*/ | ||
initElementListeners() { | ||
if (!this.element) | ||
return; | ||
this.element.addEventListener('ready', this.onReady); | ||
this.element.addEventListener('focus', this.onFocus); | ||
this.element.addEventListener('blur', this.onBlur); | ||
} | ||
/** | ||
* Creates mount points for the Stripe Element | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initMountPoints", | ||
value: function initMountPoints() { | ||
} | ||
/** | ||
* Creates mount points for the Stripe Element | ||
*/ | ||
initMountPoints() { | ||
this.stripeMountId = generateRandomMountElementId(this.tagName); | ||
if (window.ShadyDOM) appendTemplate(mountPointTemplate(this), this);else this.initShadowMountPoints(); | ||
} | ||
/** | ||
* Prepares to mount Stripe Elements in light DOM. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initShadowMountPoints", | ||
value: function initShadowMountPoints() { | ||
if (window.ShadyDOM) | ||
appendTemplate(this.mountPointTemplate(), this); | ||
else | ||
this.initShadowMountPoints(); | ||
} | ||
/** | ||
* Prepares to mount Stripe Elements in light DOM. | ||
*/ | ||
initShadowMountPoints() { | ||
// trace each shadow boundary between us and the document | ||
let host = this; | ||
this.shadowHosts = [this]; | ||
while (host = host.getRootNode().host) this.shadowHosts.push(host); // eslint-disable-line prefer-destructuring, no-loops/no-loops | ||
const { | ||
shadowHosts, | ||
slotName | ||
} = this; // Prepare the shallowest breadcrumb slot at document level | ||
while (host = host.getRootNode().host) // eslint-disable-line no-loops/no-loops, prefer-destructuring | ||
this.shadowHosts.push(host); | ||
const { shadowHosts, slotName } = this; | ||
// Prepare the shallowest breadcrumb slot at document level | ||
const hosts = [...shadowHosts]; | ||
const root = hosts.pop(); | ||
if (!root.querySelector(`[slot="${slotName}"]`)) { | ||
const div = document.createElement('div'); | ||
div.slot = slotName; | ||
root.appendChild(div); | ||
const div = document.createElement('div'); | ||
div.slot = slotName; | ||
root.appendChild(div); | ||
} | ||
const container = root.querySelector(`[slot="${slotName}"]`); // Render the form to the document, so that Stripe.js can mount | ||
appendTemplate(mountPointTemplate(this), container); // Append breadcrumb slots to each shadowroot in turn, | ||
const container = root.querySelector(`[slot="${slotName}"]`); | ||
// Render the form to the document, so that Stripe.js can mount | ||
appendTemplate(this.mountPointTemplate(), container); | ||
// Append breadcrumb slots to each shadowroot in turn, | ||
// from the document down to the <stripe-elements> instance. | ||
hosts.forEach(appendTemplate(slotTemplate(slotName))); | ||
} | ||
/** | ||
* Initializes Stripe and elements. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initStripe", | ||
value: async function initStripe() { | ||
const { | ||
publishableKey | ||
} = this; | ||
const stripe = window.Stripe && publishableKey ? Stripe(publishableKey) : null; | ||
} | ||
/** | ||
* Initializes Stripe and elements. | ||
*/ | ||
async initStripe() { | ||
const { publishableKey } = this; | ||
const stripe = (window.Stripe && publishableKey) ? Stripe(publishableKey) : null; | ||
const elements = stripe && stripe.elements(); | ||
const error = stripe ? null : this.createError('requires Stripe.js to be loaded first.'); | ||
if (error) console.warn(error.message); // eslint-disable-line no-console | ||
await this.set({ | ||
elements, | ||
error, | ||
stripe | ||
}); | ||
} | ||
/** | ||
* Mounts the Stripe Element | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "mount", | ||
value: function mount() { | ||
var _this$element4; | ||
if (error) | ||
console.warn(error.message); // eslint-disable-line no-console | ||
await this.setReadOnlyProperties({ elements, error, stripe }); | ||
} | ||
/** | ||
* Mounts the Stripe Element | ||
*/ | ||
mount() { | ||
var _a; | ||
/* istanbul ignore next */ | ||
if (!this.stripeMount) throw this.createError('Stripe Mount missing'); | ||
(_this$element4 = this.element) === null || _this$element4 === void 0 ? void 0 : _this$element4.mount(this.stripeMount); | ||
} | ||
/** | ||
* Unmounts and nullifies the card. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "unmount", | ||
value: async function unmount() { | ||
var _this$element5; | ||
(_this$element5 = this.element) === null || _this$element5 === void 0 ? void 0 : _this$element5.unmount(); | ||
await this.set({ | ||
element: null | ||
}); | ||
} | ||
/** | ||
* @param {StripeFocusEvent} event | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "onBlur", | ||
value: async function onBlur() { | ||
await this.set({ | ||
focused: false | ||
}); | ||
} | ||
/** | ||
* @param {StripeFocusEvent} event | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "onFocus", | ||
value: async function onFocus() { | ||
await this.set({ | ||
focused: true | ||
}); | ||
} | ||
/** | ||
* Sets the `ready` property when the stripe element is ready to receive focus. | ||
* @param {Event} event | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "onReady", | ||
value: async function onReady(event) { | ||
await this.set({ | ||
ready: true, | ||
stripeReady: true | ||
}); | ||
this.fire('ready', event); // DEPRECATED | ||
if (!this.stripeMount) | ||
throw this.createError('Stripe Mount missing'); | ||
(_a = this.element) === null || _a === void 0 ? void 0 : _a.mount(this.stripeMount); | ||
} | ||
mountPointTemplate() { | ||
const { stripeMountId, tagName } = this; | ||
return html `<div id="${ifDefined(stripeMountId)}" class="${tagName.toLowerCase()}-mount"></div>`; | ||
} | ||
/** | ||
* Unmounts and nullifies the card. | ||
*/ | ||
async unmount() { | ||
var _a, _b; | ||
(_b = (_a = this.element) === null || _a === void 0 ? void 0 : _a.unmount) === null || _b === void 0 ? void 0 : _b.call(_a); | ||
await this.setReadOnlyProperties({ element: null }); | ||
} | ||
/** | ||
* Updates element state when Stripe Element is blurred. | ||
*/ | ||
async onBlur() { | ||
await this.setReadOnlyProperties({ focused: false }); | ||
} | ||
/** | ||
* @param {StripeFocusEvent} event | ||
* @private | ||
*/ | ||
async onFocus() { | ||
await this.setReadOnlyProperties({ focused: true }); | ||
} | ||
/** | ||
* Sets the `ready` property when the stripe element is ready to receive focus. | ||
*/ | ||
async onReady(event) { | ||
await this.setReadOnlyProperties({ ready: true, stripeReady: true }); | ||
this.fire('ready', event); | ||
// DEPRECATED | ||
this.fire('stripe-ready', event); | ||
} | ||
/** | ||
* POSTs the payment info represenation to the endpoint at `/action` | ||
* @resolves {void} | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "postRepresentation", | ||
value: async function postRepresentation() { | ||
const onError = error => this.set({ | ||
error | ||
}); | ||
const onSuccess = success => { | ||
this.fire('success', success); // DEPRECATED | ||
this.fire('stripe-payment-success', success); | ||
} | ||
/** | ||
* POSTs the payment info represenation to the endpoint at `/action` | ||
*/ | ||
async postRepresentation() { | ||
const onError = (error) => this.setReadOnlyProperties({ error }); | ||
const onSuccess = (success) => { | ||
this.fire('success', success); | ||
// DEPRECATED | ||
this.fire('stripe-payment-success', success); | ||
}; | ||
const token = this.token || undefined; | ||
const source = this.source || undefined; | ||
const paymentMethod = this.paymentMethod || undefined; | ||
const body = JSON.stringify({ | ||
token, | ||
source, | ||
paymentMethod | ||
}); | ||
const headers = { | ||
'Content-Type': 'application/json' | ||
}; | ||
const body = JSON.stringify({ token, source, paymentMethod }); | ||
const headers = { 'Content-Type': 'application/json' }; | ||
const method = 'POST'; | ||
return fetch(this.action, { | ||
body, | ||
headers, | ||
method | ||
}).then(throwBadResponse).then(onSuccess).catch(onError); | ||
} | ||
/** | ||
* @param {string} name | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "representationChanged", | ||
value: function representationChanged(name) { | ||
if (!isRepresentation(name)) return; | ||
return fetch(this.action, { body, headers, method }) | ||
.then(throwBadResponse) | ||
.then(onSuccess) | ||
.catch(onError); | ||
} | ||
/** | ||
* Updates the state and fires events when the token, source, or payment method is updated. | ||
*/ | ||
representationChanged(name) { | ||
if (!isRepresentation(name)) | ||
return; | ||
const value = this[name]; | ||
/* istanbul ignore if */ | ||
if (!value) return; // DEPRECATED | ||
if (!value) | ||
return; | ||
// DEPRECATED | ||
this.fire(`stripe-${dash(name)}`, value); | ||
this.fire(`${dash(name)}`, value); | ||
if (this.action) this.postRepresentation(); | ||
} | ||
/** | ||
* Resets the Payment Representations | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "resetRepresentations", | ||
value: function resetRepresentations() { | ||
this.set({ | ||
paymentMethod: null, | ||
token: null, | ||
source: null | ||
if (this.action) | ||
this.postRepresentation(); | ||
} | ||
/** | ||
* Resets the Payment Representations | ||
*/ | ||
resetRepresentations() { | ||
this.setReadOnlyProperties({ | ||
paymentMethod: null, | ||
token: null, | ||
source: null, | ||
}); | ||
} | ||
}] | ||
}; | ||
}, ReadOnlyPropertiesMixin(LitNotify(LitElement))); | ||
/** @typedef {stripe.PaymentIntentResponse|stripe.PaymentMethodResponse|stripe.SetupIntentResponse|stripe.TokenResponse|stripe.SourceResponse} PaymentResponse */ | ||
} | ||
} | ||
__decorate([ | ||
property({ type: String }), | ||
__metadata("design:type", String) | ||
], StripeBase.prototype, "action", void 0); | ||
__decorate([ | ||
property({ type: String, attribute: 'client-secret' }), | ||
__metadata("design:type", String) | ||
], StripeBase.prototype, "clientSecret", void 0); | ||
__decorate([ | ||
property({ type: String }), | ||
__metadata("design:type", String) | ||
], StripeBase.prototype, "generate", void 0); | ||
__decorate([ | ||
property({ type: String, attribute: 'publishable-key', reflect: true, notify: true }), | ||
__metadata("design:type", String) | ||
], StripeBase.prototype, "publishableKey", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'show-error', reflect: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "showError", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true, attribute: 'payment-method' }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "paymentMethod", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "source", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "token", void 0); | ||
__decorate([ | ||
property({ type: Object, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "element", void 0); | ||
__decorate([ | ||
property({ type: Object, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "elements", void 0); | ||
__decorate([ | ||
property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true, | ||
reflect: true, | ||
converter: errorConverter, | ||
}), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "error", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "focused", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "ready", void 0); | ||
__decorate([ | ||
property({ type: Object, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "stripe", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'has-error', reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "hasError", void 0); | ||
__decorate([ | ||
property({ | ||
type: Boolean, | ||
attribute: 'stripe-ready', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true, | ||
}), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "stripeReady", void 0); | ||
__decorate([ | ||
bind, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeBase.prototype, "handleResponse", null); | ||
__decorate([ | ||
bind, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", []), | ||
__metadata("design:returntype", Promise) | ||
], StripeBase.prototype, "onBlur", null); | ||
__decorate([ | ||
bind, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", []), | ||
__metadata("design:returntype", Promise) | ||
], StripeBase.prototype, "onFocus", null); | ||
__decorate([ | ||
bind, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeBase.prototype, "onReady", null); | ||
__decorate([ | ||
bind, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [String]), | ||
__metadata("design:returntype", void 0) | ||
], StripeBase.prototype, "representationChanged", null); | ||
/** @typedef {{ owner: stripe.OwnerData }} SourceData */ | ||
/** @typedef {{ elementType: stripe.elements.elementsType }} StripeFocusEvent */ | ||
var sharedStyles = css`[hidden] { | ||
@@ -1208,3 +683,3 @@ display: none !important; | ||
export { StripeBase as S, mapProps as a, bound as b, camel as c, dash as d, mapDataset as m, sharedStyles as s }; | ||
export { StripeBase as S, bind as b, dash as d, sharedStyles as s }; | ||
//# sourceMappingURL=shared.js.map |
export { StripeElements } from './stripe-elements'; | ||
export { StripePaymentRequest } from './stripe-payment-request'; | ||
//# sourceMappingURL=index.js.map |
import { curry } from '@typed/curry'; | ||
import { render } from 'lit-html'; | ||
/** | ||
* Remove an element from the DOM | ||
* @param {ChildNode} el | ||
* @return {void} | ||
* @param el element to remove | ||
*/ | ||
/* istanbul ignore next */ | ||
export const remove = el => | ||
el?.remove(); | ||
export const remove = (el) => el === null || el === void 0 ? void 0 : el.remove(); | ||
export const appendTemplate = curry(function appendTemplate(template, target) { | ||
const tmp = document.createElement('div'); | ||
render(template, tmp); | ||
const { firstElementChild } = tmp; | ||
target.appendChild(firstElementChild); | ||
tmp.remove(); | ||
return firstElementChild; | ||
const tmp = document.createElement('div'); | ||
render(template, tmp); | ||
const { firstElementChild } = tmp; | ||
target.appendChild(firstElementChild); | ||
tmp.remove(); | ||
return firstElementChild; | ||
}); | ||
const mapPropEntry = mapping => ([key, value]) => | ||
key in mapping && | ||
typeof mapping[key] === 'function' ? | ||
[key, mapping[key](value)] | ||
: [key, value]; | ||
export const mapProps = mapping => obj => | ||
Object.fromEntries(Object.entries(obj).map(mapPropEntry(mapping))); | ||
export const mapDataset = f => ({ dataset }) => f(dataset); | ||
//# sourceMappingURL=dom.js.map |
/** | ||
* Throws an error if the response is not OK.) | ||
* @param {Response} response | ||
* @resolves {Response} | ||
* @rejects {Error} | ||
*/ | ||
export async function throwBadResponse(response) { | ||
const { ok, statusText } = response; | ||
if (!ok) throw new Error(statusText); | ||
return response; | ||
const { ok, statusText } = response; | ||
if (!ok) | ||
throw new Error(statusText); | ||
return response; | ||
} | ||
//# sourceMappingURL=fetch.js.map |
export const unary = f => x => f(x); | ||
//# sourceMappingURL=functions.js.map |
export const objectOf = key => x => ({ [key]: x }); | ||
//# sourceMappingURL=object.js.map |
export const elem = xs => x => xs.includes(x); | ||
export const not = p => x => !p(x); | ||
export const isRepresentation = elem(['paymentMethod', 'source', 'token']); | ||
//# sourceMappingURL=predicates.js.map |
import eagerDash from '@lavadrop/kebab-case'; | ||
import eagerCamel from '@lavadrop/camel-case'; | ||
import { memoize } from '@pacote/memoize'; | ||
const identity = x => x; | ||
/** camelCase a string */ | ||
export const camel = memoize(identity, eagerCamel); | ||
/** dash-case a string */ | ||
export const dash = memoize(identity, eagerDash); | ||
/** | ||
@@ -20,3 +16,4 @@ * Generates a random mount point for Stripe Elements. This will allow multiple | ||
export function generateRandomMountElementId(tagName) { | ||
return `${tagName.toLowerCase()}-mount-point-${(Date.now() + (Math.random() * 1000)).toString(36).substr(0, 8)}`; | ||
return `${tagName.toLowerCase()}-mount-point-${(Date.now() + (Math.random() * 1000)).toString(36).substr(0, 8)}`; | ||
} | ||
//# sourceMappingURL=strings.js.map |
@@ -1,21 +0,17 @@ | ||
/* eslint-disable no-invalid-this */ | ||
function wrap(f) { | ||
return wrapped => { | ||
const { descriptor } = wrapped; | ||
const original = descriptor.value; | ||
descriptor.value = f(original); | ||
return { ...wrapped, descriptor }; | ||
}; | ||
return (_target, _property, descriptor) => { | ||
const original = descriptor.value; | ||
descriptor.value = f(original); | ||
return descriptor; | ||
}; | ||
} | ||
export const stripeMethod = wrap(function(f) { | ||
const { name } = f; | ||
return async function(...args) { | ||
if (!this.stripe) throw new Error(`<${this.constructor.is}>: Stripe must be initialized before calling ${name}.`); | ||
return f.call(this, ...args) | ||
.then(this.handleResponse); | ||
}; | ||
export const stripeMethod = wrap(function (f) { | ||
const { name } = f; | ||
return async function (...args) { | ||
if (!this.stripe) | ||
throw new Error(`<${this.constructor.is}>: Stripe must be initialized before calling ${name}.`); | ||
return f.call(this, ...args) | ||
.then(this.handleResponse); | ||
}; | ||
}); | ||
//# sourceMappingURL=stripe-method-decorator.js.map |
export function throwResponseError(response) { | ||
if (response.error) throw response.error; | ||
else return response; | ||
if (response.error) | ||
throw response.error; | ||
else | ||
return response; | ||
} | ||
//# sourceMappingURL=stripe.js.map |
@@ -1,4 +0,429 @@ | ||
import { StripeElements } from './StripeElements'; | ||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { | ||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; | ||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); | ||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; | ||
return c > 3 && r && Object.defineProperty(target, key, r), r; | ||
}; | ||
var __metadata = (this && this.__metadata) || function (k, v) { | ||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); | ||
}; | ||
import { property, customElement } from 'lit-element'; | ||
import bound from 'bind-decorator'; | ||
import { StripeBase } from './StripeBase'; | ||
import { dash } from './lib/strings'; | ||
import { stripeMethod } from './lib/stripe-method-decorator'; | ||
import sharedStyles from './shared.css'; | ||
import style from './stripe-elements.css'; | ||
const allowedStyles = [ | ||
'color', | ||
'fontFamily', | ||
'fontSize', | ||
'fontStyle', | ||
'fontSmoothing', | ||
'fontVariant', | ||
'iconColor', | ||
'lineHeight', | ||
'letterSpacing', | ||
'textDecoration', | ||
'textShadow', | ||
'textTransform', | ||
]; | ||
/** | ||
* [Stripe.js v3 Card Elements](https://stripe.com/docs/elements), but it's a Web Component! | ||
* Supports Shadow DOM. | ||
* | ||
* 👨🎨 [Live Demo](https://bennypowers.dev/stripe-elements/?path=/docs/stripe-elements--enter-a-stripe-publishable-key) 👀 | ||
* | ||
* ### 🧙♂️ Usage | ||
* If you prebuilt with Snowpack, load the module from your `web_modules` directory | ||
* | ||
* ```html | ||
* <script type="module" src="/web_modules/@power-elements/stripe-elements/stripe-elements.js"></script> | ||
* ``` | ||
* | ||
* Alternatively, load the module from the unpkg CDN | ||
* ```html | ||
* <script type="module" src="https://unpkg.com/@power-elements/stripe-elements/stripe-elements.js?module"></script> | ||
* ``` | ||
* | ||
* Then you can add the element to your page. | ||
* | ||
* ```html | ||
* <stripe-elements id="stripe" | ||
* action="/payment" | ||
* publishable-key="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX" | ||
* ></stripe-elements> | ||
* ``` | ||
* | ||
* See the demos for more comprehensive examples. | ||
* - Using `<stripe-elements>` with [plain HTML and JavaScript](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-html--stripe-elements). | ||
* - Using `<stripe-elements>` in a [LitElement](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-litelement--stripe-elements). | ||
* - Using `<stripe-elements>` in a [Vue Component](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-vue--stripe-elements). | ||
* - Using `<stripe-elements>` in an [Angular component](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-angular--stripe-elements). | ||
* - Using `<stripe-elements>` in a [React component](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-react--stripe-elements). | ||
* - Using `<stripe-elements>` in a [Preact component](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-preact--stripe-elements). | ||
* | ||
* ## Styling | ||
* | ||
* Stripe v3's 'Stripe Elements' are not custom elements, but rather forms | ||
* hosted by stripe and injected into your page via an iFrame. When we refer to the | ||
* 'Stripe Element' in this document, we are referring to the hosted Stripe form, | ||
* not the `<stripe-element>` custom element. But when I mention the 'element', I mean the custom element. | ||
* | ||
* When you apply CSS to the custom properties available, they're parsed and sent to Stripe, who should apply them to the Stripe Element they return in the iFrame. | ||
* | ||
* - `base` styles are inherited by all other variants. | ||
* - `complete` styles are applied when the Stripe Element has valid input. | ||
* - `empty` styles are applied when the Stripe Element has no user input. | ||
* - `invalid` styles are applied when the Stripe Element has invalid input. | ||
* | ||
* There are 11 properties for each state that you can set which will be read into the Stripe Element iFrame: | ||
* | ||
* - `color` | ||
* - `font-family` | ||
* - `font-size` | ||
* - `font-smoothing` | ||
* - `font-variant` | ||
* - `icon-color` | ||
* - `line-height` | ||
* - `letter-spacing` | ||
* - `text-decoration` | ||
* - `text-shadow` | ||
* - `text-transform` | ||
* | ||
* @cssprop [--stripe-elements-border-radius=`4px`] - border radius of the element container | ||
* @cssprop [--stripe-elements-border=`1px solid transparent`] - border property of the element container | ||
* @cssprop [--stripe-elements-box-shadow=`0 1px 3px 0 #e6ebf1`] - box shadow for the element container | ||
* @cssprop [--stripe-elements-transition=`box-shadow 150ms ease`] - transition property for the element container | ||
* | ||
* @cssprop [--stripe-elements-base-color] - `color` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-font-family] - `font-family` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-font-size] - `font-size` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-font-smoothing] - `font-smoothing` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-font-variant] - `font-variant` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-icon-color] - `icon-color` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-line-height] - `line-height` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-letter-spacing] - `letter-spacing` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-text-decoration] - `text-decoration` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-text-shadow] - `text-shadow` property for the element in its base state | ||
* @cssprop [--stripe-elements-base-text-transform] - `text-transform` property for the element in its base state | ||
* | ||
* @cssprop [--stripe-elements-complete-color] - `color` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-font-family] - `font-family` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-font-size] - `font-size` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-font-smoothing] - `font-smoothing` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-font-variant] - `font-variant` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-icon-color] - `icon-color` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-line-height] - `line-height` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-letter-spacing] - `letter-spacing` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-text-decoration] - `text-decoration` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-text-shadow] - `text-shadow` property for the element in its complete state | ||
* @cssprop [--stripe-elements-complete-text-transform] - `text-transform` property for the element in its complete state | ||
* | ||
* @cssprop [--stripe-elements-empty-color] - `color` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-font-family] - `font-family` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-font-size] - `font-size` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-font-smoothing] - `font-smoothing` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-font-variant] - `font-variant` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-icon-color] - `icon-color` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-line-height] - `line-height` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-letter-spacing] - `letter-spacing` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-text-decoration] - `text-decoration` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-text-shadow] - `text-shadow` property for the element in its empty state | ||
* @cssprop [--stripe-elements-empty-text-transform] - `text-transform` property for the element in its empty state | ||
* | ||
* @cssprop [--stripe-elements-invalid-color] - `color` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-font-family] - `font-family` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-font-size] - `font-size` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-font-smoothing] - `font-smoothing` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-font-variant] - `font-variant` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-icon-color] - `icon-color` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-line-height] - `line-height` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-letter-spacing] - `letter-spacing` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-text-decoration] - `text-decoration` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-text-shadow] - `text-shadow` property for the element in its invalid state | ||
* @cssprop [--stripe-elements-invalid-text-transform] - `text-transform` property for the element in its invalid state | ||
* | ||
* @element stripe-elements | ||
* @extends StripeBase | ||
* | ||
* @fires 'change' - Stripe Element change event | ||
*/ | ||
let StripeElements = class StripeElements extends StripeBase { | ||
constructor() { | ||
super(...arguments); | ||
/* PUBLIC FIELDS */ | ||
/** | ||
* Whether to hide icons in the Stripe form. | ||
*/ | ||
this.hideIcon = false; | ||
/** | ||
* Whether or not to hide the postal code field. | ||
* Useful when you gather shipping info elsewhere. | ||
*/ | ||
this.hidePostalCode = false; | ||
/** | ||
* Stripe icon style. | ||
*/ | ||
this.iconStyle = 'default'; | ||
/** | ||
* Prefilled values for form. | ||
* @example { postalCode: '90210' } | ||
*/ | ||
this.value = {}; | ||
/* READ ONLY PROPERTIES */ | ||
/** | ||
* The card brand detected by Stripe | ||
*/ | ||
this.brand = null; | ||
/** | ||
* Whether the form is complete. | ||
*/ | ||
this.complete = false; | ||
/** | ||
* If the form is empty. | ||
*/ | ||
this.empty = true; | ||
/** | ||
* Whether the form is invalid. | ||
*/ | ||
this.invalid = false; | ||
// DEPRECATED | ||
/** | ||
* The Stripe card object. | ||
* **DEPRECATED**. Will be removed in a future version. use `element` instead | ||
* @deprecated | ||
*/ | ||
this.card = null; | ||
/** | ||
* Whether the form is empty. | ||
* **DEPRECATED**. Will be removed in a future version. use `empty` instead | ||
* @deprecated | ||
*/ | ||
this.isEmpty = true; | ||
/** | ||
* Whether the form is complete. | ||
* **DEPRECATED**. Will be removed in a future version. use `complete` instead | ||
* @deprecated | ||
*/ | ||
this.isComplete = false; | ||
} | ||
updated(changed) { | ||
super.updated(changed); | ||
// DEPRECATED | ||
if (changed.has('element') && !this.element) | ||
this.setReadOnlyProperties({ card: null }); | ||
} | ||
/* PUBLIC API */ | ||
/** | ||
* Submit payment information to generate a paymentMethod | ||
*/ | ||
async createPaymentMethod(paymentMethodData = this.getPaymentMethodData()) { | ||
return this.stripe.createPaymentMethod(paymentMethodData); | ||
} | ||
/** | ||
* Submit payment information to generate a source | ||
*/ | ||
async createSource(sourceData = this.sourceData) { | ||
return this.stripe.createSource(this.element, sourceData); | ||
} | ||
/** | ||
* Submit payment information to generate a token | ||
*/ | ||
async createToken(tokenData = this.tokenData) { | ||
return this.stripe.createToken(this.element, tokenData); | ||
} | ||
/** | ||
* Checks for potential validity. A potentially valid form is one that is not empty, not complete and has no error. A validated form also counts as potentially valid. | ||
*/ | ||
isPotentiallyValid() { | ||
return (!this.complete && !this.empty && !this.error) || this.validate(); | ||
} | ||
/** | ||
* Resets the Stripe card. | ||
*/ | ||
reset() { | ||
var _a; | ||
super.reset(); | ||
/* istanbul ignore next */ | ||
(_a = this.element) === null || _a === void 0 ? void 0 : _a.clear(); | ||
} | ||
/** | ||
* Generates a payment representation of the type specified by `generate`. | ||
*/ | ||
async submit() { | ||
switch (this.generate) { | ||
case 'payment-method': return this.createPaymentMethod(); | ||
case 'source': return this.createSource(); | ||
case 'token': return this.createToken(); | ||
default: { | ||
const error = this.createError(`cannot generate ${this.generate}`); | ||
await this.setReadOnlyProperties({ error }); | ||
throw error; | ||
} | ||
} | ||
} | ||
/** | ||
* Checks if the Stripe form is valid. | ||
*/ | ||
validate() { | ||
const { complete, empty, error } = this; | ||
const isValid = !error && complete && !empty; | ||
if (empty && !error) | ||
this.setReadOnlyProperties({ error: this.createError('Your card number is empty.') }); | ||
return isValid; | ||
} | ||
/* PRIVATE METHODS */ | ||
/** | ||
* Generates PaymentMethodData from the element. | ||
*/ | ||
getPaymentMethodData() { | ||
const type = 'card'; | ||
const { billingDetails, element: card, paymentMethodData } = this; | ||
return ({ | ||
billing_details: billingDetails, | ||
...paymentMethodData, | ||
type, | ||
card, | ||
}); | ||
} | ||
/** | ||
* Returns a Stripe-friendly style object computed from CSS custom properties | ||
*/ | ||
getStripeElementsStyles() { | ||
const computedStyle = window.ShadyCSS ? undefined : getComputedStyle(this); | ||
const getStyle = (prop) => this.getCSSCustomPropertyValue(prop, computedStyle) || undefined; | ||
const styleReducer = ({ base = {}, complete = {}, empty = {}, invalid = {}, }, camelCase) => ({ | ||
base: { ...base, [camelCase]: getStyle(`--stripe-elements-base-${dash(camelCase)}`) }, | ||
complete: { ...complete, [camelCase]: getStyle(`--stripe-elements-complete-${dash(camelCase)}`) }, | ||
empty: { ...empty, [camelCase]: getStyle(`--stripe-elements-empty-${dash(camelCase)}`) }, | ||
invalid: { ...invalid, [camelCase]: getStyle(`--stripe-elements-invalid-${dash(camelCase)}`) }, | ||
}); | ||
return allowedStyles.reduce(styleReducer, {}); | ||
} | ||
async initElement() { | ||
if (!this.stripe) | ||
return; | ||
const { hidePostalCode, hideIcon, iconStyle, value } = this; | ||
const style = this.getStripeElementsStyles(); | ||
const options = { | ||
hideIcon, | ||
hidePostalCode, | ||
iconStyle, | ||
style, | ||
value, | ||
}; | ||
const element = this.elements.create('card', options); | ||
element.addEventListener('change', this.onChange); | ||
await this.setReadOnlyProperties({ | ||
element, | ||
// DEPRECATED | ||
card: element, | ||
}); | ||
} | ||
/** | ||
* Updates the element's state. | ||
*/ | ||
async onChange(event) { | ||
const { brand, complete, empty, error = null } = event; | ||
const invalid = error || (!empty && !complete); | ||
await this.setReadOnlyProperties({ | ||
brand, | ||
complete, | ||
empty, | ||
error, | ||
invalid, | ||
// DEPRECATED | ||
isComplete: complete, | ||
isEmpty: empty, | ||
}); | ||
this.fire('change', event); | ||
// DEPRECATED | ||
this.fire('stripe-change', event); | ||
} | ||
}; | ||
StripeElements.is = 'stripe-elements'; | ||
StripeElements.elementType = 'card'; | ||
StripeElements.styles = [ | ||
sharedStyles, | ||
style, | ||
]; | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'hide-icon' }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "hideIcon", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'hide-postal-code' }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "hidePostalCode", void 0); | ||
__decorate([ | ||
property({ type: String, attribute: 'icon-style' }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "iconStyle", void 0); | ||
__decorate([ | ||
property({ type: Object }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "value", void 0); | ||
__decorate([ | ||
property({ type: String, notify: true, readOnly: true }), | ||
__metadata("design:type", String) | ||
], StripeElements.prototype, "brand", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "complete", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "empty", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "invalid", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "card", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'is-empty', reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "isEmpty", void 0); | ||
__decorate([ | ||
property({ | ||
type: Boolean, | ||
attribute: 'is-complete', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true, | ||
}), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "isComplete", void 0); | ||
__decorate([ | ||
stripeMethod, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeElements.prototype, "createPaymentMethod", null); | ||
__decorate([ | ||
stripeMethod, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeElements.prototype, "createSource", null); | ||
__decorate([ | ||
stripeMethod, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeElements.prototype, "createToken", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeElements.prototype, "onChange", null); | ||
StripeElements = __decorate([ | ||
customElement('stripe-elements') | ||
], StripeElements); | ||
export { StripeElements }; | ||
customElements.define(StripeElements.is, StripeElements); | ||
//# sourceMappingURL=stripe-elements.js.map |
@@ -1,4 +0,430 @@ | ||
import { StripePaymentRequest } from './StripePaymentRequest'; | ||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { | ||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; | ||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); | ||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; | ||
return c > 3 && r && Object.defineProperty(target, key, r), r; | ||
}; | ||
var __metadata = (this && this.__metadata) || function (k, v) { | ||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); | ||
}; | ||
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) { | ||
if (!privateMap.has(receiver)) { | ||
throw new TypeError("attempted to get private field on non-instance"); | ||
} | ||
return privateMap.get(receiver); | ||
}; | ||
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) { | ||
if (!privateMap.has(receiver)) { | ||
throw new TypeError("attempted to set private field on non-instance"); | ||
} | ||
privateMap.set(receiver, value); | ||
return value; | ||
}; | ||
var _displayItems, _shippingOptions; | ||
import { customElement, property } from 'lit-element'; | ||
import bound from 'bind-decorator'; | ||
import { StripeBase } from './StripeBase'; | ||
import { throwResponseError } from './lib/stripe'; | ||
import sharedStyles from './shared.css'; | ||
import style from './stripe-payment-request.css'; | ||
export function isStripeDisplayItem(el) { | ||
return el.tagName.toLowerCase() === 'stripe-display-item'; | ||
} | ||
function datasetToStripeDisplayItem({ dataset: { amount, label, pending } }) { | ||
return { | ||
label, | ||
amount: parseInt(amount), | ||
...pending !== undefined && { pending: pending === 'true' ? true : false }, | ||
}; | ||
} | ||
export function isStripeShippingOption(el) { | ||
return el.tagName.toLowerCase() === 'stripe-shipping-option'; | ||
} | ||
function datasetToStripeShippingOption({ dataset: { amount, ...rest } }) { | ||
return { | ||
amount: parseInt(amount), | ||
...rest, | ||
}; | ||
} | ||
function mapDataset(el) { | ||
return (isStripeDisplayItem(el) ? datasetToStripeDisplayItem(el) | ||
: datasetToStripeShippingOption(el)); | ||
} | ||
/** | ||
* Custom element wrapper for Stripe.js v3 Payment Request Buttons. | ||
* | ||
* 👨🎨 [Live Demo](https://bennypowers.dev/stripe-elements/?path=/docs/stripe-payment-request--enter-a-stripe-publishable-key) 👀 | ||
* | ||
* ### 🧙♂️ Usage | ||
* If you prebuilt with Snowpack, load the module from your `web_modules` directory | ||
* | ||
* ```html | ||
* <script type="module" src="/web_modules/@power-elements/stripe-elements/stripe-payment-request.js"></script> | ||
* ``` | ||
* | ||
* Alternatively, load the module from the unpkg CDN | ||
* ```html | ||
* <script type="module" src="https://unpkg.com/@power-elements/stripe-elements/stripe-payment-request.js?module"></script> | ||
* ``` | ||
* | ||
* Then you can add the element to your page. | ||
* | ||
* ```html | ||
* | ||
* <stripe-payment-request id="payment-request" | ||
* publishable-key="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX" | ||
* generate="token" | ||
* action="/charges" | ||
* country="CA" | ||
* currency="cad" | ||
* amount="1000" | ||
* label="Ten Bones" | ||
* request-payer-name | ||
* request-payer-email | ||
* request-payer-phone | ||
* ></stripe-payment-request> | ||
* ``` | ||
* | ||
* See the demos for more comprehensive examples. | ||
* - Using `<stripe-payment-request>` with [plain HTML and JavaScript](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-vanilla--stripe-payment-request). | ||
* - Using `<stripe-payment-request>` in a [LitElement](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-litelement--stripe-payment-request). | ||
* - Using `<stripe-payment-request>` in a [Vue Component](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-vue--stripe-payment-request). | ||
* - Using `<stripe-payment-request>` in an [Angular component](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-angular--stripe-payment-request). | ||
* - Using `<stripe-payment-request>` in a [React component](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-react--stripe-payment-request). | ||
* - Using `<stripe-payment-request>` in a [Preact component](https://bennypowers.dev/stripe-elements/?path=/docs/framework-examples-preact--stripe-payment-request). | ||
* | ||
* @cssprop [--stripe-payment-request-element-min-width=`300px`] - min-width property of the container element | ||
* @cssprop [--stripe-payment-request-element-padding=`8px 12px`] - padding property of the container element | ||
* @cssprop [--stripe-payment-request-element-background=`white`] - background property of the container element | ||
* | ||
* @element stripe-payment-request | ||
* @extends StripeBase | ||
* | ||
* @fires 'unsupported' - When the element detects that the user agent cannot make a payment | ||
* @fires 'fail' - When a payment request fails | ||
* @fires 'cancel' - When a payment request is cancelled | ||
* @fires 'shippingaddresschange' - When the user chooses a different shipping address | ||
* @fires 'shippingoptionchange' - When the user chooses a different shipping option | ||
*/ | ||
let StripePaymentRequest = class StripePaymentRequest extends StripeBase { | ||
constructor() { | ||
super(...arguments); | ||
/** | ||
* Whether or not the device can make the payment request. | ||
* @readonly | ||
*/ | ||
this.canMakePayment = null; | ||
_displayItems.set(this, void 0); | ||
/** | ||
* Stripe PaymentIntent | ||
*/ | ||
this.paymentIntent = null; | ||
/** | ||
* Stripe PaymentRequest | ||
*/ | ||
this.paymentRequest = null; | ||
/** | ||
* If you might change the payment amount later (for example, after you have calcluated shipping costs), set this to true. Note that browsers treat this as a hint for how to display things, and not necessarily as something that will prevent submission. | ||
*/ | ||
this.pending = false; | ||
_shippingOptions.set(this, void 0); | ||
this.buttonType = 'default'; | ||
this.buttonTheme = 'dark'; | ||
} | ||
/** | ||
* An array of DisplayItem objects. These objects are shown as line items in the browser’s payment interface. Note that the sum of the line item amounts does not need to add up to the total amount above. | ||
*/ | ||
get displayItems() { | ||
const value = __classPrivateFieldGet(this, _displayItems); | ||
return (Array.isArray(value) ? value | ||
: this.parseDatasets('stripe-display-item')); | ||
} | ||
set displayItems(value) { | ||
const oldValue = this.displayItems; | ||
__classPrivateFieldSet(this, _displayItems, value); | ||
this.requestUpdate('displayItems', oldValue); | ||
} | ||
/** | ||
* An array of ShippingOption objects. The first shipping option listed appears in the browser payment interface as the default option. | ||
*/ | ||
get shippingOptions() { | ||
const value = __classPrivateFieldGet(this, _shippingOptions); | ||
return Array.isArray(value) ? value : this.parseDatasets('stripe-shipping-option'); | ||
} | ||
set shippingOptions(value) { | ||
const oldValue = this.shippingOptions; | ||
__classPrivateFieldSet(this, _shippingOptions, value); | ||
this.requestUpdate('shippingOptions', oldValue); | ||
} | ||
/* PUBLIC API */ | ||
reset() { | ||
super.reset(); | ||
this.setReadOnlyProperties({ paymentIntent: null }); | ||
} | ||
/* LIFECYCLE */ | ||
/** @inheritdoc */ | ||
updated(changed) { | ||
super.updated(changed); | ||
if (changed.has('generate')) | ||
this.initPaymentRequestListeners(); | ||
} | ||
/* PRIVATE API */ | ||
/** | ||
* Creates a StripePaymentRequestOptions object. | ||
*/ | ||
getStripePaymentRequestOptions() { | ||
const { country, currency, displayItems, shippingOptions, requestPayerEmail, requestPayerName, requestPayerPhone, label, amount, } = this; | ||
const total = { label, amount }; | ||
return { | ||
country, | ||
currency, | ||
displayItems, | ||
requestPayerEmail, | ||
requestPayerName, | ||
requestPayerPhone, | ||
shippingOptions, | ||
total, | ||
}; | ||
} | ||
/** | ||
* Initializes the PaymentRequest Object. | ||
*/ | ||
async initElement() { | ||
await this.initPaymentRequest(); | ||
await this.initPaymentRequestListeners(); | ||
await this.initPaymentRequestButton(); | ||
} | ||
/** | ||
* Initialized the `PaymentRequest` object. | ||
*/ | ||
async initPaymentRequest() { | ||
if (!this.stripe) | ||
return; | ||
const stripePaymentRequestOptions = this.getStripePaymentRequestOptions(); | ||
const paymentRequest = this.stripe.paymentRequest(stripePaymentRequestOptions); | ||
const canMakePayment = await paymentRequest.canMakePayment(); | ||
await this.setReadOnlyProperties({ paymentRequest, canMakePayment }); | ||
if (!this.canMakePayment) | ||
this.fire('unsupported'); | ||
} | ||
/** | ||
* Creates Stripe Payment Request Element. | ||
*/ | ||
async initPaymentRequestButton() { | ||
const { buttonTheme: theme, buttonType: type, canMakePayment, paymentRequest } = this; | ||
if (!canMakePayment) | ||
return; | ||
const computedStyle = window.ShadyCSS ? undefined : getComputedStyle(this); | ||
const propertyName = '--stripe-payment-request-button-height'; | ||
const height = this.getCSSCustomPropertyValue(propertyName, computedStyle) || '40px'; | ||
const style = { paymentRequestButton: { height, theme, type } }; | ||
const options = { paymentRequest, style }; | ||
const element = this.elements.create('paymentRequestButton', options); | ||
await this.setReadOnlyProperties({ element }); | ||
} | ||
/** | ||
* Attaches listeners to the `PaymentRequest` object. | ||
*/ | ||
async initPaymentRequestListeners() { | ||
if (!this.canMakePayment) | ||
return; | ||
this.paymentRequest.on('cancel', this.onCancel); | ||
this.paymentRequest.on('shippingaddresschange', this.onShippingaddresschange); | ||
this.paymentRequest.on('shippingoptionchange', this.onShippingoptionchange); | ||
switch (this.generate) { | ||
case 'payment-method': | ||
this.paymentRequest.on('paymentmethod', this.onPaymentResponse); | ||
break; | ||
case 'source': | ||
this.paymentRequest.on('source', this.onPaymentResponse); | ||
break; | ||
case 'token': | ||
this.paymentRequest.on('token', this.onPaymentResponse); | ||
break; | ||
} | ||
} | ||
/** | ||
* Handle a `cancel` event | ||
*/ | ||
onCancel() { | ||
this.fire("cancel" /* cancel */); | ||
} | ||
/** | ||
* Completes the PaymentRequest. | ||
*/ | ||
async complete(paymentResponse, confirmationError) { | ||
const { error: paymentResponseError = null } = { ...paymentResponse }; | ||
const status = (paymentResponseError || confirmationError) ? "fail" /* fail */ : "success" /* success */; | ||
paymentResponse.complete(status); | ||
this.fire(status, paymentResponse); | ||
return confirmationError ? { error: confirmationError } : paymentResponse; | ||
} | ||
/** | ||
* Handle a paymentResponse from Stripe | ||
*/ | ||
async onPaymentResponse(paymentResponse) { | ||
const { clientSecret, confirmPaymentIntent, complete } = this; | ||
const { error = null, paymentMethod = null, source = null, token = null, } = { ...paymentResponse }; | ||
await this.setReadOnlyProperties({ error, paymentMethod, source, token }); | ||
const isPaymentIntent = clientSecret && !error; | ||
if (isPaymentIntent) | ||
confirmPaymentIntent(paymentResponse); | ||
else | ||
complete(paymentResponse); | ||
} | ||
/** | ||
* When a PaymentIntent client secret is set, confirm the payment | ||
*/ | ||
async confirmPaymentIntent(paymentResponse) { | ||
const confirmCardData = { payment_method: this.paymentMethod.id }; // eslint-disable-line @typescript-eslint/camelcase | ||
const { error = null, paymentIntent = null } = await this.confirmCardPayment(confirmCardData, { handleActions: false }) | ||
.then(({ error: confirmationError }) => this.complete(paymentResponse, confirmationError)) // throws if first confirm errors | ||
.then(throwResponseError) | ||
.then(() => this.confirmCardPayment()) | ||
.then(throwResponseError) | ||
.catch(error => ({ error })); // catch error from first confirm | ||
await this.setReadOnlyProperties({ error, paymentIntent }); | ||
} | ||
/** | ||
* Stripe confirmCardPayment method | ||
*/ | ||
async confirmCardPayment(data, options) { | ||
return this.stripe.confirmCardPayment(this.clientSecret, data, options); | ||
} | ||
onShippingaddresschange(originalEvent) { | ||
this.fire('shippingaddresschange', originalEvent); | ||
} | ||
onShippingoptionchange(originalEvent) { | ||
this.fire('shippingoptionchange', originalEvent); | ||
} | ||
parseDatasets(selector) { | ||
const elements = [...this.querySelectorAll(selector)]; | ||
return (!elements.length ? [] | ||
: elements.map(mapDataset)); | ||
} | ||
}; | ||
_displayItems = new WeakMap(), _shippingOptions = new WeakMap(); | ||
StripePaymentRequest.is = 'stripe-payment-request'; | ||
StripePaymentRequest.styles = [ | ||
sharedStyles, | ||
style, | ||
]; | ||
__decorate([ | ||
property({ type: Number, reflect: true }), | ||
__metadata("design:type", Number) | ||
], StripePaymentRequest.prototype, "amount", void 0); | ||
__decorate([ | ||
property({ | ||
type: Boolean, | ||
attribute: 'can-make-payment', | ||
reflect: true, | ||
readOnly: true, | ||
notify: true, | ||
}), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "canMakePayment", void 0); | ||
__decorate([ | ||
property({ type: String }), | ||
__metadata("design:type", String) | ||
], StripePaymentRequest.prototype, "country", void 0); | ||
__decorate([ | ||
property({ type: String }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "currency", void 0); | ||
__decorate([ | ||
property({ type: Array }), | ||
__metadata("design:type", Array), | ||
__metadata("design:paramtypes", [Object]) | ||
], StripePaymentRequest.prototype, "displayItems", null); | ||
__decorate([ | ||
property({ type: String, reflect: true }), | ||
__metadata("design:type", String) | ||
], StripePaymentRequest.prototype, "label", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true, attribute: 'payment-intent' }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "paymentIntent", void 0); | ||
__decorate([ | ||
property({ type: Object, attribute: 'payment-request', readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "paymentRequest", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "pending", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'request-payer-email' }), | ||
__metadata("design:type", Boolean) | ||
], StripePaymentRequest.prototype, "requestPayerEmail", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'request-payer-name' }), | ||
__metadata("design:type", Boolean) | ||
], StripePaymentRequest.prototype, "requestPayerName", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'request-payer-phone' }), | ||
__metadata("design:type", Boolean) | ||
], StripePaymentRequest.prototype, "requestPayerPhone", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'request-shipping' }), | ||
__metadata("design:type", Boolean) | ||
], StripePaymentRequest.prototype, "requestShipping", void 0); | ||
__decorate([ | ||
property({ type: Array }), | ||
__metadata("design:type", Array), | ||
__metadata("design:paramtypes", [Object]) | ||
], StripePaymentRequest.prototype, "shippingOptions", null); | ||
__decorate([ | ||
property({ type: String, attribute: 'button-type' }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "buttonType", void 0); | ||
__decorate([ | ||
property({ type: String, attribute: 'button-theme' }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "buttonTheme", void 0); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", []), | ||
__metadata("design:returntype", void 0) | ||
], StripePaymentRequest.prototype, "onCancel", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object, Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripePaymentRequest.prototype, "complete", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripePaymentRequest.prototype, "onPaymentResponse", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripePaymentRequest.prototype, "confirmPaymentIntent", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object, Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripePaymentRequest.prototype, "confirmCardPayment", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", void 0) | ||
], StripePaymentRequest.prototype, "onShippingaddresschange", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", void 0) | ||
], StripePaymentRequest.prototype, "onShippingoptionchange", null); | ||
StripePaymentRequest = __decorate([ | ||
customElement('stripe-payment-request') | ||
], StripePaymentRequest); | ||
export { StripePaymentRequest }; | ||
customElements.define(StripePaymentRequest.is, StripePaymentRequest); | ||
//# sourceMappingURL=stripe-payment-request.js.map |
@@ -0,9 +1,15 @@ | ||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { | ||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; | ||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); | ||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; | ||
return c > 3 && r && Object.defineProperty(target, key, r), r; | ||
}; | ||
var __metadata = (this && this.__metadata) || function (k, v) { | ||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); | ||
}; | ||
import { LitElement, property, html } from 'lit-element'; | ||
import { LitNotify } from '@morbidick/lit-element-notify'; | ||
import { ifDefined } from 'lit-html/directives/if-defined'; | ||
import bound from 'bound-decorator'; | ||
import { ReadOnlyPropertiesMixin } from './lib/read-only-properties'; | ||
import bound from 'bind-decorator'; | ||
import { ReadOnlyPropertiesMixin } from '@open-wc/lit-helpers'; | ||
import { appendTemplate, remove } from './lib/dom'; | ||
@@ -13,22 +19,20 @@ import { dash, generateRandomMountElementId } from './lib/strings'; | ||
import { throwBadResponse } from './lib/fetch'; | ||
class StripeElementsError extends Error { | ||
constructor(tag, message) { | ||
super(`<${tag}>: ${message}`); | ||
this.originalMessage = message; | ||
} | ||
constructor(tag, message) { | ||
super(`<${tag}>: ${message}`); | ||
this.originalMessage = message; | ||
} | ||
} | ||
function isStripeElementsError(error) { | ||
return !!error && error instanceof StripeElementsError; | ||
} | ||
/* istanbul ignore next */ | ||
const removeAllMounts = slotName => host => | ||
host.querySelectorAll(`[slot="${slotName}"][name="${slotName}"]`) | ||
const removeAllMounts = (slotName) => (host) => host.querySelectorAll(`[slot="${slotName}"][name="${slotName}"]`) | ||
.forEach(remove); | ||
const slotTemplate = slotName => | ||
html`<slot slot="${slotName}" name="${slotName}"></slot>`; | ||
const mountPointTemplate = ({ stripeMountId, tagName }) => | ||
html`<div id="${ifDefined(stripeMountId)}" class="${tagName.toLowerCase()}-mount"></div>`; | ||
const slotTemplate = (slotName) => html `<slot slot="${slotName}" name="${slotName}"></slot>`; | ||
const errorConverter = { | ||
toAttribute: (error) => !error ? null | ||
: isStripeElementsError(error) ? error.originalMessage | ||
: error.message || '', | ||
}; | ||
/** | ||
@@ -52,219 +56,82 @@ * @fires 'error' - The validation error, or the error returned from stripe.com | ||
export class StripeBase extends ReadOnlyPropertiesMixin(LitNotify(LitElement)) { | ||
/* PAYMENT CONFIGURATION */ | ||
/** | ||
* billing_details object sent to create the payment representation. (optional) | ||
* @type {stripe.BillingDetails} | ||
*/ | ||
billingDetails = {}; | ||
/** | ||
* Data passed to stripe.createPaymentMethod. (optional) | ||
* @type {stripe.PaymentMethodData} | ||
*/ | ||
paymentMethodData = {}; | ||
/** | ||
* Data passed to stripe.createSource. (optional) | ||
* @type {SourceData} | ||
*/ | ||
sourceData = {}; | ||
/** | ||
* Data passed to stripe.createToken. (optional) | ||
* @type {stripe.TokenOptions} | ||
*/ | ||
tokenData = {}; | ||
/* PAYMENT REPRESENTATIONS */ | ||
/** | ||
* Stripe PaymentMethod | ||
* @type {stripe.paymentMethod.PaymentMethod} | ||
* @readonly | ||
*/ | ||
@property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true, | ||
attribute: 'payment-method', | ||
}) paymentMethod = null; | ||
/** | ||
* Stripe Source | ||
* @type {stripe.Source} | ||
* @readonly | ||
*/ | ||
@property({ type: Object, notify: true, readOnly: true }) source = null; | ||
/** | ||
* Stripe Token | ||
* @type {stripe.Token} | ||
* @readonly | ||
*/ | ||
@property({ type: Object, notify: true, readOnly: true }) token = null; | ||
/* SETTINGS */ | ||
/** | ||
* If set, when Stripe returns the payment info (PaymentMethod, Source, or Token), | ||
* the element will POST JSON data to this URL with an object containing | ||
* a key equal to the value of the `generate` property. | ||
* @example | ||
* ```html | ||
* <stripe-elements | ||
* publishable-key="pk_test_XXXXXXXXXXXXX" | ||
* generate="token" | ||
* action="/payment" | ||
* ></stripe-elements> | ||
* ``` | ||
* will POST to `/payment` with JSON body `{ "token": { ... } }` | ||
* ```js | ||
* stripeElements.submit(); | ||
* ``` | ||
* @type {string} | ||
*/ | ||
@property({ type: String }) action; | ||
/** | ||
* The `client_secret` part of a Stripe `PaymentIntent` | ||
* @type {string} | ||
*/ | ||
@property({ type: String, attribute: 'client-secret' }) clientSecret; | ||
/** | ||
* Type of payment representation to generate. | ||
* @type {'payment-method'|'source'|'token'} | ||
* @required | ||
*/ | ||
@property({ type: String }) generate = 'source'; | ||
/** | ||
* Stripe Publishable Key. EG. `pk_test_XXXXXXXXXXXXXXXXXXXXXXXX` | ||
* @type {string} | ||
*/ | ||
@property({ | ||
type: String, | ||
attribute: 'publishable-key', | ||
reflect: true, | ||
notify: true, | ||
}) publishableKey; | ||
/** Whether to display the error message */ | ||
@property({ type: Boolean, attribute: 'show-error', reflect: true }) showError = false; | ||
/* READ-ONLY FIELDS */ | ||
/** | ||
* Stripe element instance | ||
* @type {stripe.elements.Element} | ||
* @readonly | ||
*/ | ||
@property({ type: Object, readOnly: true }) element = null; | ||
/** | ||
* Stripe Elements instance | ||
* @type {stripe.elements.Elements} | ||
* @readonly | ||
*/ | ||
@property({ type: Object, readOnly: true }) elements = null; | ||
/** | ||
* Stripe or validation error | ||
* @type {Error|stripe.Error} | ||
* @readonly | ||
*/ | ||
@property({ type: Object, notify: true, readOnly: true, reflect: true, converter: { | ||
toAttribute: error => !error ? null : error.originalMessage || error.message || '', | ||
} }) error = null; | ||
/** | ||
* If the element is focused. | ||
* @type {boolean} | ||
* @readonly | ||
*/ | ||
@property({ type: Boolean, reflect: true, notify: true, readOnly: true }) focused = false; | ||
/** | ||
* Whether the stripe element is ready to receive focus. | ||
* @type {boolean} | ||
* @readonly | ||
*/ | ||
@property({ type: Boolean, reflect: true, notify: true, readOnly: true }) ready = false; | ||
/** | ||
* Stripe instance | ||
* @type {stripe.Stripe} | ||
* @readonly | ||
*/ | ||
@property({ type: Object, readOnly: true }) stripe = null; | ||
// DEPRECATED | ||
/** | ||
* Whether the element has an error | ||
* **DEPRECATED**. Will be removed in a future version. Use `error` instead | ||
* @type {boolean} | ||
* @readonly | ||
* @deprecated | ||
*/ | ||
@property({ | ||
type: Boolean, | ||
attribute: 'has-error', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true, | ||
}) hasError = false; | ||
/** | ||
* Whether the stripe element is ready to receive focus. | ||
* **DEPRECATED**. Will be removed in a future version. use `ready` instead. | ||
* @deprecated | ||
* @type {boolean} | ||
*/ | ||
@property({ | ||
type: Boolean, | ||
attribute: 'stripe-ready', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true, | ||
}) stripeReady = false; | ||
/* PRIVATE FIELDS */ | ||
/** | ||
* Breadcrumbs back up to the document. | ||
* @type {Node[]} | ||
* @private | ||
*/ | ||
shadowHosts = []; | ||
/** | ||
* Stripe.js mount point element. Due to limitations in the Stripe.js library, this element must be connected to the document. | ||
* @type {Element} | ||
* @protected | ||
*/ | ||
get stripeMount() { return document.getElementById(this.stripeMountId); } | ||
/** | ||
* Stripe.js mount point element id. Due to limitations in the Stripe.js library, this element must be connected to the document. | ||
* @type {string} | ||
* @protected | ||
*/ | ||
stripeMountId; | ||
/** | ||
* Name for breadcrumb slots. Derived from tagName | ||
* @protected | ||
* @type {string} | ||
*/ | ||
slotName; | ||
/* LIFECYCLE */ | ||
/** @inheritdoc */ | ||
render() { | ||
const { error, showError, slotName } = this; | ||
const errorMessage = error?.originalMessage || error?.message; | ||
return html` | ||
constructor() { | ||
super(); | ||
/** | ||
* Type of payment representation to generate. | ||
*/ | ||
this.generate = 'source'; | ||
/** Whether to display the error message */ | ||
this.showError = false; | ||
/* READ-ONLY FIELDS */ | ||
/* PAYMENT REPRESENTATIONS */ | ||
/** | ||
* Stripe PaymentMethod | ||
*/ | ||
this.paymentMethod = null; | ||
/** | ||
* Stripe Source | ||
*/ | ||
this.source = null; | ||
/** | ||
* Stripe Token | ||
*/ | ||
this.token = null; | ||
/** | ||
* Stripe element instance | ||
*/ | ||
this.element = null; | ||
/** | ||
* Stripe Elements instance | ||
*/ | ||
this.elements = null; | ||
/** | ||
* Stripe or validation error | ||
*/ | ||
this.error = null; | ||
/** | ||
* If the element is focused. | ||
*/ | ||
this.focused = false; | ||
/** | ||
* Whether the stripe element is ready to receive focus. | ||
*/ | ||
this.ready = false; | ||
/** | ||
* Stripe instance | ||
*/ | ||
this.stripe = null; | ||
// DEPRECATED | ||
/** | ||
* Whether the element has an error | ||
* **DEPRECATED**. Will be removed in a future version. Use `error` instead | ||
* @deprecated | ||
*/ | ||
this.hasError = false; | ||
/** | ||
* Whether the stripe element is ready to receive focus. | ||
* **DEPRECATED**. Will be removed in a future version. use `ready` instead. | ||
* @deprecated | ||
*/ | ||
this.stripeReady = false; | ||
/* PRIVATE FIELDS */ | ||
/** | ||
* Breadcrumbs back up to the document. | ||
*/ | ||
this.shadowHosts = []; | ||
const slotName = this.tagName === 'STRIPE-ELEMENTS' ? 'stripe-elements-slot' | ||
: this.tagName === 'STRIPE-PAYMENT-REQUEST' ? 'stripe-payment-request-slot' | ||
/* istanbul ignore next */ | ||
: null; | ||
this.slotName = slotName; | ||
} | ||
/** | ||
* Stripe.js mount point element. Due to limitations in the Stripe.js library, this element must be connected to the document. | ||
*/ | ||
get stripeMount() { return document.getElementById(this.stripeMountId); } | ||
/* LIFECYCLE */ | ||
/** @inheritdoc */ | ||
render() { | ||
const { error, showError, slotName } = this; | ||
const errorMessage = isStripeElementsError(error) ? error.originalMessage : error === null || error === void 0 ? void 0 : error.message; | ||
return html ` | ||
<div id="stripe" part="stripe"> | ||
@@ -281,312 +148,389 @@ <slot id="stripe-slot" name="${slotName}"></slot> | ||
`; | ||
} | ||
constructor() { | ||
super(); | ||
this.slotName = `${this.tagName.toLowerCase()}-slot`; | ||
} | ||
/** @inheritdoc */ | ||
firstUpdated() { | ||
this.destroyMountPoints(); | ||
this.initMountPoints(); | ||
} | ||
/** @inheritdoc */ | ||
updated(changed) { | ||
super.updated?.(changed); | ||
if (changed.has('error')) this.errorChanged(); | ||
if (changed.has('publishableKey')) this.init(); | ||
[...changed.keys()].forEach(this.representationChanged); | ||
} | ||
/** @inheritdoc */ | ||
async disconnectedCallback() { | ||
super.disconnectedCallback(); | ||
await this.unmount(); | ||
this.destroyMountPoints(); | ||
} | ||
/* PUBLIC API */ | ||
/** | ||
* Resets and clears the stripe element. | ||
*/ | ||
reset() { | ||
this.element?.clear?.(); | ||
this.resetRepresentations(); | ||
this.set({ error: null }); | ||
} | ||
/** Blurs the element. */ | ||
blur() { | ||
this.element?.blur(); | ||
} | ||
/** Focuses the element. */ | ||
focus() { | ||
this.element?.focus(); | ||
} | ||
/* PRIVATE API */ | ||
/** | ||
* Creates a new StripeElementsError | ||
* @param {string} message | ||
* @return {StripeElementsError} | ||
* @private | ||
*/ | ||
createError(message) { | ||
return new StripeElementsError(this.constructor.is, message); | ||
} | ||
/** | ||
* Clears the Payment Representation and fires an error event | ||
* @private | ||
*/ | ||
async errorChanged() { | ||
// DEPRECATED | ||
const hasError = !!this.error; | ||
await this.set({ hasError }); | ||
// END DEPRECATED | ||
this.resetRepresentations(); | ||
this.fireError(this.error); | ||
} | ||
/** | ||
* Fires an event. | ||
* @param {string} type event type | ||
* @param {any} detail detail value | ||
* @param {EventInit} [opts={}] | ||
* @private | ||
*/ | ||
fire(type, detail, opts = {}) { | ||
this.dispatchEvent(new CustomEvent(type, { detail, ...opts })); | ||
} | ||
/** | ||
* Fires an Error Event | ||
* @param {Error} error | ||
* @private | ||
*/ | ||
fireError(error) { | ||
this.dispatchEvent(new ErrorEvent('error', { error })); | ||
// DEPRECATED | ||
this.dispatchEvent(new ErrorEvent('stripe-error', { bubbles: true, error })); | ||
} | ||
/** | ||
* Gets a CSS Custom Property value, respecting ShadyCSS. | ||
* @param {string} propertyName CSS Custom Property | ||
* @param {CSSStyleDeclaration} [precomputedStyle] pre-computed style declaration | ||
* @return {any} | ||
* @private | ||
*/ | ||
getCSSCustomPropertyValue(propertyName, precomputedStyle) { | ||
if (window.ShadyCSS) return ShadyCSS.getComputedStyleValue(this, propertyName); | ||
else return precomputedStyle.getPropertyValue(propertyName); | ||
} | ||
/** | ||
* Sets the token or error from the response. | ||
* @param {PaymentResponse} response Stripe Response | ||
* @return {PaymentResponse} | ||
* @private | ||
*/ | ||
@bound async handleResponse(response) { | ||
const { error = null, paymentMethod = null, source = null, token = null } = response; | ||
await this.set({ error, paymentMethod, source, token }); | ||
if (error) throw error; | ||
else return response; | ||
} | ||
/** | ||
* Removes all mount points from the DOM | ||
* @private | ||
*/ | ||
destroyMountPoints() { | ||
this.shadowHosts.forEach(removeAllMounts(this.slotName)); | ||
if (this.stripeMount) this.stripeMount.remove(); | ||
} | ||
/** | ||
* Reinitializes Stripe and mounts the element. | ||
* @private | ||
*/ | ||
async init() { | ||
await this.unmount(); | ||
await this.initStripe(); | ||
await this.initElement(); | ||
this.initElementListeners(); | ||
this.destroyMountPoints(); | ||
this.initMountPoints(); | ||
this.mount(); | ||
} | ||
/** | ||
* Adds `ready`, `focus`, and `blur` listeners to the Stripe Element | ||
* @private | ||
*/ | ||
initElementListeners() { | ||
if (!this.element) return; | ||
this.element.addEventListener('ready', this.onReady); | ||
this.element.addEventListener('focus', this.onFocus); | ||
this.element.addEventListener('blur', this.onBlur); | ||
} | ||
/** | ||
* Creates mount points for the Stripe Element | ||
* @private | ||
*/ | ||
initMountPoints() { | ||
this.stripeMountId = generateRandomMountElementId(this.tagName); | ||
if (window.ShadyDOM) appendTemplate(mountPointTemplate(this), this); | ||
else this.initShadowMountPoints(); | ||
} | ||
/** | ||
* Prepares to mount Stripe Elements in light DOM. | ||
* @private | ||
*/ | ||
initShadowMountPoints() { | ||
// trace each shadow boundary between us and the document | ||
let host = this; | ||
this.shadowHosts = [this]; | ||
while (host = host.getRootNode().host) this.shadowHosts.push(host); // eslint-disable-line prefer-destructuring, no-loops/no-loops | ||
const { shadowHosts, slotName } = this; | ||
// Prepare the shallowest breadcrumb slot at document level | ||
const hosts = [...shadowHosts]; | ||
const root = hosts.pop(); | ||
if (!root.querySelector(`[slot="${slotName}"]`)) { | ||
const div = document.createElement('div'); | ||
div.slot = slotName; | ||
root.appendChild(div); | ||
} | ||
const container = root.querySelector(`[slot="${slotName}"]`); | ||
// Render the form to the document, so that Stripe.js can mount | ||
appendTemplate(mountPointTemplate(this), container); | ||
// Append breadcrumb slots to each shadowroot in turn, | ||
// from the document down to the <stripe-elements> instance. | ||
hosts.forEach(appendTemplate(slotTemplate(slotName))); | ||
} | ||
/** | ||
* Initializes Stripe and elements. | ||
* @private | ||
*/ | ||
async initStripe() { | ||
const { publishableKey } = this; | ||
const stripe = (window.Stripe && publishableKey) ? Stripe(publishableKey) : null; | ||
const elements = stripe && stripe.elements(); | ||
const error = stripe ? null : this.createError('requires Stripe.js to be loaded first.'); | ||
if (error) console.warn(error.message); // eslint-disable-line no-console | ||
await this.set({ elements, error, stripe }); | ||
} | ||
/** | ||
* Mounts the Stripe Element | ||
* @private | ||
*/ | ||
mount() { | ||
/** @inheritdoc */ | ||
firstUpdated() { | ||
this.destroyMountPoints(); | ||
this.initMountPoints(); | ||
} | ||
/** @inheritdoc */ | ||
updated(changed) { | ||
var _a; | ||
/* istanbul ignore next */ | ||
(_a = super.updated) === null || _a === void 0 ? void 0 : _a.call(this, changed); | ||
if (changed.has('error')) | ||
this.errorChanged(); | ||
if (changed.has('publishableKey')) | ||
this.init(); | ||
[...changed.keys()].forEach(this.representationChanged); | ||
} | ||
/** @inheritdoc */ | ||
async disconnectedCallback() { | ||
var _a; | ||
super.disconnectedCallback(); | ||
/* istanbul ignore next */ | ||
await ((_a = this.unmount) === null || _a === void 0 ? void 0 : _a.call(this)); | ||
this.destroyMountPoints(); | ||
} | ||
/* PUBLIC API */ | ||
/** | ||
* Resets and clears the stripe element. | ||
*/ | ||
reset() { | ||
var _a, _b; | ||
/* istanbul ignore next */ | ||
(_b = (_a = this.element) === null || _a === void 0 ? void 0 : _a.clear) === null || _b === void 0 ? void 0 : _b.call(_a); | ||
this.resetRepresentations(); | ||
this.setReadOnlyProperties({ error: null }); | ||
} | ||
/** Blurs the element. */ | ||
blur() { | ||
var _a; | ||
/* istanbul ignore next */ | ||
(_a = this.element) === null || _a === void 0 ? void 0 : _a.blur(); | ||
} | ||
/** Focuses the element. */ | ||
focus() { | ||
var _a; | ||
/* istanbul ignore next */ | ||
(_a = this.element) === null || _a === void 0 ? void 0 : _a.focus(); | ||
} | ||
/* PRIVATE API */ | ||
/** | ||
* Creates a new StripeElementsError | ||
*/ | ||
createError(message) { | ||
return new StripeElementsError(this.constructor.is, message); | ||
} | ||
/** | ||
* Clears the Payment Representation and fires an error event | ||
*/ | ||
async errorChanged() { | ||
// DEPRECATED | ||
const hasError = !!this.error; | ||
await this.setReadOnlyProperties({ hasError }); | ||
// END DEPRECATED | ||
this.resetRepresentations(); | ||
this.fireError(this.error); | ||
} | ||
/** | ||
* Fires an event. | ||
* @param type event type | ||
* @param detail detail value | ||
* @param [opts={}] | ||
*/ | ||
fire(type, detail, opts) { | ||
this.dispatchEvent(new CustomEvent(type, { detail, ...opts })); | ||
} | ||
/** | ||
* Fires an Error Event | ||
*/ | ||
fireError(error) { | ||
this.dispatchEvent(new ErrorEvent('error', { error })); | ||
// DEPRECATED | ||
this.dispatchEvent(new ErrorEvent('stripe-error', { bubbles: true, error })); | ||
} | ||
/** | ||
* Gets a CSS Custom Property value, respecting ShadyCSS. | ||
* @param propertyName CSS Custom Property | ||
* @param precomputedStyle pre-computed style declaration | ||
*/ | ||
getCSSCustomPropertyValue(propertyName, precomputedStyle) { | ||
if (window.ShadyCSS) | ||
return window.ShadyCSS.getComputedStyleValue(this, propertyName); | ||
else | ||
return precomputedStyle.getPropertyValue(propertyName); | ||
} | ||
/** | ||
* Sets the token or error from the response. | ||
* @param response Stripe Response | ||
* @return | ||
*/ | ||
async handleResponse(response) { | ||
const { error = null, paymentMethod = null, source = null, token = null } = { ...response }; | ||
await this.setReadOnlyProperties({ error, paymentMethod, source, token }); | ||
if (error) | ||
throw error; | ||
else | ||
return response; | ||
} | ||
/** | ||
* Removes all mount points from the DOM | ||
*/ | ||
destroyMountPoints() { | ||
this.shadowHosts.forEach(removeAllMounts(this.slotName)); | ||
if (this.stripeMount) | ||
this.stripeMount.remove(); | ||
} | ||
/** @abstract */ | ||
/* istanbul ignore next */ | ||
if (!this.stripeMount) throw this.createError('Stripe Mount missing'); | ||
this.element?.mount(this.stripeMount); | ||
} | ||
/** | ||
* Unmounts and nullifies the card. | ||
* @private | ||
*/ | ||
async unmount() { | ||
this.element?.unmount(); | ||
await this.set({ element: null }); | ||
} | ||
/** | ||
* @param {StripeFocusEvent} event | ||
* @private | ||
*/ | ||
@bound async onBlur() { | ||
await this.set({ focused: false }); | ||
} | ||
/** | ||
* @param {StripeFocusEvent} event | ||
* @private | ||
*/ | ||
@bound async onFocus() { | ||
await this.set({ focused: true }); | ||
} | ||
/** | ||
* Sets the `ready` property when the stripe element is ready to receive focus. | ||
* @param {Event} event | ||
* @private | ||
*/ | ||
@bound async onReady(event) { | ||
await this.set({ ready: true, stripeReady: true }); | ||
this.fire('ready', event); | ||
// DEPRECATED | ||
this.fire('stripe-ready', event); | ||
} | ||
/** | ||
* POSTs the payment info represenation to the endpoint at `/action` | ||
* @resolves {void} | ||
* @private | ||
*/ | ||
async postRepresentation() { | ||
const onError = error => this.set({ error }); | ||
const onSuccess = success => { | ||
this.fire('success', success); | ||
// DEPRECATED | ||
this.fire('stripe-payment-success', success); | ||
}; | ||
const token = this.token || undefined; | ||
const source = this.source || undefined; | ||
const paymentMethod = this.paymentMethod || undefined; | ||
const body = JSON.stringify({ token, source, paymentMethod }); | ||
const headers = { 'Content-Type': 'application/json' }; | ||
const method = 'POST'; | ||
return fetch(this.action, { body, headers, method }) | ||
.then(throwBadResponse) | ||
.then(onSuccess) | ||
.catch(onError); | ||
} | ||
/** | ||
* @param {string} name | ||
* @private | ||
*/ | ||
@bound representationChanged(name) { | ||
if (!isRepresentation(name)) return; | ||
const value = this[name]; | ||
/* istanbul ignore if */ | ||
if (!value) return; | ||
// DEPRECATED | ||
this.fire(`stripe-${dash(name)}`, value); | ||
this.fire(`${dash(name)}`, value); | ||
if (this.action) this.postRepresentation(); | ||
} | ||
/** | ||
* Resets the Payment Representations | ||
* @private | ||
*/ | ||
resetRepresentations() { | ||
this.set({ | ||
paymentMethod: null, | ||
token: null, | ||
source: null, | ||
}); | ||
} | ||
initElement() { | ||
'abstract'; | ||
} | ||
/** | ||
* Reinitializes Stripe and mounts the element. | ||
*/ | ||
async init() { | ||
await this.unmount(); | ||
await this.initStripe(); | ||
await this.initElement(); | ||
this.initElementListeners(); | ||
this.destroyMountPoints(); | ||
this.initMountPoints(); | ||
this.mount(); | ||
} | ||
/** | ||
* Adds `ready`, `focus`, and `blur` listeners to the Stripe Element | ||
*/ | ||
initElementListeners() { | ||
if (!this.element) | ||
return; | ||
this.element.addEventListener('ready', this.onReady); | ||
this.element.addEventListener('focus', this.onFocus); | ||
this.element.addEventListener('blur', this.onBlur); | ||
} | ||
/** | ||
* Creates mount points for the Stripe Element | ||
*/ | ||
initMountPoints() { | ||
this.stripeMountId = generateRandomMountElementId(this.tagName); | ||
if (window.ShadyDOM) | ||
appendTemplate(this.mountPointTemplate(), this); | ||
else | ||
this.initShadowMountPoints(); | ||
} | ||
/** | ||
* Prepares to mount Stripe Elements in light DOM. | ||
*/ | ||
initShadowMountPoints() { | ||
// trace each shadow boundary between us and the document | ||
let host = this; | ||
this.shadowHosts = [this]; | ||
while (host = host.getRootNode().host) // eslint-disable-line no-loops/no-loops, prefer-destructuring | ||
this.shadowHosts.push(host); | ||
const { shadowHosts, slotName } = this; | ||
// Prepare the shallowest breadcrumb slot at document level | ||
const hosts = [...shadowHosts]; | ||
const root = hosts.pop(); | ||
if (!root.querySelector(`[slot="${slotName}"]`)) { | ||
const div = document.createElement('div'); | ||
div.slot = slotName; | ||
root.appendChild(div); | ||
} | ||
const container = root.querySelector(`[slot="${slotName}"]`); | ||
// Render the form to the document, so that Stripe.js can mount | ||
appendTemplate(this.mountPointTemplate(), container); | ||
// Append breadcrumb slots to each shadowroot in turn, | ||
// from the document down to the <stripe-elements> instance. | ||
hosts.forEach(appendTemplate(slotTemplate(slotName))); | ||
} | ||
/** | ||
* Initializes Stripe and elements. | ||
*/ | ||
async initStripe() { | ||
const { publishableKey } = this; | ||
const stripe = (window.Stripe && publishableKey) ? Stripe(publishableKey) : null; | ||
const elements = stripe && stripe.elements(); | ||
const error = stripe ? null : this.createError('requires Stripe.js to be loaded first.'); | ||
if (error) | ||
console.warn(error.message); // eslint-disable-line no-console | ||
await this.setReadOnlyProperties({ elements, error, stripe }); | ||
} | ||
/** | ||
* Mounts the Stripe Element | ||
*/ | ||
mount() { | ||
var _a; | ||
/* istanbul ignore next */ | ||
if (!this.stripeMount) | ||
throw this.createError('Stripe Mount missing'); | ||
(_a = this.element) === null || _a === void 0 ? void 0 : _a.mount(this.stripeMount); | ||
} | ||
mountPointTemplate() { | ||
const { stripeMountId, tagName } = this; | ||
return html `<div id="${ifDefined(stripeMountId)}" class="${tagName.toLowerCase()}-mount"></div>`; | ||
} | ||
/** | ||
* Unmounts and nullifies the card. | ||
*/ | ||
async unmount() { | ||
var _a, _b; | ||
(_b = (_a = this.element) === null || _a === void 0 ? void 0 : _a.unmount) === null || _b === void 0 ? void 0 : _b.call(_a); | ||
await this.setReadOnlyProperties({ element: null }); | ||
} | ||
/** | ||
* Updates element state when Stripe Element is blurred. | ||
*/ | ||
async onBlur() { | ||
await this.setReadOnlyProperties({ focused: false }); | ||
} | ||
/** | ||
* @param {StripeFocusEvent} event | ||
* @private | ||
*/ | ||
async onFocus() { | ||
await this.setReadOnlyProperties({ focused: true }); | ||
} | ||
/** | ||
* Sets the `ready` property when the stripe element is ready to receive focus. | ||
*/ | ||
async onReady(event) { | ||
await this.setReadOnlyProperties({ ready: true, stripeReady: true }); | ||
this.fire('ready', event); | ||
// DEPRECATED | ||
this.fire('stripe-ready', event); | ||
} | ||
/** | ||
* POSTs the payment info represenation to the endpoint at `/action` | ||
*/ | ||
async postRepresentation() { | ||
const onError = (error) => this.setReadOnlyProperties({ error }); | ||
const onSuccess = (success) => { | ||
this.fire('success', success); | ||
// DEPRECATED | ||
this.fire('stripe-payment-success', success); | ||
}; | ||
const token = this.token || undefined; | ||
const source = this.source || undefined; | ||
const paymentMethod = this.paymentMethod || undefined; | ||
const body = JSON.stringify({ token, source, paymentMethod }); | ||
const headers = { 'Content-Type': 'application/json' }; | ||
const method = 'POST'; | ||
return fetch(this.action, { body, headers, method }) | ||
.then(throwBadResponse) | ||
.then(onSuccess) | ||
.catch(onError); | ||
} | ||
/** | ||
* Updates the state and fires events when the token, source, or payment method is updated. | ||
*/ | ||
representationChanged(name) { | ||
if (!isRepresentation(name)) | ||
return; | ||
const value = this[name]; | ||
/* istanbul ignore if */ | ||
if (!value) | ||
return; | ||
// DEPRECATED | ||
this.fire(`stripe-${dash(name)}`, value); | ||
this.fire(`${dash(name)}`, value); | ||
if (this.action) | ||
this.postRepresentation(); | ||
} | ||
/** | ||
* Resets the Payment Representations | ||
*/ | ||
resetRepresentations() { | ||
this.setReadOnlyProperties({ | ||
paymentMethod: null, | ||
token: null, | ||
source: null, | ||
}); | ||
} | ||
} | ||
/** @typedef {stripe.PaymentIntentResponse|stripe.PaymentMethodResponse|stripe.SetupIntentResponse|stripe.TokenResponse|stripe.SourceResponse} PaymentResponse */ | ||
/** @typedef {{ owner: stripe.OwnerData }} SourceData */ | ||
/** @typedef {{ elementType: stripe.elements.elementsType }} StripeFocusEvent */ | ||
__decorate([ | ||
property({ type: String }), | ||
__metadata("design:type", String) | ||
], StripeBase.prototype, "action", void 0); | ||
__decorate([ | ||
property({ type: String, attribute: 'client-secret' }), | ||
__metadata("design:type", String) | ||
], StripeBase.prototype, "clientSecret", void 0); | ||
__decorate([ | ||
property({ type: String }), | ||
__metadata("design:type", String) | ||
], StripeBase.prototype, "generate", void 0); | ||
__decorate([ | ||
property({ type: String, attribute: 'publishable-key', reflect: true, notify: true }), | ||
__metadata("design:type", String) | ||
], StripeBase.prototype, "publishableKey", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'show-error', reflect: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "showError", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true, attribute: 'payment-method' }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "paymentMethod", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "source", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "token", void 0); | ||
__decorate([ | ||
property({ type: Object, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "element", void 0); | ||
__decorate([ | ||
property({ type: Object, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "elements", void 0); | ||
__decorate([ | ||
property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true, | ||
reflect: true, | ||
converter: errorConverter, | ||
}), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "error", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "focused", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "ready", void 0); | ||
__decorate([ | ||
property({ type: Object, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "stripe", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'has-error', reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "hasError", void 0); | ||
__decorate([ | ||
property({ | ||
type: Boolean, | ||
attribute: 'stripe-ready', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true, | ||
}), | ||
__metadata("design:type", Object) | ||
], StripeBase.prototype, "stripeReady", void 0); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeBase.prototype, "handleResponse", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", []), | ||
__metadata("design:returntype", Promise) | ||
], StripeBase.prototype, "onBlur", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", []), | ||
__metadata("design:returntype", Promise) | ||
], StripeBase.prototype, "onFocus", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeBase.prototype, "onReady", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [String]), | ||
__metadata("design:returntype", void 0) | ||
], StripeBase.prototype, "representationChanged", null); | ||
//# sourceMappingURL=StripeBase.js.map |
@@ -1,11 +0,7 @@ | ||
import _toArray from '@babel/runtime/helpers/esm/toArray'; | ||
import _getPrototypeOf from '@babel/runtime/helpers/esm/getPrototypeOf'; | ||
import _get from '@babel/runtime/helpers/esm/get'; | ||
import { LitNotify } from '@morbidick/lit-element-notify'; | ||
import { css, property } from 'lit-element'; | ||
import { css, property, customElement } from 'lit-element'; | ||
import { S as StripeBase, s as sharedStyles, b as bound, d as dash } from './shared.js'; | ||
import '@morbidick/lit-element-notify'; | ||
import 'lit-html/directives/if-defined'; | ||
import '@babel/runtime/helpers/esm/defineProperty'; | ||
import 'lit-html'; | ||
import '@typed/curry'; | ||
import 'lit-html'; | ||
import '@lavadrop/kebab-case'; | ||
@@ -15,24 +11,17 @@ import '@lavadrop/camel-case'; | ||
/* eslint-disable no-invalid-this */ | ||
function wrap(f) { | ||
return wrapped => { | ||
const { | ||
descriptor | ||
} = wrapped; | ||
const original = descriptor.value; | ||
descriptor.value = f(original); | ||
return { ...wrapped, | ||
descriptor | ||
return (_target, _property, descriptor) => { | ||
const original = descriptor.value; | ||
descriptor.value = f(original); | ||
return descriptor; | ||
}; | ||
}; | ||
} | ||
const stripeMethod = wrap(function (f) { | ||
const { | ||
name | ||
} = f; | ||
return async function (...args) { | ||
if (!this.stripe) throw new Error(`<${this.constructor.is}>: Stripe must be initialized before calling ${name}.`); | ||
return f.call(this, ...args).then(this.handleResponse); | ||
}; | ||
const { name } = f; | ||
return async function (...args) { | ||
if (!this.stripe) | ||
throw new Error(`<${this.constructor.is}>: Stripe must be initialized before calling ${name}.`); | ||
return f.call(this, ...args) | ||
.then(this.handleResponse); | ||
}; | ||
}); | ||
@@ -65,22 +54,25 @@ | ||
function _decorate(decorators, factory, superClass, mixins) { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); } | ||
function _getDecoratorsApi() { _getDecoratorsApi = function () { return api; }; var api = { elementsDefinitionOrder: [["method"], ["field"]], initializeInstanceElements: function (O, elements) { ["method", "field"].forEach(function (kind) { elements.forEach(function (element) { if (element.kind === kind && element.placement === "own") { this.defineClassElement(O, element); } }, this); }, this); }, initializeClassElements: function (F, elements) { var proto = F.prototype; ["method", "field"].forEach(function (kind) { elements.forEach(function (element) { var placement = element.placement; if (element.kind === kind && (placement === "static" || placement === "prototype")) { var receiver = placement === "static" ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, defineClassElement: function (receiver, element) { var descriptor = element.descriptor; if (element.kind === "field") { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver) }; } Object.defineProperty(receiver, element.key, descriptor); }, decorateClass: function (elements, decorators) { var newElements = []; var finishers = []; var placements = { static: [], prototype: [], own: [] }; elements.forEach(function (element) { this.addElementPlacement(element, placements); }, this); elements.forEach(function (element) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras = this.decorateElement(element, placements); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers }; } var result = this.decorateConstructor(newElements, decorators); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, addElementPlacement: function (element, placements, silent) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError("Duplicated element (" + element.key + ")"); } keys.push(element.key); }, decorateElement: function (element, placements) { var extras = []; var finishers = []; for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject = this.fromElementDescriptor(element); var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras }; }, decorateConstructor: function (elements, decorators) { var finishers = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj = this.fromClassDescriptor(elements); var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { throw new TypeError("Duplicated element (" + elements[j].key + ")"); } } } } } return { elements: elements, finishers: finishers }; }, fromElementDescriptor: function (element) { var obj = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === "field") obj.initializer = element.initializer; return obj; }, toElementDescriptors: function (elementObjects) { if (elementObjects === undefined) return; return _toArray(elementObjects).map(function (elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, "finisher", "An element descriptor"); this.disallowProperty(elementObject, "extras", "An element descriptor"); return element; }, this); }, toElementDescriptor: function (elementObject) { var kind = String(elementObject.kind); if (kind !== "method" && kind !== "field") { throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); } var key = _toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if (placement !== "static" && placement !== "prototype" && placement !== "own") { throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); } var descriptor = elementObject.descriptor; this.disallowProperty(elementObject, "elements", "An element descriptor"); var element = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor) }; if (kind !== "field") { this.disallowProperty(elementObject, "initializer", "A method descriptor"); } else { this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function (elementObject) { var element = this.toElementDescriptor(elementObject); var finisher = _optionalCallableProperty(elementObject, "finisher"); var extras = this.toElementDescriptors(elementObject.extras); return { element: element, finisher: finisher, extras: extras }; }, fromClassDescriptor: function (elements) { var obj = { kind: "class", elements: elements.map(this.fromElementDescriptor, this) }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, toClassDescriptor: function (obj) { var kind = String(obj.kind); if (kind !== "class") { throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); } this.disallowProperty(obj, "key", "A class descriptor"); this.disallowProperty(obj, "placement", "A class descriptor"); this.disallowProperty(obj, "descriptor", "A class descriptor"); this.disallowProperty(obj, "initializer", "A class descriptor"); this.disallowProperty(obj, "extras", "A class descriptor"); var finisher = _optionalCallableProperty(obj, "finisher"); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher }; }, runClassFinishers: function (constructor, finishers) { for (var i = 0; i < finishers.length; i++) { var newConstructor = (0, finishers[i])(constructor); if (newConstructor !== undefined) { if (typeof newConstructor !== "function") { throw new TypeError("Finishers must return a constructor."); } constructor = newConstructor; } } return constructor; }, disallowProperty: function (obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + " property."); } } }; return api; } | ||
function _createElementDescriptor(def) { var key = _toPropertyKey(def.key); var descriptor; if (def.kind === "method") { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false }; } else if (def.kind === "get") { descriptor = { get: def.value, configurable: true, enumerable: false }; } else if (def.kind === "set") { descriptor = { set: def.value, configurable: true, enumerable: false }; } else if (def.kind === "field") { descriptor = { configurable: true, writable: true, enumerable: true }; } var element = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor }; if (def.decorators) element.decorators = def.decorators; if (def.kind === "field") element.initializer = def.value; return element; } | ||
function _coalesceGetterSetter(element, other) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } } | ||
function _coalesceClassElements(elements) { var newElements = []; var isSameElement = function (other) { return other.kind === "method" && other.key === element.key && other.placement === element.placement; }; for (var i = 0; i < elements.length; i++) { var element = elements[i]; var other; if (element.kind === "method" && (other = newElements.find(isSameElement))) { if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; } | ||
function _hasDecorators(element) { return element.decorators && element.decorators.length; } | ||
function _isDataDescriptor(desc) { return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); } | ||
function _optionalCallableProperty(obj, name) { var value = obj[name]; if (value !== undefined && typeof value !== "function") { throw new TypeError("Expected '" + name + "' to be a function"); } return value; } | ||
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } | ||
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } | ||
const allowedStyles = ['color', 'fontFamily', 'fontSize', 'fontStyle', 'fontSmoothing', 'fontVariant', 'iconColor', 'lineHeight', 'letterSpacing', 'textDecoration', 'textShadow', 'textTransform']; | ||
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { | ||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; | ||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); | ||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; | ||
return c > 3 && r && Object.defineProperty(target, key, r), r; | ||
}; | ||
var __metadata = (undefined && undefined.__metadata) || function (k, v) { | ||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); | ||
}; | ||
const allowedStyles = [ | ||
'color', | ||
'fontFamily', | ||
'fontSize', | ||
'fontStyle', | ||
'fontSmoothing', | ||
'fontVariant', | ||
'iconColor', | ||
'lineHeight', | ||
'letterSpacing', | ||
'textDecoration', | ||
'textShadow', | ||
'textTransform', | ||
]; | ||
/** | ||
@@ -149,6 +141,6 @@ * [Stripe.js v3 Card Elements](https://stripe.com/docs/elements), but it's a Web Component! | ||
* | ||
* @cssprop [--stripe-elements-border-radius] - border radius of the element container. Default `4px` | ||
* @cssprop [--stripe-elements-border] - border property of the element container. Default `1px solid transparent` | ||
* @cssprop [--stripe-elements-box-shadow] - box shadow for the element container. Default `0 1px 3px 0 #e6ebf1` | ||
* @cssprop [--stripe-elements-transition] - transition property for the element container. Default `box-shadow 150ms ease` | ||
* @cssprop [--stripe-elements-border-radius=`4px`] - border radius of the element container | ||
* @cssprop [--stripe-elements-border=`1px solid transparent`] - border property of the element container | ||
* @cssprop [--stripe-elements-box-shadow=`0 1px 3px 0 #e6ebf1`] - box shadow for the element container | ||
* @cssprop [--stripe-elements-transition=`box-shadow 150ms ease`] - transition property for the element container | ||
* | ||
@@ -208,523 +200,280 @@ * @cssprop [--stripe-elements-base-color] - `color` property for the element in its base state | ||
*/ | ||
let StripeElements = _decorate(null, function (_initialize, _LitNotify) { | ||
class StripeElements extends _LitNotify { | ||
constructor(...args) { | ||
super(...args); | ||
_initialize(this); | ||
let StripeElements = class StripeElements extends StripeBase { | ||
constructor() { | ||
super(...arguments); | ||
/* PUBLIC FIELDS */ | ||
/** | ||
* Whether to hide icons in the Stripe form. | ||
*/ | ||
this.hideIcon = false; | ||
/** | ||
* Whether or not to hide the postal code field. | ||
* Useful when you gather shipping info elsewhere. | ||
*/ | ||
this.hidePostalCode = false; | ||
/** | ||
* Stripe icon style. | ||
*/ | ||
this.iconStyle = 'default'; | ||
/** | ||
* Prefilled values for form. | ||
* @example { postalCode: '90210' } | ||
*/ | ||
this.value = {}; | ||
/* READ ONLY PROPERTIES */ | ||
/** | ||
* The card brand detected by Stripe | ||
*/ | ||
this.brand = null; | ||
/** | ||
* Whether the form is complete. | ||
*/ | ||
this.complete = false; | ||
/** | ||
* If the form is empty. | ||
*/ | ||
this.empty = true; | ||
/** | ||
* Whether the form is invalid. | ||
*/ | ||
this.invalid = false; | ||
// DEPRECATED | ||
/** | ||
* The Stripe card object. | ||
* **DEPRECATED**. Will be removed in a future version. use `element` instead | ||
* @deprecated | ||
*/ | ||
this.card = null; | ||
/** | ||
* Whether the form is empty. | ||
* **DEPRECATED**. Will be removed in a future version. use `empty` instead | ||
* @deprecated | ||
*/ | ||
this.isEmpty = true; | ||
/** | ||
* Whether the form is complete. | ||
* **DEPRECATED**. Will be removed in a future version. use `complete` instead | ||
* @deprecated | ||
*/ | ||
this.isComplete = false; | ||
} | ||
} | ||
return { | ||
F: StripeElements, | ||
d: [{ | ||
kind: "field", | ||
static: true, | ||
key: "is", | ||
value() { | ||
return 'stripe-elements'; | ||
} | ||
}, { | ||
kind: "field", | ||
static: true, | ||
key: "elementType", | ||
value() { | ||
return 'card'; | ||
} | ||
}, { | ||
kind: "field", | ||
static: true, | ||
key: "styles", | ||
value() { | ||
return [sharedStyles, style]; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'hide-icon' | ||
})], | ||
key: "hideIcon", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'hide-postal-code' | ||
})], | ||
key: "hidePostalCode", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String, | ||
attribute: 'icon-style' | ||
})], | ||
key: "iconStyle", | ||
value() { | ||
return 'default'; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object | ||
})], | ||
key: "value", | ||
value() { | ||
return {}; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "brand", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "complete", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "empty", | ||
value() { | ||
return true; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "invalid", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "card", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'is-empty', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "isEmpty", | ||
value() { | ||
return true; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'is-complete', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true | ||
})], | ||
key: "isComplete", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "method", | ||
key: "updated", | ||
value: | ||
/* PUBLIC FIELDS */ | ||
/** | ||
* Whether to hide icons in the Stripe form. | ||
* @type {boolean} | ||
*/ | ||
/** | ||
* Whether or not to hide the postal code field. | ||
* Useful when you gather shipping info elsewhere. | ||
* @type {boolean} | ||
*/ | ||
/** | ||
* Stripe icon style. 'solid' or 'default'. | ||
* @type {'solid'|'default'} | ||
*/ | ||
/** | ||
* Prefilled values for form. Example {postalCode: '90210'} | ||
* @type {object} | ||
*/ | ||
/* READ ONLY PROPERTIES */ | ||
/** | ||
* The card brand detected by Stripe | ||
* @type {string} | ||
* @readonly | ||
*/ | ||
/** | ||
* Whether the form is complete. | ||
* @type {boolean} | ||
* @readonly | ||
*/ | ||
/** | ||
* If the form is empty. | ||
* @type {boolean} | ||
* @readonly | ||
*/ | ||
/** | ||
* Whether the form is invalid. | ||
* @type {boolean} | ||
* @readonly | ||
*/ | ||
// DEPRECATED | ||
/** | ||
* The Stripe card object. | ||
* **DEPRECATED**. Will be removed in a future version. use `element` instead | ||
* @type {stripe.elements.Element} | ||
* @readonly | ||
* @deprecated | ||
*/ | ||
/** | ||
* Whether the form is empty. | ||
* **DEPRECATED**. Will be removed in a future version. use `empty` instead | ||
* @type {boolean} | ||
* @deprecated | ||
*/ | ||
/** | ||
* Whether the form is complete. | ||
* **DEPRECATED**. Will be removed in a future version. use `complete` instead | ||
* @type {boolean} | ||
* @deprecated | ||
*/ | ||
function updated(changed) { | ||
_get(_getPrototypeOf(StripeElements.prototype), "updated", this).call(this, changed); // DEPRECATED | ||
if (changed.has('element') && !this.element) this.set({ | ||
card: null | ||
}); | ||
} | ||
/* PUBLIC API */ | ||
/** | ||
* Submit payment information to generate a paymentMethod | ||
* @param {stripe.PaymentMethodData} [paymentMethodData={}] | ||
* @resolves {stripe.PaymentMethodResponse} | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [stripeMethod], | ||
key: "createPaymentMethod", | ||
value: async function createPaymentMethod(paymentMethodData = this.getPaymentMethodData()) { | ||
updated(changed) { | ||
super.updated(changed); | ||
// DEPRECATED | ||
if (changed.has('element') && !this.element) | ||
this.setReadOnlyProperties({ card: null }); | ||
} | ||
/* PUBLIC API */ | ||
/** | ||
* Submit payment information to generate a paymentMethod | ||
*/ | ||
async createPaymentMethod(paymentMethodData = this.getPaymentMethodData()) { | ||
return this.stripe.createPaymentMethod(paymentMethodData); | ||
} | ||
/** | ||
* Submit payment information to generate a source | ||
* @param {{ owner: stripe.OwnerInfo }} [sourceData={}] | ||
* @resolves {stripe.SourceResponse} | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [stripeMethod], | ||
key: "createSource", | ||
value: async function createSource(sourceData = this.sourceData) { | ||
} | ||
/** | ||
* Submit payment information to generate a source | ||
*/ | ||
async createSource(sourceData = this.sourceData) { | ||
return this.stripe.createSource(this.element, sourceData); | ||
} | ||
/** | ||
* Submit payment information to generate a token | ||
* @param {TokenData} [tokenData=this.tokenData] | ||
* @resolves {stripe.TokenResponse} | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [stripeMethod], | ||
key: "createToken", | ||
value: async function createToken(tokenData = this.tokenData) { | ||
} | ||
/** | ||
* Submit payment information to generate a token | ||
*/ | ||
async createToken(tokenData = this.tokenData) { | ||
return this.stripe.createToken(this.element, tokenData); | ||
} | ||
/** | ||
* Checks for potential validity. A potentially valid form is one that is not empty, not complete and has no error. A validated form also counts as potentially valid. | ||
* @return {boolean} true if the Stripe form is potentially valid | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "isPotentiallyValid", | ||
value: function isPotentiallyValid() { | ||
return !this.complete && !this.empty && !this.error || this.validate(); | ||
} | ||
/** | ||
* Resets the Stripe card. | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "reset", | ||
value: function reset() { | ||
var _this$element; | ||
_get(_getPrototypeOf(StripeElements.prototype), "reset", this).call(this); | ||
(_this$element = this.element) === null || _this$element === void 0 ? void 0 : _this$element.clear(); | ||
} | ||
/** | ||
* Generates a payment representation of the type specified by `generate`. | ||
* @resolves {PaymentResponse} | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "submit", | ||
value: async function submit() { | ||
} | ||
/** | ||
* Checks for potential validity. A potentially valid form is one that is not empty, not complete and has no error. A validated form also counts as potentially valid. | ||
*/ | ||
isPotentiallyValid() { | ||
return (!this.complete && !this.empty && !this.error) || this.validate(); | ||
} | ||
/** | ||
* Resets the Stripe card. | ||
*/ | ||
reset() { | ||
var _a; | ||
super.reset(); | ||
/* istanbul ignore next */ | ||
(_a = this.element) === null || _a === void 0 ? void 0 : _a.clear(); | ||
} | ||
/** | ||
* Generates a payment representation of the type specified by `generate`. | ||
*/ | ||
async submit() { | ||
switch (this.generate) { | ||
case 'payment-method': | ||
return this.createPaymentMethod(); | ||
case 'source': | ||
return this.createSource(); | ||
case 'token': | ||
return this.createToken(); | ||
default: | ||
{ | ||
const error = this.createError(`cannot generate ${this.generate}`); | ||
await this.set({ | ||
error | ||
}); | ||
throw error; | ||
case 'payment-method': return this.createPaymentMethod(); | ||
case 'source': return this.createSource(); | ||
case 'token': return this.createToken(); | ||
default: { | ||
const error = this.createError(`cannot generate ${this.generate}`); | ||
await this.setReadOnlyProperties({ error }); | ||
throw error; | ||
} | ||
} | ||
} | ||
/** | ||
* Checks if the Stripe form is valid. | ||
* @return {boolean} true if the Stripe form is valid | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "validate", | ||
value: function validate() { | ||
const { | ||
complete, | ||
empty, | ||
error | ||
} = this; | ||
} | ||
/** | ||
* Checks if the Stripe form is valid. | ||
*/ | ||
validate() { | ||
const { complete, empty, error } = this; | ||
const isValid = !error && complete && !empty; | ||
if (empty && !error) this.set({ | ||
error: this.createError('Your card number is empty.') | ||
}); | ||
if (empty && !error) | ||
this.setReadOnlyProperties({ error: this.createError('Your card number is empty.') }); | ||
return isValid; | ||
} | ||
/* PRIVATE METHODS */ | ||
/** | ||
* Generates PaymentMethodData from the element. | ||
* @param {stripe.PaymentMethodData} data data, minus card property | ||
* @return {stripe.PaymentMethodData} data with card property | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "getPaymentMethodData", | ||
value: function getPaymentMethodData() { | ||
} | ||
/* PRIVATE METHODS */ | ||
/** | ||
* Generates PaymentMethodData from the element. | ||
*/ | ||
getPaymentMethodData() { | ||
const type = 'card'; | ||
const { | ||
billingDetails, | ||
element: card, | ||
paymentMethodData | ||
} = this; | ||
return { | ||
billing_details: billingDetails, | ||
...paymentMethodData, | ||
type, | ||
card | ||
}; | ||
} | ||
/** | ||
* Returns a Stripe-friendly style object computed from CSS custom properties | ||
* @return {StripeStyleInit} Stripe Style initialization object. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "getStripeElementsStyles", | ||
value: function getStripeElementsStyles() { | ||
const { billingDetails, element: card, paymentMethodData } = this; | ||
return ({ | ||
billing_details: billingDetails, | ||
...paymentMethodData, | ||
type, | ||
card, | ||
}); | ||
} | ||
/** | ||
* Returns a Stripe-friendly style object computed from CSS custom properties | ||
*/ | ||
getStripeElementsStyles() { | ||
const computedStyle = window.ShadyCSS ? undefined : getComputedStyle(this); | ||
const getStyle = prop => this.getCSSCustomPropertyValue(prop, computedStyle) || undefined; | ||
const styleReducer = ({ | ||
base = {}, | ||
complete = {}, | ||
empty = {}, | ||
invalid = {} | ||
}, camelCase) => ({ | ||
base: { ...base, | ||
[camelCase]: getStyle(`--stripe-elements-base-${dash(camelCase)}`) | ||
}, | ||
complete: { ...complete, | ||
[camelCase]: getStyle(`--stripe-elements-complete-${dash(camelCase)}`) | ||
}, | ||
empty: { ...empty, | ||
[camelCase]: getStyle(`--stripe-elements-empty-${dash(camelCase)}`) | ||
}, | ||
invalid: { ...invalid, | ||
[camelCase]: getStyle(`--stripe-elements-invalid-${dash(camelCase)}`) | ||
} | ||
const getStyle = (prop) => this.getCSSCustomPropertyValue(prop, computedStyle) || undefined; | ||
const styleReducer = ({ base = {}, complete = {}, empty = {}, invalid = {}, }, camelCase) => ({ | ||
base: { ...base, [camelCase]: getStyle(`--stripe-elements-base-${dash(camelCase)}`) }, | ||
complete: { ...complete, [camelCase]: getStyle(`--stripe-elements-complete-${dash(camelCase)}`) }, | ||
empty: { ...empty, [camelCase]: getStyle(`--stripe-elements-empty-${dash(camelCase)}`) }, | ||
invalid: { ...invalid, [camelCase]: getStyle(`--stripe-elements-invalid-${dash(camelCase)}`) }, | ||
}); | ||
return allowedStyles.reduce(styleReducer, {}); | ||
} | ||
/** | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initElement", | ||
value: async function initElement() { | ||
if (!this.stripe) return; | ||
const { | ||
hidePostalCode, | ||
hideIcon, | ||
iconStyle, | ||
value | ||
} = this; | ||
} | ||
async initElement() { | ||
if (!this.stripe) | ||
return; | ||
const { hidePostalCode, hideIcon, iconStyle, value } = this; | ||
const style = this.getStripeElementsStyles(); | ||
const options = { | ||
hideIcon, | ||
hidePostalCode, | ||
iconStyle, | ||
style, | ||
value | ||
hideIcon, | ||
hidePostalCode, | ||
iconStyle, | ||
style, | ||
value, | ||
}; | ||
const element = this.elements.create('card', options); | ||
element.addEventListener('change', this.onChange); | ||
await this.set({ | ||
element, | ||
// DEPRECATED | ||
card: element | ||
await this.setReadOnlyProperties({ | ||
element, | ||
// DEPRECATED | ||
card: element, | ||
}); | ||
} | ||
/** | ||
* Updates the element's state. | ||
* @param {stripe.elements.ElementChangeResponse} event | ||
* @param {boolean} event.empty true if value is empty | ||
* @param {boolean} event.complete true if value is well-formed and potentially complete. | ||
* @param {string} event.brand brand of the card being entered e.g. 'visa' or 'amex' | ||
* @param {stripe.Error} event.error The current validation error, if any. | ||
* @param {String|Object} event.value Value of the form. Only non-sensitive information e.g. postalCode is present. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "onChange", | ||
value: async function onChange(event) { | ||
const { | ||
brand, | ||
complete, | ||
empty, | ||
error = null | ||
} = event; | ||
const invalid = error || !empty && !complete; | ||
await this.set({ | ||
brand, | ||
complete, | ||
empty, | ||
error, | ||
invalid, | ||
// DEPRECATED | ||
isComplete: complete, | ||
isEmpty: empty | ||
} | ||
/** | ||
* Updates the element's state. | ||
*/ | ||
async onChange(event) { | ||
const { brand, complete, empty, error = null } = event; | ||
const invalid = error || (!empty && !complete); | ||
await this.setReadOnlyProperties({ | ||
brand, | ||
complete, | ||
empty, | ||
error, | ||
invalid, | ||
// DEPRECATED | ||
isComplete: complete, | ||
isEmpty: empty, | ||
}); | ||
this.fire('change', event); // DEPRECATED | ||
this.fire('change', event); | ||
// DEPRECATED | ||
this.fire('stripe-change', event); | ||
} | ||
}] | ||
}; | ||
}, LitNotify(StripeBase)); | ||
/** @typedef {{ base?: stripe.elements.Style, complete?: stripe.elements.Style, empty?: stripe.elements.Style, invalid?: stripe.elements.Style}} StripeStyleInit */ | ||
} | ||
}; | ||
StripeElements.is = 'stripe-elements'; | ||
StripeElements.elementType = 'card'; | ||
StripeElements.styles = [ | ||
sharedStyles, | ||
style, | ||
]; | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'hide-icon' }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "hideIcon", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'hide-postal-code' }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "hidePostalCode", void 0); | ||
__decorate([ | ||
property({ type: String, attribute: 'icon-style' }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "iconStyle", void 0); | ||
__decorate([ | ||
property({ type: Object }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "value", void 0); | ||
__decorate([ | ||
property({ type: String, notify: true, readOnly: true }), | ||
__metadata("design:type", String) | ||
], StripeElements.prototype, "brand", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "complete", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "empty", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "invalid", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "card", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'is-empty', reflect: true, notify: true, readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "isEmpty", void 0); | ||
__decorate([ | ||
property({ | ||
type: Boolean, | ||
attribute: 'is-complete', | ||
reflect: true, | ||
notify: true, | ||
readOnly: true, | ||
}), | ||
__metadata("design:type", Object) | ||
], StripeElements.prototype, "isComplete", void 0); | ||
__decorate([ | ||
stripeMethod, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeElements.prototype, "createPaymentMethod", null); | ||
__decorate([ | ||
stripeMethod, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeElements.prototype, "createSource", null); | ||
__decorate([ | ||
stripeMethod, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeElements.prototype, "createToken", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripeElements.prototype, "onChange", null); | ||
StripeElements = __decorate([ | ||
customElement('stripe-elements') | ||
], StripeElements); | ||
customElements.define(StripeElements.is, StripeElements); | ||
export { StripeElements }; | ||
//# sourceMappingURL=stripe-elements.js.map |
@@ -1,11 +0,7 @@ | ||
import _toArray from '@babel/runtime/helpers/esm/toArray'; | ||
import _getPrototypeOf from '@babel/runtime/helpers/esm/getPrototypeOf'; | ||
import _get from '@babel/runtime/helpers/esm/get'; | ||
import { css, property, customElement } from 'lit-element'; | ||
import { S as StripeBase, s as sharedStyles, b as bound } from './shared.js'; | ||
import '@morbidick/lit-element-notify'; | ||
import { css, property } from 'lit-element'; | ||
import { S as StripeBase, s as sharedStyles, c as camel, b as bound, m as mapDataset, a as mapProps } from './shared.js'; | ||
import 'lit-html/directives/if-defined'; | ||
import '@babel/runtime/helpers/esm/defineProperty'; | ||
import 'lit-html'; | ||
import '@typed/curry'; | ||
import 'lit-html'; | ||
import '@lavadrop/kebab-case'; | ||
@@ -16,7 +12,8 @@ import '@lavadrop/camel-case'; | ||
function throwResponseError(response) { | ||
if (response.error) throw response.error;else return response; | ||
if (response.error) | ||
throw response.error; | ||
else | ||
return response; | ||
} | ||
const unary = f => x => f(x); | ||
var style = css`#stripe { | ||
@@ -30,25 +27,48 @@ box-sizing: border-box; | ||
function _decorate(decorators, factory, superClass, mixins) { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); } | ||
function _getDecoratorsApi() { _getDecoratorsApi = function () { return api; }; var api = { elementsDefinitionOrder: [["method"], ["field"]], initializeInstanceElements: function (O, elements) { ["method", "field"].forEach(function (kind) { elements.forEach(function (element) { if (element.kind === kind && element.placement === "own") { this.defineClassElement(O, element); } }, this); }, this); }, initializeClassElements: function (F, elements) { var proto = F.prototype; ["method", "field"].forEach(function (kind) { elements.forEach(function (element) { var placement = element.placement; if (element.kind === kind && (placement === "static" || placement === "prototype")) { var receiver = placement === "static" ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, defineClassElement: function (receiver, element) { var descriptor = element.descriptor; if (element.kind === "field") { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver) }; } Object.defineProperty(receiver, element.key, descriptor); }, decorateClass: function (elements, decorators) { var newElements = []; var finishers = []; var placements = { static: [], prototype: [], own: [] }; elements.forEach(function (element) { this.addElementPlacement(element, placements); }, this); elements.forEach(function (element) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras = this.decorateElement(element, placements); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers }; } var result = this.decorateConstructor(newElements, decorators); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, addElementPlacement: function (element, placements, silent) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError("Duplicated element (" + element.key + ")"); } keys.push(element.key); }, decorateElement: function (element, placements) { var extras = []; var finishers = []; for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject = this.fromElementDescriptor(element); var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras }; }, decorateConstructor: function (elements, decorators) { var finishers = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj = this.fromClassDescriptor(elements); var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { throw new TypeError("Duplicated element (" + elements[j].key + ")"); } } } } } return { elements: elements, finishers: finishers }; }, fromElementDescriptor: function (element) { var obj = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === "field") obj.initializer = element.initializer; return obj; }, toElementDescriptors: function (elementObjects) { if (elementObjects === undefined) return; return _toArray(elementObjects).map(function (elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, "finisher", "An element descriptor"); this.disallowProperty(elementObject, "extras", "An element descriptor"); return element; }, this); }, toElementDescriptor: function (elementObject) { var kind = String(elementObject.kind); if (kind !== "method" && kind !== "field") { throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); } var key = _toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if (placement !== "static" && placement !== "prototype" && placement !== "own") { throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); } var descriptor = elementObject.descriptor; this.disallowProperty(elementObject, "elements", "An element descriptor"); var element = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor) }; if (kind !== "field") { this.disallowProperty(elementObject, "initializer", "A method descriptor"); } else { this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function (elementObject) { var element = this.toElementDescriptor(elementObject); var finisher = _optionalCallableProperty(elementObject, "finisher"); var extras = this.toElementDescriptors(elementObject.extras); return { element: element, finisher: finisher, extras: extras }; }, fromClassDescriptor: function (elements) { var obj = { kind: "class", elements: elements.map(this.fromElementDescriptor, this) }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, toClassDescriptor: function (obj) { var kind = String(obj.kind); if (kind !== "class") { throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); } this.disallowProperty(obj, "key", "A class descriptor"); this.disallowProperty(obj, "placement", "A class descriptor"); this.disallowProperty(obj, "descriptor", "A class descriptor"); this.disallowProperty(obj, "initializer", "A class descriptor"); this.disallowProperty(obj, "extras", "A class descriptor"); var finisher = _optionalCallableProperty(obj, "finisher"); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher }; }, runClassFinishers: function (constructor, finishers) { for (var i = 0; i < finishers.length; i++) { var newConstructor = (0, finishers[i])(constructor); if (newConstructor !== undefined) { if (typeof newConstructor !== "function") { throw new TypeError("Finishers must return a constructor."); } constructor = newConstructor; } } return constructor; }, disallowProperty: function (obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + " property."); } } }; return api; } | ||
function _createElementDescriptor(def) { var key = _toPropertyKey(def.key); var descriptor; if (def.kind === "method") { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false }; } else if (def.kind === "get") { descriptor = { get: def.value, configurable: true, enumerable: false }; } else if (def.kind === "set") { descriptor = { set: def.value, configurable: true, enumerable: false }; } else if (def.kind === "field") { descriptor = { configurable: true, writable: true, enumerable: true }; } var element = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor }; if (def.decorators) element.decorators = def.decorators; if (def.kind === "field") element.initializer = def.value; return element; } | ||
function _coalesceGetterSetter(element, other) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } } | ||
function _coalesceClassElements(elements) { var newElements = []; var isSameElement = function (other) { return other.kind === "method" && other.key === element.key && other.placement === element.placement; }; for (var i = 0; i < elements.length; i++) { var element = elements[i]; var other; if (element.kind === "method" && (other = newElements.find(isSameElement))) { if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; } | ||
function _hasDecorators(element) { return element.decorators && element.decorators.length; } | ||
function _isDataDescriptor(desc) { return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); } | ||
function _optionalCallableProperty(obj, name) { var value = obj[name]; if (value !== undefined && typeof value !== "function") { throw new TypeError("Expected '" + name + "' to be a function"); } return value; } | ||
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } | ||
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } | ||
const parseAmount = mapProps({ | ||
amount: unary(parseInt) | ||
}); | ||
const parseDataset = mapDataset(parseAmount); | ||
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { | ||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; | ||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); | ||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; | ||
return c > 3 && r && Object.defineProperty(target, key, r), r; | ||
}; | ||
var __metadata = (undefined && undefined.__metadata) || function (k, v) { | ||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); | ||
}; | ||
var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, privateMap) { | ||
if (!privateMap.has(receiver)) { | ||
throw new TypeError("attempted to get private field on non-instance"); | ||
} | ||
return privateMap.get(receiver); | ||
}; | ||
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, privateMap, value) { | ||
if (!privateMap.has(receiver)) { | ||
throw new TypeError("attempted to set private field on non-instance"); | ||
} | ||
privateMap.set(receiver, value); | ||
return value; | ||
}; | ||
var _displayItems, _shippingOptions; | ||
function isStripeDisplayItem(el) { | ||
return el.tagName.toLowerCase() === 'stripe-display-item'; | ||
} | ||
function datasetToStripeDisplayItem({ dataset: { amount, label, pending } }) { | ||
return { | ||
label, | ||
amount: parseInt(amount), | ||
...pending !== undefined && { pending: pending === 'true' ? true : false }, | ||
}; | ||
} | ||
function isStripeShippingOption(el) { | ||
return el.tagName.toLowerCase() === 'stripe-shipping-option'; | ||
} | ||
function datasetToStripeShippingOption({ dataset: { amount, ...rest } }) { | ||
return { | ||
amount: parseInt(amount), | ||
...rest, | ||
}; | ||
} | ||
function mapDataset(el) { | ||
return (isStripeDisplayItem(el) ? datasetToStripeDisplayItem(el) | ||
: datasetToStripeShippingOption(el)); | ||
} | ||
/** | ||
@@ -97,5 +117,5 @@ * Custom element wrapper for Stripe.js v3 Payment Request Buttons. | ||
* | ||
* @cssprop [--stripe-payment-request-element-min-width] - min-width property of the container element. Default `300px` | ||
* @cssprop [--stripe-payment-request-element-padding] - padding property of the container element. Default `8px 12px` | ||
* @cssprop [--stripe-payment-request-element-background] - background property of the container element. Default `white` | ||
* @cssprop [--stripe-payment-request-element-min-width=`300px`] - min-width property of the container element | ||
* @cssprop [--stripe-payment-request-element-padding=`8px 12px`] - padding property of the container element | ||
* @cssprop [--stripe-payment-request-element-background=`white`] - background property of the container element | ||
* | ||
@@ -111,619 +131,324 @@ * @element stripe-payment-request | ||
*/ | ||
let StripePaymentRequest = _decorate(null, function (_initialize, _StripeBase) { | ||
class StripePaymentRequest extends _StripeBase { | ||
constructor(...args) { | ||
super(...args); | ||
_initialize(this); | ||
let StripePaymentRequest = class StripePaymentRequest extends StripeBase { | ||
constructor() { | ||
super(...arguments); | ||
/** | ||
* Whether or not the device can make the payment request. | ||
* @readonly | ||
*/ | ||
this.canMakePayment = null; | ||
_displayItems.set(this, void 0); | ||
/** | ||
* Stripe PaymentIntent | ||
*/ | ||
this.paymentIntent = null; | ||
/** | ||
* Stripe PaymentRequest | ||
*/ | ||
this.paymentRequest = null; | ||
/** | ||
* If you might change the payment amount later (for example, after you have calcluated shipping costs), set this to true. Note that browsers treat this as a hint for how to display things, and not necessarily as something that will prevent submission. | ||
*/ | ||
this.pending = false; | ||
_shippingOptions.set(this, void 0); | ||
this.buttonType = 'default'; | ||
this.buttonTheme = 'dark'; | ||
} | ||
} | ||
return { | ||
F: StripePaymentRequest, | ||
d: [{ | ||
kind: "field", | ||
static: true, | ||
key: "is", | ||
value() { | ||
return 'stripe-payment-request'; | ||
} | ||
}, { | ||
kind: "field", | ||
static: true, | ||
key: "styles", | ||
value() { | ||
return [sharedStyles, style]; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Number, | ||
reflect: true | ||
})], | ||
key: "amount", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'can-make-payment', | ||
reflect: true, | ||
readOnly: true, | ||
notify: true | ||
})], | ||
key: "canMakePayment", | ||
value() { | ||
return undefined; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String | ||
})], | ||
key: "country", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String | ||
})], | ||
key: "currency", | ||
value: void 0 | ||
}, { | ||
kind: "get", | ||
decorators: [property({ | ||
type: Array | ||
})], | ||
key: "displayItems", | ||
value: | ||
/** | ||
* The amount in the currency's subunit (e.g. cents, yen, etc.) | ||
* @type {number} | ||
*/ | ||
/** | ||
* Whether or not the device can make the payment request. | ||
* @type {object} | ||
* @readonly | ||
*/ | ||
/** | ||
* The two-letter country code of your Stripe account (e.g., `US`) | ||
* @type {string} | ||
*/ | ||
/** | ||
* Three character currency code (e.g., `usd`) | ||
* @type {string} | ||
*/ | ||
/** | ||
* An array of DisplayItem objects. These objects are shown as line items in the browser’s payment interface. Note that the sum of the line item amounts does not need to add up to the total amount above. | ||
* @type {stripe.paymentRequest.DisplayItem[]} | ||
*/ | ||
function displayItems() { | ||
const value = this.__displayItems; | ||
return Array.isArray(value) ? value : this.parseDatasets('stripe-display-item'); | ||
} | ||
}, { | ||
kind: "set", | ||
key: "displayItems", | ||
value: function displayItems(value) { | ||
/** | ||
* An array of DisplayItem objects. These objects are shown as line items in the browser’s payment interface. Note that the sum of the line item amounts does not need to add up to the total amount above. | ||
*/ | ||
get displayItems() { | ||
const value = __classPrivateFieldGet(this, _displayItems); | ||
return (Array.isArray(value) ? value | ||
: this.parseDatasets('stripe-display-item')); | ||
} | ||
set displayItems(value) { | ||
const oldValue = this.displayItems; | ||
/** @private */ | ||
this.__displayItems = value; | ||
__classPrivateFieldSet(this, _displayItems, value); | ||
this.requestUpdate('displayItems', oldValue); | ||
} | ||
/** | ||
* A name that the browser shows the customer in the payment interface. | ||
* @type {string} | ||
*/ | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String, | ||
reflect: true | ||
})], | ||
key: "label", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
notify: true, | ||
readOnly: true, | ||
attribute: 'payment-intent' | ||
})], | ||
key: "paymentIntent", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Object, | ||
attribute: 'payment-request', | ||
readOnly: true | ||
})], | ||
key: "paymentRequest", | ||
value() { | ||
return null; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
reflect: true | ||
})], | ||
key: "pending", | ||
value() { | ||
return false; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'request-payer-email' | ||
})], | ||
key: "requestPayerEmail", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'request-payer-name' | ||
})], | ||
key: "requestPayerName", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'request-payer-phone' | ||
})], | ||
key: "requestPayerPhone", | ||
value: void 0 | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: Boolean, | ||
attribute: 'request-shipping' | ||
})], | ||
key: "requestShipping", | ||
value: void 0 | ||
}, { | ||
kind: "get", | ||
decorators: [property({ | ||
type: Array | ||
})], | ||
key: "shippingOptions", | ||
value: | ||
/** | ||
* Stripe PaymentIntent | ||
* @type {stripe.paymentIntents.PaymentIntent} | ||
* @readonly | ||
*/ | ||
/** | ||
* Stripe PaymentRequest | ||
* @type {stripe.paymentRequest.StripePaymentRequest} | ||
*/ | ||
/** | ||
* If you might change the payment amount later (for example, after you have calcluated shipping costs), set this to true. Note that browsers treat this as a hint for how to display things, and not necessarily as something that will prevent submission. | ||
* @type {boolean} | ||
*/ | ||
/** | ||
* See the requestPayerName option. | ||
* @type {boolean} | ||
*/ | ||
/** | ||
* By default, the browser‘s payment interface only asks the customer for actual payment information. A customer name can be collected by setting this option to true. This collected name will appears in the PaymentResponse object. | ||
* | ||
* We highly recommend you collect at least one of name, email, or phone as this also results in collection of billing address for Apple Pay. The billing address can be used to perform address verification and block fraudulent payments. For all other payment methods, the billing address is automatically collected when available. | ||
* @type {boolean} | ||
*/ | ||
/** | ||
* See the requestPayerName option. | ||
* @type {boolean} | ||
*/ | ||
/** | ||
* Collect shipping address by setting this option to true. The address appears in the PaymentResponse. | ||
* You must also supply a valid [ShippingOptions] to the shippingOptions property. This can be up front at the time stripe.paymentRequest is called, or in response to a shippingaddresschange event using the updateWith callback. | ||
* @type {boolean} | ||
*/ | ||
/** | ||
* An array of ShippingOption objects. The first shipping option listed appears in the browser payment interface as the default option. | ||
* @type {stripe.paymentRequest.ShippingOption[]} | ||
*/ | ||
function shippingOptions() { | ||
const value = this.__shippingOptions; | ||
} | ||
/** | ||
* An array of ShippingOption objects. The first shipping option listed appears in the browser payment interface as the default option. | ||
*/ | ||
get shippingOptions() { | ||
const value = __classPrivateFieldGet(this, _shippingOptions); | ||
return Array.isArray(value) ? value : this.parseDatasets('stripe-shipping-option'); | ||
} | ||
}, { | ||
kind: "set", | ||
key: "shippingOptions", | ||
value: function shippingOptions(value) { | ||
} | ||
set shippingOptions(value) { | ||
const oldValue = this.shippingOptions; | ||
/** @private */ | ||
this.__shippingOptions = value; | ||
__classPrivateFieldSet(this, _shippingOptions, value); | ||
this.requestUpdate('shippingOptions', oldValue); | ||
} | ||
/** | ||
* @type {'default'|'book'|'buy'|'donate'} | ||
*/ | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String, | ||
attribute: 'button-type' | ||
})], | ||
key: "buttonType", | ||
value() { | ||
return 'default'; | ||
} | ||
}, { | ||
kind: "field", | ||
decorators: [property({ | ||
type: String, | ||
attribute: 'button-theme' | ||
})], | ||
key: "buttonTheme", | ||
value() { | ||
return 'dark'; | ||
} | ||
}, { | ||
kind: "method", | ||
key: "reset", | ||
value: | ||
/** | ||
* @type {'dark'|'light'|'light-outline'} | ||
*/ | ||
/* PUBLIC API */ | ||
function reset() { | ||
_get(_getPrototypeOf(StripePaymentRequest.prototype), "reset", this).call(this); | ||
this.set({ | ||
paymentIntent: null | ||
}); | ||
} | ||
/* LIFECYCLE */ | ||
/** @inheritdoc */ | ||
}, { | ||
kind: "method", | ||
key: "updated", | ||
value: function updated(changed) { | ||
_get(_getPrototypeOf(StripePaymentRequest.prototype), "updated", this).call(this, changed); | ||
if (changed.has('generate')) this.initPaymentRequestListeners(); | ||
} | ||
/* PRIVATE API */ | ||
/** | ||
* Creates a StripePaymentRequestOptions object. | ||
* @return {stripe.paymentRequest.StripePaymentRequestOptions} [description] | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "getStripePaymentRequestOptions", | ||
value: function getStripePaymentRequestOptions() { | ||
const { | ||
country, | ||
currency, | ||
displayItems, | ||
shippingOptions, | ||
requestPayerEmail, | ||
requestPayerName, | ||
requestPayerPhone, | ||
label, | ||
amount | ||
} = this; | ||
const total = { | ||
label, | ||
amount | ||
}; | ||
} | ||
/* PUBLIC API */ | ||
reset() { | ||
super.reset(); | ||
this.setReadOnlyProperties({ paymentIntent: null }); | ||
} | ||
/* LIFECYCLE */ | ||
/** @inheritdoc */ | ||
updated(changed) { | ||
super.updated(changed); | ||
if (changed.has('generate')) | ||
this.initPaymentRequestListeners(); | ||
} | ||
/* PRIVATE API */ | ||
/** | ||
* Creates a StripePaymentRequestOptions object. | ||
*/ | ||
getStripePaymentRequestOptions() { | ||
const { country, currency, displayItems, shippingOptions, requestPayerEmail, requestPayerName, requestPayerPhone, label, amount, } = this; | ||
const total = { label, amount }; | ||
return { | ||
country, | ||
currency, | ||
displayItems, | ||
requestPayerEmail, | ||
requestPayerName, | ||
requestPayerPhone, | ||
shippingOptions, | ||
total | ||
country, | ||
currency, | ||
displayItems, | ||
requestPayerEmail, | ||
requestPayerName, | ||
requestPayerPhone, | ||
shippingOptions, | ||
total, | ||
}; | ||
} | ||
/** | ||
* Initializes the PaymentRequest Object. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initElement", | ||
value: async function initElement() { | ||
} | ||
/** | ||
* Initializes the PaymentRequest Object. | ||
*/ | ||
async initElement() { | ||
await this.initPaymentRequest(); | ||
await this.initPaymentRequestListeners(); | ||
await this.initPaymentRequestButton(); | ||
} | ||
/** | ||
* Initialized the `PaymentRequest` object. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initPaymentRequest", | ||
value: async function initPaymentRequest() { | ||
if (!this.stripe) return; | ||
} | ||
/** | ||
* Initialized the `PaymentRequest` object. | ||
*/ | ||
async initPaymentRequest() { | ||
if (!this.stripe) | ||
return; | ||
const stripePaymentRequestOptions = this.getStripePaymentRequestOptions(); | ||
const paymentRequest = this.stripe.paymentRequest(stripePaymentRequestOptions); | ||
const canMakePayment = await paymentRequest.canMakePayment(); | ||
await this.set({ | ||
paymentRequest, | ||
canMakePayment | ||
}); | ||
if (!this.canMakePayment) this.fire('unsupported'); | ||
} | ||
/** | ||
* Creates Stripe Payment Request Element. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initPaymentRequestButton", | ||
value: async function initPaymentRequestButton() { | ||
const { | ||
buttonTheme: theme, | ||
buttonType: type, | ||
canMakePayment, | ||
paymentRequest | ||
} = this; | ||
if (!canMakePayment) return; | ||
await this.setReadOnlyProperties({ paymentRequest, canMakePayment }); | ||
if (!this.canMakePayment) | ||
this.fire('unsupported'); | ||
} | ||
/** | ||
* Creates Stripe Payment Request Element. | ||
*/ | ||
async initPaymentRequestButton() { | ||
const { buttonTheme: theme, buttonType: type, canMakePayment, paymentRequest } = this; | ||
if (!canMakePayment) | ||
return; | ||
const computedStyle = window.ShadyCSS ? undefined : getComputedStyle(this); | ||
const propertyName = '--stripe-payment-request-button-height'; | ||
const height = this.getCSSCustomPropertyValue(propertyName, computedStyle) || '40px'; | ||
const style = { | ||
paymentRequestButton: { | ||
height, | ||
theme, | ||
type | ||
} | ||
}; | ||
const options = { | ||
paymentRequest, | ||
style | ||
}; | ||
const style = { paymentRequestButton: { height, theme, type } }; | ||
const options = { paymentRequest, style }; | ||
const element = this.elements.create('paymentRequestButton', options); | ||
await this.set({ | ||
element | ||
}); | ||
} | ||
/** | ||
* Attaches listeners to the `PaymentRequest` object. | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "initPaymentRequestListeners", | ||
value: async function initPaymentRequestListeners() { | ||
if (!this.canMakePayment) return; | ||
const stripeEvent = camel(this.generate).toLowerCase(); | ||
this.paymentRequest.on(stripeEvent, this.onPaymentResponse); | ||
await this.setReadOnlyProperties({ element }); | ||
} | ||
/** | ||
* Attaches listeners to the `PaymentRequest` object. | ||
*/ | ||
async initPaymentRequestListeners() { | ||
if (!this.canMakePayment) | ||
return; | ||
this.paymentRequest.on('cancel', this.onCancel); | ||
this.paymentRequest.on('shippingaddresschange', this.onShippingaddresschange); | ||
this.paymentRequest.on('shippingoptionchange', this.onShippingoptionchange); | ||
} | ||
/** | ||
* Handle a `cancel` event | ||
* @param {StripeCancelEvent} originalEvent | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "onCancel", | ||
value: function onCancel(originalEvent) { | ||
this.fire('cancel', originalEvent); | ||
} | ||
/** | ||
* Completes the PaymentRequest. If a confirmation error is passed in the second argument, | ||
* will throw that error | ||
* @param {PaymentResponse} paymentResponse | ||
* @param {stripe.Error} [confirmationError] error from Stripe#confirmCardPayment. Should be thrown so that element state remains sane. | ||
* @resolvees {PaymentResponse} | ||
* @sideeffect | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "complete", | ||
value: async function complete(paymentResponse, confirmationError) { | ||
const { | ||
error: paymentResponseError | ||
} = paymentResponse; | ||
const status = paymentResponseError || confirmationError ? 'fail' : 'success'; | ||
switch (this.generate) { | ||
case 'payment-method': | ||
this.paymentRequest.on('paymentmethod', this.onPaymentResponse); | ||
break; | ||
case 'source': | ||
this.paymentRequest.on('source', this.onPaymentResponse); | ||
break; | ||
case 'token': | ||
this.paymentRequest.on('token', this.onPaymentResponse); | ||
break; | ||
} | ||
} | ||
/** | ||
* Handle a `cancel` event | ||
*/ | ||
onCancel() { | ||
this.fire("cancel" /* cancel */); | ||
} | ||
/** | ||
* Completes the PaymentRequest. | ||
*/ | ||
async complete(paymentResponse, confirmationError) { | ||
const { error: paymentResponseError = null } = { ...paymentResponse }; | ||
const status = (paymentResponseError || confirmationError) ? "fail" /* fail */ : "success" /* success */; | ||
paymentResponse.complete(status); | ||
this.fire(status, paymentResponse); | ||
return confirmationError ? { | ||
error: confirmationError | ||
} : paymentResponse; | ||
} | ||
/** | ||
* Handle a paymentResponse from Stripe | ||
* @param {PaymentResponse} paymentResponse stripe PaymentResponse paymentResponse | ||
* @resolves {PaymentResponse} | ||
* @rejects {stripe.Error|Error} | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "onPaymentResponse", | ||
value: async function onPaymentResponse(paymentResponse) { | ||
const { | ||
clientSecret, | ||
confirmPaymentIntent, | ||
complete | ||
} = this; | ||
const { | ||
error = null, | ||
paymentMethod = null, | ||
source = null, | ||
token = null | ||
} = paymentResponse; | ||
await this.set({ | ||
error, | ||
paymentMethod, | ||
source, | ||
token | ||
}); | ||
return confirmationError ? { error: confirmationError } : paymentResponse; | ||
} | ||
/** | ||
* Handle a paymentResponse from Stripe | ||
*/ | ||
async onPaymentResponse(paymentResponse) { | ||
const { clientSecret, confirmPaymentIntent, complete } = this; | ||
const { error = null, paymentMethod = null, source = null, token = null, } = { ...paymentResponse }; | ||
await this.setReadOnlyProperties({ error, paymentMethod, source, token }); | ||
const isPaymentIntent = clientSecret && !error; | ||
return isPaymentIntent ? confirmPaymentIntent(paymentResponse) : complete(paymentResponse); | ||
} | ||
/** | ||
* When a PaymentIntent client secret is set, confirm the payment | ||
* @param {PaymentResponse} paymentResponse | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "confirmPaymentIntent", | ||
value: async function confirmPaymentIntent(paymentResponse) { | ||
const confirmCardData = { | ||
payment_method: this.paymentMethod.id | ||
}; | ||
const { | ||
error = null, | ||
paymentIntent = null | ||
} = await this.confirmCardPayment(confirmCardData, { | ||
handleActions: false | ||
}).then(({ | ||
error: confirmationError | ||
}) => this.complete(paymentResponse, confirmationError)) // throws if first confirm errors | ||
.then(throwResponseError).then(() => this.confirmCardPayment()).then(throwResponseError).catch(error => ({ | ||
error | ||
})); // catch error from first confirm | ||
await this.set({ | ||
error, | ||
paymentIntent | ||
}); | ||
} | ||
/** | ||
* Stripe confirmCardPayment method | ||
* @param {stripe.ConfirmCardPaymentData} data | ||
* @param {stripe.ConfirmCardPaymentOptions} options | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "confirmCardPayment", | ||
value: async function confirmCardPayment(data, options) { | ||
if (isPaymentIntent) | ||
confirmPaymentIntent(paymentResponse); | ||
else | ||
complete(paymentResponse); | ||
} | ||
/** | ||
* When a PaymentIntent client secret is set, confirm the payment | ||
*/ | ||
async confirmPaymentIntent(paymentResponse) { | ||
const confirmCardData = { payment_method: this.paymentMethod.id }; // eslint-disable-line @typescript-eslint/camelcase | ||
const { error = null, paymentIntent = null } = await this.confirmCardPayment(confirmCardData, { handleActions: false }) | ||
.then(({ error: confirmationError }) => this.complete(paymentResponse, confirmationError)) // throws if first confirm errors | ||
.then(throwResponseError) | ||
.then(() => this.confirmCardPayment()) | ||
.then(throwResponseError) | ||
.catch(error => ({ error })); // catch error from first confirm | ||
await this.setReadOnlyProperties({ error, paymentIntent }); | ||
} | ||
/** | ||
* Stripe confirmCardPayment method | ||
*/ | ||
async confirmCardPayment(data, options) { | ||
return this.stripe.confirmCardPayment(this.clientSecret, data, options); | ||
} | ||
/** | ||
* @param {ShippingAddressChangeEvent} originalEvent | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "onShippingaddresschange", | ||
value: function onShippingaddresschange(originalEvent) { | ||
} | ||
onShippingaddresschange(originalEvent) { | ||
this.fire('shippingaddresschange', originalEvent); | ||
} | ||
/** | ||
* @param {ShippingOptionChangeEvent} originalEvent | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
decorators: [bound], | ||
key: "onShippingoptionchange", | ||
value: function onShippingoptionchange(originalEvent) { | ||
} | ||
onShippingoptionchange(originalEvent) { | ||
this.fire('shippingoptionchange', originalEvent); | ||
} | ||
/** | ||
* Parses an element's dataset number props from string to number | ||
* @param {String} selector | ||
* @return {Object} | ||
* @private | ||
*/ | ||
}, { | ||
kind: "method", | ||
key: "parseDatasets", | ||
value: function parseDatasets(selector) { | ||
} | ||
parseDatasets(selector) { | ||
const elements = [...this.querySelectorAll(selector)]; | ||
return !elements.length ? undefined : elements.map(parseDataset); | ||
} | ||
}] | ||
}; | ||
}, StripeBase); | ||
/** | ||
* @typedef {Object} ShippingAddressChangeEvent | ||
* @param {(options: stripe.paymentRequest.UpdateDetails) => void} updateWith | ||
* @param {stripe.paymentRequest.ShippingAddress} shippingAddress | ||
*/ | ||
return (!elements.length ? [] | ||
: elements.map(mapDataset)); | ||
} | ||
}; | ||
_displayItems = new WeakMap(), _shippingOptions = new WeakMap(); | ||
StripePaymentRequest.is = 'stripe-payment-request'; | ||
StripePaymentRequest.styles = [ | ||
sharedStyles, | ||
style, | ||
]; | ||
__decorate([ | ||
property({ type: Number, reflect: true }), | ||
__metadata("design:type", Number) | ||
], StripePaymentRequest.prototype, "amount", void 0); | ||
__decorate([ | ||
property({ | ||
type: Boolean, | ||
attribute: 'can-make-payment', | ||
reflect: true, | ||
readOnly: true, | ||
notify: true, | ||
}), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "canMakePayment", void 0); | ||
__decorate([ | ||
property({ type: String }), | ||
__metadata("design:type", String) | ||
], StripePaymentRequest.prototype, "country", void 0); | ||
__decorate([ | ||
property({ type: String }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "currency", void 0); | ||
__decorate([ | ||
property({ type: Array }), | ||
__metadata("design:type", Array), | ||
__metadata("design:paramtypes", [Object]) | ||
], StripePaymentRequest.prototype, "displayItems", null); | ||
__decorate([ | ||
property({ type: String, reflect: true }), | ||
__metadata("design:type", String) | ||
], StripePaymentRequest.prototype, "label", void 0); | ||
__decorate([ | ||
property({ type: Object, notify: true, readOnly: true, attribute: 'payment-intent' }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "paymentIntent", void 0); | ||
__decorate([ | ||
property({ type: Object, attribute: 'payment-request', readOnly: true }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "paymentRequest", void 0); | ||
__decorate([ | ||
property({ type: Boolean, reflect: true }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "pending", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'request-payer-email' }), | ||
__metadata("design:type", Boolean) | ||
], StripePaymentRequest.prototype, "requestPayerEmail", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'request-payer-name' }), | ||
__metadata("design:type", Boolean) | ||
], StripePaymentRequest.prototype, "requestPayerName", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'request-payer-phone' }), | ||
__metadata("design:type", Boolean) | ||
], StripePaymentRequest.prototype, "requestPayerPhone", void 0); | ||
__decorate([ | ||
property({ type: Boolean, attribute: 'request-shipping' }), | ||
__metadata("design:type", Boolean) | ||
], StripePaymentRequest.prototype, "requestShipping", void 0); | ||
__decorate([ | ||
property({ type: Array }), | ||
__metadata("design:type", Array), | ||
__metadata("design:paramtypes", [Object]) | ||
], StripePaymentRequest.prototype, "shippingOptions", null); | ||
__decorate([ | ||
property({ type: String, attribute: 'button-type' }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "buttonType", void 0); | ||
__decorate([ | ||
property({ type: String, attribute: 'button-theme' }), | ||
__metadata("design:type", Object) | ||
], StripePaymentRequest.prototype, "buttonTheme", void 0); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", []), | ||
__metadata("design:returntype", void 0) | ||
], StripePaymentRequest.prototype, "onCancel", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object, Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripePaymentRequest.prototype, "complete", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripePaymentRequest.prototype, "onPaymentResponse", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripePaymentRequest.prototype, "confirmPaymentIntent", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object, Object]), | ||
__metadata("design:returntype", Promise) | ||
], StripePaymentRequest.prototype, "confirmCardPayment", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", void 0) | ||
], StripePaymentRequest.prototype, "onShippingaddresschange", null); | ||
__decorate([ | ||
bound, | ||
__metadata("design:type", Function), | ||
__metadata("design:paramtypes", [Object]), | ||
__metadata("design:returntype", void 0) | ||
], StripePaymentRequest.prototype, "onShippingoptionchange", null); | ||
StripePaymentRequest = __decorate([ | ||
customElement('stripe-payment-request') | ||
], StripePaymentRequest); | ||
/** | ||
* @typedef {Object} ShippingOptionChangeEvent | ||
* @param {(options: stripe.paymentRequest.UpdateDetails) => void} updateWith | ||
* @param {stripe.paymentRequest.ShippingOption} shippingOption | ||
*/ | ||
/** @typedef {stripe.Error|stripe.PaymentIntentResponse|stripe.Token|stripe.Source} PaymentResponseOrError */ | ||
/** @typedef {(x: PaymentResponseOrError) => PaymentResponseOrError} PaymentResponseHandler */ | ||
/** @typedef {stripe.paymentRequest.StripeSourcePaymentResponse|stripe.paymentRequest.StripeTokenPaymentResponse|stripe.paymentRequest.StripePaymentMethodPaymentResponse} PaymentResponse */ | ||
customElements.define(StripePaymentRequest.is, StripePaymentRequest); | ||
export { StripePaymentRequest }; | ||
export { StripePaymentRequest, isStripeDisplayItem, isStripeShippingOption }; | ||
//# sourceMappingURL=stripe-payment-request.js.map |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
529604
71
7871
701
48
3
+ Addedtslib@^1.11.1
+ Addedtslib@1.14.1(transitive)
- Removed@open-wc/lit-helpers@^0.3.1
- Removed@open-wc/lit-helpers@0.3.12(transitive)
Updated@babel/runtime@^7.9.2
Updated@pacote/memoize@^1.1.2
Updated@types/stripe-v3@^3.1.17
Updatedlit-element@^2.3.1
Updatedpatch-package@^6.2.2