@scayle/storefront-core 8.6.1 → 8.7.1

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 (41) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/api/customer.d.ts +73 -0
  3. package/dist/api/customer.mjs +59 -0
  4. package/dist/api/oauth.d.ts +62 -12
  5. package/dist/api/oauth.mjs +51 -15
  6. package/dist/cache/cache.d.ts +47 -0
  7. package/dist/cache/cached.d.ts +93 -0
  8. package/dist/cache/cached.mjs +62 -0
  9. package/dist/cache/providers/unstorage.d.ts +64 -0
  10. package/dist/cache/providers/unstorage.mjs +64 -0
  11. package/dist/constants/cache.d.ts +4 -0
  12. package/dist/constants/hash.d.ts +4 -0
  13. package/dist/constants/hash.mjs +1 -0
  14. package/dist/constants/httpStatus.d.ts +12 -2
  15. package/dist/constants/httpStatus.mjs +2 -2
  16. package/dist/constants/product.d.ts +3 -0
  17. package/dist/constants/promotion.d.ts +6 -0
  18. package/dist/constants/sorting.d.ts +6 -0
  19. package/dist/constants/withParameters.d.ts +28 -0
  20. package/dist/errors/errorResponse.d.ts +37 -0
  21. package/dist/errors/errorResponse.mjs +14 -0
  22. package/dist/helpers/filterHelper.mjs +1 -1
  23. package/dist/index.d.ts +48 -0
  24. package/dist/rpc/methods/checkout/checkout.mjs +1 -1
  25. package/dist/test/factories/index.d.ts +1 -0
  26. package/dist/test/factories/index.mjs +1 -0
  27. package/dist/test/factories/user.d.ts +3 -0
  28. package/dist/test/factories/user.mjs +16 -0
  29. package/dist/types/api/context.d.ts +1 -1
  30. package/dist/utils/basket.d.ts +23 -0
  31. package/dist/utils/fetch.d.ts +21 -2
  32. package/dist/utils/hash.d.ts +67 -0
  33. package/dist/utils/hash.mjs +3 -3
  34. package/dist/utils/keys.d.ts +38 -0
  35. package/dist/utils/log.d.ts +77 -8
  36. package/dist/utils/log.mjs +61 -6
  37. package/dist/utils/response.d.ts +8 -3
  38. package/dist/utils/sapi.d.ts +10 -2
  39. package/dist/utils/timeout.d.ts +18 -0
  40. package/dist/utils/user.d.ts +22 -0
  41. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -6,15 +6,63 @@ export * from './constants';
6
6
  export * from './cache';
7
7
  export * from './helpers';
8
8
  export * from './types';
9
+ /**
10
+ * Core RPC methods available within `@scayle/storefront-core`.
11
+ */
9
12
  type RpcMethodsCore = typeof rpcMethods;
13
+ /**
14
+ * Interface for extending RPC methods within `@scayle/storefront-core`. Allows custom RPC methods
15
+ * to be added to the SCAYLE Storefront application by extending this interface.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // nuxt.config.ts
20
+ * import * as customRpcMethods from './rpc'
21
+ * declare module '@scayle/storefront-core' {
22
+ * export interface RpcMethodsStorefrontInternal extends typeof customRpcMethods {}
23
+ * }
24
+ * ```
25
+ */
10
26
  export interface RpcMethodsStorefrontInternal {
11
27
  }
28
+ /**
29
+ * Combined RPC methods, merging core methods with SCAYLE Storefront application extensions.
30
+ * Extensions from `@scayle/storefront-core` take precedence in case of naming conflicts.
31
+ */
12
32
  export type RpcMethods = {
13
33
  [Key in keyof RpcMethodsCore | keyof RpcMethodsStorefrontInternal]: Key extends keyof RpcMethodsStorefrontInternal ? RpcMethodsStorefrontInternal[Key] : Key extends keyof RpcMethodsCore ? RpcMethodsCore[Key] : never;
14
34
  };
35
+ /**
36
+ * Type alias representing the name of an RPC method. This uses a
37
+ * resolution technique to avoid inlining method names in compiled
38
+ * type declarations, which is essential for supporting dynamically
39
+ * added RPC methods from the SCAYLE Storefront application.
40
+ *
41
+ * @see https://github.com/microsoft/TypeScript/pull/42149#issuecomment-865385560
42
+ * @
43
+ * Without this workaround, the signature to `rpcCall` looks something like
44
+ * `rpcCall(m: 'addItemToBasket' | 'addItemToWishlist'...)`.
45
+ * But we need it to look like `rpcCall(m: RpcMethodName)` in order to include
46
+ * RPC methods added by the SCAYLE Storefront application.
47
+ */
15
48
  type Resolve<T> = T extends T ? T : never;
16
49
  export type RpcMethodName = Resolve<keyof RpcMethods>;
50
+ /**
51
+ * Describes the type of a specific RPC method by its name.
52
+ *
53
+ * @template N The name of the RPC method.
54
+ */
17
55
  export type RpcMethod<N extends RpcMethodName> = RpcMethods[N];
56
+ /**
57
+ * Describes the type of the parameters for a specific RPC method.
58
+ *
59
+ * @template N The name of the RPC method.
60
+ */
18
61
  export type RpcMethodParameters<N extends RpcMethodName> = Parameters<RpcMethod<N>>[0];
62
+ /**
63
+ * Describes the return type of a specific RPC method.
64
+ *
65
+ * @template N The name of the RPC method.
66
+ */
19
67
  export type RpcMethodReturnType<N extends RpcMethodName> = ReturnType<RpcMethod<N>>;
20
68
  export { ExistingItemHandling, AddToBasketFailureKind, UpdateBasketItemFailureKind, AddToWishlistFailureKind, PromotionEffectType, FilterTypes, APISortOption, APISortOrder, type ProductSortConfig, } from '@scayle/storefront-api';
@@ -35,7 +35,7 @@ export const getCheckoutToken = async function getCheckoutToken2(jwtPayload = {}
35
35
  carrier,
36
36
  basketId: context.basketKey,
37
37
  campaignKey: context.campaignKey
38
- }).setIssuedAt(now).setNotBefore(now).setExpirationTime("1h").setIssuer(`${"@scayle/storefront-core"}@${"8.6.1"}`).setProtectedHeader({ alg: "HS256", typ: "JWT" }).sign(secret);
38
+ }).setIssuedAt(now).setNotBefore(now).setExpirationTime("1h").setIssuer(`${"@scayle/storefront-core"}@${"8.7.1"}`).setProtectedHeader({ alg: "HS256", typ: "JWT" }).sign(secret);
39
39
  return {
40
40
  accessToken: refreshedAccessToken,
41
41
  checkoutJwt
@@ -1 +1,2 @@
1
1
  export * from '@scayle/storefront-api/dist/test/factories';
2
+ export * from './user';
@@ -1 +1,2 @@
1
1
  export * from "@scayle/storefront-api/dist/test/factories";
2
+ export * from "./user.mjs";
@@ -0,0 +1,3 @@
1
+ import { Factory } from 'fishery';
2
+ import type { ShopUser } from '../../types';
3
+ export declare const userFactory: Factory<ShopUser, any, ShopUser>;
@@ -0,0 +1,16 @@
1
+ import { Factory } from "fishery";
2
+ export const userFactory = Factory.define(() => ({
3
+ id: 1,
4
+ app_id: 1,
5
+ completed_orders: 0,
6
+ createdAt: "2024-12-12T09:08:06+01:00",
7
+ updatedAt: "2025-02-14T07:29:05+01:00",
8
+ email: "user@example.org",
9
+ firstName: "John",
10
+ lastName: "Neil",
11
+ gender: "n",
12
+ publicKey: "test-public-key",
13
+ referenceKey: "test-ref-key",
14
+ isGuest: false,
15
+ isReturningCustomer: false
16
+ }));
@@ -75,7 +75,7 @@ export type RpcContext = {
75
75
  sapiClient: StorefrontAPIClient;
76
76
  cached: CachedType;
77
77
  shopId: number;
78
- domain: string;
78
+ domain?: string;
79
79
  withParams?: WithParams;
80
80
  campaignKey?: string;
81
81
  destroySessionsForUserId: (userId: number, sessionsToKeep?: string[]) => Promise<void>;
@@ -1,2 +1,25 @@
1
1
  import type { AddOrUpdateItemError } from '@scayle/storefront-api';
2
+ /**
3
+ * Checks if all basket add/update errors indicate that items were added with reduced quantity.
4
+ * This function helps determine if a basket operation partially succeeded, meaning some items were added but with a lower quantity than requested.
5
+ *
6
+ * @param errors An array of `AddOrUpdateItemError` objects, typically returned from a basket add/update operation.
7
+ * @returns `true` if all errors indicate reduced quantity, `false` otherwise (including when the `errors` array is empty, null, or undefined).
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const errors: AddOrUpdateItemError[] = [
12
+ * { operation: 'add', kind: AddToBasketFailureKind.ITEM_ADDED_WITH_REDUCED_QUANTITY, variantId: 123 },
13
+ * { operation: 'update', kind: UpdateBasketItemFailureKind.ITEM_ADDED_WITH_REDUCED_QUANTITY, variantId: 456 },
14
+ * ]
15
+ *
16
+ * const allReducedQuantity = wasAddedWithReducedQuantity(errors) // true
17
+ *
18
+ * const noErrors = wasAddedWithReducedQuantity() // false
19
+ *
20
+ * const otherErrors = wasAddedWithReducedQuantity([
21
+ * { operation: 'add', kind: AddToBasketFailureKind.ITEM_NOT_FOUND, variantId: 789 },
22
+ * ]) // false
23
+ * ```
24
+ */
2
25
  export declare const wasAddedWithReducedQuantity: (errors?: AddOrUpdateItemError[]) => boolean;
@@ -1,6 +1,25 @@
1
1
  /**
2
- * A custom Error type for errors that occur in a fetch() request
3
- * Contains the Response object from the request, and optionally the response data
2
+ * A custom Error type for errors that occur during a `fetch()` request.
3
+ * Includes the `Response` object and optional response data for more detailed error analysis.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * try {
8
+ * const response = await fetch('/some/url')
9
+ *
10
+ * if (!response.ok) {
11
+ * const data = await response.json(); // Attempt to parse JSON error data
12
+ * throw new FetchError(response, data)
13
+ * }
14
+ * // ... process successful response
15
+ * } catch (error) {
16
+ * if (error instanceof FetchError) {
17
+ * console.error("Fetch error:", error.message, error.response.status, error.data)
18
+ * } else {
19
+ * console.error("Other error:", error)
20
+ * }
21
+ * }
22
+ * ```
4
23
  */
5
24
  export declare class FetchError extends Error {
6
25
  response: Response;
@@ -1,8 +1,75 @@
1
+ /**
2
+ * Calculates the MD5 hash of a string.
3
+ * Uses `CryptoJS` for MD5 calculation. Throws an error if MD5 support is omitted in the build.
4
+ *
5
+ * @see https://cryptojs.gitbook.io/docs/
6
+ *
7
+ * @param value The string to hash.
8
+ *
9
+ * @returns A Promise that resolves with the MD5 hash as a hex string.
10
+ *
11
+ * @throws {Error} If SFC is built without MD5 support (SFC_OMIT_MD5 environment variable is set).
12
+ */
1
13
  export declare const md5: (value: string) => Promise<any>;
14
+ /**
15
+ * Calculates the SHA256 hash of a string.
16
+ *
17
+ * @param value The input string.
18
+ *
19
+ * @returns A Promise that resolves with the SHA256 hash as a hexadecimal string.
20
+ */
2
21
  export declare const sha256: (value: string) => Promise<string>;
22
+ /**
23
+ * Calculates the HMAC (Hash-based Message Authentication Code) of a string.
24
+ *
25
+ * @param value The input string (message).
26
+ * @param secret The secret key.
27
+ * @param algorithm The hashing algorithm to use (e.g., 'SHA-256'). Defaults to 'SHA-256'.
28
+ *
29
+ * @returns A Promise that resolves with the HMAC as a hexadecimal string.
30
+ */
3
31
  export declare const hmac: (value: string, secret: string, algorithm?: string) => Promise<string>;
32
+ /**
33
+ * Encodes a string to Base64. Works in both Node.js and browser environments.
34
+ *
35
+ * @param string The string to encode.
36
+ *
37
+ * @returns The Base64 encoded string.
38
+ */
4
39
  export declare const encodeBase64: (string: string) => string;
40
+ /**
41
+ * Decodes a Base64 encoded string. Works in both Node.js and browser environments.
42
+ *
43
+ * @param string The Base64 encoded string.
44
+ *
45
+ * @returns The decoded string.
46
+ */
5
47
  export declare const decodeBase64: (string: string) => string;
48
+ /**
49
+ * Verifies an order success token by comparing its signature with an expected signature.
50
+ *
51
+ * @template T The type of the parsed payload.
52
+ *
53
+ * @param token The token to verify.
54
+ * @param secret The secret key used to generate the signature.
55
+ *
56
+ * @returns A Promise resolving to the parsed token payload if the signature is valid, or undefined otherwise.
57
+ */
6
58
  export declare const verifyOrderSuccessToken: <T = unknown>(token: string, secret: string) => Promise<T | undefined>;
59
+ /**
60
+ * Builds a hash payload by stringifying and Base64 encoding a given payload.
61
+ *
62
+ * @param payload The payload to hash.
63
+ *
64
+ * @returns The Base64 encoded hash payload.
65
+ */
7
66
  export declare const buildHashPayload: (payload: unknown) => string;
67
+ /**
68
+ * Builds a signature for a given payload hash and secret.
69
+ *
70
+ * @param payloadHash The hash of the payload.
71
+ * @param secret The secret key.
72
+ *
73
+ * @returns A Promise resolving to the Base64 encoded signature.
74
+ */
8
75
  export declare const buildSignature: (payloadHash: string, secret: string) => Promise<string>;
@@ -56,10 +56,10 @@ export const decodeBase64 = (string) => {
56
56
  export const verifyOrderSuccessToken = async (token, secret) => {
57
57
  const [encodedPayload, signature] = token.split(".", 2);
58
58
  const expectedSignature = encodeBase64(await hmac(encodedPayload, secret));
59
- if (expectedSignature === signature) {
60
- return JSON.parse(decodeBase64(encodedPayload));
59
+ if (expectedSignature !== signature) {
60
+ return;
61
61
  }
62
- return void 0;
62
+ return JSON.parse(decodeBase64(encodedPayload));
63
63
  };
64
64
  export const buildHashPayload = (payload) => encodeBase64(JSON.stringify(payload));
65
65
  export const buildSignature = async (payloadHash, secret) => encodeBase64(await hmac(payloadHash, secret));
@@ -1,6 +1,20 @@
1
1
  import type { Log } from '..';
2
2
  import { HashAlgorithm } from '../constants/hash';
3
+ /**
4
+ * Generates a key based on a template, shop ID, user ID, and optional hash algorithm.
5
+ *
6
+ * @param params The required asynchronous function parameters.
7
+ * @param params.keyName Deprecated and unused value to specify the name of a key.
8
+ * @param params.keyTemplate The template string for the key, which can include placeholders for `shopId` and `userId`.
9
+ * @param params.hashAlgorithm The hash algorithm to use (MD5, SHA256, or none). Defaults to SHA256.
10
+ * @param params.shopId The shop ID.
11
+ * @param params.userId The user ID.
12
+ * @param params.log Optional logger instance.
13
+ *
14
+ * @returns A Promise resolving to the generated key.
15
+ */
3
16
  export declare const generateKey: ({ keyTemplate, hashAlgorithm, shopId, userId, log, }: {
17
+ /** @deprecated */
4
18
  keyName?: string;
5
19
  keyTemplate: string;
6
20
  hashAlgorithm: HashAlgorithm;
@@ -8,6 +22,18 @@ export declare const generateKey: ({ keyTemplate, hashAlgorithm, shopId, userId,
8
22
  userId: string;
9
23
  log?: Log;
10
24
  }) => Promise<string>;
25
+ /**
26
+ * Generates a wishlist key.
27
+ *
28
+ * @param params The required asynchronous function parameters.
29
+ * @param params.keyTemplate The template string for the key.
30
+ * @param params.hashAlgorithm The hash algorithm to use. Defaults to SHA256.
31
+ * @param params.shopId The shop ID.
32
+ * @param params.userId The user ID.
33
+ * @param params.log Optional logger instance.
34
+ *
35
+ * @returns A Promise resolving to the generated wishlist key.
36
+ */
11
37
  export declare const generateWishlistKey: ({ keyTemplate, hashAlgorithm, shopId, userId, log, }: {
12
38
  keyTemplate: string;
13
39
  hashAlgorithm: HashAlgorithm;
@@ -15,6 +41,18 @@ export declare const generateWishlistKey: ({ keyTemplate, hashAlgorithm, shopId,
15
41
  userId: string;
16
42
  log?: Log;
17
43
  }) => Promise<string>;
44
+ /**
45
+ * Generates a basket key.
46
+ *
47
+ * @param params The required asynchronous function parameters.
48
+ * @param params.keyTemplate The template string for the key.
49
+ * @param params.hashAlgorithm The hash algorithm to use. Defaults to SHA256.
50
+ * @param params.shopId The shop ID.
51
+ * @param params.userId The user ID.
52
+ * @param params.log Optional logger instance.
53
+ *
54
+ * @returns A Promise resolving to the generated basket key.
55
+ */
18
56
  export declare const generateBasketKey: ({ keyTemplate, hashAlgorithm, shopId, userId, log, }: {
19
57
  keyTemplate: string;
20
58
  hashAlgorithm: HashAlgorithm;
@@ -1,43 +1,112 @@
1
+ /**
2
+ * Represents a log level.
3
+ */
1
4
  export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
5
+ /**
6
+ * Represents a single log entry.
7
+ */
2
8
  export interface LogEntry {
3
9
  level: LogLevel;
4
10
  space: string;
5
11
  message: string;
6
12
  data?: object;
7
13
  }
14
+ /**
15
+ * A function that handles log entries.
16
+ *
17
+ * @param entry The log entry to handle.
18
+ */
8
19
  export type LogHandler = (entry: LogEntry) => void;
20
+ /**
21
+ * Options for configuring the logger.
22
+ */
9
23
  export interface LogOptions {
10
24
  handler?: LogHandler;
11
25
  space: string;
12
26
  }
13
27
  /**
14
- * This log provides a way to log messages to a custom log handler (in a serial manner).
15
- * If no handler is provided, it will log to the console.
28
+ * A logger that provides structured logging with namespaces.
29
+ * Supports custom log handlers or if no handler is provided, logging to the console.
16
30
  */
17
31
  export declare class Log {
32
+ /**
33
+ * The default log instance, logging to the console with the `global` namespace.
34
+ */
18
35
  static readonly default: Log;
19
36
  _handler?: LogHandler;
20
37
  _space: string;
21
38
  _type: string;
39
+ /**
40
+ * Creates a new Log instance.
41
+ *
42
+ * @param options Options for the logger.
43
+ */
22
44
  constructor(options?: LogOptions);
45
+ /**
46
+ * Logs a debug message.
47
+ *
48
+ * @param message The debug message.
49
+ * @param data Optional additional data.
50
+ */
23
51
  debug(message: string, data?: any): void;
52
+ /**
53
+ * Logs an informational message.
54
+ *
55
+ * @param message The informational message.
56
+ * @param data Optional additional data.
57
+ */
24
58
  info(message: string, data?: any): void;
59
+ /**
60
+ * Logs a warning message.
61
+ *
62
+ * @param message The warning message.
63
+ * @param data Optional additional data.
64
+ */
25
65
  warn(message: string, data?: any): void;
66
+ /**
67
+ * Logs an error message.
68
+ *
69
+ * @param message The error message or an Error object.
70
+ * @param data Optional additional data.
71
+ */
26
72
  error(message: string | Error, data?: any): void;
73
+ /**
74
+ * Writes a log entry.
75
+ *
76
+ * @param level The log level.
77
+ * @param message The log message.
78
+ * @param data Optional additional data.
79
+ */
27
80
  write(level: LogLevel, message: string, data?: any): void;
28
81
  /**
29
- * Create a new sub-space.
30
- * All spaces are being separated by a dot. E.g. `global.api` and `global.api.getUser`
31
- * @param subSpace The name of the sub-space in camel-case (e.g. `api` and `api.getUser`)
82
+ * Creates a new Log instance with a sub-namespace.
83
+ * Namespaces are separated by dots (e.g., "global.api.getUser").
84
+ *
85
+ * @param subSpace The sub-namespace to add in camel-case (e.g. `api` and `api.getUser`)
86
+ *
87
+ * @returns A new Log instance with the updated namespace.
32
88
  */
33
89
  space(subSpace: string): Log;
34
90
  /**
35
- * Measure the time of a function.
91
+ * Measures the execution time of an asynchronous function and logs a debug message.
92
+ *
93
+ * @param message A message to include in the log output.
94
+ * @param func The asynchronous function to time.
95
+ *
96
+ * @returns A Promise that resolves with the result of the timed function.
36
97
  */
37
98
  time(message: string, func: () => any): Promise<any>;
38
99
  /**
39
- * Attach the log to the request object: `req.$log`.
40
- * This function should be called in a server middleware before storefront-core is initialized.
100
+ * Attaches the log instance to a request object.
101
+ * This is typically used in server middleware.
102
+ *
103
+ * @param req The request object.
104
+ * @param log The Log instance to attach.
105
+ *
106
+ * @example
107
+ * Log.attachToRequest(req, new Log({ space: 'myModule' }))
108
+ *
109
+ * @deprecated
41
110
  */
42
111
  static attachToRequest(req: any, log: Log): void;
43
112
  }
@@ -1,4 +1,7 @@
1
1
  export class Log {
2
+ /**
3
+ * The default log instance, logging to the console with the `global` namespace.
4
+ */
2
5
  static default = new this({
3
6
  space: "global",
4
7
  handler: consoleLogHandler
@@ -6,19 +9,48 @@ export class Log {
6
9
  _handler;
7
10
  _space;
8
11
  _type = "log";
12
+ /**
13
+ * Creates a new Log instance.
14
+ *
15
+ * @param options Options for the logger.
16
+ */
9
17
  constructor(options) {
10
18
  this._handler = options?.handler || Log.default._handler;
11
19
  this._space = options?.space || Log.default._space;
12
20
  }
21
+ /**
22
+ * Logs a debug message.
23
+ *
24
+ * @param message The debug message.
25
+ * @param data Optional additional data.
26
+ */
13
27
  debug(message, data) {
14
28
  this.write("debug", message, data);
15
29
  }
30
+ /**
31
+ * Logs an informational message.
32
+ *
33
+ * @param message The informational message.
34
+ * @param data Optional additional data.
35
+ */
16
36
  info(message, data) {
17
37
  this.write("info", message, data);
18
38
  }
39
+ /**
40
+ * Logs a warning message.
41
+ *
42
+ * @param message The warning message.
43
+ * @param data Optional additional data.
44
+ */
19
45
  warn(message, data) {
20
46
  this.write("warn", message, data);
21
47
  }
48
+ /**
49
+ * Logs an error message.
50
+ *
51
+ * @param message The error message or an Error object.
52
+ * @param data Optional additional data.
53
+ */
22
54
  error(message, data) {
23
55
  const error = message instanceof Error ? message : null;
24
56
  if (error) {
@@ -29,6 +61,13 @@ export class Log {
29
61
  }
30
62
  this.write("error", error?.message ?? message, data);
31
63
  }
64
+ /**
65
+ * Writes a log entry.
66
+ *
67
+ * @param level The log level.
68
+ * @param message The log message.
69
+ * @param data Optional additional data.
70
+ */
32
71
  write(level, message, data) {
33
72
  if (typeof data !== "undefined") {
34
73
  data = typeof data !== "object" ? { data } : data;
@@ -41,9 +80,12 @@ export class Log {
41
80
  }
42
81
  }
43
82
  /**
44
- * Create a new sub-space.
45
- * All spaces are being separated by a dot. E.g. `global.api` and `global.api.getUser`
46
- * @param subSpace The name of the sub-space in camel-case (e.g. `api` and `api.getUser`)
83
+ * Creates a new Log instance with a sub-namespace.
84
+ * Namespaces are separated by dots (e.g., "global.api.getUser").
85
+ *
86
+ * @param subSpace The sub-namespace to add in camel-case (e.g. `api` and `api.getUser`)
87
+ *
88
+ * @returns A new Log instance with the updated namespace.
47
89
  */
48
90
  space(subSpace) {
49
91
  return new Log({
@@ -52,7 +94,12 @@ export class Log {
52
94
  });
53
95
  }
54
96
  /**
55
- * Measure the time of a function.
97
+ * Measures the execution time of an asynchronous function and logs a debug message.
98
+ *
99
+ * @param message A message to include in the log output.
100
+ * @param func The asynchronous function to time.
101
+ *
102
+ * @returns A Promise that resolves with the result of the timed function.
56
103
  */
57
104
  async time(message, func) {
58
105
  const start = Date.now();
@@ -62,8 +109,16 @@ export class Log {
62
109
  return result;
63
110
  }
64
111
  /**
65
- * Attach the log to the request object: `req.$log`.
66
- * This function should be called in a server middleware before storefront-core is initialized.
112
+ * Attaches the log instance to a request object.
113
+ * This is typically used in server middleware.
114
+ *
115
+ * @param req The request object.
116
+ * @param log The Log instance to attach.
117
+ *
118
+ * @example
119
+ * Log.attachToRequest(req, new Log({ space: 'myModule' }))
120
+ *
121
+ * @deprecated
67
122
  */
68
123
  static attachToRequest(req, log) {
69
124
  req.$log = log;
@@ -1,6 +1,11 @@
1
1
  /**
2
- * Unwrap a possible response into its body
3
- * @param res
4
- * @returns unwrapped response
2
+ * Unwraps a value that might be a `Response` object or a direct value. If it's a `Response`,
3
+ * it parses the JSON body and returns it; otherwise, it returns the value directly.
4
+ *
5
+ * @template T The expected type of the unwrapped value.
6
+ *
7
+ * @param res The value to unwrap, which can be a `Promise`, `Response`, or a direct value.
8
+ *
9
+ * @returns A Promise resolving to the unwrapped value.
5
10
  */
6
11
  export declare function unwrap<T>(res: Promise<Response | T> | Response | T): Promise<T>;
@@ -1,5 +1,13 @@
1
1
  /**
2
- * Wrap a SAPI API function, catching any SAPI FetchErrors thrown
3
- * and translating them to a Response return
2
+ * Wraps a SAPI API function, catching SAPI FetchErrors and converting them to a structured Response.
3
+ * This allows handling SAPI errors in a consistent way, returning a JSON response with status information.
4
+ *
5
+ * @template T The type of the SAPI API function.
6
+ *
7
+ * @param func The SAPI API function to wrap.
8
+ *
9
+ * @returns A wrapped function that returns a Promise resolving to either the original function's result or a JSON Response representing the error.
10
+ *
11
+ * @throws Re-throws any error that is not an instance of FetchError.
4
12
  */
5
13
  export declare function mapSAPIFetchErrorToResponse<T extends (...args: any) => any>(func: T): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>> | Response>;
@@ -1,2 +1,20 @@
1
+ /**
2
+ * Pauses execution for a specified number of milliseconds.
3
+ *
4
+ * @param ms The number of milliseconds to wait.
5
+ *
6
+ * @returns A Promise that resolves after the specified delay.
7
+ */
1
8
  export declare const wait: (ms: number) => Promise<unknown>;
9
+ /**
10
+ * Wraps a promise with a timeout. Rejects the promise if it doesn't resolve within the given time.
11
+ *
12
+ * @template T The type of the promise's resolved value.
13
+ * @param ms The timeout duration in milliseconds.
14
+ * @param promise The promise to wrap.
15
+ *
16
+ * @returns A new promise that resolves or rejects based on the original promise or the timeout.
17
+ *
18
+ * @throws {Error} If the promise times out. The error message will be "timeout".
19
+ */
2
20
  export declare const timeout: <T>(ms: number, promise: Promise<T>) => Promise<T>;
@@ -1,4 +1,15 @@
1
1
  import type { BasketWithOptions, RpcContext } from '../types';
2
+ /**
3
+ * Merges two baskets. Adds the items from the `fromBasketKey` basket to the `toBasketKey` basket
4
+ * and then clears the `fromBasketKey` basket. Handles existing items by adding quantities.
5
+ *
6
+ * @param fromBasketKey The key of the source basket.
7
+ * @param toBasketKey The key of the destination basket.
8
+ * @param withOptions Options for retrieving basket data (including custom and order data).
9
+ * @param context The RPC context.
10
+ *
11
+ * @returns The merged basket.
12
+ */
2
13
  export declare const mergeBaskets: (fromBasketKey: string, toBasketKey: string, withOptions: BasketWithOptions & {
3
14
  orderCustomData?: Record<string, unknown>;
4
15
  }, context: RpcContext) => Promise<{
@@ -13,4 +24,15 @@ export declare const mergeBaskets: (fromBasketKey: string, toBasketKey: string,
13
24
  readonly basket: import("@scayle/storefront-api").BasketResponseData<import("@scayle/storefront-api").Product, import("@scayle/storefront-api").Variant>;
14
25
  readonly errors: import("@scayle/storefront-api").AddOrUpdateItemError[];
15
26
  } | undefined>;
27
+ /**
28
+ * Merges two wishlists. Adds the items from the `fromWishlistKey` wishlist to the `toWishlistKey` wishlist
29
+ * and then clears the `fromWishlistKey` wishlist.
30
+ *
31
+ * @param fromWishlistKey The key of the source wishlist.
32
+ * @param toWishlistKey The key of the destination wishlist.
33
+ * @param withOptions Options for retrieving wishlist data.
34
+ * @param context The RPC context.
35
+ *
36
+ * @returns Nothing (resolves when the merge operation is complete).
37
+ */
16
38
  export declare const mergeWishlists: (fromWishlistKey: string, toWishlistKey: string, withOptions: BasketWithOptions, context: RpcContext) => Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scayle/storefront-core",
3
- "version": "8.6.1",
3
+ "version": "8.7.1",
4
4
  "description": "Collection of essential utilities to work with the Storefront API",
5
5
  "author": "SCAYLE Commerce Engine",
6
6
  "license": "MIT",