@stancer/stancer 1.0.2 → 1.1.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 (184) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/dist/api-endpoint/http/fetch-http-client.d.ts.map +1 -1
  3. package/dist/api-endpoint/http/fetch-http-client.js +7 -1
  4. package/dist/api-endpoint/http/fetch-http-client.js.map +1 -1
  5. package/dist/core/common/handler/metadata-handler.d.ts +18 -0
  6. package/dist/core/common/handler/metadata-handler.d.ts.map +1 -0
  7. package/dist/core/common/handler/metadata-handler.js +19 -0
  8. package/dist/core/common/handler/metadata-handler.js.map +1 -0
  9. package/dist/event/model.d.ts +20 -0
  10. package/dist/event/model.d.ts.map +1 -0
  11. package/dist/event/model.js +30 -0
  12. package/dist/event/model.js.map +1 -0
  13. package/dist/index.d.ts +60 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +57 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/payment-intent/api-endpoint.d.ts +16 -1
  18. package/dist/payment-intent/api-endpoint.d.ts.map +1 -1
  19. package/dist/payment-intent/api-endpoint.js +2 -1
  20. package/dist/payment-intent/api-endpoint.js.map +1 -1
  21. package/dist/payment-intent/model.d.ts +3 -2
  22. package/dist/payment-intent/model.d.ts.map +1 -1
  23. package/dist/payment-intent/model.js +6 -0
  24. package/dist/payment-intent/model.js.map +1 -1
  25. package/dist/payment-intent/repository.d.ts +1 -1
  26. package/dist/payment-intent/repository.d.ts.map +1 -1
  27. package/dist/webhook/api-endpoint.d.ts +16 -0
  28. package/dist/webhook/api-endpoint.d.ts.map +1 -0
  29. package/dist/webhook/api-endpoint.js +33 -0
  30. package/dist/webhook/api-endpoint.js.map +1 -0
  31. package/dist/webhook/model.d.ts +35 -0
  32. package/dist/webhook/model.d.ts.map +1 -0
  33. package/dist/webhook/model.js +110 -0
  34. package/dist/webhook/model.js.map +1 -0
  35. package/dist/webhook/repository.d.ts +7 -0
  36. package/dist/webhook/repository.d.ts.map +1 -0
  37. package/dist/webhook/repository.js +10 -0
  38. package/dist/webhook/repository.js.map +1 -0
  39. package/dist/webhook/validator.d.ts +4 -0
  40. package/dist/webhook/validator.d.ts.map +1 -0
  41. package/dist/webhook/validator.js +16 -0
  42. package/dist/webhook/validator.js.map +1 -0
  43. package/package.json +33 -22
  44. package/dist/main.d.ts +0 -2
  45. package/dist/main.d.ts.map +0 -1
  46. package/dist/main.js +0 -2
  47. package/dist/main.js.map +0 -1
  48. package/reports/base.css +0 -362
  49. package/reports/block-navigation.js +0 -75
  50. package/reports/cobertura-coverage.xml +0 -18
  51. package/reports/favicon.png +0 -0
  52. package/reports/index.html +0 -177
  53. package/reports/junit.xml +0 -25
  54. package/reports/prettify.css +0 -101
  55. package/reports/prettify.js +0 -955
  56. package/reports/sort-arrow-sprite.png +0 -0
  57. package/reports/sorter.js +0 -205
  58. package/src/address/api-endpoint.ts +0 -30
  59. package/src/address/model.ts +0 -79
  60. package/src/address/repository.ts +0 -18
  61. package/src/address/validator.ts +0 -34
  62. package/src/api-endpoint/abstract-api-endpoint.ts +0 -310
  63. package/src/api-endpoint/configuration.ts +0 -125
  64. package/src/api-endpoint/http/fetch-http-client.ts +0 -29
  65. package/src/api-endpoint/http/http.ts +0 -75
  66. package/src/api-endpoint/http/index.ts +0 -2
  67. package/src/api-endpoint/version.ts +0 -4
  68. package/src/card/api-endpoint.ts +0 -39
  69. package/src/card/enum/funding.ts +0 -11
  70. package/src/card/enum/nature.ts +0 -7
  71. package/src/card/enum/network.ts +0 -16
  72. package/src/card/model.ts +0 -139
  73. package/src/card/repository.ts +0 -11
  74. package/src/card/validator.ts +0 -79
  75. package/src/core/abstract-model.ts +0 -126
  76. package/src/core/abstract-repository.ts +0 -201
  77. package/src/core/common/branded-type.ts +0 -15
  78. package/src/core/common/handler/date-handler.ts +0 -31
  79. package/src/core/common/handler/enum-handler.ts +0 -18
  80. package/src/core/common/handler/handler.ts +0 -64
  81. package/src/core/common/handler/id-handler.ts +0 -27
  82. package/src/core/common/id-validator.ts +0 -23
  83. package/src/core/common/mutation-tracked-object.ts +0 -49
  84. package/src/core/endpoint-interface.ts +0 -43
  85. package/src/core/error/base-error.ts +0 -1
  86. package/src/core/error/endpoint/api/api-conflict-error.ts +0 -7
  87. package/src/core/error/endpoint/api/api-error.ts +0 -10
  88. package/src/core/error/endpoint/api/api-not-found-error.ts +0 -7
  89. package/src/core/error/endpoint/api/api-unauthorized-error.ts +0 -7
  90. package/src/core/error/endpoint/api/api-unknown-error.ts +0 -7
  91. package/src/core/error/endpoint/api/api-validation-error.ts +0 -13
  92. package/src/core/error/endpoint/api/index.ts +0 -6
  93. package/src/core/error/endpoint/route-inaccessible-error.ts +0 -8
  94. package/src/core/error/unpopulated-error.ts +0 -3
  95. package/src/core/error/unsendable-error.ts +0 -3
  96. package/src/core/error/validation-error.ts +0 -3
  97. package/src/core/validator.ts +0 -129
  98. package/src/customer/api-endpoint.ts +0 -29
  99. package/src/customer/model.ts +0 -113
  100. package/src/customer/repository.ts +0 -14
  101. package/src/customer/validator.ts +0 -26
  102. package/src/payment/api-endpoint.ts +0 -118
  103. package/src/payment/enum/currency.ts +0 -14
  104. package/src/payment/enum/method.ts +0 -2
  105. package/src/payment/enum/status.ts +0 -21
  106. package/src/payment/model.ts +0 -378
  107. package/src/payment/repository.ts +0 -73
  108. package/src/payment/validator.ts +0 -96
  109. package/src/payment-intent/api-endpoint.ts +0 -123
  110. package/src/payment-intent/enum/status.ts +0 -21
  111. package/src/payment-intent/enum/threeds.ts +0 -2
  112. package/src/payment-intent/model.ts +0 -266
  113. package/src/payment-intent/repository.ts +0 -85
  114. package/src/payment-intent/validator.ts +0 -45
  115. package/src/payout/model.ts +0 -8
  116. package/src/refund/api-endpoint.ts +0 -33
  117. package/src/refund/enum/refund-status.ts +0 -11
  118. package/src/refund/model.ts +0 -90
  119. package/src/refund/repository.ts +0 -14
  120. package/src/refund/validator.ts +0 -44
  121. package/src/sepa/api-endpoint.ts +0 -26
  122. package/src/sepa/model.ts +0 -80
  123. package/src/sepa/repository.ts +0 -11
  124. package/src/sepa/validator.ts +0 -56
  125. package/test/fixtures/endpoint.stub.ts +0 -22
  126. package/test/fixtures/list-endpoint.stub.ts +0 -33
  127. package/test/fixtures/list-model.stub.ts +0 -24
  128. package/test/fixtures/model.stub.ts +0 -12
  129. package/test/functional/address.test.ts +0 -126
  130. package/test/functional/card.test.ts +0 -175
  131. package/test/functional/customer.test.ts +0 -174
  132. package/test/functional/payment-intent.test.ts +0 -215
  133. package/test/functional/payment.test.ts +0 -206
  134. package/test/functional/refund.test.ts +0 -112
  135. package/test/functional/sepa.test.ts +0 -136
  136. package/test/integration/stub-integration.test.ts +0 -88
  137. package/test/stub/stub-endpoint.ts +0 -42
  138. package/test/stub/stub-model.ts +0 -82
  139. package/test/stub/stub-repository.ts +0 -11
  140. package/test/test-helper.ts +0 -133
  141. package/test/unit/address/api-endpoint.test.ts +0 -134
  142. package/test/unit/address/fixtures.ts +0 -60
  143. package/test/unit/address/model.test.ts +0 -75
  144. package/test/unit/address/repository.test.ts +0 -148
  145. package/test/unit/address/validator.test.ts +0 -49
  146. package/test/unit/api-endpoint/http/fetch-http-client.test.ts +0 -44
  147. package/test/unit/api-endpoint/http/http.test.ts +0 -152
  148. package/test/unit/card/api-endpoint.test.ts +0 -170
  149. package/test/unit/card/card-helper.ts +0 -116
  150. package/test/unit/card/fixtures.ts +0 -87
  151. package/test/unit/card/model.test.ts +0 -167
  152. package/test/unit/card/repository.test.ts +0 -146
  153. package/test/unit/card/validator.test.ts +0 -96
  154. package/test/unit/core/common/mutation-tracked-object.test.ts +0 -24
  155. package/test/unit/customer/api-endpoint.test.ts +0 -143
  156. package/test/unit/customer/fixtures.ts +0 -73
  157. package/test/unit/customer/model.test.ts +0 -90
  158. package/test/unit/customer/repository.test.ts +0 -148
  159. package/test/unit/customer/validator.test.ts +0 -62
  160. package/test/unit/payment/api-endpoint.test.ts +0 -188
  161. package/test/unit/payment/fixtures.ts +0 -116
  162. package/test/unit/payment/model.test.ts +0 -240
  163. package/test/unit/payment/repository.test.ts +0 -270
  164. package/test/unit/payment/validator.test.ts +0 -137
  165. package/test/unit/payment-intent/api-endpoint.test.ts +0 -142
  166. package/test/unit/payment-intent/fixtures.ts +0 -94
  167. package/test/unit/payment-intent/model.test.ts +0 -157
  168. package/test/unit/payment-intent/repository.test.ts +0 -263
  169. package/test/unit/payment-intent/validator.test.ts +0 -136
  170. package/test/unit/refund/api-endpoint.test.ts +0 -129
  171. package/test/unit/refund/fixtures.ts +0 -58
  172. package/test/unit/refund/model.test.ts +0 -89
  173. package/test/unit/refund/repository.test.ts +0 -157
  174. package/test/unit/refund/validator.test.ts +0 -89
  175. package/test/unit/sepa/api-endpoint.test.ts +0 -170
  176. package/test/unit/sepa/fixture.ts +0 -62
  177. package/test/unit/sepa/model.test.ts +0 -86
  178. package/test/unit/sepa/repository.test.ts +0 -149
  179. package/test/unit/sepa/sepa-helper.ts +0 -71
  180. package/test/unit/sepa/validator.test.ts +0 -58
  181. package/test/unit/stub/stub-endpoint.test.ts +0 -236
  182. package/test/unit/stub/stub-list-endpoint.test.ts +0 -86
  183. package/test/unit/stub/stub-model.test.ts +0 -111
  184. package/test/unit/stub/stub-repository.test.ts +0 -144
@@ -1,125 +0,0 @@
1
- import { StancerError } from '#error/base-error.js';
2
-
3
- import pkg from './../../package.json' with { type: 'json' };
4
- import { httpClient } from './http/fetch-http-client.js';
5
- import { type Http } from './http/index.js';
6
- import { ApiVersion } from './version.js';
7
-
8
- export class _Configuration {
9
- //#region Properties
10
-
11
- private _apiVersion: ApiVersion = ApiVersion.Default;
12
- // Host is not publicly settable. It already point to the API.
13
- private _host: string = 'api.stancer.com';
14
- private _httpClient: Http.Client = httpClient;
15
- private _httpUserAgent: string = `libstancer-ts/${pkg.version} node-fetch`;
16
- private _keys: {
17
- privateLiveKey: string | null;
18
- privateTestKey: string | null;
19
- } = {
20
- privateLiveKey: null,
21
- privateTestKey: null,
22
- };
23
-
24
- private _mode: 'prod' | 'test' = 'test';
25
- public port?: number;
26
- //#endregion
27
-
28
- //#region Getters
29
-
30
- private get _privateKey(): string | null {
31
- switch (this._mode) {
32
- case 'prod':
33
- return this._keys.privateLiveKey;
34
- case 'test':
35
- return this._keys.privateTestKey;
36
- default:
37
- return null;
38
- }
39
- }
40
-
41
- get apiVersion(): string {
42
- return this._apiVersion;
43
- }
44
-
45
- get baseUrl(): string {
46
- return this.port
47
- ? `https://${this.host}:${this.port}/${this.apiVersion}`
48
- : `https://${this.host}/${this.apiVersion}`;
49
- }
50
-
51
- get defaultHttpHeaders(): Record<string, string> {
52
- return {
53
- 'user-agent': this.httpUserAgent,
54
- };
55
- }
56
-
57
- get host(): string {
58
- return this._host;
59
- }
60
-
61
- get httpBasicAuthHeader() {
62
- if (!this._privateKey) {
63
- return {};
64
- }
65
- return {
66
- // This api only run in node env if private key is malformed we get an unauthorized error.
67
- authorization: `Basic ${Buffer.from(`${this._privateKey}:`).toString('base64')}`,
68
- };
69
- }
70
-
71
- get httpClient(): Http.Client {
72
- return this._httpClient;
73
- }
74
-
75
- get httpUserAgent(): string {
76
- return this._httpUserAgent;
77
- }
78
-
79
- public get mode(): 'prod' | 'test' {
80
- return this._mode;
81
- }
82
-
83
- //#endregion
84
-
85
- //#region Methods
86
-
87
- init({ keys, mode }: { keys: Partial<_Configuration['_keys']>; mode: _Configuration['mode'] }) {
88
- if (mode !== 'prod' && mode !== 'test') {
89
- throw new StancerError(`Invalid mode: ${mode}. Must be 'prod' or 'test'`);
90
- }
91
- if (mode === 'prod' && !keys.privateLiveKey) {
92
- throw new StancerError(`Prod key is required for production mode`);
93
- }
94
- if (mode === 'test' && !keys.privateTestKey) {
95
- throw new StancerError(`Test key is required for test mode`);
96
- }
97
- this._keys = Object.assign({}, this._keys, keys);
98
- this._mode = mode;
99
- return this;
100
- }
101
-
102
- setApiVersion(apiVersion: ApiVersion) {
103
- this._apiVersion = apiVersion;
104
- }
105
-
106
- setKey(keys: Partial<_Configuration['_keys']>) {
107
- this._keys = Object.assign({}, this._keys, keys);
108
- }
109
-
110
- setMode(mode: 'test' | 'prod') {
111
- if ((mode === 'prod' && this._keys.privateLiveKey) || (mode === 'test' && this._keys.privateTestKey)) {
112
- this._mode = mode;
113
- return;
114
- }
115
- throw new StancerError(`key matching mode ${mode} is necessary to set it`);
116
- }
117
-
118
- setUserAgent(userAgent: string) {
119
- this._httpUserAgent = userAgent;
120
- }
121
-
122
- //#endregion
123
- }
124
-
125
- export const Configuration = new _Configuration();
@@ -1,29 +0,0 @@
1
- import { StancerApiUnknownError } from '#error/endpoint/api/api-unknown-error.js';
2
-
3
- import { Http } from './index.js';
4
-
5
- export const httpClient: Http.Client = {
6
- makeRequest: async (request: Http.Request): Promise<Http.Response> => {
7
- const headers = {
8
- ...(request.headers ?? {}),
9
- };
10
- if (!headers['user-agent']) {
11
- headers['user-agent'] = 'Stancer fetch';
12
- }
13
- const partialRequest = {
14
- method: request.method,
15
- headers,
16
- };
17
- const completeRequest = request.body ? { ...partialRequest, body: request.body } : partialRequest;
18
- try {
19
- const response = await fetch(request.url, completeRequest);
20
-
21
- return {
22
- status: response.status,
23
- json: async <T>() => (await response.json()) as T,
24
- };
25
- } catch (e) {
26
- throw new StancerApiUnknownError(0, e instanceof Error ? e.message : 'Network error');
27
- }
28
- },
29
- };
@@ -1,75 +0,0 @@
1
- import {
2
- StancerApiConflictError,
3
- StancerApiError,
4
- StancerApiNotFoundError,
5
- StancerApiUnauthorizedError,
6
- StancerApiUnknownError,
7
- StancerApiValidationError,
8
- type StancerApiValidationErrorDetails,
9
- } from '#error/endpoint/api/index.js';
10
-
11
- import { Configuration } from '../configuration.js';
12
-
13
- //#region interfaces
14
- export interface Client {
15
- makeRequest: (request: Request) => Promise<Response>;
16
- }
17
-
18
- export interface Request {
19
- url: string;
20
- method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
21
- headers?: Record<string, string>;
22
- body?: string;
23
- authenticated?: boolean;
24
- }
25
-
26
- export interface Response {
27
- status: number;
28
- json<T>(): Promise<T>;
29
- }
30
- //#endregion
31
-
32
- //#region implementation
33
- export const createRequest = (req: Request): Request => {
34
- return {
35
- ...req,
36
- headers: {
37
- ...(req.authenticated ? Configuration.httpBasicAuthHeader : {}),
38
- ...Configuration.defaultHttpHeaders,
39
- ...req.headers,
40
- },
41
- };
42
- };
43
-
44
- export const handleHttpResponseErrors = async (response: Response) => {
45
- if (response.status >= 200 && response.status < 300) {
46
- return response;
47
- }
48
- try {
49
- const data = await response.json<{ error: string | object; detail: StancerApiValidationErrorDetails[] }>();
50
- const stringifyError = (error: string | object) => (typeof error === 'string' ? error : JSON.stringify(error));
51
- switch (response.status) {
52
- case 401:
53
- throw new StancerApiUnauthorizedError(stringifyError(data.error));
54
- case 422:
55
- throw new StancerApiValidationError(data.detail);
56
- case 404:
57
- throw new StancerApiNotFoundError(stringifyError(data.error));
58
- case 409:
59
- throw new StancerApiConflictError(stringifyError(data.error));
60
- default:
61
- throw new StancerApiUnknownError(response.status, stringifyError(data.error) ?? `${response.status} error`);
62
- }
63
- } catch (e) {
64
- if (e instanceof StancerApiError) {
65
- throw e;
66
- }
67
- throw new StancerApiUnknownError(response.status, `HTTP Error ${response.status}`);
68
- }
69
- };
70
-
71
- export const transformResponseToData = async <T>(response: Response) => {
72
- await handleHttpResponseErrors(response);
73
- return response.json<T>();
74
- };
75
- //#endregion
@@ -1,2 +0,0 @@
1
- export * as Http from './http.js';
2
- export * as FetchHttpClient from './fetch-http-client.js';
@@ -1,4 +0,0 @@
1
- export enum ApiVersion {
2
- V2 = 'v2',
3
- Default = ApiVersion.V2,
4
- }
@@ -1,39 +0,0 @@
1
- import { ApiEndpoint, baseHandler } from '#api/abstract-api-endpoint.js';
2
- import { enumHandler } from '#core/common/handler/enum-handler.js';
3
- import { defaultHandler } from '#core/common/handler/handler.js';
4
- import { IdHandler } from '#core/common/handler/id-handler.js';
5
-
6
- import { CustomerModel, type IdCustomer } from '../customer/model.js';
7
- import { FundingCardEnum } from './enum/funding.js';
8
- import { NatureCardEnum } from './enum/nature.js';
9
- import { NetworkCardEnum, PreferredNetworkCardEnum } from './enum/network.js';
10
- import { type CardData, CardModel, type IdCard } from './model.js';
11
-
12
- export class CardApiEndpoint extends ApiEndpoint<CardData> {
13
- public _handler = {
14
- ...baseHandler('created'),
15
- id: IdHandler<IdCard>(CardModel.regex),
16
- brand: defaultHandler<CardData['brand']>('string', { patchable: false, postable: false }),
17
- country: defaultHandler<CardData['country']>('string', { patchable: false, postable: false }),
18
- customer: IdHandler<IdCustomer>(CustomerModel.regex, { patchable: false }),
19
- cvc: defaultHandler<CardData['cvc']>('string', { gettable: false, patchable: false }),
20
- expMonth: defaultHandler<CardData['expMonth']>('number', { postRequired: true }),
21
- expYear: defaultHandler<CardData['expYear']>('number', { postRequired: true }),
22
- externalId: defaultHandler<CardData['externalId']>('string'),
23
- funding: enumHandler(FundingCardEnum, { patchable: false, postable: false }),
24
- last4: defaultHandler<CardData['last4']>('string', { postable: false, patchable: false }),
25
- name: defaultHandler<CardData['name']>('string', { patchable: false }),
26
- nature: enumHandler(NatureCardEnum, { patchable: false, postable: false }),
27
- network: enumHandler(NetworkCardEnum, { postable: false, patchable: false }),
28
- number: defaultHandler<CardData['number']>('string', { gettable: false, patchable: false, postRequired: true }),
29
- preferredNetwork: enumHandler(PreferredNetworkCardEnum, { patchable: false }),
30
- tokenize: defaultHandler<CardData['tokenize']>('boolean', { gettable: false, patchable: false }),
31
- zipCode: defaultHandler<CardData['zipCode']>('string'),
32
- };
33
-
34
- constructor() {
35
- super({
36
- name: 'cards',
37
- });
38
- }
39
- }
@@ -1,11 +0,0 @@
1
- export const FundingCardEnum = [
2
- 'credit',
3
- 'debit',
4
- 'prepaid',
5
- 'universal',
6
- 'charge',
7
- 'deferred',
8
- 'unknown',
9
- ] as const;
10
-
11
- export type FundingCard = (typeof FundingCardEnum)[number];
@@ -1,7 +0,0 @@
1
- export const NatureCardEnum = [
2
- 'personal',
3
- 'corporate',
4
- 'unknown',
5
- ] as const;
6
-
7
- export type NatureCard = (typeof NatureCardEnum)[number];
@@ -1,16 +0,0 @@
1
- export const NetworkCardEnum = [
2
- 'national',
3
- 'visa',
4
- 'mastercard',
5
- 'unknown',
6
- ] as const;
7
-
8
- export type NetworkCard = (typeof NetworkCardEnum)[number];
9
-
10
- export const PreferredNetworkCardEnum = [
11
- 'national',
12
- 'visa',
13
- 'mastercard',
14
- ] as const;
15
-
16
- export type PreferredNetworkCard = (typeof PreferredNetworkCardEnum)[number];
package/src/card/model.ts DELETED
@@ -1,139 +0,0 @@
1
- import { AbstractModel, type ModelData } from '#core/abstract-model.js';
2
- import type { IdValue } from '#core/common/branded-type.js';
3
- import { validateID } from '#core/common/id-validator.js';
4
-
5
- import type { IdCustomer } from '../customer/model.js';
6
- import { type FundingCard } from './enum/funding.js';
7
- import type { NatureCard } from './enum/nature.js';
8
- import type { NetworkCard, PreferredNetworkCard } from './enum/network.js';
9
-
10
- export type IdCard = IdValue<`card_${string}`>;
11
- export const idCard = (id: string) => validateID<IdCard>(id, CardModel.regex);
12
- export interface CardData extends ModelData {
13
- brand: string;
14
- country: string;
15
- customer: IdCustomer;
16
- cvc: string;
17
- deleted: boolean;
18
- expMonth: number;
19
- expYear: number;
20
- externalId: string;
21
- funding: FundingCard;
22
- id: IdCard;
23
- last4: string;
24
- name: string;
25
- nature: NatureCard;
26
- network: NetworkCard;
27
- number: string;
28
- preferredNetwork: PreferredNetworkCard;
29
- tokenize: boolean;
30
- zipCode: string;
31
- }
32
-
33
- export class CardModel extends AbstractModel<CardData> {
34
- static regex = /^card_[a-zA-Z0-9]{24}$/;
35
-
36
- get customer() {
37
- return this._data.customer;
38
- }
39
-
40
- get brand() {
41
- return this._data.brand;
42
- }
43
-
44
- get country() {
45
- return this._data.country;
46
- }
47
-
48
- get expMonth() {
49
- return this._data.expMonth;
50
- }
51
-
52
- get expYear() {
53
- return this._data.expYear;
54
- }
55
-
56
- get externalId() {
57
- return this._data.externalId;
58
- }
59
-
60
- get funding() {
61
- return this._data.funding;
62
- }
63
-
64
- get last4() {
65
- if (!this._data.last4 && this._data.number) {
66
- return this._data.number.slice(-4);
67
- }
68
- return this._data.last4;
69
- }
70
-
71
- get name() {
72
- return this._data.name;
73
- }
74
-
75
- get nature() {
76
- return this._data.nature;
77
- }
78
-
79
- get preferredNetwork() {
80
- return this._data.preferredNetwork;
81
- }
82
-
83
- get network() {
84
- return this._data.network;
85
- }
86
-
87
- get zipCode() {
88
- return this._data.zipCode;
89
- }
90
-
91
- setCustomer(value: IdCustomer) {
92
- this._data.customer = value;
93
- return this;
94
- }
95
-
96
- setCvc(value: string) {
97
- this._data.cvc = value;
98
- return this;
99
- }
100
-
101
- setExpYear(value: number) {
102
- this._data.expYear = value;
103
- return this;
104
- }
105
-
106
- setExpMonth(value: number) {
107
- this._data.expMonth = value;
108
- return this;
109
- }
110
- setExternalId(value: string) {
111
- this._data.externalId = value;
112
- return this;
113
- }
114
-
115
- setName(value: string) {
116
- this._data.name = value;
117
- return this;
118
- }
119
-
120
- setNumber(value: string) {
121
- this._data.number = value;
122
- return this;
123
- }
124
-
125
- setPreferredNetwork(value: PreferredNetworkCard) {
126
- this._data.preferredNetwork = value;
127
- return this;
128
- }
129
-
130
- setTokenize(value: boolean) {
131
- this._data.tokenize = value;
132
- return this;
133
- }
134
-
135
- setZipCode(value: string) {
136
- this._data.zipCode = value;
137
- return this;
138
- }
139
- }
@@ -1,11 +0,0 @@
1
- import { CardApiEndpoint } from '#card/api-endpoint.js';
2
- import { type CardData, CardModel } from '#card/model.js';
3
- import { cardValidator } from '#card/validator.js';
4
- import { AbstractRepository, type Repository } from '#core/abstract-repository.js';
5
- import type { EndpointInterface } from '#core/endpoint-interface.js';
6
-
7
- export class CardRepository extends AbstractRepository<CardData, CardModel> implements Repository<CardData, CardModel> {
8
- constructor(endpoint?: EndpointInterface<CardData>) {
9
- super({ endpoint: endpoint ?? new CardApiEndpoint(), validator: cardValidator, model: CardModel });
10
- }
11
- }
@@ -1,79 +0,0 @@
1
- import { IdValidator } from '#core/common/id-validator.js';
2
- import { type Validator, createdAtValidator, enumValidator, goldilocksValidator } from '#core/validator.js';
3
-
4
- import { CustomerModel, type IdCustomer } from '../customer/model.js';
5
- import { FundingCardEnum } from './enum/funding.js';
6
- import { NatureCardEnum } from './enum/nature.js';
7
- import { NetworkCardEnum, PreferredNetworkCardEnum } from './enum/network.js';
8
- import { type CardData, CardModel, type IdCard } from './model.js';
9
-
10
- const expMonthValidator = {
11
- validate: (arg0: number) => typeof arg0 === 'number' && arg0 > 0 && arg0 <= 12,
12
- errorMessage: (value: string) => `${value} is not a month (between 1 and 12)`,
13
- };
14
- const expYearValidator = {
15
- validate: (arg0: number) => typeof arg0 === 'number' && String(arg0).length === 4,
16
- errorMessage: (value: string) => `${value} is not a correct year (must be 4 digits)`,
17
- };
18
-
19
- export const cardNumberValidator = {
20
- validate: (arg0: string) => {
21
- if (typeof arg0 !== 'string') {
22
- return false;
23
- }
24
-
25
- const numb = arg0.replaceAll(/\s/g, '').replaceAll(/\D/g, '');
26
-
27
- if (!numb) {
28
- return false;
29
- }
30
-
31
- const reversed: string[] = numb.split('').reverse();
32
- const calc = (digit: number) => {
33
- const number = digit * 2;
34
- if (number < 10) {
35
- return number;
36
- }
37
- const splited = String(number).split('');
38
- return Number(splited[0]) + Number(splited[1]);
39
- };
40
- const sum = reversed.reduce((n, sum, index) => {
41
- if (index % 2) {
42
- return String(Number(n) + calc(Number(sum)));
43
- }
44
- return String(Number(n) + Number(sum));
45
- }, '0');
46
-
47
- if (Number(sum) % 10) {
48
- return false;
49
- }
50
-
51
- return true;
52
- },
53
- errorMessage: (value: string) => `${value} is not a valid credit card number`,
54
- };
55
-
56
- export const cardValidator: Validator<CardData> = {
57
- id: IdValidator<IdCard>(CardModel.regex),
58
- brand: true,
59
- country: goldilocksValidator('country', { size: 2 }),
60
- customer: IdValidator<IdCustomer>(CustomerModel.regex),
61
- cvc: {
62
- validate: (arg0: string) => /^\d{3}$/.test(arg0),
63
- errorMessage: (value: string) => `${value} is not a valid CVC (must be 3 digits)`,
64
- },
65
- createdAt: createdAtValidator,
66
- deleted: true,
67
- expMonth: expMonthValidator,
68
- expYear: expYearValidator,
69
- externalId: goldilocksValidator('externalID', { min: 1, max: 36 }),
70
- funding: enumValidator(FundingCardEnum, false),
71
- last4: true,
72
- name: goldilocksValidator('name', { min: 1, max: 64 }),
73
- nature: enumValidator(NatureCardEnum, false),
74
- network: enumValidator(NetworkCardEnum, false),
75
- number: cardNumberValidator,
76
- preferredNetwork: enumValidator(PreferredNetworkCardEnum),
77
- tokenize: true,
78
- zipCode: goldilocksValidator('zipCode', { min: 0, max: 8 }),
79
- };
@@ -1,126 +0,0 @@
1
- import type { Temporal } from 'temporal-polyfill';
2
-
3
- import { type ValidationFunction, type Validator, processValidator } from '#core/validator.js';
4
-
5
- import { IdValue } from './common/branded-type.js';
6
- import { type MutationTrackedObject, trackObjectMutations } from './common/mutation-tracked-object.js';
7
-
8
- //#region Types & Interfaces
9
-
10
- export interface ModelData {
11
- createdAt: Temporal.Instant;
12
- deleted: boolean;
13
- }
14
-
15
- export interface ModelType extends ModelData {
16
- id: IdValue;
17
- }
18
-
19
- //#endregion
20
-
21
- /**
22
- * All setters and getters of AbstractModel and their children will be inconsistent.
23
- * This is intentional to help users use only the values accessible to them.
24
- */
25
- export abstract class AbstractModel<Data extends ModelType> {
26
- //#region Properties
27
-
28
- protected _data: MutationTrackedObject<Partial<Data>>;
29
- protected _id: Data['id'] | undefined;
30
- protected validator: ValidationFunction<Data>;
31
-
32
- //#endregion
33
-
34
- //#region Constructor
35
-
36
- /**
37
- * Construct a model object.
38
- * Prefer using repository.create() instead of constructing it directly.
39
- * @param validator - The validator function for this model
40
- * @param id - Optional ID string or partial data object
41
- */
42
- constructor(validator: Validator<Data>, id?: string | Partial<Data>) {
43
- this.validator = processValidator(validator);
44
- this._data = trackObjectMutations<Data>({}, this.validator);
45
-
46
- if (typeof id === 'object' && id !== null) {
47
- const data = id;
48
- const keys = Object.keys(data) as (keyof Partial<Data>)[];
49
- keys.forEach((key) => {
50
- if (data[key] === undefined) {
51
- return;
52
- }
53
- this.validator(key, data[key]);
54
- (this._data[key] as Partial<Data>[keyof Data]) = data[key];
55
- });
56
- this._id = data.id ?? undefined;
57
- return;
58
- }
59
-
60
- if (id) {
61
- const stringID = IdValue(id);
62
- this.validator('id', stringID);
63
- this._id = stringID;
64
- this._data['id'] = this._id;
65
- }
66
- }
67
-
68
- //#endregion
69
-
70
- //#region Public Methods
71
-
72
- /**
73
- * Recreate a DataTrackObject with no mutations.
74
- * Call when data has been synced and is no longer considered mutated.
75
- * @param data - The data to be tracked
76
- */
77
- public dataTrackMutations(data: Partial<Data>): void {
78
- const keys = Object.keys(data) as (keyof Partial<Data>)[];
79
- keys.forEach((key) => {
80
- if (data[key] === undefined) {
81
- return;
82
- }
83
- this.validator(key, data[key]);
84
- });
85
- this._id = data.id;
86
- this._data = trackObjectMutations<Data>(data, this.validator);
87
- }
88
-
89
- //#endregion
90
-
91
- //#region Getters
92
-
93
- /**
94
- * Date of creation of this model in our API.
95
- * Alias: createdAt
96
- */
97
- get created(): Temporal.Instant | undefined {
98
- return this._data.createdAt;
99
- }
100
-
101
- /**
102
- * Date of creation of this model in our API.
103
- * Alias: created
104
- */
105
- get createdAt(): Temporal.Instant | undefined {
106
- return this._data.createdAt;
107
- }
108
-
109
- get deleted(): boolean | undefined {
110
- return this._data.deleted;
111
- }
112
-
113
- get id(): Data['id'] | undefined {
114
- return this._id;
115
- }
116
-
117
- /**
118
- * Get mutated data.
119
- * This is what will be sent to our endpoint.
120
- */
121
- get mutations() {
122
- return this._data.getMutations();
123
- }
124
-
125
- //#endregion
126
- }