content
stringlengths
28
1.34M
import { Parent, ResolveField, Resolver } from '@nestjs/graphql'; import { AuthenticationMethod as AuthenticationMethodType } from '@vendure/common/lib/generated-types'; import { NATIVE_AUTH_STRATEGY_NAME } from '../../../config/auth/native-authentication-strategy'; import { AuthenticationMethod } from '../../../entity/authentication-method/authentication-method.entity'; import { ExternalAuthenticationMethod } from '../../../entity/authentication-method/external-authentication-method.entity'; import { User } from '../../../entity/user/user.entity'; import { UserService } from '../../../service/services/user.service'; import { RequestContext } from '../../common/request-context'; import { Ctx } from '../../decorators/request-context.decorator'; @Resolver('User') export class UserEntityResolver { constructor(private userService: UserService) {} @ResolveField() async authenticationMethods( @Ctx() ctx: RequestContext, @Parent() user: User, ): Promise<AuthenticationMethodType[]> { let methodEntities: AuthenticationMethod[] = []; if (user.authenticationMethods) { methodEntities = user.authenticationMethods; } methodEntities = await this.userService .getUserById(ctx, user.id) .then(u => u?.authenticationMethods ?? []); return methodEntities.map(m => ({ ...m, id: m.id.toString(), strategy: m instanceof ExternalAuthenticationMethod ? m.strategy : NATIVE_AUTH_STRATEGY_NAME, })); } }
import { Parent, ResolveField, Resolver } from '@nestjs/graphql'; import { Country } from '../../../entity/region/country.entity'; import { Zone } from '../../../entity/zone/zone.entity'; import { ZoneService } from '../../../service/services/zone.service'; import { RequestContext } from '../../common/request-context'; import { Ctx } from '../../decorators/request-context.decorator'; @Resolver('Zone') export class ZoneEntityResolver { constructor(private zoneService: ZoneService) {} @ResolveField() async members(@Ctx() ctx: RequestContext, @Parent() zone: Zone): Promise<Country[]> { if (Array.isArray(zone.members)) { return zone.members; } const zoneWithMembers = await this.zoneService.findOne(ctx, zone.id); return zoneWithMembers?.members ?? []; } }
import { Args, Context, Mutation, Query, Resolver } from '@nestjs/graphql'; import { AuthenticationResult, ErrorCode, InvalidCredentialsError, MissingPasswordError, MutationAuthenticateArgs, MutationLoginArgs, MutationRefreshCustomerVerificationArgs, MutationRegisterCustomerAccountArgs, MutationRequestPasswordResetArgs, MutationRequestUpdateCustomerEmailAddressArgs, MutationResetPasswordArgs, MutationUpdateCustomerEmailAddressArgs, MutationUpdateCustomerPasswordArgs, MutationVerifyCustomerAccountArgs, NativeAuthenticationResult, Permission, RefreshCustomerVerificationResult, RegisterCustomerAccountResult, RequestPasswordResetResult, RequestUpdateCustomerEmailAddressResult, ResetPasswordResult, Success, UpdateCustomerEmailAddressResult, UpdateCustomerPasswordResult, VerifyCustomerAccountResult, } from '@vendure/common/lib/generated-shop-types'; import { HistoryEntryType } from '@vendure/common/lib/generated-types'; import { Request, Response } from 'express'; import { isGraphQlErrorResult } from '../../../common/error/error-result'; import { ForbiddenError } from '../../../common/error/errors'; import { NativeAuthStrategyError } from '../../../common/error/generated-graphql-shop-errors'; import { NATIVE_AUTH_STRATEGY_NAME } from '../../../config/auth/native-authentication-strategy'; import { ConfigService } from '../../../config/config.service'; import { Logger } from '../../../config/logger/vendure-logger'; import { AdministratorService } from '../../../service/services/administrator.service'; import { AuthService } from '../../../service/services/auth.service'; import { CustomerService } from '../../../service/services/customer.service'; import { HistoryService } from '../../../service/services/history.service'; import { UserService } from '../../../service/services/user.service'; import { RequestContext } from '../../common/request-context'; import { setSessionToken } from '../../common/set-session-token'; import { Allow } from '../../decorators/allow.decorator'; import { Ctx } from '../../decorators/request-context.decorator'; import { Transaction } from '../../decorators/transaction.decorator'; import { BaseAuthResolver } from '../base/base-auth.resolver'; @Resolver() export class ShopAuthResolver extends BaseAuthResolver { constructor( authService: AuthService, userService: UserService, administratorService: AdministratorService, configService: ConfigService, protected customerService: CustomerService, protected historyService: HistoryService, ) { super(authService, userService, administratorService, configService); } @Transaction() @Mutation() @Allow(Permission.Public) async login( @Args() args: MutationLoginArgs, @Ctx() ctx: RequestContext, @Context('req') req: Request, @Context('res') res: Response, ): Promise<NativeAuthenticationResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } return (await super.baseLogin(args, ctx, req, res)) as AuthenticationResult; } @Transaction() @Mutation() @Allow(Permission.Public) async authenticate( @Args() args: MutationAuthenticateArgs, @Ctx() ctx: RequestContext, @Context('req') req: Request, @Context('res') res: Response, ): Promise<AuthenticationResult> { return (await this.authenticateAndCreateSession(ctx, args, req, res)) as AuthenticationResult; } @Transaction() @Mutation() @Allow(Permission.Public) async logout( @Ctx() ctx: RequestContext, @Context('req') req: Request, @Context('res') res: Response, ): Promise<Success> { return super.logout(ctx, req, res); } @Query() @Allow(Permission.Authenticated) me(@Ctx() ctx: RequestContext) { return super.me(ctx, 'shop'); } @Transaction() @Mutation() @Allow(Permission.Public) async registerCustomerAccount( @Ctx() ctx: RequestContext, @Args() args: MutationRegisterCustomerAccountArgs, ): Promise<RegisterCustomerAccountResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } const result = await this.customerService.registerCustomerAccount(ctx, args.input); if (isGraphQlErrorResult(result)) { if (result.errorCode === ErrorCode.EMAIL_ADDRESS_CONFLICT_ERROR) { // We do not want to reveal the email address conflict, // otherwise account enumeration attacks become possible. return { success: true }; } return result as MissingPasswordError; } return { success: true }; } @Transaction() @Mutation() @Allow(Permission.Public) async verifyCustomerAccount( @Ctx() ctx: RequestContext, @Args() args: MutationVerifyCustomerAccountArgs, @Context('req') req: Request, @Context('res') res: Response, ): Promise<VerifyCustomerAccountResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } const { token, password } = args; const customer = await this.customerService.verifyCustomerEmailAddress( ctx, token, password || undefined, ); if (isGraphQlErrorResult(customer)) { return customer; } const session = await this.authService.createAuthenticatedSessionForUser( ctx, // We know that there is a user, since the Customer // was found with the .getCustomerByUserId() method. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion customer.user!, NATIVE_AUTH_STRATEGY_NAME, ); if (isGraphQlErrorResult(session)) { // This code path should never be reached - in this block // the type of `session` is `NotVerifiedError`, however we // just successfully verified the user above. So throw it // so that we have some record of the error if it somehow // occurs. throw session; } setSessionToken({ req, res, authOptions: this.configService.authOptions, rememberMe: true, sessionToken: session.token, }); return this.publiclyAccessibleUser(session.user); } @Transaction() @Mutation() @Allow(Permission.Public) async refreshCustomerVerification( @Ctx() ctx: RequestContext, @Args() args: MutationRefreshCustomerVerificationArgs, ): Promise<RefreshCustomerVerificationResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } await this.customerService.refreshVerificationToken(ctx, args.emailAddress); return { success: true }; } @Transaction() @Mutation() @Allow(Permission.Public) async requestPasswordReset( @Ctx() ctx: RequestContext, @Args() args: MutationRequestPasswordResetArgs, ): Promise<RequestPasswordResetResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } await this.customerService.requestPasswordReset(ctx, args.emailAddress); return { success: true }; } @Transaction() @Mutation() @Allow(Permission.Public) async resetPassword( @Ctx() ctx: RequestContext, @Args() args: MutationResetPasswordArgs, @Context('req') req: Request, @Context('res') res: Response, ): Promise<ResetPasswordResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } const { token, password } = args; const resetResult = await this.customerService.resetPassword(ctx, token, password); if (isGraphQlErrorResult(resetResult)) { return resetResult; } const authResult = await super.authenticateAndCreateSession( ctx, { input: { [NATIVE_AUTH_STRATEGY_NAME]: { username: resetResult.identifier, password: args.password, }, }, }, req, res, ); if (isGraphQlErrorResult(authResult) && authResult.__typename === 'NotVerifiedError') { return authResult; } if (isGraphQlErrorResult(authResult)) { // This should never occur in theory throw authResult; } return authResult; } @Transaction() @Mutation() @Allow(Permission.Owner) async updateCustomerPassword( @Ctx() ctx: RequestContext, @Args() args: MutationUpdateCustomerPasswordArgs, ): Promise<UpdateCustomerPasswordResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } const result = await super.updatePassword(ctx, args.currentPassword, args.newPassword); if (isGraphQlErrorResult(result)) { return result; } if (result && ctx.activeUserId) { const customer = await this.customerService.findOneByUserId(ctx, ctx.activeUserId); if (customer) { await this.historyService.createHistoryEntryForCustomer({ ctx, customerId: customer.id, type: HistoryEntryType.CUSTOMER_PASSWORD_UPDATED, data: {}, }); } } return { success: result }; } @Transaction() @Mutation() @Allow(Permission.Owner) async requestUpdateCustomerEmailAddress( @Ctx() ctx: RequestContext, @Args() args: MutationRequestUpdateCustomerEmailAddressArgs, ): Promise<RequestUpdateCustomerEmailAddressResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } if (!ctx.activeUserId) { throw new ForbiddenError(); } const verify = await this.authService.verifyUserPassword(ctx, ctx.activeUserId, args.password); if (isGraphQlErrorResult(verify)) { return verify as InvalidCredentialsError; } const result = await this.customerService.requestUpdateEmailAddress( ctx, ctx.activeUserId, args.newEmailAddress, ); if (isGraphQlErrorResult(result)) { return result; } return { success: result, }; } @Transaction() @Mutation() @Allow(Permission.Owner) async updateCustomerEmailAddress( @Ctx() ctx: RequestContext, @Args() args: MutationUpdateCustomerEmailAddressArgs, ): Promise<UpdateCustomerEmailAddressResult> { const nativeAuthStrategyError = this.requireNativeAuthStrategy(); if (nativeAuthStrategyError) { return nativeAuthStrategyError; } const result = await this.customerService.updateEmailAddress(ctx, args.token); if (isGraphQlErrorResult(result)) { return result; } return { success: result }; } protected requireNativeAuthStrategy() { const { shopAuthenticationStrategy } = this.configService.authOptions; const nativeAuthStrategyIsConfigured = !!shopAuthenticationStrategy.find( strategy => strategy.name === NATIVE_AUTH_STRATEGY_NAME, ); if (!nativeAuthStrategyIsConfigured) { const authStrategyNames = shopAuthenticationStrategy.map(s => s.name).join(', '); const errorMessage = 'This GraphQL operation requires that the NativeAuthenticationStrategy be configured for the Shop API.\n' + `Currently the following AuthenticationStrategies are enabled: ${authStrategyNames}`; Logger.error(errorMessage); return new NativeAuthStrategyError(); } } }
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { MutationDeleteCustomerAddressArgs, MutationUpdateCustomerArgs, Success, } from '@vendure/common/lib/generated-shop-types'; import { MutationCreateCustomerAddressArgs, MutationUpdateCustomerAddressArgs, Permission, } from '@vendure/common/lib/generated-types'; import { ForbiddenError, InternalServerError } from '../../../common/error/errors'; import { idsAreEqual } from '../../../common/utils'; import { Address, Customer } from '../../../entity'; import { CustomerService } from '../../../service/services/customer.service'; import { RequestContext } from '../../common/request-context'; import { Allow } from '../../decorators/allow.decorator'; import { Ctx } from '../../decorators/request-context.decorator'; import { Transaction } from '../../decorators/transaction.decorator'; @Resolver() export class ShopCustomerResolver { constructor(private customerService: CustomerService) {} @Query() @Allow(Permission.Owner) async activeCustomer(@Ctx() ctx: RequestContext): Promise<Customer | undefined> { const userId = ctx.activeUserId; if (userId) { return this.customerService.findOneByUserId(ctx, userId); } } @Transaction() @Mutation() @Allow(Permission.Owner) async updateCustomer( @Ctx() ctx: RequestContext, @Args() args: MutationUpdateCustomerArgs, ): Promise<Customer> { const customer = await this.getCustomerForOwner(ctx); return this.customerService.update(ctx, { id: customer.id, ...args.input, }); } @Transaction() @Mutation() @Allow(Permission.Owner) async createCustomerAddress( @Ctx() ctx: RequestContext, @Args() args: MutationCreateCustomerAddressArgs, ): Promise<Address> { const customer = await this.getCustomerForOwner(ctx); return this.customerService.createAddress(ctx, customer.id, args.input); } @Transaction() @Mutation() @Allow(Permission.Owner) async updateCustomerAddress( @Ctx() ctx: RequestContext, @Args() args: MutationUpdateCustomerAddressArgs, ): Promise<Address> { const customer = await this.getCustomerForOwner(ctx); const customerAddresses = await this.customerService.findAddressesByCustomerId(ctx, customer.id); if (!customerAddresses.find(address => idsAreEqual(address.id, args.input.id))) { throw new ForbiddenError(); } return this.customerService.updateAddress(ctx, args.input); } @Transaction() @Mutation() @Allow(Permission.Owner) async deleteCustomerAddress( @Ctx() ctx: RequestContext, @Args() args: MutationDeleteCustomerAddressArgs, ): Promise<Success> { const customer = await this.getCustomerForOwner(ctx); const customerAddresses = await this.customerService.findAddressesByCustomerId(ctx, customer.id); if (!customerAddresses.find(address => idsAreEqual(address.id, args.id))) { throw new ForbiddenError(); } const success = await this.customerService.deleteAddress(ctx, args.id); return { success }; } /** * Returns the Customer entity associated with the current user. */ private async getCustomerForOwner(ctx: RequestContext): Promise<Customer> { const userId = ctx.activeUserId; if (!userId) { throw new ForbiddenError(); } const customer = await this.customerService.findOneByUserId(ctx, userId); if (!customer) { throw new InternalServerError('error.no-customer-found-for-current-user'); } return customer; } }
import { Query, Resolver } from '@nestjs/graphql'; import { Channel } from '../../../entity'; import { RequestContext } from '../../common/request-context'; import { Ctx } from '../../decorators/request-context.decorator'; @Resolver() export class ShopEnvironmentResolver { @Query() async activeChannel(@Ctx() ctx: RequestContext): Promise<Channel> { return ctx.channel; } }
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { ActiveOrderResult, AddPaymentToOrderResult, ApplyCouponCodeResult, MutationAddItemToOrderArgs, MutationAddPaymentToOrderArgs, MutationAdjustOrderLineArgs, MutationApplyCouponCodeArgs, MutationRemoveOrderLineArgs, MutationSetCustomerForOrderArgs, MutationSetOrderBillingAddressArgs, MutationSetOrderCustomFieldsArgs, MutationSetOrderShippingAddressArgs, MutationSetOrderShippingMethodArgs, MutationTransitionOrderToStateArgs, PaymentMethodQuote, Permission, QueryOrderArgs, QueryOrderByCodeArgs, RemoveOrderItemsResult, SetCustomerForOrderResult, SetOrderShippingMethodResult, ShippingMethodQuote, TransitionOrderToStateResult, UpdateOrderItemsResult, } from '@vendure/common/lib/generated-shop-types'; import { QueryCountriesArgs } from '@vendure/common/lib/generated-types'; import { unique } from '@vendure/common/lib/unique'; import { ErrorResultUnion, isGraphQlErrorResult } from '../../../common/error/error-result'; import { ForbiddenError } from '../../../common/error/errors'; import { AlreadyLoggedInError, NoActiveOrderError, } from '../../../common/error/generated-graphql-shop-errors'; import { Translated } from '../../../common/types/locale-types'; import { idsAreEqual } from '../../../common/utils'; import { ACTIVE_ORDER_INPUT_FIELD_NAME, ConfigService, LogLevel } from '../../../config'; import { Country } from '../../../entity'; import { Order } from '../../../entity/order/order.entity'; import { ActiveOrderService, CountryService } from '../../../service'; import { OrderState } from '../../../service/helpers/order-state-machine/order-state'; import { CustomerService } from '../../../service/services/customer.service'; import { OrderService } from '../../../service/services/order.service'; import { SessionService } from '../../../service/services/session.service'; import { RequestContext } from '../../common/request-context'; import { Allow } from '../../decorators/allow.decorator'; import { RelationPaths, Relations } from '../../decorators/relations.decorator'; import { Ctx } from '../../decorators/request-context.decorator'; import { Transaction } from '../../decorators/transaction.decorator'; type ActiveOrderArgs = { [ACTIVE_ORDER_INPUT_FIELD_NAME]?: any }; @Resolver() export class ShopOrderResolver { constructor( private orderService: OrderService, private customerService: CustomerService, private sessionService: SessionService, private countryService: CountryService, private activeOrderService: ActiveOrderService, private configService: ConfigService, ) {} @Query() availableCountries( @Ctx() ctx: RequestContext, @Args() args: QueryCountriesArgs, ): Promise<Array<Translated<Country>>> { return this.countryService.findAllAvailable(ctx); } @Query() @Allow(Permission.Owner) async order( @Ctx() ctx: RequestContext, @Args() args: QueryOrderArgs, @Relations(Order) relations: RelationPaths<Order>, ): Promise<Order | undefined> { const requiredRelations: RelationPaths<Order> = ['customer', 'customer.user']; const order = await this.orderService.findOne( ctx, args.id, unique([...relations, ...requiredRelations]), ); if (order && ctx.authorizedAsOwnerOnly) { const orderUserId = order.customer && order.customer.user && order.customer.user.id; if (idsAreEqual(ctx.activeUserId, orderUserId)) { return order; } else { return; } } } @Query() @Allow(Permission.Owner) async activeOrder( @Ctx() ctx: RequestContext, @Relations(Order) relations: RelationPaths<Order>, @Args() args: ActiveOrderArgs, ): Promise<Order | undefined> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { return this.orderService.findOne(ctx, sessionOrder.id); } else { return; } } } @Query() @Allow(Permission.Owner) async orderByCode( @Ctx() ctx: RequestContext, @Args() args: QueryOrderByCodeArgs, @Relations(Order) relations: RelationPaths<Order>, ): Promise<Order | undefined> { if (ctx.authorizedAsOwnerOnly) { const requiredRelations: RelationPaths<Order> = ['customer', 'customer.user']; const order = await this.orderService.findOneByCode( ctx, args.code, unique([...relations, ...requiredRelations]), ); if ( order && (await this.configService.orderOptions.orderByCodeAccessStrategy.canAccessOrder(ctx, order)) ) { return order; } // We throw even if the order does not exist, since giving a different response // opens the door to an enumeration attack to find valid order codes. throw new ForbiddenError(LogLevel.Verbose); } } @Transaction() @Mutation() @Allow(Permission.Owner) async setOrderShippingAddress( @Ctx() ctx: RequestContext, @Args() args: MutationSetOrderShippingAddressArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<ActiveOrderResult, Order>> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { return this.orderService.setShippingAddress(ctx, sessionOrder.id, args.input); } } return new NoActiveOrderError(); } @Transaction() @Mutation() @Allow(Permission.Owner) async setOrderBillingAddress( @Ctx() ctx: RequestContext, @Args() args: MutationSetOrderBillingAddressArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<ActiveOrderResult, Order>> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { return this.orderService.setBillingAddress(ctx, sessionOrder.id, args.input); } } return new NoActiveOrderError(); } @Query() @Allow(Permission.Owner) async eligibleShippingMethods( @Ctx() ctx: RequestContext, @Args() args: ActiveOrderArgs, ): Promise<ShippingMethodQuote[]> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { return this.orderService.getEligibleShippingMethods(ctx, sessionOrder.id); } } return []; } @Query() @Allow(Permission.Owner) async eligiblePaymentMethods( @Ctx() ctx: RequestContext, @Args() args: ActiveOrderArgs, ): Promise<PaymentMethodQuote[]> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { return this.orderService.getEligiblePaymentMethods(ctx, sessionOrder.id); } } return []; } @Transaction() @Mutation() @Allow(Permission.Owner) async setOrderShippingMethod( @Ctx() ctx: RequestContext, @Args() args: MutationSetOrderShippingMethodArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<SetOrderShippingMethodResult, Order>> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { return this.orderService.setShippingMethod(ctx, sessionOrder.id, args.shippingMethodId); } } return new NoActiveOrderError(); } @Transaction() @Mutation() @Allow(Permission.Owner) async setOrderCustomFields( @Ctx() ctx: RequestContext, @Args() args: MutationSetOrderCustomFieldsArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<ActiveOrderResult, Order>> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { return this.orderService.updateCustomFields(ctx, sessionOrder.id, args.input.customFields); } } return new NoActiveOrderError(); } @Transaction() @Query() @Allow(Permission.Owner) async nextOrderStates( @Ctx() ctx: RequestContext, @Args() args: ActiveOrderArgs, ): Promise<readonly string[]> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], true, ); return this.orderService.getNextOrderStates(sessionOrder); } return []; } @Transaction() @Mutation() @Allow(Permission.Owner) async transitionOrderToState( @Ctx() ctx: RequestContext, @Args() args: MutationTransitionOrderToStateArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<TransitionOrderToStateResult, Order> | undefined> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], true, ); return await this.orderService.transitionToState(ctx, sessionOrder.id, args.state as OrderState); } } @Transaction() @Mutation() @Allow(Permission.UpdateOrder, Permission.Owner) async addItemToOrder( @Ctx() ctx: RequestContext, @Args() args: MutationAddItemToOrderArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<UpdateOrderItemsResult, Order>> { const order = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], true, ); return this.orderService.addItemToOrder( ctx, order.id, args.productVariantId, args.quantity, (args as any).customFields, ); } @Transaction() @Mutation() @Allow(Permission.UpdateOrder, Permission.Owner) async adjustOrderLine( @Ctx() ctx: RequestContext, @Args() args: MutationAdjustOrderLineArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<UpdateOrderItemsResult, Order>> { if (args.quantity === 0) { return this.removeOrderLine(ctx, { orderLineId: args.orderLineId }); } const order = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], true, ); return this.orderService.adjustOrderLine( ctx, order.id, args.orderLineId, args.quantity, (args as any).customFields, ); } @Transaction() @Mutation() @Allow(Permission.UpdateOrder, Permission.Owner) async removeOrderLine( @Ctx() ctx: RequestContext, @Args() args: MutationRemoveOrderLineArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<RemoveOrderItemsResult, Order>> { const order = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], true, ); return this.orderService.removeItemFromOrder(ctx, order.id, args.orderLineId); } @Transaction() @Mutation() @Allow(Permission.UpdateOrder, Permission.Owner) async removeAllOrderLines( @Ctx() ctx: RequestContext, @Args() args: ActiveOrderArgs, ): Promise<ErrorResultUnion<RemoveOrderItemsResult, Order>> { const order = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], true, ); return this.orderService.removeAllItemsFromOrder(ctx, order.id); } @Transaction() @Mutation() @Allow(Permission.UpdateOrder, Permission.Owner) async applyCouponCode( @Ctx() ctx: RequestContext, @Args() args: MutationApplyCouponCodeArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<ApplyCouponCodeResult, Order>> { const order = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], true, ); return this.orderService.applyCouponCode(ctx, order.id, args.couponCode); } @Transaction() @Mutation() @Allow(Permission.UpdateOrder, Permission.Owner) async removeCouponCode( @Ctx() ctx: RequestContext, @Args() args: MutationApplyCouponCodeArgs & ActiveOrderArgs, ): Promise<Order> { const order = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], true, ); return this.orderService.removeCouponCode(ctx, order.id, args.couponCode); } @Transaction() @Mutation() @Allow(Permission.UpdateOrder, Permission.Owner) async addPaymentToOrder( @Ctx() ctx: RequestContext, @Args() args: MutationAddPaymentToOrderArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<AddPaymentToOrderResult, Order>> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { const order = await this.orderService.addPaymentToOrder(ctx, sessionOrder.id, args.input); if (isGraphQlErrorResult(order)) { return order; } if (order.active === false) { await this.customerService.createAddressesForNewCustomer(ctx, order); } if (order.active === false && ctx.session?.activeOrderId === sessionOrder.id) { await this.sessionService.unsetActiveOrder(ctx, ctx.session); } return order; } } return new NoActiveOrderError(); } @Transaction() @Mutation() @Allow(Permission.Owner) async setCustomerForOrder( @Ctx() ctx: RequestContext, @Args() args: MutationSetCustomerForOrderArgs & ActiveOrderArgs, ): Promise<ErrorResultUnion<SetCustomerForOrderResult, Order>> { if (ctx.authorizedAsOwnerOnly) { const sessionOrder = await this.activeOrderService.getActiveOrder( ctx, args[ACTIVE_ORDER_INPUT_FIELD_NAME], ); if (sessionOrder) { const { guestCheckoutStrategy } = this.configService.orderOptions; const result = await guestCheckoutStrategy.setCustomerForOrder(ctx, sessionOrder, args.input); if (isGraphQlErrorResult(result)) { return result; } return this.orderService.addCustomerToOrder(ctx, sessionOrder.id, result); } } return new NoActiveOrderError(); } }
import { Args, Query, Resolver } from '@nestjs/graphql'; import { QueryCollectionArgs, QueryCollectionsArgs, QueryFacetArgs, QueryFacetsArgs, QueryProductArgs, QueryProductsArgs, SearchResponse, } from '@vendure/common/lib/generated-shop-types'; import { Omit } from '@vendure/common/lib/omit'; import { PaginatedList } from '@vendure/common/lib/shared-types'; import { InternalServerError, UserInputError } from '../../../common/error/errors'; import { ListQueryOptions } from '../../../common/types/common-types'; import { Translated } from '../../../common/types/locale-types'; import { Collection } from '../../../entity/collection/collection.entity'; import { Facet } from '../../../entity/facet/facet.entity'; import { Product } from '../../../entity/product/product.entity'; import { CollectionService, FacetService } from '../../../service'; import { FacetValueService } from '../../../service/services/facet-value.service'; import { ProductVariantService } from '../../../service/services/product-variant.service'; import { ProductService } from '../../../service/services/product.service'; import { RequestContext } from '../../common/request-context'; import { RelationPaths, Relations } from '../../decorators/relations.decorator'; import { Ctx } from '../../decorators/request-context.decorator'; @Resolver() export class ShopProductsResolver { constructor( private productService: ProductService, private productVariantService: ProductVariantService, private facetValueService: FacetValueService, private collectionService: CollectionService, private facetService: FacetService, ) {} @Query() async products( @Ctx() ctx: RequestContext, @Args() args: QueryProductsArgs, @Relations({ entity: Product, omit: ['variants', 'assets'] }) relations: RelationPaths<Product>, ): Promise<PaginatedList<Translated<Product>>> { const options: ListQueryOptions<Product> = { ...args.options, filter: { ...(args.options && args.options.filter), enabled: { eq: true }, }, }; return this.productService.findAll(ctx, options, relations); } @Query() async product( @Ctx() ctx: RequestContext, @Args() args: QueryProductArgs, @Relations({ entity: Product, omit: ['variants', 'assets'] }) relations: RelationPaths<Product>, ): Promise<Translated<Product> | undefined> { let result: Translated<Product> | undefined; if (args.id) { result = await this.productService.findOne(ctx, args.id, relations); } else if (args.slug) { result = await this.productService.findOneBySlug(ctx, args.slug, relations); } else { throw new UserInputError('error.product-id-or-slug-must-be-provided'); } if (!result) { return; } if (result.enabled === false) { return; } result.facetValues = result.facetValues?.filter(fv => !fv.facet.isPrivate) as any; return result; } @Query() async collections( @Ctx() ctx: RequestContext, @Args() args: QueryCollectionsArgs, @Relations({ entity: Collection, omit: ['productVariants', 'assets', 'parent.productVariants', 'children.productVariants'], }) relations: RelationPaths<Collection>, ): Promise<PaginatedList<Translated<Collection>>> { const options: ListQueryOptions<Collection> = { ...args.options, filter: { ...(args.options && args.options.filter), isPrivate: { eq: false }, }, }; return this.collectionService.findAll(ctx, options || undefined, relations); } @Query() async collection( @Ctx() ctx: RequestContext, @Args() args: QueryCollectionArgs, @Relations({ entity: Collection, omit: ['productVariants', 'assets', 'parent.productVariants', 'children.productVariants'], }) relations: RelationPaths<Collection>, ): Promise<Translated<Collection> | undefined> { let collection: Translated<Collection> | undefined; if (args.id) { collection = await this.collectionService.findOne(ctx, args.id, relations); if (args.slug && collection && collection.slug !== args.slug) { throw new UserInputError('error.collection-id-slug-mismatch'); } } else if (args.slug) { collection = await this.collectionService.findOneBySlug(ctx, args.slug, relations); } else { throw new UserInputError('error.collection-id-or-slug-must-be-provided'); } if (collection && collection.isPrivate) { return; } return collection; } @Query() async search(...args: any): Promise<Omit<SearchResponse, 'facetValues'>> { throw new InternalServerError('error.no-search-plugin-configured'); } @Query() async facets( @Ctx() ctx: RequestContext, @Args() args: QueryFacetsArgs, @Relations(Facet) relations: RelationPaths<Facet>, ): Promise<PaginatedList<Translated<Facet>>> { const options: ListQueryOptions<Facet> = { ...args.options, filter: { ...(args.options && args.options.filter), isPrivate: { eq: false }, }, }; return this.facetService.findAll(ctx, options || undefined, relations); } @Query() async facet( @Ctx() ctx: RequestContext, @Args() args: QueryFacetArgs, @Relations(Facet) relations: RelationPaths<Facet>, ): Promise<Translated<Facet> | undefined> { const facet = await this.facetService.findOne(ctx, args.id, relations); if (facet && facet.isPrivate) { return; } return facet; } }
import { Module } from '@nestjs/common'; import { RequestContextCacheService } from './request-context-cache.service'; @Module({ providers: [RequestContextCacheService], exports: [RequestContextCacheService], }) export class CacheModule {}
export * from './request-context-cache.service';
import { beforeEach, describe, expect, it } from 'vitest'; import { RequestContext } from '../api'; import { RequestContextCacheService } from './request-context-cache.service'; describe('Request context cache', () => { let cache: RequestContextCacheService; beforeEach(() => { cache = new RequestContextCacheService(); }); it('stores and retrieves a multiple values', () => { const ctx = RequestContext.empty(); cache.set(ctx, 'test', 1); cache.set(ctx, 'test2', 2); expect(cache.get(ctx, 'test')).toBe(1); expect(cache.get(ctx, 'test2')).toBe(2); }); it('uses getDefault function', async () => { const ctx = RequestContext.empty(); const result = cache.get(ctx, 'test', async () => 'foo'); expect(result instanceof Promise).toBe(true); expect(await result).toBe('foo'); }); it('can use objects as keys', () => { const ctx = RequestContext.empty(); const x = {}; cache.set(ctx, x, 1); expect(cache.get(ctx, x)).toBe(1); }); it('uses separate stores per context', () => { const ctx = RequestContext.empty(); const ctx2 = RequestContext.empty(); cache.set(ctx, 'test', 1); cache.set(ctx2, 'test', 2); expect(cache.get(ctx, 'test')).toBe(1); expect(cache.get(ctx2, 'test')).toBe(2); }); });
import { RequestContext } from '../api'; /** * @description * This service is used to cache arbitrary data relative to an ongoing request. * It does this by using a WeakMap bound to the current RequestContext, so the cached * data is available for the duration of the request. Once the request completes, the * cached data will be automatically garbage-collected. */ export class RequestContextCacheService { private caches = new WeakMap<RequestContext, Map<any, any>>(); set<T = any>(ctx: RequestContext, key: any, val: T): void { this.getContextCache(ctx).set(key, val); } get<T = any>(ctx: RequestContext, key: any): T | undefined; get<T>(ctx: RequestContext, key: any, getDefault?: () => T): T; get<T>(ctx: RequestContext, key: any, getDefault?: () => T): T | Promise<T> | undefined { const ctxCache = this.getContextCache(ctx); const result = ctxCache.get(key); if (result) { return result; } if (getDefault) { const defaultResultOrPromise = getDefault(); ctxCache.set(key, defaultResultOrPromise); return defaultResultOrPromise; } else { return; } } private getContextCache(ctx: RequestContext): Map<any, any> { let ctxCache = this.caches.get(ctx); if (!ctxCache) { ctxCache = new Map<any, any>(); this.caches.set(ctx, ctxCache); } return ctxCache; } private isPromise<T>(input: T | Promise<T>): input is Promise<T> { return typeof (input as any).then === 'function'; } }
export * from './populate';
import { INestApplicationContext } from '@nestjs/common'; import fs from 'fs-extra'; import path from 'path'; import { lastValueFrom } from 'rxjs'; const loggerCtx = 'Populate'; /* eslint-disable no-console */ /** * @description * Populates the Vendure server with some initial data and (optionally) product data from * a supplied CSV file. The format of the CSV file is described in the section * [Importing Product Data](/guides/developer-guide/importing-data/). * * If the `channelOrToken` argument is provided, all ChannelAware entities (Products, ProductVariants, * Assets, ShippingMethods, PaymentMethods etc.) will be assigned to the specified Channel. * The argument can be either a Channel object or a valid channel `token`. * * Internally the `populate()` function does the following: * * 1. Uses the {@link Populator} to populate the {@link InitialData}. * 2. If `productsCsvPath` is provided, uses {@link Importer} to populate Product data. * 3. Uses {@link Populator} to populate collections specified in the {@link InitialData}. * * @example * ```ts * import { bootstrap } from '\@vendure/core'; * import { populate } from '\@vendure/core/cli'; * import { config } from './vendure-config.ts' * import { initialData } from './my-initial-data.ts'; * * const productsCsvFile = path.join(__dirname, 'path/to/products.csv') * * populate( * () => bootstrap(config), * initialData, * productsCsvFile, * ) * .then(app => app.close()) * .then( * () => process.exit(0), * err => { * console.log(err); * process.exit(1); * }, * ); * ``` * * @docsCategory import-export */ export async function populate<T extends INestApplicationContext>( bootstrapFn: () => Promise<T | undefined>, initialDataPathOrObject: string | object, productsCsvPath?: string, channelOrToken?: string | import('@vendure/core').Channel, ): Promise<T> { const app = await bootstrapFn(); if (!app) { throw new Error('Could not bootstrap the Vendure app'); } let channel: import('@vendure/core').Channel | undefined; const { ChannelService, Channel, Logger } = await import('@vendure/core'); if (typeof channelOrToken === 'string') { channel = await app.get(ChannelService).getChannelFromToken(channelOrToken); if (!channel) { Logger.warn( `Warning: channel with token "${channelOrToken}" was not found. Using default Channel instead.`, loggerCtx, ); } } else if (channelOrToken instanceof Channel) { channel = channelOrToken; } const initialData: import('@vendure/core').InitialData = typeof initialDataPathOrObject === 'string' ? require(initialDataPathOrObject) : initialDataPathOrObject; await populateInitialData(app, initialData, channel); if (productsCsvPath) { const importResult = await importProductsFromCsv( app, productsCsvPath, initialData.defaultLanguage, channel, ); if (importResult.errors && importResult.errors.length) { const errorFile = path.join(process.cwd(), 'vendure-import-error.log'); Logger.error( `${importResult.errors.length} errors encountered when importing product data. See: ${errorFile}`, loggerCtx, ); await fs.writeFile(errorFile, importResult.errors.join('\n')); } Logger.info(`Imported ${importResult.imported} products`, loggerCtx); await populateCollections(app, initialData, channel); } Logger.info('Done!', loggerCtx); return app; } export async function populateInitialData( app: INestApplicationContext, initialData: import('@vendure/core').InitialData, channel?: import('@vendure/core').Channel, ) { const { Populator, Logger } = await import('@vendure/core'); const populator = app.get(Populator); try { await populator.populateInitialData(initialData, channel); Logger.info('Populated initial data', loggerCtx); } catch (err: any) { Logger.error(err.message, loggerCtx); } } export async function populateCollections( app: INestApplicationContext, initialData: import('@vendure/core').InitialData, channel?: import('@vendure/core').Channel, ) { const { Populator, Logger } = await import('@vendure/core'); const populator = app.get(Populator); try { if (initialData.collections.length) { await populator.populateCollections(initialData, channel); Logger.info(`Created ${initialData.collections.length} Collections`, loggerCtx); } } catch (err: any) { Logger.info(err.message, loggerCtx); } } export async function importProductsFromCsv( app: INestApplicationContext, productsCsvPath: string, languageCode: import('@vendure/core').LanguageCode, channel?: import('@vendure/core').Channel, ): Promise<import('@vendure/core').ImportProgress> { const { Importer, RequestContextService } = await import('@vendure/core'); const importer = app.get(Importer); const requestContextService = app.get(RequestContextService); const productData = await fs.readFile(productsCsvPath, 'utf-8'); const ctx = await requestContextService.create({ apiType: 'admin', languageCode, channelOrToken: channel, }); return lastValueFrom(importer.parseAndImport(productData, ctx, true)); }
export type Task<T = any> = () => Promise<T> | T; export type Resolve<T> = (val: T) => void; export type Reject<T> = (val: T) => void; type TaskQueueItem = { task: Task; resolve: Resolve<any>; reject: Reject<any> }; /** * @description * A queue class for limiting concurrent async tasks. This can be used e.g. to prevent * race conditions when working on a shared resource such as writing to a database. * * @docsCategory common */ export class AsyncQueue { private static running: { [label: string]: number } = {}; private static taskQueue: { [label: string]: TaskQueueItem[] } = {}; constructor(private label: string = 'default', private concurrency: number = 1) { if (!AsyncQueue.taskQueue[label]) { AsyncQueue.taskQueue[label] = []; AsyncQueue.running[label] = 0; } } private get running(): number { return AsyncQueue.running[this.label]; } private inc() { AsyncQueue.running[this.label]++; } private dec() { AsyncQueue.running[this.label]--; } /** * @description * Pushes a new task onto the queue, upon which the task will either execute immediately or * (if the number of running tasks is equal to the concurrency limit) enqueue the task to * be executed at the soonest opportunity. */ push<T>(task: Task<T>): Promise<T> { return new Promise<T>((resolve, reject) => { void (this.running < this.concurrency ? this.runTask(task, resolve, reject) : this.enqueueTask(task, resolve, reject)); }); } private async runTask<T>(task: Task<T>, resolve: Resolve<T>, reject: Reject<T>) { this.inc(); try { const result = await task(); resolve(result); } catch (e: any) { reject(e); } this.dec(); if (this.getQueue().length > 0) { const nextTask = this.getQueue().shift(); if (nextTask) { await this.runTask(nextTask.task, nextTask.resolve, nextTask.reject); } } } private enqueueTask<T>(task: Task<T>, resolve: Resolve<T>, reject: Reject<T>) { this.getQueue().push({ task, resolve, reject }); } private getQueue(): TaskQueueItem[] { return AsyncQueue.taskQueue[this.label]; } }
import { OrderByCondition, SelectQueryBuilder } from 'typeorm'; /** * The property name we use to store the CalculatedColumnDefinitions to the * entity class. */ export const CALCULATED_PROPERTIES = '__calculatedProperties__'; /** * @description * Optional metadata used to tell the {@link ListQueryBuilder} & {@link Relations} decorator how to deal with * calculated columns when sorting, filtering and deriving required relations from GraphQL operations. * * @docsCategory data-access * @docsPage Calculated */ export interface CalculatedColumnQueryInstruction { /** * @description * If the calculated property depends on one or more relations being present * on the entity (e.g. an `Order` entity calculating the `totalQuantity` by adding * up the quantities of each `OrderLine`), then those relations should be defined here. */ relations?: string[]; query?: (qb: SelectQueryBuilder<any>) => void; expression?: string; } export interface CalculatedColumnDefinition { name: string | symbol; listQuery?: CalculatedColumnQueryInstruction; } /** * @description * Used to define calculated entity getters. The decorator simply attaches an array of "calculated" * property names to the entity's prototype. This array is then used by the {@link CalculatedPropertySubscriber} * to transfer the getter function from the prototype to the entity instance. * * @docsCategory data-access * @docsWeight 0 */ export function Calculated(queryInstruction?: CalculatedColumnQueryInstruction): MethodDecorator { return ( target: object & { [key: string]: any }, propertyKey: string | symbol, descriptor: PropertyDescriptor, ) => { const definition: CalculatedColumnDefinition = { name: propertyKey, listQuery: queryInstruction, }; if (target[CALCULATED_PROPERTIES]) { if ( !target[CALCULATED_PROPERTIES].map((p: CalculatedColumnDefinition) => p.name).includes( definition.name, ) ) { target[CALCULATED_PROPERTIES].push(definition); } } else { target[CALCULATED_PROPERTIES] = [definition]; } }; }
// prettier-ignore import { ConfigArg, ConfigArgDefinition, ConfigurableOperationDefinition, LanguageCode, LocalizedString, Maybe, StringFieldOption, } from '@vendure/common/lib/generated-types'; import { ConfigArgType, DefaultFormComponentConfig, ID, UiComponentConfig, } from '@vendure/common/lib/shared-types'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { RequestContext } from '../api/common/request-context'; import { DEFAULT_LANGUAGE_CODE } from './constants'; import { InternalServerError } from './error/errors'; import { Injector } from './injector'; import { InjectableStrategy } from './types/injectable-strategy'; /** * @description * An array of string values in a given {@link LanguageCode}, used to define human-readable string values. * The `ui` property can be used in conjunction with the Vendure Admin UI to specify a custom form input * component. * * @example * ```ts * const title: LocalizedStringArray = [ * { languageCode: LanguageCode.en, value: 'English Title' }, * { languageCode: LanguageCode.de, value: 'German Title' }, * { languageCode: LanguageCode.zh, value: 'Chinese Title' }, * ] * ``` * * @docsCategory ConfigurableOperationDef */ export type LocalizedStringArray = Array<Omit<LocalizedString, '__typename'>>; export interface ConfigArgCommonDef<T extends ConfigArgType> { type: T; required?: boolean; defaultValue?: ConfigArgTypeToTsType<T>; list?: boolean; label?: LocalizedStringArray; description?: LocalizedStringArray; ui?: UiComponentConfig<string>; } export type ConfigArgListDef< T extends ConfigArgType, C extends ConfigArgCommonDef<T> = ConfigArgCommonDef<T>, > = C & { list: true }; export type WithArgConfig<T> = { config?: T; }; export type StringArgConfig = WithArgConfig<{ options?: Maybe<StringFieldOption[]>; }>; export type IntArgConfig = WithArgConfig<{ inputType?: 'default' | 'percentage' | 'money'; }>; export type ConfigArgDef<T extends ConfigArgType> = T extends 'string' ? ConfigArgCommonDef<'string'> & StringArgConfig : T extends 'int' ? ConfigArgCommonDef<'int'> & IntArgConfig : ConfigArgCommonDef<T> & WithArgConfig<never>; /** * @description * A object which defines the configurable arguments which may be passed to * functions in those classes which implement the {@link ConfigurableOperationDef} interface. * * ## Data types * Each argument has a data type, which must be one of {@link ConfigArgType}. * * @example * ```ts * { * apiKey: { type: 'string' }, * maxRetries: { type: 'int' }, * logErrors: { type: 'boolean' }, * } * ``` * * ## Lists * Setting the `list` property to `true` will make the argument into an array of the specified * data type. For example, if you want to store an array of strings: * * @example * ```ts * { * aliases: { * type: 'string', * list: true, * }, * } *``` * In the Admin UI, this will be rendered as an orderable list of string inputs. * * ## UI Component * The `ui` field allows you to specify a specific input component to be used in the Admin UI. * When not set, a default input component is used appropriate to the data type. * * @example * ```ts * { * operator: { * type: 'string', * ui: { * component: 'select-form-input', * options: [ * { value: 'startsWith' }, * { value: 'endsWith' }, * { value: 'contains' }, * { value: 'doesNotContain' }, * ], * }, * }, * secretKey: { * type: 'string', * ui: { component: 'password-form-input' }, * }, * } * ``` * The available components as well as their configuration options can be found in the {@link DefaultFormConfigHash} docs. * Custom UI components may also be defined via an Admin UI extension using the `registerFormInputComponent()` function * which is exported from `@vendure/admin-ui/core`. * * @docsCategory ConfigurableOperationDef */ export type ConfigArgs = { [name: string]: ConfigArgDef<ConfigArgType>; }; /** * Represents the ConfigArgs once they have been coerced into JavaScript values for use * in business logic. */ export type ConfigArgValues<T extends ConfigArgs> = { [K in keyof T]: ConfigArgDefToType<T[K]>; }; /** * Converts a ConfigArgDef to a TS type, e.g: * * ConfigArgListDef<'datetime'> -> Date[] * ConfigArgDef<'boolean'> -> boolean */ export type ConfigArgDefToType<D extends ConfigArgDef<ConfigArgType>> = D extends ConfigArgListDef< 'int' | 'float' > ? number[] : D extends ConfigArgDef<'int' | 'float'> ? number : D extends ConfigArgListDef<'datetime'> ? Date[] : D extends ConfigArgDef<'datetime'> ? Date : D extends ConfigArgListDef<'boolean'> ? boolean[] : D extends ConfigArgDef<'boolean'> ? boolean : D extends ConfigArgListDef<'ID'> ? ID[] : D extends ConfigArgDef<'ID'> ? ID : D extends ConfigArgListDef<'string'> ? string[] : string; /** * Converts a ConfigArgType to a TypeScript type * * ConfigArgTypeToTsType<'int'> -> number */ export type ConfigArgTypeToTsType<T extends ConfigArgType> = T extends 'string' ? string : T extends 'int' ? number : T extends 'float' ? number : T extends 'boolean' ? boolean : T extends 'datetime' ? Date : ID; /** * Converts a TS type to a ConfigArgDef, e.g: * * Date[] -> ConfigArgListDef<'datetime'> * boolean -> ConfigArgDef<'boolean'> */ export type TypeToConfigArgDef<T extends ConfigArgDefToType<any>> = T extends number ? ConfigArgDef<'int' | 'float'> : T extends number[] ? ConfigArgListDef<'int' | 'float'> : T extends Date[] ? ConfigArgListDef<'datetime'> : T extends Date ? ConfigArgDef<'datetime'> : T extends boolean[] ? ConfigArgListDef<'boolean'> : T extends boolean ? ConfigArgDef<'boolean'> : T extends string[] ? ConfigArgListDef<'string'> : T extends string ? ConfigArgDef<'string'> : T extends ID[] ? ConfigArgListDef<'ID'> : ConfigArgDef<'ID'>; /** * @description * Common configuration options used when creating a new instance of a * {@link ConfigurableOperationDef} ( * * @docsCategory ConfigurableOperationDef */ export interface ConfigurableOperationDefOptions<T extends ConfigArgs> extends InjectableStrategy { /** * @description * A unique code used to identify this operation. */ code: string; /** * @description * Optional provider-specific arguments which, when specified, are * editable in the admin-ui. For example, args could be used to store an API key * for a payment provider service. * * @example * ```ts * args: { * apiKey: { type: 'string' }, * } * ``` * * See {@link ConfigArgs} for available configuration options. */ args: T; /** * @description * A human-readable description for the operation method. */ description: LocalizedStringArray; } /** * @description * A ConfigurableOperationDef is a special type of object used extensively by Vendure to define * code blocks which have arguments which are configurable at run-time by the administrator. * * This is the mechanism used by: * * * {@link CollectionFilter} * * {@link PaymentMethodHandler} * * {@link PromotionAction} * * {@link PromotionCondition} * * {@link ShippingCalculator} * * {@link ShippingEligibilityChecker} * * Any class which extends ConfigurableOperationDef works in the same way: it takes a * config object as the constructor argument. That config object extends the {@link ConfigurableOperationDefOptions} * interface and typically adds some kind of business logic function to it. * * For example, in the case of `ShippingEligibilityChecker`, * it adds the `check()` function to the config object which defines the logic for checking whether an Order is eligible * for a particular ShippingMethod. * * ## The `args` property * * The key feature of the ConfigurableOperationDef is the `args` property. This is where we define those * arguments that are exposed via the Admin UI as data input components. This allows their values to * be set at run-time by the Administrator. Those values can then be accessed in the business logic * of the operation. * * The data type of the args can be one of {@link ConfigArgType}, and the configuration is further explained in * the docs of {@link ConfigArgs}. * * ## Dependency Injection * If your business logic relies on injectable providers, such as the `TransactionalConnection` object, or any of the * internal Vendure services or those defined in a plugin, you can inject them by using the config object's * `init()` method, which exposes the {@link Injector}. * * Here's an example of a ShippingCalculator that injects a service which has been defined in a plugin: * * @example * ```ts * import { Injector, ShippingCalculator } from '\@vendure/core'; * import { ShippingRatesService } from './shipping-rates.service'; * * // We keep reference to our injected service by keeping it * // in the top-level scope of the file. * let shippingRatesService: ShippingRatesService; * * export const customShippingCalculator = new ShippingCalculator({ * code: 'custom-shipping-calculator', * description: [], * args: {}, * * init(injector: Injector) { * // The init function is called during bootstrap, and allows * // us to inject any providers we need. * shippingRatesService = injector.get(ShippingRatesService); * }, * * calculate: async (order, args) => { * // We can now use the injected provider in the business logic. * const { price, priceWithTax } = await shippingRatesService.getRate({ * destination: order.shippingAddress, * contents: order.lines, * }); * * return { * price, * priceWithTax, * }; * }, * }); * ``` * * @docsCategory ConfigurableOperationDef */ export class ConfigurableOperationDef<T extends ConfigArgs = ConfigArgs> { get code(): string { return this.options.code; } get args(): T { return this.options.args; } get description(): LocalizedStringArray { return this.options.description; } constructor(protected options: ConfigurableOperationDefOptions<T>) {} async init(injector: Injector) { if (typeof this.options.init === 'function') { await this.options.init(injector); } } async destroy() { if (typeof this.options.destroy === 'function') { await this.options.destroy(); } } /** * @description * Convert a ConfigurableOperationDef into a ConfigurableOperationDefinition object, typically * so that it can be sent via the API. */ toGraphQlType(ctx: RequestContext): ConfigurableOperationDefinition { return { code: this.code, description: localizeString(this.description, ctx.languageCode, ctx.channel.defaultLanguageCode), args: Object.entries(this.args).map( ([name, arg]) => ({ name, type: arg.type, list: arg.list ?? false, required: arg.required ?? true, defaultValue: arg.defaultValue, ui: arg.ui, label: arg.label && localizeString(arg.label, ctx.languageCode, ctx.channel.defaultLanguageCode), description: arg.description && localizeString( arg.description, ctx.languageCode, ctx.channel.defaultLanguageCode, ), } as Required<ConfigArgDefinition>), ), }; } /** * @description * Coverts an array of ConfigArgs into a hash object: * * from: * `[{ name: 'foo', type: 'string', value: 'bar'}]` * * to: * `{ foo: 'bar' }` **/ protected argsArrayToHash(args: ConfigArg[]): ConfigArgValues<T> { const output: ConfigArgValues<T> = {} as any; for (const arg of args) { if (arg && arg.value != null && this.args[arg.name] != null) { output[arg.name as keyof ConfigArgValues<T>] = coerceValueToType<T>( arg.value, this.args[arg.name].type, this.args[arg.name].list || false, ); } } return output; } } function localizeString( stringArray: LocalizedStringArray, languageCode: LanguageCode, channelLanguageCode: LanguageCode, ): string { let match = stringArray.find(x => x.languageCode === languageCode); if (!match) { match = stringArray.find(x => x.languageCode === channelLanguageCode); } if (!match) { match = stringArray.find(x => x.languageCode === DEFAULT_LANGUAGE_CODE); } if (!match) { match = stringArray[0]; } return match.value; } function coerceValueToType<T extends ConfigArgs>( value: string, type: ConfigArgType, isList: boolean, ): ConfigArgValues<T>[keyof T] { if (isList) { try { return (JSON.parse(value) as string[]).map(v => coerceValueToType(v, type, false)) as any; } catch (err: any) { throw new InternalServerError( `Could not parse list value "${value}": ` + JSON.stringify(err.message), ); } } switch (type) { case 'string': return value as any; case 'int': return Number.parseInt(value || '', 10) as any; case 'float': return Number.parseFloat(value || '') as any; case 'datetime': return Date.parse(value || '') as any; case 'boolean': return !!(value && (value.toLowerCase() === 'true' || value === '1')) as any; case 'ID': return value as any; default: assertNever(type); } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { CrudPermissionDefinition, PermissionDefinition, PermissionMetadata } from './permission-definition'; /** * This value should be rarely used - only in those contexts where we have no access to the * VendureConfig to ensure at least a valid LanguageCode is available. */ export const DEFAULT_LANGUAGE_CODE = LanguageCode.en; export const TRANSACTION_MANAGER_KEY = Symbol('TRANSACTION_MANAGER'); export const REQUEST_CONTEXT_KEY = 'vendureRequestContext'; export const REQUEST_CONTEXT_MAP_KEY = 'vendureRequestContextMap'; export const DEFAULT_PERMISSIONS: PermissionDefinition[] = [ new PermissionDefinition({ name: 'Authenticated', description: 'Authenticated means simply that the user is logged in', assignable: true, internal: true, }), new PermissionDefinition({ name: 'SuperAdmin', description: 'SuperAdmin has unrestricted access to all operations', assignable: true, internal: true, }), new PermissionDefinition({ name: 'Owner', description: "Owner means the user owns this entity, e.g. a Customer's own Order", assignable: false, internal: true, }), new PermissionDefinition({ name: 'Public', description: 'Public means any unauthenticated user may perform the operation', assignable: false, internal: true, }), new PermissionDefinition({ name: 'UpdateGlobalSettings', description: 'Grants permission to update GlobalSettings', assignable: true, internal: false, }), new CrudPermissionDefinition( 'Catalog', operation => `Grants permission to ${operation} Products, Facets, Assets, Collections`, ), new CrudPermissionDefinition( 'Settings', operation => `Grants permission to ${operation} PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings`, ), new CrudPermissionDefinition('Administrator'), new CrudPermissionDefinition('Asset'), new CrudPermissionDefinition('Channel'), new CrudPermissionDefinition('Collection'), new CrudPermissionDefinition('Country'), new CrudPermissionDefinition('Customer'), new CrudPermissionDefinition('CustomerGroup'), new CrudPermissionDefinition('Facet'), new CrudPermissionDefinition('Order'), new CrudPermissionDefinition('PaymentMethod'), new CrudPermissionDefinition('Product'), new CrudPermissionDefinition('Promotion'), new CrudPermissionDefinition('ShippingMethod'), new CrudPermissionDefinition('Tag'), new CrudPermissionDefinition('TaxCategory'), new CrudPermissionDefinition('TaxRate'), new CrudPermissionDefinition('Seller'), new CrudPermissionDefinition('StockLocation'), new CrudPermissionDefinition('System'), new CrudPermissionDefinition('Zone'), ]; export function getAllPermissionsMetadata(customPermissions: PermissionDefinition[]): PermissionMetadata[] { const allPermissions = [...DEFAULT_PERMISSIONS, ...customPermissions]; return allPermissions.reduce((all, def) => [...all, ...def.getMetadata()], [] as PermissionMetadata[]); } export const CacheKey = { GlobalSettings: 'GlobalSettings', AllZones: 'AllZones', ActiveTaxZone: 'ActiveTaxZone', ActiveTaxZone_PPA: 'ActiveTaxZone_PPA', };
// eslint-disable-next-line @typescript-eslint/no-var-requires const { customAlphabet } = require('nanoid'); const nanoid = customAlphabet('123456789ABCDEFGHJKLMNPQRSTUVWXYZ', 16); /** * Generates a random, human-readable string of numbers and upper-case letters * for use as public-facing identifiers for things like order or customers. * * The restriction to only uppercase letters and numbers is intended to make * reading and reciting the generated string easier and less error-prone for people. * Note that the letters "O" and "I" and number 0 are also omitted because they are easily * confused. * * There is a trade-off between the length of the string and the probability * of collisions (the same ID being generated twice). We are using a length of * 16, which according to calculations (https://zelark.github.io/nano-id-cc/) * would require IDs to be generated at a rate of 1000/hour for 23k years to * reach a probability of 1% that a collision would occur. */ export function generatePublicId(): string { return nanoid(); }
export * from './finite-state-machine/finite-state-machine'; export * from './finite-state-machine/types'; export * from './async-queue'; export * from './calculated-decorator'; export * from './error/errors'; export * from './error/error-result'; export * from './error/generated-graphql-admin-errors'; export * from './injector'; export * from './permission-definition'; export * from './ttl-cache'; export * from './self-refreshing-cache'; export * from './round-money'; export * from './types/common-types'; export * from './types/entity-relation-paths'; export * from './types/injectable-strategy'; export * from './types/locale-types'; export * from './utils';
import { Type } from '@nestjs/common'; import { ContextId, ModuleRef } from '@nestjs/core'; import { getConnectionToken } from '@nestjs/typeorm'; import { Connection } from 'typeorm'; /** * @description * The Injector wraps the underlying Nestjs `ModuleRef`, allowing injection of providers * known to the application's dependency injection container. This is intended to enable the injection * of services into objects which exist outside of the Nestjs module system, e.g. the various * Strategies which can be supplied in the VendureConfig. * * @docsCategory common */ export class Injector { constructor(private moduleRef: ModuleRef) {} /** * @description * Retrieve an instance of the given type from the app's dependency injection container. * Wraps the Nestjs `ModuleRef.get()` method. */ get<T, R = T>(typeOrToken: Type<T> | string | symbol): R { return this.moduleRef.get(typeOrToken, { strict: false }); } /** * @description * Retrieve an instance of the given scoped provider (transient or request-scoped) from the * app's dependency injection container. * Wraps the Nestjs `ModuleRef.resolve()` method. */ resolve<T, R = T>(typeOrToken: Type<T> | string | symbol, contextId?: ContextId): Promise<R> { return this.moduleRef.resolve(typeOrToken, contextId, { strict: false }); } }
import { Permission } from '@vendure/common/lib/generated-types'; /** * @description * Configures a {@link PermissionDefinition} * * @docsCategory auth * @docsPage PermissionDefinition */ export interface PermissionDefinitionConfig { /** * @description * The name of the permission. By convention this should be * UpperCamelCased. */ name: string; /** * @description * A description of the permission. */ description?: string; /** * @description * Whether this permission can be assigned to a Role. In general this * should be left as the default `true` except in special cases. * * @default true */ assignable?: boolean; /** * @description * Internal permissions are not exposed via the API and are reserved for * special use-cases such at the `Owner` or `Public` permissions. * * @default false */ internal?: boolean; } /** * @description * Permission metadata used internally in generating the GraphQL `Permissions` enum. * * @internal */ export type PermissionMetadata = Required<PermissionDefinitionConfig>; /** * @description * Defines a new Permission with which to control access to GraphQL resolvers & REST controllers. * Used in conjunction with the {@link Allow} decorator (see example below). * * **Note:** To define CRUD permissions, use the {@link CrudPermissionDefinition}. * * @example * ```ts * export const sync = new PermissionDefinition({ * name: 'SyncInventory', * description: 'Allows syncing stock levels via Admin API' * }); * ``` * * ```ts * const config: VendureConfig = { * authOptions: { * customPermissions: [sync], * }, * } * ``` * * ```ts * \@Resolver() * export class ExternalSyncResolver { * * \@Allow(sync.Permission) * \@Mutation() * syncStockLevels() { * // ... * } * } * ``` * @docsCategory auth * @docsPage PermissionDefinition * @docsWeight 0 */ export class PermissionDefinition { constructor(protected config: PermissionDefinitionConfig) {} /** @internal */ getMetadata(): PermissionMetadata[] { const { name, description, assignable, internal } = this.config; return [ { name, description: description || `Grants permissions on ${name} operations`, assignable: assignable ?? true, internal: internal ?? false, }, ]; } /** * @description * Returns the permission defined by this definition, for use in the * {@link Allow} decorator. */ get Permission(): Permission { return this.config.name as Permission; } } /** * @description * Defines a set of CRUD Permissions for the given name, i.e. a `name` of 'Wishlist' will create * 4 Permissions: 'CreateWishlist', 'ReadWishlist', 'UpdateWishlist' & 'DeleteWishlist'. * * @example * ```ts * export const wishlist = new CrudPermissionDefinition('Wishlist'); * ``` * * ```ts * const config: VendureConfig = { * authOptions: { * customPermissions: [wishlist], * }, * } * ``` * * ```ts * \@Resolver() * export class WishlistResolver { * * \@Allow(wishlist.Create) * \@Mutation() * createWishlist() { * // ... * } * } * ``` * * @docsCategory auth * @docsPage PermissionDefinition * @docsWeight 1 */ export class CrudPermissionDefinition extends PermissionDefinition { constructor( name: string, private descriptionFn?: (operation: 'create' | 'read' | 'update' | 'delete') => string, ) { super({ name }); } /** @internal */ getMetadata(): PermissionMetadata[] { return ['Create', 'Read', 'Update', 'Delete'].map(operation => ({ name: `${operation}${this.config.name}`, description: typeof this.descriptionFn === 'function' ? this.descriptionFn(operation.toLocaleLowerCase() as any) : `Grants permission to ${operation.toLocaleLowerCase()} ${this.config.name}`, assignable: true, internal: false, })); } /** * @description * Returns the 'Create' CRUD permission defined by this definition, for use in the * {@link Allow} decorator. */ get Create(): Permission { return `Create${this.config.name}` as Permission; } /** * @description * Returns the 'Read' CRUD permission defined by this definition, for use in the * {@link Allow} decorator. */ get Read(): Permission { return `Read${this.config.name}` as Permission; } /** * @description * Returns the 'Update' CRUD permission defined by this definition, for use in the * {@link Allow} decorator. */ get Update(): Permission { return `Update${this.config.name}` as Permission; } /** * @description * Returns the 'Delete' CRUD permission defined by this definition, for use in the * {@link Allow} decorator. */ get Delete(): Permission { return `Delete${this.config.name}` as Permission; } }
import { getConfig } from '../config/config-helpers'; import { MoneyStrategy } from '../config/entity/money-strategy'; let moneyStrategy: MoneyStrategy; /** * @description * Rounds a monetary value according to the configured {@link MoneyStrategy}. * * @docsCategory money * @since 2.0.0 */ export function roundMoney(value: number, quantity = 1): number { if (!moneyStrategy) { moneyStrategy = getConfig().entityOptions.moneyStrategy; } return moneyStrategy.round(value, quantity); }
import { beforeAll, describe, expect, it, vi } from 'vitest'; import { createSelfRefreshingCache, SelfRefreshingCache } from './self-refreshing-cache'; describe('SelfRefreshingCache', () => { let testCache: SelfRefreshingCache<number, [string]>; const fetchFn = vi.fn().mockImplementation((arg: string) => arg.length); let currentTime = 0; beforeAll(async () => { testCache = await createSelfRefreshingCache<number, [string]>({ name: 'test', ttl: 1000, refresh: { fn: async arg => { return fetchFn(arg) as number; }, defaultArgs: ['default'], }, getTimeFn: () => currentTime, }); }); it('fetches value on first call', async () => { const result = await testCache.value(); expect(result).toBe(7); expect(fetchFn.mock.calls.length).toBe(1); }); it('passes default args on first call', () => { expect(fetchFn.mock.calls[0]).toEqual(['default']); }); it('return from cache on second call', async () => { const result = await testCache.value(); expect(result).toBe(7); expect(fetchFn.mock.calls.length).toBe(1); }); it('automatically refresh after ttl expires', async () => { currentTime = 1001; const result = await testCache.value('custom'); expect(result).toBe(6); expect(fetchFn.mock.calls.length).toBe(2); }); it('refresh forces fetch with supplied args', async () => { const result = await testCache.refresh('new arg which is longer'); expect(result).toBe(23); expect(fetchFn.mock.calls.length).toBe(3); expect(fetchFn.mock.calls[2]).toEqual(['new arg which is longer']); }); describe('memoization', () => { const memoizedFn = vi.fn(); let getMemoized: (arg1: string, arg2: number) => Promise<number>; beforeAll(() => { getMemoized = async (arg1, arg2) => { return testCache.memoize([arg1, arg2], ['quux'], async (value, a1, a2) => { memoizedFn(a1, a2); return value * +a2; }); }; }); it('calls the memoized function only once for the given args', async () => { const result1 = await getMemoized('foo', 1); expect(result1).toBe(23 * 1); expect(memoizedFn.mock.calls.length).toBe(1); expect(memoizedFn.mock.calls[0]).toEqual(['foo', 1]); const result2 = await getMemoized('foo', 1); expect(result2).toBe(23 * 1); expect(memoizedFn.mock.calls.length).toBe(1); }); it('calls the memoized function when args change', async () => { const result1 = await getMemoized('foo', 2); expect(result1).toBe(23 * 2); expect(memoizedFn.mock.calls.length).toBe(2); expect(memoizedFn.mock.calls[1]).toEqual(['foo', 2]); }); it('retains memoized results from earlier calls', async () => { const result1 = await getMemoized('foo', 1); expect(result1).toBe(23 * 1); expect(memoizedFn.mock.calls.length).toBe(2); }); it('re-fetches and re-runs memoized function after ttl expires', async () => { currentTime = 3000; const result1 = await getMemoized('foo', 1); expect(result1).toBe(4 * 1); expect(memoizedFn.mock.calls.length).toBe(3); await getMemoized('foo', 1); expect(memoizedFn.mock.calls.length).toBe(3); }); it('works with alternating calls', async () => { const result1 = await getMemoized('foo', 1); expect(result1).toBe(4 * 1); expect(memoizedFn.mock.calls.length).toBe(3); const result2 = await getMemoized('foo', 3); expect(result2).toBe(4 * 3); expect(memoizedFn.mock.calls.length).toBe(4); const result3 = await getMemoized('foo', 1); expect(result3).toBe(4 * 1); expect(memoizedFn.mock.calls.length).toBe(4); const result4 = await getMemoized('foo', 3); expect(result4).toBe(4 * 3); expect(memoizedFn.mock.calls.length).toBe(4); const result5 = await getMemoized('foo', 1); expect(result5).toBe(4 * 1); expect(memoizedFn.mock.calls.length).toBe(4); }); }); });
import { Json } from '@vendure/common/lib/shared-types'; import { Logger } from '../config/logger/vendure-logger'; /** * @description * A cache which automatically refreshes itself if the value is found to be stale. */ export interface SelfRefreshingCache<V, RefreshArgs extends any[] = []> { /** * @description * The current value of the cache. If the value is stale, the data will be refreshed and then * the fresh value will be returned. */ value(...refreshArgs: RefreshArgs | [undefined] | []): Promise<V>; /** * @description * Allows a memoized function to be defined. For the given arguments, the `fn` function will * be invoked only once and its output cached and returned. * The results cache is cleared along with the rest of the cache according to the configured * `ttl` value. */ memoize<Args extends any[], R>( args: Args, refreshArgs: RefreshArgs, fn: (value: V, ...args: Args) => R, ): Promise<R>; /** * @description * Force a refresh of the value, e.g. when it is known that the value has changed such as after * an update operation to the source data in the database. */ refresh(...args: RefreshArgs): Promise<V>; } export interface SelfRefreshingCacheConfig<V, RefreshArgs extends any[]> { name: string; ttl: number; refresh: { fn: (...args: RefreshArgs) => Promise<V>; /** * Default arguments, passed to refresh function */ defaultArgs: RefreshArgs; }; /** * Intended for unit testing the SelfRefreshingCache only. * By default uses `() => new Date().getTime()` */ getTimeFn?: () => number; } /** * @description * Creates a {@link SelfRefreshingCache} object, which is used to cache a single frequently-accessed value. In this type * of cache, the function used to populate the value (`refreshFn`) is defined during the creation of the cache, and * it is immediately used to populate the initial value. * * From there, when the `.value` property is accessed, it will return a value from the cache, and if the * value has expired, it will automatically run the `refreshFn` to update the value and then return the * fresh value. */ export async function createSelfRefreshingCache<V, RefreshArgs extends any[]>( config: SelfRefreshingCacheConfig<V, RefreshArgs>, refreshArgs?: RefreshArgs, ): Promise<SelfRefreshingCache<V, RefreshArgs>> { const { ttl, name, refresh, getTimeFn } = config; const getTimeNow = getTimeFn ?? (() => new Date().getTime()); const initialValue: V = await refresh.fn(...(refreshArgs ?? refresh.defaultArgs)); let value = initialValue; let expires = getTimeNow() + ttl; const memoCache = new Map<string, { expires: number; value: any }>(); const refreshValue = (resetMemoCache = true, args: RefreshArgs): Promise<V> => { return refresh .fn(...args) .then(newValue => { value = newValue; expires = getTimeNow() + ttl; if (resetMemoCache) { memoCache.clear(); } return value; }) .catch((err: any) => { const _message = err.message; const message = typeof _message === 'string' ? _message : JSON.stringify(err.message); Logger.error( `Failed to update SelfRefreshingCache "${name}": ${message}`, undefined, err.stack, ); return value; }); }; const getValue = async (_refreshArgs?: RefreshArgs, resetMemoCache = true): Promise<V> => { const now = getTimeNow(); if (expires < now) { return refreshValue(resetMemoCache, _refreshArgs ?? refresh.defaultArgs); } return value; }; const memoize = async <Args extends any[], R>( args: Args, _refreshArgs: RefreshArgs, fn: (value: V, ...args: Args) => R, ): Promise<R> => { const key = JSON.stringify(args); const cached = memoCache.get(key); const now = getTimeNow(); if (cached && now < cached.expires) { return cached.value; } const result = getValue(_refreshArgs, false).then(val => fn(val, ...args)); memoCache.set(key, { expires: now + ttl, value: result, }); return result; }; return { value: (...args) => getValue( !args.length || (args.length === 1 && args[0] === undefined) ? undefined : (args as RefreshArgs), ), refresh: (...args) => refreshValue(true, args), memoize, }; }
/** * Returns the tax component of a given gross price. */ export function taxComponentOf(grossPrice: number, taxRatePc: number): number { return grossPrice - grossPrice / ((100 + taxRatePc) / 100); } /** * Given a gross (tax-inclusive) price, returns the net price. */ export function netPriceOf(grossPrice: number, taxRatePc: number): number { return grossPrice - taxComponentOf(grossPrice, taxRatePc); } /** * Returns the tax applicable to the given net price. */ export function taxPayableOn(netPrice: number, taxRatePc: number): number { return netPrice * (taxRatePc / 100); } /** * Given a net price, return the gross price (net + tax) */ export function grossPriceOf(netPrice: number, taxRatePc: number): number { return netPrice + taxPayableOn(netPrice, taxRatePc); }
/** * An in-memory cache with a configurable TTL (time to live) which means cache items * expire after they have been in the cache longer than that time. * * The `ttl` config option is in milliseconds. Defaults to 30 seconds TTL and a cache size of 1000. */ export class TtlCache<K, V> { private cache = new Map<K, { value: V; expires: number }>(); private readonly ttl: number = 30 * 1000; private readonly cacheSize: number = 1000; constructor(config?: { ttl?: number; cacheSize?: number }) { if (config?.ttl) { this.ttl = config.ttl; } if (config?.cacheSize) { this.cacheSize = config.cacheSize; } } get(key: K): V | undefined { const hit = this.cache.get(key); const now = new Date().getTime(); if (hit) { if (now < hit.expires) { return hit.value; } else { this.cache.delete(key); } } } set(key: K, value: V) { if (this.cache.has(key)) { // delete key to put the item to the end of // the cache, marking it as new again this.cache.delete(key); } else if (this.cache.size === this.cacheSize) { // evict oldest this.cache.delete(this.first()); } this.cache.set(key, { value, expires: new Date().getTime() + this.ttl, }); } delete(key: K) { this.cache.delete(key); } private first() { return this.cache.keys().next().value; } }
import { describe, expect, it } from 'vitest'; import { convertRelationPaths, isEmailAddressLike, normalizeEmailAddress } from './utils'; describe('convertRelationPaths()', () => { it('undefined', () => { const result = convertRelationPaths<any>(undefined); expect(result).toEqual(undefined); }); it('null', () => { const result = convertRelationPaths<any>(null); expect(result).toEqual(undefined); }); it('single relation', () => { const result = convertRelationPaths<any>(['a']); expect(result).toEqual({ a: true, }); }); it('flat list', () => { const result = convertRelationPaths<any>(['a', 'b', 'c']); expect(result).toEqual({ a: true, b: true, c: true, }); }); it('three-level nested', () => { const result = convertRelationPaths<any>(['a', 'b.c', 'd.e.f']); expect(result).toEqual({ a: true, b: { c: true, }, d: { e: { f: true, }, }, }); }); }); describe('normalizeEmailAddress()', () => { it('should trim whitespace', () => { expect(normalizeEmailAddress(' test@test.com ')).toBe('test@test.com'); }); it('should lowercase email addresses', async () => { expect(normalizeEmailAddress('JoeSmith@test.com')).toBe('joesmith@test.com'); expect(normalizeEmailAddress('TEST@TEST.COM')).toBe('test@test.com'); expect(normalizeEmailAddress('test.person@TEST.COM')).toBe('test.person@test.com'); expect(normalizeEmailAddress('test.person+Extra@TEST.COM')).toBe('test.person+extra@test.com'); expect(normalizeEmailAddress('TEST-person+Extra@TEST.COM')).toBe('test-person+extra@test.com'); expect(normalizeEmailAddress('我買@屋企.香港')).toBe('我買@屋企.香港'); }); it('ignores surrounding whitespace', async () => { expect(normalizeEmailAddress(' JoeSmith@test.com')).toBe('joesmith@test.com'); expect(normalizeEmailAddress('TEST@TEST.COM ')).toBe('test@test.com'); expect(normalizeEmailAddress(' test.person@TEST.COM ')).toBe('test.person@test.com'); }); it('should not lowercase non-email address identifiers', async () => { expect(normalizeEmailAddress('Test')).toBe('Test'); expect(normalizeEmailAddress('Ucj30Da2.!3rAA')).toBe('Ucj30Da2.!3rAA'); }); }); describe('isEmailAddressLike()', () => { it('returns true for valid email addresses', () => { expect(isEmailAddressLike('simple@example.com')).toBe(true); expect(isEmailAddressLike('very.common@example.com')).toBe(true); expect(isEmailAddressLike('abc@example.co.uk')).toBe(true); expect(isEmailAddressLike('disposable.style.email.with+symbol@example.com')).toBe(true); expect(isEmailAddressLike('other.email-with-hyphen@example.com')).toBe(true); expect(isEmailAddressLike('fully-qualified-domain@example.com')).toBe(true); expect(isEmailAddressLike('user.name+tag+sorting@example.com')).toBe(true); expect(isEmailAddressLike('example-indeed@strange-example.com')).toBe(true); expect(isEmailAddressLike('example-indeed@strange-example.inininini')).toBe(true); }); it('ignores surrounding whitespace', () => { expect(isEmailAddressLike(' simple@example.com')).toBe(true); expect(isEmailAddressLike('very.common@example.com ')).toBe(true); expect(isEmailAddressLike(' abc@example.co.uk ')).toBe(true); }); it('returns false for invalid email addresses', () => { expect(isEmailAddressLike('username')).toBe(false); expect(isEmailAddressLike('823@ee28qje')).toBe(false); expect(isEmailAddressLike('Abc.example.com')).toBe(false); expect(isEmailAddressLike('A@b@')).toBe(false); }); });
import { AssetType } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { lastValueFrom, Observable, Observer } from 'rxjs'; import { FindOptionsRelations } from 'typeorm/find-options/FindOptionsRelations'; import { RelationPaths } from '../api/decorators/relations.decorator'; import { VendureEntity } from '../entity/base/base.entity'; /** * Takes a predicate function and returns a negated version. */ export function not(predicate: (...args: any[]) => boolean) { return (...args: any[]) => !predicate(...args); } /** * Returns a predicate function which returns true if the item is found in the set, * as determined by a === equality check on the given compareBy property. */ export function foundIn<T>(set: T[], compareBy: keyof T) { return (item: T) => set.some(t => t[compareBy] === item[compareBy]); } /** * Identity function which asserts to the type system that a promise which can resolve to T or undefined * does in fact resolve to T. * Used when performing a "find" operation on an entity which we are sure exists, as in the case that we * just successfully created or updated it. */ export function assertFound<T>(promise: Promise<T | undefined | null>): Promise<T> { return promise as Promise<T>; } /** * Compare ID values for equality, taking into account the fact that they may not be of matching types * (string or number). */ export function idsAreEqual(id1?: ID, id2?: ID): boolean { if (id1 === undefined || id2 === undefined) { return false; } return id1.toString() === id2.toString(); } /** * Returns the AssetType based on the mime type. */ export function getAssetType(mimeType: string): AssetType { const type = mimeType.split('/')[0]; switch (type) { case 'image': return AssetType.IMAGE; case 'video': return AssetType.VIDEO; default: return AssetType.BINARY; } } /** * A simple normalization for email addresses. Lowercases the whole address, * even though technically the local part (before the '@') is case-sensitive * per the spec. In practice, however, it seems safe to treat emails as * case-insensitive to allow for users who might vary the usage of * upper/lower case. See more discussion here: https://ux.stackexchange.com/a/16849 */ export function normalizeEmailAddress(input: string): string { return isEmailAddressLike(input) ? input.trim().toLowerCase() : input.trim(); } /** * This is a "good enough" check for whether the input is an email address. * From https://stackoverflow.com/a/32686261 * It is used to determine whether to apply normalization (lower-casing) * when comparing identifiers in user lookups. This allows case-sensitive * identifiers for other authentication methods. */ export function isEmailAddressLike(input: string): boolean { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.trim()); } /** * Converts a value that may be wrapped into a Promise or Observable into a Promise-wrapped * value. */ export async function awaitPromiseOrObservable<T>(value: T | Promise<T> | Observable<T>): Promise<T> { let result = await value; if (result instanceof Observable) { result = await lastValueFrom(result); } return result; } /** * @description * Returns an observable which executes the given async work function and completes with * the returned value. This is useful in methods which need to return * an Observable but also want to work with async (Promise-returning) code. * * @example * ```ts * \@Controller() * export class MyWorkerController { * * \@MessagePattern('test') * handleTest() { * return asyncObservable(async observer => { * const value = await this.connection.fetchSomething(); * return value; * }); * } * } * ``` */ export function asyncObservable<T>(work: (observer: Observer<T>) => Promise<T | void>): Observable<T> { return new Observable<T>(subscriber => { void (async () => { try { const result = await work(subscriber); if (result) { subscriber.next(result); } subscriber.complete(); } catch (e: any) { subscriber.error(e); } })(); }); } export function convertRelationPaths<T extends VendureEntity>( relationPaths?: RelationPaths<T> | null, ): FindOptionsRelations<T> | undefined { const result: FindOptionsRelations<T> = {}; if (relationPaths == null) { return undefined; } for (const path of relationPaths) { const parts = (path as string).split('.'); let current: any = result; for (const [i, part] of Object.entries(parts)) { if (!current[part]) { current[part] = +i === parts.length - 1 ? true : {}; } current = current[part]; } } return result; }
import { VendureEntity } from '../../entity/base/base.entity'; export type GraphQLErrorResult = { errorCode: string; message: string; }; /** * @description * Takes an ErrorResult union type (i.e. a generated union type consisting of some query/mutation result * plus one or more ErrorResult types) and returns a union of _just_ the ErrorResult types. * * @example * ```ts * type UpdateOrderItemsResult = Order | OrderModificationError | OrderLimitError | NegativeQuantityError; * * type T1 = JustErrorResults<UpdateOrderItemsResult>; * // T1 = OrderModificationError | OrderLimitError | NegativeQuantityError * ``` */ export type JustErrorResults<T extends GraphQLErrorResult | U, U = any> = Exclude< T, T extends GraphQLErrorResult ? never : T >; /** * @description * Used to construct a TypeScript return type for a query or mutation which, in the GraphQL schema, * returns a union type composed of a success result (e.g. Order) plus one or more ErrorResult * types. * * Since the TypeScript entities do not correspond 1-to-1 with their GraphQL type counterparts, * we use this type to substitute them. * * @example * ```ts * type UpdateOrderItemsResult = Order | OrderModificationError | OrderLimitError | NegativeQuantityError; * type T1 = ErrorResultUnion<UpdateOrderItemsResult, VendureEntityOrder>; * // T1 = VendureEntityOrder | OrderModificationError | OrderLimitError | NegativeQuantityError; * ``` * * @docsCategory errors */ export type ErrorResultUnion<T extends GraphQLErrorResult | U, E extends VendureEntity, U = any> = | JustErrorResults<T> | E; /** * @description * Returns true if the {@link ErrorResultUnion} is actually an ErrorResult type. This is useful when dealing with * certain internal service method that return an ErrorResultUnion. * * @example * ```ts * import { isGraphQlErrorResult } from '\@vendure/core'; * * // ... * * const transitionResult = await this.orderService.transitionToState(ctx, order.id, newState); * if (isGraphQlErrorResult(transitionResult)) { * // The transition failed with an ErrorResult * throw transitionResult; * } else { * // TypeScript will correctly infer the type of `transitionResult` to be `Order` * return transitionResult; * } * ``` * * @docsCategory errors */ export function isGraphQlErrorResult<T extends GraphQLErrorResult | U, U = any>( input: T, ): input is JustErrorResults<T>; export function isGraphQlErrorResult<T, E extends VendureEntity>( input: ErrorResultUnion<T, E>, ): input is JustErrorResults<ErrorResultUnion<T, E>> { return ( input && !!( (input as unknown as GraphQLErrorResult).errorCode && (input as unknown as GraphQLErrorResult).message != null ) && (input as any).__typename ); }
import { ID } from '@vendure/common/lib/shared-types'; import { LogLevel } from '../../config/logger/vendure-logger'; import { coreEntitiesMap } from '../../entity/entities'; import { I18nError } from '../../i18n/i18n-error'; /** * @description * This error should be thrown when some unexpected and exceptional case is encountered. * * @docsCategory errors * @docsPage Error Types */ export class InternalServerError extends I18nError { constructor(message: string, variables: { [key: string]: string | number } = {}) { super(message, variables, 'INTERNAL_SERVER_ERROR', LogLevel.Error); } } /** * @description * This error should be thrown when user input is not as expected. * * @docsCategory errors * @docsPage Error Types */ export class UserInputError extends I18nError { constructor(message: string, variables: { [key: string]: string | number } = {}) { super(message, variables, 'USER_INPUT_ERROR', LogLevel.Warn); } } /** * @description * This error should be thrown when an operation is attempted which is not allowed. * * @docsCategory errors * @docsPage Error Types */ export class IllegalOperationError extends I18nError { constructor(message: string, variables: { [key: string]: string | number } = {}) { super(message, variables, 'ILLEGAL_OPERATION', LogLevel.Warn); } } /** * @description * This error should be thrown when the user's authentication credentials do not match. * * @docsCategory errors * @docsPage Error Types */ export class UnauthorizedError extends I18nError { constructor() { super('error.unauthorized', {}, 'UNAUTHORIZED', LogLevel.Info); } } /** * @description * This error should be thrown when a user attempts to access a resource which is outside of * his or her privileges. * * @docsCategory errors * @docsPage Error Types */ export class ForbiddenError extends I18nError { constructor(logLevel: LogLevel = LogLevel.Warn) { super('error.forbidden', {}, 'FORBIDDEN', logLevel); } } /** * @description * This error should be thrown when a {@link Channel} cannot be found based on the provided * channel token. * * @docsCategory errors * @docsPage Error Types */ export class ChannelNotFoundError extends I18nError { constructor(token: string) { super('error.channel-not-found', { token }, 'CHANNEL_NOT_FOUND', LogLevel.Info); } } /** * @description * This error should be thrown when an entity cannot be found in the database, i.e. no entity of * the given entityName (Product, User etc.) exists with the provided id. * * @docsCategory errors * @docsPage Error Types */ export class EntityNotFoundError extends I18nError { constructor(entityName: keyof typeof coreEntitiesMap | string, id: ID) { super('error.entity-with-id-not-found', { entityName, id }, 'ENTITY_NOT_FOUND', LogLevel.Warn); } }
/* eslint-disable */ /** This file was generated by the graphql-errors-plugin, which is part of the "codegen" npm script. */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; DateTime: any; JSON: any; Money: any; Upload: any; }; export class ErrorResult { readonly __typename: string; readonly errorCode: string; readonly message: Scalars['String']; } export class AlreadyRefundedError extends ErrorResult { readonly __typename = 'AlreadyRefundedError'; readonly errorCode = 'ALREADY_REFUNDED_ERROR' as any; readonly message = 'ALREADY_REFUNDED_ERROR'; readonly refundId: Scalars['ID']; constructor( input: { refundId: Scalars['ID'] } ) { super(); this.refundId = input.refundId } } export class CancelActiveOrderError extends ErrorResult { readonly __typename = 'CancelActiveOrderError'; readonly errorCode = 'CANCEL_ACTIVE_ORDER_ERROR' as any; readonly message = 'CANCEL_ACTIVE_ORDER_ERROR'; readonly orderState: Scalars['String']; constructor( input: { orderState: Scalars['String'] } ) { super(); this.orderState = input.orderState } } export class CancelPaymentError extends ErrorResult { readonly __typename = 'CancelPaymentError'; readonly errorCode = 'CANCEL_PAYMENT_ERROR' as any; readonly message = 'CANCEL_PAYMENT_ERROR'; readonly paymentErrorMessage: Scalars['String']; constructor( input: { paymentErrorMessage: Scalars['String'] } ) { super(); this.paymentErrorMessage = input.paymentErrorMessage } } export class ChannelDefaultLanguageError extends ErrorResult { readonly __typename = 'ChannelDefaultLanguageError'; readonly errorCode = 'CHANNEL_DEFAULT_LANGUAGE_ERROR' as any; readonly message = 'CHANNEL_DEFAULT_LANGUAGE_ERROR'; readonly channelCode: Scalars['String']; readonly language: Scalars['String']; constructor( input: { channelCode: Scalars['String'], language: Scalars['String'] } ) { super(); this.channelCode = input.channelCode this.language = input.language } } export class CouponCodeExpiredError extends ErrorResult { readonly __typename = 'CouponCodeExpiredError'; readonly errorCode = 'COUPON_CODE_EXPIRED_ERROR' as any; readonly message = 'COUPON_CODE_EXPIRED_ERROR'; readonly couponCode: Scalars['String']; constructor( input: { couponCode: Scalars['String'] } ) { super(); this.couponCode = input.couponCode } } export class CouponCodeInvalidError extends ErrorResult { readonly __typename = 'CouponCodeInvalidError'; readonly errorCode = 'COUPON_CODE_INVALID_ERROR' as any; readonly message = 'COUPON_CODE_INVALID_ERROR'; readonly couponCode: Scalars['String']; constructor( input: { couponCode: Scalars['String'] } ) { super(); this.couponCode = input.couponCode } } export class CouponCodeLimitError extends ErrorResult { readonly __typename = 'CouponCodeLimitError'; readonly errorCode = 'COUPON_CODE_LIMIT_ERROR' as any; readonly message = 'COUPON_CODE_LIMIT_ERROR'; readonly couponCode: Scalars['String']; readonly limit: Scalars['Int']; constructor( input: { couponCode: Scalars['String'], limit: Scalars['Int'] } ) { super(); this.couponCode = input.couponCode this.limit = input.limit } } export class CreateFulfillmentError extends ErrorResult { readonly __typename = 'CreateFulfillmentError'; readonly errorCode = 'CREATE_FULFILLMENT_ERROR' as any; readonly message = 'CREATE_FULFILLMENT_ERROR'; readonly fulfillmentHandlerError: Scalars['String']; constructor( input: { fulfillmentHandlerError: Scalars['String'] } ) { super(); this.fulfillmentHandlerError = input.fulfillmentHandlerError } } export class DuplicateEntityError extends ErrorResult { readonly __typename = 'DuplicateEntityError'; readonly errorCode = 'DUPLICATE_ENTITY_ERROR' as any; readonly message = 'DUPLICATE_ENTITY_ERROR'; readonly duplicationError: Scalars['String']; constructor( input: { duplicationError: Scalars['String'] } ) { super(); this.duplicationError = input.duplicationError } } export class EmailAddressConflictError extends ErrorResult { readonly __typename = 'EmailAddressConflictError'; readonly errorCode = 'EMAIL_ADDRESS_CONFLICT_ERROR' as any; readonly message = 'EMAIL_ADDRESS_CONFLICT_ERROR'; constructor( ) { super(); } } export class EmptyOrderLineSelectionError extends ErrorResult { readonly __typename = 'EmptyOrderLineSelectionError'; readonly errorCode = 'EMPTY_ORDER_LINE_SELECTION_ERROR' as any; readonly message = 'EMPTY_ORDER_LINE_SELECTION_ERROR'; constructor( ) { super(); } } export class FacetInUseError extends ErrorResult { readonly __typename = 'FacetInUseError'; readonly errorCode = 'FACET_IN_USE_ERROR' as any; readonly message = 'FACET_IN_USE_ERROR'; readonly facetCode: Scalars['String']; readonly productCount: Scalars['Int']; readonly variantCount: Scalars['Int']; constructor( input: { facetCode: Scalars['String'], productCount: Scalars['Int'], variantCount: Scalars['Int'] } ) { super(); this.facetCode = input.facetCode this.productCount = input.productCount this.variantCount = input.variantCount } } export class FulfillmentStateTransitionError extends ErrorResult { readonly __typename = 'FulfillmentStateTransitionError'; readonly errorCode = 'FULFILLMENT_STATE_TRANSITION_ERROR' as any; readonly message = 'FULFILLMENT_STATE_TRANSITION_ERROR'; readonly fromState: Scalars['String']; readonly toState: Scalars['String']; readonly transitionError: Scalars['String']; constructor( input: { fromState: Scalars['String'], toState: Scalars['String'], transitionError: Scalars['String'] } ) { super(); this.fromState = input.fromState this.toState = input.toState this.transitionError = input.transitionError } } export class GuestCheckoutError extends ErrorResult { readonly __typename = 'GuestCheckoutError'; readonly errorCode = 'GUEST_CHECKOUT_ERROR' as any; readonly message = 'GUEST_CHECKOUT_ERROR'; readonly errorDetail: Scalars['String']; constructor( input: { errorDetail: Scalars['String'] } ) { super(); this.errorDetail = input.errorDetail } } export class IneligibleShippingMethodError extends ErrorResult { readonly __typename = 'IneligibleShippingMethodError'; readonly errorCode = 'INELIGIBLE_SHIPPING_METHOD_ERROR' as any; readonly message = 'INELIGIBLE_SHIPPING_METHOD_ERROR'; constructor( ) { super(); } } export class InsufficientStockError extends ErrorResult { readonly __typename = 'InsufficientStockError'; readonly errorCode = 'INSUFFICIENT_STOCK_ERROR' as any; readonly message = 'INSUFFICIENT_STOCK_ERROR'; readonly order: any; readonly quantityAvailable: Scalars['Int']; constructor( input: { order: any, quantityAvailable: Scalars['Int'] } ) { super(); this.order = input.order this.quantityAvailable = input.quantityAvailable } } export class InsufficientStockOnHandError extends ErrorResult { readonly __typename = 'InsufficientStockOnHandError'; readonly errorCode = 'INSUFFICIENT_STOCK_ON_HAND_ERROR' as any; readonly message = 'INSUFFICIENT_STOCK_ON_HAND_ERROR'; readonly productVariantId: Scalars['ID']; readonly productVariantName: Scalars['String']; readonly stockOnHand: Scalars['Int']; constructor( input: { productVariantId: Scalars['ID'], productVariantName: Scalars['String'], stockOnHand: Scalars['Int'] } ) { super(); this.productVariantId = input.productVariantId this.productVariantName = input.productVariantName this.stockOnHand = input.stockOnHand } } export class InvalidCredentialsError extends ErrorResult { readonly __typename = 'InvalidCredentialsError'; readonly errorCode = 'INVALID_CREDENTIALS_ERROR' as any; readonly message = 'INVALID_CREDENTIALS_ERROR'; readonly authenticationError: Scalars['String']; constructor( input: { authenticationError: Scalars['String'] } ) { super(); this.authenticationError = input.authenticationError } } export class InvalidFulfillmentHandlerError extends ErrorResult { readonly __typename = 'InvalidFulfillmentHandlerError'; readonly errorCode = 'INVALID_FULFILLMENT_HANDLER_ERROR' as any; readonly message = 'INVALID_FULFILLMENT_HANDLER_ERROR'; constructor( ) { super(); } } export class ItemsAlreadyFulfilledError extends ErrorResult { readonly __typename = 'ItemsAlreadyFulfilledError'; readonly errorCode = 'ITEMS_ALREADY_FULFILLED_ERROR' as any; readonly message = 'ITEMS_ALREADY_FULFILLED_ERROR'; constructor( ) { super(); } } export class LanguageNotAvailableError extends ErrorResult { readonly __typename = 'LanguageNotAvailableError'; readonly errorCode = 'LANGUAGE_NOT_AVAILABLE_ERROR' as any; readonly message = 'LANGUAGE_NOT_AVAILABLE_ERROR'; readonly languageCode: Scalars['String']; constructor( input: { languageCode: Scalars['String'] } ) { super(); this.languageCode = input.languageCode } } export class ManualPaymentStateError extends ErrorResult { readonly __typename = 'ManualPaymentStateError'; readonly errorCode = 'MANUAL_PAYMENT_STATE_ERROR' as any; readonly message = 'MANUAL_PAYMENT_STATE_ERROR'; constructor( ) { super(); } } export class MimeTypeError extends ErrorResult { readonly __typename = 'MimeTypeError'; readonly errorCode = 'MIME_TYPE_ERROR' as any; readonly message = 'MIME_TYPE_ERROR'; readonly fileName: Scalars['String']; readonly mimeType: Scalars['String']; constructor( input: { fileName: Scalars['String'], mimeType: Scalars['String'] } ) { super(); this.fileName = input.fileName this.mimeType = input.mimeType } } export class MissingConditionsError extends ErrorResult { readonly __typename = 'MissingConditionsError'; readonly errorCode = 'MISSING_CONDITIONS_ERROR' as any; readonly message = 'MISSING_CONDITIONS_ERROR'; constructor( ) { super(); } } export class MultipleOrderError extends ErrorResult { readonly __typename = 'MultipleOrderError'; readonly errorCode = 'MULTIPLE_ORDER_ERROR' as any; readonly message = 'MULTIPLE_ORDER_ERROR'; constructor( ) { super(); } } export class NativeAuthStrategyError extends ErrorResult { readonly __typename = 'NativeAuthStrategyError'; readonly errorCode = 'NATIVE_AUTH_STRATEGY_ERROR' as any; readonly message = 'NATIVE_AUTH_STRATEGY_ERROR'; constructor( ) { super(); } } export class NegativeQuantityError extends ErrorResult { readonly __typename = 'NegativeQuantityError'; readonly errorCode = 'NEGATIVE_QUANTITY_ERROR' as any; readonly message = 'NEGATIVE_QUANTITY_ERROR'; constructor( ) { super(); } } export class NoActiveOrderError extends ErrorResult { readonly __typename = 'NoActiveOrderError'; readonly errorCode = 'NO_ACTIVE_ORDER_ERROR' as any; readonly message = 'NO_ACTIVE_ORDER_ERROR'; constructor( ) { super(); } } export class NoChangesSpecifiedError extends ErrorResult { readonly __typename = 'NoChangesSpecifiedError'; readonly errorCode = 'NO_CHANGES_SPECIFIED_ERROR' as any; readonly message = 'NO_CHANGES_SPECIFIED_ERROR'; constructor( ) { super(); } } export class NothingToRefundError extends ErrorResult { readonly __typename = 'NothingToRefundError'; readonly errorCode = 'NOTHING_TO_REFUND_ERROR' as any; readonly message = 'NOTHING_TO_REFUND_ERROR'; constructor( ) { super(); } } export class OrderLimitError extends ErrorResult { readonly __typename = 'OrderLimitError'; readonly errorCode = 'ORDER_LIMIT_ERROR' as any; readonly message = 'ORDER_LIMIT_ERROR'; readonly maxItems: Scalars['Int']; constructor( input: { maxItems: Scalars['Int'] } ) { super(); this.maxItems = input.maxItems } } export class OrderModificationError extends ErrorResult { readonly __typename = 'OrderModificationError'; readonly errorCode = 'ORDER_MODIFICATION_ERROR' as any; readonly message = 'ORDER_MODIFICATION_ERROR'; constructor( ) { super(); } } export class OrderModificationStateError extends ErrorResult { readonly __typename = 'OrderModificationStateError'; readonly errorCode = 'ORDER_MODIFICATION_STATE_ERROR' as any; readonly message = 'ORDER_MODIFICATION_STATE_ERROR'; constructor( ) { super(); } } export class OrderStateTransitionError extends ErrorResult { readonly __typename = 'OrderStateTransitionError'; readonly errorCode = 'ORDER_STATE_TRANSITION_ERROR' as any; readonly message = 'ORDER_STATE_TRANSITION_ERROR'; readonly fromState: Scalars['String']; readonly toState: Scalars['String']; readonly transitionError: Scalars['String']; constructor( input: { fromState: Scalars['String'], toState: Scalars['String'], transitionError: Scalars['String'] } ) { super(); this.fromState = input.fromState this.toState = input.toState this.transitionError = input.transitionError } } export class PaymentMethodMissingError extends ErrorResult { readonly __typename = 'PaymentMethodMissingError'; readonly errorCode = 'PAYMENT_METHOD_MISSING_ERROR' as any; readonly message = 'PAYMENT_METHOD_MISSING_ERROR'; constructor( ) { super(); } } export class PaymentOrderMismatchError extends ErrorResult { readonly __typename = 'PaymentOrderMismatchError'; readonly errorCode = 'PAYMENT_ORDER_MISMATCH_ERROR' as any; readonly message = 'PAYMENT_ORDER_MISMATCH_ERROR'; constructor( ) { super(); } } export class PaymentStateTransitionError extends ErrorResult { readonly __typename = 'PaymentStateTransitionError'; readonly errorCode = 'PAYMENT_STATE_TRANSITION_ERROR' as any; readonly message = 'PAYMENT_STATE_TRANSITION_ERROR'; readonly fromState: Scalars['String']; readonly toState: Scalars['String']; readonly transitionError: Scalars['String']; constructor( input: { fromState: Scalars['String'], toState: Scalars['String'], transitionError: Scalars['String'] } ) { super(); this.fromState = input.fromState this.toState = input.toState this.transitionError = input.transitionError } } export class ProductOptionInUseError extends ErrorResult { readonly __typename = 'ProductOptionInUseError'; readonly errorCode = 'PRODUCT_OPTION_IN_USE_ERROR' as any; readonly message = 'PRODUCT_OPTION_IN_USE_ERROR'; readonly optionGroupCode: Scalars['String']; readonly productVariantCount: Scalars['Int']; constructor( input: { optionGroupCode: Scalars['String'], productVariantCount: Scalars['Int'] } ) { super(); this.optionGroupCode = input.optionGroupCode this.productVariantCount = input.productVariantCount } } export class QuantityTooGreatError extends ErrorResult { readonly __typename = 'QuantityTooGreatError'; readonly errorCode = 'QUANTITY_TOO_GREAT_ERROR' as any; readonly message = 'QUANTITY_TOO_GREAT_ERROR'; constructor( ) { super(); } } export class RefundAmountError extends ErrorResult { readonly __typename = 'RefundAmountError'; readonly errorCode = 'REFUND_AMOUNT_ERROR' as any; readonly message = 'REFUND_AMOUNT_ERROR'; readonly maximumRefundable: Scalars['Int']; constructor( input: { maximumRefundable: Scalars['Int'] } ) { super(); this.maximumRefundable = input.maximumRefundable } } export class RefundOrderStateError extends ErrorResult { readonly __typename = 'RefundOrderStateError'; readonly errorCode = 'REFUND_ORDER_STATE_ERROR' as any; readonly message = 'REFUND_ORDER_STATE_ERROR'; readonly orderState: Scalars['String']; constructor( input: { orderState: Scalars['String'] } ) { super(); this.orderState = input.orderState } } export class RefundPaymentIdMissingError extends ErrorResult { readonly __typename = 'RefundPaymentIdMissingError'; readonly errorCode = 'REFUND_PAYMENT_ID_MISSING_ERROR' as any; readonly message = 'REFUND_PAYMENT_ID_MISSING_ERROR'; constructor( ) { super(); } } export class RefundStateTransitionError extends ErrorResult { readonly __typename = 'RefundStateTransitionError'; readonly errorCode = 'REFUND_STATE_TRANSITION_ERROR' as any; readonly message = 'REFUND_STATE_TRANSITION_ERROR'; readonly fromState: Scalars['String']; readonly toState: Scalars['String']; readonly transitionError: Scalars['String']; constructor( input: { fromState: Scalars['String'], toState: Scalars['String'], transitionError: Scalars['String'] } ) { super(); this.fromState = input.fromState this.toState = input.toState this.transitionError = input.transitionError } } export class SettlePaymentError extends ErrorResult { readonly __typename = 'SettlePaymentError'; readonly errorCode = 'SETTLE_PAYMENT_ERROR' as any; readonly message = 'SETTLE_PAYMENT_ERROR'; readonly paymentErrorMessage: Scalars['String']; constructor( input: { paymentErrorMessage: Scalars['String'] } ) { super(); this.paymentErrorMessage = input.paymentErrorMessage } } const errorTypeNames = new Set<string>(['AlreadyRefundedError', 'CancelActiveOrderError', 'CancelPaymentError', 'ChannelDefaultLanguageError', 'CouponCodeExpiredError', 'CouponCodeInvalidError', 'CouponCodeLimitError', 'CreateFulfillmentError', 'DuplicateEntityError', 'EmailAddressConflictError', 'EmptyOrderLineSelectionError', 'FacetInUseError', 'FulfillmentStateTransitionError', 'GuestCheckoutError', 'IneligibleShippingMethodError', 'InsufficientStockError', 'InsufficientStockOnHandError', 'InvalidCredentialsError', 'InvalidFulfillmentHandlerError', 'ItemsAlreadyFulfilledError', 'LanguageNotAvailableError', 'ManualPaymentStateError', 'MimeTypeError', 'MissingConditionsError', 'MultipleOrderError', 'NativeAuthStrategyError', 'NegativeQuantityError', 'NoActiveOrderError', 'NoChangesSpecifiedError', 'NothingToRefundError', 'OrderLimitError', 'OrderModificationError', 'OrderModificationStateError', 'OrderStateTransitionError', 'PaymentMethodMissingError', 'PaymentOrderMismatchError', 'PaymentStateTransitionError', 'ProductOptionInUseError', 'QuantityTooGreatError', 'RefundAmountError', 'RefundOrderStateError', 'RefundPaymentIdMissingError', 'RefundStateTransitionError', 'SettlePaymentError']); function isGraphQLError(input: any): input is import('@vendure/common/lib/generated-types').ErrorResult { return input instanceof ErrorResult || errorTypeNames.has(input.__typename); } export const adminErrorOperationTypeResolvers = { AddFulfillmentToOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Fulfillment'; }, }, UpdateOrderItemsResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, AddManualPaymentToOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, ApplyCouponCodeResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, AuthenticationResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'CurrentUser'; }, }, CancelOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, CancelPaymentResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Payment'; }, }, CreateAssetResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Asset'; }, }, CreateChannelResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Channel'; }, }, CreateCustomerResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Customer'; }, }, CreatePromotionResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Promotion'; }, }, DuplicateEntityResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'DuplicateEntitySuccess'; }, }, NativeAuthenticationResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'CurrentUser'; }, }, ModifyOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, RefundOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Refund'; }, }, RemoveOrderItemsResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, RemoveFacetFromChannelResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Facet'; }, }, RemoveOptionGroupFromProductResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Product'; }, }, SetCustomerForDraftOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, SetOrderShippingMethodResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, SettlePaymentResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Payment'; }, }, SettleRefundResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Refund'; }, }, TransitionFulfillmentToStateResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Fulfillment'; }, }, TransitionOrderToStateResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, TransitionPaymentToStateResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Payment'; }, }, UpdateChannelResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Channel'; }, }, UpdateCustomerResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Customer'; }, }, UpdateGlobalSettingsResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'GlobalSettings'; }, }, UpdatePromotionResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Promotion'; }, }, };
/* eslint-disable */ /** This file was generated by the graphql-errors-plugin, which is part of the "codegen" npm script. */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; DateTime: any; JSON: any; Money: any; Upload: any; }; export class ErrorResult { readonly __typename: string; readonly errorCode: string; readonly message: Scalars['String']; } export class AlreadyLoggedInError extends ErrorResult { readonly __typename = 'AlreadyLoggedInError'; readonly errorCode = 'ALREADY_LOGGED_IN_ERROR' as any; readonly message = 'ALREADY_LOGGED_IN_ERROR'; constructor( ) { super(); } } export class CouponCodeExpiredError extends ErrorResult { readonly __typename = 'CouponCodeExpiredError'; readonly errorCode = 'COUPON_CODE_EXPIRED_ERROR' as any; readonly message = 'COUPON_CODE_EXPIRED_ERROR'; readonly couponCode: Scalars['String']; constructor( input: { couponCode: Scalars['String'] } ) { super(); this.couponCode = input.couponCode } } export class CouponCodeInvalidError extends ErrorResult { readonly __typename = 'CouponCodeInvalidError'; readonly errorCode = 'COUPON_CODE_INVALID_ERROR' as any; readonly message = 'COUPON_CODE_INVALID_ERROR'; readonly couponCode: Scalars['String']; constructor( input: { couponCode: Scalars['String'] } ) { super(); this.couponCode = input.couponCode } } export class CouponCodeLimitError extends ErrorResult { readonly __typename = 'CouponCodeLimitError'; readonly errorCode = 'COUPON_CODE_LIMIT_ERROR' as any; readonly message = 'COUPON_CODE_LIMIT_ERROR'; readonly couponCode: Scalars['String']; readonly limit: Scalars['Int']; constructor( input: { couponCode: Scalars['String'], limit: Scalars['Int'] } ) { super(); this.couponCode = input.couponCode this.limit = input.limit } } export class EmailAddressConflictError extends ErrorResult { readonly __typename = 'EmailAddressConflictError'; readonly errorCode = 'EMAIL_ADDRESS_CONFLICT_ERROR' as any; readonly message = 'EMAIL_ADDRESS_CONFLICT_ERROR'; constructor( ) { super(); } } export class GuestCheckoutError extends ErrorResult { readonly __typename = 'GuestCheckoutError'; readonly errorCode = 'GUEST_CHECKOUT_ERROR' as any; readonly message = 'GUEST_CHECKOUT_ERROR'; readonly errorDetail: Scalars['String']; constructor( input: { errorDetail: Scalars['String'] } ) { super(); this.errorDetail = input.errorDetail } } export class IdentifierChangeTokenExpiredError extends ErrorResult { readonly __typename = 'IdentifierChangeTokenExpiredError'; readonly errorCode = 'IDENTIFIER_CHANGE_TOKEN_EXPIRED_ERROR' as any; readonly message = 'IDENTIFIER_CHANGE_TOKEN_EXPIRED_ERROR'; constructor( ) { super(); } } export class IdentifierChangeTokenInvalidError extends ErrorResult { readonly __typename = 'IdentifierChangeTokenInvalidError'; readonly errorCode = 'IDENTIFIER_CHANGE_TOKEN_INVALID_ERROR' as any; readonly message = 'IDENTIFIER_CHANGE_TOKEN_INVALID_ERROR'; constructor( ) { super(); } } export class IneligiblePaymentMethodError extends ErrorResult { readonly __typename = 'IneligiblePaymentMethodError'; readonly errorCode = 'INELIGIBLE_PAYMENT_METHOD_ERROR' as any; readonly message = 'INELIGIBLE_PAYMENT_METHOD_ERROR'; readonly eligibilityCheckerMessage: any; constructor( input: { eligibilityCheckerMessage: any } ) { super(); this.eligibilityCheckerMessage = input.eligibilityCheckerMessage } } export class IneligibleShippingMethodError extends ErrorResult { readonly __typename = 'IneligibleShippingMethodError'; readonly errorCode = 'INELIGIBLE_SHIPPING_METHOD_ERROR' as any; readonly message = 'INELIGIBLE_SHIPPING_METHOD_ERROR'; constructor( ) { super(); } } export class InsufficientStockError extends ErrorResult { readonly __typename = 'InsufficientStockError'; readonly errorCode = 'INSUFFICIENT_STOCK_ERROR' as any; readonly message = 'INSUFFICIENT_STOCK_ERROR'; readonly order: any; readonly quantityAvailable: Scalars['Int']; constructor( input: { order: any, quantityAvailable: Scalars['Int'] } ) { super(); this.order = input.order this.quantityAvailable = input.quantityAvailable } } export class InvalidCredentialsError extends ErrorResult { readonly __typename = 'InvalidCredentialsError'; readonly errorCode = 'INVALID_CREDENTIALS_ERROR' as any; readonly message = 'INVALID_CREDENTIALS_ERROR'; readonly authenticationError: Scalars['String']; constructor( input: { authenticationError: Scalars['String'] } ) { super(); this.authenticationError = input.authenticationError } } export class MissingPasswordError extends ErrorResult { readonly __typename = 'MissingPasswordError'; readonly errorCode = 'MISSING_PASSWORD_ERROR' as any; readonly message = 'MISSING_PASSWORD_ERROR'; constructor( ) { super(); } } export class NativeAuthStrategyError extends ErrorResult { readonly __typename = 'NativeAuthStrategyError'; readonly errorCode = 'NATIVE_AUTH_STRATEGY_ERROR' as any; readonly message = 'NATIVE_AUTH_STRATEGY_ERROR'; constructor( ) { super(); } } export class NegativeQuantityError extends ErrorResult { readonly __typename = 'NegativeQuantityError'; readonly errorCode = 'NEGATIVE_QUANTITY_ERROR' as any; readonly message = 'NEGATIVE_QUANTITY_ERROR'; constructor( ) { super(); } } export class NoActiveOrderError extends ErrorResult { readonly __typename = 'NoActiveOrderError'; readonly errorCode = 'NO_ACTIVE_ORDER_ERROR' as any; readonly message = 'NO_ACTIVE_ORDER_ERROR'; constructor( ) { super(); } } export class NotVerifiedError extends ErrorResult { readonly __typename = 'NotVerifiedError'; readonly errorCode = 'NOT_VERIFIED_ERROR' as any; readonly message = 'NOT_VERIFIED_ERROR'; constructor( ) { super(); } } export class OrderLimitError extends ErrorResult { readonly __typename = 'OrderLimitError'; readonly errorCode = 'ORDER_LIMIT_ERROR' as any; readonly message = 'ORDER_LIMIT_ERROR'; readonly maxItems: Scalars['Int']; constructor( input: { maxItems: Scalars['Int'] } ) { super(); this.maxItems = input.maxItems } } export class OrderModificationError extends ErrorResult { readonly __typename = 'OrderModificationError'; readonly errorCode = 'ORDER_MODIFICATION_ERROR' as any; readonly message = 'ORDER_MODIFICATION_ERROR'; constructor( ) { super(); } } export class OrderPaymentStateError extends ErrorResult { readonly __typename = 'OrderPaymentStateError'; readonly errorCode = 'ORDER_PAYMENT_STATE_ERROR' as any; readonly message = 'ORDER_PAYMENT_STATE_ERROR'; constructor( ) { super(); } } export class OrderStateTransitionError extends ErrorResult { readonly __typename = 'OrderStateTransitionError'; readonly errorCode = 'ORDER_STATE_TRANSITION_ERROR' as any; readonly message = 'ORDER_STATE_TRANSITION_ERROR'; readonly fromState: Scalars['String']; readonly toState: Scalars['String']; readonly transitionError: Scalars['String']; constructor( input: { fromState: Scalars['String'], toState: Scalars['String'], transitionError: Scalars['String'] } ) { super(); this.fromState = input.fromState this.toState = input.toState this.transitionError = input.transitionError } } export class PasswordAlreadySetError extends ErrorResult { readonly __typename = 'PasswordAlreadySetError'; readonly errorCode = 'PASSWORD_ALREADY_SET_ERROR' as any; readonly message = 'PASSWORD_ALREADY_SET_ERROR'; constructor( ) { super(); } } export class PasswordResetTokenExpiredError extends ErrorResult { readonly __typename = 'PasswordResetTokenExpiredError'; readonly errorCode = 'PASSWORD_RESET_TOKEN_EXPIRED_ERROR' as any; readonly message = 'PASSWORD_RESET_TOKEN_EXPIRED_ERROR'; constructor( ) { super(); } } export class PasswordResetTokenInvalidError extends ErrorResult { readonly __typename = 'PasswordResetTokenInvalidError'; readonly errorCode = 'PASSWORD_RESET_TOKEN_INVALID_ERROR' as any; readonly message = 'PASSWORD_RESET_TOKEN_INVALID_ERROR'; constructor( ) { super(); } } export class PasswordValidationError extends ErrorResult { readonly __typename = 'PasswordValidationError'; readonly errorCode = 'PASSWORD_VALIDATION_ERROR' as any; readonly message = 'PASSWORD_VALIDATION_ERROR'; readonly validationErrorMessage: Scalars['String']; constructor( input: { validationErrorMessage: Scalars['String'] } ) { super(); this.validationErrorMessage = input.validationErrorMessage } } export class PaymentDeclinedError extends ErrorResult { readonly __typename = 'PaymentDeclinedError'; readonly errorCode = 'PAYMENT_DECLINED_ERROR' as any; readonly message = 'PAYMENT_DECLINED_ERROR'; readonly paymentErrorMessage: Scalars['String']; constructor( input: { paymentErrorMessage: Scalars['String'] } ) { super(); this.paymentErrorMessage = input.paymentErrorMessage } } export class PaymentFailedError extends ErrorResult { readonly __typename = 'PaymentFailedError'; readonly errorCode = 'PAYMENT_FAILED_ERROR' as any; readonly message = 'PAYMENT_FAILED_ERROR'; readonly paymentErrorMessage: Scalars['String']; constructor( input: { paymentErrorMessage: Scalars['String'] } ) { super(); this.paymentErrorMessage = input.paymentErrorMessage } } export class VerificationTokenExpiredError extends ErrorResult { readonly __typename = 'VerificationTokenExpiredError'; readonly errorCode = 'VERIFICATION_TOKEN_EXPIRED_ERROR' as any; readonly message = 'VERIFICATION_TOKEN_EXPIRED_ERROR'; constructor( ) { super(); } } export class VerificationTokenInvalidError extends ErrorResult { readonly __typename = 'VerificationTokenInvalidError'; readonly errorCode = 'VERIFICATION_TOKEN_INVALID_ERROR' as any; readonly message = 'VERIFICATION_TOKEN_INVALID_ERROR'; constructor( ) { super(); } } const errorTypeNames = new Set<string>(['AlreadyLoggedInError', 'CouponCodeExpiredError', 'CouponCodeInvalidError', 'CouponCodeLimitError', 'EmailAddressConflictError', 'GuestCheckoutError', 'IdentifierChangeTokenExpiredError', 'IdentifierChangeTokenInvalidError', 'IneligiblePaymentMethodError', 'IneligibleShippingMethodError', 'InsufficientStockError', 'InvalidCredentialsError', 'MissingPasswordError', 'NativeAuthStrategyError', 'NegativeQuantityError', 'NoActiveOrderError', 'NotVerifiedError', 'OrderLimitError', 'OrderModificationError', 'OrderPaymentStateError', 'OrderStateTransitionError', 'PasswordAlreadySetError', 'PasswordResetTokenExpiredError', 'PasswordResetTokenInvalidError', 'PasswordValidationError', 'PaymentDeclinedError', 'PaymentFailedError', 'VerificationTokenExpiredError', 'VerificationTokenInvalidError']); function isGraphQLError(input: any): input is import('@vendure/common/lib/generated-types').ErrorResult { return input instanceof ErrorResult || errorTypeNames.has(input.__typename); } export const shopErrorOperationTypeResolvers = { UpdateOrderItemsResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, AddPaymentToOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, ApplyCouponCodeResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, AuthenticationResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'CurrentUser'; }, }, NativeAuthenticationResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'CurrentUser'; }, }, RefreshCustomerVerificationResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Success'; }, }, RegisterCustomerAccountResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Success'; }, }, RemoveOrderItemsResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, RequestPasswordResetResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Success'; }, }, RequestUpdateCustomerEmailAddressResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Success'; }, }, ResetPasswordResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'CurrentUser'; }, }, SetCustomerForOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, ActiveOrderResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, SetOrderShippingMethodResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, TransitionOrderToStateResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Order'; }, }, UpdateCustomerEmailAddressResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Success'; }, }, UpdateCustomerPasswordResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'Success'; }, }, VerifyCustomerAccountResult: { __resolveType(value: any) { return isGraphQLError(value) ? (value as any).__typename : 'CurrentUser'; }, }, };
import { of } from 'rxjs'; import { describe, expect, it, vi } from 'vitest'; import { FSM } from './finite-state-machine'; import { Transitions } from './types'; describe('Finite State Machine', () => { type TestState = 'DoorsClosed' | 'DoorsOpen' | 'Moving'; const transitions: Transitions<TestState> = { DoorsClosed: { to: ['Moving', 'DoorsOpen'], }, DoorsOpen: { to: ['DoorsClosed'], }, Moving: { to: ['DoorsClosed'], }, }; it('initialState works', () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>({ transitions }, initialState); expect(fsm.initialState).toBe(initialState); }); it('getNextStates() works', () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>({ transitions }, initialState); expect(fsm.getNextStates()).toEqual(['Moving', 'DoorsOpen']); }); it('allows valid transitions', async () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>({ transitions }, initialState); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe('Moving'); await fsm.transitionTo('DoorsClosed', {}); expect(fsm.currentState).toBe('DoorsClosed'); await fsm.transitionTo('DoorsOpen', {}); expect(fsm.currentState).toBe('DoorsOpen'); await fsm.transitionTo('DoorsClosed', {}); expect(fsm.currentState).toBe('DoorsClosed'); }); it('does not allow invalid transitions', async () => { const initialState = 'DoorsOpen'; const fsm = new FSM<TestState>({ transitions }, initialState); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe('DoorsOpen'); await fsm.transitionTo('DoorsClosed', {}); expect(fsm.currentState).toBe('DoorsClosed'); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe('Moving'); await fsm.transitionTo('DoorsOpen', {}); expect(fsm.currentState).toBe('Moving'); }); it('onTransitionStart() is invoked before a transition takes place', async () => { const initialState = 'DoorsClosed'; const spy = vi.fn(); const data = 123; let currentStateDuringCallback = ''; const fsm = new FSM<TestState>( { transitions, onTransitionStart: spy.mockImplementation(() => { currentStateDuringCallback = fsm.currentState; }), }, initialState, ); await fsm.transitionTo('Moving', data); expect(spy).toHaveBeenCalledWith(initialState, 'Moving', data); expect(currentStateDuringCallback).toBe(initialState); }); it('onTransitionEnd() is invoked after a transition takes place', async () => { const initialState = 'DoorsClosed'; const spy = vi.fn(); const data = 123; let currentStateDuringCallback = ''; const fsm = new FSM<TestState>( { transitions, onTransitionEnd: spy.mockImplementation(() => { currentStateDuringCallback = fsm.currentState; }), }, initialState, ); const { finalize } = await fsm.transitionTo('Moving', data); await finalize(); expect(spy).toHaveBeenCalledWith(initialState, 'Moving', data); expect(currentStateDuringCallback).toBe('Moving'); }); it('onTransitionStart() cancels transition when it returns false', async () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>( { transitions, onTransitionStart: () => false, }, initialState, ); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe(initialState); }); it('onTransitionStart() cancels transition when it returns Promise<false>', async () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>( { transitions, onTransitionStart: () => Promise.resolve(false), }, initialState, ); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe(initialState); }); it('onTransitionStart() cancels transition when it returns Observable<false>', async () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>( { transitions, onTransitionStart: () => of(false), }, initialState, ); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe(initialState); }); it('onTransitionStart() cancels transition when it returns a string', async () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>( { transitions, onTransitionStart: () => 'foo', }, initialState, ); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe(initialState); }); it('onTransitionStart() allows transition when it returns true', async () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>( { transitions, onTransitionStart: () => true, }, initialState, ); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe('Moving'); }); it('onTransitionStart() allows transition when it returns void', async () => { const initialState = 'DoorsClosed'; const fsm = new FSM<TestState>( { transitions, onTransitionStart: () => { /* empty */ }, }, initialState, ); await fsm.transitionTo('Moving', {}); expect(fsm.currentState).toBe('Moving'); }); it('onError() is invoked for invalid transitions', async () => { const initialState = 'DoorsOpen'; const spy = vi.fn(); const fsm = new FSM<TestState>( { transitions, onError: spy, }, initialState, ); await fsm.transitionTo('Moving', {}); expect(spy).toHaveBeenCalledWith(initialState, 'Moving', undefined); }); it('onTransitionStart() invokes onError() if it returns a string', async () => { const initialState = 'DoorsClosed'; const spy = vi.fn(); const fsm = new FSM<TestState>( { transitions, onTransitionStart: () => 'error', onError: spy, }, initialState, ); await fsm.transitionTo('Moving', {}); expect(spy).toHaveBeenCalledWith(initialState, 'Moving', 'error'); }); });
import { awaitPromiseOrObservable } from '../utils'; import { StateMachineConfig } from './types'; /** * @description * A simple type-safe finite state machine. This is used internally to control the Order process, ensuring that * the state of Orders, Payments, Fulfillments and Refunds follows a well-defined behaviour. * * @docsCategory StateMachine */ export class FSM<T extends string, Data = any> { private readonly _initialState: T; private _currentState: T; constructor(private config: StateMachineConfig<T, Data>, initialState: T) { this._currentState = initialState; this._initialState = initialState; } /** * Returns the state with which the FSM was initialized. */ get initialState(): T { return this._initialState; } /** * Returns the current state. */ get currentState(): T { return this._currentState; } /** * Attempts to transition from the current state to the given state. If this transition is not allowed * per the config, then an error will be logged. */ async transitionTo(state: T, data: Data): Promise<{ finalize: () => Promise<any> }> { const finalizeNoop: () => Promise<any> = async () => { /**/ }; if (this.canTransitionTo(state)) { // If the onTransitionStart callback is defined, invoke it. If it returns false, // then the transition will be cancelled. if (typeof this.config.onTransitionStart === 'function') { const canTransition = await awaitPromiseOrObservable( this.config.onTransitionStart(this._currentState, state, data), ); if (canTransition === false) { return { finalize: finalizeNoop }; } else if (typeof canTransition === 'string') { await this.onError(this._currentState, state, canTransition); return { finalize: finalizeNoop }; } } const fromState = this._currentState; // All is well, so transition to the new state. this._currentState = state; // If the onTransitionEnd callback is defined, invoke it. return { finalize: async () => { if (typeof this.config.onTransitionEnd === 'function') { await awaitPromiseOrObservable(this.config.onTransitionEnd(fromState, state, data)); } }, }; } else { await this.onError(this._currentState, state); return { finalize: finalizeNoop }; } } /** * Jumps from the current state to the given state without regard to whether this transition is allowed or not. * None of the lifecycle callbacks will be invoked. */ jumpTo(state: T) { this._currentState = state; } /** * Returns an array of state to which the machine may transition from the current state. */ getNextStates(): readonly T[] { return this.config.transitions[this._currentState]?.to ?? []; } /** * Returns true if the machine can transition from its current state to the given state. */ canTransitionTo(state: T): boolean { return -1 < this.config.transitions[this._currentState].to.indexOf(state); } private async onError(fromState: T, toState: T, message?: string) { if (typeof this.config.onError === 'function') { await awaitPromiseOrObservable(this.config.onError(fromState, toState, message)); } } }
import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { mergeTransitionDefinitions } from './merge-transition-definitions'; import { Transitions } from './types'; describe('FSM mergeTransitionDefinitions()', () => { it('handles no b', () => { const a: Transitions<'Start' | 'End'> = { Start: { to: ['End'] }, End: { to: [] }, }; const result = mergeTransitionDefinitions(a); expect(result).toEqual(a); }); it('adding new state, merge by default', () => { const a: Transitions<'Start' | 'End'> = { Start: { to: ['End'] }, End: { to: [] }, }; const b: Transitions<'Start' | 'Cancelled'> = { Start: { to: ['Cancelled'] }, Cancelled: { to: [] }, }; const result = mergeTransitionDefinitions(a, b); expect(result).toEqual({ Start: { to: ['End', 'Cancelled'] }, End: { to: [] }, Cancelled: { to: [] }, }); }); it('adding new state, replace', () => { const a: Transitions<'Start' | 'End'> = { Start: { to: ['End'] }, End: { to: [] }, }; const b: Transitions<'Start' | 'Cancelled'> = { Start: { to: ['Cancelled'], mergeStrategy: 'replace' }, Cancelled: { to: ['Start'] }, }; const result = mergeTransitionDefinitions(a, b); expect(result).toEqual({ Start: { to: ['Cancelled'] }, End: { to: [] }, Cancelled: { to: ['Start'] }, }); }); it('is an idempotent, pure function', () => { const a: Transitions<'Start' | 'End'> = { Start: { to: ['End'] }, End: { to: [] }, }; const aCopy = { ...a }; const b: Transitions<'Start' | 'Cancelled'> = { Start: { to: ['Cancelled'] }, Cancelled: { to: ['Start'] }, }; let result = mergeTransitionDefinitions(a, b); result = mergeTransitionDefinitions(a, b); expect(a).toEqual(aCopy); expect(result).toEqual({ Start: { to: ['End', 'Cancelled'] }, End: { to: [] }, Cancelled: { to: ['Start'] }, }); }); });
import { simpleDeepClone } from '@vendure/common/lib/simple-deep-clone'; import { Transitions } from './types'; /** * Merges two state machine Transitions definitions. */ export function mergeTransitionDefinitions<A extends string, B extends string>( a: Transitions<A>, b?: Transitions<B>, ): Transitions<A | B> { if (!b) { return a as Transitions<A | B>; } const merged: Transitions<A | B> = simpleDeepClone(a) as any; for (const k of Object.keys(b)) { const key = k as B; if (merged.hasOwnProperty(key)) { if (b[key].mergeStrategy === 'replace') { merged[key].to = b[key].to; } else { merged[key].to = merged[key].to.concat(b[key].to); } } else { merged[key] = b[key]; } } return merged; }
import { Observable } from 'rxjs'; /** * @description * A type which is used to define valid states and transitions for a state machine based * on {@link FSM}. * * @example * ```ts * type LightColor = 'Green' | 'Amber' | 'Red'; * * const trafficLightTransitions: Transitions<LightColor> = { * Green: { * to: ['Amber'], * }, * Amber: { * to: ['Red'], * }, * Red: { * to: ['Green'], * }, * }; * ``` * * The `mergeStrategy` property defines how to handle the merging of states when one set of * transitions is being merged with another (as in the case of defining a {@link CustomerOrderProcess}) * * @docsCategory StateMachine */ export type Transitions<State extends string, Target extends string = State> = { [S in State]: { to: Readonly<Target[]>; mergeStrategy?: 'merge' | 'replace'; }; }; /** * @description * Called before a transition takes place. If the function resolves to `false` or a string, then the transition * will be cancelled. In the case of a string, the string (error message) will be forwarded to the onError handler. * * If this function returns a value resolving to `true` or `void` (no return value), then the transition * will be permitted. * * @docsCategory StateMachine * @docsPage StateMachineConfig */ export type OnTransitionStartFn<T extends string, Data> = ( fromState: T, toState: T, data: Data, ) => boolean | string | void | Promise<boolean | string | void> | Observable<boolean | string | void>; /** * @description * Called when a transition is prevented and the `onTransitionStart` handler has returned an * error message. * * @docsCategory StateMachine * @docsPage StateMachineConfig */ export type OnTransitionErrorFn<T extends string> = ( fromState: T, toState: T, message?: string, ) => void | Promise<void> | Observable<void>; /** * @description * Called after a transition has taken place. * * @docsCategory StateMachine * @docsPage StateMachineConfig */ export type OnTransitionEndFn<T extends string, Data> = ( fromState: T, toState: T, data: Data, ) => void | Promise<void> | Observable<void>; /** * @description * The config object used to instantiate a new {@link FSM} instance. * * @docsCategory StateMachine * @docsPage StateMachineConfig * @docsWeight 0 */ export interface StateMachineConfig<T extends string, Data = undefined> { /** * @description * Defines the available states of the state machine as well as the permitted * transitions from one state to another. */ readonly transitions: Transitions<T>; /** * @description * Called before a transition takes place. If the function resolves to `false` or a string, then the transition * will be cancelled. In the case of a string, the string (error message) will be forwarded to the onError handler. * * If this function returns a value resolving to `true` or `void` (no return value), then the transition * will be permitted. */ onTransitionStart?: OnTransitionStartFn<T, Data>; /** * @description * Called after a transition has taken place. */ onTransitionEnd?: OnTransitionEndFn<T, Data>; /** * @description * Called when a transition is prevented and the `onTransitionStart` handler has returned an * error message. */ onError?: OnTransitionErrorFn<T>; }
import { describe, expect, it } from 'vitest'; import { OrderState } from '../../service/helpers/order-state-machine/order-state'; import { Transitions } from './types'; import { validateTransitionDefinition } from './validate-transition-definition'; describe('FSM validateTransitionDefinition()', () => { it('valid definition', () => { const valid: Transitions<'Start' | 'End'> = { Start: { to: ['End'] }, End: { to: ['Start'] }, }; const result = validateTransitionDefinition(valid, 'Start'); expect(result.valid).toBe(true); }); it('valid complex definition', () => { const orderStateTransitions: Transitions<OrderState> = { Created: { to: ['AddingItems', 'Draft'], }, Draft: { to: ['ArrangingPayment'], }, AddingItems: { to: ['ArrangingPayment', 'Cancelled'], }, ArrangingPayment: { to: ['PaymentAuthorized', 'PaymentSettled', 'AddingItems', 'Cancelled', 'Modifying'], }, PaymentAuthorized: { to: ['PaymentSettled', 'Cancelled'], }, PaymentSettled: { to: ['PartiallyDelivered', 'Delivered', 'PartiallyShipped', 'Shipped', 'Cancelled'], }, PartiallyShipped: { to: ['Shipped', 'PartiallyDelivered', 'Cancelled'], }, Shipped: { to: ['PartiallyDelivered', 'Delivered', 'Cancelled'], }, PartiallyDelivered: { to: ['Delivered', 'Cancelled'], }, Delivered: { to: ['Cancelled'], }, ArrangingAdditionalPayment: { to: ['ArrangingPayment'], }, Modifying: { to: ['ArrangingAdditionalPayment'], }, Cancelled: { to: [], }, }; const result = validateTransitionDefinition(orderStateTransitions, 'Created'); expect(result.valid).toBe(true); }); it('invalid - unreachable state', () => { const valid: Transitions<'Start' | 'End' | 'Unreachable'> = { Start: { to: ['End'] }, End: { to: ['Start'] }, Unreachable: { to: [] }, }; const result = validateTransitionDefinition(valid, 'Start'); expect(result.valid).toBe(true); expect(result.error).toBe('The following states are unreachable: Unreachable'); }); it('invalid - non-existent transition', () => { const valid: Transitions<'Start' | 'End' | 'Unreachable'> = { Start: { to: ['End'] }, End: { to: ['Bad' as any] }, Unreachable: { to: [] }, }; const result = validateTransitionDefinition(valid, 'Start'); expect(result.valid).toBe(false); expect(result.error).toBe('The state "End" has a transition to an unknown state "Bad"'); }); it('invalid - missing initial state', () => { const valid: Transitions<'Start' | 'End' | 'Unreachable'> = { Start: { to: ['End'] }, End: { to: ['Start'] }, Unreachable: { to: [] }, }; const result = validateTransitionDefinition(valid, 'Created' as any); expect(result.valid).toBe(false); expect(result.error).toBe('The initial state "Created" is not defined'); }); });
import { Transitions } from './types'; type ValidationResult = { reachable: boolean }; /** * This function validates a finite state machine transition graph to ensure * that all states are reachable from the given initial state. */ export function validateTransitionDefinition<T extends string>( transitions: Transitions<T>, initialState: T, ): { valid: boolean; error?: string } { if (!transitions[initialState]) { return { valid: false, error: `The initial state "${initialState}" is not defined`, }; } const states = Object.keys(transitions) as T[]; const result: { [State in T]: ValidationResult } = states.reduce((res, state) => { return { ...res, [state]: { reachable: false }, }; }, {} as any); // walk the state graph starting with the initialState and // check whether all states are reachable. function allStatesReached(): boolean { return Object.values(result).every(r => (r as ValidationResult).reachable); } function walkGraph(state: T) { const candidates = transitions[state].to; result[state].reachable = true; if (allStatesReached()) { return true; } for (const candidate of candidates) { if (result[candidate] === undefined) { throw new Error(`The state "${state}" has a transition to an unknown state "${candidate}"`); } if (!result[candidate].reachable) { walkGraph(candidate); } } } try { walkGraph(initialState); } catch (e: any) { return { valid: false, error: e.message, }; } const error = !allStatesReached() ? `The following states are unreachable: ${Object.entries(result) .filter(([s, v]) => !(v as ValidationResult).reachable) .map(([s]) => s) .join(', ')}` : undefined; return { valid: true, error, }; }
import { Adjustment, AdjustmentType } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { VendureEntity } from '../../entity/base/base.entity'; export type TestResult = boolean | object; export abstract class AdjustmentSource extends VendureEntity { type: AdjustmentType; getSourceId(): string { return `${this.type}:${this.id}`; } static decodeSourceId(sourceId: string): { type: AdjustmentType; id: ID } { const [type, id] = sourceId.split(':'); return { type: type as AdjustmentType, id: Number.isNaN(+id) ? id : +id, }; } abstract test(...args: any[]): TestResult | Promise<TestResult>; abstract apply(...args: any[]): Adjustment | undefined | Promise<Adjustment | undefined>; }
import { LogicalOperator } from '@vendure/common/lib/generated-types'; import { Type } from '@vendure/common/lib/shared-types'; import { VendureEntity } from '../../entity/base/base.entity'; import { Channel } from '../../entity/channel/channel.entity'; import { Tag } from '../../entity/tag/tag.entity'; import { LocaleString } from './locale-types'; /** * @description * Entities which can be assigned to Channels should implement this interface. * * @docsCategory entities * @docsPage interfaces */ export interface ChannelAware { channels: Channel[]; } /** * @description * Entities which can be soft deleted should implement this interface. * * @docsCategory entities * @docsPage interfaces */ export interface SoftDeletable { deletedAt: Date | null; } /** * @description * Entities which can be ordered relative to their siblings in a list. * * @docsCategory entities * @docsPage interfaces */ export interface Orderable { position: number; } /** * @description * Entities which can have Tags applied to them. * * @docsCategory entities * @docsPage interfaces */ export interface Taggable { tags: Tag[]; } /** * Creates a type based on T, but with all properties non-optional * and readonly. */ export type ReadOnlyRequired<T> = { +readonly [K in keyof T]-?: T[K] }; /** * Given an array type e.g. Array<string>, return the inner type e.g. string. */ export type UnwrappedArray<T extends any[]> = T[number]; /** * Parameters for list queries */ export interface ListQueryOptions<T extends VendureEntity> { take?: number | null; skip?: number | null; sort?: NullOptionals<SortParameter<T>> | null; filter?: NullOptionals<FilterParameter<T>> | null; filterOperator?: LogicalOperator; } /** * Returns a type T where any optional fields also have the "null" type added. * This is needed to provide interop with the Apollo-generated interfaces, where * nullable fields have the type `field?: <type> | null`. */ export type NullOptionals<T> = { [K in keyof T]: undefined extends T[K] ? NullOptionals<T[K]> | null : NullOptionals<T[K]>; }; export type SortOrder = 'ASC' | 'DESC'; // prettier-ignore export type PrimitiveFields<T extends VendureEntity> = { [K in keyof T]: NonNullable<T[K]> extends LocaleString | number | string | boolean | Date ? K : never }[keyof T]; // prettier-ignore export type SortParameter<T extends VendureEntity> = { [K in PrimitiveFields<T>]?: SortOrder }; // prettier-ignore export type CustomFieldSortParameter = { [customField: string]: SortOrder; }; // prettier-ignore export type FilterParameter<T extends VendureEntity> = { [K in PrimitiveFields<T>]?: T[K] extends string | LocaleString ? StringOperators : T[K] extends number ? NumberOperators : T[K] extends boolean ? BooleanOperators : T[K] extends Date ? DateOperators : StringOperators; } & { _and?: Array<FilterParameter<T>>; _or?: Array<FilterParameter<T>>; }; export interface StringOperators { eq?: string; notEq?: string; contains?: string; notContains?: string; in?: string[]; notIn?: string[]; regex?: string; isNull?: boolean; } export interface BooleanOperators { eq?: boolean; isNull?: boolean; } export interface NumberRange { start: number; end: number; } export interface NumberOperators { eq?: number; lt?: number; lte?: number; gt?: number; gte?: number; between?: NumberRange; isNull?: boolean; } export interface DateRange { start: Date; end: Date; } export interface DateOperators { eq?: Date; before?: Date; after?: Date; between?: DateRange; isNull?: boolean; } export interface ListOperators { inList?: string | number | boolean | Date; } export type PaymentMetadata = { [prop: string]: any; } & { public?: any; }; /** * @description * The result of the price calculation from the {@link ProductVariantPriceCalculationStrategy} or the * {@link OrderItemPriceCalculationStrategy}. * * @docsCategory Common */ export type PriceCalculationResult = { price: number; priceIncludesTax: boolean; }; // eslint-disable-next-line @typescript-eslint/ban-types export type MiddlewareHandler = Type<any> | Function; /** * @description * Defines API middleware, set in the {@link ApiOptions}. Middleware can be either * [Express middleware](https://expressjs.com/en/guide/using-middleware.html) or [NestJS middleware](https://docs.nestjs.com/middleware). * * ## Increasing the maximum request body size limit * * Internally, Vendure relies on the body-parser middleware to parse incoming JSON data. By default, the maximum * body size is set to 100kb. Attempting to send a request with more than 100kb of JSON data will result in a * `PayloadTooLargeError`. To increase this limit, we can manually configure the body-parser middleware: * * @example * ```ts * import { VendureConfig } from '\@vendure/core'; * import { json } from 'body-parser'; * * export const config: VendureConfig = { * // ... * apiOptions: { * middleware: [{ * handler: json({ limit: '10mb' }), * route: '*', * beforeListen: true, * }], * }, * }; * ``` * * @docsCategory Common */ export interface Middleware { /** * @description * The Express middleware function or NestJS `NestMiddleware` class. */ handler: MiddlewareHandler; /** * @description * The route to which this middleware will apply. Pattern based routes are supported as well. * * The `'ab*cd'` route path will match `abcd`, `ab_cd`, `abecd`, and so on. The characters `?`, `+`, `*`, and `()` may be used in a route path, * and are subsets of their regular expression counterparts. The hyphen (`-`) and the dot (`.`) are interpreted literally. */ route: string; /** * @description * When set to `true`, this will cause the middleware to be applied before the Vendure server (and underlying Express server) starts listening * for connections. In practical terms this means that the middleware will be at the very start of the middleware stack, before even the * `body-parser` middleware which is automatically applied by NestJS. This can be useful in certain cases such as when you need to access the * raw unparsed request for a specific route. * * @since 1.1.0 * @default false */ beforeListen?: boolean; }
import { VendureEntity } from '../../entity/base/base.entity'; /** * @description * This type allows type-safe access to entity relations using strings with dot notation. * It works to 2 levels deep. * * @example * ```ts * type T1 = EntityRelationPaths<Product>; * ``` * In the above example, the type `T1` will be a string union of all relations of the * `Product` entity: * * * `'featuredAsset'` * * `'variants'` * * `'variants.options'` * * `'variants.featuredAsset'` * * etc. * * @docsCategory Common */ export type EntityRelationPaths<T extends VendureEntity> = | `customFields.${string}` | PathsToStringProps1<T> | Join<PathsToStringProps2<T>, '.'> | TripleDotPath; export type EntityRelationKeys<T extends VendureEntity> = { [K in Extract<keyof T, string>]: Required<T>[K] extends VendureEntity | null ? K : Required<T>[K] extends VendureEntity[] ? K : never; }[Extract<keyof T, string>]; export type EntityRelations<T extends VendureEntity> = { [K in EntityRelationKeys<T>]: T[K]; }; export type PathsToStringProps1<T extends VendureEntity> = T extends string ? [] : { [K in EntityRelationKeys<T>]: K; }[Extract<EntityRelationKeys<T>, string>]; export type PathsToStringProps2<T extends VendureEntity> = T extends string ? never : { [K in EntityRelationKeys<T>]: T[K] extends VendureEntity[] ? [K, PathsToStringProps1<T[K][number]>] : T[K] extends VendureEntity | undefined ? [K, PathsToStringProps1<NonNullable<T[K]>>] : never; }[Extract<EntityRelationKeys<T>, string>]; export type TripleDotPath = `${string}.${string}.${string}`; // Based on https://stackoverflow.com/a/47058976/772859 export type Join<T extends Array<string | any>, D extends string> = T extends [] ? never : T extends [infer F] ? F : // eslint-disable-next-line no-shadow,@typescript-eslint/no-shadow T extends [infer F, ...infer R] ? F extends string ? `${F}${D}${Join<Extract<R, string[]>, D>}` : never : string;
import { Injector } from '../injector'; /** * @description * This interface defines the setup and teardown hooks available to the * various strategies used to configure Vendure. * * @docsCategory common */ export interface InjectableStrategy { /** * @description * Defines setup logic to be run during application bootstrap. Receives * the {@link Injector} as an argument, which allows application providers * to be used as part of the setup. This hook will be called on both the * main server and the worker processes. * * @example * ```ts * async init(injector: Injector) { * const myService = injector.get(MyService); * await myService.doSomething(); * } * ``` */ init?: (injector: Injector) => void | Promise<void>; /** * @description * Defines teardown logic to be run before application shutdown. */ destroy?: () => void | Promise<void>; }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { CustomFieldsObject, ID } from '@vendure/common/lib/shared-types'; import { VendureEntity } from '../../entity/base/base.entity'; import { TranslatableRelationsKeys } from '../../service/helpers/utils/translate-entity'; import { UnwrappedArray } from './common-types'; /** * This type should be used in any interfaces where the value is to be * localized into different languages. */ export type LocaleString = string & { _opaqueType: 'LocaleString' }; export type TranslatableKeys<T, U = Omit<T, 'translations'>> = { [K in keyof U]: U[K] extends LocaleString ? K : never; }[keyof U]; export type NonTranslateableKeys<T> = { [K in keyof T]: T[K] extends LocaleString ? never : K }[keyof T]; // prettier-ignore /** * @description * Entities which have localizable string properties should implement this type. * * @docsCategory entities * @docsPage interfaces */ export interface Translatable { translations: Array<Translation<VendureEntity>>; } export type TranslationCustomFields<T> = { [K in keyof T]: K extends 'customFields' ? K : never }[keyof T]; // prettier-ignore /** * Translations of localizable entities should implement this type. */ export type Translation<T> = // Translation must include the languageCode and a reference to the base Translatable entity it is associated with { id: ID; languageCode: LanguageCode; base: T; } & // Translation must include all translatable keys as a string type { [K in TranslatableKeys<T>]: string; } & { [K in TranslationCustomFields<T>]: CustomFieldsObject; }; /** * This is the type of a translation object when provided as input to a create or update operation. */ export type TranslationInput<T> = { [K in TranslatableKeys<T>]?: string | null } & { id?: ID | null; languageCode: LanguageCode; }; /** * This interface defines the shape of a DTO used to create / update an entity which has one or more LocaleString * properties. */ export interface TranslatedInput<T> { translations?: Array<TranslationInput<T>> | null; } // prettier-ignore /** * This is the type of a Translatable entity after it has been deep-translated into a given language. */ export type Translated<T> = T & { languageCode: LanguageCode; } & { [K in TranslatableRelationsKeys<T>]: T[K] extends any[] ? Array<Translated<UnwrappedArray<T[K]>>> : Translated<T[K]>; };
import path from 'path'; import { mergeConfig } from './merge-config'; import { PartialVendureConfig, RuntimeVendureConfig } from './vendure-config'; let activeConfig: RuntimeVendureConfig; const defaultConfigPath = path.join(__dirname, 'default-config'); /** * Reset the activeConfig object back to the initial default state. */ export function resetConfig() { // eslint-disable-next-line @typescript-eslint/no-var-requires activeConfig = require(defaultConfigPath).defaultConfig; } /** * Override the default config by merging in the supplied values. Should only be used prior to * bootstrapping the app. */ export async function setConfig(userConfig: PartialVendureConfig) { if (!activeConfig) { activeConfig = (await import(defaultConfigPath)).defaultConfig; } activeConfig = mergeConfig(activeConfig, userConfig); } /** * Ensures that the config has been loaded. This is necessary for tests which * do not go through the normal bootstrap process. */ export async function ensureConfigLoaded() { if (!activeConfig) { activeConfig = (await import(defaultConfigPath)).defaultConfig; } } /** * Returns the app config object. In general this function should only be * used before bootstrapping the app. In all other contexts, the {@link ConfigService} * should be used to access config settings. */ export function getConfig(): Readonly<RuntimeVendureConfig> { if (!activeConfig) { try { // eslint-disable-next-line @typescript-eslint/no-var-requires activeConfig = require(defaultConfigPath).defaultConfig; } catch (e: any) { // eslint-disable-next-line no-console console.log( 'Error loading config. If this is a test, make sure you have called ensureConfigLoaded() before using the config.', ); } } return activeConfig; }
import { Module, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import { ModuleRef } from '@nestjs/core'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { ConfigurableOperationDef } from '../common/configurable-operation'; import { Injector } from '../common/injector'; import { InjectableStrategy } from '../common/types/injectable-strategy'; import { resetConfig } from './config-helpers'; import { ConfigService } from './config.service'; @Module({ providers: [ConfigService], exports: [ConfigService], }) export class ConfigModule implements OnApplicationBootstrap, OnApplicationShutdown { constructor(private configService: ConfigService, private moduleRef: ModuleRef) {} async onApplicationBootstrap() { await this.initInjectableStrategies(); await this.initConfigurableOperations(); } async onApplicationShutdown(signal?: string) { await this.destroyInjectableStrategies(); await this.destroyConfigurableOperations(); /** * When the application shuts down, we reset the activeConfig to the default. Usually this is * redundant, as the app shutdown would normally coincide with the process ending. However, in some * circumstances, such as when running migrations immediately followed by app bootstrap, the activeConfig * will persist between these two applications and mutations e.g. to the CustomFields will result in * hard-to-debug errors. So resetting is a precaution against this scenario. */ resetConfig(); } private async initInjectableStrategies() { const injector = new Injector(this.moduleRef); for (const strategy of this.getInjectableStrategies()) { if (typeof strategy.init === 'function') { await strategy.init(injector); } } } private async destroyInjectableStrategies() { for (const strategy of this.getInjectableStrategies()) { if (typeof strategy.destroy === 'function') { await strategy.destroy(); } } } private async initConfigurableOperations() { const injector = new Injector(this.moduleRef); for (const operation of this.getConfigurableOperations()) { await operation.init(injector); } } private async destroyConfigurableOperations() { for (const operation of this.getConfigurableOperations()) { await operation.destroy(); } } private getInjectableStrategies(): InjectableStrategy[] { const { assetNamingStrategy, assetPreviewStrategy, assetStorageStrategy } = this.configService.assetOptions; const { productVariantPriceCalculationStrategy, productVariantPriceSelectionStrategy, productVariantPriceUpdateStrategy, stockDisplayStrategy, stockLocationStrategy, } = this.configService.catalogOptions; const { adminAuthenticationStrategy, shopAuthenticationStrategy, sessionCacheStrategy, passwordHashingStrategy, passwordValidationStrategy, } = this.configService.authOptions; const { taxZoneStrategy, taxLineCalculationStrategy } = this.configService.taxOptions; const { jobQueueStrategy, jobBufferStorageStrategy } = this.configService.jobQueueOptions; const { mergeStrategy, checkoutMergeStrategy, orderItemPriceCalculationStrategy, process: orderProcess, orderCodeStrategy, orderByCodeAccessStrategy, stockAllocationStrategy, activeOrderStrategy, changedPriceHandlingStrategy, orderSellerStrategy, guestCheckoutStrategy, } = this.configService.orderOptions; const { customFulfillmentProcess, process: fulfillmentProcess, shippingLineAssignmentStrategy, } = this.configService.shippingOptions; const { customPaymentProcess, process: paymentProcess } = this.configService.paymentOptions; const { entityIdStrategy: entityIdStrategyDeprecated } = this.configService; const { entityIdStrategy } = this.configService.entityOptions; const { healthChecks, errorHandlers } = this.configService.systemOptions; const { assetImportStrategy } = this.configService.importExportOptions; return [ ...adminAuthenticationStrategy, ...shopAuthenticationStrategy, sessionCacheStrategy, passwordHashingStrategy, passwordValidationStrategy, assetNamingStrategy, assetPreviewStrategy, assetStorageStrategy, taxZoneStrategy, taxLineCalculationStrategy, jobQueueStrategy, jobBufferStorageStrategy, mergeStrategy, checkoutMergeStrategy, orderCodeStrategy, orderByCodeAccessStrategy, entityIdStrategyDeprecated, ...[entityIdStrategy].filter(notNullOrUndefined), productVariantPriceCalculationStrategy, productVariantPriceUpdateStrategy, orderItemPriceCalculationStrategy, ...orderProcess, ...customFulfillmentProcess, ...fulfillmentProcess, ...customPaymentProcess, ...paymentProcess, stockAllocationStrategy, stockDisplayStrategy, ...healthChecks, ...errorHandlers, assetImportStrategy, changedPriceHandlingStrategy, ...(Array.isArray(activeOrderStrategy) ? activeOrderStrategy : [activeOrderStrategy]), orderSellerStrategy, shippingLineAssignmentStrategy, stockLocationStrategy, productVariantPriceSelectionStrategy, guestCheckoutStrategy, ]; } private getConfigurableOperations(): Array<ConfigurableOperationDef<any>> { const { paymentMethodHandlers, paymentMethodEligibilityCheckers } = this.configService.paymentOptions; const { collectionFilters } = this.configService.catalogOptions; const { entityDuplicators } = this.configService.entityOptions; const { promotionActions, promotionConditions } = this.configService.promotionOptions; const { shippingCalculators, shippingEligibilityCheckers, fulfillmentHandlers } = this.configService.shippingOptions; return [ ...(paymentMethodEligibilityCheckers || []), ...paymentMethodHandlers, ...collectionFilters, ...(promotionActions || []), ...(promotionConditions || []), ...(shippingCalculators || []), ...(shippingEligibilityCheckers || []), ...(fulfillmentHandlers || []), ...(entityDuplicators || []), ]; } }
/* eslint-disable @typescript-eslint/ban-types */ import { vi, Mock } from 'vitest'; import { VendureEntity } from '../entity/base/base.entity'; import { MockClass } from '../testing/testing-types'; import { ConfigService } from './config.service'; import { EntityIdStrategy, PrimaryKeyType } from './entity/entity-id-strategy'; export class MockConfigService implements MockClass<ConfigService> { apiOptions = { channelTokenKey: 'vendure-token', adminApiPath: 'admin-api', adminApiPlayground: false, adminApiDebug: true, shopApiPath: 'shop-api', shopApiPlayground: false, shopApiDebug: true, port: 3000, cors: false, middleware: [], apolloServerPlugins: [], }; authOptions: {}; defaultChannelToken: 'channel-token'; defaultLanguageCode: Mock<any>; roundingStrategy: {}; entityIdStrategy = new MockIdStrategy(); entityOptions = {}; assetOptions = { assetNamingStrategy: {} as any, assetStorageStrategy: {} as any, assetPreviewStrategy: {} as any, }; catalogOptions: {}; uploadMaxFileSize = 1024; dbConnectionOptions = {}; shippingOptions = {}; promotionOptions = { promotionConditions: [], promotionActions: [], }; paymentOptions: {}; taxOptions: {}; emailOptions: {}; importExportOptions: {}; orderOptions = {}; customFields = {}; plugins = []; logger = {} as any; jobQueueOptions = {}; systemOptions = {}; } export const ENCODED = 'encoded'; export const DECODED = 'decoded'; export class MockIdStrategy implements EntityIdStrategy<'increment'> { readonly primaryKeyType = 'increment'; encodeId = vi.fn().mockReturnValue(ENCODED); decodeId = vi.fn().mockReturnValue(DECODED); }
import { DynamicModule, Injectable, Type } from '@nestjs/common'; import { LanguageCode } from '@vendure/common/lib/generated-types'; import { DataSourceOptions } from 'typeorm'; import { getConfig } from './config-helpers'; import { CustomFields } from './custom-field/custom-field-types'; import { EntityIdStrategy } from './entity/entity-id-strategy'; import { Logger, VendureLogger } from './logger/vendure-logger'; import { ApiOptions, AssetOptions, AuthOptions, CatalogOptions, EntityOptions, ImportExportOptions, JobQueueOptions, OrderOptions, PaymentOptions, PromotionOptions, RuntimeVendureConfig, ShippingOptions, SystemOptions, TaxOptions, VendureConfig, } from './vendure-config'; @Injectable() export class ConfigService implements VendureConfig { private activeConfig: RuntimeVendureConfig; constructor() { this.activeConfig = getConfig(); if (this.activeConfig.authOptions.disableAuth) { // eslint-disable-next-line Logger.warn('Auth has been disabled. This should never be the case for a production system!'); } } get apiOptions(): Required<ApiOptions> { return this.activeConfig.apiOptions; } get authOptions(): Required<AuthOptions> { return this.activeConfig.authOptions; } get catalogOptions(): Required<CatalogOptions> { return this.activeConfig.catalogOptions; } get defaultChannelToken(): string | null { return this.activeConfig.defaultChannelToken; } get defaultLanguageCode(): LanguageCode { return this.activeConfig.defaultLanguageCode; } get entityOptions(): Required<Omit<EntityOptions, 'entityIdStrategy'>> & EntityOptions { return this.activeConfig.entityOptions; } get entityIdStrategy(): EntityIdStrategy<any> { return this.activeConfig.entityIdStrategy; } get assetOptions(): Required<AssetOptions> { return this.activeConfig.assetOptions; } get dbConnectionOptions(): DataSourceOptions { return this.activeConfig.dbConnectionOptions; } get promotionOptions(): Required<PromotionOptions> { return this.activeConfig.promotionOptions; } get shippingOptions(): Required<ShippingOptions> { return this.activeConfig.shippingOptions; } get orderOptions(): Required<OrderOptions> { return this.activeConfig.orderOptions; } get paymentOptions(): Required<PaymentOptions> { return this.activeConfig.paymentOptions as Required<PaymentOptions>; } get taxOptions(): Required<TaxOptions> { return this.activeConfig.taxOptions; } get importExportOptions(): Required<ImportExportOptions> { return this.activeConfig.importExportOptions; } get customFields(): Required<CustomFields> { return this.activeConfig.customFields; } get plugins(): Array<DynamicModule | Type<any>> { return this.activeConfig.plugins; } get logger(): VendureLogger { return this.activeConfig.logger; } get jobQueueOptions(): Required<JobQueueOptions> { return this.activeConfig.jobQueueOptions; } get systemOptions(): Required<SystemOptions> { return this.activeConfig.systemOptions; } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { DEFAULT_AUTH_TOKEN_HEADER_KEY, SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD, DEFAULT_CHANNEL_TOKEN_KEY, } from '@vendure/common/lib/shared-constants'; import { TypeORMHealthCheckStrategy } from '../health-check/typeorm-health-check-strategy'; import { InMemoryJobQueueStrategy } from '../job-queue/in-memory-job-queue-strategy'; import { InMemoryJobBufferStorageStrategy } from '../job-queue/job-buffer/in-memory-job-buffer-storage-strategy'; import { DefaultAssetImportStrategy } from './asset-import-strategy/default-asset-import-strategy'; import { DefaultAssetNamingStrategy } from './asset-naming-strategy/default-asset-naming-strategy'; import { NoAssetPreviewStrategy } from './asset-preview-strategy/no-asset-preview-strategy'; import { NoAssetStorageStrategy } from './asset-storage-strategy/no-asset-storage-strategy'; import { BcryptPasswordHashingStrategy } from './auth/bcrypt-password-hashing-strategy'; import { DefaultPasswordValidationStrategy } from './auth/default-password-validation-strategy'; import { NativeAuthenticationStrategy } from './auth/native-authentication-strategy'; import { defaultCollectionFilters } from './catalog/default-collection-filters'; import { DefaultProductVariantPriceCalculationStrategy } from './catalog/default-product-variant-price-calculation-strategy'; import { DefaultProductVariantPriceSelectionStrategy } from './catalog/default-product-variant-price-selection-strategy'; import { DefaultProductVariantPriceUpdateStrategy } from './catalog/default-product-variant-price-update-strategy'; import { DefaultStockDisplayStrategy } from './catalog/default-stock-display-strategy'; import { DefaultStockLocationStrategy } from './catalog/default-stock-location-strategy'; import { AutoIncrementIdStrategy } from './entity/auto-increment-id-strategy'; import { DefaultMoneyStrategy } from './entity/default-money-strategy'; import { defaultEntityDuplicators } from './entity/entity-duplicators/index'; import { defaultFulfillmentProcess } from './fulfillment/default-fulfillment-process'; import { manualFulfillmentHandler } from './fulfillment/manual-fulfillment-handler'; import { DefaultLogger } from './logger/default-logger'; import { DefaultActiveOrderStrategy } from './order/default-active-order-strategy'; import { DefaultChangedPriceHandlingStrategy } from './order/default-changed-price-handling-strategy'; import { DefaultGuestCheckoutStrategy } from './order/default-guest-checkout-strategy'; import { DefaultOrderItemPriceCalculationStrategy } from './order/default-order-item-price-calculation-strategy'; import { DefaultOrderPlacedStrategy } from './order/default-order-placed-strategy'; import { defaultOrderProcess } from './order/default-order-process'; import { DefaultOrderSellerStrategy } from './order/default-order-seller-strategy'; import { DefaultStockAllocationStrategy } from './order/default-stock-allocation-strategy'; import { MergeOrdersStrategy } from './order/merge-orders-strategy'; import { DefaultOrderByCodeAccessStrategy } from './order/order-by-code-access-strategy'; import { DefaultOrderCodeStrategy } from './order/order-code-strategy'; import { UseGuestStrategy } from './order/use-guest-strategy'; import { defaultPaymentProcess } from './payment/default-payment-process'; import { defaultPromotionActions, defaultPromotionConditions } from './promotion'; import { InMemorySessionCacheStrategy } from './session-cache/in-memory-session-cache-strategy'; import { defaultShippingCalculator } from './shipping-method/default-shipping-calculator'; import { defaultShippingEligibilityChecker } from './shipping-method/default-shipping-eligibility-checker'; import { DefaultShippingLineAssignmentStrategy } from './shipping-method/default-shipping-line-assignment-strategy'; import { DefaultTaxLineCalculationStrategy } from './tax/default-tax-line-calculation-strategy'; import { DefaultTaxZoneStrategy } from './tax/default-tax-zone-strategy'; import { RuntimeVendureConfig } from './vendure-config'; /** * @description * The default configuration settings which are used if not explicitly overridden in the bootstrap() call. * * @docsCategory configuration */ export const defaultConfig: RuntimeVendureConfig = { defaultChannelToken: null, defaultLanguageCode: LanguageCode.en, logger: new DefaultLogger(), apiOptions: { hostname: '', port: 3000, adminApiPath: 'admin-api', adminApiPlayground: false, adminApiDebug: false, adminListQueryLimit: 1000, adminApiValidationRules: [], shopApiPath: 'shop-api', shopApiPlayground: false, shopApiDebug: false, shopListQueryLimit: 100, shopApiValidationRules: [], channelTokenKey: DEFAULT_CHANNEL_TOKEN_KEY, cors: { origin: true, credentials: true, }, middleware: [], introspection: true, apolloServerPlugins: [], }, authOptions: { disableAuth: false, tokenMethod: 'cookie', cookieOptions: { secret: Math.random().toString(36).substr(3), httpOnly: true, sameSite: 'lax', }, authTokenHeaderKey: DEFAULT_AUTH_TOKEN_HEADER_KEY, sessionDuration: '1y', sessionCacheStrategy: new InMemorySessionCacheStrategy(), sessionCacheTTL: 300, requireVerification: true, verificationTokenDuration: '7d', superadminCredentials: { identifier: SUPER_ADMIN_USER_IDENTIFIER, password: SUPER_ADMIN_USER_PASSWORD, }, shopAuthenticationStrategy: [new NativeAuthenticationStrategy()], adminAuthenticationStrategy: [new NativeAuthenticationStrategy()], customPermissions: [], passwordHashingStrategy: new BcryptPasswordHashingStrategy(), passwordValidationStrategy: new DefaultPasswordValidationStrategy({ minLength: 4 }), }, catalogOptions: { collectionFilters: defaultCollectionFilters, productVariantPriceSelectionStrategy: new DefaultProductVariantPriceSelectionStrategy(), productVariantPriceCalculationStrategy: new DefaultProductVariantPriceCalculationStrategy(), productVariantPriceUpdateStrategy: new DefaultProductVariantPriceUpdateStrategy({ syncPricesAcrossChannels: false, }), stockDisplayStrategy: new DefaultStockDisplayStrategy(), stockLocationStrategy: new DefaultStockLocationStrategy(), }, entityIdStrategy: new AutoIncrementIdStrategy(), assetOptions: { assetNamingStrategy: new DefaultAssetNamingStrategy(), assetStorageStrategy: new NoAssetStorageStrategy(), assetPreviewStrategy: new NoAssetPreviewStrategy(), permittedFileTypes: ['image/*', 'video/*', 'audio/*', '.pdf'], uploadMaxFileSize: 20971520, }, dbConnectionOptions: { timezone: 'Z', type: 'mysql', }, entityOptions: { moneyStrategy: new DefaultMoneyStrategy(), entityDuplicators: defaultEntityDuplicators, channelCacheTtl: 30000, zoneCacheTtl: 30000, taxRateCacheTtl: 30000, metadataModifiers: [], }, promotionOptions: { promotionConditions: defaultPromotionConditions, promotionActions: defaultPromotionActions, }, shippingOptions: { shippingEligibilityCheckers: [defaultShippingEligibilityChecker], shippingCalculators: [defaultShippingCalculator], shippingLineAssignmentStrategy: new DefaultShippingLineAssignmentStrategy(), customFulfillmentProcess: [], process: [defaultFulfillmentProcess], fulfillmentHandlers: [manualFulfillmentHandler], }, orderOptions: { orderItemsLimit: 999, orderLineItemsLimit: 999, orderItemPriceCalculationStrategy: new DefaultOrderItemPriceCalculationStrategy(), mergeStrategy: new MergeOrdersStrategy(), checkoutMergeStrategy: new UseGuestStrategy(), process: [defaultOrderProcess], stockAllocationStrategy: new DefaultStockAllocationStrategy(), orderCodeStrategy: new DefaultOrderCodeStrategy(), orderByCodeAccessStrategy: new DefaultOrderByCodeAccessStrategy('2h'), changedPriceHandlingStrategy: new DefaultChangedPriceHandlingStrategy(), orderPlacedStrategy: new DefaultOrderPlacedStrategy(), activeOrderStrategy: new DefaultActiveOrderStrategy(), orderSellerStrategy: new DefaultOrderSellerStrategy(), guestCheckoutStrategy: new DefaultGuestCheckoutStrategy(), }, paymentOptions: { paymentMethodEligibilityCheckers: [], paymentMethodHandlers: [], customPaymentProcess: [], process: [defaultPaymentProcess], }, taxOptions: { taxZoneStrategy: new DefaultTaxZoneStrategy(), taxLineCalculationStrategy: new DefaultTaxLineCalculationStrategy(), }, importExportOptions: { importAssetsDir: __dirname, assetImportStrategy: new DefaultAssetImportStrategy(), }, jobQueueOptions: { jobQueueStrategy: new InMemoryJobQueueStrategy(), jobBufferStorageStrategy: new InMemoryJobBufferStorageStrategy(), activeQueues: [], prefix: '', }, customFields: { Address: [], Administrator: [], Asset: [], Channel: [], Collection: [], Customer: [], CustomerGroup: [], Facet: [], FacetValue: [], Fulfillment: [], GlobalSettings: [], Order: [], OrderLine: [], PaymentMethod: [], Product: [], ProductOption: [], ProductOptionGroup: [], ProductVariant: [], ProductVariantPrice: [], Promotion: [], Region: [], Seller: [], ShippingMethod: [], StockLocation: [], TaxCategory: [], TaxRate: [], User: [], Zone: [], }, plugins: [], systemOptions: { healthChecks: [new TypeORMHealthCheckStrategy()], errorHandlers: [], }, };
export * from './asset-import-strategy/asset-import-strategy'; export * from './asset-naming-strategy/asset-naming-strategy'; export * from './asset-naming-strategy/default-asset-naming-strategy'; export * from './asset-preview-strategy/asset-preview-strategy'; export * from './asset-storage-strategy/asset-storage-strategy'; export * from './auth/authentication-strategy'; export * from './auth/bcrypt-password-hashing-strategy'; export * from './auth/default-password-validation-strategy'; export * from './auth/native-authentication-strategy'; export * from './auth/password-hashing-strategy'; export * from './auth/password-validation-strategy'; export * from './catalog/collection-filter'; export * from './catalog/default-collection-filters'; export * from './catalog/default-product-variant-price-selection-strategy'; export * from './catalog/default-product-variant-price-update-strategy'; export * from './catalog/default-stock-display-strategy'; export * from './catalog/default-stock-location-strategy'; export * from './catalog/product-variant-price-calculation-strategy'; export * from './catalog/product-variant-price-selection-strategy'; export * from './catalog/product-variant-price-update-strategy'; export * from './catalog/stock-display-strategy'; export * from './catalog/stock-location-strategy'; export * from './config.module'; export * from './config.service'; export * from './config-helpers'; export * from './custom-field/custom-field-types'; export * from './default-config'; export * from './entity/auto-increment-id-strategy'; export * from './entity/default-money-strategy'; export * from './entity/entity-duplicator'; export * from './entity/entity-duplicators/index'; export * from './entity/bigint-money-strategy'; export * from './entity/entity-id-strategy'; export * from './entity/money-strategy'; export * from './entity/uuid-id-strategy'; export * from './entity-metadata/entity-metadata-modifier'; export * from './fulfillment/default-fulfillment-process'; export * from './fulfillment/fulfillment-handler'; export * from './fulfillment/fulfillment-process'; export * from './fulfillment/manual-fulfillment-handler'; export * from './job-queue/inspectable-job-queue-strategy'; export * from './job-queue/job-queue-strategy'; export * from './logger/default-logger'; export * from './logger/noop-logger'; export * from './logger/vendure-logger'; export * from './merge-config'; export * from './order/active-order-strategy'; export * from './order/changed-price-handling-strategy'; export * from './order/default-active-order-strategy'; export * from './order/default-changed-price-handling-strategy'; export * from './order/default-order-placed-strategy'; export * from './order/default-order-process'; export * from './order/default-order-seller-strategy'; export * from './order/default-stock-allocation-strategy'; export * from './order/default-guest-checkout-strategy'; export * from './order/guest-checkout-strategy'; export * from './order/merge-orders-strategy'; export * from './order/order-by-code-access-strategy'; export * from './order/order-code-strategy'; export * from './order/order-item-price-calculation-strategy'; export * from './order/order-merge-strategy'; export * from './order/order-placed-strategy'; export * from './order/order-process'; export * from './order/order-seller-strategy'; export * from './order/stock-allocation-strategy'; export * from './order/use-existing-strategy'; export * from './order/use-guest-if-existing-empty-strategy'; export * from './order/use-guest-strategy'; export * from './payment/default-payment-process'; export * from './payment/dummy-payment-method-handler'; export * from './payment/example-payment-method-handler'; export * from './payment/payment-method-eligibility-checker'; export * from './payment/payment-method-handler'; export * from './payment/payment-process'; export * from './promotion'; export * from './session-cache/in-memory-session-cache-strategy'; export * from './session-cache/noop-session-cache-strategy'; export * from './session-cache/session-cache-strategy'; export * from './shipping-method/default-shipping-calculator'; export * from './shipping-method/default-shipping-eligibility-checker'; export * from './shipping-method/default-shipping-line-assignment-strategy'; export * from './shipping-method/shipping-calculator'; export * from './shipping-method/shipping-eligibility-checker'; export * from './shipping-method/shipping-line-assignment-strategy'; export * from './system/health-check-strategy'; export * from './system/error-handler-strategy'; export * from './tax/default-tax-line-calculation-strategy'; export * from './tax/default-tax-zone-strategy'; export * from './tax/tax-line-calculation-strategy'; export * from './tax/tax-zone-strategy'; export * from './vendure-config';
import { describe, expect, it } from 'vitest'; import { mergeConfig } from './merge-config'; describe('mergeConfig()', () => { it('creates a new object reference', () => { const nestedObject = { b: 2 }; const input: any = { a: nestedObject, }; const result = mergeConfig(input, { c: 5 } as any); expect(result).toEqual({ a: nestedObject, c: 5, }); expect(input).not.toBe(result); expect(input.a).not.toBe(result.a); }); it('merges top-level properties', () => { const input: any = { a: 1, b: 2, }; const result = mergeConfig(input, { b: 3, c: 5 } as any); expect(result).toEqual({ a: 1, b: 3, c: 5, }); }); it('does not merge arrays', () => { const input: any = { a: [1], }; const result = mergeConfig(input, { a: [2] } as any); expect(result).toEqual({ a: [2], }); }); it('merges deep properties', () => { const input: any = { a: 1, b: { c: 2 }, }; const result = mergeConfig(input, { b: { c: 5 } } as any); expect(result).toEqual({ a: 1, b: { c: 5 }, }); }); it('does not mutate target', () => { const input: any = { a: 1, b: { c: { d: 'foo', e: { f: 1 } } }, }; const result = mergeConfig(input, { b: { c: { d: 'bar' } } } as any); expect(result).toEqual({ a: 1, b: { c: { d: 'bar', e: { f: 1 } } }, }); expect(input).toEqual({ a: 1, b: { c: { d: 'foo', e: { f: 1 } } }, }); }); it('works when nested', () => { const input1: any = { a: 1, b: { c: { d: 'foo1', e: { f: 1 } } }, }; const input2: any = { b: { c: { d: 'foo2', e: { f: 2 } } }, }; const result = mergeConfig(input1, mergeConfig(input2, { b: { c: { d: 'bar' } } } as any)); expect(result).toEqual({ a: 1, b: { c: { d: 'bar', e: { f: 2 } } }, }); expect(input1).toEqual({ a: 1, b: { c: { d: 'foo1', e: { f: 1 } } }, }); expect(input2).toEqual({ b: { c: { d: 'foo2', e: { f: 2 } } }, }); }); it('replaces class instances rather than merging their properties', () => { class Foo { name = 'foo'; } class Bar { name = 'bar'; } const input: any = { class: new Foo(), }; const result = mergeConfig(input, { class: new Bar() } as any); expect(result.class instanceof Bar).toBe(true); expect(result.class.name).toBe('bar'); }); });
import { isClassInstance, isObject } from '@vendure/common/lib/shared-utils'; import { simpleDeepClone } from '@vendure/common/lib/simple-deep-clone'; import { PartialVendureConfig, VendureConfig } from './vendure-config'; /** * @description * Performs a deep merge of two VendureConfig objects. Unlike `Object.assign()` the `target` object is * not mutated, instead the function returns a new object which is the result of deeply merging the * values of `source` into `target`. * * Arrays do not get merged, they are treated as a single value that will be replaced. So if merging the * `plugins` array, you must explicitly concatenate the array. * * @example * ```ts * const result = mergeConfig(defaultConfig, { * assetOptions: { * uploadMaxFileSize: 5000, * }, * plugins: [ * ...defaultConfig.plugins, * MyPlugin, * ] * }; * ``` * * @docsCategory configuration */ export function mergeConfig<T extends VendureConfig>(target: T, source: PartialVendureConfig, depth = 0): T { if (!source) { return target; } if (depth === 0) { target = simpleDeepClone(target); } if (isObject(target) && isObject(source)) { for (const key in source) { if (isObject((source as any)[key])) { if (!(target as any)[key]) { Object.assign(target as any, { [key]: {} }); } if (!isClassInstance((source as any)[key])) { mergeConfig((target as any)[key], (source as any)[key], depth + 1); } else { (target as any)[key] = (source as any)[key]; } } else { Object.assign(target, { [key]: (source as any)[key] }); } } } return target; }
import { ApolloServerPlugin } from '@apollo/server'; import { RenderPageOptions } from '@apollographql/graphql-playground-html'; import { DynamicModule, Type } from '@nestjs/common'; import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface'; import { LanguageCode } from '@vendure/common/lib/generated-types'; import { ValidationContext } from 'graphql'; import { DataSourceOptions } from 'typeorm'; import { Middleware } from '../common'; import { PermissionDefinition } from '../common/permission-definition'; import { JobBufferStorageStrategy } from '../job-queue/job-buffer/job-buffer-storage-strategy'; import { AssetImportStrategy } from './asset-import-strategy/asset-import-strategy'; import { AssetNamingStrategy } from './asset-naming-strategy/asset-naming-strategy'; import { AssetPreviewStrategy } from './asset-preview-strategy/asset-preview-strategy'; import { AssetStorageStrategy } from './asset-storage-strategy/asset-storage-strategy'; import { AuthenticationStrategy } from './auth/authentication-strategy'; import { PasswordHashingStrategy } from './auth/password-hashing-strategy'; import { PasswordValidationStrategy } from './auth/password-validation-strategy'; import { CollectionFilter } from './catalog/collection-filter'; import { ProductVariantPriceCalculationStrategy } from './catalog/product-variant-price-calculation-strategy'; import { ProductVariantPriceSelectionStrategy } from './catalog/product-variant-price-selection-strategy'; import { ProductVariantPriceUpdateStrategy } from './catalog/product-variant-price-update-strategy'; import { StockDisplayStrategy } from './catalog/stock-display-strategy'; import { StockLocationStrategy } from './catalog/stock-location-strategy'; import { CustomFields } from './custom-field/custom-field-types'; import { EntityDuplicator } from './entity/entity-duplicator'; import { EntityIdStrategy } from './entity/entity-id-strategy'; import { MoneyStrategy } from './entity/money-strategy'; import { EntityMetadataModifier } from './entity-metadata/entity-metadata-modifier'; import { FulfillmentHandler } from './fulfillment/fulfillment-handler'; import { FulfillmentProcess } from './fulfillment/fulfillment-process'; import { JobQueueStrategy } from './job-queue/job-queue-strategy'; import { VendureLogger } from './logger/vendure-logger'; import { ActiveOrderStrategy } from './order/active-order-strategy'; import { ChangedPriceHandlingStrategy } from './order/changed-price-handling-strategy'; import { GuestCheckoutStrategy } from './order/guest-checkout-strategy'; import { OrderByCodeAccessStrategy } from './order/order-by-code-access-strategy'; import { OrderCodeStrategy } from './order/order-code-strategy'; import { OrderItemPriceCalculationStrategy } from './order/order-item-price-calculation-strategy'; import { OrderMergeStrategy } from './order/order-merge-strategy'; import { OrderPlacedStrategy } from './order/order-placed-strategy'; import { OrderProcess } from './order/order-process'; import { OrderSellerStrategy } from './order/order-seller-strategy'; import { StockAllocationStrategy } from './order/stock-allocation-strategy'; import { PaymentMethodEligibilityChecker } from './payment/payment-method-eligibility-checker'; import { PaymentMethodHandler } from './payment/payment-method-handler'; import { PaymentProcess } from './payment/payment-process'; import { PromotionAction } from './promotion/promotion-action'; import { PromotionCondition } from './promotion/promotion-condition'; import { SessionCacheStrategy } from './session-cache/session-cache-strategy'; import { ShippingCalculator } from './shipping-method/shipping-calculator'; import { ShippingEligibilityChecker } from './shipping-method/shipping-eligibility-checker'; import { ShippingLineAssignmentStrategy } from './shipping-method/shipping-line-assignment-strategy'; import { ErrorHandlerStrategy } from './system/error-handler-strategy'; import { HealthCheckStrategy } from './system/health-check-strategy'; import { TaxLineCalculationStrategy } from './tax/tax-line-calculation-strategy'; import { TaxZoneStrategy } from './tax/tax-zone-strategy'; /** * @description * The ApiOptions define how the Vendure GraphQL APIs are exposed, as well as allowing the API layer * to be extended with middleware. * * @docsCategory configuration */ export interface ApiOptions { /** * @description * Set the hostname of the server. If not set, the server will be available on localhost. * * @default '' */ hostname?: string; /** * @description * Which port the Vendure server should listen on. * * @default 3000 */ port: number; /** * @description * The path to the admin GraphQL API. * * @default 'admin-api' */ adminApiPath?: string; /** * @description * The path to the shop GraphQL API. * * @default 'shop-api' */ shopApiPath?: string; /** * @description * The playground config to the admin GraphQL API * [ApolloServer playground](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#constructoroptions-apolloserver). * * @default false */ adminApiPlayground?: boolean | RenderPageOptions; /** * @description * The playground config to the shop GraphQL API * [ApolloServer playground](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#constructoroptions-apolloserver). * * @default false */ shopApiPlayground?: boolean | RenderPageOptions; /** * @description * The debug config to the admin GraphQL API * [ApolloServer playground](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#constructoroptions-apolloserver). * * @default false */ adminApiDebug?: boolean; /** * @description * The debug config to the shop GraphQL API * [ApolloServer playground](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#constructoroptions-apolloserver). * * @default false */ shopApiDebug?: boolean; /** * @description * The maximum number of items that may be returned by a query which returns a `PaginatedList` response. In other words, * this is the upper limit of the `take` input option. * * @default 100 */ shopListQueryLimit?: number; /** * @description * The maximum number of items that may be returned by a query which returns a `PaginatedList` response. In other words, * this is the upper limit of the `take` input option. * * @default 1000 */ adminListQueryLimit?: number; /** * @description * Custom functions to use as additional validation rules when validating the schema for the admin GraphQL API * [ApolloServer validation rules](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#validationrules). * * @default [] */ adminApiValidationRules?: Array<(context: ValidationContext) => any>; /** * @description * Custom functions to use as additional validation rules when validating the schema for the shop GraphQL API * [ApolloServer validation rules](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#validationrules). * * @default [] */ shopApiValidationRules?: Array<(context: ValidationContext) => any>; /** * @description * The name of the property which contains the token of the * active channel. This property can be included either in * the request header or as a query string. * * @default 'vendure-token' */ channelTokenKey?: string; /** * @description * Set the CORS handling for the server. See the [express CORS docs](https://github.com/expressjs/cors#configuration-options). * * @default { origin: true, credentials: true } */ cors?: boolean | CorsOptions; /** * @description * Custom Express or NestJS middleware for the server. More information can be found in the {@link Middleware} docs. * * @default [] */ middleware?: Middleware[]; /** * @description * Custom [ApolloServerPlugins](https://www.apollographql.com/docs/apollo-server/integrations/plugins/) which * allow the extension of the Apollo Server, which is the underlying GraphQL server used by Vendure. * * Apollo plugins can be used e.g. to perform custom data transformations on incoming operations or outgoing * data. * * @default [] */ apolloServerPlugins?: ApolloServerPlugin[]; /** * @description * Controls whether introspection of the GraphQL APIs is enabled. For production, it is recommended to disable * introspection, since exposing your entire schema can allow an attacker to trivially learn all operations * and much more easily find any potentially exploitable queries. * * **Note:** when introspection is disabled, tooling which relies on it for things like autocompletion * will not work. * * @example * ```ts * { * introspection: process.env.NODE_ENV !== 'production' * } * ``` * * @default true * @since 1.5.0 */ introspection?: boolean; } /** * @description * Options for the handling of the cookies used to track sessions (only applicable if * `authOptions.tokenMethod` is set to `'cookie'`). These options are passed directly * to the Express [cookie-session middleware](https://github.com/expressjs/cookie-session). * * @docsCategory auth */ export interface CookieOptions { /** * @description * The name of the cookies to set. * If set to a string, both cookies for the Admin API and Shop API will have the same name. * If set as an object, it makes it possible to give different names to the Admin API and the Shop API cookies * * @default 'session' */ name?: string | { shop: string; admin: string }; /** * @description * The secret used for signing the session cookies for authenticated users. Only applies * tokenMethod is set to 'cookie'. * * In production applications, this should not be stored as a string in * source control for security reasons, but may be loaded from an external * file not under source control, or from an environment variable, for example. * * @default (random character string) */ secret?: string; /** * @description * a string indicating the path of the cookie. * * @default '/' */ path?: string; /** * @description * a string indicating the domain of the cookie (no default). */ domain?: string; /** * @description * a boolean or string indicating whether the cookie is a "same site" cookie (false by default). This can be set to 'strict', * 'lax', 'none', or true (which maps to 'strict'). * * @default false */ sameSite?: 'strict' | 'lax' | 'none' | boolean; /** * @description * a boolean indicating whether the cookie is only to be sent over HTTPS (false by default for HTTP, true by default for HTTPS). */ secure?: boolean; /** * @description * a boolean indicating whether the cookie is only to be sent over HTTPS (use this if you handle SSL not in your node process). */ secureProxy?: boolean; /** * @description * a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (true by default). * * @default true */ httpOnly?: boolean; /** * @description * a boolean indicating whether the cookie is to be signed (true by default). If this is true, another cookie of the same name with the .sig * suffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of cookie-name=cookie-value against the * first Keygrip key. This signature key is used to detect tampering the next time a cookie is received. */ signed?: boolean; /** * @description * a boolean indicating whether to overwrite previously set cookies of the same name (true by default). If this is true, all cookies set during * the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie. */ overwrite?: boolean; /** * @description * A number representing the milliseconds from Date.now() for expiry * * @since 2.2.0 */ maxAge?: number; /** * @description * a Date object indicating the cookie's expiration date (expires at the end of session by default). * * @since 2.2.0 */ expires?: Date; } /** * @description * The AuthOptions define how authentication and authorization is managed. * * @docsCategory auth * */ export interface AuthOptions { /** * @description * Disable authentication & permissions checks. * NEVER set the to true in production. It exists * only to aid certain development tasks. * * @default false */ disableAuth?: boolean; /** * @description * Sets the method by which the session token is delivered and read. * * * 'cookie': Upon login, a 'Set-Cookie' header will be returned to the client, setting a * cookie containing the session token. A browser-based client (making requests with credentials) * should automatically send the session cookie with each request. * * 'bearer': Upon login, the token is returned in the response and should be then stored by the * client app. Each request should include the header `Authorization: Bearer <token>`. * * Note that if the bearer method is used, Vendure will automatically expose the configured * `authTokenHeaderKey` in the server's CORS configuration (adding `Access-Control-Expose-Headers: vendure-auth-token` * by default). * * From v1.2.0 it is possible to specify both methods as a tuple: `['cookie', 'bearer']`. * * @default 'cookie' */ tokenMethod?: 'cookie' | 'bearer' | ReadonlyArray<'cookie' | 'bearer'>; /** * @description * Options related to the handling of cookies when using the 'cookie' tokenMethod. */ cookieOptions?: CookieOptions; /** * @description * Sets the header property which will be used to send the auth token when using the 'bearer' method. * * @default 'vendure-auth-token' */ authTokenHeaderKey?: string; /** * @description * Session duration, i.e. the time which must elapse from the last authenticated request * after which the user must re-authenticate. * * Expressed as a string describing a time span per * [zeit/ms](https://github.com/zeit/ms.js). Eg: `60`, `'2 days'`, `'10h'`, `'7d'` * * @default '1y' */ sessionDuration?: string | number; /** * @description * This strategy defines how sessions will be cached. By default, sessions are cached using a simple * in-memory caching strategy which is suitable for development and low-traffic, single-instance * deployments. * * @default InMemorySessionCacheStrategy */ sessionCacheStrategy?: SessionCacheStrategy; /** * @description * The "time to live" of a given item in the session cache. This determines the length of time (in seconds) * that a cache entry is kept before being considered "stale" and being replaced with fresh data * taken from the database. * * @default 300 */ sessionCacheTTL?: number; /** * @description * Determines whether new User accounts require verification of their email address. * * If set to "true", when registering via the `registerCustomerAccount` mutation, one should *not* set the * `password` property - doing so will result in an error. Instead, the password is set at a later stage * (once the email with the verification token has been opened) via the `verifyCustomerAccount` mutation. * * @default true */ requireVerification?: boolean; /** * @description * Sets the length of time that a verification token is valid for, after which the verification token must be refreshed. * * Expressed as a string describing a time span per * [zeit/ms](https://github.com/zeit/ms.js). Eg: `60`, `'2 days'`, `'10h'`, `'7d'` * * @default '7d' */ verificationTokenDuration?: string | number; /** * @description * Configures the credentials to be used to create a superadmin */ superadminCredentials?: SuperadminCredentials; /** * @description * Configures one or more AuthenticationStrategies which defines how authentication * is handled in the Shop API. * @default NativeAuthenticationStrategy */ shopAuthenticationStrategy?: AuthenticationStrategy[]; /** * @description * Configures one or more AuthenticationStrategy which defines how authentication * is handled in the Admin API. * @default NativeAuthenticationStrategy */ adminAuthenticationStrategy?: AuthenticationStrategy[]; /** * @description * Allows custom Permissions to be defined, which can be used to restrict access to custom * GraphQL resolvers defined in plugins. * * @default [] */ customPermissions?: PermissionDefinition[]; /** * @description * Allows you to customize the way passwords are hashed when using the {@link NativeAuthenticationStrategy}. * * @default BcryptPasswordHashingStrategy * @since 1.3.0 */ passwordHashingStrategy?: PasswordHashingStrategy; /** * @description * Allows you to set a custom policy for passwords when using the {@link NativeAuthenticationStrategy}. * By default, it uses the {@link DefaultPasswordValidationStrategy}, which will impose a minimum length * of four characters. To improve security for production, you are encouraged to specify a more strict * policy, which you can do like this: * * @example * ```ts * { * passwordValidationStrategy: new DefaultPasswordValidationStrategy({ * // Minimum eight characters, at least one letter and one number * regexp: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, * }), * } * ``` * * @since 1.5.0 * @default DefaultPasswordValidationStrategy */ passwordValidationStrategy?: PasswordValidationStrategy; } /** * @docsCategory orders * @docsPage OrderOptions * */ export interface OrderOptions { /** * @description * The maximum number of individual items allowed in a single order. This option exists * to prevent excessive resource usage when dealing with very large orders. For example, * if an order contains a million items, then any operations on that order (modifying a quantity, * adding or removing an item) will require Vendure to loop through all million items * to perform price calculations against active promotions and taxes. This can have a significant * performance impact for very large values. * * Attempting to exceed this limit will cause Vendure to throw a {@link OrderItemsLimitError}. * * @default 999 */ orderItemsLimit?: number; /** * @description * The maximum number of items allowed per order line. This option is an addition * on the `orderItemsLimit` for more granular control. Note `orderItemsLimit` is still * important in order to prevent excessive resource usage. * * Attempting to exceed this limit will cause Vendure to throw a {@link OrderItemsLimitError}. * * @default 999 */ orderLineItemsLimit?: number; /** * @description * Defines the logic used to calculate the unit price of an OrderLine when adding an * item to an Order. * * @default DefaultPriceCalculationStrategy */ orderItemPriceCalculationStrategy?: OrderItemPriceCalculationStrategy; /** * @description * Allows the definition of custom states and transition logic for the order process state machine. * Takes an array of objects implementing the {@link OrderProcess} interface. * * @default [] */ process?: Array<OrderProcess<any>>; /** * @description * Determines the point of the order process at which stock gets allocated. * * @default DefaultStockAllocationStrategy */ stockAllocationStrategy?: StockAllocationStrategy; /** * @description * Defines the strategy used to merge a guest Order and an existing Order when * signing in. * * @default MergeOrdersStrategy */ mergeStrategy?: OrderMergeStrategy; /** * @description * Defines the strategy used to merge a guest Order and an existing Order when * signing in as part of the checkout flow. * * @default UseGuestStrategy */ checkoutMergeStrategy?: OrderMergeStrategy; /** * @description * Allows a user-defined function to create Order codes. This can be useful when * integrating with existing systems. By default, Vendure will generate a 16-character * alphanumeric string. * * Note: when using a custom function for Order codes, bear in mind the database limit * for string types (e.g. 255 chars for a varchar field in MySQL), and also the need * for codes to be unique. * * @default DefaultOrderCodeStrategy */ orderCodeStrategy?: OrderCodeStrategy; /** * @description * Defines the strategy used to check if and how an Order may be retrieved via the orderByCode query. * * The default strategy permits permanent access to the Customer owning the Order and anyone * within 2 hours after placing the Order. * * @since 1.1.0 * @default DefaultOrderByCodeAccessStrategy */ orderByCodeAccessStrategy?: OrderByCodeAccessStrategy; /** * @description * Defines how we handle the situation where an item exists in an Order, and * then later on another is added but in the meantime the price of the ProductVariant has changed. * * By default, the latest price will be used. Any price changes resulting from using a newer price * will be reflected in the GraphQL `OrderLine.unitPrice[WithTax]ChangeSinceAdded` field. * * @default DefaultChangedPriceHandlingStrategy */ changedPriceHandlingStrategy?: ChangedPriceHandlingStrategy; /** * @description * Defines the point of the order process at which the Order is set as "placed". * * @default DefaultOrderPlacedStrategy */ orderPlacedStrategy?: OrderPlacedStrategy; /** * @description * Defines the strategy used to determine the active Order when interacting with Shop API operations * such as `activeOrder` and `addItemToOrder`. By default, the strategy uses the active Session. * * Note that if multiple strategies are defined, they will be checked in order and the first one that * returns an Order will be used. * * @since 1.9.0 * @default DefaultActiveOrderStrategy */ activeOrderStrategy?: ActiveOrderStrategy<any> | Array<ActiveOrderStrategy<any>>; /** * @description * Defines how Orders will be split amongst multiple Channels in a multivendor scenario. * * @since 2.0.0 * @default DefaultOrderSellerStrategy */ orderSellerStrategy?: OrderSellerStrategy; /** * @description * Defines how we deal with guest checkouts. * * @since 2.0.0 * @default DefaultGuestCheckoutStrategy */ guestCheckoutStrategy?: GuestCheckoutStrategy; } /** * @description * The AssetOptions define how assets (images and other files) are named and stored, and how preview images are generated. * * **Note**: If you are using the `AssetServerPlugin`, it is not necessary to configure these options. * * @docsCategory assets * */ export interface AssetOptions { /** * @description * Defines how asset files and preview images are named before being saved. * * @default DefaultAssetNamingStrategy */ assetNamingStrategy?: AssetNamingStrategy; /** * @description * Defines the strategy used for storing uploaded binary files. * * @default NoAssetStorageStrategy */ assetStorageStrategy?: AssetStorageStrategy; /** * @description * Defines the strategy used for creating preview images of uploaded assets. * * @default NoAssetPreviewStrategy */ assetPreviewStrategy?: AssetPreviewStrategy; /** * @description * An array of the permitted file types that may be uploaded as Assets. Each entry * should be in the form of a valid * [unique file type specifier](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers) * i.e. either a file extension (".pdf") or a mime type ("image/*", "audio/mpeg" etc.). * * @default image, audio, video MIME types plus PDFs */ permittedFileTypes?: string[]; /** * @description * The max file size in bytes for uploaded assets. * * @default 20971520 */ uploadMaxFileSize?: number; } /** * @description * Options related to products and collections. * * @docsCategory products & stock */ export interface CatalogOptions { /** * @description * Allows custom {@link CollectionFilter}s to be defined. * * @default defaultCollectionFilters */ collectionFilters?: Array<CollectionFilter<any>>; /** * @description * Defines the strategy used to select the price of a ProductVariant, based on factors * such as the active Channel and active CurrencyCode. * * @since 2.0.0 * @default DefaultProductVariantPriceSelectionStrategy */ productVariantPriceSelectionStrategy?: ProductVariantPriceSelectionStrategy; /** * @description * Defines the strategy used for calculating the price of ProductVariants based * on the Channel settings and active tax Zone. * * @default DefaultTaxCalculationStrategy */ productVariantPriceCalculationStrategy?: ProductVariantPriceCalculationStrategy; /** * @description * Defines the strategy which determines what happens to a ProductVariant's prices * when one of the prices gets updated. For instance, this can be used to synchronize * prices across multiple Channels. * * @default DefaultProductVariantPriceUpdateStrategy * @since 2.2.0 */ productVariantPriceUpdateStrategy?: ProductVariantPriceUpdateStrategy; /** * @description * Defines how the `ProductVariant.stockLevel` value is obtained. It is usually not desirable * to directly expose stock levels over a public API, as this could be considered a leak of * sensitive information. However, the storefront will usually want to display _some_ indication * of whether a given ProductVariant is in stock. The default StockDisplayStrategy will * display "IN_STOCK", "OUT_OF_STOCK" or "LOW_STOCK" rather than exposing the actual saleable * stock level. * * @default DefaultStockDisplayStrategy */ stockDisplayStrategy?: StockDisplayStrategy; /** * @description * Defines the strategy used to determine which StockLocation should be used when performing * stock operations such as allocating and releasing stock as well as determining the * amount of stock available for sale. * * @default DefaultStockLocationStrategy * @since 2.0.0 */ stockLocationStrategy?: StockLocationStrategy; } /** * @docsCategory promotions */ export interface PromotionOptions { /** * @description * An array of conditions which can be used to construct Promotions */ promotionConditions?: Array<PromotionCondition<any>>; /** * @description * An array of actions which can be used to construct Promotions */ promotionActions?: Array<PromotionAction<any>>; } /** * @docsCategory shipping * */ export interface ShippingOptions { /** * @description * An array of available ShippingEligibilityCheckers for use in configuring ShippingMethods */ shippingEligibilityCheckers?: Array<ShippingEligibilityChecker<any>>; /** * @description * An array of available ShippingCalculators for use in configuring ShippingMethods */ shippingCalculators?: Array<ShippingCalculator<any>>; /** * @description * This strategy is used to assign a given {@link ShippingLine} to one or more {@link OrderLine}s of the Order. * This allows you to set multiple shipping methods for a single order, each assigned a different subset of * OrderLines. * * @since 2.0.0 */ shippingLineAssignmentStrategy?: ShippingLineAssignmentStrategy; /** * @description * Allows the definition of custom states and transition logic for the fulfillment process state machine. * Takes an array of objects implementing the {@link FulfillmentProcess} interface. * * @deprecated use `process` */ customFulfillmentProcess?: Array<FulfillmentProcess<any>>; /** * @description * Allows the definition of custom states and transition logic for the fulfillment process state machine. * Takes an array of objects implementing the {@link FulfillmentProcess} interface. * * @since 2.0.0 * @default defaultFulfillmentProcess */ process?: Array<FulfillmentProcess<any>>; /** * @description * An array of available FulfillmentHandlers. */ fulfillmentHandlers?: Array<FulfillmentHandler<any>>; } /** * @description * These credentials will be used to create the Superadmin user & administrator * when Vendure first bootstraps. * * @docsCategory auth */ export interface SuperadminCredentials { /** * @description * The identifier to be used to create a superadmin account * @default 'superadmin' */ identifier: string; /** * @description * The password to be used to create a superadmin account * @default 'superadmin' */ password: string; } /** * @description * Defines payment-related options in the {@link VendureConfig}. * * @docsCategory payment * */ export interface PaymentOptions { /** * @description * Defines which {@link PaymentMethodHandler}s are available when configuring * {@link PaymentMethod}s */ paymentMethodHandlers: PaymentMethodHandler[]; /** * @description * Defines which {@link PaymentMethodEligibilityChecker}s are available when configuring * {@link PaymentMethod}s */ paymentMethodEligibilityCheckers?: PaymentMethodEligibilityChecker[]; /** * @deprecated use `process` */ customPaymentProcess?: Array<PaymentProcess<any>>; /** * @description * Allows the definition of custom states and transition logic for the payment process state machine. * Takes an array of objects implementing the {@link PaymentProcess} interface. * * @default defaultPaymentProcess * @since 2.0.0 */ process?: Array<PaymentProcess<any>>; } /** * @docsCategory tax * * */ export interface TaxOptions { /** * @description * Defines the strategy used to determine the applicable Zone used in tax calculations. * * @default DefaultTaxZoneStrategy */ taxZoneStrategy?: TaxZoneStrategy; /** * @description * Defines the strategy used to calculate the TaxLines added to OrderItems. * * @default DefaultTaxLineCalculationStrategy */ taxLineCalculationStrategy?: TaxLineCalculationStrategy; } /** * @description * Options related to importing & exporting data. * * @docsCategory import-export */ export interface ImportExportOptions { /** * @description * The directory in which assets to be imported are located. * * @default __dirname */ importAssetsDir?: string; /** * @description * This strategy determines how asset files get imported based on the path given in the * import CSV or via the {@link AssetImporter} `getAssets()` method. * * @since 1.7.0 */ assetImportStrategy?: AssetImportStrategy; } /** * @description * Options related to the built-in job queue. * * @docsCategory JobQueue */ export interface JobQueueOptions { /** * @description * Defines how the jobs in the queue are persisted and accessed. * * @default InMemoryJobQueueStrategy */ jobQueueStrategy?: JobQueueStrategy; jobBufferStorageStrategy?: JobBufferStorageStrategy; /** * @description * Defines the queues that will run in this process. * This can be used to configure only certain queues to run in this process. * If its empty all queues will be run. Note: this option is primarily intended * to apply to the Worker process. Jobs will _always_ get published to the queue * regardless of this setting, but this setting determines whether they get * _processed_ or not. */ activeQueues?: string[]; /** * @description * Prefixes all job queue names with the passed string. This is useful with multiple deployments * in cloud environments using services such as Amazon SQS or Google Cloud Tasks. * * For example, we might have a staging and a production deployment in the same account/project and * each one will need its own task queue. We can achieve this with a prefix. * * @since 1.5.0 */ prefix?: string; } /** * @description * Options relating to the internal handling of entities. * * @since 1.3.0 * @docsCategory configuration * @docsPage EntityOptions * @docsWeight 0 */ export interface EntityOptions { /** * @description * Defines the strategy used for both storing the primary keys of entities * in the database, and the encoding & decoding of those ids when exposing * entities via the API. The default uses a simple auto-increment integer * strategy. * * :::caution * Note: changing from an integer-based strategy to a uuid-based strategy * on an existing Vendure database will lead to problems with broken foreign-key * references. To change primary key types like this, you'll need to start with * a fresh database. * ::: * * @since 1.3.0 * @default AutoIncrementIdStrategy */ entityIdStrategy?: EntityIdStrategy<any>; /** * @description * An array of {@link EntityDuplicator} instances which are used to duplicate entities * when using the `duplicateEntity` mutation. * * @since 2.2.0 * @default defaultEntityDuplicators */ entityDuplicators?: Array<EntityDuplicator<any>>; /** * @description * Defines the strategy used to store and round monetary values. * * @since 2.0.0 * @default DefaultMoneyStrategy */ moneyStrategy?: MoneyStrategy; /** * @description * Channels get cached in-memory as they are accessed very frequently. This * setting determines how long the cache lives (in ms) until it is considered stale and * refreshed. For multi-instance deployments (e.g. serverless, load-balanced), a * smaller value here will prevent data inconsistencies between instances. * * @since 1.3.0 * @default 30000 */ channelCacheTtl?: number; /** * @description * Zones get cached in-memory as they are accessed very frequently. This * setting determines how long the cache lives (in ms) until it is considered stale and * refreshed. For multi-instance deployments (e.g. serverless, load-balanced), a * smaller value here will prevent data inconsistencies between instances. * * @since 1.3.0 * @default 30000 */ zoneCacheTtl?: number; /** * @description * TaxRates get cached in-memory as they are accessed very frequently. This * setting determines how long the cache lives (in ms) until it is considered stale and * refreshed. For multi-instance deployments (e.g. serverless, load-balanced), a * smaller value here will prevent data inconsistencies between instances. * * @since 1.9.0 * @default 30000 */ taxRateCacheTtl?: number; /** * @description * Allows the metadata of the built-in TypeORM entities to be manipulated. This allows you * to do things like altering data types, adding indices etc. This is an advanced feature * which should be used with some caution as it will result in DB schema changes. For examples * see {@link EntityMetadataModifier}. * * @since 1.6.0 * @default [] */ metadataModifiers?: EntityMetadataModifier[]; } /** * @description * Options relating to system functions. * * @since 1.6.0 * @docsCategory configuration */ export interface SystemOptions { /** * @description * Defines an array of {@link HealthCheckStrategy} instances which are used by the `/health` endpoint to verify * that any critical systems which the Vendure server depends on are also healthy. * * @default [TypeORMHealthCheckStrategy] * @since 1.6.0 */ healthChecks?: HealthCheckStrategy[]; /** * @description * Defines an array of {@link ErrorHandlerStrategy} instances which are used to define logic to be executed * when an error occurs, either on the server or the worker. * * @default [] * @since 2.2.0 */ errorHandlers?: ErrorHandlerStrategy[]; } /** * @description * All possible configuration options are defined by the * [`VendureConfig`](https://github.com/vendure-ecommerce/vendure/blob/master/server/src/config/vendure-config.ts) interface. * * @docsCategory configuration * */ export interface VendureConfig { /** * @description * Configuration for the GraphQL APIs, including hostname, port, CORS settings, * middleware etc. */ apiOptions: ApiOptions; /** * @description * Configuration for the handling of Assets. */ assetOptions?: AssetOptions; /** * @description * Configuration for authorization. */ authOptions: AuthOptions; /** * @description * Configuration for Products and Collections. */ catalogOptions?: CatalogOptions; /** * @description * Defines custom fields which can be used to extend the built-in entities. * * @default {} */ customFields?: CustomFields; /** * @description * The connection options used by TypeORM to connect to the database. * See the [TypeORM documentation](https://typeorm.io/#/connection-options) for a * full description of all available options. */ dbConnectionOptions: DataSourceOptions; /** * @description * The token for the default channel. If not specified, a token * will be randomly generated. * * @default null */ defaultChannelToken?: string | null; /** * @description * The default languageCode of the app. * * @default LanguageCode.en */ defaultLanguageCode?: LanguageCode; /** * @description * Defines the strategy used for both storing the primary keys of entities * in the database, and the encoding & decoding of those ids when exposing * entities via the API. The default uses a simple auto-increment integer * strategy. * * @deprecated Use entityOptions.entityIdStrategy instead * @default AutoIncrementIdStrategy */ entityIdStrategy?: EntityIdStrategy<any>; entityOptions?: EntityOptions; /** * @description * Configuration settings for data import and export. */ importExportOptions?: ImportExportOptions; /** * @description * Configuration settings governing how orders are handled. */ orderOptions?: OrderOptions; /** * @description * Configures available payment processing methods. */ paymentOptions: PaymentOptions; /** * @description * An array of plugins. * * @default [] */ plugins?: Array<DynamicModule | Type<any>>; /** * @description * Configures the Conditions and Actions available when creating Promotions. */ promotionOptions?: PromotionOptions; /** * @description * Configures the available checkers and calculators for ShippingMethods. */ shippingOptions?: ShippingOptions; /** * @description * Provide a logging service which implements the {@link VendureLogger} interface. * Note that the logging of SQL queries is controlled separately by the * `dbConnectionOptions.logging` property. * * @default DefaultLogger */ logger?: VendureLogger; /** * @description * Configures how taxes are calculated on products. */ taxOptions?: TaxOptions; /** * @description * Configures how the job queue is persisted and processed. */ jobQueueOptions?: JobQueueOptions; /** * @description * Configures system options * * @since 1.6.0 */ systemOptions?: SystemOptions; } /** * @description * This interface represents the VendureConfig object available at run-time, i.e. the user-supplied * config values have been merged with the {@link defaultConfig} values. * * @docsCategory configuration */ export interface RuntimeVendureConfig extends Required<VendureConfig> { apiOptions: Required<ApiOptions>; assetOptions: Required<AssetOptions>; authOptions: Required<AuthOptions>; catalogOptions: Required<CatalogOptions>; customFields: Required<CustomFields>; entityOptions: Required<Omit<EntityOptions, 'entityIdStrategy'>> & EntityOptions; importExportOptions: Required<ImportExportOptions>; jobQueueOptions: Required<JobQueueOptions>; orderOptions: Required<OrderOptions>; promotionOptions: Required<PromotionOptions>; shippingOptions: Required<ShippingOptions>; taxOptions: Required<TaxOptions>; systemOptions: Required<SystemOptions>; } type DeepPartialSimple<T> = { [P in keyof T]?: | null | (T[P] extends Array<infer U> ? Array<DeepPartialSimple<U>> : T[P] extends ReadonlyArray<infer X> ? ReadonlyArray<DeepPartialSimple<X>> : T[P] extends Type<any> ? T[P] : DeepPartialSimple<T[P]>); }; export type PartialVendureConfig = DeepPartialSimple<VendureConfig>;
import { Readable } from 'stream'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * The AssetImportStrategy determines how asset files get imported based on the path given in the * import CSV or via the {@link AssetImporter} `getAssets()` method. * * The {@link DefaultAssetImportStrategy} is able to load files from either the local filesystem * or from a remote URL. * * A custom strategy could be created which could e.g. get the asset file from an S3 bucket. * * :::info * * This is configured via the `importExportOptions.assetImportStrategy` property of * your VendureConfig. * * ::: * * @since 1.7.0 * @docsCategory import-export */ export interface AssetImportStrategy extends InjectableStrategy { /** * @description * Given an asset path, this method should return a Stream of file data. This could * e.g. be read from a file system or fetch from a remote location. */ getStreamFromPath(assetPath: string): Readable | Promise<Readable>; }
import fs from 'fs-extra'; import http from 'http'; import https from 'https'; import path from 'path'; import { from, lastValueFrom } from 'rxjs'; import { delay, retryWhen, take, tap } from 'rxjs/operators'; import { Readable } from 'stream'; import { URL } from 'url'; import { Injector } from '../../common/injector'; import { ConfigService } from '../config.service'; import { Logger } from '../logger/vendure-logger'; import { AssetImportStrategy } from './asset-import-strategy'; function fetchUrl(urlString: string): Promise<Readable> { return new Promise((resolve, reject) => { const url = new URL(urlString); const get = url.protocol.startsWith('https') ? https.get : http.get; get( url, { timeout: 5000, }, res => { const { statusCode } = res; if (statusCode !== 200) { Logger.error( `Failed to fetch "${urlString.substr(0, 100)}", statusCode: ${ statusCode || 'unknown' }`, ); reject(new Error(`Request failed. Status code: ${statusCode || 'unknown'}`)); } else { resolve(res); } }, ); }); } /** * @description * The DefaultAssetImportStrategy is able to import paths from the local filesystem (taking into account the * `importExportOptions.importAssetsDir` setting) as well as remote http/https urls. * * @since 1.7.0 * @docsCategory import-export */ export class DefaultAssetImportStrategy implements AssetImportStrategy { private configService: ConfigService; constructor( private options?: { retryDelayMs: number; retryCount: number; }, ) {} init(injector: Injector) { this.configService = injector.get(ConfigService); } getStreamFromPath(assetPath: string) { if (/^https?:\/\//.test(assetPath)) { return this.getStreamFromUrl(assetPath); } else { return this.getStreamFromLocalFile(assetPath); } } private getStreamFromUrl(assetUrl: string): Promise<Readable> { const { retryCount, retryDelayMs } = this.options ?? {}; return lastValueFrom( from(fetchUrl(assetUrl)).pipe( retryWhen(errors => errors.pipe( tap(value => { Logger.verbose(value); Logger.verbose(`DefaultAssetImportStrategy: retrying fetchUrl for ${assetUrl}`); }), delay(retryDelayMs ?? 200), take(retryCount ?? 3), ), ), ), ); } private getStreamFromLocalFile(assetPath: string): Readable { const { importAssetsDir } = this.configService.importExportOptions; const filename = path.join(importAssetsDir, assetPath); if (fs.existsSync(filename)) { const fileStat = fs.statSync(filename); if (fileStat.isFile()) { try { const stream = fs.createReadStream(filename); return stream; } catch (err) { throw err; } } else { throw new Error(`Could not find file "${filename}"`); } } else { throw new Error(`File "${filename}" does not exist`); } } }
import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * The AssetNamingStrategy determines how file names are generated based on the uploaded source file name, * as well as how to handle naming conflicts. * * :::info * * This is configured via the `assetOptions.assetNamingStrategy` property of * your VendureConfig. * * ::: * * @docsCategory assets */ export interface AssetNamingStrategy extends InjectableStrategy { /** * @description * Given the original file name of the uploaded file, generate a file name to * be stored on the server. Operations like normalization and time-stamping can * be performed in this method. * * The output will be checked for a naming conflict with an existing file. If a conflict * exists, this method will be invoked again with the second argument passed in and a new, unique * file name should then be generated. This process will repeat until a unique file name has * been returned. */ generateSourceFileName(ctx: RequestContext, originalFileName: string, conflictFileName?: string): string; /** * @description * Given the source file name generated in the `generateSourceFileName` method, this method * should generate the file name of the preview image. * * The same mechanism of checking for conflicts is used as described above. */ generatePreviewFileName(ctx: RequestContext, sourceFileName: string, conflictFileName?: string): string; }
import { describe, expect, it } from 'vitest'; import { RequestContext } from '../../api/common/request-context'; import { DefaultAssetNamingStrategy } from './default-asset-naming-strategy'; describe('DefaultAssetNamingStrategy', () => { const ctx = RequestContext.empty(); describe('generateSourceFileName()', () => { it('normalizes file names', () => { const strategy = new DefaultAssetNamingStrategy(); expect(strategy.generateSourceFileName(ctx, 'foo.jpg')).toBe('foo.jpg'); expect(strategy.generateSourceFileName(ctx, 'curaçao.jpg')).toBe('curacao.jpg'); expect(strategy.generateSourceFileName(ctx, 'dấu hỏi.jpg')).toBe('dau-hoi.jpg'); }); it('increments conflicting file names', () => { const strategy = new DefaultAssetNamingStrategy(); expect(strategy.generateSourceFileName(ctx, 'foo.jpg', 'foo.jpg')).toBe('foo__02.jpg'); expect(strategy.generateSourceFileName(ctx, 'foo.jpg', 'foo__02.jpg')).toBe('foo__03.jpg'); expect(strategy.generateSourceFileName(ctx, 'foo.jpg', 'foo__09.jpg')).toBe('foo__10.jpg'); expect(strategy.generateSourceFileName(ctx, 'foo.jpg', 'foo__99.jpg')).toBe('foo__100.jpg'); expect(strategy.generateSourceFileName(ctx, 'foo.jpg', 'foo__999.jpg')).toBe('foo__1000.jpg'); }); it('increments conflicting file names with no extension', () => { const strategy = new DefaultAssetNamingStrategy(); expect(strategy.generateSourceFileName(ctx, 'ext45000000000505', 'ext45000000000505')).toBe( 'ext45000000000505__02', ); expect(strategy.generateSourceFileName(ctx, 'ext45000000000505', 'ext45000000000505__02')).toBe( 'ext45000000000505__03', ); expect(strategy.generateSourceFileName(ctx, 'ext45000000000505', 'ext45000000000505__09')).toBe( 'ext45000000000505__10', ); }); }); describe('generatePreviewFileName()', () => { it('adds the preview suffix', () => { const strategy = new DefaultAssetNamingStrategy(); expect(strategy.generatePreviewFileName(ctx, 'foo.jpg')).toBe('foo__preview.jpg'); }); it('preserves the extension of supported image files', () => { const strategy = new DefaultAssetNamingStrategy(); expect(strategy.generatePreviewFileName(ctx, 'foo.jpg')).toBe('foo__preview.jpg'); expect(strategy.generatePreviewFileName(ctx, 'foo.jpeg')).toBe('foo__preview.jpeg'); expect(strategy.generatePreviewFileName(ctx, 'foo.png')).toBe('foo__preview.png'); expect(strategy.generatePreviewFileName(ctx, 'foo.webp')).toBe('foo__preview.webp'); expect(strategy.generatePreviewFileName(ctx, 'foo.tiff')).toBe('foo__preview.tiff'); expect(strategy.generatePreviewFileName(ctx, 'foo.gif')).toBe('foo__preview.gif'); expect(strategy.generatePreviewFileName(ctx, 'foo.avif')).toBe('foo__preview.avif'); }); it('adds a png extension for unsupported images and other files', () => { const strategy = new DefaultAssetNamingStrategy(); expect(strategy.generatePreviewFileName(ctx, 'foo.svg')).toBe('foo__preview.svg.png'); expect(strategy.generatePreviewFileName(ctx, 'foo.pdf')).toBe('foo__preview.pdf.png'); }); }); });
import { normalizeString } from '@vendure/common/lib/normalize-string'; import path from 'path'; import { RequestContext } from '../../api/common/request-context'; import { AssetNamingStrategy } from './asset-naming-strategy'; /** * @description * The default strategy normalizes the file names to remove unwanted characters and * in the case of conflicts, increments a counter suffix. * * @docsCategory assets */ export class DefaultAssetNamingStrategy implements AssetNamingStrategy { private readonly numberingRe = /__(\d+)(\.[^.]+)?$/; generateSourceFileName(ctx: RequestContext, originalFileName: string, conflictFileName?: string): string { const normalized = normalizeString(originalFileName, '-'); if (!conflictFileName) { return normalized; } else { return this.incrementOrdinalSuffix(normalized, conflictFileName); } } generatePreviewFileName(ctx: RequestContext, sourceFileName: string, conflictFileName?: string): string { const previewSuffix = '__preview'; const previewFileName = this.isSupportedImageFormat(sourceFileName) ? this.addSuffix(sourceFileName, previewSuffix) : this.addSuffix(sourceFileName, previewSuffix) + '.png'; if (!conflictFileName) { return previewFileName; } else { return this.incrementOrdinalSuffix(previewFileName, conflictFileName); } } /** * A "supported format" means that the Sharp library can transform it and output the same * file type. Unsupported images and other non-image files will be converted to png. * * See http://sharp.pixelplumbing.com/en/stable/api-output/#tobuffer */ private isSupportedImageFormat(fileName: string): boolean { const imageExtensions = ['.jpg', '.jpeg', '.png', '.webp', '.tiff', '.avif', '.gif']; const ext = path.extname(fileName); return imageExtensions.includes(ext); } private incrementOrdinalSuffix(baseFileName: string, conflictFileName: string): string { const matches = conflictFileName.match(this.numberingRe); const ord = Number(matches && matches[1]) || 1; return this.addOrdinalSuffix(baseFileName, ord + 1); } private addOrdinalSuffix(fileName: string, order: number): string { const paddedOrder = order.toString(10).padStart(2, '0'); return this.addSuffix(fileName, `__${paddedOrder}`); } private addSuffix(fileName: string, suffix: string): string { const ext = path.extname(fileName); const baseName = path.basename(fileName, ext); return `${baseName}${suffix}${ext}`; } }
import { Stream } from 'stream'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * The AssetPreviewStrategy determines how preview images for assets are created. For image * assets, this would usually typically involve resizing to sensible dimensions. Other file types * could be previewed in a variety of ways, e.g.: * * - waveform images generated for audio files * - preview images generated for pdf documents * - watermarks added to preview images * * :::info * * This is configured via the `assetOptions.assetPreviewStrategy` property of * your VendureConfig. * * ::: * * @docsCategory assets */ export interface AssetPreviewStrategy extends InjectableStrategy { generatePreviewImage(ctx: RequestContext, mimeType: string, data: Buffer): Promise<Buffer>; }
import { RequestContext } from '../../api/common/request-context'; import { InternalServerError } from '../../common/error/errors'; import { AssetPreviewStrategy } from './asset-preview-strategy'; /** * A placeholder strategy which will simply throw an error when used. */ export class NoAssetPreviewStrategy implements AssetPreviewStrategy { generatePreviewImage(ctx: RequestContext, mimeType: string, data: Buffer): Promise<Buffer> { throw new InternalServerError('error.no-asset-preview-strategy-configured'); } }
import { Request } from 'express'; import { Stream } from 'stream'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * The AssetPersistenceStrategy determines how Asset files are physically stored * and retrieved. * * :::info * * This is configured via the `assetOptions.assetStorageStrategy` property of * your VendureConfig. * * ::: * * @docsCategory assets */ export interface AssetStorageStrategy extends InjectableStrategy { /** * @description * Writes a buffer to the store and returns a unique identifier for that * file such as a file path or a URL. */ writeFileFromBuffer(fileName: string, data: Buffer): Promise<string>; /** * @description * Writes a readable stream to the store and returns a unique identifier for that * file such as a file path or a URL. */ writeFileFromStream(fileName: string, data: Stream): Promise<string>; /** * @description * Reads a file based on an identifier which was generated by the writeFile * method, and returns the as a Buffer. */ readFileToBuffer(identifier: string): Promise<Buffer>; /** * @description * Reads a file based on an identifier which was generated by the writeFile * method, and returns the file as a Stream. */ readFileToStream(identifier: string): Promise<Stream>; /** * @description * Deletes a file from the storage. */ deleteFile(identifier: string): Promise<void>; /** * @description * Check whether a file with the given name already exists. Used to avoid * naming conflicts before saving the file. */ fileExists(fileName: string): Promise<boolean>; /** * @description * Convert an identifier as generated by the writeFile... methods into an absolute * url (if it is not already in that form). If no conversion step is needed * (i.e. the identifier is already an absolute url) then this method * should not be implemented. */ toAbsoluteUrl?(request: Request, identifier: string): string; }
import { Request } from 'express'; import { Stream } from 'stream'; import { InternalServerError } from '../../common/error/errors'; import { AssetStorageStrategy } from './asset-storage-strategy'; const errorMessage = 'error.no-asset-storage-strategy-configured'; /** * A placeholder strategy which will simply throw an error when used. */ export class NoAssetStorageStrategy implements AssetStorageStrategy { writeFileFromStream(fileName: string, data: Stream): Promise<string> { throw new InternalServerError(errorMessage); } writeFileFromBuffer(fileName: string, data: Buffer): Promise<string> { throw new InternalServerError(errorMessage); } readFileToBuffer(identifier: string): Promise<Buffer> { throw new InternalServerError(errorMessage); } readFileToStream(identifier: string): Promise<Stream> { throw new InternalServerError(errorMessage); } deleteFile(identifier: string): Promise<void> { throw new InternalServerError(errorMessage); } toAbsoluteUrl(request: Request, identifier: string): string { throw new InternalServerError(errorMessage); } fileExists(fileName: string): Promise<boolean> { throw new InternalServerError(errorMessage); } }
import { DocumentNode } from 'graphql'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { User } from '../../entity/user/user.entity'; /** * @description * An AuthenticationStrategy defines how a User (which can be a Customer in the Shop API or * and Administrator in the Admin API) may be authenticated. * * Real-world examples can be found in the [Authentication guide](/guides/core-concepts/auth/). * * :::info * * This is configured via the `authOptions.shopAuthenticationStrategy` and `authOptions.adminAuthenticationStrategy` * properties of your VendureConfig. * * ::: * * @docsCategory auth */ export interface AuthenticationStrategy<Data = unknown> extends InjectableStrategy { /** * @description * The name of the strategy, for example `'facebook'`, `'google'`, `'keycloak'`. */ readonly name: string; /** * @description * Defines the type of the GraphQL Input object expected by the `authenticate` * mutation. The final input object will be a map, with the key being the name * of the strategy. The shape of the input object should match the generic `Data` * type argument. * * @example * For example, given the following: * * ```ts * defineInputType() { * return gql` * input MyAuthInput { * token: String! * } * `; * } * ``` * * assuming the strategy name is "my_auth", then the resulting call to `authenticate` * would look like: * * ```GraphQL * authenticate(input: { * my_auth: { * token: "foo" * } * }) { * # ... * } * ``` * * **Note:** if more than one graphql `input` type is being defined (as in a nested input type), then * the _first_ input will be assumed to be the top-level input. */ defineInputType(): DocumentNode; /** * @description * Used to authenticate a user with the authentication provider. This method * will implement the provider-specific authentication logic, and should resolve to either a * {@link User} object on success, or `false | string` on failure. * A `string` return could be used to describe what error happened, otherwise `false` to an unknown error. */ authenticate(ctx: RequestContext, data: Data): Promise<User | false | string>; /** * @description * Called when a user logs out, and may perform any required tasks * related to the user logging out with the external provider. */ onLogOut?(ctx: RequestContext, user: User): Promise<void>; }
import { PasswordHashingStrategy } from './password-hashing-strategy'; const SALT_ROUNDS = 12; /** * @description * A hashing strategy which uses bcrypt (https://en.wikipedia.org/wiki/Bcrypt) to hash plaintext password strings. * * @docsCategory auth * @since 1.3.0 */ export class BcryptPasswordHashingStrategy implements PasswordHashingStrategy { private bcrypt: any; hash(plaintext: string): Promise<string> { this.getBcrypt(); return this.bcrypt.hash(plaintext, SALT_ROUNDS); } check(plaintext: string, hash: string): Promise<boolean> { this.getBcrypt(); return this.bcrypt.compare(plaintext, hash); } private getBcrypt() { if (!this.bcrypt) { // The bcrypt lib is lazily loaded so that if we want to run Vendure // in an environment that does not support native Node modules // (such as an online sandbox like Stackblitz) the bcrypt dependency // does not get loaded when linking the source files on startup. this.bcrypt = require('bcrypt'); } } }
import { RequestContext } from '../../api/common/request-context'; import { PasswordValidationStrategy } from './password-validation-strategy'; /** * @description * The DefaultPasswordValidationStrategy allows you to specify a minimum length and/or * a regular expression to match passwords against. * * TODO: * By default, the `minLength` will be set to `4`. This is rather permissive and is only * this way in order to reduce the risk of backward-compatibility breaks. In the next major version * this default will be made more strict. * * @docsCategory auth * @since 1.5.0 */ export class DefaultPasswordValidationStrategy implements PasswordValidationStrategy { constructor(private options: { minLength?: number; regexp?: RegExp }) {} validate(ctx: RequestContext, password: string): boolean | string { const { minLength, regexp } = this.options; if (minLength != null) { if (password.length < minLength) { return false; } } if (regexp != null) { if (!regexp.test(password)) { return false; } } return true; } }
import { ID } from '@vendure/common/lib/shared-types'; import { DocumentNode } from 'graphql'; import gql from 'graphql-tag'; import { RequestContext } from '../../api/common/request-context'; import { Injector } from '../../common/injector'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { NativeAuthenticationMethod } from '../../entity/authentication-method/native-authentication-method.entity'; import { User } from '../../entity/user/user.entity'; import { AuthenticationStrategy } from './authentication-strategy'; export interface NativeAuthenticationData { username: string; password: string; } export const NATIVE_AUTH_STRATEGY_NAME = 'native'; /** * @description * This strategy implements a username/password credential-based authentication, with the credentials * being stored in the Vendure database. This is the default method of authentication, and it is advised * to keep it configured unless there is a specific reason not to. * * @docsCategory auth */ export class NativeAuthenticationStrategy implements AuthenticationStrategy<NativeAuthenticationData> { readonly name = NATIVE_AUTH_STRATEGY_NAME; private connection: TransactionalConnection; private passwordCipher: import('../../service/helpers/password-cipher/password-cipher').PasswordCipher; private userService: import('../../service/services/user.service').UserService; async init(injector: Injector) { this.connection = injector.get(TransactionalConnection); // These are lazily-loaded to avoid a circular dependency const { PasswordCipher } = await import('../../service/helpers/password-cipher/password-cipher.js'); const { UserService } = await import('../../service/services/user.service.js'); this.passwordCipher = injector.get(PasswordCipher); this.userService = injector.get(UserService); } defineInputType(): DocumentNode { return gql` input NativeAuthInput { username: String! password: String! } `; } async authenticate(ctx: RequestContext, data: NativeAuthenticationData): Promise<User | false> { const user = await this.userService.getUserByEmailAddress(ctx, data.username); if (!user) { return false; } const passwordMatch = await this.verifyUserPassword(ctx, user.id, data.password); if (!passwordMatch) { return false; } return user; } /** * Verify the provided password against the one we have for the given user. */ async verifyUserPassword(ctx: RequestContext, userId: ID, password: string): Promise<boolean> { const user = await this.connection.getRepository(ctx, User).findOne({ where: { id: userId }, relations: ['authenticationMethods'], }); if (!user) { return false; } const nativeAuthMethod = user.getNativeAuthenticationMethod(false); if (!nativeAuthMethod) { return false; } const pw = ( await this.connection.getRepository(ctx, NativeAuthenticationMethod).findOne({ where: { id: nativeAuthMethod.id }, select: ['passwordHash'], }) )?.passwordHash ?? ''; const passwordMatches = await this.passwordCipher.check(password, pw); if (!passwordMatches) { return false; } return true; } }
import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * Defines how user passwords get hashed when using the {@link NativeAuthenticationStrategy}. * * :::info * * This is configured via the `authOptions.passwordHashingStrategy` property of * your VendureConfig. * * ::: * * @docsCategory auth * @since 1.3.0 */ export interface PasswordHashingStrategy extends InjectableStrategy { hash(plaintext: string): Promise<string>; check(plaintext: string, hash: string): Promise<boolean>; }
import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * Defines validation to apply to new password (when creating an account or updating an existing account's * password when using the {@link NativeAuthenticationStrategy}. * * :::info * * This is configured via the `authOptions.passwordValidationStrategy` property of * your VendureConfig. * * ::: * * @docsCategory auth * @since 1.5.0 */ export interface PasswordValidationStrategy extends InjectableStrategy { /** * @description * Validates a password submitted during account registration or when a customer updates their password. * The method should resolve to `true` if the password is acceptable. If not, it should return `false` or * optionally a string which will be passed to the returned ErrorResult, which can e.g. advise on why * exactly the proposed password is not valid. * * @since 1.5.0 */ validate(ctx: RequestContext, password: string): Promise<boolean | string> | boolean | string; }
import { TaxCategory } from '../../entity/tax-category/tax-category.entity'; import { TaxRate } from '../../entity/tax-rate/tax-rate.entity'; import { Zone } from '../../entity/zone/zone.entity';
import { ConfigArg } from '@vendure/common/lib/generated-types'; import { SelectQueryBuilder } from 'typeorm'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; export type ApplyCollectionFilterFn<T extends ConfigArgs> = ( qb: SelectQueryBuilder<ProductVariant>, args: ConfigArgValues<T>, ) => SelectQueryBuilder<ProductVariant>; export interface CollectionFilterConfig<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { apply: ApplyCollectionFilterFn<T>; } /* eslint-disable max-len */ /** * @description * A CollectionFilter defines a rule which can be used to associate ProductVariants with a Collection. * The filtering is done by defining the `apply()` function, which receives a TypeORM * [`QueryBuilder`](https://typeorm.io/#/select-query-builder) object to which clauses may be added. * * Creating a CollectionFilter is considered an advanced Vendure topic. For more insight into how * they work, study the [default collection filters](https://github.com/vendure-ecommerce/vendure/blob/master/packages/core/src/config/catalog/default-collection-filters.ts) * * Here's a simple example of a custom CollectionFilter: * * @example * ```ts * import { CollectionFilter, LanguageCode } from '\@vendure/core'; * * export const skuCollectionFilter = new CollectionFilter({ * args: { * // The `args` object defines the user-configurable arguments * // which will get passed to the filter's `apply()` function. * sku: { * type: 'string', * label: [{ languageCode: LanguageCode.en, value: 'SKU' }], * description: [ * { * languageCode: LanguageCode.en, * value: 'Matches any product variants with SKUs containing this value', * }, * ], * }, * }, * code: 'variant-sku-filter', * description: [{ languageCode: LanguageCode.en, value: 'Filter by matching SKU' }], * * // This is the function that defines the logic of the filter. * apply: (qb, args) => { * const LIKE = qb.connection.options.type === 'postgres' ? 'ILIKE' : 'LIKE'; * return qb.andWhere(`productVariant.sku ${LIKE} :sku`, { sku: `%${args.sku}%` }); * }, * }); * ``` * * @docsCategory configuration */ export class CollectionFilter<T extends ConfigArgs = ConfigArgs> extends ConfigurableOperationDef<T> { /* eslint-enable max-len */ private readonly applyFn: ApplyCollectionFilterFn<T>; constructor(config: CollectionFilterConfig<T>) { super(config); this.applyFn = config.apply; } apply(qb: SelectQueryBuilder<ProductVariant>, args: ConfigArg[]): SelectQueryBuilder<ProductVariant> { return this.applyFn(qb, this.argsArrayToHash(args)); } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { ConfigArgDef } from '../../common/configurable-operation'; import { UserInputError } from '../../common/error/errors'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { CollectionFilter } from './collection-filter'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { customAlphabet } = require('nanoid'); /** * @description * Used to created unique key names for DB query parameters, to avoid conflicts if the * same filter is applied multiple times. */ export function randomSuffix(prefix: string) { const nanoid = customAlphabet('123456789abcdefghijklmnopqrstuvwxyz', 6); return `${prefix}_${nanoid() as string}`; } /** * @description * Add this to your CollectionFilter `args` object to display the standard UI component * for selecting the combination mode when working with multiple filters. */ export const combineWithAndArg: ConfigArgDef<'boolean'> = { type: 'boolean', label: [{ languageCode: LanguageCode.en, value: 'Combination mode' }], description: [ { languageCode: LanguageCode.en, // eslint-disable-next-line max-len value: 'If this filter is being combined with other filters, do all conditions need to be satisfied (AND), or just one or the other (OR)?', }, ], defaultValue: true, ui: { component: 'combination-mode-form-input', }, }; /** * Filters for ProductVariants having the given facetValueIds (including parent Product) */ export const facetValueCollectionFilter = new CollectionFilter({ args: { facetValueIds: { type: 'ID', list: true, ui: { component: 'facet-value-form-input', }, label: [{ languageCode: LanguageCode.en, value: 'Facet values' }], }, containsAny: { type: 'boolean', label: [{ languageCode: LanguageCode.en, value: 'Contains any' }], description: [ { languageCode: LanguageCode.en, value: 'If checked, product variants must have at least one of the selected facet values. ' + 'If not checked, the variant must have all selected values.', }, ], }, combineWithAnd: combineWithAndArg, }, code: 'facet-value-filter', description: [{ languageCode: LanguageCode.en, value: 'Filter by facet values' }], apply: (qb, args) => { const ids = args.facetValueIds; if (ids.length) { // uuid IDs can include `-` chars, which we cannot use in a TypeORM key name. const safeIdsConcat = ids.join('_').replace(/-/g, '_'); const idsName = `ids_${safeIdsConcat}`; const countName = `count_${safeIdsConcat}`; const productFacetValues = qb.connection .createQueryBuilder(ProductVariant, 'product_variant') .select('product_variant.id', 'variant_id') .addSelect('facet_value.id', 'facet_value_id') .leftJoin('product_variant.facetValues', 'facet_value') .where(`facet_value.id IN (:...${idsName})`); const variantFacetValues = qb.connection .createQueryBuilder(ProductVariant, 'product_variant') .select('product_variant.id', 'variant_id') .addSelect('facet_value.id', 'facet_value_id') .leftJoin('product_variant.product', 'product') .leftJoin('product.facetValues', 'facet_value') .where(`facet_value.id IN (:...${idsName})`); const union = qb.connection .createQueryBuilder() .select('union_table.variant_id') .from( `(${productFacetValues.getQuery()} UNION ${variantFacetValues.getQuery()})`, 'union_table', ) .groupBy('variant_id') .having(`COUNT(*) >= :${countName}`); const variantIds = qb.connection .createQueryBuilder() .select('variant_ids_table.variant_id') .from(`(${union.getQuery()})`, 'variant_ids_table'); const clause = `productVariant.id IN (${variantIds.getQuery()})`; const params = { [idsName]: ids, [countName]: args.containsAny ? 1 : ids.length, }; if (args.combineWithAnd !== false) { qb.andWhere(clause).setParameters(params); } else { qb.orWhere(clause).setParameters(params); } } else { // If no facetValueIds are specified, no ProductVariants will be matched. if (args.combineWithAnd !== false) { qb.andWhere('1 = 0'); } } return qb; }, }); export const variantNameCollectionFilter = new CollectionFilter({ args: { operator: { type: 'string', ui: { component: 'select-form-input', options: [ { value: 'startsWith' }, { value: 'endsWith' }, { value: 'contains' }, { value: 'doesNotContain' }, ], }, }, term: { type: 'string' }, combineWithAnd: combineWithAndArg, }, code: 'variant-name-filter', description: [{ languageCode: LanguageCode.en, value: 'Filter by product variant name' }], apply: (qb, args) => { let translationAlias = 'variant_name_filter_translation'; const termName = randomSuffix('term'); const translationsJoin = qb.expressionMap.joinAttributes.find( ja => ja.entityOrProperty === 'productVariant.translations', ); if (!translationsJoin) { qb.leftJoin('productVariant.translations', translationAlias); } else { translationAlias = translationsJoin.alias.name; } const LIKE = qb.connection.options.type === 'postgres' ? 'ILIKE' : 'LIKE'; let clause: string; let params: Record<string, string>; switch (args.operator) { case 'contains': clause = `${translationAlias}.name ${LIKE} :${termName}`; params = { [termName]: `%${args.term}%`, }; break; case 'doesNotContain': clause = `${translationAlias}.name NOT ${LIKE} :${termName}`; params = { [termName]: `%${args.term}%`, }; break; case 'startsWith': clause = `${translationAlias}.name ${LIKE} :${termName}`; params = { [termName]: `${args.term}%`, }; break; case 'endsWith': clause = `${translationAlias}.name ${LIKE} :${termName}`; params = { [termName]: `%${args.term}`, }; break; default: throw new UserInputError(`${args.operator} is not a valid operator`); } if (args.combineWithAnd === false) { return qb.orWhere(clause, params); } else { return qb.andWhere(clause, params); } }, }); export const variantIdCollectionFilter = new CollectionFilter({ args: { variantIds: { type: 'ID', list: true, label: [{ languageCode: LanguageCode.en, value: 'Product variants' }], ui: { component: 'product-multi-form-input', selectionMode: 'variant', }, }, combineWithAnd: combineWithAndArg, }, code: 'variant-id-filter', description: [{ languageCode: LanguageCode.en, value: 'Manually select product variants' }], apply: (qb, args) => { if (args.variantIds.length === 0) { return qb; } const variantIdsKey = randomSuffix('variantIds'); const clause = `productVariant.id IN (:...${variantIdsKey})`; const params = { [variantIdsKey]: args.variantIds }; if (args.combineWithAnd === false) { return qb.orWhere(clause, params); } else { return qb.andWhere(clause, params); } }, }); export const productIdCollectionFilter = new CollectionFilter({ args: { productIds: { type: 'ID', list: true, label: [{ languageCode: LanguageCode.en, value: 'Products' }], ui: { component: 'product-multi-form-input', selectionMode: 'product', }, }, combineWithAnd: combineWithAndArg, }, code: 'product-id-filter', description: [{ languageCode: LanguageCode.en, value: 'Manually select products' }], apply: (qb, args) => { if (args.productIds.length === 0) { return qb; } const productIdsKey = randomSuffix('productIds'); const clause = `productVariant.productId IN (:...${productIdsKey})`; const params = { [productIdsKey]: args.productIds }; if (args.combineWithAnd === false) { return qb.orWhere(clause, params); } else { return qb.andWhere(clause, params); } }, }); export const defaultCollectionFilters = [ facetValueCollectionFilter, variantNameCollectionFilter, variantIdCollectionFilter, productIdCollectionFilter, ];
import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { roundMoney } from '../../common/round-money'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { createRequestContext, MockTaxRateService, taxCategoryReduced, taxCategoryStandard, taxRateDefaultReduced, taxRateDefaultStandard, zoneDefault, zoneOther, zoneWithNoTaxRate, } from '../../testing/order-test-utils'; import { ensureConfigLoaded } from '../config-helpers'; describe('DefaultProductVariantPriceCalculationStrategy', () => { let strategy: import('./default-product-variant-price-calculation-strategy').DefaultProductVariantPriceCalculationStrategy; const inputPrice = 6543; const productVariant = new ProductVariant({}); beforeAll(async () => { await ensureConfigLoaded(); }); beforeEach(async () => { // Dynamic import to avoid vitest circular dependency issue const { DefaultProductVariantPriceCalculationStrategy } = await import( './default-product-variant-price-calculation-strategy.js' ); strategy = new DefaultProductVariantPriceCalculationStrategy(); const mockInjector = { get: () => { return new MockTaxRateService(); }, } as any; strategy.init(mockInjector); }); describe('with prices which do not include tax', () => { it('standard tax, default zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryStandard, activeTaxZone: zoneDefault, ctx, productVariant, }); expect(result).toEqual({ price: inputPrice, priceIncludesTax: false, }); }); it('reduced tax, default zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryReduced, activeTaxZone: zoneDefault, ctx, productVariant, }); expect(result).toEqual({ price: inputPrice, priceIncludesTax: false, }); }); it('standard tax, other zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryStandard, activeTaxZone: zoneOther, ctx, productVariant, }); expect(result).toEqual({ price: inputPrice, priceIncludesTax: false, }); }); it('reduced tax, other zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryReduced, activeTaxZone: zoneOther, ctx, productVariant, }); expect(result).toEqual({ price: inputPrice, priceIncludesTax: false, }); }); it('standard tax, unconfigured zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryReduced, activeTaxZone: zoneWithNoTaxRate, ctx, productVariant, }); expect(result).toEqual({ price: inputPrice, priceIncludesTax: false, }); }); }); describe('with prices which include tax', () => { it('standard tax, default zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryStandard, activeTaxZone: zoneDefault, ctx, productVariant, }); expect(result).toEqual({ price: inputPrice, priceIncludesTax: true, }); }); it('reduced tax, default zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryReduced, activeTaxZone: zoneDefault, ctx, productVariant, }); expect(result).toEqual({ price: inputPrice, priceIncludesTax: true, }); }); it('standard tax, other zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryStandard, activeTaxZone: zoneOther, ctx, productVariant, }); expect(result).toEqual({ price: roundMoney(taxRateDefaultStandard.netPriceOf(inputPrice)), priceIncludesTax: false, }); }); it('reduced tax, other zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryReduced, activeTaxZone: zoneOther, ctx, productVariant, }); expect(result).toEqual({ price: roundMoney(taxRateDefaultReduced.netPriceOf(inputPrice)), priceIncludesTax: false, }); }); it('standard tax, unconfigured zone', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const result = await strategy.calculate({ inputPrice, taxCategory: taxCategoryStandard, activeTaxZone: zoneWithNoTaxRate, ctx, productVariant, }); expect(result).toEqual({ price: roundMoney(taxRateDefaultStandard.netPriceOf(inputPrice)), priceIncludesTax: false, }); }); }); });
import { Injector } from '../../common/injector'; import { roundMoney } from '../../common/round-money'; import { PriceCalculationResult } from '../../common/types/common-types'; import { idsAreEqual } from '../../common/utils'; import { TaxRateService } from '../../service/services/tax-rate.service'; import { ProductVariantPriceCalculationArgs, ProductVariantPriceCalculationStrategy, } from './product-variant-price-calculation-strategy'; /** * @description * A default ProductVariant price calculation function. * * @docsCategory products & stock */ export class DefaultProductVariantPriceCalculationStrategy implements ProductVariantPriceCalculationStrategy { private taxRateService: TaxRateService; init(injector: Injector) { this.taxRateService = injector.get(TaxRateService); } async calculate(args: ProductVariantPriceCalculationArgs): Promise<PriceCalculationResult> { const { inputPrice, activeTaxZone, ctx, taxCategory } = args; let price = inputPrice; let priceIncludesTax = false; if (ctx.channel.pricesIncludeTax) { const isDefaultZone = idsAreEqual(activeTaxZone.id, ctx.channel.defaultTaxZone.id); if (isDefaultZone) { priceIncludesTax = true; } else { const taxRateForDefaultZone = await this.taxRateService.getApplicableTaxRate( ctx, ctx.channel.defaultTaxZone, taxCategory, ); price = roundMoney(taxRateForDefaultZone.netPriceOf(inputPrice)); } } return { price, priceIncludesTax, }; } }
import { RequestContext } from '../../api/common/request-context'; import { idsAreEqual } from '../../common/utils'; import { ProductVariantPrice } from '../../entity/product-variant/product-variant-price.entity'; import { ProductVariantPriceSelectionStrategy } from './product-variant-price-selection-strategy'; /** * @description * The default strategy for selecting the price for a ProductVariant in a given Channel. It * first filters all available prices to those which are in the current Channel, and then * selects the first price which matches the current currency. * * @docsCategory configuration * @docsPage ProductVariantPriceSelectionStrategy * @since 2.0.0 */ export class DefaultProductVariantPriceSelectionStrategy implements ProductVariantPriceSelectionStrategy { selectPrice(ctx: RequestContext, prices: ProductVariantPrice[]) { const pricesInChannel = prices.filter(p => idsAreEqual(p.channelId, ctx.channelId)); const priceInCurrency = pricesInChannel.find(p => p.currencyCode === ctx.currencyCode); return priceInCurrency; } }
import { RequestContext } from '../../api/common/request-context'; import { ProductVariantPrice } from '../../entity/product-variant/product-variant-price.entity'; import { ProductVariantPriceUpdateStrategy } from './product-variant-price-update-strategy'; /** * @description * The options available to the {@link DefaultProductVariantPriceUpdateStrategy}. * * @docsCategory configuration * @docsPage ProductVariantPriceUpdateStrategy * @since 2.2.0 */ export interface DefaultProductVariantPriceUpdateStrategyOptions { /** * @description * When `true`, any price changes to a ProductVariant in one Channel will update any other * prices of the same currencyCode in other Channels. Note that if there are different * tax settings across the channels, these will not be taken into account. To handle this * case, a custom strategy should be implemented. */ syncPricesAcrossChannels: boolean; } /** * @description * The default {@link ProductVariantPriceUpdateStrategy} which by default will not update any other * prices when a price is created, updated or deleted. * * If the `syncPricesAcrossChannels` option is set to `true`, then when a price is updated in one Channel, * the price of the same currencyCode in other Channels will be updated to match. Note that if there are different * tax settings across the channels, these will not be taken into account. To handle this * case, a custom strategy should be implemented. * * @example * ```ts * import { DefaultProductVariantPriceUpdateStrategy, VendureConfig } from '\@vendure/core'; * * export const config: VendureConfig = { * // ... * catalogOptions: { * // highlight-start * productVariantPriceUpdateStrategy: new DefaultProductVariantPriceUpdateStrategy({ * syncPricesAcrossChannels: true, * }), * // highlight-end * }, * // ... * }; * ``` * * @docsCategory configuration * @docsPage ProductVariantPriceUpdateStrategy * @since 2.2.0 */ export class DefaultProductVariantPriceUpdateStrategy implements ProductVariantPriceUpdateStrategy { constructor(private options: DefaultProductVariantPriceUpdateStrategyOptions) {} onPriceCreated(ctx: RequestContext, price: ProductVariantPrice) { return []; } onPriceUpdated(ctx: RequestContext, updatedPrice: ProductVariantPrice, prices: ProductVariantPrice[]) { if (this.options.syncPricesAcrossChannels) { return prices .filter(p => p.currencyCode === updatedPrice.currencyCode) .map(p => ({ id: p.id, price: updatedPrice.price, })); } else { return []; } } onPriceDeleted(ctx: RequestContext, deletedPrice: ProductVariantPrice, prices: ProductVariantPrice[]) { return []; } }
import { RequestContext } from '../../api/common/request-context'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { StockDisplayStrategy } from './stock-display-strategy'; /** * @description * Displays the `ProductVariant.stockLevel` as either `'IN_STOCK'`, `'OUT_OF_STOCK'` or `'LOW_STOCK'`. * Low stock is defined as a saleable stock level less than or equal to the `lowStockLevel` as passed in * to the constructor (defaults to `2`). * * @docsCategory products & stock */ export class DefaultStockDisplayStrategy implements StockDisplayStrategy { constructor(private lowStockLevel: number = 2) {} getStockLevel(ctx: RequestContext, productVariant: ProductVariant, saleableStockLevel: number): string { return saleableStockLevel < 1 ? 'OUT_OF_STOCK' : saleableStockLevel <= this.lowStockLevel ? 'LOW_STOCK' : 'IN_STOCK'; } }
import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { Injector } from '../../common/injector'; import { idsAreEqual } from '../../common/utils'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { StockLevel } from '../../entity/stock-level/stock-level.entity'; import { StockLocation } from '../../entity/stock-location/stock-location.entity'; import { Allocation } from '../../entity/stock-movement/allocation.entity'; import { AvailableStock, LocationWithQuantity, StockLocationStrategy } from './stock-location-strategy'; /** * @description * The DefaultStockLocationStrategy is the default implementation of the {@link StockLocationStrategy}. * It assumes only a single StockLocation and that all stock is allocated from that location. * * @docsCategory products & stock * @since 2.0.0 */ export class DefaultStockLocationStrategy implements StockLocationStrategy { protected connection: TransactionalConnection; init(injector: Injector) { this.connection = injector.get(TransactionalConnection); } getAvailableStock(ctx: RequestContext, productVariantId: ID, stockLevels: StockLevel[]): AvailableStock { let stockOnHand = 0; let stockAllocated = 0; for (const stockLevel of stockLevels) { stockOnHand += stockLevel.stockOnHand; stockAllocated += stockLevel.stockAllocated; } return { stockOnHand, stockAllocated }; } forAllocation( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ): LocationWithQuantity[] | Promise<LocationWithQuantity[]> { return [{ location: stockLocations[0], quantity }]; } async forCancellation( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ): Promise<LocationWithQuantity[]> { return this.getLocationsBasedOnAllocations(ctx, stockLocations, orderLine, quantity); } async forRelease( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ): Promise<LocationWithQuantity[]> { return this.getLocationsBasedOnAllocations(ctx, stockLocations, orderLine, quantity); } async forSale( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ): Promise<LocationWithQuantity[]> { return this.getLocationsBasedOnAllocations(ctx, stockLocations, orderLine, quantity); } private async getLocationsBasedOnAllocations( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ) { const allocations = await this.connection.getRepository(ctx, Allocation).find({ where: { orderLine: { id: orderLine.id }, }, }); let unallocated = quantity; const quantityByLocationId = new Map<ID, number>(); for (const allocation of allocations) { if (unallocated <= 0) { break; } const qtyAtLocation = quantityByLocationId.get(allocation.stockLocationId); const qtyToAdd = Math.min(allocation.quantity, unallocated); if (qtyAtLocation != null) { quantityByLocationId.set(allocation.stockLocationId, qtyAtLocation + qtyToAdd); } else { quantityByLocationId.set(allocation.stockLocationId, qtyToAdd); } unallocated -= qtyToAdd; } return [...quantityByLocationId.entries()].map(([locationId, qty]) => ({ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion location: stockLocations.find(l => idsAreEqual(l.id, locationId))!, quantity: qty, })); } }
import { RequestContext } from '../../api/common/request-context'; import { PriceCalculationResult } from '../../common/types/common-types'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { TaxCategory } from '../../entity/tax-category/tax-category.entity'; import { Zone } from '../../entity/zone/zone.entity'; /** * @description * Defines how ProductVariant are calculated based on the input price, tax zone and current request context. * * :::info * * This is configured via the `catalogOptions.productVariantPriceCalculationStrategy` property of * your VendureConfig. * * ::: * * @docsCategory products & stock * @docsPage ProductVariantPriceCalculationStrategy */ export interface ProductVariantPriceCalculationStrategy extends InjectableStrategy { calculate(args: ProductVariantPriceCalculationArgs): Promise<PriceCalculationResult>; } /** * @description * The arguments passed the `calculate` method of the configured {@link ProductVariantPriceCalculationStrategy}. * * The `productVariant` argument was added in v2.1.0. * * @docsCategory products & stock * @docsPage ProductVariantPriceCalculationStrategy */ export interface ProductVariantPriceCalculationArgs { inputPrice: number; productVariant: ProductVariant; taxCategory: TaxCategory; activeTaxZone: Zone; ctx: RequestContext; }
import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { ProductVariantPrice } from '../../entity/product-variant/product-variant-price.entity'; /** * @description * The strategy for selecting the price for a ProductVariant in a given Channel. * * :::info * * This is configured via the `catalogOptions.productVariantPriceSelectionStrategy` property of * your VendureConfig. * * ::: * * @docsCategory configuration * @docsPage ProductVariantPriceSelectionStrategy * @docsWeight 0 * @since 2.0.0 */ export interface ProductVariantPriceSelectionStrategy extends InjectableStrategy { selectPrice( ctx: RequestContext, prices: ProductVariantPrice[], ): ProductVariantPrice | undefined | Promise<ProductVariantPrice | undefined>; }
import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { ProductVariantPrice } from '../../entity/product-variant/product-variant-price.entity'; /** * @description * The return value of the `onPriceCreated`, `onPriceUpdated` and `onPriceDeleted` methods * of the {@link ProductVariantPriceUpdateStrategy}. * * @docsPage ProductVariantPriceUpdateStrategy * @since 2.2.0 */ export interface UpdatedProductVariantPrice { /** * @description * The ID of the ProductVariantPrice to update. */ id: ID; /** * @description * The new price to set. */ price: number; } /** * @description * This strategy determines how updates to a ProductVariantPrice is handled in regard to * any other prices which may be associated with the same ProductVariant. * * For instance, in a multichannel setup, if a price is updated for a ProductVariant in one * Channel, this strategy can be used to update the prices in other Channels. * * Using custom logic, this can be made more sophisticated - for example, you could have a * one-way sync that only updates prices in child channels when the price in the default * channel is updated. You could also have a conditional sync which is dependent on the * permissions of the current administrator, or based on custom field flags on the ProductVariant * or Channel. * * Another use-case might be to update the prices of a ProductVariant in other currencies * when a price is updated in one currency, based on the current exchange rate. * * * :::info * * This is configured via the `catalogOptions.productVariantPriceUpdateStrategy` property of * your VendureConfig. * * ::: * * @docsCategory configuration * @docsPage ProductVariantPriceUpdateStrategy * @docsWeight 0 * @since 2.2.0 */ export interface ProductVariantPriceUpdateStrategy extends InjectableStrategy { /** * @description * This method is called when a ProductVariantPrice is created. It receives the created * ProductVariantPrice and the array of all prices associated with the ProductVariant. * * It should return an array of UpdatedProductVariantPrice objects which will be used to update * the prices of the specific ProductVariantPrices. */ onPriceCreated( ctx: RequestContext, createdPrice: ProductVariantPrice, prices: ProductVariantPrice[], ): UpdatedProductVariantPrice[] | Promise<UpdatedProductVariantPrice[]>; /** * @description * This method is called when a ProductVariantPrice is updated. It receives the updated * ProductVariantPrice and the array of all prices associated with the ProductVariant. * * It should return an array of UpdatedProductVariantPrice objects which will be used to update * the prices of the specific ProductVariantPrices. */ onPriceUpdated( ctx: RequestContext, updatedPrice: ProductVariantPrice, prices: ProductVariantPrice[], ): UpdatedProductVariantPrice[] | Promise<UpdatedProductVariantPrice[]>; /** * @description * This method is called when a ProductVariantPrice is deleted. It receives the deleted * ProductVariantPrice and the array of all prices associated with the ProductVariant. * * It should return an array of UpdatedProductVariantPrice objects which will be used to update * the prices of the specific ProductVariantPrices. */ onPriceDeleted( ctx: RequestContext, deletedPrice: ProductVariantPrice, prices: ProductVariantPrice[], ): UpdatedProductVariantPrice[] | Promise<UpdatedProductVariantPrice[]>; }
import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; /** * @description * Defines how the `ProductVariant.stockLevel` value is obtained. It is usually not desirable * to directly expose stock levels over a public API, as this could be considered a leak of * sensitive information. However, the storefront will usually want to display _some_ indication * of whether a given ProductVariant is in stock. * * :::info * * This is configured via the `catalogOptions.stockDisplayStrategy` property of * your VendureConfig. * * ::: * * @docsCategory products & stock */ export interface StockDisplayStrategy extends InjectableStrategy { /** * @description * Returns a string representing the stock level, which will be used directly * in the GraphQL `ProductVariant.stockLevel` field. */ getStockLevel( ctx: RequestContext, productVariant: ProductVariant, saleableStockLevel: number, ): string | Promise<string>; }
import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { StockLevel } from '../../entity/stock-level/stock-level.entity'; import { StockLocation } from '../../entity/stock-location/stock-location.entity'; /** * @description * The overall available stock for a ProductVariant as determined by the logic of the * {@link StockLocationStrategy}'s `getAvailableStock` method. * * @docsCategory products & stock * @since 2.0.0 * @docsPage StockLocationStrategy */ export interface AvailableStock { stockOnHand: number; stockAllocated: number; } /** * @description * Returned by the `StockLocationStrategy` methods to indicate how much stock from each * location should be used in the allocation/sale/release/cancellation of an OrderLine. * * @docsCategory products & stock * @since 2.0.0 * @docsPage StockLocationStrategy */ export interface LocationWithQuantity { location: StockLocation; quantity: number; } /** * @description * The StockLocationStrategy is responsible for determining which {@link StockLocation}s * should be used to fulfill an {@link OrderLine} and how much stock should be allocated * from each location. It is also used to determine the available stock for a given * {@link ProductVariant}. * * :::info * * This is configured via the `catalogOptions.stockLocationStrategy` property of * your VendureConfig. * * ::: * * @docsCategory products & stock * @docsWeight 0 * @since 2.0.0 */ export interface StockLocationStrategy extends InjectableStrategy { /** * @description * Returns the available stock for the given ProductVariant, taking into account * the stock levels at each StockLocation. */ getAvailableStock( ctx: RequestContext, productVariantId: ID, stockLevels: StockLevel[], ): AvailableStock | Promise<AvailableStock>; /** * @description * Determines which StockLocations should be used to when allocating stock when * and Order is placed. */ forAllocation( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ): LocationWithQuantity[] | Promise<LocationWithQuantity[]>; /** * @description * Determines which StockLocations should be used to when releasing allocated * stock when an OrderLine is cancelled before being fulfilled. */ forRelease( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ): LocationWithQuantity[] | Promise<LocationWithQuantity[]>; /** * @description * Determines which StockLocations should be used to when creating a Sale * and reducing the stockOnHand upon fulfillment. */ forSale( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ): LocationWithQuantity[] | Promise<LocationWithQuantity[]>; /** * @description * Determines which StockLocations should be used to when creating a Cancellation * of an OrderLine which has already been fulfilled. */ forCancellation( ctx: RequestContext, stockLocations: StockLocation[], orderLine: OrderLine, quantity: number, ): LocationWithQuantity[] | Promise<LocationWithQuantity[]>; }
import { BooleanCustomFieldConfig as GraphQLBooleanCustomFieldConfig, CustomField, DateTimeCustomFieldConfig as GraphQLDateTimeCustomFieldConfig, FloatCustomFieldConfig as GraphQLFloatCustomFieldConfig, IntCustomFieldConfig as GraphQLIntCustomFieldConfig, LocaleStringCustomFieldConfig as GraphQLLocaleStringCustomFieldConfig, LocaleTextCustomFieldConfig as GraphQLLocaleTextCustomFieldConfig, LocalizedString, Permission, RelationCustomFieldConfig as GraphQLRelationCustomFieldConfig, StringCustomFieldConfig as GraphQLStringCustomFieldConfig, TextCustomFieldConfig as GraphQLTextCustomFieldConfig, } from '@vendure/common/lib/generated-types'; import { CustomFieldsObject, CustomFieldType, DefaultFormComponentId, Type, UiComponentConfig, } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { Injector } from '../../common/injector'; import { VendureEntity } from '../../entity/base/base.entity'; // prettier-ignore export type DefaultValueType<T extends CustomFieldType> = T extends 'string' | 'localeString' | 'text' | 'localeText' ? string : T extends 'int' | 'float' ? number : T extends 'boolean' ? boolean : T extends 'datetime' ? Date : T extends 'relation' ? any : never; export type BaseTypedCustomFieldConfig<T extends CustomFieldType, C extends CustomField> = Omit< C, '__typename' | 'list' | 'requiresPermission' > & { type: T; /** * @description * Whether the custom field is available via the Shop API. * @default true */ public?: boolean; nullable?: boolean; unique?: boolean; /** * @description * The permission(s) required to read or write to this field. * If the user has at least one of these permissions, they will be * able to access the field. * * @since 2.2.0 */ requiresPermission?: Array<Permission | string> | Permission | string; ui?: UiComponentConfig<DefaultFormComponentId | string>; }; /** * @description * Configures a custom field on an entity in the {@link CustomFields} config object. * * @docsCategory custom-fields */ export type TypedCustomSingleFieldConfig< T extends CustomFieldType, C extends CustomField, > = BaseTypedCustomFieldConfig<T, C> & { list?: false; defaultValue?: DefaultValueType<T>; validate?: ( value: DefaultValueType<T>, injector: Injector, ctx: RequestContext, ) => string | LocalizedString[] | void | Promise<string | LocalizedString[] | void>; }; export type TypedCustomListFieldConfig< T extends CustomFieldType, C extends CustomField, > = BaseTypedCustomFieldConfig<T, C> & { list?: true; defaultValue?: Array<DefaultValueType<T>>; validate?: (value: Array<DefaultValueType<T>>) => string | LocalizedString[] | void; }; export type TypedCustomFieldConfig< T extends CustomFieldType, C extends CustomField, > = BaseTypedCustomFieldConfig<T, C> & (TypedCustomSingleFieldConfig<T, C> | TypedCustomListFieldConfig<T, C>); export type StringCustomFieldConfig = TypedCustomFieldConfig<'string', GraphQLStringCustomFieldConfig>; export type LocaleStringCustomFieldConfig = TypedCustomFieldConfig< 'localeString', GraphQLLocaleStringCustomFieldConfig >; export type TextCustomFieldConfig = TypedCustomFieldConfig<'text', GraphQLTextCustomFieldConfig>; export type LocaleTextCustomFieldConfig = TypedCustomFieldConfig< 'localeText', GraphQLLocaleTextCustomFieldConfig >; export type IntCustomFieldConfig = TypedCustomFieldConfig<'int', GraphQLIntCustomFieldConfig>; export type FloatCustomFieldConfig = TypedCustomFieldConfig<'float', GraphQLFloatCustomFieldConfig>; export type BooleanCustomFieldConfig = TypedCustomFieldConfig<'boolean', GraphQLBooleanCustomFieldConfig>; export type DateTimeCustomFieldConfig = TypedCustomFieldConfig<'datetime', GraphQLDateTimeCustomFieldConfig>; export type RelationCustomFieldConfig = TypedCustomFieldConfig< 'relation', Omit<GraphQLRelationCustomFieldConfig, 'entity' | 'scalarFields'> > & { entity: Type<VendureEntity>; graphQLType?: string; eager?: boolean; inverseSide?: string | ((object: any) => any); }; /** * @description * An object used to configure a custom field. * * @docsCategory custom-fields */ export type CustomFieldConfig = | StringCustomFieldConfig | LocaleStringCustomFieldConfig | TextCustomFieldConfig | LocaleTextCustomFieldConfig | IntCustomFieldConfig | FloatCustomFieldConfig | BooleanCustomFieldConfig | DateTimeCustomFieldConfig | RelationCustomFieldConfig; /** * @description * Most entities can have additional fields added to them by defining an array of {@link CustomFieldConfig} * objects on against the corresponding key. * * @example * ```ts * bootstrap({ * // ... * customFields: { * Product: [ * { name: 'infoUrl', type: 'string' }, * { name: 'downloadable', type: 'boolean', defaultValue: false }, * { name: 'shortName', type: 'localeString' }, * ], * User: [ * { name: 'socialLoginToken', type: 'string', public: false }, * ], * }, * }) * ``` * * @docsCategory custom-fields */ export type CustomFields = { Address?: CustomFieldConfig[]; Administrator?: CustomFieldConfig[]; Asset?: CustomFieldConfig[]; Channel?: CustomFieldConfig[]; Collection?: CustomFieldConfig[]; Customer?: CustomFieldConfig[]; CustomerGroup?: CustomFieldConfig[]; Facet?: CustomFieldConfig[]; FacetValue?: CustomFieldConfig[]; Fulfillment?: CustomFieldConfig[]; GlobalSettings?: CustomFieldConfig[]; Order?: CustomFieldConfig[]; OrderLine?: CustomFieldConfig[]; PaymentMethod?: CustomFieldConfig[]; Product?: CustomFieldConfig[]; ProductOption?: CustomFieldConfig[]; ProductOptionGroup?: CustomFieldConfig[]; ProductVariant?: CustomFieldConfig[]; ProductVariantPrice?: CustomFieldConfig[]; Promotion?: CustomFieldConfig[]; Region?: CustomFieldConfig[]; Seller?: CustomFieldConfig[]; ShippingMethod?: CustomFieldConfig[]; StockLocation?: CustomFieldConfig[]; TaxCategory?: CustomFieldConfig[]; TaxRate?: CustomFieldConfig[]; User?: CustomFieldConfig[]; Zone?: CustomFieldConfig[]; } & { [entity: string]: CustomFieldConfig[] }; /** * This interface should be implemented by any entity which can be extended * with custom fields. */ export interface HasCustomFields { customFields: CustomFieldsObject; }
import { MetadataArgsStorage } from 'typeorm/metadata-args/MetadataArgsStorage'; /** * @description * A function which allows TypeORM entity metadata to be manipulated prior to the DB schema being generated * during bootstrap. * * :::caution * Certain DB schema modifications will result in auto-generated migrations which will lead to data loss. For instance, * changing the data type of a column will drop the column & data and then re-create it. To avoid loss of important data, * always check and modify your migration scripts as needed. * ::: * * @example * ```ts * import { Index } from 'typeorm'; * import { EntityMetadataModifier, ProductVariant } from '\@vendure/core'; * * // Adds a unique index to the ProductVariant.sku column * export const addSkuUniqueIndex: EntityMetadataModifier = metadata => { * const instance = new ProductVariant(); * Index({ unique: true })(instance, 'sku'); * }; * ``` * * @example * ```ts * import { Column } from 'typeorm'; * import { EntityMetadataModifier, ProductTranslation } from '\@vendure/core'; * * // Use the "mediumtext" datatype for the Product's description rather than * // the default "text" type. * export const makeProductDescriptionMediumText: EntityMetadataModifier = metadata => { * const descriptionColumnIndex = metadata.columns.findIndex( * col => col.propertyName === 'description' && col.target === ProductTranslation, * ); * if (-1 < descriptionColumnIndex) { * // First we need to remove the existing column definition * // from the metadata. * metadata.columns.splice(descriptionColumnIndex, 1); * // Then we add a new column definition with our custom * // data type "mediumtext" * // DANGER: this particular modification will generate a DB migration * // which will result in data loss of existing descriptions. Make sure * // to manually check & modify your migration scripts. * const instance = new ProductTranslation(); * Column({ type: 'mediumtext' })(instance, 'description'); * } * }; * ``` * * @docsCategory configuration * @docsPage EntityOptions * @since 1.6.0 */ export type EntityMetadataModifier = (metadata: MetadataArgsStorage) => void | Promise<void>;
import { EntityIdStrategy } from './entity-id-strategy'; /** * @description * An id strategy which uses auto-increment integers as primary keys * for all entities. This is the default strategy used by Vendure. * * @docsCategory configuration * @docsPage EntityIdStrategy */ export class AutoIncrementIdStrategy implements EntityIdStrategy<'increment'> { readonly primaryKeyType = 'increment'; decodeId(id: string): number { const asNumber = +id; return Number.isNaN(asNumber) ? -1 : asNumber; } encodeId(primaryKey: number): string { return primaryKey.toString(); } }
import { EntityIdStrategy } from './entity-id-strategy'; /** * An example custom strategy which uses base64 encoding on integer ids. */ export class Base64IdStrategy implements EntityIdStrategy<'increment'> { readonly primaryKeyType = 'increment'; decodeId(id: string): number { const asNumber = +Buffer.from(id, 'base64').toString(); return Number.isNaN(asNumber) ? -1 : asNumber; } encodeId(primaryKey: number): string { return Buffer.from(primaryKey.toString()).toString('base64').replace(/=+$/, ''); } }
import { ColumnOptions } from 'typeorm'; import { Logger } from '../logger/vendure-logger'; import { MoneyStrategy } from './money-strategy'; /** * @description * A {@link MoneyStrategy} that stores monetary values as a `bigint` type in the database, which * allows values up to ~9 quadrillion to be stored (limited by JavaScript's `MAX_SAFE_INTEGER` limit). * * This strategy also slightly differs in the way rounding is performed, with rounding being done _after_ * multiplying the unit price, rather than before (as is the case with the {@link DefaultMoneyStrategy}. * * @docsCategory money * @since 2.0.0 */ export class BigIntMoneyStrategy implements MoneyStrategy { readonly moneyColumnOptions: ColumnOptions = { type: 'bigint', transformer: { to: (entityValue: number) => { return entityValue; }, from: (databaseValue: string): number => { if (databaseValue == null) { return databaseValue; } const intVal = Number.parseInt(databaseValue, 10); if (!Number.isSafeInteger(intVal)) { Logger.warn(`Monetary value ${databaseValue} is not a safe integer!`); } if (Number.isNaN(intVal)) { Logger.warn(`Monetary value ${databaseValue} is not a number!`); } return intVal; }, }, }; precision = 2; round(value: number, quantity = 1): number { return Math.round(value * quantity); } }
import { ColumnOptions } from 'typeorm'; import { Logger } from '../logger/vendure-logger'; import { MoneyStrategy } from './money-strategy'; /** * @description * A {@link MoneyStrategy} that stores monetary values as a `int` type in the database. * The storage configuration and rounding logic replicates the behaviour of Vendure pre-2.0. * * @docsCategory money * @since 2.0.0 */ export class DefaultMoneyStrategy implements MoneyStrategy { readonly moneyColumnOptions: ColumnOptions = { type: 'int', }; readonly precision: number = 2; round(value: number, quantity = 1): number { return Math.round(value) * quantity; } }
import { ConfigArg, Permission } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { VendureEntity } from '../../entity/base/base.entity'; /** * @description * A function which performs the duplication of an entity. * * @docsPage EntityDuplicator * @docsCategory configuration * @since 2.2.0 */ export type DuplicateEntityFn<T extends ConfigArgs> = (input: { ctx: RequestContext; entityName: string; id: ID; args: ConfigArgValues<T>; }) => Promise<VendureEntity>; /** * @description * Configuration for creating a new EntityDuplicator. * * @docsPage EntityDuplicator * @docsCategory configuration * @since 2.2.0 */ export interface EntityDuplicatorConfig<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { /** * @description * The permissions required in order to execute this duplicator. If an array is passed, * then the administrator must have at least one of the permissions in the array. */ requiresPermission: Array<Permission | string> | Permission | string; /** * @description * The entities for which this duplicator is able to duplicate. */ forEntities: string[]; /** * @description * The function which performs the duplication. * * @example * ```ts * duplicate: async input => { * const { ctx, id, args } = input; * * // perform the duplication logic here * * return newEntity; * } * ``` */ duplicate: DuplicateEntityFn<T>; } /** * @description * An EntityDuplicator is used to define the logic for duplicating entities when the `duplicateEntity` mutation is called. * This allows you to add support for duplication of both core and custom entities. * * @example * ```ts title=src/config/custom-collection-duplicator.ts * import { Collection, LanguageCode, Permission * EntityDuplicator, TransactionalConnection, CollectionService } from '\@vendure/core'; * * let collectionService: CollectionService; * let connection: TransactionalConnection; * * // This is just an example - we already ship with a built-in duplicator for Collections. * const customCollectionDuplicator = new EntityDuplicator({ * code: 'custom-collection-duplicator', * description: [{ languageCode: LanguageCode.en, value: 'Custom collection duplicator' }], * args: { * throwError: { * type: 'boolean', * defaultValue: false, * }, * }, * forEntities: ['Collection'], * requiresPermission: [Permission.UpdateCollection], * init(injector) { * collectionService = injector.get(CollectionService); * connection = injector.get(TransactionalConnection); * }, * duplicate: async input => { * const { ctx, id, args } = input; * * const original = await connection.getEntityOrThrow(ctx, Collection, id, { * relations: { * assets: true, * featuredAsset: true, * }, * }); * const newCollection = await collectionService.create(ctx, { * isPrivate: original.isPrivate, * customFields: original.customFields, * assetIds: original.assets.map(a => a.id), * featuredAssetId: original.featuredAsset?.id, * parentId: original.parentId, * filters: original.filters.map(f => ({ * code: f.code, * arguments: f.args, * })), * inheritFilters: original.inheritFilters, * translations: original.translations.map(t => ({ * languageCode: t.languageCode, * name: `${t.name} (copy)`, * slug: `${t.slug}-copy`, * description: t.description, * customFields: t.customFields, * })), * }); * * if (args.throwError) { * // If an error is thrown at any point during the duplication process, the entire * // transaction will get automatically rolled back, and the mutation will return * // an ErrorResponse containing the error message. * throw new Error('Dummy error'); * } * * return newCollection; * }, * }); * ``` * * The duplicator then gets passed to your VendureConfig object: * * ```ts title=src/vendure-config.ts * import { VendureConfig, defaultEntityDuplicators } from '\@vendure/core'; * import { customCollectionDuplicator } from './config/custom-collection-duplicator'; * * export const config: VendureConfig = { * // ... * entityOptions: { * entityDuplicators: [ * ...defaultEntityDuplicators, * customCollectionDuplicator, * ], * }, * }; * ``` * * @docsPage EntityDuplicator * @docsWeight 0 * @docsCategory configuration * @since 2.2.0 */ export class EntityDuplicator<T extends ConfigArgs = ConfigArgs> extends ConfigurableOperationDef<T> { private _forEntities: string[]; private _requiresPermission: Array<Permission | string> | Permission | string; private duplicateFn: DuplicateEntityFn<T>; /** @internal */ canDuplicate(entityName: string): boolean { return this._forEntities.includes(entityName); } /** @internal */ get forEntities() { return this._forEntities; } /** @internal */ get requiresPermission(): Permission[] { return (Array.isArray(this._requiresPermission) ? this._requiresPermission : [this._requiresPermission]) as any as Permission[]; } constructor(config: EntityDuplicatorConfig<T>) { super(config); this._forEntities = config.forEntities; this._requiresPermission = config.requiresPermission; this.duplicateFn = config.duplicate; } duplicate(input: { ctx: RequestContext; entityName: string; id: ID; args: ConfigArg[]; }): Promise<VendureEntity> { return this.duplicateFn({ ...input, args: this.argsArrayToHash(input.args), }); } }
import { InjectableStrategy } from '../../common/types/injectable-strategy'; export type PrimaryKeyType<T> = T extends 'uuid' ? string : T extends 'increment' ? number : any; /** * @description * The EntityIdStrategy determines how entity IDs are generated and stored in the * database, as well as how they are transformed when being passed from the API to the * service layer and vice versa. * * Vendure ships with two strategies: {@link AutoIncrementIdStrategy} and {@link UuidIdStrategy}, * but custom strategies can be used, e.g. to apply some custom encoding to the ID before exposing * it in the GraphQL API. * * :::info * * This is configured via the `entityOptions.entityIdStrategy` property of * your VendureConfig. * * ::: * * :::caution * Note: changing from an integer-based strategy to a uuid-based strategy * on an existing Vendure database will lead to problems with broken foreign-key * references. To change primary key types like this, you'll need to start with * a fresh database. * ::: * * @docsCategory configuration * @docsPage EntityIdStrategy * */ export interface EntityIdStrategy<T extends 'increment' | 'uuid'> extends InjectableStrategy { /** * @description * Defines how the primary key will be stored in the database - either * `'increment'` for auto-increment integer IDs, or `'uuid'` for a unique * string ID. */ readonly primaryKeyType: T; /** * @description * Allows the raw ID from the database to be transformed in some way before exposing * it in the GraphQL API. * * For example, you may need to use auto-increment integer IDs due to some business * constraint, but you may not want to expose this data publicly in your API. In this * case, you can use the encode/decode methods to obfuscate the ID with some kind of * encoding scheme, such as base64 (or something more sophisticated). */ encodeId: (primaryKey: PrimaryKeyType<T>) => string; /** * @description * Reverses the transformation performed by the `encodeId` method in order to get * back to the raw ID value. */ decodeId: (id: string) => PrimaryKeyType<T>; }
import { ColumnOptions } from 'typeorm'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * The MoneyStrategy defines how monetary values are stored and manipulated. The MoneyStrategy * is defined in {@link EntityOptions}: * * @example * ```ts * const config: VendureConfig = { * entityOptions: { * moneyStrategy: new MyCustomMoneyStrategy(), * } * }; * ``` * * ## Range * * The {@link DefaultMoneyStrategy} uses an `int` field in the database, which puts an * effective limit of ~21.4 million on any stored value. For certain use cases * (e.g. business sales with very high amounts, or currencies with very large * denominations), this may cause issues. In this case, you can use the * {@link BigIntMoneyStrategy} which will use the `bigint` type to store monetary values, * giving an effective upper limit of over 9 quadrillion. * * ## Precision * * Both the `DefaultMoneyStrategy` and `BigIntMoneyStrategy` store monetary values as integers, representing * the price in the minor units of the currency (i.e. _cents_ in USD or _pennies_ in GBP). * * Since v2.2.0, you can configure the precision of the stored values via the `precision` property of the * strategy. Changing the precision has **no effect** on the stored value. It is merely a hint to the * UI as to how many decimal places to display. * * @example * ```ts * import { DefaultMoneyStrategy, VendureConfig } from '\@vendure/core'; * * export class ThreeDecimalPlacesMoneyStrategy extends DefaultMoneyStrategy { * readonly precision = 3; * } * * export const config: VendureConfig = { * // ... * entityOptions: { * moneyStrategy: new ThreeDecimalPlacesMoneyStrategy(), * } * }; * ``` * * :::info * * This is configured via the `entityOptions.moneyStrategy` property of * your VendureConfig. * * ::: * * @docsCategory money * @since 2.0.0 */ export interface MoneyStrategy extends InjectableStrategy { /** * @description * Defines the TypeORM column used to store monetary values. */ readonly moneyColumnOptions: ColumnOptions; /** * @description * Defines the precision (i.e. number of decimal places) represented by the monetary values. * For example, consider a product variant with a price value of `12345`. * * - If the precision is `2`, then the price is `123.45`. * - If the precision is `3`, then the price is `12.345`. * * Changing the precision has **no effect** on the stored value. It is merely a hint to the * UI as to how many decimal places to display. * * @default 2 * @since 2.2.0 */ readonly precision?: number; /** * @description * Defines the logic used to round monetary values. For instance, the default behavior * in the {@link DefaultMoneyStrategy} is to round the value, then multiply. * * ```ts * return Math.round(value) * quantity; * ``` * * However, it may be desirable to instead round only _after_ the unit amount has been * multiplied. In this case you can define a custom strategy with logic like this: * * ```ts * return Math.round(value * quantity); * ``` */ round(value: number, quantity?: number): number; }
import { EntityIdStrategy } from './entity-id-strategy'; /** * @description * An id strategy which uses string uuids as primary keys * for all entities. This strategy can be configured with the * `entityIdStrategy` property of the `entityOptions` property * of {@link VendureConfig}. * * @example * ```ts * import { UuidIdStrategy, VendureConfig } from '\@vendure/core'; * * export const config: VendureConfig = { * entityOptions: { * entityIdStrategy: new UuidIdStrategy(), * // ... * } * } * ``` * * @docsCategory configuration * @docsPage EntityIdStrategy */ export class UuidIdStrategy implements EntityIdStrategy<'uuid'> { readonly primaryKeyType = 'uuid'; decodeId(id: string): string { return id; } encodeId(primaryKey: string): string { return primaryKey; } }
import { CreateCollectionInput, CreateCollectionTranslationInput, LanguageCode, Permission, } from '@vendure/common/lib/generated-types'; import { Injector } from '../../../common/injector'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Collection } from '../../../entity/collection/collection.entity'; import { CollectionService } from '../../../service/services/collection.service'; import { EntityDuplicator } from '../entity-duplicator'; let connection: TransactionalConnection; let collectionService: CollectionService; /** * @description * Duplicates a Collection */ export const collectionDuplicator = new EntityDuplicator({ code: 'collection-duplicator', description: [ { languageCode: LanguageCode.en, value: 'Default duplicator for Collections', }, ], requiresPermission: [Permission.CreateCollection, Permission.CreateCatalog], forEntities: ['Collection'], args: {}, init(injector: Injector) { connection = injector.get(TransactionalConnection); collectionService = injector.get(CollectionService); }, async duplicate({ ctx, id }) { const collection = await connection.getEntityOrThrow(ctx, Collection, id, { relations: { featuredAsset: true, assets: true, channels: true, }, }); const translations: CreateCollectionTranslationInput[] = collection.translations.map(translation => { return { name: translation.name + ' (copy)', slug: translation.slug + '-copy', description: translation.description, languageCode: translation.languageCode, customFields: translation.customFields, }; }); const collectionInput: CreateCollectionInput = { featuredAssetId: collection.featuredAsset?.id, isPrivate: true, assetIds: collection.assets.map(value => value.assetId), parentId: collection.parentId, translations, customFields: collection.customFields, filters: collection.filters.map(filter => ({ code: filter.code, arguments: filter.args, })), }; const duplicatedCollection = await collectionService.create(ctx, collectionInput); return duplicatedCollection; }, });
import { CreateFacetInput, FacetTranslationInput, LanguageCode, Permission, } from '@vendure/common/lib/generated-types'; import { Injector } from '../../../common/injector'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Facet } from '../../../entity/facet/facet.entity'; import { FacetValueService } from '../../../service/services/facet-value.service'; import { FacetService } from '../../../service/services/facet.service'; import { EntityDuplicator } from '../entity-duplicator'; let connection: TransactionalConnection; let facetService: FacetService; let facetValueService: FacetValueService; /** * @description * Duplicates a Facet */ export const facetDuplicator = new EntityDuplicator({ code: 'facet-duplicator', description: [ { languageCode: LanguageCode.en, value: 'Default duplicator for Facets', }, ], requiresPermission: [Permission.CreateFacet, Permission.CreateCatalog], forEntities: ['Facet'], args: { includeFacetValues: { type: 'boolean', defaultValue: true, label: [{ languageCode: LanguageCode.en, value: 'Include facet values' }], }, }, init(injector: Injector) { connection = injector.get(TransactionalConnection); facetService = injector.get(FacetService); facetValueService = injector.get(FacetValueService); }, async duplicate({ ctx, id, args }) { const facet = await connection.getEntityOrThrow(ctx, Facet, id, { relations: { values: true, }, }); const translations: FacetTranslationInput[] = facet.translations.map(translation => { return { name: translation.name + ' (copy)', languageCode: translation.languageCode, customFields: translation.customFields, }; }); const facetInput: CreateFacetInput = { isPrivate: true, translations, customFields: facet.customFields, code: facet.code + '-copy', }; const duplicatedFacet = await facetService.create(ctx, facetInput); if (args.includeFacetValues) { if (facet.values.length) { for (const value of facet.values) { const newValue = await facetValueService.create(ctx, duplicatedFacet, { code: value.code + '-copy', translations: value.translations.map(translation => ({ name: translation.name + ' (copy)', languageCode: translation.languageCode, customFields: translation.customFields, })), facetId: duplicatedFacet.id, customFields: value.customFields, }); duplicatedFacet.values.push(newValue); } } } return duplicatedFacet; }, });
import { collectionDuplicator } from './collection-duplicator'; import { facetDuplicator } from './facet-duplicator'; import { productDuplicator } from './product-duplicator'; import { promotionDuplicator } from './promotion-duplicator'; export const defaultEntityDuplicators = [ productDuplicator, collectionDuplicator, facetDuplicator, promotionDuplicator, ];
import { CreateProductInput, CreateProductOptionInput, CreateProductVariantInput, LanguageCode, Permission, ProductTranslationInput, } from '@vendure/common/lib/generated-types'; import { IsNull } from 'typeorm'; import { InternalServerError } from '../../../common/error/errors'; import { Injector } from '../../../common/injector'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Product } from '../../../entity/product/product.entity'; import { ProductOptionGroup } from '../../../entity/product-option-group/product-option-group.entity'; import { ProductVariant } from '../../../entity/product-variant/product-variant.entity'; import { ProductOptionGroupService } from '../../../service/services/product-option-group.service'; import { ProductOptionService } from '../../../service/services/product-option.service'; import { ProductVariantService } from '../../../service/services/product-variant.service'; import { ProductService } from '../../../service/services/product.service'; import { EntityDuplicator } from '../entity-duplicator'; let connection: TransactionalConnection; let productService: ProductService; let productVariantService: ProductVariantService; let productOptionGroupService: ProductOptionGroupService; let productOptionService: ProductOptionService; /** * @description * Duplicates a Product and its associated ProductVariants. */ export const productDuplicator = new EntityDuplicator({ code: 'product-duplicator', description: [ { languageCode: LanguageCode.en, value: 'Default duplicator for Products', }, ], requiresPermission: [Permission.CreateProduct, Permission.CreateCatalog], forEntities: ['Product'], args: { includeVariants: { type: 'boolean', defaultValue: true, label: [{ languageCode: LanguageCode.en, value: 'Include variants' }], }, }, init(injector: Injector) { connection = injector.get(TransactionalConnection); productService = injector.get(ProductService); productVariantService = injector.get(ProductVariantService); productOptionGroupService = injector.get(ProductOptionGroupService); productOptionService = injector.get(ProductOptionService); }, async duplicate({ ctx, id, args }) { const product = await connection.getEntityOrThrow(ctx, Product, id, { relations: { featuredAsset: true, assets: true, channels: true, facetValues: { facet: true, }, optionGroups: { options: true, }, }, }); const translations: ProductTranslationInput[] = product.translations.map(translation => { return { name: translation.name + ' (copy)', slug: translation.slug + '-copy', description: translation.description, languageCode: translation.languageCode, customFields: translation.customFields, }; }); const productInput: CreateProductInput = { featuredAssetId: product.featuredAsset?.id, enabled: false, assetIds: product.assets.map(value => value.assetId), facetValueIds: product.facetValues.map(value => value.id), translations, customFields: product.customFields, }; const duplicatedProduct = await productService.create(ctx, productInput); if (args.includeVariants) { const productVariants = await connection.getRepository(ctx, ProductVariant).find({ where: { productId: id, deletedAt: IsNull(), }, relations: { options: { group: true, }, assets: true, featuredAsset: true, stockLevels: true, facetValues: true, }, }); if (product.optionGroups && product.optionGroups.length) { for (const optionGroup of product.optionGroups) { const newOptionGroup = await productOptionGroupService.create(ctx, { code: optionGroup.code, translations: optionGroup.translations.map(translation => { return { languageCode: translation.languageCode, name: translation.name, customFields: translation.customFields, }; }), }); const options: CreateProductOptionInput[] = optionGroup.options.map(option => { return { code: option.code, productOptionGroupId: newOptionGroup.id, translations: option.translations.map(translation => { return { languageCode: translation.languageCode, name: translation.name, customFields: translation.customFields, }; }), }; }); if (options && options.length) { for (const option of options) { const newOption = await productOptionService.create(ctx, newOptionGroup, option); newOptionGroup.options.push(newOption); } } await productService.addOptionGroupToProduct( ctx, duplicatedProduct.id, newOptionGroup.id, ); } } const newOptionGroups = await connection.getRepository(ctx, ProductOptionGroup).find({ where: { product: { id: duplicatedProduct.id }, }, relations: { options: true, }, }); const variantInput: CreateProductVariantInput[] = productVariants.map((variant, i) => { const options = variant.options.map(existingOption => { const newOption = newOptionGroups .find(og => og.code === existingOption.group.code) ?.options.find(o => o.code === existingOption.code); if (!newOption) { throw new InternalServerError( `An error occurred when creating option ${existingOption.code}`, ); } return newOption; }); return { productId: duplicatedProduct.id, price: variant.price, sku: `${variant.sku}-copy`, stockOnHand: 1, featuredAssetId: variant.featuredAsset?.id, useGlobalOutOfStockThreshold: variant.useGlobalOutOfStockThreshold, trackInventory: variant.trackInventory, assetIds: variant.assets.map(value => value.assetId), translations: variant.translations.map(translation => { return { languageCode: translation.languageCode, name: translation.name, }; }), optionIds: options.map(option => option.id), facetValueIds: variant.facetValues.map(value => value.id), stockLevels: variant.stockLevels.map(stockLevel => ({ stockLocationId: stockLevel.stockLocationId, stockOnHand: stockLevel.stockOnHand, })), }; }); const duplicatedProductVariants = await productVariantService.create(ctx, variantInput); duplicatedProduct.variants = duplicatedProductVariants; } return duplicatedProduct; }, });
import { CreatePromotionInput, LanguageCode, Permission, PromotionTranslationInput, } from '@vendure/common/lib/generated-types'; import { isGraphQlErrorResult } from '../../../common/error/error-result'; import { Injector } from '../../../common/injector'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Promotion } from '../../../entity/promotion/promotion.entity'; import { PromotionService } from '../../../service/services/promotion.service'; import { EntityDuplicator } from '../entity-duplicator'; let connection: TransactionalConnection; let promotionService: PromotionService; /** * @description * Duplicates a Promotion */ export const promotionDuplicator = new EntityDuplicator({ code: 'promotion-duplicator', description: [ { languageCode: LanguageCode.en, value: 'Default duplicator for Promotions', }, ], requiresPermission: [Permission.CreatePromotion], forEntities: ['Promotion'], args: {}, init(injector: Injector) { connection = injector.get(TransactionalConnection); promotionService = injector.get(PromotionService); }, async duplicate({ ctx, id }) { const promotion = await connection.getEntityOrThrow(ctx, Promotion, id); const translations: PromotionTranslationInput[] = promotion.translations.map(translation => { return { name: translation.name + ' (copy)', description: translation.description, languageCode: translation.languageCode, customFields: translation.customFields, }; }); const promotionInput: CreatePromotionInput = { couponCode: promotion.couponCode, startsAt: promotion.startsAt, endsAt: promotion.endsAt, perCustomerUsageLimit: promotion.perCustomerUsageLimit, usageLimit: promotion.usageLimit, conditions: promotion.conditions.map(condition => ({ code: condition.code, arguments: condition.args, })), actions: promotion.actions.map(action => ({ code: action.code, arguments: action.args, })), enabled: false, translations, customFields: promotion.customFields, }; const duplicatedPromotion = await promotionService.createPromotion(ctx, promotionInput); if (isGraphQlErrorResult(duplicatedPromotion)) { throw new Error(duplicatedPromotion.message); } return duplicatedPromotion; }, });
import { HistoryEntryType } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { isGraphQlErrorResult } from '../../common/error/error-result'; import { InternalServerError } from '../../common/error/errors'; import { awaitPromiseOrObservable } from '../../common/utils'; import { Fulfillment } from '../../entity/fulfillment/fulfillment.entity'; import { Order } from '../../entity/order/order.entity'; import { FulfillmentState } from '../../service/helpers/fulfillment-state-machine/fulfillment-state'; import { OrderState } from '../../service/helpers/order-state-machine/order-state'; import { orderItemsAreDelivered, orderItemsAreShipped } from '../../service/helpers/utils/order-utils'; import { FulfillmentProcess } from './fulfillment-process'; declare module '../../service/helpers/fulfillment-state-machine/fulfillment-state' { interface FulfillmentStates { Shipped: never; Delivered: never; } } let connection: import('../../connection/transactional-connection').TransactionalConnection; let configService: import('../config.service').ConfigService; let orderService: import('../../service/index').OrderService; let historyService: import('../../service/index').HistoryService; let stockMovementService: import('../../service/index').StockMovementService; let stockLevelService: import('../../service/index').StockLevelService; /** * @description * The default {@link FulfillmentProcess}. This process includes the following actions: * * - Executes the configured `FulfillmentHandler.onFulfillmentTransition()` before any state * transition. * - On cancellation of a Fulfillment, creates the necessary {@link Cancellation} & {@link Allocation} * stock movement records. * - When a Fulfillment transitions from the `Created` to `Pending` state, the necessary * {@link Sale} stock movements are created. * * @docsCategory fulfillment * @docsPage FulfillmentProcess * @since 2.0.0 */ export const defaultFulfillmentProcess: FulfillmentProcess<FulfillmentState> = { transitions: { Created: { to: ['Pending'], }, Pending: { to: ['Shipped', 'Delivered', 'Cancelled'], }, Shipped: { to: ['Delivered', 'Cancelled'], }, Delivered: { to: ['Cancelled'], }, Cancelled: { to: [], }, }, async init(injector) { // Lazily import these services to avoid a circular dependency error // due to this being used as part of the DefaultConfig const TransactionalConnection = await import('../../connection/transactional-connection.js').then( m => m.TransactionalConnection, ); const ConfigService = await import('../config.service.js').then(m => m.ConfigService); const HistoryService = await import('../../service/index.js').then(m => m.HistoryService); const OrderService = await import('../../service/index.js').then(m => m.OrderService); const StockMovementService = await import('../../service/index.js').then(m => m.StockMovementService); const StockLevelService = await import('../../service/index.js').then(m => m.StockLevelService); connection = injector.get(TransactionalConnection); configService = injector.get(ConfigService); orderService = injector.get(OrderService); historyService = injector.get(HistoryService); stockMovementService = injector.get(StockMovementService); stockLevelService = injector.get(StockLevelService); }, async onTransitionStart(fromState, toState, data) { const { fulfillmentHandlers } = configService.shippingOptions; const fulfillmentHandler = fulfillmentHandlers.find(h => h.code === data.fulfillment.handlerCode); if (fulfillmentHandler) { const result = await awaitPromiseOrObservable( fulfillmentHandler.onFulfillmentTransition(fromState, toState, data), ); if (result === false || typeof result === 'string') { return result; } } }, async onTransitionEnd(fromState, toState, { ctx, fulfillment, orders }) { if (toState === 'Cancelled') { const orderLineInput = fulfillment.lines.map(l => ({ orderLineId: l.orderLineId, quantity: l.quantity, })); await stockMovementService.createCancellationsForOrderLines(ctx, orderLineInput); // const lines = await groupOrderItemsIntoLines(ctx, orderLineInput); await stockMovementService.createAllocationsForOrderLines(ctx, orderLineInput); } if (fromState === 'Created' && toState === 'Pending') { await stockMovementService.createSalesForOrder(ctx, fulfillment.lines); } const historyEntryPromises = orders.map(order => historyService.createHistoryEntryForOrder({ orderId: order.id, type: HistoryEntryType.ORDER_FULFILLMENT_TRANSITION, ctx, data: { fulfillmentId: fulfillment.id, from: fromState, to: toState, }, }), ); await Promise.all(historyEntryPromises); await Promise.all( orders.map(order => handleFulfillmentStateTransitByOrder(ctx, order, fulfillment, fromState, toState), ), ); }, }; async function handleFulfillmentStateTransitByOrder( ctx: RequestContext, order: Order, fulfillment: Fulfillment, fromState: FulfillmentState, toState: FulfillmentState, ): Promise<void> { const nextOrderStates = orderService.getNextOrderStates(order); const transitionOrderIfStateAvailable = async (state: OrderState) => { if (nextOrderStates.includes(state)) { const result = await orderService.transitionToState(ctx, order.id, state); if (isGraphQlErrorResult(result)) { throw new InternalServerError(result.message); } } }; if (toState === 'Shipped') { const orderWithFulfillment = await getOrderWithFulfillments(ctx, order.id); if (orderItemsAreShipped(orderWithFulfillment)) { await transitionOrderIfStateAvailable('Shipped'); } else { await transitionOrderIfStateAvailable('PartiallyShipped'); } } if (toState === 'Delivered') { const orderWithFulfillment = await getOrderWithFulfillments(ctx, order.id); if (orderItemsAreDelivered(orderWithFulfillment)) { await transitionOrderIfStateAvailable('Delivered'); } else { await transitionOrderIfStateAvailable('PartiallyDelivered'); } } } async function getOrderWithFulfillments(ctx: RequestContext, orderId: ID) { return await connection.getEntityOrThrow(ctx, Order, orderId, { relations: ['lines', 'fulfillments', 'fulfillments.lines', 'fulfillments.lines.fulfillment'], }); }
import { ConfigArg, OrderLineInput } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { OnTransitionStartFn } from '../../common/finite-state-machine/types'; import { Fulfillment } from '../../entity/fulfillment/fulfillment.entity'; import { Order } from '../../entity/order/order.entity'; import { FulfillmentState, FulfillmentTransitionData, } from '../../service/helpers/fulfillment-state-machine/fulfillment-state'; /** * @docsCategory fulfillment * @docsPage FulfillmentHandler * @docsWeight 3 */ export type CreateFulfillmentResult = Partial<Pick<Fulfillment, 'trackingCode' | 'method' | 'customFields'>>; /** * @description * The function called when creating a new Fulfillment * * @docsCategory fulfillment * @docsPage FulfillmentHandler * @docsWeight 2 */ export type CreateFulfillmentFn<T extends ConfigArgs> = ( ctx: RequestContext, orders: Order[], lines: OrderLineInput[], args: ConfigArgValues<T>, ) => CreateFulfillmentResult | Promise<CreateFulfillmentResult>; /** * @description * The configuration object used to instantiate a {@link FulfillmentHandler}. * * @docsCategory fulfillment * @docsPage FulfillmentHandler * @docsWeight 1 */ export interface FulfillmentHandlerConfig<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { /** * @description * Invoked when the `addFulfillmentToOrder` mutation is executed with this handler selected. * * If an Error is thrown from within this function, no Fulfillment is created and the `CreateFulfillmentError` * result will be returned. */ createFulfillment: CreateFulfillmentFn<T>; /** * @description * This allows the handler to intercept state transitions of the created Fulfillment. This works much in the * same way as the {@link CustomFulfillmentProcess} `onTransitionStart` method (i.e. returning `false` or * `string` will be interpreted as an error and prevent the state transition), except that it is only invoked * on Fulfillments which were created with this particular FulfillmentHandler. * * It can be useful e.g. to intercept Fulfillment cancellations and relay that information to a 3rd-party * shipping API. */ onFulfillmentTransition?: OnTransitionStartFn<FulfillmentState, FulfillmentTransitionData>; } /** * @description * A FulfillmentHandler is used when creating a new {@link Fulfillment}. When the `addFulfillmentToOrder` mutation * is executed, the specified handler will be used and it's `createFulfillment` method is called. This method * may perform async tasks such as calling a 3rd-party shipping API to register a new shipment and receive * a tracking code. This data can then be returned and will be incorporated into the created Fulfillment. * * If the `args` property is defined, this means that arguments passed to the `addFulfillmentToOrder` mutation * will be passed through to the `createFulfillment` method as the last argument. * * @example * ```ts * let shipomatic; * * export const shipomaticFulfillmentHandler = new FulfillmentHandler({ * code: 'ship-o-matic', * description: [{ * languageCode: LanguageCode.en, * value: 'Generate tracking codes via the Ship-o-matic API' * }], * * args: { * preferredService: { * type: 'string', * ui: { component: 'select-form-input', * options: [ * { value: 'first_class' }, * { value: 'priority'}, * { value: 'standard' }, * ], * }, * } * }, * * init: () => { * // some imaginary shipping service * shipomatic = new ShipomaticClient(API_KEY); * }, * * createFulfillment: async (ctx, orders, lines, args) => { * * const shipment = getShipmentFromOrders(orders, lines); * * try { * const transaction = await shipomatic.transaction.create({ * shipment, * service_level: args.preferredService, * label_file_type: 'png', * }) * * return { * method: `Ship-o-matic ${args.preferredService}`, * trackingCode: transaction.tracking_code, * customFields: { * shippingTransactionId: transaction.id, * } * }; * } catch (e: any) { * // Errors thrown from within this function will * // result in a CreateFulfillmentError being returned * throw e; * } * }, * * onFulfillmentTransition: async (fromState, toState, { fulfillment }) => { * if (toState === 'Cancelled') { * await shipomatic.transaction.cancel({ * transaction_id: fulfillment.customFields.shippingTransactionId, * }); * } * } * }); * ``` * * @docsCategory fulfillment * @docsPage FulfillmentHandler * @docsWeight 0 */ export class FulfillmentHandler<T extends ConfigArgs = ConfigArgs> extends ConfigurableOperationDef<T> { private readonly createFulfillmentFn: CreateFulfillmentFn<T>; private readonly onFulfillmentTransitionFn: | OnTransitionStartFn<FulfillmentState, FulfillmentTransitionData> | undefined; constructor(config: FulfillmentHandlerConfig<T>) { super(config); this.createFulfillmentFn = config.createFulfillment; if (config.onFulfillmentTransition) { this.onFulfillmentTransitionFn = config.onFulfillmentTransition; } } /** * @internal */ createFulfillment( ctx: RequestContext, orders: Order[], lines: OrderLineInput[], args: ConfigArg[], ): Partial<Fulfillment> | Promise<Partial<Fulfillment>> { return this.createFulfillmentFn(ctx, orders, lines, this.argsArrayToHash(args)); } /** * @internal */ onFulfillmentTransition( fromState: FulfillmentState, toState: FulfillmentState, data: FulfillmentTransitionData, ) { if (typeof this.onFulfillmentTransitionFn === 'function') { return this.onFulfillmentTransitionFn(fromState, toState, data); } } }
import { OnTransitionEndFn, OnTransitionErrorFn, OnTransitionStartFn, Transitions, } from '../../common/finite-state-machine/types'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { CustomFulfillmentStates, FulfillmentState, FulfillmentTransitionData, } from '../../service/helpers/fulfillment-state-machine/fulfillment-state'; /** * @description * A FulfillmentProcess is used to define the way the fulfillment process works as in: what states a Fulfillment can be * in, and how it may transition from one state to another. Using the `onTransitionStart()` hook, a * FulfillmentProcess can perform checks before allowing a state transition to occur, and the `onTransitionEnd()` * hook allows logic to be executed after a state change. * * For detailed description of the interface members, see the {@link StateMachineConfig} docs. * * @docsCategory fulfillment * @since 2.0.0 */ export interface FulfillmentProcess<State extends keyof CustomFulfillmentStates | string> extends InjectableStrategy { transitions?: Transitions<State, State | FulfillmentState> & Partial<Transitions<FulfillmentState | State>>; onTransitionStart?: OnTransitionStartFn<State | FulfillmentState, FulfillmentTransitionData>; onTransitionEnd?: OnTransitionEndFn<State | FulfillmentState, FulfillmentTransitionData>; onTransitionError?: OnTransitionErrorFn<State | FulfillmentState>; } /** * @description * Used to define extensions to or modifications of the default fulfillment process. * * For detailed description of the interface members, see the {@link StateMachineConfig} docs. * * @deprecated Use FulfillmentProcess */ export interface CustomFulfillmentProcess<State extends keyof CustomFulfillmentStates | string> extends FulfillmentProcess<State> {}