@kiva/kv-shop 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # kv-shop
2
+
3
+ A library of methods and components related to the Kiva Shop.
4
+
5
+ ## Install
6
+
7
+ Deployed:
8
+
9
+ ```bash
10
+ npm i @kiva/kv-shop
11
+ ```
12
+
13
+ Local:
14
+
15
+ ```bash
16
+ # Open kv-ui-elements folder in Terminal
17
+ npm link -w @kiva/kv-shop
18
+
19
+ # Open target local project folder in Terminal
20
+ npm link @kiva/kv-shop
21
+ ```
22
+
23
+ Extra step for Nuxt local development:
24
+
25
+ ```ts
26
+ // Open nuxt.config.ts in target project and add with your username
27
+ ...
28
+ vite: {
29
+ optimizeDeps: {
30
+ exclude: ['@kiva/kv-shop'],
31
+ },
32
+ server: {
33
+ fs: {
34
+ allow: ['/Users/username/kiva/kv-ui-elements'],
35
+ },
36
+ },
37
+ },
38
+ ...
39
+ ```
40
+
41
+ ## Lint
42
+
43
+ ```bash
44
+ npm run lint
45
+ ```
46
+
47
+ ## Build
48
+
49
+ ```bash
50
+ npm run build
51
+ ```
52
+
53
+ ## Contribution Guidelines
54
+
55
+ The Kiva UI project is bound by a [Code of Conduct](https://github.com/kiva/ui/blob/master/code_of_conduct.md).
56
+
57
+ Kiva welcomes outside contributions to our UI repository. If you have any ideas for a feature or improvement, create an issue and we can discuss whether it makes sense to create a pull request. Thanks for the help!
@@ -0,0 +1,40 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/basket.ts
20
+ var basket_exports = {};
21
+ __export(basket_exports, {
22
+ getBasketID: () => getBasketID,
23
+ setBasketID: () => setBasketID
24
+ });
25
+ module.exports = __toCommonJS(basket_exports);
26
+ var getCookieValue = (name) => {
27
+ if (typeof document !== void 0) {
28
+ return document.cookie.match(`(^|;)\\s*${name}\\s*=\\s*([^;]+)/`)?.pop() || "";
29
+ }
30
+ };
31
+ function getBasketID() {
32
+ return getCookieValue("kvbskt");
33
+ }
34
+ function setBasketID(basketId) {
35
+ }
36
+ // Annotate the CommonJS export names for ESM import in node:
37
+ 0 && (module.exports = {
38
+ getBasketID,
39
+ setBasketID
40
+ });
@@ -0,0 +1,4 @@
1
+ declare function getBasketID(): string;
2
+ declare function setBasketID(basketId: string): void;
3
+
4
+ export { getBasketID, setBasketID };
package/dist/basket.js ADDED
@@ -0,0 +1,8 @@
1
+ import {
2
+ getBasketID,
3
+ setBasketID
4
+ } from "./chunk-AEVGXKI6.js";
5
+ export {
6
+ getBasketID,
7
+ setBasketID
8
+ };
@@ -0,0 +1,116 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/basketItems.ts
30
+ var basketItems_exports = {};
31
+ __export(basketItems_exports, {
32
+ setTipDonation: () => setTipDonation
33
+ });
34
+ module.exports = __toCommonJS(basketItems_exports);
35
+ var import_client = require("@apollo/client");
36
+ var import_numeral = __toESM(require("numeral"), 1);
37
+
38
+ // src/basket.ts
39
+ var getCookieValue = (name) => {
40
+ if (typeof document !== void 0) {
41
+ return document.cookie.match(`(^|;)\\s*${name}\\s*=\\s*([^;]+)/`)?.pop() || "";
42
+ }
43
+ };
44
+ function getBasketID() {
45
+ return getCookieValue("kvbskt");
46
+ }
47
+
48
+ // src/shopError.ts
49
+ var ShopError = class extends Error {
50
+ constructor({ code, original }, ...params) {
51
+ super(...params);
52
+ if (Error.captureStackTrace) {
53
+ Error.captureStackTrace(this, ShopError);
54
+ }
55
+ this.name = "ShopError";
56
+ this.code = code;
57
+ this.original = original;
58
+ }
59
+ };
60
+ function parseShopError(error) {
61
+ const errorCode = error?.code ?? error?.name ?? "";
62
+ const errorMessage = typeof error === "string" ? error : error?.message ?? "";
63
+ if (errorCode === "invalidMethodParameter" && errorMessage.includes("paymentMethod.create")) {
64
+ return new ShopError({
65
+ code: "paymentMethod.create.invalidMethodParameter",
66
+ original: error
67
+ }, "There was a problem validating your payment information. Please double-check the details and try again.");
68
+ }
69
+ return new ShopError({
70
+ code: "shop.unknown",
71
+ original: error
72
+ }, "An unknown error occurred.");
73
+ }
74
+
75
+ // src/basketItems.ts
76
+ async function setTipDonation({ amount, apollo }) {
77
+ let data;
78
+ let error;
79
+ try {
80
+ const result = await apollo.mutate({
81
+ mutation: import_client.gql`mutation setTipDonation($price: Money!, $basketId: String) {
82
+ shop (basketId: $basketId) {
83
+ id
84
+ updateDonation (donation: {
85
+ price: $price,
86
+ isTip: true
87
+ })
88
+ {
89
+ id
90
+ price
91
+ isTip
92
+ }
93
+ }
94
+ }`,
95
+ variables: {
96
+ price: (0, import_numeral.default)(amount).format("0.00"),
97
+ basketId: getBasketID()
98
+ }
99
+ });
100
+ if (result.error || result.errors.length) {
101
+ error = result.error ?? result.errors[0];
102
+ } else {
103
+ data = result.data;
104
+ }
105
+ } catch (e) {
106
+ error = e;
107
+ }
108
+ if (error) {
109
+ throw parseShopError(error);
110
+ }
111
+ return data?.shop?.updateDonation;
112
+ }
113
+ // Annotate the CommonJS export names for ESM import in node:
114
+ 0 && (module.exports = {
115
+ setTipDonation
116
+ });
@@ -0,0 +1,7 @@
1
+ interface SetTipDonationOptions {
2
+ amount: string | number;
3
+ apollo: any;
4
+ }
5
+ declare function setTipDonation({ amount, apollo }: SetTipDonationOptions): Promise<any>;
6
+
7
+ export { SetTipDonationOptions, setTipDonation };
@@ -0,0 +1,8 @@
1
+ import {
2
+ setTipDonation
3
+ } from "./chunk-CBOAIFK6.js";
4
+ import "./chunk-AEVGXKI6.js";
5
+ import "./chunk-H35VQXDR.js";
6
+ export {
7
+ setTipDonation
8
+ };
@@ -0,0 +1,16 @@
1
+ // src/basket.ts
2
+ var getCookieValue = (name) => {
3
+ if (typeof document !== void 0) {
4
+ return document.cookie.match(`(^|;)\\s*${name}\\s*=\\s*([^;]+)/`)?.pop() || "";
5
+ }
6
+ };
7
+ function getBasketID() {
8
+ return getCookieValue("kvbskt");
9
+ }
10
+ function setBasketID(basketId) {
11
+ }
12
+
13
+ export {
14
+ getBasketID,
15
+ setBasketID
16
+ };
@@ -0,0 +1,51 @@
1
+ import {
2
+ getBasketID
3
+ } from "./chunk-AEVGXKI6.js";
4
+ import {
5
+ parseShopError
6
+ } from "./chunk-H35VQXDR.js";
7
+
8
+ // src/basketItems.ts
9
+ import { gql } from "@apollo/client";
10
+ import numeral from "numeral";
11
+ async function setTipDonation({ amount, apollo }) {
12
+ let data;
13
+ let error;
14
+ try {
15
+ const result = await apollo.mutate({
16
+ mutation: gql`mutation setTipDonation($price: Money!, $basketId: String) {
17
+ shop (basketId: $basketId) {
18
+ id
19
+ updateDonation (donation: {
20
+ price: $price,
21
+ isTip: true
22
+ })
23
+ {
24
+ id
25
+ price
26
+ isTip
27
+ }
28
+ }
29
+ }`,
30
+ variables: {
31
+ price: numeral(amount).format("0.00"),
32
+ basketId: getBasketID()
33
+ }
34
+ });
35
+ if (result.error || result.errors.length) {
36
+ error = result.error ?? result.errors[0];
37
+ } else {
38
+ data = result.data;
39
+ }
40
+ } catch (e) {
41
+ error = e;
42
+ }
43
+ if (error) {
44
+ throw parseShopError(error);
45
+ }
46
+ return data?.shop?.updateDonation;
47
+ }
48
+
49
+ export {
50
+ setTipDonation
51
+ };
@@ -0,0 +1,31 @@
1
+ // src/shopError.ts
2
+ var ShopError = class extends Error {
3
+ constructor({ code, original }, ...params) {
4
+ super(...params);
5
+ if (Error.captureStackTrace) {
6
+ Error.captureStackTrace(this, ShopError);
7
+ }
8
+ this.name = "ShopError";
9
+ this.code = code;
10
+ this.original = original;
11
+ }
12
+ };
13
+ function parseShopError(error) {
14
+ const errorCode = error?.code ?? error?.name ?? "";
15
+ const errorMessage = typeof error === "string" ? error : error?.message ?? "";
16
+ if (errorCode === "invalidMethodParameter" && errorMessage.includes("paymentMethod.create")) {
17
+ return new ShopError({
18
+ code: "paymentMethod.create.invalidMethodParameter",
19
+ original: error
20
+ }, "There was a problem validating your payment information. Please double-check the details and try again.");
21
+ }
22
+ return new ShopError({
23
+ code: "shop.unknown",
24
+ original: error
25
+ }, "An unknown error occurred.");
26
+ }
27
+
28
+ export {
29
+ ShopError,
30
+ parseShopError
31
+ };
@@ -0,0 +1,26 @@
1
+ // src/oneTimeCheckout.ts
2
+ import { gql } from "@apollo/client";
3
+ async function executeOneTimeCheckout({ apollo }) {
4
+ }
5
+ async function waitOnTransaction({ apollo, transactionId }) {
6
+ const result = await apollo.query({
7
+ query: gql`
8
+ query checkoutStatus($transactionId: String!, $visitorId: string) {
9
+ checkoutStatus(transactionId: $transactionId, visitorId: $visitorId) {
10
+ errorCode
11
+ errorMessage
12
+ status
13
+ transactionId
14
+ }
15
+ }
16
+ `,
17
+ variables: {
18
+ transactionId
19
+ }
20
+ });
21
+ }
22
+
23
+ export {
24
+ executeOneTimeCheckout,
25
+ waitOnTransaction
26
+ };
@@ -0,0 +1,160 @@
1
+ import {
2
+ ShopError,
3
+ parseShopError
4
+ } from "./chunk-H35VQXDR.js";
5
+
6
+ // src/useBraintreeDropIn.ts
7
+ import { gql } from "@apollo/client";
8
+ import numeral from "numeral";
9
+ import { ref } from "vue-demi";
10
+ var defaultPaymentTypes = ["paypal", "card", "applePay", "googlePay"];
11
+ async function getClientToken(apollo) {
12
+ const { data, error, errors } = await apollo.query({
13
+ query: gql`query getClientToken {
14
+ shop {
15
+ id
16
+ getClientToken(useCustomerId: true)
17
+ }
18
+ }`
19
+ });
20
+ if (error || errors.length) {
21
+ throw parseShopError(error ?? errors[0]);
22
+ }
23
+ return data?.shop?.getClientToken;
24
+ }
25
+ function useBraintreeDropIn() {
26
+ let instance;
27
+ let formattedAmount = "";
28
+ const paymentMethodRequestable = ref(false);
29
+ function getApplePaymentRequest(amount) {
30
+ return {
31
+ countryCode: "US",
32
+ currencyCode: "USD",
33
+ // merchantCapabilities: ['supports3DS'], // TODO: confirm/update
34
+ requiredBillingContactFields: ["postalAddress"],
35
+ // supportedNetworks: ['amex', 'discover', 'interac', 'jcb', 'masterCard', 'visa'], // TODO: confirm/update
36
+ total: {
37
+ label: "Kiva",
38
+ amount
39
+ }
40
+ };
41
+ }
42
+ function getGoogleTransactionInfo(amount) {
43
+ return {
44
+ totalPriceStatus: "FINAL",
45
+ totalPrice: amount,
46
+ currencyCode: "USD",
47
+ countryCode: "US"
48
+ };
49
+ }
50
+ function initDropInActions() {
51
+ if (instance.isPaymentMethodRequestable()) {
52
+ paymentMethodRequestable.value = true;
53
+ }
54
+ instance.on("paymentMethodRequestable", (event) => {
55
+ paymentMethodRequestable.value = true;
56
+ });
57
+ instance.on("noPaymentMethodRequestable", () => {
58
+ paymentMethodRequestable.value = false;
59
+ });
60
+ }
61
+ async function initDropIn({
62
+ amount,
63
+ authToken,
64
+ container,
65
+ googlePayMerchantId,
66
+ paymentTypes = [...defaultPaymentTypes],
67
+ preselectVaultedPaymentMethod = true,
68
+ paypalFlow = "checkout"
69
+ }) {
70
+ formattedAmount = numeral(amount).format("0.00");
71
+ const { default: DropIn } = await import("braintree-web-drop-in");
72
+ try {
73
+ instance = await DropIn.create({
74
+ authorization: authToken,
75
+ container,
76
+ dataCollector: {
77
+ kount: true
78
+ // Required if Kount fraud data collection is enabled
79
+ },
80
+ // vaultManager: true, - Useful for testing and removing payment methods easily.
81
+ paymentOptionPriority: paymentTypes,
82
+ preselectVaultedPaymentMethod,
83
+ card: {
84
+ vault: {
85
+ allowVaultCardOverride: true
86
+ }
87
+ },
88
+ paypal: {
89
+ flow: paypalFlow,
90
+ amount: formattedAmount,
91
+ currency: "USD",
92
+ buttonStyle: {
93
+ // @ts-ignore
94
+ color: "gold",
95
+ // @ts-ignore
96
+ shape: "rect",
97
+ // @ts-ignore
98
+ size: "responsive"
99
+ }
100
+ },
101
+ googlePay: {
102
+ googlePayVersion: 2,
103
+ merchantId: googlePayMerchantId,
104
+ transactionInfo: getGoogleTransactionInfo(formattedAmount),
105
+ button: {
106
+ allowedPaymentMethods: [{
107
+ type: "CARD",
108
+ // @ts-ignore
109
+ parameters: {
110
+ // allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'], // TODO: confirm/update
111
+ // allowedCardNetworks: ['AMEX', 'DISCOVER', 'INTERAC', 'JCB', 'MASTERCARD', 'VISA'], // TODO: confirm/update
112
+ billingAddressRequired: true,
113
+ billingAddressParameters: {
114
+ format: "FULL"
115
+ }
116
+ }
117
+ }]
118
+ }
119
+ },
120
+ applePay: {
121
+ displayName: "Kiva",
122
+ paymentRequest: getApplePaymentRequest(formattedAmount)
123
+ }
124
+ });
125
+ initDropInActions();
126
+ } catch (e) {
127
+ throw new ShopError({
128
+ code: "shop.braintreeDropinInitError",
129
+ original: e
130
+ }, "An Error has occured. Please refresh the page and try again.");
131
+ }
132
+ return instance;
133
+ }
134
+ async function requestPaymentMethod() {
135
+ if (instance.isPaymentMethodRequestable()) {
136
+ return instance.requestPaymentMethod();
137
+ }
138
+ }
139
+ function updateAmount(amount) {
140
+ const newAmount = numeral(amount).format("0.00");
141
+ if (newAmount !== formattedAmount) {
142
+ formattedAmount = newAmount;
143
+ instance?.updateConfiguration("paypal", "amount", formattedAmount);
144
+ instance?.updateConfiguration("googlePay", "transactionInfo", getGoogleTransactionInfo(formattedAmount));
145
+ instance?.updateConfiguration?.("applePay", "paymentRequest", getApplePaymentRequest(formattedAmount));
146
+ }
147
+ }
148
+ return {
149
+ initDropIn,
150
+ paymentMethodRequestable,
151
+ requestPaymentMethod,
152
+ updateAmount
153
+ };
154
+ }
155
+
156
+ export {
157
+ defaultPaymentTypes,
158
+ getClientToken,
159
+ useBraintreeDropIn
160
+ };
@@ -0,0 +1,104 @@
1
+ import {
2
+ ShopError,
3
+ parseShopError
4
+ } from "./chunk-H35VQXDR.js";
5
+
6
+ // src/subscriptionCheckout.ts
7
+ import { gql } from "@apollo/client";
8
+ async function checkSubscriptionStatus(apollo) {
9
+ const { data: subsData } = await apollo.query({
10
+ query: gql`query subscriptionStatus{
11
+ my {
12
+ id
13
+ subscriptions {
14
+ totalCount
15
+ }
16
+ autoDeposit {
17
+ id
18
+ isSubscriber
19
+ }
20
+ }
21
+ }`
22
+ });
23
+ if (!subsData?.my?.id) {
24
+ throw new ShopError({ code: "api.authenticationRequired" }, "You must be logged in to continue.");
25
+ }
26
+ if ((subsData?.my?.subscriptions?.totalCount ?? 0) > 0 || subsData?.my?.autoDeposit?.isSubscriber) {
27
+ throw new ShopError({ code: "shop.subscriptionExists" }, "You already have an existing Monthly Good subscription. Changes can be made in your subscription settings.");
28
+ }
29
+ if (subsData?.my?.autoDeposit?.id) {
30
+ throw new ShopError({ code: "shop.autoDepositExists" }, "You already have existing Auto Deposit settings. Changes can be made in your subscription settings.");
31
+ }
32
+ return true;
33
+ }
34
+ async function executeNewSubscriptionCheckout({
35
+ amount,
36
+ apollo,
37
+ dayOfMonth = (/* @__PURE__ */ new Date()).getDate(),
38
+ donateAmount,
39
+ paymentMethod
40
+ }) {
41
+ const amountRegex = new RegExp(/^\d+\.\d{2}$/);
42
+ if (!amountRegex.test(amount) || !amountRegex.test(donateAmount)) {
43
+ throw new ShopError({
44
+ code: "api.invalidMethodParameter"
45
+ }, "Please check that the amount is correct and try again.");
46
+ }
47
+ await checkSubscriptionStatus(apollo);
48
+ const { deviceData, nonce } = paymentMethod;
49
+ let data;
50
+ let error;
51
+ try {
52
+ const result = await apollo.query({
53
+ variables: {
54
+ dayOfMonth,
55
+ deviceData,
56
+ nonce
57
+ },
58
+ query: gql`mutation createAutoDepositSubscription(
59
+ $nonce: String!,
60
+ $deviceData: String,
61
+ $amount: Money!,
62
+ $donateAmount: Money!,
63
+ $dayOfMonth: Int!
64
+ ) {
65
+ my {
66
+ createAutoDeposit (
67
+ autoDeposit: {
68
+ amount: $amount,
69
+ donateAmount: $donateAmount,
70
+ dayOfMonth: $dayOfMonth,
71
+ },
72
+ deviceData: $deviceData,
73
+ paymentMethodNonce: $nonce
74
+ ) {
75
+ id amount donateAmount dayOfMonth status
76
+ }
77
+ }
78
+ }`
79
+ });
80
+ if (result.error || result.errors.length) {
81
+ error = result.error ?? result.errors[0];
82
+ } else {
83
+ data = result.data;
84
+ }
85
+ } catch (e) {
86
+ error = e;
87
+ }
88
+ if (error) {
89
+ const parsed = parseShopError(error);
90
+ if (parsed.code === "shop.unknown") {
91
+ throw new ShopError({
92
+ code: "shop.createAutoDepositError",
93
+ original: parsed
94
+ }, "There was a problem trying to setup your monthly deposit.");
95
+ }
96
+ throw parsed;
97
+ }
98
+ return data?.my?.createAutoDeposit;
99
+ }
100
+
101
+ export {
102
+ checkSubscriptionStatus,
103
+ executeNewSubscriptionCheckout
104
+ };