@k-msg/core 0.1.0 → 0.1.2

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.
package/dist/index.d.ts CHANGED
@@ -1,565 +1,12 @@
1
- /**
2
- * Standardized error handling system for K-Message Platform
3
- */
4
- declare enum KMessageErrorCode {
5
- UNKNOWN_ERROR = "UNKNOWN_ERROR",
6
- VALIDATION_ERROR = "VALIDATION_ERROR",
7
- CONFIGURATION_ERROR = "CONFIGURATION_ERROR",
8
- PROVIDER_NOT_FOUND = "PROVIDER_NOT_FOUND",
9
- PROVIDER_NOT_AVAILABLE = "PROVIDER_NOT_AVAILABLE",
10
- PROVIDER_AUTHENTICATION_FAILED = "PROVIDER_AUTHENTICATION_FAILED",
11
- PROVIDER_CONNECTION_FAILED = "PROVIDER_CONNECTION_FAILED",
12
- PROVIDER_RATE_LIMITED = "PROVIDER_RATE_LIMITED",
13
- PROVIDER_INSUFFICIENT_BALANCE = "PROVIDER_INSUFFICIENT_BALANCE",
14
- TEMPLATE_NOT_FOUND = "TEMPLATE_NOT_FOUND",
15
- TEMPLATE_VALIDATION_FAILED = "TEMPLATE_VALIDATION_FAILED",
16
- TEMPLATE_CREATION_FAILED = "TEMPLATE_CREATION_FAILED",
17
- TEMPLATE_MODIFICATION_FAILED = "TEMPLATE_MODIFICATION_FAILED",
18
- TEMPLATE_DELETION_FAILED = "TEMPLATE_DELETION_FAILED",
19
- MESSAGE_SEND_FAILED = "MESSAGE_SEND_FAILED",
20
- MESSAGE_INVALID_PHONE_NUMBER = "MESSAGE_INVALID_PHONE_NUMBER",
21
- MESSAGE_INVALID_VARIABLES = "MESSAGE_INVALID_VARIABLES",
22
- MESSAGE_QUOTA_EXCEEDED = "MESSAGE_QUOTA_EXCEEDED",
23
- MESSAGE_RESERVATION_FAILED = "MESSAGE_RESERVATION_FAILED",
24
- MESSAGE_CANCELLATION_FAILED = "MESSAGE_CANCELLATION_FAILED",
25
- NETWORK_TIMEOUT = "NETWORK_TIMEOUT",
26
- NETWORK_CONNECTION_FAILED = "NETWORK_CONNECTION_FAILED",
27
- NETWORK_SERVICE_UNAVAILABLE = "NETWORK_SERVICE_UNAVAILABLE",
28
- API_INVALID_REQUEST = "API_INVALID_REQUEST",
29
- API_UNAUTHORIZED = "API_UNAUTHORIZED",
30
- API_FORBIDDEN = "API_FORBIDDEN",
31
- API_NOT_FOUND = "API_NOT_FOUND",
32
- API_TOO_MANY_REQUESTS = "API_TOO_MANY_REQUESTS",
33
- API_INTERNAL_SERVER_ERROR = "API_INTERNAL_SERVER_ERROR"
34
- }
35
- interface KMessageErrorContext {
36
- providerId?: string;
37
- templateCode?: string;
38
- phoneNumber?: string;
39
- messageId?: string;
40
- requestId?: string;
41
- timestamp?: Date;
42
- [key: string]: any;
43
- }
44
- declare class KMessageError extends Error {
45
- readonly code: KMessageErrorCode;
46
- readonly context: KMessageErrorContext;
47
- readonly retryable: boolean;
48
- readonly statusCode?: number;
49
- readonly cause?: Error;
50
- constructor(code: KMessageErrorCode, message: string, context?: KMessageErrorContext, options?: {
51
- retryable?: boolean;
52
- statusCode?: number;
53
- cause?: Error;
54
- });
55
- private isRetryableByDefault;
56
- toJSON(): {
57
- name: string;
58
- code: KMessageErrorCode;
59
- message: string;
60
- context: KMessageErrorContext;
61
- retryable: boolean;
62
- statusCode: number | undefined;
63
- stack: string | undefined;
64
- };
65
- }
66
- declare class ProviderError extends KMessageError {
67
- constructor(providerId: string, code: KMessageErrorCode, message: string, context?: Omit<KMessageErrorContext, 'providerId'>, options?: {
68
- retryable?: boolean;
69
- statusCode?: number;
70
- cause?: Error;
71
- });
72
- }
73
- declare class TemplateError extends KMessageError {
74
- constructor(templateCode: string, code: KMessageErrorCode, message: string, context?: Omit<KMessageErrorContext, 'templateCode'>, options?: {
75
- retryable?: boolean;
76
- statusCode?: number;
77
- cause?: Error;
78
- });
79
- }
80
- declare class MessageError extends KMessageError {
81
- constructor(phoneNumber: string, code: KMessageErrorCode, message: string, context?: Omit<KMessageErrorContext, 'phoneNumber'>, options?: {
82
- retryable?: boolean;
83
- statusCode?: number;
84
- cause?: Error;
85
- });
86
- }
87
- /**
88
- * Error factory functions for common error scenarios
89
- */
90
- declare const ErrorFactory: {
91
- providerNotFound: (providerId: string) => ProviderError;
92
- providerNotAvailable: (providerId: string, reason?: string) => ProviderError;
93
- authenticationFailed: (providerId: string, details?: string) => ProviderError;
94
- templateNotFound: (templateCode: string) => TemplateError;
95
- invalidPhoneNumber: (phoneNumber: string) => MessageError;
96
- networkTimeout: (providerId?: string, timeout?: number) => KMessageError;
97
- rateLimited: (providerId: string, retryAfter?: number) => ProviderError;
98
- insufficientBalance: (providerId: string, balance?: string) => ProviderError;
99
- fromHttpStatus: (statusCode: number, message: string, context?: KMessageErrorContext) => KMessageError;
100
- };
101
- /**
102
- * Result wrapper for operations that can fail
103
- */
104
- type Result<T, E = KMessageError> = {
105
- success: true;
106
- data: T;
107
- } | {
108
- success: false;
109
- error: E;
110
- };
111
- declare const Result: {
112
- success: <T>(data: T) => Result<T>;
113
- failure: <E = KMessageError>(error: E) => Result<never, E>;
114
- fromPromise: <T>(promise: Promise<T>) => Promise<Result<T>>;
115
- };
116
- /**
117
- * Error handling utilities
118
- */
119
- declare const ErrorUtils: {
120
- isRetryable: (error: Error) => boolean;
121
- getStatusCode: (error: Error) => number;
122
- formatErrorForClient: (error: Error) => {
123
- code: KMessageErrorCode;
124
- message: string;
125
- retryable: boolean;
126
- context: KMessageErrorContext;
127
- };
128
- formatErrorForLogging: (error: Error) => {
129
- name: string;
130
- message: string;
131
- stack: string | undefined;
132
- } | {
133
- code: KMessageErrorCode;
134
- context: KMessageErrorContext;
135
- retryable: boolean;
136
- statusCode: number | undefined;
137
- name: string;
138
- message: string;
139
- stack: string | undefined;
140
- };
141
- };
142
-
143
- /**
144
- * Test utilities for K-Message Platform
145
- */
146
-
147
- /**
148
- * Mock provider for testing
149
- */
150
- declare class MockProvider implements BaseProvider {
151
- readonly id: string;
152
- readonly name: string;
153
- private _healthy;
154
- private _issues;
155
- private _balance;
156
- private _templates;
157
- private _history;
158
- constructor(id?: string, name?: string);
159
- healthCheck(): Promise<ProviderHealthStatus>;
160
- setHealthy(healthy: boolean, issues?: string[]): void;
161
- setBalance(balance: string): void;
162
- setTemplates(templates: any[]): void;
163
- setHistory(history: any[]): void;
164
- sendMessage(templateCode: string, phoneNumber: string, variables: Record<string, any>, options?: any): Promise<{
165
- success: boolean;
166
- messageId: string;
167
- status: string;
168
- error: null;
169
- }>;
170
- getTemplates(page?: number, size?: number, filters?: any): Promise<{
171
- code: number;
172
- message: string;
173
- totalCount: number;
174
- list: any[];
175
- }>;
176
- createTemplate(name: string, content: string, category?: string, buttons?: any[]): Promise<{
177
- success: boolean;
178
- templateCode: string;
179
- status: string;
180
- error: null;
181
- }>;
182
- modifyTemplate(templateCode: string, name: string, content: string, buttons?: any[]): Promise<{
183
- success: boolean;
184
- templateCode: string;
185
- status: string;
186
- error: null;
187
- }>;
188
- deleteTemplate(templateCode: string): Promise<{
189
- code: number;
190
- message: string;
191
- }>;
192
- getHistory(page?: number, size?: number, filters?: any): Promise<{
193
- code: number;
194
- message: string;
195
- totalCount: number;
196
- list: any[];
197
- }>;
198
- cancelReservation(messageId: string): Promise<{
199
- code: number;
200
- message: string;
201
- }>;
202
- }
203
- /**
204
- * Test assertion helpers
205
- */
206
- declare const TestAssertions: {
207
- /**
208
- * Assert that an error is a KMessageError with specific code
209
- */
210
- assertKMessageError: (error: unknown, expectedCode: KMessageErrorCode, expectedMessage?: string) => void;
211
- /**
212
- * Assert that an error is retryable
213
- */
214
- assertRetryable: (error: KMessageError, expected?: boolean) => void;
215
- /**
216
- * Assert that a health status is healthy
217
- */
218
- assertHealthy: (health: ProviderHealthStatus | PlatformHealthStatus, expected?: boolean) => void;
219
- /**
220
- * Assert that a provider result has expected structure
221
- */
222
- assertProviderResult: (result: any, expectSuccess?: boolean) => void;
223
- /**
224
- * Assert that API response has expected structure
225
- */
226
- assertApiResponse: (response: any, expectedCode?: number) => void;
227
- };
228
- /**
229
- * Test data generators
230
- */
231
- declare const TestData: {
232
- createMockTemplate: (overrides?: Partial<any>) => {
233
- templateCode: string;
234
- templateName: string;
235
- templateContent: string;
236
- status: string;
237
- createDate: string;
238
- };
239
- createMockMessage: (overrides?: Partial<any>) => {
240
- seqNo: number;
241
- phone: string;
242
- templateCode: string;
243
- statusCode: string;
244
- statusCodeName: string;
245
- requestDate: string;
246
- sendDate: string;
247
- receiveDate: string;
248
- sendMessage: string;
249
- };
250
- createMockVariables: (overrides?: Record<string, any>) => {
251
- 서비스명: string;
252
- 고객명: string;
253
- 인증코드: string;
254
- };
255
- generatePhoneNumber: (valid?: boolean) => string;
256
- };
257
- /**
258
- * Test environment setup helpers
259
- */
260
- declare const TestSetup: {
261
- /**
262
- * Create a test environment with mock providers
263
- */
264
- createTestEnvironment: () => {
265
- providers: {
266
- healthy: MockProvider;
267
- unhealthy: MockProvider;
268
- rateLimited: MockProvider;
269
- };
270
- cleanup: () => void;
271
- };
272
- /**
273
- * Create test data for various scenarios
274
- */
275
- createTestScenarios: () => {
276
- validMessage: {
277
- templateCode: string;
278
- phoneNumber: string;
279
- variables: {
280
- 서비스명: string;
281
- 고객명: string;
282
- 인증코드: string;
283
- };
284
- };
285
- invalidMessage: {
286
- templateCode: string;
287
- phoneNumber: string;
288
- variables: {};
289
- };
290
- templates: {
291
- templateCode: string;
292
- templateName: string;
293
- templateContent: string;
294
- status: string;
295
- createDate: string;
296
- }[];
297
- history: {
298
- seqNo: number;
299
- phone: string;
300
- templateCode: string;
301
- statusCode: string;
302
- statusCodeName: string;
303
- requestDate: string;
304
- sendDate: string;
305
- receiveDate: string;
306
- sendMessage: string;
307
- }[];
308
- };
309
- };
310
- /**
311
- * Performance testing helpers
312
- */
313
- declare const PerformanceTest: {
314
- /**
315
- * Measure execution time of a function
316
- */
317
- measureTime: <T>(fn: () => Promise<T>) => Promise<{
318
- result: T;
319
- duration: number;
320
- }>;
321
- /**
322
- * Run a function multiple times and get statistics
323
- */
324
- benchmark: <T>(fn: () => Promise<T>, iterations?: number) => Promise<{
325
- results: T[];
326
- statistics: {
327
- min: number;
328
- max: number;
329
- average: number;
330
- median: number;
331
- };
332
- }>;
333
- };
334
-
335
- /**
336
- * Error recovery and retry patterns for K-Message Platform
337
- */
338
- interface RetryOptions {
339
- maxAttempts: number;
340
- initialDelay: number;
341
- maxDelay: number;
342
- backoffMultiplier: number;
343
- jitter: boolean;
344
- retryCondition?: (error: Error, attempt: number) => boolean;
345
- onRetry?: (error: Error, attempt: number) => void;
346
- }
347
- interface CircuitBreakerOptions {
348
- failureThreshold: number;
349
- timeout: number;
350
- resetTimeout: number;
351
- onOpen?: () => void;
352
- onHalfOpen?: () => void;
353
- onClose?: () => void;
354
- }
355
- interface BulkOperationOptions {
356
- concurrency: number;
357
- retryOptions: RetryOptions;
358
- failFast: boolean;
359
- onProgress?: (completed: number, total: number, failed: number) => void;
360
- }
361
- /**
362
- * Exponential backoff retry mechanism
363
- */
364
- declare class RetryHandler {
365
- private static defaultOptions;
366
- static execute<T>(operation: () => Promise<T>, options?: Partial<RetryOptions>): Promise<T>;
367
- static createRetryableFunction<T extends any[], R>(func: (...args: T) => Promise<R>, options?: Partial<RetryOptions>): (...args: T) => Promise<R>;
368
- }
369
- /**
370
- * Circuit breaker pattern implementation
371
- */
372
- declare class CircuitBreaker {
373
- private options;
374
- private state;
375
- private failureCount;
376
- private lastFailureTime;
377
- private nextAttemptTime;
378
- constructor(options: CircuitBreakerOptions);
379
- execute<T>(operation: () => Promise<T>): Promise<T>;
380
- private recordFailure;
381
- getState(): string;
382
- getFailureCount(): number;
383
- reset(): void;
384
- }
385
- /**
386
- * Bulk operation handler with error recovery
387
- */
388
- declare class BulkOperationHandler {
389
- static execute<T, R>(items: T[], operation: (item: T) => Promise<R>, options?: Partial<BulkOperationOptions>): Promise<{
390
- successful: {
391
- item: T;
392
- result: R;
393
- }[];
394
- failed: {
395
- item: T;
396
- error: Error;
397
- }[];
398
- summary: {
399
- total: number;
400
- successful: number;
401
- failed: number;
402
- duration: number;
403
- };
404
- }>;
405
- private static createBatches;
406
- }
407
- /**
408
- * Rate limiter for API calls
409
- */
410
- declare class RateLimiter {
411
- private maxRequests;
412
- private windowMs;
413
- private requests;
414
- constructor(maxRequests: number, windowMs: number);
415
- acquire(): Promise<void>;
416
- canMakeRequest(): boolean;
417
- getRemainingRequests(): number;
418
- }
419
- /**
420
- * Health check monitor with automatic recovery
421
- */
422
- declare class HealthMonitor {
423
- private services;
424
- private healthStatus;
425
- private lastCheck;
426
- private checkInterval;
427
- private intervalId?;
428
- constructor(services: Map<string, () => Promise<boolean>>, checkIntervalMs?: number);
429
- start(): void;
430
- stop(): void;
431
- private checkAllServices;
432
- getServiceHealth(serviceName: string): boolean | undefined;
433
- getAllHealth(): Record<string, boolean>;
434
- isServiceHealthy(serviceName: string): boolean;
435
- getLastCheckTime(serviceName: string): number | undefined;
436
- }
437
- /**
438
- * Graceful degradation handler
439
- */
440
- declare class GracefulDegradation {
441
- private fallbackStrategies;
442
- registerFallback<T>(operationName: string, fallbackFunction: () => Promise<T>): void;
443
- executeWithFallback<T>(operationName: string, primaryOperation: () => Promise<T>, options?: {
444
- timeout?: number;
445
- retryOptions?: Partial<RetryOptions>;
446
- }): Promise<T>;
447
- }
448
- /**
449
- * Error recovery utilities
450
- */
451
- declare const ErrorRecovery: {
452
- /**
453
- * Create a resilient function that combines multiple recovery patterns
454
- */
455
- createResilientFunction<T extends any[], R>(func: (...args: T) => Promise<R>, options?: {
456
- retryOptions?: Partial<RetryOptions>;
457
- circuitBreaker?: CircuitBreakerOptions;
458
- rateLimiter?: {
459
- maxRequests: number;
460
- windowMs: number;
461
- };
462
- timeout?: number;
463
- fallback?: (...args: T) => Promise<R>;
464
- }): (...args: T) => Promise<R>;
465
- };
466
-
467
- /**
468
- * Core AlimTalk Platform types and interfaces
469
- */
470
-
471
- interface ProviderHealthStatus {
472
- healthy: boolean;
473
- issues: string[];
474
- data?: {
475
- balance?: string;
476
- status?: string;
477
- code?: number;
478
- message?: string;
479
- };
480
- }
481
- interface PlatformHealthStatus {
482
- healthy: boolean;
483
- providers: Record<string, boolean>;
484
- issues: string[];
485
- }
486
- interface PlatformInfo {
487
- version: string;
488
- providers: string[];
489
- features: string[];
490
- }
491
- interface MessageSendOptions {
492
- templateId: string;
493
- recipients: {
494
- phoneNumber: string;
495
- variables?: Record<string, any>;
496
- }[];
497
- variables: Record<string, any>;
498
- }
499
- interface MessageSendResult {
500
- results: Array<{
501
- messageId?: string;
502
- status: string;
503
- phoneNumber: string;
504
- error?: {
505
- message: string;
506
- };
507
- }>;
508
- summary: {
509
- total: number;
510
- sent: number;
511
- failed: number;
512
- };
513
- }
514
- interface BaseProvider {
515
- id: string;
516
- name: string;
517
- healthCheck(): Promise<ProviderHealthStatus>;
518
- sendMessage?(templateCode: string, phoneNumber: string, variables: Record<string, any>, options?: any): Promise<any>;
519
- getTemplates?(page: number, size: number, filters?: any): Promise<any>;
520
- createTemplate?(name: string, content: string, category?: string, buttons?: any[]): Promise<any>;
521
- modifyTemplate?(templateCode: string, name: string, content: string, buttons?: any[]): Promise<any>;
522
- deleteTemplate?(templateCode: string): Promise<any>;
523
- getHistory?(page: number, size: number, filters?: any): Promise<any>;
524
- cancelReservation?(messageId: string): Promise<any>;
525
- }
526
- /**
527
- * Core AlimTalk Platform interface
528
- */
529
- interface IAlimTalkPlatform {
530
- getInfo(): PlatformInfo;
531
- registerProvider(provider: BaseProvider): void;
532
- getProvider(providerId: string): BaseProvider | null;
533
- listProviders(): string[];
534
- healthCheck(): Promise<PlatformHealthStatus>;
535
- messages: {
536
- send(options: MessageSendOptions): Promise<MessageSendResult>;
537
- getStatus(messageId: string): Promise<string>;
538
- };
539
- }
540
- /**
541
- * Configuration interface
542
- */
543
- interface PlatformConfig {
544
- providers: string[];
545
- defaultProvider: string;
546
- features: {
547
- enableBulkSending?: boolean;
548
- enableScheduling?: boolean;
549
- enableAnalytics?: boolean;
550
- };
551
- }
552
- /**
553
- * Template categories
554
- */
555
- declare enum TemplateCategory {
556
- AUTHENTICATION = "AUTHENTICATION",
557
- NOTIFICATION = "NOTIFICATION",
558
- PROMOTION = "PROMOTION",
559
- INFORMATION = "INFORMATION",
560
- RESERVATION = "RESERVATION",
561
- SHIPPING = "SHIPPING",
562
- PAYMENT = "PAYMENT"
563
- }
564
-
565
- export { type BaseProvider, BulkOperationHandler, type BulkOperationOptions, CircuitBreaker, type CircuitBreakerOptions, ErrorFactory, ErrorRecovery, ErrorUtils, GracefulDegradation, HealthMonitor, type IAlimTalkPlatform, KMessageError, KMessageErrorCode, type KMessageErrorContext, MessageError, type MessageSendOptions, type MessageSendResult, MockProvider, PerformanceTest, type PlatformConfig, type PlatformHealthStatus, type PlatformInfo, ProviderError, type ProviderHealthStatus, RateLimiter, Result, RetryHandler, type RetryOptions, TemplateCategory, TemplateError, TestAssertions, TestData, TestSetup };
1
+ export * from "./config";
2
+ export * from "./errors";
3
+ export * from "./health";
4
+ export * from "./logger";
5
+ export * from "./platform";
6
+ export * from "./provider";
7
+ export * from "./provider-registry";
8
+ export * from "./resilience/index";
9
+ export * from "./result";
10
+ export * from "./test-utils";
11
+ export * from "./types/index";
12
+ export * from "./universal-provider";