@scayle/storefront-core 7.59.1 → 7.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/errors/errorResponse.cjs +27 -0
  3. package/dist/errors/errorResponse.d.ts +12 -0
  4. package/dist/errors/errorResponse.mjs +20 -0
  5. package/dist/errors/index.cjs +11 -0
  6. package/dist/errors/index.d.ts +1 -0
  7. package/dist/errors/index.mjs +1 -0
  8. package/dist/rpc/methods/basket/basket.cjs +14 -4
  9. package/dist/rpc/methods/basket/basket.d.ts +5 -4
  10. package/dist/rpc/methods/basket/basket.mjs +24 -14
  11. package/dist/rpc/methods/checkout/checkout.cjs +4 -2
  12. package/dist/rpc/methods/checkout/checkout.mjs +8 -2
  13. package/dist/rpc/methods/checkout/order.cjs +9 -6
  14. package/dist/rpc/methods/checkout/order.d.ts +2 -1
  15. package/dist/rpc/methods/checkout/order.mjs +38 -7
  16. package/dist/rpc/methods/checkout/shopUser.cjs +14 -7
  17. package/dist/rpc/methods/checkout/shopUser.d.ts +3 -2
  18. package/dist/rpc/methods/checkout/shopUser.mjs +42 -9
  19. package/dist/rpc/methods/oauth/idp.cjs +4 -6
  20. package/dist/rpc/methods/oauth/idp.d.ts +2 -1
  21. package/dist/rpc/methods/oauth/idp.mjs +12 -2
  22. package/dist/rpc/methods/products.cjs +15 -6
  23. package/dist/rpc/methods/products.d.ts +3 -2
  24. package/dist/rpc/methods/products.mjs +15 -10
  25. package/dist/rpc/methods/session.cjs +40 -37
  26. package/dist/rpc/methods/session.d.ts +3 -2
  27. package/dist/rpc/methods/session.mjs +74 -46
  28. package/dist/rpc/methods/wishlist.cjs +7 -2
  29. package/dist/rpc/methods/wishlist.mjs +16 -3
  30. package/dist/utils/timeout.cjs +5 -4
  31. package/dist/utils/timeout.d.ts +1 -1
  32. package/dist/utils/timeout.mjs +5 -4
  33. package/package.json +7 -7
@@ -1,4 +1,6 @@
1
1
  import { SignJWT } from "jose";
2
+ import { ErrorResponse } from "../../../errors/index.mjs";
3
+ import { HttpStatusCode, HttpStatusMessage } from "../../../constants/index.mjs";
2
4
  import { assertSession } from "../../../types/index.mjs";
3
5
  import { getOAuthClient } from "../../../api/oauth.mjs";
4
6
  import { postLogin } from "../session.mjs";
@@ -7,10 +9,18 @@ export const getExternalIdpRedirect = async function getExternalIdpRedirect2({ q
7
9
  return {};
8
10
  }
9
11
  if (context.idp.idpKeys.length === 0) {
10
- return new Response("No IDP keys are configured", { status: 400 });
12
+ return new ErrorResponse(
13
+ HttpStatusCode.BAD_REQUEST,
14
+ HttpStatusMessage.BAD_REQUEST,
15
+ "No IDP keys are configured"
16
+ );
11
17
  }
12
18
  if (!context.idp.idpRedirectURL) {
13
- return new Response("No IDP redirect url is configured", { status: 400 });
19
+ return new ErrorResponse(
20
+ HttpStatusCode.BAD_REQUEST,
21
+ HttpStatusMessage.BAD_REQUEST,
22
+ "No IDP redirect url is configured"
23
+ );
14
24
  }
15
25
  const OAuthClient = getOAuthClient(context);
16
26
  const redirectUrl = new URL(context.idp.idpRedirectURL);
@@ -8,6 +8,7 @@ var _helpers = require("../../helpers/index.cjs");
8
8
  var _constants = require("../../constants/index.cjs");
9
9
  var _cache = require("../../cache/index.cjs");
10
10
  var _response = require("../../utils/response.cjs");
11
+ var _errors = require("../../errors/index.cjs");
11
12
  const MAX_PER_PAGE = 100;
12
13
  const sanitizeAttributesForBAPI = ({
13
14
  attributes,
@@ -152,13 +153,17 @@ const getFilters = exports.getFilters = async function getFilters2({
152
153
  result = await cached(bapiClient.categories.getByPath, {
153
154
  cacheKeyPrefix: `getByPath-categories-${category}`
154
155
  })((0, _helpers.splitAndRemoveEmpty)(category));
155
- allFiltersForCategory = await (0, _response.unwrap)(fetchAllFiltersForCategory({
156
+ const response = await fetchAllFiltersForCategory({
156
157
  category: {
157
158
  id: result.id,
158
159
  slug: category
159
160
  },
160
161
  includedFilters
161
- }, context));
162
+ }, context);
163
+ if (response instanceof _errors.ErrorResponse) {
164
+ return response;
165
+ }
166
+ allFiltersForCategory = await (0, _response.unwrap)(response);
162
167
  }
163
168
  const sanitizedAttributes = sanitizeAttributesForBAPI({
164
169
  attributes: where?.attributes || [],
@@ -227,14 +232,18 @@ const getProductsByCategory = exports.getProductsByCategory = async function get
227
232
  cacheKeyPrefix: `getByPath-categories-${category}`
228
233
  })((0, _helpers.splitAndRemoveEmpty)(category));
229
234
  }
230
- const {
231
- filters
232
- } = await (0, _response.unwrap)(getFilters({
235
+ const getFiltersResponse = getFilters({
233
236
  category,
234
237
  includeSoldOut,
235
238
  where,
236
239
  includeSellableForFree
237
- }, context));
240
+ }, context);
241
+ if (getFiltersResponse instanceof _errors.ErrorResponse) {
242
+ return getFiltersResponse;
243
+ }
244
+ const {
245
+ filters
246
+ } = await (0, _response.unwrap)(getFiltersResponse);
238
247
  const {
239
248
  entities: products,
240
249
  pagination
@@ -1,5 +1,6 @@
1
1
  import type { FiltersEndpointResponseData } from '@scayle/storefront-api';
2
2
  import type { FetchFiltersParams, FetchProductParams, FetchProductsByCategoryParams, FetchProductsByIdsParams, FetchProductsByReferenceKeysParams, FetchProductsCountParams, Product, RpcContext } from '../../types';
3
+ import { ErrorResponse } from '../../errors';
3
4
  export declare const getProductById: (options: FetchProductParams, { bapiClient, cached, campaignKey, withParams }: RpcContext) => Promise<Product>;
4
5
  export declare const getProductsByIds: (options: FetchProductsByIdsParams, { bapiClient, cached, campaignKey, withParams }: RpcContext) => Promise<Product[]>;
5
6
  export declare const getProductsByReferenceKeys: (options: FetchProductsByReferenceKeysParams, { bapiClient, cached, campaignKey, withParams }: RpcContext) => Promise<Product[]>;
@@ -13,11 +14,11 @@ export declare const fetchAllFiltersForCategory: ({ includedFilters, category }:
13
14
  id: number;
14
15
  };
15
16
  }, { cached, bapiClient, campaignKey }: RpcContext) => Promise<string[]>;
16
- export declare const getFilters: ({ category, includedFilters, where, includeSoldOut, includeSellableForFree, orFiltersOperator, }: FetchFiltersParams, context: RpcContext) => Promise<{
17
+ export declare const getFilters: ({ category, includedFilters, where, includeSoldOut, includeSellableForFree, orFiltersOperator, }: FetchFiltersParams, context: RpcContext) => Promise<(string[] & ErrorResponse) | {
17
18
  filters: FiltersEndpointResponseData;
18
19
  unfilteredCount: number;
19
20
  }>;
20
- export declare const getProductsByCategory: ({ category, cache, with: _with, perPage, page, where, sort, pricePromotionKey, includeSellableForFree, includeSoldOut, orFiltersOperator, }: FetchProductsByCategoryParams, context: RpcContext) => Promise<{
21
+ export declare const getProductsByCategory: ({ category, cache, with: _with, perPage, page, where, sort, pricePromotionKey, includeSellableForFree, includeSoldOut, orFiltersOperator, }: FetchProductsByCategoryParams, context: RpcContext) => Promise<ErrorResponse | {
21
22
  products: Product[];
22
23
  pagination: {
23
24
  current: number;
@@ -2,6 +2,7 @@ import { splitAndRemoveEmpty } from "../../helpers/index.mjs";
2
2
  import { MIN_WITH_PARAMS_PRODUCT } from "../../constants/index.mjs";
3
3
  import { MINUTE } from "../../cache/index.mjs";
4
4
  import { unwrap } from "../../utils/response.mjs";
5
+ import { ErrorResponse } from "../../errors/index.mjs";
5
6
  const MAX_PER_PAGE = 100;
6
7
  const sanitizeAttributesForBAPI = ({
7
8
  attributes,
@@ -112,12 +113,14 @@ export const getFilters = async function getFilters2({
112
113
  result = await cached(bapiClient.categories.getByPath, {
113
114
  cacheKeyPrefix: `getByPath-categories-${category}`
114
115
  })(splitAndRemoveEmpty(category));
115
- allFiltersForCategory = await unwrap(
116
- fetchAllFiltersForCategory(
117
- { category: { id: result.id, slug: category }, includedFilters },
118
- context
119
- )
116
+ const response = await fetchAllFiltersForCategory(
117
+ { category: { id: result.id, slug: category }, includedFilters },
118
+ context
120
119
  );
120
+ if (response instanceof ErrorResponse) {
121
+ return response;
122
+ }
123
+ allFiltersForCategory = await unwrap(response);
121
124
  }
122
125
  const sanitizedAttributes = sanitizeAttributesForBAPI({
123
126
  attributes: where?.attributes || [],
@@ -191,12 +194,14 @@ export const getProductsByCategory = async function getProductsByCategory2({
191
194
  cacheKeyPrefix: `getByPath-categories-${category}`
192
195
  })(splitAndRemoveEmpty(category));
193
196
  }
194
- const { filters } = await unwrap(
195
- getFilters(
196
- { category, includeSoldOut, where, includeSellableForFree },
197
- context
198
- )
197
+ const getFiltersResponse = getFilters(
198
+ { category, includeSoldOut, where, includeSellableForFree },
199
+ context
199
200
  );
201
+ if (getFiltersResponse instanceof ErrorResponse) {
202
+ return getFiltersResponse;
203
+ }
204
+ const { filters } = await unwrap(getFiltersResponse);
200
205
  const { entities: products, pagination } = await cached(
201
206
  bapiClient.products.query,
202
207
  {
@@ -14,17 +14,20 @@ var _user = require("../../utils/user.cjs");
14
14
  var _user2 = require("../../rpc/methods/user.cjs");
15
15
  var _response = require("../../utils/response.cjs");
16
16
  var _oauth = require("../../api/oauth.cjs");
17
+ var _errors = require("../../errors/index.cjs");
17
18
  const convertErrorForRpcCall = (error, httpStatuses) => {
18
19
  if (error instanceof _fetch.FetchError && httpStatuses.includes(error.response.status)) {
19
- return new Response(null, {
20
- status: error.response.status
21
- });
20
+ return new _errors.ErrorResponse(error.response.status, error.response.statusText, error.name);
22
21
  }
23
22
  };
24
23
  async function postLogin(context, tokens) {
25
- const user = await (0, _response.unwrap)((0, _user2.fetchUser)({
24
+ const fetchUserResponse = await (0, _user2.fetchUser)({
26
25
  accessToken: tokens.access_token
27
- }, context));
26
+ }, context);
27
+ if (fetchUserResponse instanceof _errors.ErrorResponse) {
28
+ return fetchUserResponse;
29
+ }
30
+ const user = await (0, _response.unwrap)(fetchUserResponse);
28
31
  context.updateTokens({
29
32
  accessToken: tokens.access_token,
30
33
  refreshToken: tokens.refresh_token
@@ -47,24 +50,24 @@ const oauthLogin = async (login, context) => {
47
50
  const shopId = context.shopId;
48
51
  const client = (0, _oauth.getOAuthClient)(context);
49
52
  if (!login.email || !login.password) {
50
- throw new Error("Login or password are missing, seems like validation has failed");
53
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.BAD_REQUEST, _constants.HttpStatusMessage.BAD_REQUEST, "Login or password are missing");
51
54
  }
52
55
  try {
53
56
  const tokens = await client.login({
54
57
  ...login,
55
58
  shop_id: shopId
56
59
  });
57
- await postLogin(context, tokens);
58
- } catch (error) {
59
- const res = convertErrorForRpcCall(error, [_constants.HttpStatusCode.INTERNAL_SERVER_ERROR, _constants.HttpStatusCode.BAD_REQUEST, _constants.HttpStatusCode.UNAUTHORIZED, _constants.HttpStatusCode.NOT_FOUND, _constants.HttpStatusCode.FORBIDDEN]);
60
- if (res) {
61
- return res;
60
+ const postLoginResponse = await postLogin(context, tokens);
61
+ if (postLoginResponse instanceof _errors.ErrorResponse) {
62
+ return postLoginResponse;
62
63
  }
63
- throw error;
64
+ return new Response(null, {
65
+ status: _constants.HttpStatusCode.NO_CONTENT
66
+ });
67
+ } catch (error) {
68
+ context.log.error("OAuthClient.login failed", error);
69
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.INTERNAL_SERVER_ERROR, _constants.HttpStatusMessage.INTERNAL_SERVER_ERROR, "Login failed");
64
70
  }
65
- return new Response(null, {
66
- status: _constants.HttpStatusCode.NO_CONTENT
67
- });
68
71
  };
69
72
  exports.oauthLogin = oauthLogin;
70
73
  const oauthRegister = async (register, context) => {
@@ -76,17 +79,17 @@ const oauthRegister = async (register, context) => {
76
79
  ...register,
77
80
  shop_id: shopId
78
81
  });
79
- await postLogin(context, tokens);
80
- } catch (error) {
81
- const res = convertErrorForRpcCall(error, [_constants.HttpStatusCode.BAD_REQUEST, _constants.HttpStatusCode.UNAUTHORIZED, _constants.HttpStatusCode.CONFLICT, _constants.HttpStatusCode.FORBIDDEN]);
82
- if (res) {
83
- return res;
82
+ const postLoginResponse = await postLogin(context, tokens);
83
+ if (postLoginResponse instanceof _errors.ErrorResponse) {
84
+ return postLoginResponse;
84
85
  }
85
- throw error;
86
+ return new Response(null, {
87
+ status: _constants.HttpStatusCode.NO_CONTENT
88
+ });
89
+ } catch (error) {
90
+ context.log.error("OAuthClient.register failed", error);
91
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.INTERNAL_SERVER_ERROR, _constants.HttpStatusMessage.INTERNAL_SERVER_ERROR, "Register failed");
86
92
  }
87
- return new Response(null, {
88
- status: _constants.HttpStatusCode.NO_CONTENT
89
- });
90
93
  };
91
94
  exports.oauthRegister = oauthRegister;
92
95
  const oauthGuestLogin = async (guest, context) => {
@@ -98,17 +101,17 @@ const oauthGuestLogin = async (guest, context) => {
98
101
  ...guest,
99
102
  shop_id: shopId
100
103
  });
101
- await postLogin(context, tokens);
102
- } catch (error) {
103
- const res = convertErrorForRpcCall(error, [_constants.HttpStatusCode.BAD_REQUEST, _constants.HttpStatusCode.UNAUTHORIZED, _constants.HttpStatusCode.CONFLICT, _constants.HttpStatusCode.FORBIDDEN]);
104
- if (res) {
105
- return res;
104
+ const postLoginResponse = await postLogin(context, tokens);
105
+ if (postLoginResponse instanceof _errors.ErrorResponse) {
106
+ return postLoginResponse;
106
107
  }
107
- throw error;
108
+ return new Response(null, {
109
+ status: _constants.HttpStatusCode.NO_CONTENT
110
+ });
111
+ } catch (error) {
112
+ context.log.error("OAuthClient.guestLogin failed", error);
113
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.INTERNAL_SERVER_ERROR, _constants.HttpStatusMessage.INTERNAL_SERVER_ERROR, "Guest login failed");
108
114
  }
109
- return new Response(null, {
110
- status: _constants.HttpStatusCode.NO_CONTENT
111
- });
112
115
  };
113
116
  exports.oauthGuestLogin = oauthGuestLogin;
114
117
  const refreshAccessToken = async context => {
@@ -116,7 +119,7 @@ const refreshAccessToken = async context => {
116
119
  const refreshToken = context.refreshToken;
117
120
  const client = (0, _oauth.getOAuthClient)(context);
118
121
  if (!refreshToken) {
119
- throw new Error("No app refresh token provided");
122
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.BAD_REQUEST, _constants.HttpStatusMessage.BAD_REQUEST, "No refresh token present");
120
123
  }
121
124
  try {
122
125
  const tokens = await client.refreshToken({
@@ -145,7 +148,7 @@ const oauthRevokeToken = async context => {
145
148
  (0, _types.assertSession)(context);
146
149
  const accessToken = context.accessToken;
147
150
  if (!accessToken) {
148
- throw new Error("No app oauth authentication credentials");
151
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.UNAUTHORIZED, _constants.HttpStatusMessage.UNAUTHORIZED, "No access token present");
149
152
  }
150
153
  const user = context.user;
151
154
  const client = (0, _oauth.getOAuthClient)(context);
@@ -179,7 +182,7 @@ const oauthForgetPassword = async ({
179
182
  const client = (0, _oauth.getOAuthClient)(context);
180
183
  try {
181
184
  if (!context.auth.resetPasswordUrl) {
182
- throw new Error("Missing password reset URL");
185
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.INTERNAL_SERVER_ERROR, _constants.HttpStatusMessage.INTERNAL_SERVER_ERROR, "Missing password reset URL");
183
186
  }
184
187
  const resetUrl = new URL(context.auth.resetPasswordUrl);
185
188
  if (!resetUrl.searchParams.has("hash")) {
@@ -225,7 +228,7 @@ const updatePasswordByHash = async (passwordHash, context) => {
225
228
  if (res) {
226
229
  return res;
227
230
  }
228
- throw error;
231
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.INTERNAL_SERVER_ERROR, _constants.HttpStatusMessage.INTERNAL_SERVER_ERROR, "Error during update password by hash");
229
232
  }
230
233
  return new Response(null, {
231
234
  status: _constants.HttpStatusCode.NO_CONTENT
@@ -1,6 +1,7 @@
1
1
  import type { Optional } from 'utility-types';
2
- import type { GuestRequest, LoginRequest, Oauth, RegisterRequest, RpcContext, RpcContextWithSession, UpdatePasswordByHashRequest } from '../../types';
3
- export declare function postLogin(context: RpcContextWithSession, tokens: Oauth): Promise<void>;
2
+ import type { GuestRequest, LoginRequest, Oauth, RegisterRequest, RpcContext, RpcContextWithSession, ShopUser, UpdatePasswordByHashRequest } from '../../types';
3
+ import { ErrorResponse } from '../../errors';
4
+ export declare function postLogin(context: RpcContextWithSession, tokens: Oauth): Promise<(ShopUser & ErrorResponse) | undefined>;
4
5
  export declare const oauthLogin: (login: Optional<LoginRequest, "shop_id">, context: RpcContext) => Promise<Response>;
5
6
  export declare const oauthRegister: (register: Optional<RegisterRequest, "shop_id">, context: RpcContext) => Promise<Response>;
6
7
  export declare const oauthGuestLogin: (guest: Optional<GuestRequest, "shop_id">, context: RpcContext) => Promise<Response>;
@@ -1,20 +1,34 @@
1
1
  import { decodeJwt } from "jose";
2
2
  import { assertSession } from "../../types/index.mjs";
3
- import { DEFAULT_WITH_LISTING, HttpStatusCode } from "../../constants/index.mjs";
3
+ import {
4
+ DEFAULT_WITH_LISTING,
5
+ HttpStatusCode,
6
+ HttpStatusMessage
7
+ } from "../../constants/index.mjs";
4
8
  import { FetchError } from "../../utils/fetch.mjs";
5
9
  import { mergeBaskets, mergeWishlists } from "../../utils/user.mjs";
6
10
  import { fetchUser } from "../../rpc/methods/user.mjs";
7
11
  import { unwrap } from "../../utils/response.mjs";
8
12
  import { getOAuthClient } from "../../api/oauth.mjs";
13
+ import { ErrorResponse } from "../../errors/index.mjs";
9
14
  const convertErrorForRpcCall = (error, httpStatuses) => {
10
15
  if (error instanceof FetchError && httpStatuses.includes(error.response.status)) {
11
- return new Response(null, { status: error.response.status });
16
+ return new ErrorResponse(
17
+ error.response.status,
18
+ error.response.statusText,
19
+ error.name
20
+ );
12
21
  }
13
22
  };
14
23
  export async function postLogin(context, tokens) {
15
- const user = await unwrap(
16
- fetchUser({ accessToken: tokens.access_token }, context)
24
+ const fetchUserResponse = await fetchUser(
25
+ { accessToken: tokens.access_token },
26
+ context
17
27
  );
28
+ if (fetchUserResponse instanceof ErrorResponse) {
29
+ return fetchUserResponse;
30
+ }
31
+ const user = await unwrap(fetchUserResponse);
18
32
  context.updateTokens({
19
33
  accessToken: tokens.access_token,
20
34
  refreshToken: tokens.refresh_token
@@ -48,27 +62,27 @@ export const oauthLogin = async (login, context) => {
48
62
  const shopId = context.shopId;
49
63
  const client = getOAuthClient(context);
50
64
  if (!login.email || !login.password) {
51
- throw new Error(
52
- "Login or password are missing, seems like validation has failed"
65
+ return new ErrorResponse(
66
+ HttpStatusCode.BAD_REQUEST,
67
+ HttpStatusMessage.BAD_REQUEST,
68
+ "Login or password are missing"
53
69
  );
54
70
  }
55
71
  try {
56
72
  const tokens = await client.login({ ...login, shop_id: shopId });
57
- await postLogin(context, tokens);
73
+ const postLoginResponse = await postLogin(context, tokens);
74
+ if (postLoginResponse instanceof ErrorResponse) {
75
+ return postLoginResponse;
76
+ }
77
+ return new Response(null, { status: HttpStatusCode.NO_CONTENT });
58
78
  } catch (error) {
59
- const res = convertErrorForRpcCall(error, [
79
+ context.log.error("OAuthClient.login failed", error);
80
+ return new ErrorResponse(
60
81
  HttpStatusCode.INTERNAL_SERVER_ERROR,
61
- HttpStatusCode.BAD_REQUEST,
62
- HttpStatusCode.UNAUTHORIZED,
63
- HttpStatusCode.NOT_FOUND,
64
- HttpStatusCode.FORBIDDEN
65
- ]);
66
- if (res) {
67
- return res;
68
- }
69
- throw error;
82
+ HttpStatusMessage.INTERNAL_SERVER_ERROR,
83
+ "Login failed"
84
+ );
70
85
  }
71
- return new Response(null, { status: HttpStatusCode.NO_CONTENT });
72
86
  };
73
87
  export const oauthRegister = async (register, context) => {
74
88
  assertSession(context);
@@ -79,20 +93,19 @@ export const oauthRegister = async (register, context) => {
79
93
  ...register,
80
94
  shop_id: shopId
81
95
  });
82
- await postLogin(context, tokens);
83
- } catch (error) {
84
- const res = convertErrorForRpcCall(error, [
85
- HttpStatusCode.BAD_REQUEST,
86
- HttpStatusCode.UNAUTHORIZED,
87
- HttpStatusCode.CONFLICT,
88
- HttpStatusCode.FORBIDDEN
89
- ]);
90
- if (res) {
91
- return res;
96
+ const postLoginResponse = await postLogin(context, tokens);
97
+ if (postLoginResponse instanceof ErrorResponse) {
98
+ return postLoginResponse;
92
99
  }
93
- throw error;
100
+ return new Response(null, { status: HttpStatusCode.NO_CONTENT });
101
+ } catch (error) {
102
+ context.log.error("OAuthClient.register failed", error);
103
+ return new ErrorResponse(
104
+ HttpStatusCode.INTERNAL_SERVER_ERROR,
105
+ HttpStatusMessage.INTERNAL_SERVER_ERROR,
106
+ "Register failed"
107
+ );
94
108
  }
95
- return new Response(null, { status: HttpStatusCode.NO_CONTENT });
96
109
  };
97
110
  export const oauthGuestLogin = async (guest, context) => {
98
111
  assertSession(context);
@@ -103,27 +116,30 @@ export const oauthGuestLogin = async (guest, context) => {
103
116
  ...guest,
104
117
  shop_id: shopId
105
118
  });
106
- await postLogin(context, tokens);
107
- } catch (error) {
108
- const res = convertErrorForRpcCall(error, [
109
- HttpStatusCode.BAD_REQUEST,
110
- HttpStatusCode.UNAUTHORIZED,
111
- HttpStatusCode.CONFLICT,
112
- HttpStatusCode.FORBIDDEN
113
- ]);
114
- if (res) {
115
- return res;
119
+ const postLoginResponse = await postLogin(context, tokens);
120
+ if (postLoginResponse instanceof ErrorResponse) {
121
+ return postLoginResponse;
116
122
  }
117
- throw error;
123
+ return new Response(null, { status: HttpStatusCode.NO_CONTENT });
124
+ } catch (error) {
125
+ context.log.error("OAuthClient.guestLogin failed", error);
126
+ return new ErrorResponse(
127
+ HttpStatusCode.INTERNAL_SERVER_ERROR,
128
+ HttpStatusMessage.INTERNAL_SERVER_ERROR,
129
+ "Guest login failed"
130
+ );
118
131
  }
119
- return new Response(null, { status: HttpStatusCode.NO_CONTENT });
120
132
  };
121
133
  export const refreshAccessToken = async (context) => {
122
134
  assertSession(context);
123
135
  const refreshToken = context.refreshToken;
124
136
  const client = getOAuthClient(context);
125
137
  if (!refreshToken) {
126
- throw new Error("No app refresh token provided");
138
+ return new ErrorResponse(
139
+ HttpStatusCode.BAD_REQUEST,
140
+ HttpStatusMessage.BAD_REQUEST,
141
+ "No refresh token present"
142
+ );
127
143
  }
128
144
  try {
129
145
  const tokens = await client.refreshToken({
@@ -150,7 +166,11 @@ export const oauthRevokeToken = async (context) => {
150
166
  assertSession(context);
151
167
  const accessToken = context.accessToken;
152
168
  if (!accessToken) {
153
- throw new Error("No app oauth authentication credentials");
169
+ return new ErrorResponse(
170
+ HttpStatusCode.UNAUTHORIZED,
171
+ HttpStatusMessage.UNAUTHORIZED,
172
+ "No access token present"
173
+ );
154
174
  }
155
175
  const user = context.user;
156
176
  const client = getOAuthClient(context);
@@ -181,7 +201,11 @@ export const oauthForgetPassword = async ({ email }, context) => {
181
201
  const client = getOAuthClient(context);
182
202
  try {
183
203
  if (!context.auth.resetPasswordUrl) {
184
- throw new Error("Missing password reset URL");
204
+ return new ErrorResponse(
205
+ HttpStatusCode.INTERNAL_SERVER_ERROR,
206
+ HttpStatusMessage.INTERNAL_SERVER_ERROR,
207
+ "Missing password reset URL"
208
+ );
185
209
  }
186
210
  const resetUrl = new URL(context.auth.resetPasswordUrl);
187
211
  if (!resetUrl.searchParams.has("hash")) {
@@ -231,7 +255,11 @@ export const updatePasswordByHash = async (passwordHash, context) => {
231
255
  if (res) {
232
256
  return res;
233
257
  }
234
- throw error;
258
+ return new ErrorResponse(
259
+ HttpStatusCode.INTERNAL_SERVER_ERROR,
260
+ HttpStatusMessage.INTERNAL_SERVER_ERROR,
261
+ "Error during update password by hash"
262
+ );
235
263
  }
236
264
  return new Response(null, { status: HttpStatusCode.NO_CONTENT });
237
265
  };
@@ -7,6 +7,7 @@ exports.removeItemFromWishlist = exports.getWishlist = exports.clearWishlist = e
7
7
  var _types = require("../../types/index.cjs");
8
8
  var _constants = require("../../constants/index.cjs");
9
9
  var _response = require("../../utils/response.cjs");
10
+ var _errors = require("../../errors/index.cjs");
10
11
  function getWithParams(params, context) {
11
12
  return params.with ?? context.withParams?.wishlist ?? _constants.MIN_WITH_PARAMS_WISHLIST;
12
13
  }
@@ -40,7 +41,7 @@ const addItemToWishlist = exports.addItemToWishlist = async function addItemToWi
40
41
  const resolvedWith = getWithParams(options, context);
41
42
  const pricePromotionKey = resolvedWith?.pricePromotionKey ?? "";
42
43
  if (!productId && !variantId) {
43
- throw new Error("No productId or variantId given");
44
+ return new _errors.ErrorResponse(_constants.HttpStatusCode.BAD_REQUEST, _constants.HttpStatusMessage.BAD_REQUEST, "No productId or variantId given");
44
45
  }
45
46
  const result = await bapiClient.wishlist.addItem(wishlistKey, variantId ? {
46
47
  variantId
@@ -82,7 +83,11 @@ const removeItemFromWishlist = exports.removeItemFromWishlist = async function r
82
83
  });
83
84
  };
84
85
  const clearWishlist = exports.clearWishlist = async function clearWishlist2(context) {
85
- const wishlist = await (0, _response.unwrap)(getWishlist({}, context));
86
+ const wishlistResponse = await getWishlist({}, context);
87
+ if (wishlistResponse instanceof _errors.ErrorResponse) {
88
+ return wishlistResponse;
89
+ }
90
+ const wishlist = await (0, _response.unwrap)(wishlistResponse);
86
91
  await Promise.all(wishlist.items.map(async item => {
87
92
  await removeItemFromWishlist({
88
93
  itemKey: item.key
@@ -1,6 +1,11 @@
1
1
  import { assertSession } from "../../types/index.mjs";
2
- import { MIN_WITH_PARAMS_WISHLIST } from "../../constants/index.mjs";
2
+ import {
3
+ HttpStatusCode,
4
+ HttpStatusMessage,
5
+ MIN_WITH_PARAMS_WISHLIST
6
+ } from "../../constants/index.mjs";
3
7
  import { unwrap } from "../../utils/response.mjs";
8
+ import { ErrorResponse } from "../../errors/index.mjs";
4
9
  function getWithParams(params, context) {
5
10
  return params.with ?? context.withParams?.wishlist ?? MIN_WITH_PARAMS_WISHLIST;
6
11
  }
@@ -21,7 +26,11 @@ export const addItemToWishlist = async function addItemToWishlist2(options, cont
21
26
  const resolvedWith = getWithParams(options, context);
22
27
  const pricePromotionKey = resolvedWith?.pricePromotionKey ?? "";
23
28
  if (!productId && !variantId) {
24
- throw new Error("No productId or variantId given");
29
+ return new ErrorResponse(
30
+ HttpStatusCode.BAD_REQUEST,
31
+ HttpStatusMessage.BAD_REQUEST,
32
+ "No productId or variantId given"
33
+ );
25
34
  }
26
35
  const result = await bapiClient.wishlist.addItem(
27
36
  wishlistKey,
@@ -50,7 +59,11 @@ export const removeItemFromWishlist = async function removeItemFromWishlist2(opt
50
59
  });
51
60
  };
52
61
  export const clearWishlist = async function clearWishlist2(context) {
53
- const wishlist = await unwrap(getWishlist({}, context));
62
+ const wishlistResponse = await getWishlist({}, context);
63
+ if (wishlistResponse instanceof ErrorResponse) {
64
+ return wishlistResponse;
65
+ }
66
+ const wishlist = await unwrap(wishlistResponse);
54
67
  await Promise.all(
55
68
  wishlist.items.map(async (item) => {
56
69
  await removeItemFromWishlist({ itemKey: item.key }, context);
@@ -9,9 +9,10 @@ const wait = ms => {
9
9
  };
10
10
  exports.wait = wait;
11
11
  const timeout = (ms, promise) => {
12
- const breaker = new Promise((_resolve, reject) => {
13
- setTimeout(() => reject(new Error("timeout")), ms);
14
- });
15
- return Promise.race([promise, breaker]);
12
+ let pendingTimeout;
13
+ return new Promise((resolve, reject) => {
14
+ pendingTimeout = setTimeout(() => reject(new Error("timeout")), ms);
15
+ promise.then(resolve, reject);
16
+ }).finally(() => clearTimeout(pendingTimeout));
16
17
  };
17
18
  exports.timeout = timeout;
@@ -1,2 +1,2 @@
1
1
  export declare const wait: (ms: number) => Promise<unknown>;
2
- export declare const timeout: (ms: number, promise: Promise<any>) => Promise<any>;
2
+ export declare const timeout: <T>(ms: number, promise: Promise<T>) => Promise<T>;
@@ -2,8 +2,9 @@ export const wait = (ms) => {
2
2
  return new Promise((resolve) => setTimeout(resolve, ms));
3
3
  };
4
4
  export const timeout = (ms, promise) => {
5
- const breaker = new Promise((_resolve, reject) => {
6
- setTimeout(() => reject(new Error("timeout")), ms);
7
- });
8
- return Promise.race([promise, breaker]);
5
+ let pendingTimeout;
6
+ return new Promise((resolve, reject) => {
7
+ pendingTimeout = setTimeout(() => reject(new Error("timeout")), ms);
8
+ promise.then(resolve, reject);
9
+ }).finally(() => clearTimeout(pendingTimeout));
9
10
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scayle/storefront-core",
3
- "version": "7.59.1",
3
+ "version": "7.60.0",
4
4
  "description": "Collection of essential utilities to work with the Storefront API",
5
5
  "author": "SCAYLE Commerce Engine",
6
6
  "license": "MIT",
@@ -59,7 +59,7 @@
59
59
  "test:ci": "vitest --run --passWithNoTests --coverage --reporter=default --reporter=junit"
60
60
  },
61
61
  "dependencies": {
62
- "@scayle/storefront-api": "17.4.0",
62
+ "@scayle/storefront-api": "17.4.1",
63
63
  "crypto-js": "^4.2.0",
64
64
  "hookable": "^5.5.3",
65
65
  "jose": "^5.6.3",
@@ -72,19 +72,19 @@
72
72
  "devDependencies": {
73
73
  "@scayle/eslint-config-storefront": "4.2.0",
74
74
  "@types/crypto-js": "4.2.2",
75
- "@types/node": "20.14.10",
75
+ "@types/node": "20.14.11",
76
76
  "@types/webpack-env": "1.18.5",
77
- "@vitest/coverage-v8": "2.0.2",
77
+ "@vitest/coverage-v8": "2.0.3",
78
78
  "dprint": "0.47.2",
79
- "eslint": "9.6.0",
79
+ "eslint": "9.7.0",
80
80
  "eslint-formatter-gitlab": "5.1.0",
81
- "publint": "0.2.8",
81
+ "publint": "0.2.9",
82
82
  "rimraf": "6.0.1",
83
83
  "ts-node": "10.9.2",
84
84
  "typescript": "5.5.3",
85
85
  "unbuild": "2.0.0",
86
86
  "unstorage": "1.10.2",
87
- "vitest": "2.0.2"
87
+ "vitest": "2.0.3"
88
88
  },
89
89
  "optionalDependencies": {
90
90
  "redis": "4"