@channlize/core 0.1.0-alpha.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.
package/README.md ADDED
@@ -0,0 +1,147 @@
1
+ # @channlize/core
2
+
3
+ Core TypeScript SDK for the Channlize platform. Provides API client functionality for submitting contact forms and managing chat sessions.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @channlize/core
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Basic Setup
14
+
15
+ ```typescript
16
+ import { ChannlizeClient } from '@channlize/core';
17
+
18
+ const client = new ChannlizeClient({
19
+ apiKey: 'your-api-key',
20
+ projectId: 'your-project-id',
21
+ baseUrl: 'https://api.channlize.com', // optional
22
+ timeout: 10000, // optional, default 10s
23
+ });
24
+ ```
25
+
26
+ ### Contact Forms
27
+
28
+ ```typescript
29
+ // Submit a contact form
30
+ const response = await client.submitContactForm({
31
+ name: 'John Doe',
32
+ email: 'john@example.com',
33
+ subject: 'Support Request',
34
+ message: 'I need help with my account',
35
+ customFields: {
36
+ department: 'support',
37
+ priority: 'high',
38
+ },
39
+ });
40
+
41
+ console.log('Submission ID:', response.id);
42
+ console.log('Slack thread:', response.slackThreadUrl);
43
+ ```
44
+
45
+ ### Chat Sessions
46
+
47
+ ```typescript
48
+ // Create a new chat session
49
+ const sessionResponse = await client.createChatSession({
50
+ userAgent: navigator.userAgent,
51
+ pageUrl: window.location.href,
52
+ });
53
+
54
+ const session = sessionResponse.session;
55
+
56
+ // Send a message
57
+ await client.sendMessage(session.id, 'Hello, I need help!');
58
+
59
+ // Send message with file attachments
60
+ const files = [document.querySelector('input[type="file"]').files[0]];
61
+ await client.sendMessage(session.id, 'Please see attached file', files);
62
+
63
+ // Get session details
64
+ const updatedSession = await client.getChatSession(session.id);
65
+
66
+ // Get messages
67
+ const messages = await client.getChatMessages(session.id, 50, 0);
68
+
69
+ // Close session
70
+ await client.closeChatSession(session.id);
71
+ ```
72
+
73
+ ### Error Handling
74
+
75
+ ```typescript
76
+ import {
77
+ ChannlizeError,
78
+ ValidationError,
79
+ AuthenticationError,
80
+ RateLimitError,
81
+ } from '@channlize/core';
82
+
83
+ try {
84
+ await client.submitContactForm(formData);
85
+ } catch (error) {
86
+ if (error instanceof ValidationError) {
87
+ console.error('Validation failed:', error.message, error.field);
88
+ } else if (error instanceof AuthenticationError) {
89
+ console.error('Authentication failed:', error.message);
90
+ } else if (error instanceof RateLimitError) {
91
+ console.error('Rate limit exceeded:', error.message);
92
+ } else if (error instanceof ChannlizeError) {
93
+ console.error('API error:', error.message, error.statusCode);
94
+ } else {
95
+ console.error('Unknown error:', error);
96
+ }
97
+ }
98
+ ```
99
+
100
+ ## API Reference
101
+
102
+ ### ChannlizeClient
103
+
104
+ #### Constructor Options
105
+
106
+ ```typescript
107
+ interface ChannlizeConfig {
108
+ apiKey: string; // Required: Your API key
109
+ projectId: string; // Required: Your project ID
110
+ baseUrl?: string; // Optional: API base URL
111
+ timeout?: number; // Optional: Request timeout in ms
112
+ }
113
+ ```
114
+
115
+ #### Methods
116
+
117
+ - `submitContactForm(data: ContactFormData): Promise<CreateContactResponse>`
118
+ - `createChatSession(metadata?: Record<string, unknown>): Promise<CreateChatSessionResponse>`
119
+ - `sendMessage(sessionId: string, content: string, attachments?: File[]): Promise<SendMessageResponse>`
120
+ - `getChatSession(sessionId: string): Promise<ChatSession>`
121
+ - `getChatMessages(sessionId: string, limit?: number, offset?: number): Promise<ChatMessage[]>`
122
+ - `closeChatSession(sessionId: string): Promise<ChatSession>`
123
+
124
+ ### Types
125
+
126
+ All TypeScript types are exported from the package:
127
+
128
+ ```typescript
129
+ import type {
130
+ ChannlizeConfig,
131
+ ContactFormData,
132
+ ChatMessage,
133
+ ChatSession,
134
+ FileAttachment,
135
+ CreateContactResponse,
136
+ CreateChatSessionResponse,
137
+ SendMessageResponse,
138
+ ChannlizeError,
139
+ ValidationError,
140
+ AuthenticationError,
141
+ RateLimitError,
142
+ } from '@channlize/core';
143
+ ```
144
+
145
+ ## License
146
+
147
+ MIT
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Core types for Channlize SDK
3
+ */
4
+ interface ChannlizeConfig {
5
+ /** API key for authentication */
6
+ apiKey: string;
7
+ /** Base URL for the Channlize API */
8
+ baseUrl?: string;
9
+ /** Project ID */
10
+ projectId: string;
11
+ /** Request timeout in milliseconds */
12
+ timeout?: number;
13
+ }
14
+ interface ContactFormData {
15
+ /** Contact's name */
16
+ name: string;
17
+ /** Contact's email address */
18
+ email: string;
19
+ /** Subject of the inquiry */
20
+ subject?: string;
21
+ /** Message content */
22
+ message: string;
23
+ /** Custom fields */
24
+ customFields?: Record<string, unknown>;
25
+ /** Page URL where the form was submitted */
26
+ pageUrl?: string;
27
+ /** User agent string */
28
+ userAgent?: string;
29
+ }
30
+ interface ChatMessage {
31
+ /** Unique message ID */
32
+ id: string;
33
+ /** Message content */
34
+ content: string;
35
+ /** Message timestamp */
36
+ timestamp: Date;
37
+ /** Message author (user or agent) */
38
+ author: 'user' | 'agent';
39
+ /** Author metadata */
40
+ authorData?: {
41
+ name?: string;
42
+ email?: string;
43
+ avatarUrl?: string;
44
+ };
45
+ /** Attached files */
46
+ attachments?: FileAttachment[];
47
+ }
48
+ interface FileAttachment {
49
+ /** File ID */
50
+ id: string;
51
+ /** Original filename */
52
+ name: string;
53
+ /** File size in bytes */
54
+ size: number;
55
+ /** MIME type */
56
+ type: string;
57
+ /** Download URL */
58
+ url: string;
59
+ }
60
+ interface ChatSession {
61
+ /** Session ID */
62
+ id: string;
63
+ /** Session status */
64
+ status: 'active' | 'closed' | 'waiting';
65
+ /** Messages in the session */
66
+ messages: ChatMessage[];
67
+ /** Session metadata */
68
+ metadata?: Record<string, unknown>;
69
+ /** Created timestamp */
70
+ createdAt: Date;
71
+ /** Updated timestamp */
72
+ updatedAt: Date;
73
+ }
74
+ interface ApiResponse<T = unknown> {
75
+ /** Response data */
76
+ data: T;
77
+ /** Success status */
78
+ success: boolean;
79
+ /** Error message if any */
80
+ error?: string;
81
+ /** Additional metadata */
82
+ meta?: Record<string, unknown>;
83
+ }
84
+ interface CreateContactResponse {
85
+ /** Contact form submission ID */
86
+ id: string;
87
+ /** Status of the submission */
88
+ status: 'received' | 'processing' | 'delivered';
89
+ /** Slack thread URL if available */
90
+ slackThreadUrl?: string;
91
+ }
92
+ interface CreateChatSessionResponse {
93
+ /** Chat session data */
94
+ session: ChatSession;
95
+ /** SSE endpoint for real-time updates */
96
+ sseEndpoint?: string;
97
+ }
98
+ interface SendMessageResponse {
99
+ /** The sent message */
100
+ message: ChatMessage;
101
+ /** Updated session */
102
+ session: ChatSession;
103
+ }
104
+ /**
105
+ * Error types
106
+ */
107
+ declare class ChannlizeError extends Error {
108
+ statusCode?: number | undefined;
109
+ code?: string | undefined;
110
+ constructor(message: string, statusCode?: number | undefined, code?: string | undefined);
111
+ }
112
+ declare class ValidationError extends ChannlizeError {
113
+ field?: string | undefined;
114
+ constructor(message: string, field?: string | undefined);
115
+ }
116
+ declare class AuthenticationError extends ChannlizeError {
117
+ constructor(message?: string);
118
+ }
119
+ declare class RateLimitError extends ChannlizeError {
120
+ constructor(message?: string);
121
+ }
122
+
123
+ /**
124
+ * Channlize API Client
125
+ * Provides methods to interact with the Channlize platform
126
+ */
127
+ declare class ChannlizeClient {
128
+ private readonly config;
129
+ constructor(config: ChannlizeConfig);
130
+ private validateConfig;
131
+ private makeRequest;
132
+ private handleErrorResponse;
133
+ /**
134
+ * Submit a contact form
135
+ */
136
+ submitContactForm(data: ContactFormData): Promise<CreateContactResponse>;
137
+ /**
138
+ * Create a new chat session
139
+ */
140
+ createChatSession(metadata?: Record<string, unknown>): Promise<CreateChatSessionResponse>;
141
+ /**
142
+ * Send a message in a chat session
143
+ */
144
+ sendMessage(sessionId: string, content: string, attachments?: File[]): Promise<SendMessageResponse>;
145
+ /**
146
+ * Get chat session details
147
+ */
148
+ getChatSession(sessionId: string): Promise<ChatSession>;
149
+ /**
150
+ * Get messages for a chat session
151
+ */
152
+ getChatMessages(sessionId: string, limit?: number, offset?: number): Promise<ChatMessage[]>;
153
+ /**
154
+ * Close a chat session
155
+ */
156
+ closeChatSession(sessionId: string): Promise<ChatSession>;
157
+ }
158
+
159
+ export { type ApiResponse, AuthenticationError, ChannlizeClient, type ChannlizeConfig, ChannlizeError, type ChatMessage, type ChatSession, type ContactFormData, type CreateChatSessionResponse, type CreateContactResponse, type FileAttachment, RateLimitError, type SendMessageResponse, ValidationError, ChannlizeClient as default };
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Core types for Channlize SDK
3
+ */
4
+ interface ChannlizeConfig {
5
+ /** API key for authentication */
6
+ apiKey: string;
7
+ /** Base URL for the Channlize API */
8
+ baseUrl?: string;
9
+ /** Project ID */
10
+ projectId: string;
11
+ /** Request timeout in milliseconds */
12
+ timeout?: number;
13
+ }
14
+ interface ContactFormData {
15
+ /** Contact's name */
16
+ name: string;
17
+ /** Contact's email address */
18
+ email: string;
19
+ /** Subject of the inquiry */
20
+ subject?: string;
21
+ /** Message content */
22
+ message: string;
23
+ /** Custom fields */
24
+ customFields?: Record<string, unknown>;
25
+ /** Page URL where the form was submitted */
26
+ pageUrl?: string;
27
+ /** User agent string */
28
+ userAgent?: string;
29
+ }
30
+ interface ChatMessage {
31
+ /** Unique message ID */
32
+ id: string;
33
+ /** Message content */
34
+ content: string;
35
+ /** Message timestamp */
36
+ timestamp: Date;
37
+ /** Message author (user or agent) */
38
+ author: 'user' | 'agent';
39
+ /** Author metadata */
40
+ authorData?: {
41
+ name?: string;
42
+ email?: string;
43
+ avatarUrl?: string;
44
+ };
45
+ /** Attached files */
46
+ attachments?: FileAttachment[];
47
+ }
48
+ interface FileAttachment {
49
+ /** File ID */
50
+ id: string;
51
+ /** Original filename */
52
+ name: string;
53
+ /** File size in bytes */
54
+ size: number;
55
+ /** MIME type */
56
+ type: string;
57
+ /** Download URL */
58
+ url: string;
59
+ }
60
+ interface ChatSession {
61
+ /** Session ID */
62
+ id: string;
63
+ /** Session status */
64
+ status: 'active' | 'closed' | 'waiting';
65
+ /** Messages in the session */
66
+ messages: ChatMessage[];
67
+ /** Session metadata */
68
+ metadata?: Record<string, unknown>;
69
+ /** Created timestamp */
70
+ createdAt: Date;
71
+ /** Updated timestamp */
72
+ updatedAt: Date;
73
+ }
74
+ interface ApiResponse<T = unknown> {
75
+ /** Response data */
76
+ data: T;
77
+ /** Success status */
78
+ success: boolean;
79
+ /** Error message if any */
80
+ error?: string;
81
+ /** Additional metadata */
82
+ meta?: Record<string, unknown>;
83
+ }
84
+ interface CreateContactResponse {
85
+ /** Contact form submission ID */
86
+ id: string;
87
+ /** Status of the submission */
88
+ status: 'received' | 'processing' | 'delivered';
89
+ /** Slack thread URL if available */
90
+ slackThreadUrl?: string;
91
+ }
92
+ interface CreateChatSessionResponse {
93
+ /** Chat session data */
94
+ session: ChatSession;
95
+ /** SSE endpoint for real-time updates */
96
+ sseEndpoint?: string;
97
+ }
98
+ interface SendMessageResponse {
99
+ /** The sent message */
100
+ message: ChatMessage;
101
+ /** Updated session */
102
+ session: ChatSession;
103
+ }
104
+ /**
105
+ * Error types
106
+ */
107
+ declare class ChannlizeError extends Error {
108
+ statusCode?: number | undefined;
109
+ code?: string | undefined;
110
+ constructor(message: string, statusCode?: number | undefined, code?: string | undefined);
111
+ }
112
+ declare class ValidationError extends ChannlizeError {
113
+ field?: string | undefined;
114
+ constructor(message: string, field?: string | undefined);
115
+ }
116
+ declare class AuthenticationError extends ChannlizeError {
117
+ constructor(message?: string);
118
+ }
119
+ declare class RateLimitError extends ChannlizeError {
120
+ constructor(message?: string);
121
+ }
122
+
123
+ /**
124
+ * Channlize API Client
125
+ * Provides methods to interact with the Channlize platform
126
+ */
127
+ declare class ChannlizeClient {
128
+ private readonly config;
129
+ constructor(config: ChannlizeConfig);
130
+ private validateConfig;
131
+ private makeRequest;
132
+ private handleErrorResponse;
133
+ /**
134
+ * Submit a contact form
135
+ */
136
+ submitContactForm(data: ContactFormData): Promise<CreateContactResponse>;
137
+ /**
138
+ * Create a new chat session
139
+ */
140
+ createChatSession(metadata?: Record<string, unknown>): Promise<CreateChatSessionResponse>;
141
+ /**
142
+ * Send a message in a chat session
143
+ */
144
+ sendMessage(sessionId: string, content: string, attachments?: File[]): Promise<SendMessageResponse>;
145
+ /**
146
+ * Get chat session details
147
+ */
148
+ getChatSession(sessionId: string): Promise<ChatSession>;
149
+ /**
150
+ * Get messages for a chat session
151
+ */
152
+ getChatMessages(sessionId: string, limit?: number, offset?: number): Promise<ChatMessage[]>;
153
+ /**
154
+ * Close a chat session
155
+ */
156
+ closeChatSession(sessionId: string): Promise<ChatSession>;
157
+ }
158
+
159
+ export { type ApiResponse, AuthenticationError, ChannlizeClient, type ChannlizeConfig, ChannlizeError, type ChatMessage, type ChatSession, type ContactFormData, type CreateChatSessionResponse, type CreateContactResponse, type FileAttachment, RateLimitError, type SendMessageResponse, ValidationError, ChannlizeClient as default };
package/dist/index.js ADDED
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AuthenticationError: () => AuthenticationError,
34
+ ChannlizeClient: () => ChannlizeClient,
35
+ ChannlizeError: () => ChannlizeError,
36
+ RateLimitError: () => RateLimitError,
37
+ ValidationError: () => ValidationError,
38
+ default: () => ChannlizeClient
39
+ });
40
+ module.exports = __toCommonJS(index_exports);
41
+
42
+ // src/client.ts
43
+ var import_cross_fetch = __toESM(require("cross-fetch"));
44
+
45
+ // src/types.ts
46
+ var ChannlizeError = class extends Error {
47
+ constructor(message, statusCode, code) {
48
+ super(message);
49
+ this.statusCode = statusCode;
50
+ this.code = code;
51
+ this.name = "ChannlizeError";
52
+ }
53
+ };
54
+ var ValidationError = class extends ChannlizeError {
55
+ constructor(message, field) {
56
+ super(message, 400, "VALIDATION_ERROR");
57
+ this.field = field;
58
+ this.name = "ValidationError";
59
+ }
60
+ };
61
+ var AuthenticationError = class extends ChannlizeError {
62
+ constructor(message = "Authentication failed") {
63
+ super(message, 401, "AUTHENTICATION_ERROR");
64
+ this.name = "AuthenticationError";
65
+ }
66
+ };
67
+ var RateLimitError = class extends ChannlizeError {
68
+ constructor(message = "Rate limit exceeded") {
69
+ super(message, 429, "RATE_LIMIT_ERROR");
70
+ this.name = "RateLimitError";
71
+ }
72
+ };
73
+
74
+ // src/client.ts
75
+ var ChannlizeClient = class {
76
+ config;
77
+ constructor(config) {
78
+ this.config = {
79
+ baseUrl: config.baseUrl || "https://api.channlize.com",
80
+ timeout: 1e4,
81
+ ...config
82
+ };
83
+ this.validateConfig();
84
+ }
85
+ validateConfig() {
86
+ if (!this.config.apiKey) {
87
+ throw new ValidationError("Widget key is required");
88
+ }
89
+ }
90
+ async makeRequest(endpoint, options = {}) {
91
+ const url = `${this.config.baseUrl}${endpoint}`;
92
+ const controller = new AbortController();
93
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
94
+ try {
95
+ const response = await (0, import_cross_fetch.default)(url, {
96
+ ...options,
97
+ signal: controller.signal,
98
+ headers: {
99
+ "Content-Type": "application/json",
100
+ ...options.headers
101
+ }
102
+ });
103
+ clearTimeout(timeoutId);
104
+ if (!response.ok) {
105
+ await this.handleErrorResponse(response);
106
+ }
107
+ const data = await response.json();
108
+ return data;
109
+ } catch (error) {
110
+ clearTimeout(timeoutId);
111
+ if (error instanceof ChannlizeError) {
112
+ throw error;
113
+ }
114
+ if (error instanceof Error && error.name === "AbortError") {
115
+ throw new ChannlizeError("Request timeout", 408, "TIMEOUT");
116
+ }
117
+ throw new ChannlizeError(
118
+ `Network error: ${error instanceof Error ? error.message : "Unknown error"}`
119
+ );
120
+ }
121
+ }
122
+ async handleErrorResponse(response) {
123
+ const contentType = response.headers.get("content-type");
124
+ let errorData = {};
125
+ if (contentType?.includes("application/json")) {
126
+ try {
127
+ errorData = await response.json();
128
+ } catch {
129
+ }
130
+ }
131
+ const message = errorData.error || `HTTP ${response.status}: ${response.statusText}`;
132
+ switch (response.status) {
133
+ case 401:
134
+ throw new AuthenticationError(message);
135
+ case 400:
136
+ throw new ValidationError(message, errorData.field);
137
+ case 429:
138
+ throw new RateLimitError(message);
139
+ default:
140
+ throw new ChannlizeError(message, response.status, errorData.code);
141
+ }
142
+ }
143
+ /**
144
+ * Submit a contact form
145
+ */
146
+ async submitContactForm(data) {
147
+ const response = await this.makeRequest("/public/contact", {
148
+ method: "POST",
149
+ body: JSON.stringify({
150
+ widgetKey: this.config.apiKey,
151
+ // apiKey is actually the widgetKey
152
+ subject: data.subject,
153
+ message: data.message,
154
+ email: data.email,
155
+ name: data.name,
156
+ pageUrl: data.pageUrl || (typeof window !== "undefined" ? window.location.href : void 0),
157
+ userAgent: data.userAgent || (typeof navigator !== "undefined" ? navigator.userAgent : void 0)
158
+ })
159
+ });
160
+ return response.data || response;
161
+ }
162
+ /**
163
+ * Create a new chat session
164
+ */
165
+ async createChatSession(metadata) {
166
+ const response = await this.makeRequest("/v1/chat/sessions", {
167
+ method: "POST",
168
+ body: JSON.stringify({
169
+ widgetKey: this.config.apiKey,
170
+ // apiKey is actually the widgetKey
171
+ metadata: {
172
+ ...metadata,
173
+ pageUrl: typeof window !== "undefined" ? window.location.href : void 0,
174
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0
175
+ }
176
+ })
177
+ });
178
+ return response.data;
179
+ }
180
+ /**
181
+ * Send a message in a chat session
182
+ */
183
+ async sendMessage(sessionId, content, attachments) {
184
+ const idempotencyKey = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
185
+ const response = await this.makeRequest(
186
+ `/v1/chat/sessions/${sessionId}/messages`,
187
+ {
188
+ method: "POST",
189
+ body: JSON.stringify({
190
+ content,
191
+ idempotencyKey
192
+ })
193
+ }
194
+ );
195
+ return response.data;
196
+ }
197
+ /**
198
+ * Get chat session details
199
+ */
200
+ async getChatSession(sessionId) {
201
+ const response = await this.makeRequest(`/v1/chat/sessions/${sessionId}`);
202
+ return response.data;
203
+ }
204
+ /**
205
+ * Get messages for a chat session
206
+ */
207
+ async getChatMessages(sessionId, limit = 50, offset = 0) {
208
+ const response = await this.makeRequest(
209
+ `/v1/chat/sessions/${sessionId}/messages?limit=${limit}&offset=${offset}`
210
+ );
211
+ return response.data;
212
+ }
213
+ /**
214
+ * Close a chat session
215
+ */
216
+ async closeChatSession(sessionId) {
217
+ const response = await this.makeRequest(
218
+ `/v1/chat/sessions/${sessionId}/close`,
219
+ { method: "POST" }
220
+ );
221
+ return response.data;
222
+ }
223
+ };
224
+ // Annotate the CommonJS export names for ESM import in node:
225
+ 0 && (module.exports = {
226
+ AuthenticationError,
227
+ ChannlizeClient,
228
+ ChannlizeError,
229
+ RateLimitError,
230
+ ValidationError
231
+ });
232
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/types.ts"],"sourcesContent":["/**\n * @channlize/core\n * Core TypeScript SDK for Channlize platform\n */\n\nexport { ChannlizeClient } from './client';\nexport * from './types';\n\n// Re-export for convenience\nexport { ChannlizeClient as default } from './client';\n","import fetch from 'cross-fetch';\nimport type {\n ChannlizeConfig,\n ContactFormData,\n ChatMessage,\n ApiResponse,\n CreateContactResponse,\n CreateChatSessionResponse,\n SendMessageResponse,\n ChatSession,\n} from './types';\nimport {\n ChannlizeError,\n AuthenticationError,\n ValidationError,\n RateLimitError,\n} from './types';\n\n/**\n * Channlize API Client\n * Provides methods to interact with the Channlize platform\n */\nexport class ChannlizeClient {\n private readonly config: Required<ChannlizeConfig>;\n\n constructor(config: ChannlizeConfig) {\n this.config = {\n baseUrl: config.baseUrl || 'https://api.channlize.com',\n timeout: 10000,\n ...config,\n };\n\n this.validateConfig();\n }\n\n private validateConfig(): void {\n if (!this.config.apiKey) {\n throw new ValidationError('Widget key is required');\n }\n }\n\n private async makeRequest<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<ApiResponse<T>> {\n const url = `${this.config.baseUrl}${endpoint}`;\n \n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers,\n },\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n await this.handleErrorResponse(response);\n }\n\n const data = await response.json();\n return data as ApiResponse<T>;\n } catch (error) {\n clearTimeout(timeoutId);\n \n if (error instanceof ChannlizeError) {\n throw error;\n }\n \n if (error instanceof Error && error.name === 'AbortError') {\n throw new ChannlizeError('Request timeout', 408, 'TIMEOUT');\n }\n \n throw new ChannlizeError(\n `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n private async handleErrorResponse(response: Response): Promise<never> {\n const contentType = response.headers.get('content-type');\n let errorData: any = {};\n\n if (contentType?.includes('application/json')) {\n try {\n errorData = await response.json();\n } catch {\n // Ignore JSON parsing errors\n }\n }\n\n const message = errorData.error || `HTTP ${response.status}: ${response.statusText}`;\n\n switch (response.status) {\n case 401:\n throw new AuthenticationError(message);\n case 400:\n throw new ValidationError(message, errorData.field);\n case 429:\n throw new RateLimitError(message);\n default:\n throw new ChannlizeError(message, response.status, errorData.code);\n }\n }\n\n /**\n * Submit a contact form\n */\n async submitContactForm(data: ContactFormData): Promise<CreateContactResponse> {\n const response = await this.makeRequest<CreateContactResponse>('/public/contact', {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n subject: data.subject,\n message: data.message,\n email: data.email,\n name: data.name,\n pageUrl: data.pageUrl || (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent: data.userAgent || (typeof navigator !== 'undefined' ? navigator.userAgent : undefined),\n }),\n });\n\n return response.data || response;\n }\n\n /**\n * Create a new chat session\n */\n async createChatSession(metadata?: Record<string, unknown>): Promise<CreateChatSessionResponse> {\n const response = await this.makeRequest<CreateChatSessionResponse>('/v1/chat/sessions', {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n metadata: {\n ...metadata,\n pageUrl: typeof window !== 'undefined' ? window.location.href : undefined,\n userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : undefined,\n },\n }),\n });\n\n return response.data;\n }\n\n /**\n * Send a message in a chat session\n */\n async sendMessage(\n sessionId: string,\n content: string,\n attachments?: File[]\n ): Promise<SendMessageResponse> {\n // Generate idempotency key to prevent duplicate message creation\n const idempotencyKey = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n \n // For now, we send as JSON. File attachments support can be added later.\n // TODO: Implement file upload support\n const response = await this.makeRequest<SendMessageResponse>(\n `/v1/chat/sessions/${sessionId}/messages`,\n {\n method: 'POST',\n body: JSON.stringify({\n content,\n idempotencyKey,\n }),\n }\n );\n\n return response.data;\n }\n\n /**\n * Get chat session details\n */\n async getChatSession(sessionId: string): Promise<ChatSession> {\n const response = await this.makeRequest<ChatSession>(`/v1/chat/sessions/${sessionId}`);\n return response.data;\n }\n\n /**\n * Get messages for a chat session\n */\n async getChatMessages(sessionId: string, limit = 50, offset = 0): Promise<ChatMessage[]> {\n const response = await this.makeRequest<ChatMessage[]>(\n `/v1/chat/sessions/${sessionId}/messages?limit=${limit}&offset=${offset}`\n );\n return response.data;\n }\n\n /**\n * Close a chat session\n */\n async closeChatSession(sessionId: string): Promise<ChatSession> {\n const response = await this.makeRequest<ChatSession>(\n `/v1/chat/sessions/${sessionId}/close`,\n { method: 'POST' }\n );\n return response.data;\n }\n}\n","/**\n * Core types for Channlize SDK\n */\n\nexport interface ChannlizeConfig {\n /** API key for authentication */\n apiKey: string;\n /** Base URL for the Channlize API */\n baseUrl?: string;\n /** Project ID */\n projectId: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\nexport interface ContactFormData {\n /** Contact's name */\n name: string;\n /** Contact's email address */\n email: string;\n /** Subject of the inquiry */\n subject?: string;\n /** Message content */\n message: string;\n /** Custom fields */\n customFields?: Record<string, unknown>;\n /** Page URL where the form was submitted */\n pageUrl?: string;\n /** User agent string */\n userAgent?: string;\n}\n\nexport interface ChatMessage {\n /** Unique message ID */\n id: string;\n /** Message content */\n content: string;\n /** Message timestamp */\n timestamp: Date;\n /** Message author (user or agent) */\n author: 'user' | 'agent';\n /** Author metadata */\n authorData?: {\n name?: string;\n email?: string;\n avatarUrl?: string;\n };\n /** Attached files */\n attachments?: FileAttachment[];\n}\n\nexport interface FileAttachment {\n /** File ID */\n id: string;\n /** Original filename */\n name: string;\n /** File size in bytes */\n size: number;\n /** MIME type */\n type: string;\n /** Download URL */\n url: string;\n}\n\nexport interface ChatSession {\n /** Session ID */\n id: string;\n /** Session status */\n status: 'active' | 'closed' | 'waiting';\n /** Messages in the session */\n messages: ChatMessage[];\n /** Session metadata */\n metadata?: Record<string, unknown>;\n /** Created timestamp */\n createdAt: Date;\n /** Updated timestamp */\n updatedAt: Date;\n}\n\nexport interface ApiResponse<T = unknown> {\n /** Response data */\n data: T;\n /** Success status */\n success: boolean;\n /** Error message if any */\n error?: string;\n /** Additional metadata */\n meta?: Record<string, unknown>;\n}\n\nexport interface CreateContactResponse {\n /** Contact form submission ID */\n id: string;\n /** Status of the submission */\n status: 'received' | 'processing' | 'delivered';\n /** Slack thread URL if available */\n slackThreadUrl?: string;\n}\n\nexport interface CreateChatSessionResponse {\n /** Chat session data */\n session: ChatSession;\n /** SSE endpoint for real-time updates */\n sseEndpoint?: string;\n}\n\nexport interface SendMessageResponse {\n /** The sent message */\n message: ChatMessage;\n /** Updated session */\n session: ChatSession;\n}\n\n/**\n * Error types\n */\nexport class ChannlizeError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public code?: string\n ) {\n super(message);\n this.name = 'ChannlizeError';\n }\n}\n\nexport class ValidationError extends ChannlizeError {\n constructor(message: string, public field?: string) {\n super(message, 400, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n\nexport class AuthenticationError extends ChannlizeError {\n constructor(message: string = 'Authentication failed') {\n super(message, 401, 'AUTHENTICATION_ERROR');\n this.name = 'AuthenticationError';\n }\n}\n\nexport class RateLimitError extends ChannlizeError {\n constructor(message: string = 'Rate limit exceeded') {\n super(message, 429, 'RATE_LIMIT_ERROR');\n this.name = 'RateLimitError';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAkB;;;ACoHX,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACO,YACA,MACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cA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AAAA;AAAA,EAKA,MAAM,iBAAiB,WAAyC;AAC9D,UAAM,WAAW,MAAM,KAAK;AAAA,MAC1B,qBAAqB,SAAS;AAAA,MAC9B,EAAE,QAAQ,OAAO;AAAA,IACnB;AACA,WAAO,SAAS;AAAA,EAClB;AACF;","names":["fetch"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,191 @@
1
+ // src/client.ts
2
+ import fetch from "cross-fetch";
3
+
4
+ // src/types.ts
5
+ var ChannlizeError = class extends Error {
6
+ constructor(message, statusCode, code) {
7
+ super(message);
8
+ this.statusCode = statusCode;
9
+ this.code = code;
10
+ this.name = "ChannlizeError";
11
+ }
12
+ };
13
+ var ValidationError = class extends ChannlizeError {
14
+ constructor(message, field) {
15
+ super(message, 400, "VALIDATION_ERROR");
16
+ this.field = field;
17
+ this.name = "ValidationError";
18
+ }
19
+ };
20
+ var AuthenticationError = class extends ChannlizeError {
21
+ constructor(message = "Authentication failed") {
22
+ super(message, 401, "AUTHENTICATION_ERROR");
23
+ this.name = "AuthenticationError";
24
+ }
25
+ };
26
+ var RateLimitError = class extends ChannlizeError {
27
+ constructor(message = "Rate limit exceeded") {
28
+ super(message, 429, "RATE_LIMIT_ERROR");
29
+ this.name = "RateLimitError";
30
+ }
31
+ };
32
+
33
+ // src/client.ts
34
+ var ChannlizeClient = class {
35
+ config;
36
+ constructor(config) {
37
+ this.config = {
38
+ baseUrl: config.baseUrl || "https://api.channlize.com",
39
+ timeout: 1e4,
40
+ ...config
41
+ };
42
+ this.validateConfig();
43
+ }
44
+ validateConfig() {
45
+ if (!this.config.apiKey) {
46
+ throw new ValidationError("Widget key is required");
47
+ }
48
+ }
49
+ async makeRequest(endpoint, options = {}) {
50
+ const url = `${this.config.baseUrl}${endpoint}`;
51
+ const controller = new AbortController();
52
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
53
+ try {
54
+ const response = await fetch(url, {
55
+ ...options,
56
+ signal: controller.signal,
57
+ headers: {
58
+ "Content-Type": "application/json",
59
+ ...options.headers
60
+ }
61
+ });
62
+ clearTimeout(timeoutId);
63
+ if (!response.ok) {
64
+ await this.handleErrorResponse(response);
65
+ }
66
+ const data = await response.json();
67
+ return data;
68
+ } catch (error) {
69
+ clearTimeout(timeoutId);
70
+ if (error instanceof ChannlizeError) {
71
+ throw error;
72
+ }
73
+ if (error instanceof Error && error.name === "AbortError") {
74
+ throw new ChannlizeError("Request timeout", 408, "TIMEOUT");
75
+ }
76
+ throw new ChannlizeError(
77
+ `Network error: ${error instanceof Error ? error.message : "Unknown error"}`
78
+ );
79
+ }
80
+ }
81
+ async handleErrorResponse(response) {
82
+ const contentType = response.headers.get("content-type");
83
+ let errorData = {};
84
+ if (contentType?.includes("application/json")) {
85
+ try {
86
+ errorData = await response.json();
87
+ } catch {
88
+ }
89
+ }
90
+ const message = errorData.error || `HTTP ${response.status}: ${response.statusText}`;
91
+ switch (response.status) {
92
+ case 401:
93
+ throw new AuthenticationError(message);
94
+ case 400:
95
+ throw new ValidationError(message, errorData.field);
96
+ case 429:
97
+ throw new RateLimitError(message);
98
+ default:
99
+ throw new ChannlizeError(message, response.status, errorData.code);
100
+ }
101
+ }
102
+ /**
103
+ * Submit a contact form
104
+ */
105
+ async submitContactForm(data) {
106
+ const response = await this.makeRequest("/public/contact", {
107
+ method: "POST",
108
+ body: JSON.stringify({
109
+ widgetKey: this.config.apiKey,
110
+ // apiKey is actually the widgetKey
111
+ subject: data.subject,
112
+ message: data.message,
113
+ email: data.email,
114
+ name: data.name,
115
+ pageUrl: data.pageUrl || (typeof window !== "undefined" ? window.location.href : void 0),
116
+ userAgent: data.userAgent || (typeof navigator !== "undefined" ? navigator.userAgent : void 0)
117
+ })
118
+ });
119
+ return response.data || response;
120
+ }
121
+ /**
122
+ * Create a new chat session
123
+ */
124
+ async createChatSession(metadata) {
125
+ const response = await this.makeRequest("/v1/chat/sessions", {
126
+ method: "POST",
127
+ body: JSON.stringify({
128
+ widgetKey: this.config.apiKey,
129
+ // apiKey is actually the widgetKey
130
+ metadata: {
131
+ ...metadata,
132
+ pageUrl: typeof window !== "undefined" ? window.location.href : void 0,
133
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0
134
+ }
135
+ })
136
+ });
137
+ return response.data;
138
+ }
139
+ /**
140
+ * Send a message in a chat session
141
+ */
142
+ async sendMessage(sessionId, content, attachments) {
143
+ const idempotencyKey = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
144
+ const response = await this.makeRequest(
145
+ `/v1/chat/sessions/${sessionId}/messages`,
146
+ {
147
+ method: "POST",
148
+ body: JSON.stringify({
149
+ content,
150
+ idempotencyKey
151
+ })
152
+ }
153
+ );
154
+ return response.data;
155
+ }
156
+ /**
157
+ * Get chat session details
158
+ */
159
+ async getChatSession(sessionId) {
160
+ const response = await this.makeRequest(`/v1/chat/sessions/${sessionId}`);
161
+ return response.data;
162
+ }
163
+ /**
164
+ * Get messages for a chat session
165
+ */
166
+ async getChatMessages(sessionId, limit = 50, offset = 0) {
167
+ const response = await this.makeRequest(
168
+ `/v1/chat/sessions/${sessionId}/messages?limit=${limit}&offset=${offset}`
169
+ );
170
+ return response.data;
171
+ }
172
+ /**
173
+ * Close a chat session
174
+ */
175
+ async closeChatSession(sessionId) {
176
+ const response = await this.makeRequest(
177
+ `/v1/chat/sessions/${sessionId}/close`,
178
+ { method: "POST" }
179
+ );
180
+ return response.data;
181
+ }
182
+ };
183
+ export {
184
+ AuthenticationError,
185
+ ChannlizeClient,
186
+ ChannlizeError,
187
+ RateLimitError,
188
+ ValidationError,
189
+ ChannlizeClient as default
190
+ };
191
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/types.ts"],"sourcesContent":["import fetch from 'cross-fetch';\nimport type {\n ChannlizeConfig,\n ContactFormData,\n ChatMessage,\n ApiResponse,\n CreateContactResponse,\n CreateChatSessionResponse,\n SendMessageResponse,\n ChatSession,\n} from './types';\nimport {\n ChannlizeError,\n AuthenticationError,\n ValidationError,\n RateLimitError,\n} from './types';\n\n/**\n * Channlize API Client\n * Provides methods to interact with the Channlize platform\n */\nexport class ChannlizeClient {\n private readonly config: Required<ChannlizeConfig>;\n\n constructor(config: ChannlizeConfig) {\n this.config = {\n baseUrl: config.baseUrl || 'https://api.channlize.com',\n timeout: 10000,\n ...config,\n };\n\n this.validateConfig();\n }\n\n private validateConfig(): void {\n if (!this.config.apiKey) {\n throw new ValidationError('Widget key is required');\n }\n }\n\n private async makeRequest<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<ApiResponse<T>> {\n const url = `${this.config.baseUrl}${endpoint}`;\n \n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers,\n },\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n await this.handleErrorResponse(response);\n }\n\n const data = await response.json();\n return data as ApiResponse<T>;\n } catch (error) {\n clearTimeout(timeoutId);\n \n if (error instanceof ChannlizeError) {\n throw error;\n }\n \n if (error instanceof Error && error.name === 'AbortError') {\n throw new ChannlizeError('Request timeout', 408, 'TIMEOUT');\n }\n \n throw new ChannlizeError(\n `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n private async handleErrorResponse(response: Response): Promise<never> {\n const contentType = response.headers.get('content-type');\n let errorData: any = {};\n\n if (contentType?.includes('application/json')) {\n try {\n errorData = await response.json();\n } catch {\n // Ignore JSON parsing errors\n }\n }\n\n const message = errorData.error || `HTTP ${response.status}: ${response.statusText}`;\n\n switch (response.status) {\n case 401:\n throw new AuthenticationError(message);\n case 400:\n throw new ValidationError(message, errorData.field);\n case 429:\n throw new RateLimitError(message);\n default:\n throw new ChannlizeError(message, response.status, errorData.code);\n }\n }\n\n /**\n * Submit a contact form\n */\n async submitContactForm(data: ContactFormData): Promise<CreateContactResponse> {\n const response = await this.makeRequest<CreateContactResponse>('/public/contact', {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n subject: data.subject,\n message: data.message,\n email: data.email,\n name: data.name,\n pageUrl: data.pageUrl || (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent: data.userAgent || (typeof navigator !== 'undefined' ? navigator.userAgent : undefined),\n }),\n });\n\n return response.data || response;\n }\n\n /**\n * Create a new chat session\n */\n async createChatSession(metadata?: Record<string, unknown>): Promise<CreateChatSessionResponse> {\n const response = await this.makeRequest<CreateChatSessionResponse>('/v1/chat/sessions', {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n metadata: {\n ...metadata,\n pageUrl: typeof window !== 'undefined' ? window.location.href : undefined,\n userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : undefined,\n },\n }),\n });\n\n return response.data;\n }\n\n /**\n * Send a message in a chat session\n */\n async sendMessage(\n sessionId: string,\n content: string,\n attachments?: File[]\n ): Promise<SendMessageResponse> {\n // Generate idempotency key to prevent duplicate message creation\n const idempotencyKey = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n \n // For now, we send as JSON. File attachments support can be added later.\n // TODO: Implement file upload support\n const response = await this.makeRequest<SendMessageResponse>(\n `/v1/chat/sessions/${sessionId}/messages`,\n {\n method: 'POST',\n body: JSON.stringify({\n content,\n idempotencyKey,\n }),\n }\n );\n\n return response.data;\n }\n\n /**\n * Get chat session details\n */\n async getChatSession(sessionId: string): Promise<ChatSession> {\n const response = await this.makeRequest<ChatSession>(`/v1/chat/sessions/${sessionId}`);\n return response.data;\n }\n\n /**\n * Get messages for a chat session\n */\n async getChatMessages(sessionId: string, limit = 50, offset = 0): Promise<ChatMessage[]> {\n const response = await this.makeRequest<ChatMessage[]>(\n `/v1/chat/sessions/${sessionId}/messages?limit=${limit}&offset=${offset}`\n );\n return response.data;\n }\n\n /**\n * Close a chat session\n */\n async closeChatSession(sessionId: string): Promise<ChatSession> {\n const response = await this.makeRequest<ChatSession>(\n `/v1/chat/sessions/${sessionId}/close`,\n { method: 'POST' }\n );\n return response.data;\n }\n}\n","/**\n * Core types for Channlize SDK\n */\n\nexport interface ChannlizeConfig {\n /** API key for authentication */\n apiKey: string;\n /** Base URL for the Channlize API */\n baseUrl?: string;\n /** Project ID */\n projectId: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n}\n\nexport interface ContactFormData {\n /** Contact's name */\n name: string;\n /** Contact's email address */\n email: string;\n /** Subject of the inquiry */\n subject?: string;\n /** Message content */\n message: string;\n /** Custom fields */\n customFields?: Record<string, unknown>;\n /** Page URL where the form was submitted */\n pageUrl?: string;\n /** User agent string */\n userAgent?: string;\n}\n\nexport interface ChatMessage {\n /** Unique message ID */\n id: string;\n /** Message content */\n content: string;\n /** Message timestamp */\n timestamp: Date;\n /** Message author (user or agent) */\n author: 'user' | 'agent';\n /** Author metadata */\n authorData?: {\n name?: string;\n email?: string;\n avatarUrl?: string;\n };\n /** Attached files */\n attachments?: FileAttachment[];\n}\n\nexport interface FileAttachment {\n /** File ID */\n id: string;\n /** Original filename */\n name: string;\n /** File size in bytes */\n size: number;\n /** MIME type */\n type: string;\n /** Download URL */\n url: string;\n}\n\nexport interface ChatSession {\n /** Session ID */\n id: string;\n /** Session status */\n status: 'active' | 'closed' | 'waiting';\n /** Messages in the session */\n messages: ChatMessage[];\n /** Session metadata */\n metadata?: Record<string, unknown>;\n /** Created timestamp */\n createdAt: Date;\n /** Updated timestamp */\n updatedAt: Date;\n}\n\nexport interface ApiResponse<T = unknown> {\n /** Response data */\n data: T;\n /** Success status */\n success: boolean;\n /** Error message if any */\n error?: string;\n /** Additional metadata */\n meta?: Record<string, unknown>;\n}\n\nexport interface CreateContactResponse {\n /** Contact form submission ID */\n id: string;\n /** Status of the submission */\n status: 'received' | 'processing' | 'delivered';\n /** Slack thread URL if available */\n slackThreadUrl?: string;\n}\n\nexport interface CreateChatSessionResponse {\n /** Chat session data */\n session: ChatSession;\n /** SSE endpoint for real-time updates */\n sseEndpoint?: string;\n}\n\nexport interface SendMessageResponse {\n /** The sent message */\n message: ChatMessage;\n /** Updated session */\n session: ChatSession;\n}\n\n/**\n * Error types\n */\nexport class ChannlizeError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public code?: string\n ) {\n super(message);\n this.name = 'ChannlizeError';\n }\n}\n\nexport class ValidationError extends ChannlizeError {\n constructor(message: string, public field?: string) {\n super(message, 400, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n\nexport class AuthenticationError extends ChannlizeError {\n constructor(message: string = 'Authentication failed') {\n super(message, 401, 'AUTHENTICATION_ERROR');\n this.name = 'AuthenticationError';\n }\n}\n\nexport class RateLimitError extends ChannlizeError {\n constructor(message: string = 'Rate limit exceeded') {\n super(message, 429, 'RATE_LIMIT_ERROR');\n this.name = 'RateLimitError';\n }\n}\n"],"mappings":";AAAA,OAAO,WAAW;;;ACoHX,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACO,YACA,MACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,eAAe;AAAA,EAClD,YAAY,SAAwB,OAAgB;AAClD,UAAM,SAAS,KAAK,kBAAkB;AADJ;AAElC,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,sBAAN,cAAkC,eAAe;AAAA,EACtD,YAAY,UAAkB,yBAAyB;AACrD,UAAM,SAAS,KAAK,sBAAsB;AAC1C,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,eAAe;AAAA,EACjD,YAAY,UAAkB,uBAAuB;AACnD,UAAM,SAAS,KAAK,kBAAkB;AACtC,SAAK,OAAO;AAAA,EACd;AACF;;;AD5HO,IAAM,kBAAN,MAAsB;AAAA,EACV;AAAA,EAEjB,YAAY,QAAyB;AACnC,SAAK,SAAS;AAAA,MACZ,SAAS,OAAO,WA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A;AAAA;AAAA;AAAA,EAKA,MAAM,YACJ,WACA,SACA,aAC8B;AAE9B,UAAM,iBAAiB,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,GAAG,CAAC,CAAC;AAInF,UAAM,WAAW,MAAM,KAAK;AAAA,MAC1B,qBAAqB,SAAS;AAAA,MAC9B;AAAA,QACE,QAAQ;AAAA,QACR,MAAM,KAAK,UAAU;AAAA,UACnB;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAEA,WAAO,SAAS;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,eAAe,WAAyC;AAC5D,UAAM,WAAW,MAAM,KAAK,YAAyB,qBAAqB,SAAS,EAAE;AACrF,WAAO,SAAS;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,gBAAgB,WAAmB,QAAQ,IAAI,SAAS,GAA2B;AACvF,UAAM,WAAW,MAAM,KAAK;AAAA,MAC1B,qBAAqB,SAAS,mBAAmB,KAAK,WAAW,MAAM;AAAA,IACzE;AACA,WAAO,SAAS;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,iBAAiB,WAAyC;AAC9D,UAAM,WAAW,MAAM,KAAK;AAAA,MAC1B,qBAAqB,SAAS;AAAA,MAC9B,EAAE,QAAQ,OAAO;AAAA,IACnB;AACA,WAAO,SAAS;AAAA,EAClB;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@channlize/core",
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "Channlize Core SDK - TypeScript API wrapper for Channlize platform",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsup",
20
+ "dev": "tsup --watch",
21
+ "lint": "eslint src --ext .ts",
22
+ "lint:fix": "eslint src --ext .ts --fix",
23
+ "type-check": "tsc --noEmit",
24
+ "clean": "rm -rf dist"
25
+ },
26
+ "keywords": [
27
+ "channlize",
28
+ "api",
29
+ "typescript",
30
+ "sdk"
31
+ ],
32
+ "author": "Channlize Team",
33
+ "license": "MIT",
34
+ "dependencies": {
35
+ "cross-fetch": "^4.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^20.11.5",
39
+ "@typescript-eslint/eslint-plugin": "^6.21.0",
40
+ "@typescript-eslint/parser": "^6.21.0",
41
+ "eslint": "^8.56.0",
42
+ "tsup": "^8.0.1",
43
+ "typescript": "^5.3.3"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/channlize/sdk.git",
51
+ "directory": "packages/core"
52
+ }
53
+ }