@commercetools/connect-payments-sdk 0.0.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 (68) hide show
  1. package/.github/workflows/ci.yml +34 -0
  2. package/.github/workflows/release.yml +46 -0
  3. package/.husky/pre-commit +4 -0
  4. package/CHANGELOG.md +7 -0
  5. package/README.md +19 -0
  6. package/dist/api/context/request-context.provider.d.ts +14 -0
  7. package/dist/api/context/request-context.provider.js +21 -0
  8. package/dist/api/context/types/request-context.type.d.ts +16 -0
  9. package/dist/api/context/types/request-context.type.js +2 -0
  10. package/dist/api/handlers/config.handler.d.ts +4 -0
  11. package/dist/api/handlers/config.handler.js +10 -0
  12. package/dist/api/handlers/status.handler.d.ts +25 -0
  13. package/dist/api/handlers/status.handler.js +73 -0
  14. package/dist/api/handlers/types/handler.type.d.ts +5 -0
  15. package/dist/api/handlers/types/handler.type.js +2 -0
  16. package/dist/api/hooks/session-auth.hook.d.ts +15 -0
  17. package/dist/api/hooks/session-auth.hook.js +31 -0
  18. package/dist/api/index.d.ts +5 -0
  19. package/dist/api/index.js +21 -0
  20. package/dist/commercetools/api/base-api.d.ts +7 -0
  21. package/dist/commercetools/api/base-api.js +22 -0
  22. package/dist/commercetools/api/cart-api.d.ts +8 -0
  23. package/dist/commercetools/api/cart-api.js +34 -0
  24. package/dist/commercetools/api/payment-api.d.ts +10 -0
  25. package/dist/commercetools/api/payment-api.js +40 -0
  26. package/dist/commercetools/api/root-api.d.ts +15 -0
  27. package/dist/commercetools/api/root-api.js +45 -0
  28. package/dist/commercetools/errors/ct-api.error.d.ts +13 -0
  29. package/dist/commercetools/errors/ct-api.error.js +17 -0
  30. package/dist/commercetools/index.d.ts +2 -0
  31. package/dist/commercetools/index.js +2 -0
  32. package/dist/commercetools/services/ct-cart.service.d.ts +14 -0
  33. package/dist/commercetools/services/ct-cart.service.js +54 -0
  34. package/dist/commercetools/services/ct-payment.service.d.ts +20 -0
  35. package/dist/commercetools/services/ct-payment.service.js +129 -0
  36. package/dist/commercetools/types/api.type.d.ts +32 -0
  37. package/dist/commercetools/types/api.type.js +2 -0
  38. package/dist/commercetools/types/cart.type.d.ts +21 -0
  39. package/dist/commercetools/types/cart.type.js +2 -0
  40. package/dist/commercetools/types/payment.type.d.ts +38 -0
  41. package/dist/commercetools/types/payment.type.js +2 -0
  42. package/dist/errorx/errorx.d.ts +150 -0
  43. package/dist/errorx/errorx.js +326 -0
  44. package/dist/errorx/index.d.ts +1 -0
  45. package/dist/errorx/index.js +17 -0
  46. package/dist/fetch/decorators/base.decorator.d.ts +9 -0
  47. package/dist/fetch/decorators/base.decorator.js +12 -0
  48. package/dist/fetch/decorators/monitoring.decorator.d.ts +13 -0
  49. package/dist/fetch/decorators/monitoring.decorator.js +32 -0
  50. package/dist/fetch/types/fetch.type.d.ts +6 -0
  51. package/dist/fetch/types/fetch.type.js +2 -0
  52. package/dist/index.d.ts +33 -0
  53. package/dist/index.js +74 -0
  54. package/dist/logger/index.d.ts +1 -0
  55. package/dist/logger/index.js +17 -0
  56. package/dist/logger/logger.d.ts +6 -0
  57. package/dist/logger/logger.js +2 -0
  58. package/dist/security/auth/session.auth.d.ts +20 -0
  59. package/dist/security/auth/session.auth.js +54 -0
  60. package/dist/security/index.d.ts +3 -0
  61. package/dist/security/index.js +19 -0
  62. package/dist/security/services/oauth2.service.d.ts +16 -0
  63. package/dist/security/services/oauth2.service.js +53 -0
  64. package/dist/security/types/oauth2.type.d.ts +13 -0
  65. package/dist/security/types/oauth2.type.js +2 -0
  66. package/dist/security/types/session.type.d.ts +10 -0
  67. package/dist/security/types/session.type.js +2 -0
  68. package/package.json +21 -0
@@ -0,0 +1,34 @@
1
+ name: CI
2
+
3
+ on:
4
+ pull_request:
5
+ branches: [ main ]
6
+
7
+ jobs:
8
+ ci:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - name: Checkout Repo
12
+ uses: actions/checkout@v4
13
+
14
+ - name: Install Node.js
15
+ uses: actions/setup-node@v3
16
+ with:
17
+ node-version: 20
18
+
19
+ - name: Install dependencies
20
+ uses: pnpm/action-setup@v2
21
+ with:
22
+ version: 8
23
+ run_install: |
24
+ - recursive: true
25
+ args: [--frozen-lockfile, --strict-peer-dependencies]
26
+
27
+ - name: Build
28
+ run: pnpm run build
29
+
30
+ - name: Static code analysis
31
+ run: pnpm run lint
32
+
33
+ - name: Tests
34
+ run: pnpm run test
@@ -0,0 +1,46 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ branches: [ main ]
6
+
7
+ jobs:
8
+ publish-gpr:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - name: Checkout Repo
12
+ uses: actions/checkout@v4
13
+
14
+ - name: Install Node.js
15
+ uses: actions/setup-node@v3
16
+ with:
17
+ node-version: 20
18
+
19
+ - name: Install dependencies
20
+ uses: pnpm/action-setup@v2
21
+ with:
22
+ version: 8
23
+ run_install: |
24
+ - recursive: true
25
+ args: [--frozen-lockfile, --strict-peer-dependencies]
26
+
27
+ - name: Static code analysis
28
+ run: pnpm run lint
29
+
30
+ - name: Tests
31
+ run: pnpm run test
32
+
33
+ - name: Create Release Pull Request or Publish to npm
34
+ id: changesets
35
+ uses: changesets/action@v1
36
+ with:
37
+ # This expects you to have a script called release which does a build for your packages and calls changeset publish
38
+ publish: pnpm run release
39
+ env:
40
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
41
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
42
+
43
+ - name: Create release
44
+ if: steps.changesets.outputs.published == 'true'
45
+ # You can do something when a publish happens.
46
+ run: VERSION=$(jq '.version' package.json -r);gh release create "$VERSION" --title "$VERSION [@commercetools/connect-payments-sdk]" --notes 'Check CHANGELOG.md file.'
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env sh
2
+ . "$(dirname -- "$0")/_/husky.sh"
3
+
4
+ pnpm run format && pnpm run lint
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @commercetools/connect-payments-sdk
2
+
3
+ ## 0.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - c489d1a: Initial commit
package/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # @commercetools/connect-payments-sdk
2
+
3
+ This is the SDK for integrating payments with commercetools platform using TypeScript.
4
+
5
+ ## Installation
6
+
7
+ Install the package using npm:
8
+
9
+ ```bash
10
+ npm install @commercetools/connect-payments-sdk
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ First, import the SDK:
16
+
17
+ ```typescript
18
+ import { setupPaymentSDK } from '@commercetools/connect-payments-sdk';
19
+ ```
@@ -0,0 +1,14 @@
1
+ import { ContextProvider, RequestContextData } from './types/request-context.type';
2
+ /**
3
+ * ContextProvider is a class that provides a way to access and update the context data.
4
+ */
5
+ export declare class RequestContextProvider implements ContextProvider<RequestContextData> {
6
+ private getContextFn;
7
+ private updateContextFn;
8
+ constructor(opts: {
9
+ getContextFn: () => RequestContextData;
10
+ updateContextFn: (ctx: Partial<RequestContextData>) => void;
11
+ });
12
+ getContextData(): RequestContextData;
13
+ updateContextData(ctx: Partial<RequestContextData>): void;
14
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequestContextProvider = void 0;
4
+ /**
5
+ * ContextProvider is a class that provides a way to access and update the context data.
6
+ */
7
+ class RequestContextProvider {
8
+ getContextFn;
9
+ updateContextFn;
10
+ constructor(opts) {
11
+ this.getContextFn = opts.getContextFn;
12
+ this.updateContextFn = opts.updateContextFn;
13
+ }
14
+ getContextData() {
15
+ return this.getContextFn();
16
+ }
17
+ updateContextData(ctx) {
18
+ this.updateContextFn(ctx);
19
+ }
20
+ }
21
+ exports.RequestContextProvider = RequestContextProvider;
@@ -0,0 +1,16 @@
1
+ import { PaymentSessionData } from '../../../security';
2
+ /**
3
+ * Context provider interface
4
+ */
5
+ export interface ContextProvider<T> {
6
+ getContextData(): T;
7
+ updateContextData(ctx: Partial<T>): void;
8
+ }
9
+ /**
10
+ * Request context data
11
+ */
12
+ export type RequestContextData = {
13
+ correlationId: string;
14
+ requestId: string;
15
+ sessionData?: PaymentSessionData;
16
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ import { HandlerResponse } from './types/handler.type';
2
+ export declare const configHandler: (options: {
3
+ configuration: () => Promise<object> | object;
4
+ }) => () => Promise<HandlerResponse>;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.configHandler = void 0;
4
+ const configHandler = (options) => async () => {
5
+ return {
6
+ status: 200,
7
+ body: await options.configuration(),
8
+ };
9
+ };
10
+ exports.configHandler = configHandler;
@@ -0,0 +1,25 @@
1
+ import { Oauth2Service } from '../../security/types/oauth2.type';
2
+ import { HandlerResponse } from './types/handler.type';
3
+ export type HealthCheckResult = {
4
+ name: string;
5
+ status: 'UP' | 'DOWN';
6
+ details?: object;
7
+ };
8
+ export type HealthCheck = () => Promise<HealthCheckResult> | HealthCheckResult;
9
+ export declare const statusHandler: (options: {
10
+ timeout: number;
11
+ checks: HealthCheck[];
12
+ metadataFn?: () => Promise<object> | object;
13
+ }) => () => Promise<HandlerResponse>;
14
+ /**
15
+ * Check if CoCo permissions are available
16
+ * @param opts
17
+ * @returns
18
+ */
19
+ export declare const healthCheckCoCoPermissions: (opts: {
20
+ oauth2Service: Oauth2Service;
21
+ clientId: string;
22
+ clientSecret: string;
23
+ projectKey: string;
24
+ requiredPermissions: string[];
25
+ }) => () => Promise<HealthCheckResult>;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.healthCheckCoCoPermissions = exports.statusHandler = void 0;
4
+ const statusHandler = (options) => async () => {
5
+ const status = {
6
+ timestamp: new Date().toISOString(),
7
+ version: process.env.npm_package_version ?? '0.0.0',
8
+ };
9
+ if (options.metadataFn) {
10
+ status.metadata = await options.metadataFn();
11
+ }
12
+ let timeoutId = null;
13
+ const timeoutPromise = new Promise((_, reject) => (timeoutId = setTimeout(() => reject(new Error('Timeout')), options.timeout)));
14
+ try {
15
+ const results = await Promise.race([Promise.all(options.checks.map((check) => check())), timeoutPromise]);
16
+ if (results.findIndex((result) => result.status === 'DOWN') !== -1) {
17
+ status.status = 'Partially Available';
18
+ }
19
+ else {
20
+ status.status = 'OK';
21
+ }
22
+ status.checks = results;
23
+ return {
24
+ status: 200,
25
+ body: status,
26
+ };
27
+ }
28
+ catch (error) {
29
+ status.status = 'Unavailable';
30
+ status.checks = [];
31
+ return {
32
+ status: 503,
33
+ body: status,
34
+ };
35
+ }
36
+ finally {
37
+ if (timeoutId) {
38
+ clearTimeout(timeoutId);
39
+ }
40
+ }
41
+ };
42
+ exports.statusHandler = statusHandler;
43
+ /**
44
+ * Check if CoCo permissions are available
45
+ * @param opts
46
+ * @returns
47
+ */
48
+ const healthCheckCoCoPermissions = (opts) => async () => {
49
+ const token = await opts.oauth2Service.getAccessToken({
50
+ clientId: opts.clientId,
51
+ clientSecret: opts.clientSecret,
52
+ });
53
+ const foundAll = opts.requiredPermissions.every((currentScope) => token.scope.split(' ').some((scopeInToken) => scopeInToken === `${currentScope}:${opts.projectKey}`));
54
+ if (foundAll) {
55
+ return {
56
+ name: 'CoCo Permissions',
57
+ status: 'UP',
58
+ details: {
59
+ scope: token.scope,
60
+ },
61
+ };
62
+ }
63
+ return {
64
+ name: 'CoCo Permissions',
65
+ status: 'DOWN',
66
+ details: {
67
+ expectedScopes: opts.requiredPermissions,
68
+ actualScopes: token.scope,
69
+ reason: 'scopes not available',
70
+ },
71
+ };
72
+ };
73
+ exports.healthCheckCoCoPermissions = healthCheckCoCoPermissions;
@@ -0,0 +1,5 @@
1
+ export type HandlerResponse = {
2
+ status: number;
3
+ body?: object;
4
+ headers?: object;
5
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,15 @@
1
+ import { IncomingHttpHeaders } from 'node:http';
2
+ import { SessionAuthenticator } from '../../security/types/session.type';
3
+ import { ContextProvider, RequestContextData } from '../context/types/request-context.type';
4
+ export type SessionAuthHookOptions = {
5
+ sessionAuthenticator: SessionAuthenticator;
6
+ contextProvider: ContextProvider<RequestContextData>;
7
+ };
8
+ /**
9
+ * Fastify hook to authenticate and getting session information
10
+ * @param opts
11
+ * @returns
12
+ */
13
+ export declare const sessionAuthHook: (opts: SessionAuthHookOptions) => (req: {
14
+ headers: IncomingHttpHeaders;
15
+ }) => Promise<void>;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sessionAuthHook = void 0;
4
+ const errorx_1 = require("../../errorx/errorx");
5
+ /**
6
+ * Fastify hook to authenticate and getting session information
7
+ * @param opts
8
+ * @returns
9
+ */
10
+ const sessionAuthHook = (opts) => async (req) => {
11
+ const sessionId = req.headers['x-session-id'];
12
+ if (sessionId) {
13
+ const sessionData = await opts.sessionAuthenticator.introspectSession({
14
+ sessionId,
15
+ });
16
+ opts.contextProvider.updateContextData({
17
+ sessionData,
18
+ });
19
+ //updateSessionContext(sessionData);
20
+ }
21
+ else {
22
+ //TODO: throw a forbidden error
23
+ throw new errorx_1.ErrorAuthErrorResponse({
24
+ privateMessage: 'Session is not valid',
25
+ fields: {
26
+ id: sessionId,
27
+ },
28
+ });
29
+ }
30
+ };
31
+ exports.sessionAuthHook = sessionAuthHook;
@@ -0,0 +1,5 @@
1
+ export * from './context/request-context.provider';
2
+ export * from './context/types/request-context.type';
3
+ export * from './handlers/config.handler';
4
+ export * from './handlers/status.handler';
5
+ export * from './hooks/session-auth.hook';
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./context/request-context.provider"), exports);
18
+ __exportStar(require("./context/types/request-context.type"), exports);
19
+ __exportStar(require("./handlers/config.handler"), exports);
20
+ __exportStar(require("./handlers/status.handler"), exports);
21
+ __exportStar(require("./hooks/session-auth.hook"), exports);
@@ -0,0 +1,7 @@
1
+ import { ClientResponse } from '@commercetools/platform-sdk';
2
+ import { APIOpts, CommercetoolsClient } from '../types/api.type';
3
+ export declare abstract class CommercetoolsBaseAPI {
4
+ protected client: CommercetoolsClient;
5
+ constructor(opts: APIOpts);
6
+ protected executeCall<T>(cr: Promise<ClientResponse<T>>): Promise<T>;
7
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommercetoolsBaseAPI = void 0;
4
+ const ct_api_error_1 = require("../errors/ct-api.error");
5
+ class CommercetoolsBaseAPI {
6
+ client;
7
+ constructor(opts) {
8
+ this.client = opts.client;
9
+ }
10
+ async executeCall(cr) {
11
+ try {
12
+ return (await cr).body;
13
+ }
14
+ catch (e) {
15
+ if (e instanceof Object && 'statusCode' in e) {
16
+ throw new ct_api_error_1.CommercetoolsAPIError(e);
17
+ }
18
+ throw e;
19
+ }
20
+ }
21
+ }
22
+ exports.CommercetoolsBaseAPI = CommercetoolsBaseAPI;
@@ -0,0 +1,8 @@
1
+ import { Cart } from '@commercetools/platform-sdk';
2
+ import { APIOpts, AddPayment, CartAPI } from '../types/api.type';
3
+ import { CommercetoolsBaseAPI } from './base-api';
4
+ export declare class CommercetoolsCartAPI extends CommercetoolsBaseAPI implements CartAPI {
5
+ constructor(opts: APIOpts);
6
+ getCartById(id: string): Promise<Cart>;
7
+ addPayment(opts: AddPayment): Promise<Cart>;
8
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommercetoolsCartAPI = void 0;
4
+ const base_api_1 = require("./base-api");
5
+ class CommercetoolsCartAPI extends base_api_1.CommercetoolsBaseAPI {
6
+ constructor(opts) {
7
+ super(opts);
8
+ Object.setPrototypeOf(this, CommercetoolsCartAPI.prototype);
9
+ }
10
+ async getCartById(id) {
11
+ return this.executeCall(this.client.carts().withId({ ID: id }).get().execute());
12
+ }
13
+ async addPayment(opts) {
14
+ return this.executeCall(this.client
15
+ .carts()
16
+ .withId({ ID: opts.resource.id })
17
+ .post({
18
+ body: {
19
+ version: opts.resource.version,
20
+ actions: [
21
+ {
22
+ action: 'addPayment',
23
+ payment: {
24
+ id: opts.paymentId,
25
+ typeId: 'payment',
26
+ },
27
+ },
28
+ ],
29
+ },
30
+ })
31
+ .execute());
32
+ }
33
+ }
34
+ exports.CommercetoolsCartAPI = CommercetoolsCartAPI;
@@ -0,0 +1,10 @@
1
+ import { Payment, PaymentDraft, PaymentPagedQueryResponse } from '@commercetools/platform-sdk';
2
+ import { APIOpts, PaymentAPI, UpdatePayment } from '../types/api.type';
3
+ import { CommercetoolsBaseAPI } from './base-api';
4
+ export declare class CommercetoolsPaymentAPI extends CommercetoolsBaseAPI implements PaymentAPI {
5
+ constructor(opts: APIOpts);
6
+ getPaymentById(id: string): Promise<Payment>;
7
+ find(queryPredicate: string): Promise<PaymentPagedQueryResponse>;
8
+ createPayment(paymentDraft: PaymentDraft): Promise<Payment>;
9
+ updatePayment(opts: UpdatePayment): Promise<Payment>;
10
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommercetoolsPaymentAPI = void 0;
4
+ const base_api_1 = require("./base-api");
5
+ class CommercetoolsPaymentAPI extends base_api_1.CommercetoolsBaseAPI {
6
+ constructor(opts) {
7
+ super(opts);
8
+ Object.setPrototypeOf(this, CommercetoolsPaymentAPI.prototype);
9
+ }
10
+ async getPaymentById(id) {
11
+ return this.executeCall(this.client.payments().withId({ ID: id }).get().execute());
12
+ }
13
+ async find(queryPredicate) {
14
+ return this.executeCall(this.client
15
+ .payments()
16
+ .get({ queryArgs: { where: queryPredicate } })
17
+ .execute());
18
+ }
19
+ async createPayment(paymentDraft) {
20
+ return this.executeCall(this.client
21
+ .payments()
22
+ .post({
23
+ body: paymentDraft,
24
+ })
25
+ .execute());
26
+ }
27
+ async updatePayment(opts) {
28
+ return this.executeCall(this.client
29
+ .payments()
30
+ .withId({ ID: opts.resource.id })
31
+ .post({
32
+ body: {
33
+ version: opts.resource.version,
34
+ actions: opts.actions,
35
+ },
36
+ })
37
+ .execute());
38
+ }
39
+ }
40
+ exports.CommercetoolsPaymentAPI = CommercetoolsPaymentAPI;
@@ -0,0 +1,15 @@
1
+ import { ContextProvider, RequestContextData } from '../../api';
2
+ import { CartAPI, CommercetoolsAPI, CommercetoolsClient, PaymentAPI } from '../types/api.type';
3
+ export declare class DefaultCommercetoolsAPI implements CommercetoolsAPI {
4
+ client: CommercetoolsClient;
5
+ cart: CartAPI;
6
+ payment: PaymentAPI;
7
+ constructor(opts: {
8
+ clientId: string;
9
+ clientSecret: string;
10
+ authUrl: string;
11
+ apiUrl: string;
12
+ projectKey: string;
13
+ contextProvider: ContextProvider<RequestContextData>;
14
+ });
15
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultCommercetoolsAPI = void 0;
4
+ const platform_sdk_1 = require("@commercetools/platform-sdk");
5
+ const sdk_client_v2_1 = require("@commercetools/sdk-client-v2");
6
+ const cart_api_1 = require("./cart-api");
7
+ const payment_api_1 = require("./payment-api");
8
+ class DefaultCommercetoolsAPI {
9
+ client;
10
+ cart;
11
+ payment;
12
+ constructor(opts) {
13
+ this.client = createClient(opts);
14
+ this.cart = new cart_api_1.CommercetoolsCartAPI({ client: this.client });
15
+ this.payment = new payment_api_1.CommercetoolsPaymentAPI({ client: this.client });
16
+ }
17
+ }
18
+ exports.DefaultCommercetoolsAPI = DefaultCommercetoolsAPI;
19
+ const createClient = (opts) => {
20
+ const authMiddlewareOptions = {
21
+ host: opts.authUrl,
22
+ projectKey: opts.projectKey,
23
+ credentials: {
24
+ clientId: opts.clientId,
25
+ clientSecret: opts.clientSecret,
26
+ },
27
+ };
28
+ const httpMiddlewareOptions = {
29
+ host: opts.apiUrl,
30
+ };
31
+ const correlationIdMiddlewareOptions = {
32
+ generate: () => {
33
+ const correlationID = opts.contextProvider.getContextData().correlationId;
34
+ return correlationID;
35
+ },
36
+ };
37
+ const ctpClient = new sdk_client_v2_1.ClientBuilder()
38
+ .withClientCredentialsFlow(authMiddlewareOptions)
39
+ .withCorrelationIdMiddleware(correlationIdMiddlewareOptions)
40
+ .withHttpMiddleware(httpMiddlewareOptions)
41
+ .build();
42
+ return (0, platform_sdk_1.createApiBuilderFromCtpClient)(ctpClient).withProjectKey({
43
+ projectKey: opts.projectKey,
44
+ });
45
+ };
@@ -0,0 +1,13 @@
1
+ import { Errorx } from '../../errorx/errorx';
2
+ export type CocoErrorType = {
3
+ body?: {
4
+ code?: string;
5
+ message?: string;
6
+ errors?: object[];
7
+ };
8
+ statusCode: number;
9
+ message?: string;
10
+ };
11
+ export declare class CommercetoolsAPIError extends Errorx {
12
+ constructor(err: CocoErrorType);
13
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommercetoolsAPIError = void 0;
4
+ const errorx_1 = require("../../errorx/errorx");
5
+ class CommercetoolsAPIError extends errorx_1.Errorx {
6
+ constructor(err) {
7
+ super({
8
+ code: err.body?.code ?? 'CommercetoolsAPIError',
9
+ message: err?.body?.message ?? err?.message ?? '',
10
+ httpErrorStatus: err.statusCode,
11
+ cause: err,
12
+ fields: err.body?.errors,
13
+ });
14
+ this.name = 'CommercetoolsAPIError';
15
+ }
16
+ }
17
+ exports.CommercetoolsAPIError = CommercetoolsAPIError;
@@ -0,0 +1,2 @@
1
+ export { CartService as CommercetoolsCartService } from './types/cart.type';
2
+ export { PaymentService as CommercetoolsPaymentService, TransactionData, UpdatePayment } from './types/payment.type';
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,14 @@
1
+ import { CartService, CartServiceOptions, GetCart, GetPaymentAmount } from '../types/cart.type';
2
+ import { Cart } from '@commercetools/platform-sdk';
3
+ import { PaymentAmount } from '../types/payment.type';
4
+ import { AddPayment } from '../types/api.type';
5
+ /**
6
+ * Default implementation of the CartService interface.
7
+ */
8
+ export declare class DefaultCartService implements CartService {
9
+ private ctAPI;
10
+ constructor(opts: CartServiceOptions);
11
+ getCart(opts: GetCart): Promise<Cart>;
12
+ getPaymentAmount(opts: GetPaymentAmount): PaymentAmount;
13
+ addPayment(opts: AddPayment): Promise<Cart>;
14
+ }