@godaddy/react
Version:
The `createCheckoutSession` function creates a new checkout session with GoDaddy's commerce API.
2,310 lines • 65.7 kB
JavaScript
import { initGraphQLTada } from "gql.tada";
import { ClientError, request } from "graphql-request";
//#region src/components/checkout/utils/case-conversion.ts
/**
* Convert kebab-case string to camelCase
* @example kebabToCamel('font-sans') // 'fontSans'
*/
function kebabToCamel(str) {
return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
}
/**
* Convert camelCase string to kebab-case
* @example camelToKebab('fontSans') // 'font-sans'
*/
function camelToKebab(str) {
return str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
}
/**
* Convert kebab-case CSS variables object to camelCase for GraphQL
* @param variables - Object with kebab-case keys
* @returns Object with camelCase keys
* @example
* convertCSSVariablesToCamelCase({ 'font-sans': 'Arial', 'secondary-background': '#fff' })
* // { fontSans: 'Arial', secondaryBackground: '#fff' }
*/
function convertCSSVariablesToCamelCase(variables) {
const result = {};
for (const [key, value] of Object.entries(variables)) if (value !== void 0) result[kebabToCamel(key)] = value;
return result;
}
/**
* Convert camelCase object keys to kebab-case (for GraphQL response to CSS variables)
* @param obj - Object with camelCase keys
* @returns Object with kebab-case keys typed as CSSVariables
* @example
* convertCamelCaseToKebabCase({ fontSans: 'Arial', secondaryBackground: '#fff' })
* // { 'font-sans': 'Arial', 'secondary-background': '#fff' }
*/
function convertCamelCaseToKebabCase(obj) {
const result = {};
for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[camelToKebab(key)] = value;
return result;
}
//#endregion
//#region src/lib/gql/gql-catalog-storefront.tada.ts
const graphql$2 = initGraphQLTada();
//#endregion
//#region src/lib/godaddy/catalog-storefront-queries.ts
const SkuGroupsQuery = graphql$2(`
query SkuGroups($first: Int, $after: String, $id: SKUGroupIdsFilter, $listId: ListIdFilter, $label: LabelFilter) {
skuGroups(first: $first, after: $after, id: $id, listId: $listId, label: $label) {
edges {
cursor
node {
id
name
label
description
htmlDescription
type
priceRange {
min
max
}
compareAtPriceRange {
min
max
}
mediaObjects(first: 25) {
edges {
node {
url
type
}
}
}
attributes {
edges {
node {
id
name
label
description
htmlDescription
values(first: 50) {
edges {
node {
id
name
label
}
}
}
}
}
}
skus(first: 2) {
edges {
node {
id
label
name
prices(first: 1) {
edges {
node {
value {
currencyCode
}
}
}
}
inventoryCounts {
edges {
node {
id
quantity
type
}
}
}
}
}
}
}
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
totalCount
}
}
`);
const SkuGroupQuery = graphql$2(`
query SkuGroup($id: String!, $first: Int, $attributeValues: [String!] = []) {
skuGroup(id: $id) {
id
name
label
description
htmlDescription
type
priceRange {
min
max
}
compareAtPriceRange {
min
max
}
mediaObjects(first: 25) {
edges {
node {
url
type
}
}
}
attributes {
edges {
node {
id
name
label
description
htmlDescription
values(first: 50) {
edges {
node {
id
name
label
}
}
}
}
}
}
skus(
attributeValues: { has: $attributeValues }
first: $first
) {
edges {
node {
id
label
name
prices(first: 1) {
edges {
node {
value {
currencyCode
}
}
}
}
inventoryCounts {
edges {
node {
id
quantity
type
}
}
}
}
}
}
}
}
`);
const SkuQuery = graphql$2(`
query Sku($id: String!) {
sku(id: $id) {
id
label
name
description
htmlDescription
code
prices {
edges {
node {
id
value {
value
currencyCode
}
compareAtValue {
value
currencyCode
}
}
}
}
inventoryCounts {
edges {
node {
id
quantity
type
}
}
}
mediaObjects {
edges {
node {
id
url
type
label
position
}
}
}
attributeValues {
edges {
node {
id
name
label
}
}
}
}
}
`);
//#endregion
//#region src/lib/gql/gql-orders-storefront.tada.ts
const graphql$1 = initGraphQLTada();
//#endregion
//#region src/lib/godaddy/orders-storefront-mutations.ts
const AddCartOrderMutation = graphql$1(`
mutation AddCartOrder($input: AddDraftOrderInput!) {
addDraftOrder(input: $input) {
id
customerId
createdAt
updatedAt
context {
storeId
channelId
}
lineItems {
id
name
quantity
skuId
type
fulfillmentMode
totals {
subTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
}
}
totals {
subTotal {
value
currencyCode
}
shippingTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
total {
value
currencyCode
}
}
}
}
`);
const AddLineItemBySkuIdMutation = graphql$1(`
mutation AddLineItemBySkuId($input: AddLineItemInput!) {
addLineItemBySkuId(input: $input) {
id
name
quantity
skuId
type
fulfillmentMode
details {
productAssetUrl
sku
unitOfMeasure
selectedOptions {
attribute
values
}
selectedAddons {
attribute
sku
values {
name
costAdjustment {
value
currencyCode
}
}
}
}
totals {
subTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
}
discounts {
id
name
code
amount {
value
currencyCode
}
}
taxes {
id
name
amount {
value
currencyCode
}
ratePercentage
}
createdAt
updatedAt
}
}
`);
const UpdateCartOrderMutation = graphql$1(`
mutation UpdateCartOrder($input: UpdateDraftOrderInput!) {
updateDraftOrder(input: $input) {
id
customerId
createdAt
updatedAt
context {
storeId
channelId
}
lineItems {
id
name
quantity
skuId
type
fulfillmentMode
totals {
subTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
}
}
totals {
subTotal {
value
currencyCode
}
shippingTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
total {
value
currencyCode
}
}
}
}
`);
const DeleteLineItemByIdMutation = graphql$1(`
mutation DeleteLineItemById($id: ID!, $orderId: ID!) {
deleteLineItemById(id: $id, orderId: $orderId)
}
`);
const ApplyDiscountCodesMutation = graphql$1(`
mutation ApplyDiscountCodes($input: ApplyDiscountCodesInput!) {
applyDiscountCodes(input: $input) {
id
discounts {
id
name
code
amount {
value
currencyCode
}
ratePercentage
appliedBeforeTax
}
totals {
subTotal {
value
currencyCode
}
shippingTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
productDiscountTotal {
value
currencyCode
}
shippingDiscountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
total {
value
currencyCode
}
}
}
}
`);
const UpdateLineItemByIdMutation = graphql$1(`
mutation UpdateLineItemById($input: UpdateLineItemByIdInput!) {
updateLineItemById(input: $input) {
id
name
quantity
skuId
type
fulfillmentMode
details {
productAssetUrl
sku
unitOfMeasure
}
totals {
subTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
}
updatedAt
}
}
`);
//#endregion
//#region src/lib/godaddy/orders-storefront-queries.ts
const GetCartOrderQuery = graphql$1(`
query GetCartOrder($id: ID!) {
orderById(id: $id) {
id
customerId
createdAt
updatedAt
context {
storeId
channelId
}
lineItems {
id
name
quantity
skuId
type
fulfillmentMode
details {
productAssetUrl
sku
unitOfMeasure
selectedOptions {
attribute
values
}
selectedAddons {
attribute
sku
values {
name
costAdjustment {
value
currencyCode
}
}
}
}
totals {
subTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
}
discounts {
id
name
code
amount {
value
currencyCode
}
ratePercentage
}
taxes {
id
name
amount {
value
currencyCode
}
ratePercentage
}
notes {
id
content
author
authorType
}
}
totals {
subTotal {
value
currencyCode
}
shippingTotal {
value
currencyCode
}
taxTotal {
value
currencyCode
}
discountTotal {
value
currencyCode
}
productDiscountTotal {
value
currencyCode
}
shippingDiscountTotal {
value
currencyCode
}
feeTotal {
value
currencyCode
}
total {
value
currencyCode
}
}
discounts {
id
name
code
amount {
value
currencyCode
}
ratePercentage
appliedBeforeTax
}
taxes {
id
name
amount {
value
currencyCode
}
ratePercentage
included
exempted
}
shipping {
firstName
lastName
email
phone
companyName
address {
addressLine1
addressLine2
addressLine3
adminArea1
adminArea2
adminArea3
adminArea4
postalCode
countryCode
}
}
notes {
id
content
author
authorType
createdAt
}
tags
}
}
`);
//#endregion
//#region src/lib/graphql-with-errors.ts
var GraphQLErrorWithCodes = class extends Error {
constructor(errors) {
const errorMessage = errors.length === 1 ? `${errors[0].message || "Unknown error"}` : `${errors.map((e) => e.message).filter(Boolean).join("; ")}`;
super(errorMessage);
this.errors = errors;
this.name = "GraphQLErrorWithCodes";
}
get codes() {
return this.errors.map((e) => e.code).filter(Boolean);
}
get messages() {
return this.errors.map((e) => e.message).filter(Boolean);
}
};
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getPaymentActionRequiredResult(error) {
if (!(error instanceof GraphQLErrorWithCodes)) return void 0;
for (const graphqlError of error.errors) {
if (graphqlError.code !== "PAYMENT_ACTION_REQUIRED") continue;
const paymentResult = graphqlError.extensions?.paymentResult;
if (!isRecord(paymentResult) || paymentResult.status !== "ACTION_REQUIRED") continue;
const nextStep = paymentResult.nextStep;
if (!isRecord(nextStep) || typeof nextStep.type !== "string") continue;
return paymentResult;
}
}
async function graphqlRequestWithErrors(endpoint, query, variables, headers) {
try {
return await request(endpoint, query, variables, headers);
} catch (err) {
if (err instanceof ClientError && err.response?.errors?.length) throw new GraphQLErrorWithCodes(err.response.errors.map((e) => ({
message: e.message,
code: e.extensions?.code,
extensions: e.extensions,
path: e.extensions?.path
})));
throw err;
}
}
//#endregion
//#region src/lib/gql/gql-checkout.tada.ts
const graphql = initGraphQLTada();
//#endregion
//#region src/lib/godaddy/checkout-mutations.ts
const CreateCheckoutSessionMutation = graphql(`
mutation CreateCheckoutSession($input: MutationCreateCheckoutSessionInput!) {
createCheckoutSession(input: $input) {
id
token
url
sourceApp
returnUrl
successUrl
storeId
businessId
channelId
customerId
storeName
environment
enableTips
tips {
default {
amounts
percentages
}
thresholds {
minSubtotal
maxSubtotal
amounts
percentages
}
}
enabledLocales
enableSurcharge
enableLocalPickup
enableShipping
enablePhoneCollection
enableNotesCollection
enablePromotionCodes
enableTaxCollection
enableShippingAddressCollection
enableBillingAddressCollection
enableAddressAutocomplete
appearance {
theme
variables {
fontSans
fontSerif
fontMono
defaultFontFamily
background
secondaryBackground
foreground
card
cardForeground
popover
popoverForeground
primary
primaryForeground
secondary
secondaryForeground
muted
mutedForeground
accent
accentForeground
destructive
destructiveForeground
border
input
ring
radius
}
}
experimental_rules {
gopay_override {
enabled
goPayAppId
}
}
shipping {
originAddress {
addressLine1
addressLine2
addressLine3
postalCode
countryCode
adminArea1
adminArea2
adminArea3
adminArea4
}
}
paymentMethods {
card {
processor
checkoutTypes
}
ccavenue {
processor
checkoutTypes
}
express {
processor
checkoutTypes
}
applePay {
processor
checkoutTypes
}
googlePay {
processor
checkoutTypes
}
paypal {
processor
checkoutTypes
}
paze {
processor
checkoutTypes
}
offline {
processor
checkoutTypes
}
mercadopago {
processor
checkoutTypes
}
ach {
processor
checkoutTypes
}
}
draftOrder {
id
statuses {
status
}
totals {
total {
currencyCode
value
}
}
}
locations {
id
isDefault
address {
addressLine1
addressLine2
addressLine3
postalCode
countryCode
adminArea1
adminArea2
adminArea3
adminArea4
}
operatingHours {
pickupWindowInDays
pickupMode
leadTime
pickupSlotInterval
timeZone
hours {
monday {
enabled
openTime
closeTime
}
tuesday {
enabled
openTime
closeTime
}
wednesday {
enabled
openTime
closeTime
}
thursday {
enabled
openTime
closeTime
}
friday {
enabled
openTime
closeTime
}
saturday {
enabled
openTime
closeTime
}
sunday {
enabled
openTime
closeTime
}
}
}
}
defaultOperatingHours {
pickupWindowInDays
pickupMode
leadTime
pickupSlotInterval
timeZone
hours {
monday {
enabled
openTime
closeTime
}
tuesday {
enabled
openTime
closeTime
}
wednesday {
enabled
openTime
closeTime
}
thursday {
enabled
openTime
closeTime
}
friday {
enabled
openTime
closeTime
}
saturday {
enabled
openTime
closeTime
}
sunday {
enabled
openTime
closeTime
}
}
}
}
}
`);
const VerifyCheckoutSessionAddressMutation = graphql(`
mutation VerifyCheckoutSessionAddress($input: MutationVerifyAddressInput!) {
verifyAddress(input: $input) {
addressLine1
addressLine2
addressLine3
postalCode
countryCode
adminArea1
adminArea2
adminArea3
adminArea4
}
}
`);
const UpdateCheckoutSessionDraftOrderMutation = graphql(`
mutation UpdateCheckoutSessionDraftOrder($input: MutationUpdateCheckoutSessionDraftOrderInput!) {
updateCheckoutSessionDraftOrder(input: $input) {
id
totals {
discountTotal {
currencyCode
value
}
feeTotal {
currencyCode
value
}
shippingTotal {
currencyCode
value
}
subTotal {
currencyCode
value
}
taxTotal {
currencyCode
value
}
total {
currencyCode
value
}
}
}
}
`);
const CalculateCheckoutSessionTaxesMutation = graphql(`
mutation CalculateCheckoutSessionTaxes($destination: TaxDestinationAddressInput) {
calculateCheckoutSessionTaxes(destination: $destination) {
totalTaxAmount {
value
currencyCode
}
}
}
`);
const ApplyCheckoutSessionDiscountMutation = graphql(`
mutation ApplyCheckoutSessionDiscount($input: MutationApplyCheckoutSessionDiscountInput!) {
applyCheckoutSessionDiscount(input: $input) {
id
lineItems {
externalId
fulfillmentMode
id
name
productId
quantity
status
tags
type
discounts {
amount {
currencyCode
value
}
appliedBeforeTax
code
id
name
ratePercentage
}
fees {
appliedBeforeTax
id
name
ratePercentage
}
totals {
discountTotal {
currencyCode
value
}
feeTotal {
currencyCode
value
}
subTotal {
currencyCode
value
}
taxTotal {
currencyCode
value
}
}
unitAmount {
currencyCode
value
}
}
shippingLines {
id
discounts {
id
amount {
currencyCode
value
}
appliedBeforeTax
code
}
}
discounts {
amount {
currencyCode
value
}
appliedBeforeTax
code
id
name
ratePercentage
}
totals {
discountTotal {
currencyCode
value
}
total {
currencyCode
value
}
}
}
}
`);
const ConfirmCheckoutSessionMutation = graphql(`
mutation ConfirmCheckoutSession($input: MutationConfirmCheckoutSessionInput!, $sessionId: String!) {
confirmCheckoutSession(input: $input, sessionId: $sessionId) {
status
}
}
`);
const ApplyCheckoutSessionShippingMethodMutation = graphql(`
mutation ApplyCheckoutSessionShippingMethod($input: [ApplyShippingMethodInput!]!) {
applyCheckoutSessionShippingMethod(input: $input) {
status
draftOrder {
totals {
shippingTotal {
currencyCode
value
}
}
}
}
}
`);
const ApplyCheckoutSessionDeliveryMethodMutation = graphql(`
mutation ApplyCheckoutSessionDeliveryMethod($input: MutationApplyCheckoutSessionDeliveryMethodInput!) {
applyCheckoutSessionDeliveryMethod(input: $input) {
status
}
}
`);
const ApplyCheckoutSessionFulfillmentLocationMutation = graphql(`
mutation ApplyCheckoutSessionFulfillmentLocation($input: MutationApplyCheckoutSessionFulfillmentLocationInput!) {
applyCheckoutSessionFulfillmentLocation(input: $input) {
status
}
}
`);
const ExchangeCheckoutTokenMutation = graphql(`
mutation ExchangeCheckoutToken($input: MutationExchangeCheckoutTokenInput!) {
exchangeCheckoutToken(input: $input) {
jwt
expiresAt
expiresIn
}
}
`);
const RefreshCheckoutTokenMutation = graphql(`
mutation RefreshCheckoutToken {
refreshCheckoutToken {
jwt
expiresAt
expiresIn
}
}
`);
const AuthorizeCheckoutSessionMutation = graphql(`
mutation AuthorizeCheckoutSession($input: MutationAuthorizeCheckoutSessionInput!) {
authorizeCheckoutSession(input: $input) {
... on SaleTransaction {
transactionRefNum
}
... on AuthorizeTransaction {
transactionRefNum
}
}
}
`);
//#endregion
//#region src/lib/godaddy/checkout-queries.ts
const GetCheckoutSessionQuery = graphql(`
query GetCheckoutSession {
checkoutSession {
id
token
url
sourceApp
returnUrl
successUrl
storeId
channelId
businessId
customerId
storeName
environment
enableTips
tips {
default {
amounts
percentages
}
thresholds {
minSubtotal
maxSubtotal
amounts
percentages
}
}
enabledLocales
enableSurcharge
enableLocalPickup
enableShipping
enablePhoneCollection
enableNotesCollection
enablePromotionCodes
enableTaxCollection
enableShippingAddressCollection
enableBillingAddressCollection
enableAddressAutocomplete
appearance {
theme
variables {
fontSans
fontSerif
fontMono
defaultFontFamily
background
secondaryBackground
foreground
card
cardForeground
popover
popoverForeground
primary
primaryForeground
secondary
secondaryForeground
muted
mutedForeground
accent
accentForeground
destructive
destructiveForeground
border
input
ring
radius
}
}
experimental_rules {
gopay_override {
enabled
goPayAppId
}
}
enabledStoreApplications {
id
name
release {
id
version
uiExtensions {
id
applicationId
releaseId
name
handle
type
target
}
}
}
shipping {
originAddress {
addressLine1
addressLine2
addressLine3
postalCode
countryCode
adminArea1
adminArea2
adminArea3
adminArea4
}
}
paymentMethods {
card {
processor
checkoutTypes
}
ccavenue {
processor
checkoutTypes
}
express {
processor
checkoutTypes
}
applePay {
processor
checkoutTypes
}
googlePay {
processor
checkoutTypes
}
paypal {
processor
checkoutTypes
}
paze {
processor
checkoutTypes
}
offline {
processor
checkoutTypes
}
ach {
processor
checkoutTypes
}
mercadopago {
processor
checkoutTypes
}
}
locations {
id
isDefault
address {
addressLine1
addressLine2
addressLine3
postalCode
countryCode
adminArea1
adminArea2
adminArea3
adminArea4
}
operatingHours {
pickupWindowInDays
pickupMode
leadTime
pickupSlotInterval
timeZone
hours {
monday {
enabled
openTime
closeTime
}
tuesday {
enabled
openTime
closeTime
}
wednesday {
enabled
openTime
closeTime
}
thursday {
enabled
openTime
closeTime
}
friday {
enabled
openTime
closeTime
}
saturday {
enabled
openTime
closeTime
}
sunday {
enabled
openTime
closeTime
}
}
}
}
defaultOperatingHours {
pickupWindowInDays
pickupMode
leadTime
pickupSlotInterval
timeZone
hours {
monday {
enabled
openTime
closeTime
}
tuesday {
enabled
openTime
closeTime
}
wednesday {
enabled
openTime
closeTime
}
thursday {
enabled
openTime
closeTime
}
friday {
enabled
openTime
closeTime
}
saturday {
enabled
openTime
closeTime
}
sunday {
enabled
openTime
closeTime
}
}
}
draftOrder {
id
statuses {
fulfillmentStatus
paymentStatus
status
}
totals {
taxTotal {
currencyCode
value
}
shippingTotal {
currencyCode
value
}
feeTotal {
currencyCode
value
}
subTotal {
currencyCode
value
}
discountTotal {
currencyCode
value
}
total {
currencyCode
value
}
}
}
}
}
`);
const GetEnabledStoreUiExtensionsQuery = graphql(`
query GetEnabledStoreUiExtensions($storeId: String!, $target: String!) {
enabledStoreUiExtensions(storeId: $storeId, target: $target) {
id
applicationId
releaseId
name
handle
type
target
}
}
`);
const AddressMatchesQuery = graphql(`
query CheckoutSessionWithAddressMatches($query: String!) {
checkoutSession {
id
addresses(input: { query: $query }) {
addressLine1
addressLine2
adminArea1
adminArea3
countryCode
postalCode
}
}
}
`);
const CheckoutOrderStatusQuery = graphql(`
query CheckoutOrderStatus {
checkoutSession {
id
orderStatus {
status
paymentStatus
}
}
}
`);
const DraftOrderQuery = graphql(`
query DraftOrder {
checkoutSession {
id
draftOrder {
id
statuses {
fulfillmentStatus
paymentStatus
status
}
shippingLines {
id
name
requestedProvider
requestedService
amount {
currencyCode
value
}
discounts {
id
name
amount {
value
currencyCode
}
code
ratePercentage
appliedBeforeTax
metafields {
key
value
}
}
}
lineItems {
externalId
fulfillmentMode
id
name
productId
quantity
status
tags
type
metafields {
key
type
value
}
details {
productAssetUrl
selectedAddons {
attribute
sku
values {
costAdjustment {
currencyCode
value
}
name
}
}
selectedOptions {
attribute
values
}
sku
unitOfMeasure
}
discounts {
amount {
currencyCode
value
}
appliedBeforeTax
code
id
name
ratePercentage
}
fees {
appliedBeforeTax
id
name
ratePercentage
}
notes {
authorType
content
id
}
taxes {
exempted
id
included
name
ratePercentage
}
totals {
discountTotal {
currencyCode
value
}
feeTotal {
currencyCode
value
}
subTotal {
currencyCode
value
}
taxTotal {
currencyCode
value
}
}
unitAmount {
currencyCode
value
}
}
shipping {
firstName,
lastName,
email,
phone,
address {
addressLine1
addressLine2
addressLine3
adminArea1
adminArea2
adminArea3
adminArea4
countryCode
postalCode
}
}
billing {
firstName,
lastName,
email,
phone,
address {
addressLine1
addressLine2
addressLine3
adminArea1
adminArea2
adminArea3
adminArea4
countryCode
postalCode
}
}
notes {
authorType
content
id
}
discounts {
amount {
currencyCode
value
}
appliedBeforeTax
code
id
name
ratePercentage
}
taxes {
amount {
value
}
included
}
totals {
discountTotal {
currencyCode
value
}
feeTotal {
currencyCode
value
}
shippingTotal {
currencyCode
value
}
subTotal {
currencyCode
value
}
taxTotal {
currencyCode
value
}
total {
currencyCode
value
}
}
}
}
}
`);
const DraftOrderSkusQuery = graphql(`
query Skus {
checkoutSession {
id
skus(first: 100) {
edges {
node {
id
code
name
label
description
status
weight,
unitOfWeight
disableShipping
htmlDescription
prices {
currencyCode
value
}
attributes {
id
name
label
values {
id
name
label
}
}
attributeValues {
id
name
label
}
}
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
}
}
`);
const DraftOrderTaxesQuery = graphql(`
query Taxes($destination: TaxDestinationAddressInput, $lines: [TaxLineInput!], $discountAdjustments: CalculatedAdjustmentsInput) {
checkoutSession {
id
storeId
draftOrder {
id
calculatedTaxes(destination: $destination, lines: $lines, discountAdjustments: $discountAdjustments) {
totalTaxAmount {
currencyCode
value
}
taxAmounts {
rate {
id
name
label
calculationMethod
value {
appliedPercentage
appliedAmount {
currencyCode
value
}
amount {
currencyCode
value
}
percentage
}
}
totalTaxAmount {
currencyCode
value
}
}
lines {
calculationLine {
id
}
totalTaxAmount {
currencyCode
value
}
taxAmounts {
rate {
id
name
calculationMethod
}
totalTaxAmount {
currencyCode
value
}
}
}
}
}
}
}
`);
const DraftOrderShippingRatesQuery = graphql(`
query ShippingRates($destination: DestinationAddressInput) {
checkoutSession {
id
storeId
draftOrder {
id
calculatedShippingRates(destination: $destination) {
rates {
carrierCode
cost {
value
currencyCode
}
description
displayName
features
maxDeliveryDate
minDeliveryDate
serviceCode
}
}
}
}
}
`);
const DraftOrderPriceAdjustmentsQuery = graphql(`
query PriceAdjustments($discountCodes: [String!], $shippingLines: [PriceAdjustmentShippingLineInput!]) {
checkoutSession {
id
storeId
draftOrder {
id
calculatedAdjustments(discountCodes: $discountCodes, shippingLines: $shippingLines) {
adjustments {
adjustment {
... on CalculatedDiscount {
description
id
label
name
}
... on CalculatedFee {
description
id
label
name
}
}
totalAmount {
currencyCode
value
}
}
lines {
calculationLine {
id
type
}
adjustments {
adjustment {
... on CalculatedDiscount {
description
id
label
name
}
... on CalculatedFee {
description
id
label
name
}
}
totalAmount {
currencyCode
value
}
}
totalDiscountAmount {
currencyCode
value
}
totalFeeAmount {
currencyCode
value
}
}
totalDiscountAmount {
currencyCode
value
}
totalFeeAmount {
currencyCode
value
}
}
}
}
}
`);
//#endregion
//#region src/lib/godaddy/godaddy.ts
function getHostByEnvironment(apiHost) {
return `https://checkout.commerce.${apiHost || "api.godaddy.com"}`;
}
function getApiHostByEnvironment(apiHost, endpoint) {
return `https://${apiHost || "api.godaddy.com"}${endpoint ? endpoint : ""}`;
}
async function createCheckoutSession(input, { accessToken, apiHost, endpoint }) {
if (!accessToken) throw new Error("No public access token provided");
let convertedVariables;
if (input.appearance?.variables) {
const variables = input.appearance.variables;
if ("checkout" in variables) convertedVariables = convertCSSVariablesToCamelCase(variables.checkout);
else convertedVariables = convertCSSVariablesToCamelCase(variables);
}
const { appearance,...restInput } = input;
const graphqlInput = {
...restInput,
...appearance && { appearance: {
theme: appearance.theme,
...convertedVariables && { variables: convertedVariables }
} }
};
return (await graphqlRequestWithErrors(endpoint ? getApiHostByEnvironment(apiHost, endpoint) : getHostByEnvironment(apiHost), CreateCheckoutSessionMutation, { input: graphqlInput }, { Authorization: `Bearer ${accessToken}` })).createCheckoutSession;
}
async function exchangeCheckoutToken(input, apiHost) {
if (!input.sessionId || !input.token) throw new Error("No session ID or token provided");
return (await graphqlRequestWithErrors(getHostByEnvironment(apiHost), ExchangeCheckoutTokenMutation, { input })).exchangeCheckoutToken;
}
async function refreshCheckoutToken(accessToken, apiHost) {
if (!accessToken) throw new Error("No access token provided");
return (await graphqlRequestWithErrors(getHostByEnvironment(apiHost), RefreshCheckoutTokenMutation, {}, { Authorization: `Bearer ${accessToken}` })).refreshCheckoutToken;
}
async function getCheckoutSession({ accessToken }, apiHost) {
return (await graphqlRequestWithErrors(getHostByEnvironment(apiHost), GetCheckoutSessionQuery, {}, { Authorization: `Bearer ${accessToken}` })).checkoutSession;
}
async function getEnabledStoreUiExtensions(input, apiHost) {
return (await graphqlRequestWithErrors(getHostByEnvironment(apiHost), GetEnabledStoreUiExtensionsQuery, input, { "x-store-id": input.storeId })).enabledStoreUiExtensions;
}
async function getAddressMatches(input, sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, AddressMatchesQuery, input, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, AddressMatchesQuery, input, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function getDraftOrder(sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderQuery, void 0, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderQuery, void 0, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function getCheckoutOrderStatus(sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, CheckoutOrderStatusQuery, void 0, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, CheckoutOrderStatusQuery, void 0, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function getDraftOrderTaxes(sessionOrAuth, { destination, lines, discountAdjustments }, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderTaxesQuery, {
destination,
lines,
discountAdjustments
}, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderTaxesQuery, {
destination,
lines,
discountAdjustments
}, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
async function updateDraftOrder(input, sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, UpdateCheckoutSessionDraftOrderMutation, { input }, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, UpdateCheckoutSessionDraftOrderMutation, { input }, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
async function getProductsFromOrderSkus(sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderSkusQuery, void 0, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderSkusQuery, void 0, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function updateDraftOrderTaxes(sessionOrAuth, destination, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, CalculateCheckoutSessionTaxesMutation, { destination }, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, CalculateCheckoutSessionTaxesMutation, { destination }, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function applyDiscount(discountCodes, sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, ApplyCheckoutSessionDiscountMutation, { input: { discountCodes } }, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, ApplyCheckoutSessionDiscountMutation, {
input: { discountCodes },
sessionId: session.id
}, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function applyShippingMethod(shippingMethods, sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, ApplyCheckoutSessionShippingMethodMutation, { input: [...shippingMethods] }, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, ApplyCheckoutSessionShippingMethodMutation, { input: [...shippingMethods] }, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function confirmCheckout(input, sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, ConfirmCheckoutSessionMutation, {
input,
sessionId: sessionOrAuth.sessionId
}, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, ConfirmCheckoutSessionMutation, {
input,
sessionId: session.id
}, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function authorizeCheckoutSession(input, sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, AuthorizeCheckoutSessionMutation, { input }, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, AuthorizeCheckoutSessionMutation, { input }, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function getDraftOrderShippingMethods(sessionOrAuth, destination, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderShippingRatesQuery, { destination }, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderShippingRatesQuery, { destination }, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function getDraftOrderPriceAdjustments(sessionOrAuth, discountCodes, shippingLines, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderPriceAdjustmentsQuery, {
shippingLines,
discountCodes
}, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, DraftOrderPriceAdjustmentsQuery, {
shippingLines,
discountCodes
}, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function applyFulfillmentLocation(input, sessionOrAuth, apiHost) {
const GODADDY_HOST = getHostByEnvironment(apiHost);
if (sessionOrAuth && "accessToken" in sessionOrAuth) {
if (!sessionOrAuth.accessToken) throw new Error("No access token provided");
return graphqlRequestWithErrors(GODADDY_HOST, ApplyCheckoutSessionFulfillmentLocationMutation, { input }, { Authorization: `Bearer ${sessionOrAuth.accessToken}` });
}
const session = sessionOrAuth;
if (!session?.token || !session?.id) throw new Error("No session token or ID provided");
return graphqlRequestWithErrors(GODADDY_HOST, ApplyCheckoutSessionFulfillmentLocationMutation, { input }, {
"x-session-token": `${session.token}`,
"x-session-id": session.id,
"x-store-id": session.storeId
});
}
function getSkuGroups(input, storeId, clientId, apiHost) {
return graphqlRequestWithErrors(getApiHostByEnvironment(apiHost, `/v2/commerce/stores/${storeId}/catalog-subgraph/storefront`), SkuGroupsQuery, input, {
"X-Store-ID": storeId,
"X-Client-ID": clientId
});
}
function getSkuGroup(input, storeId, clientId, apiHost) {
return graphqlRequestWithErrors(getApiHostByEnvironment(apiHost, `/v2/commerce/stores/${storeId}/catalog-subgraph/storefront`), SkuGroupQuery, input, {
"X-Store-ID": storeId,
"X-Client-ID": clientId
});
}
function getSku(input, storeId, clientId, apiHost) {
return graphqlRequestWithErrors(getApiHostByEnvironment(apiHost, `/v2/commerce/stores/${storeId}/catalog-subgraph/storefront`), SkuQuery, input, {
"X-Store-ID": storeId,
"X-Client-ID": clientId
});
}
function createCartOrder(input, storeId, clientId, apiHost) {
return graphqlRequestWithErrors(getApiHostByEnvironment(apiHost, `/v1/commerce/order-storefront-subgraph`), AddCartOrderMutation, { input }, {
"X-Store-ID": storeId,
"X-Client-ID": clientId
});
}
function getCartOrder(orderId, storeId, clientId, apiHost) {
return graphqlRequestWithErrors(getApiHostByEnvironment(apiHost, `/v1/commerce/order-storefront-subgraph`), GetCartOrderQuery, { id: orderId }, {
"X-Store-ID": storeId,
"X-Client-ID": clientId
});
}
function addCartLineItem(input, storeId, clientId, apiHost) {
return graphqlRequestWithErrors(getApiHostByEnvironment(apiHost, `/v1/commerce/order-storefront-subgraph`), AddLineItemBySkuIdMutation, { input }, {
"X-Store-ID": storeId,
"X-Client-ID": clientId
});
}
function deleteCartLineItem(input, storeId, clientId, apiHost) {
return graphqlRequestWithErrors(getApiHostByEnvironment(apiHost, `/v1/commerce/order-storefront-subgraph`), DeleteLineItemByIdMutation, input, {
"X-Store-ID": storeId,
"X-Client-ID": clientId
});
}
//#endregion
export { getSkuGroups as C, GraphQLErrorWithCodes as D, updateDraftOrderTaxes as E, getPaymentActionRequiredResult as O, getSkuGroup as S, updateDraftOrder as T, getDraftOrderShippingMethods as _, authorizeCheckoutSession as a, getProductsFromOrderSkus as b, createCheckoutSession as c, getAddressMatches as d, getCartOrder as f, getDraftOrderPriceAdjustments as g, getDraftOrder as h, applyShippingMethod as i, convertCamelCaseToKebabCase as k, deleteCartLineItem as l, getCheckoutSession as m, applyDiscount as n, confirmCheckout as o, getCheckoutOrderStatus as p, applyFulfillmentLocation as r, createCartOrder as s, addCartLineItem as t, exchangeCheckoutToken as u, getDraftOrderTaxes as v, refreshCheckoutToken as w, getSku as x, getEnabledStoreUiExtensions as y };