cgs-compliance-sdk 2.0.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.
@@ -0,0 +1,546 @@
1
+ // src/core/errors.ts
2
+ var CGSError = class _CGSError extends Error {
3
+ constructor(message, code, statusCode, details) {
4
+ super(message);
5
+ this.code = code;
6
+ this.statusCode = statusCode;
7
+ this.details = details;
8
+ this.name = "CGSError";
9
+ Object.setPrototypeOf(this, _CGSError.prototype);
10
+ }
11
+ };
12
+ var NetworkError = class _NetworkError extends CGSError {
13
+ constructor(message, originalError) {
14
+ super(message, "NETWORK_ERROR", void 0, { originalError });
15
+ this.originalError = originalError;
16
+ this.name = "NetworkError";
17
+ Object.setPrototypeOf(this, _NetworkError.prototype);
18
+ }
19
+ };
20
+ var ServiceUnavailableError = class _ServiceUnavailableError extends CGSError {
21
+ constructor(service) {
22
+ super(`${service} is unavailable`, "SERVICE_UNAVAILABLE", 503, { service });
23
+ this.name = "ServiceUnavailableError";
24
+ Object.setPrototypeOf(this, _ServiceUnavailableError.prototype);
25
+ }
26
+ };
27
+ var AuthenticationError = class _AuthenticationError extends CGSError {
28
+ constructor(message = "Authentication failed") {
29
+ super(message, "AUTHENTICATION_ERROR", 401);
30
+ this.name = "AuthenticationError";
31
+ Object.setPrototypeOf(this, _AuthenticationError.prototype);
32
+ }
33
+ };
34
+ var RateLimitError = class _RateLimitError extends CGSError {
35
+ constructor(retryAfter) {
36
+ super("Rate limit exceeded", "RATE_LIMIT_EXCEEDED", 429, { retryAfter });
37
+ this.retryAfter = retryAfter;
38
+ this.name = "RateLimitError";
39
+ Object.setPrototypeOf(this, _RateLimitError.prototype);
40
+ }
41
+ };
42
+ var TimeoutError = class _TimeoutError extends CGSError {
43
+ constructor(timeout) {
44
+ super(`Request timeout after ${timeout}ms`, "TIMEOUT", 408, { timeout });
45
+ this.timeout = timeout;
46
+ this.name = "TimeoutError";
47
+ Object.setPrototypeOf(this, _TimeoutError.prototype);
48
+ }
49
+ };
50
+
51
+ // src/core/client.ts
52
+ var BaseClient = class {
53
+ constructor(config) {
54
+ this.config = {
55
+ baseURL: config.baseURL,
56
+ tenantId: config.tenantId,
57
+ apiKey: config.apiKey || "",
58
+ headers: config.headers || {},
59
+ timeout: config.timeout || 1e4,
60
+ retries: config.retries || 3,
61
+ debug: config.debug || false
62
+ };
63
+ }
64
+ /**
65
+ * Make an HTTP request with timeout and error handling
66
+ */
67
+ async request(endpoint, options = {}, serviceURL) {
68
+ const url = `${serviceURL || this.config.baseURL}${endpoint}`;
69
+ const headers = {
70
+ "Content-Type": "application/json",
71
+ "X-Tenant-ID": this.config.tenantId,
72
+ ...this.config.headers,
73
+ ...options.headers || {}
74
+ };
75
+ if (this.config.apiKey) {
76
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
77
+ }
78
+ const controller = new AbortController();
79
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
80
+ try {
81
+ if (this.config.debug) {
82
+ console.log(`[CGS SDK] ${options.method || "GET"} ${url}`, {
83
+ headers,
84
+ body: options.body
85
+ });
86
+ }
87
+ const response = await fetch(url, {
88
+ ...options,
89
+ headers,
90
+ signal: controller.signal
91
+ });
92
+ clearTimeout(timeoutId);
93
+ const data = await response.json();
94
+ if (!response.ok) {
95
+ this.handleErrorResponse(response.status, data);
96
+ }
97
+ if (this.config.debug) {
98
+ console.log(`[CGS SDK] Response:`, data);
99
+ }
100
+ return data;
101
+ } catch (error) {
102
+ clearTimeout(timeoutId);
103
+ if (error instanceof Error) {
104
+ if (error.name === "AbortError") {
105
+ throw new TimeoutError(this.config.timeout);
106
+ }
107
+ if (error instanceof CGSError) {
108
+ throw error;
109
+ }
110
+ }
111
+ throw new NetworkError("Network request failed", error);
112
+ }
113
+ }
114
+ /**
115
+ * Make an HTTP request with retry logic
116
+ */
117
+ async requestWithRetry(endpoint, options = {}, serviceURL, retries = this.config.retries) {
118
+ let lastError;
119
+ for (let attempt = 0; attempt <= retries; attempt++) {
120
+ try {
121
+ return await this.request(endpoint, options, serviceURL);
122
+ } catch (error) {
123
+ lastError = error instanceof Error ? error : new Error("Unknown error");
124
+ if (lastError instanceof CGSError && lastError.statusCode && lastError.statusCode >= 400 && lastError.statusCode < 500) {
125
+ throw lastError;
126
+ }
127
+ if (attempt === retries) {
128
+ break;
129
+ }
130
+ const delay = Math.min(1e3 * Math.pow(2, attempt) + Math.random() * 1e3, 1e4);
131
+ await new Promise((resolve) => setTimeout(resolve, delay));
132
+ if (this.config.debug) {
133
+ console.log(`[CGS SDK] Retry attempt ${attempt + 1}/${retries} after ${delay.toFixed(0)}ms`);
134
+ }
135
+ }
136
+ }
137
+ throw new NetworkError(`Request failed after ${retries} retries`, lastError);
138
+ }
139
+ /**
140
+ * Handle error responses from API
141
+ */
142
+ handleErrorResponse(status, data) {
143
+ const message = data.error || data.message || `HTTP ${status}`;
144
+ switch (status) {
145
+ case 400:
146
+ throw new CGSError(message, "BAD_REQUEST", 400, data);
147
+ case 401:
148
+ throw new AuthenticationError(message);
149
+ case 403:
150
+ throw new CGSError(message, "FORBIDDEN", 403, data);
151
+ case 404:
152
+ throw new CGSError(message, "NOT_FOUND", 404, data);
153
+ case 429:
154
+ const retryAfter = data.retry_after || data.retryAfter;
155
+ throw new RateLimitError(retryAfter);
156
+ case 500:
157
+ case 502:
158
+ case 503:
159
+ case 504:
160
+ throw new ServiceUnavailableError(message);
161
+ default:
162
+ throw new CGSError(message, "UNKNOWN_ERROR", status, data);
163
+ }
164
+ }
165
+ /**
166
+ * Build query string from parameters
167
+ */
168
+ buildQueryString(params) {
169
+ const query = new URLSearchParams();
170
+ Object.entries(params).forEach(([key, value]) => {
171
+ if (value !== void 0 && value !== null) {
172
+ if (Array.isArray(value)) {
173
+ value.forEach((item) => query.append(key, String(item)));
174
+ } else {
175
+ query.append(key, String(value));
176
+ }
177
+ }
178
+ });
179
+ const queryString = query.toString();
180
+ return queryString ? `?${queryString}` : "";
181
+ }
182
+ /**
183
+ * Update client configuration
184
+ */
185
+ updateConfig(config) {
186
+ this.config = {
187
+ ...this.config,
188
+ ...config,
189
+ headers: {
190
+ ...this.config.headers,
191
+ ...config.headers || {}
192
+ }
193
+ };
194
+ }
195
+ /**
196
+ * Get current configuration (readonly)
197
+ */
198
+ getConfig() {
199
+ return { ...this.config };
200
+ }
201
+ /**
202
+ * Health check endpoint
203
+ */
204
+ async healthCheck() {
205
+ return this.request("/api/v1/health");
206
+ }
207
+ };
208
+
209
+ // src/risk-profile/client.ts
210
+ var RiskProfileClient = class extends BaseClient {
211
+ constructor(config) {
212
+ super(config);
213
+ }
214
+ // ============================================================================
215
+ // Profile Management
216
+ // ============================================================================
217
+ /**
218
+ * Create a new customer risk profile
219
+ *
220
+ * @param request - Profile creation data
221
+ * @returns Created customer profile
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * const profile = await client.createProfile({
226
+ * customer_id: 'CUST-12345',
227
+ * entity_type: 'individual',
228
+ * customer_status: 'active',
229
+ * full_name: 'John Doe',
230
+ * email_address: 'john@example.com',
231
+ * date_of_birth: '1990-01-15',
232
+ * country_of_residence: 'US'
233
+ * });
234
+ * ```
235
+ */
236
+ async createProfile(request) {
237
+ return this.request("/api/v1/profiles", {
238
+ method: "POST",
239
+ body: JSON.stringify(request)
240
+ });
241
+ }
242
+ /**
243
+ * Get customer profile by customer ID
244
+ *
245
+ * Note: This searches for the profile using the customer_id field.
246
+ * Returns the first matching profile for the tenant.
247
+ *
248
+ * @param customerId - Customer ID to search for
249
+ * @returns Customer profile
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * const profile = await client.getProfile('CUST-12345');
254
+ * console.log('Risk score:', profile.risk_score);
255
+ * ```
256
+ */
257
+ async getProfile(customerId) {
258
+ const response = await this.queryProfiles({
259
+ search: customerId,
260
+ page: 1,
261
+ page_size: 1
262
+ });
263
+ if (response.data.length === 0) {
264
+ throw new Error(`Profile not found for customer ID: ${customerId}`);
265
+ }
266
+ return response.data[0];
267
+ }
268
+ /**
269
+ * Get profile by UUID
270
+ *
271
+ * @param profileId - Profile UUID
272
+ * @returns Customer profile
273
+ */
274
+ async getProfileById(profileId) {
275
+ const details = await this.getProfileDetails(profileId);
276
+ return details.profile;
277
+ }
278
+ /**
279
+ * Get detailed profile information including risk factors and history
280
+ *
281
+ * @param profileId - Profile UUID
282
+ * @returns Detailed profile response with risk factors and history
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * const details = await client.getProfileDetails(profileId);
287
+ * console.log('Risk factors:', details.risk_factors);
288
+ * console.log('Risk history:', details.risk_history);
289
+ * console.log('Alert counts:', {
290
+ * watchlist: details.watchlist_alert_count,
291
+ * fraud: details.fraud_alert_count,
292
+ * geo: details.geolocation_alert_count
293
+ * });
294
+ * ```
295
+ */
296
+ async getProfileDetails(profileId) {
297
+ return this.request(
298
+ `/api/v1/risk-dashboard/profiles/${profileId}`
299
+ );
300
+ }
301
+ /**
302
+ * Update customer profile
303
+ *
304
+ * @param profileId - Profile UUID
305
+ * @param updates - Fields to update
306
+ * @returns Updated customer profile
307
+ *
308
+ * @example
309
+ * ```typescript
310
+ * const updated = await client.updateProfile(profileId, {
311
+ * location: 'New York, USA',
312
+ * location_compliance: 'compliant',
313
+ * last_recorded_activity: new Date().toISOString()
314
+ * });
315
+ * ```
316
+ */
317
+ async updateProfile(profileId, updates) {
318
+ return this.request(`/api/v1/profiles/${profileId}`, {
319
+ method: "PUT",
320
+ body: JSON.stringify(updates)
321
+ });
322
+ }
323
+ /**
324
+ * Manually recalculate risk score for a profile
325
+ *
326
+ * Triggers immediate risk score recalculation based on current risk factors.
327
+ *
328
+ * @param profileId - Profile UUID
329
+ * @param reason - Optional reason for recalculation
330
+ *
331
+ * @example
332
+ * ```typescript
333
+ * await client.recalculateRiskScore(profileId, 'Manual review completed');
334
+ * ```
335
+ */
336
+ async recalculateRiskScore(profileId, reason) {
337
+ const body = reason ? JSON.stringify({ reason }) : void 0;
338
+ await this.request(`/api/v1/profiles/recalculate/${profileId}`, {
339
+ method: "POST",
340
+ body
341
+ });
342
+ }
343
+ // ============================================================================
344
+ // Query & Search
345
+ // ============================================================================
346
+ /**
347
+ * Query profiles with advanced filters
348
+ *
349
+ * @param filters - Filter criteria and pagination
350
+ * @returns Paginated list of profiles
351
+ *
352
+ * @example
353
+ * ```typescript
354
+ * const results = await client.queryProfiles({
355
+ * risk_category: ['high', 'critical'],
356
+ * kyc_status: ['pending'],
357
+ * is_pep: true,
358
+ * page: 1,
359
+ * page_size: 20,
360
+ * sort_by: 'risk_score',
361
+ * sort_order: 'desc'
362
+ * });
363
+ *
364
+ * console.log(`Found ${results.total} high-risk profiles`);
365
+ * results.data.forEach(profile => {
366
+ * console.log(`${profile.full_name}: ${profile.risk_score}`);
367
+ * });
368
+ * ```
369
+ */
370
+ async queryProfiles(filters = {}) {
371
+ const queryString = this.buildQueryString(filters);
372
+ return this.request(
373
+ `/api/v1/risk-dashboard/profiles${queryString}`
374
+ );
375
+ }
376
+ /**
377
+ * Search profiles by text (searches name, email, customer_id, account_number)
378
+ *
379
+ * @param searchText - Text to search for
380
+ * @param limit - Maximum results to return (default: 10)
381
+ * @returns Array of matching profiles
382
+ */
383
+ async searchProfiles(searchText, limit = 10) {
384
+ const response = await this.queryProfiles({
385
+ search: searchText,
386
+ page: 1,
387
+ page_size: limit
388
+ });
389
+ return response.data;
390
+ }
391
+ /**
392
+ * Get all high-risk profiles (high + critical)
393
+ *
394
+ * @param limit - Maximum results to return (default: 50)
395
+ * @returns Array of high-risk profiles
396
+ */
397
+ async getHighRiskProfiles(limit = 50) {
398
+ const response = await this.queryProfiles({
399
+ risk_category: ["high", "critical"],
400
+ page: 1,
401
+ page_size: limit,
402
+ sort_by: "risk_score",
403
+ sort_order: "desc"
404
+ });
405
+ return response.data;
406
+ }
407
+ /**
408
+ * Get profiles requiring PEP review
409
+ *
410
+ * @param limit - Maximum results to return (default: 50)
411
+ * @returns Array of PEP profiles
412
+ */
413
+ async getPEPProfiles(limit = 50) {
414
+ const response = await this.queryProfiles({
415
+ is_pep: true,
416
+ page: 1,
417
+ page_size: limit
418
+ });
419
+ return response.data;
420
+ }
421
+ /**
422
+ * Get profiles with sanctions matches
423
+ *
424
+ * @param limit - Maximum results to return (default: 50)
425
+ * @returns Array of sanctioned profiles
426
+ */
427
+ async getSanctionedProfiles(limit = 50) {
428
+ const response = await this.queryProfiles({
429
+ has_sanctions: true,
430
+ page: 1,
431
+ page_size: limit
432
+ });
433
+ return response.data;
434
+ }
435
+ // ============================================================================
436
+ // Dashboard & Metrics
437
+ // ============================================================================
438
+ /**
439
+ * Get risk dashboard metrics and statistics
440
+ *
441
+ * @param startDate - Optional start date for metrics (ISO format)
442
+ * @param endDate - Optional end date for metrics (ISO format)
443
+ * @returns Dashboard metrics
444
+ *
445
+ * @example
446
+ * ```typescript
447
+ * const metrics = await client.getDashboardMetrics();
448
+ * console.log('Total risky profiles:', metrics.total_risky_profiles);
449
+ * console.log('Critical profiles:', metrics.total_critical_profiles);
450
+ * console.log('Average risk score:', metrics.average_risk_score);
451
+ *
452
+ * metrics.risk_distribution.forEach(item => {
453
+ * console.log(`${item.category}: ${item.count} (${item.percentage}%)`);
454
+ * });
455
+ * ```
456
+ */
457
+ async getDashboardMetrics(startDate, endDate) {
458
+ const params = {};
459
+ if (startDate) params.start_date = startDate;
460
+ if (endDate) params.end_date = endDate;
461
+ const queryString = this.buildQueryString(params);
462
+ return this.request(
463
+ `/api/v1/risk-dashboard/metrics${queryString}`
464
+ );
465
+ }
466
+ // ============================================================================
467
+ // Bulk Operations
468
+ // ============================================================================
469
+ /**
470
+ * Get or create profile (idempotent operation)
471
+ *
472
+ * Attempts to get existing profile by customer_id, creates if not found.
473
+ *
474
+ * @param customerId - Customer ID
475
+ * @param createRequest - Profile data to use if creating new profile
476
+ * @returns Existing or newly created profile
477
+ *
478
+ * @example
479
+ * ```typescript
480
+ * const profile = await client.getOrCreateProfile('CUST-123', {
481
+ * customer_id: 'CUST-123',
482
+ * entity_type: 'individual',
483
+ * full_name: 'John Doe',
484
+ * email_address: 'john@example.com'
485
+ * });
486
+ * ```
487
+ */
488
+ async getOrCreateProfile(customerId, createRequest) {
489
+ try {
490
+ return await this.getProfile(customerId);
491
+ } catch (error) {
492
+ return await this.createProfile(createRequest);
493
+ }
494
+ }
495
+ /**
496
+ * Batch get profiles by customer IDs
497
+ *
498
+ * @param customerIds - Array of customer IDs
499
+ * @returns Array of profiles (may be less than input if some not found)
500
+ */
501
+ async batchGetProfiles(customerIds) {
502
+ const profiles = [];
503
+ for (const customerId of customerIds) {
504
+ try {
505
+ const profile = await this.getProfile(customerId);
506
+ profiles.push(profile);
507
+ } catch (error) {
508
+ if (this.config.debug) {
509
+ console.warn(`[RiskProfileClient] Profile not found for: ${customerId}`);
510
+ }
511
+ }
512
+ }
513
+ return profiles;
514
+ }
515
+ // ============================================================================
516
+ // Configuration
517
+ // ============================================================================
518
+ /**
519
+ * Get risk configuration for tenant
520
+ *
521
+ * Returns the risk scoring weights and thresholds configured for the tenant.
522
+ *
523
+ * @returns Risk configuration
524
+ */
525
+ async getRiskConfiguration() {
526
+ return this.request("/api/v1/risk-config");
527
+ }
528
+ /**
529
+ * Update risk configuration for tenant
530
+ *
531
+ * Updates risk scoring weights and/or thresholds.
532
+ *
533
+ * @param config - Configuration updates
534
+ * @returns Updated risk configuration
535
+ */
536
+ async updateRiskConfiguration(config) {
537
+ return this.request("/api/v1/risk-config", {
538
+ method: "PUT",
539
+ body: JSON.stringify(config)
540
+ });
541
+ }
542
+ };
543
+
544
+ export { RiskProfileClient };
545
+ //# sourceMappingURL=index.mjs.map
546
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/errors.ts","../../src/core/client.ts","../../src/risk-profile/client.ts"],"names":[],"mappings":";AAOO,IAAM,QAAA,GAAN,MAAM,SAAA,SAAiB,KAAA,CAAM;AAAA,EAClC,WAAA,CACE,OAAA,EACO,IAAA,EACA,UAAA,EACA,OAAA,EACP;AACA,IAAA,KAAA,CA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CACJ,UAAA,EACA,aAAA,EAC0B;AAC1B,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,IAAA,CAAK,UAAA,CAAW,UAAU,CAAA;AAAA,IACzC,SAAS,KAAA,EAAO;AAEd,MAAA,OAAO,MAAM,IAAA,CAAK,aAAA,CAAc,aAAa,CAAA;AAAA,IAC/C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,iBAAiB,WAAA,EAAmD;AAGxE,IAAA,MAAM,WAA8B,EAAC;AAErC,IAAA,KAAA,MAAW,cAAc,WAAA,EAAa;AACpC,MAAA,IAAI;AACF,QAAA,MAAM,OAAA,GAAU,MAAM,IAAA,CAAK,UAAA,CAAW,UAAU,CAAA;AAChD,QAAA,QAAA,CAAS,KAAK,OAAO,CAAA;AAAA,MACvB,SAAS,KAAA,EAAO;AAEd,QAAA,IAAI,IAAA,CAAK,OAAO,KAAA,EAAO;AACrB,UAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,2CAAA,EAA8C,UAAU,CAAA,CAAE,CAAA;AAAA,QACzE;AAAA,MACF;AAAA,IACF;AAEA,IAAA,OAAO,QAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,oBAAA,GAAmD;AACvD,IAAA,OAAO,IAAA,CAAK,QAA2B,qBAAqB,CAAA;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,wBACJ,MAAA,EAC4B;AAC5B,IAAA,OAAO,IAAA,CAAK,QAA2B,qBAAA,EAAuB;AAAA,MAC5D,MAAA,EAAQ,KAAA;AAAA,MACR,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,MAAM;AAAA,KAC5B,CAAA;AAAA,EACH;AACF","file":"index.mjs","sourcesContent":["/**\n * Error hierarchy for CGS SDK\n *\n * Provides structured error handling with specific error types\n * for different failure scenarios.\n */\n\nexport class CGSError extends Error {\n constructor(\n message: string,\n public code: string,\n public statusCode?: number,\n public details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'CGSError';\n Object.setPrototypeOf(this, CGSError.prototype);\n }\n}\n\nexport class NetworkError extends CGSError {\n constructor(message: string, public originalError?: unknown) {\n super(message, 'NETWORK_ERROR', undefined, { originalError });\n this.name = 'NetworkError';\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\nexport class ValidationError extends CGSError {\n constructor(message: string, fields?: string[]) {\n super(message, 'VALIDATION_ERROR', 400, { fields });\n this.name = 'ValidationError';\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class ServiceUnavailableError extends CGSError {\n constructor(service: string) {\n super(`${service} is unavailable`, 'SERVICE_UNAVAILABLE', 503, { service });\n this.name = 'ServiceUnavailableError';\n Object.setPrototypeOf(this, ServiceUnavailableError.prototype);\n }\n}\n\nexport class ComplianceBlockedError extends CGSError {\n constructor(reasons: string[]) {\n super('Access blocked due to compliance rules', 'COMPLIANCE_BLOCKED', 403, { reasons });\n this.name = 'ComplianceBlockedError';\n Object.setPrototypeOf(this, ComplianceBlockedError.prototype);\n }\n}\n\nexport class AuthenticationError extends CGSError {\n constructor(message: string = 'Authentication failed') {\n super(message, 'AUTHENTICATION_ERROR', 401);\n this.name = 'AuthenticationError';\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\nexport class RateLimitError extends CGSError {\n constructor(public retryAfter?: number) {\n super('Rate limit exceeded', 'RATE_LIMIT_EXCEEDED', 429, { retryAfter });\n this.name = 'RateLimitError';\n Object.setPrototypeOf(this, RateLimitError.prototype);\n }\n}\n\nexport class TimeoutError extends CGSError {\n constructor(public timeout: number) {\n super(`Request timeout after ${timeout}ms`, 'TIMEOUT', 408, { timeout });\n this.name = 'TimeoutError';\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\nexport class ComplianceError extends CGSError {\n constructor(\n message: string,\n public originalError?: unknown,\n code: string = 'COMPLIANCE_ERROR'\n ) {\n super(message, code, undefined, { originalError });\n this.name = 'ComplianceError';\n Object.setPrototypeOf(this, ComplianceError.prototype);\n }\n}\n","/**\n * Base HTTP client for all CGS SDK clients\n *\n * Provides common functionality:\n * - Request/response handling\n * - Error handling\n * - Retry logic with exponential backoff\n * - Timeout management\n * - Debug logging\n */\n\nimport type { BaseClientConfig, RequiredBaseClientConfig } from './config';\nimport {\n CGSError,\n NetworkError,\n TimeoutError,\n AuthenticationError,\n RateLimitError,\n ServiceUnavailableError,\n} from './errors';\n\nexport abstract class BaseClient {\n protected config: RequiredBaseClientConfig;\n\n constructor(config: BaseClientConfig) {\n this.config = {\n baseURL: config.baseURL,\n tenantId: config.tenantId,\n apiKey: config.apiKey || '',\n headers: config.headers || {},\n timeout: config.timeout || 10000,\n retries: config.retries || 3,\n debug: config.debug || false,\n };\n }\n\n /**\n * Make an HTTP request with timeout and error handling\n */\n protected async request<T>(\n endpoint: string,\n options: RequestInit = {},\n serviceURL?: string\n ): Promise<T> {\n const url = `${serviceURL || this.config.baseURL}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Tenant-ID': this.config.tenantId,\n ...this.config.headers,\n ...((options.headers as Record<string, string>) || {}),\n };\n\n if (this.config.apiKey) {\n headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n try {\n if (this.config.debug) {\n console.log(`[CGS SDK] ${options.method || 'GET'} ${url}`, {\n headers,\n body: options.body,\n });\n }\n\n const response = await fetch(url, {\n ...options,\n headers,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n const data = await response.json();\n\n if (!response.ok) {\n this.handleErrorResponse(response.status, data);\n }\n\n if (this.config.debug) {\n console.log(`[CGS SDK] Response:`, data);\n }\n\n return data as T;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new TimeoutError(this.config.timeout);\n }\n if (error instanceof CGSError) {\n throw error;\n }\n }\n\n throw new NetworkError('Network request failed', error);\n }\n }\n\n /**\n * Make an HTTP request with retry logic\n */\n protected async requestWithRetry<T>(\n endpoint: string,\n options: RequestInit = {},\n serviceURL?: string,\n retries: number = this.config.retries\n ): Promise<T> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await this.request<T>(endpoint, options, serviceURL);\n } catch (error) {\n lastError = error instanceof Error ? error : new Error('Unknown error');\n\n // Don't retry on client errors (4xx) or authentication errors\n if (\n lastError instanceof CGSError &&\n lastError.statusCode &&\n lastError.statusCode >= 400 &&\n lastError.statusCode < 500\n ) {\n throw lastError;\n }\n\n // Don't retry on last attempt\n if (attempt === retries) {\n break;\n }\n\n // Exponential backoff with jitter\n const delay = Math.min(1000 * Math.pow(2, attempt) + Math.random() * 1000, 10000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n if (this.config.debug) {\n console.log(`[CGS SDK] Retry attempt ${attempt + 1}/${retries} after ${delay.toFixed(0)}ms`);\n }\n }\n }\n\n throw new NetworkError(`Request failed after ${retries} retries`, lastError);\n }\n\n /**\n * Handle error responses from API\n */\n protected handleErrorResponse(status: number, data: any): never {\n const message = data.error || data.message || `HTTP ${status}`;\n\n switch (status) {\n case 400:\n throw new CGSError(message, 'BAD_REQUEST', 400, data);\n case 401:\n throw new AuthenticationError(message);\n case 403:\n throw new CGSError(message, 'FORBIDDEN', 403, data);\n case 404:\n throw new CGSError(message, 'NOT_FOUND', 404, data);\n case 429:\n const retryAfter = data.retry_after || data.retryAfter;\n throw new RateLimitError(retryAfter);\n case 500:\n case 502:\n case 503:\n case 504:\n throw new ServiceUnavailableError(message);\n default:\n throw new CGSError(message, 'UNKNOWN_ERROR', status, data);\n }\n }\n\n /**\n * Build query string from parameters\n */\n protected buildQueryString(params: Record<string, unknown>): string {\n const query = new URLSearchParams();\n\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n if (Array.isArray(value)) {\n value.forEach((item) => query.append(key, String(item)));\n } else {\n query.append(key, String(value));\n }\n }\n });\n\n const queryString = query.toString();\n return queryString ? `?${queryString}` : '';\n }\n\n /**\n * Update client configuration\n */\n updateConfig(config: Partial<BaseClientConfig>): void {\n this.config = {\n ...this.config,\n ...config,\n headers: {\n ...this.config.headers,\n ...(config.headers || {}),\n },\n };\n }\n\n /**\n * Get current configuration (readonly)\n */\n getConfig(): Readonly<BaseClientConfig> {\n return { ...this.config };\n }\n\n /**\n * Health check endpoint\n */\n async healthCheck(): Promise<{ status: string; timestamp: string }> {\n return this.request('/api/v1/health');\n }\n}\n","/**\n * RiskProfileClient - Customer Risk Profile Management\n *\n * Provides methods to create, retrieve, and manage customer risk profiles\n * in the CGS Compliance Platform.\n */\n\nimport { BaseClient } from '../core/client';\nimport type { BaseClientConfig } from '../core/config';\nimport type {\n CustomerProfile,\n CreateProfileRequest,\n UpdateProfileRequest,\n ProfileDetailsResponse,\n ProfileFilters,\n ProfileListResponse,\n RiskDashboardMetrics,\n RiskConfiguration,\n} from './types';\n\nexport class RiskProfileClient extends BaseClient {\n constructor(config: BaseClientConfig) {\n super(config);\n }\n\n // ============================================================================\n // Profile Management\n // ============================================================================\n\n /**\n * Create a new customer risk profile\n *\n * @param request - Profile creation data\n * @returns Created customer profile\n *\n * @example\n * ```typescript\n * const profile = await client.createProfile({\n * customer_id: 'CUST-12345',\n * entity_type: 'individual',\n * customer_status: 'active',\n * full_name: 'John Doe',\n * email_address: 'john@example.com',\n * date_of_birth: '1990-01-15',\n * country_of_residence: 'US'\n * });\n * ```\n */\n async createProfile(request: CreateProfileRequest): Promise<CustomerProfile> {\n return this.request<CustomerProfile>('/api/v1/profiles', {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n /**\n * Get customer profile by customer ID\n *\n * Note: This searches for the profile using the customer_id field.\n * Returns the first matching profile for the tenant.\n *\n * @param customerId - Customer ID to search for\n * @returns Customer profile\n *\n * @example\n * ```typescript\n * const profile = await client.getProfile('CUST-12345');\n * console.log('Risk score:', profile.risk_score);\n * ```\n */\n async getProfile(customerId: string): Promise<CustomerProfile> {\n const response = await this.queryProfiles({\n search: customerId,\n page: 1,\n page_size: 1,\n });\n\n if (response.data.length === 0) {\n throw new Error(`Profile not found for customer ID: ${customerId}`);\n }\n\n return response.data[0];\n }\n\n /**\n * Get profile by UUID\n *\n * @param profileId - Profile UUID\n * @returns Customer profile\n */\n async getProfileById(profileId: string): Promise<CustomerProfile> {\n // Note: The dashboard endpoint provides detailed profile view\n const details = await this.getProfileDetails(profileId);\n return details.profile;\n }\n\n /**\n * Get detailed profile information including risk factors and history\n *\n * @param profileId - Profile UUID\n * @returns Detailed profile response with risk factors and history\n *\n * @example\n * ```typescript\n * const details = await client.getProfileDetails(profileId);\n * console.log('Risk factors:', details.risk_factors);\n * console.log('Risk history:', details.risk_history);\n * console.log('Alert counts:', {\n * watchlist: details.watchlist_alert_count,\n * fraud: details.fraud_alert_count,\n * geo: details.geolocation_alert_count\n * });\n * ```\n */\n async getProfileDetails(profileId: string): Promise<ProfileDetailsResponse> {\n return this.request<ProfileDetailsResponse>(\n `/api/v1/risk-dashboard/profiles/${profileId}`\n );\n }\n\n /**\n * Update customer profile\n *\n * @param profileId - Profile UUID\n * @param updates - Fields to update\n * @returns Updated customer profile\n *\n * @example\n * ```typescript\n * const updated = await client.updateProfile(profileId, {\n * location: 'New York, USA',\n * location_compliance: 'compliant',\n * last_recorded_activity: new Date().toISOString()\n * });\n * ```\n */\n async updateProfile(\n profileId: string,\n updates: UpdateProfileRequest\n ): Promise<CustomerProfile> {\n return this.request<CustomerProfile>(`/api/v1/profiles/${profileId}`, {\n method: 'PUT',\n body: JSON.stringify(updates),\n });\n }\n\n /**\n * Manually recalculate risk score for a profile\n *\n * Triggers immediate risk score recalculation based on current risk factors.\n *\n * @param profileId - Profile UUID\n * @param reason - Optional reason for recalculation\n *\n * @example\n * ```typescript\n * await client.recalculateRiskScore(profileId, 'Manual review completed');\n * ```\n */\n async recalculateRiskScore(profileId: string, reason?: string): Promise<void> {\n const body = reason ? JSON.stringify({ reason }) : undefined;\n await this.request(`/api/v1/profiles/recalculate/${profileId}`, {\n method: 'POST',\n body,\n });\n }\n\n // ============================================================================\n // Query & Search\n // ============================================================================\n\n /**\n * Query profiles with advanced filters\n *\n * @param filters - Filter criteria and pagination\n * @returns Paginated list of profiles\n *\n * @example\n * ```typescript\n * const results = await client.queryProfiles({\n * risk_category: ['high', 'critical'],\n * kyc_status: ['pending'],\n * is_pep: true,\n * page: 1,\n * page_size: 20,\n * sort_by: 'risk_score',\n * sort_order: 'desc'\n * });\n *\n * console.log(`Found ${results.total} high-risk profiles`);\n * results.data.forEach(profile => {\n * console.log(`${profile.full_name}: ${profile.risk_score}`);\n * });\n * ```\n */\n async queryProfiles(filters: ProfileFilters = {}): Promise<ProfileListResponse> {\n const queryString = this.buildQueryString(filters);\n return this.request<ProfileListResponse>(\n `/api/v1/risk-dashboard/profiles${queryString}`\n );\n }\n\n /**\n * Search profiles by text (searches name, email, customer_id, account_number)\n *\n * @param searchText - Text to search for\n * @param limit - Maximum results to return (default: 10)\n * @returns Array of matching profiles\n */\n async searchProfiles(searchText: string, limit: number = 10): Promise<CustomerProfile[]> {\n const response = await this.queryProfiles({\n search: searchText,\n page: 1,\n page_size: limit,\n });\n return response.data;\n }\n\n /**\n * Get all high-risk profiles (high + critical)\n *\n * @param limit - Maximum results to return (default: 50)\n * @returns Array of high-risk profiles\n */\n async getHighRiskProfiles(limit: number = 50): Promise<CustomerProfile[]> {\n const response = await this.queryProfiles({\n risk_category: ['high', 'critical'],\n page: 1,\n page_size: limit,\n sort_by: 'risk_score',\n sort_order: 'desc',\n });\n return response.data;\n }\n\n /**\n * Get profiles requiring PEP review\n *\n * @param limit - Maximum results to return (default: 50)\n * @returns Array of PEP profiles\n */\n async getPEPProfiles(limit: number = 50): Promise<CustomerProfile[]> {\n const response = await this.queryProfiles({\n is_pep: true,\n page: 1,\n page_size: limit,\n });\n return response.data;\n }\n\n /**\n * Get profiles with sanctions matches\n *\n * @param limit - Maximum results to return (default: 50)\n * @returns Array of sanctioned profiles\n */\n async getSanctionedProfiles(limit: number = 50): Promise<CustomerProfile[]> {\n const response = await this.queryProfiles({\n has_sanctions: true,\n page: 1,\n page_size: limit,\n });\n return response.data;\n }\n\n // ============================================================================\n // Dashboard & Metrics\n // ============================================================================\n\n /**\n * Get risk dashboard metrics and statistics\n *\n * @param startDate - Optional start date for metrics (ISO format)\n * @param endDate - Optional end date for metrics (ISO format)\n * @returns Dashboard metrics\n *\n * @example\n * ```typescript\n * const metrics = await client.getDashboardMetrics();\n * console.log('Total risky profiles:', metrics.total_risky_profiles);\n * console.log('Critical profiles:', metrics.total_critical_profiles);\n * console.log('Average risk score:', metrics.average_risk_score);\n *\n * metrics.risk_distribution.forEach(item => {\n * console.log(`${item.category}: ${item.count} (${item.percentage}%)`);\n * });\n * ```\n */\n async getDashboardMetrics(\n startDate?: string,\n endDate?: string\n ): Promise<RiskDashboardMetrics> {\n const params: Record<string, string> = {};\n if (startDate) params.start_date = startDate;\n if (endDate) params.end_date = endDate;\n\n const queryString = this.buildQueryString(params);\n return this.request<RiskDashboardMetrics>(\n `/api/v1/risk-dashboard/metrics${queryString}`\n );\n }\n\n // ============================================================================\n // Bulk Operations\n // ============================================================================\n\n /**\n * Get or create profile (idempotent operation)\n *\n * Attempts to get existing profile by customer_id, creates if not found.\n *\n * @param customerId - Customer ID\n * @param createRequest - Profile data to use if creating new profile\n * @returns Existing or newly created profile\n *\n * @example\n * ```typescript\n * const profile = await client.getOrCreateProfile('CUST-123', {\n * customer_id: 'CUST-123',\n * entity_type: 'individual',\n * full_name: 'John Doe',\n * email_address: 'john@example.com'\n * });\n * ```\n */\n async getOrCreateProfile(\n customerId: string,\n createRequest: CreateProfileRequest\n ): Promise<CustomerProfile> {\n try {\n return await this.getProfile(customerId);\n } catch (error) {\n // Profile doesn't exist, create it\n return await this.createProfile(createRequest);\n }\n }\n\n /**\n * Batch get profiles by customer IDs\n *\n * @param customerIds - Array of customer IDs\n * @returns Array of profiles (may be less than input if some not found)\n */\n async batchGetProfiles(customerIds: string[]): Promise<CustomerProfile[]> {\n // Note: Current API doesn't have batch endpoint, so we query with search\n // In production, this should use a dedicated batch endpoint\n const profiles: CustomerProfile[] = [];\n\n for (const customerId of customerIds) {\n try {\n const profile = await this.getProfile(customerId);\n profiles.push(profile);\n } catch (error) {\n // Profile not found, skip\n if (this.config.debug) {\n console.warn(`[RiskProfileClient] Profile not found for: ${customerId}`);\n }\n }\n }\n\n return profiles;\n }\n\n // ============================================================================\n // Configuration\n // ============================================================================\n\n /**\n * Get risk configuration for tenant\n *\n * Returns the risk scoring weights and thresholds configured for the tenant.\n *\n * @returns Risk configuration\n */\n async getRiskConfiguration(): Promise<RiskConfiguration> {\n return this.request<RiskConfiguration>('/api/v1/risk-config');\n }\n\n /**\n * Update risk configuration for tenant\n *\n * Updates risk scoring weights and/or thresholds.\n *\n * @param config - Configuration updates\n * @returns Updated risk configuration\n */\n async updateRiskConfiguration(\n config: Partial<RiskConfiguration>\n ): Promise<RiskConfiguration> {\n return this.request<RiskConfiguration>('/api/v1/risk-config', {\n method: 'PUT',\n body: JSON.stringify(config),\n });\n }\n}\n"]}