@channlize/core 0.1.0 → 0.2.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/dist/index.js CHANGED
@@ -35,11 +35,12 @@ __export(index_exports, {
35
35
  ChannlizeError: () => ChannlizeError,
36
36
  RateLimitError: () => RateLimitError,
37
37
  ValidationError: () => ValidationError,
38
+ createNotifier: () => createNotifier,
38
39
  default: () => ChannlizeClient
39
40
  });
40
41
  module.exports = __toCommonJS(index_exports);
41
42
 
42
- // src/client.ts
43
+ // src/http.ts
43
44
  var import_cross_fetch = __toESM(require("cross-fetch"));
44
45
 
45
46
  // src/types.ts
@@ -74,14 +75,149 @@ var RateLimitError = class extends ChannlizeError {
74
75
  }
75
76
  };
76
77
 
78
+ // src/http.ts
79
+ async function requestJson(http, endpoint, options = {}) {
80
+ const url = `${http.baseUrl}${endpoint}`;
81
+ const controller = new AbortController();
82
+ const timeoutId = setTimeout(() => controller.abort(), http.timeout);
83
+ try {
84
+ const mergedHeaders = {
85
+ "Content-Type": "application/json",
86
+ ...options.headers
87
+ };
88
+ if (mergedHeaders["Content-Type"] === "") {
89
+ delete mergedHeaders["Content-Type"];
90
+ }
91
+ const response = await (0, import_cross_fetch.default)(url, {
92
+ ...options,
93
+ signal: controller.signal,
94
+ headers: mergedHeaders
95
+ });
96
+ clearTimeout(timeoutId);
97
+ if (!response.ok) {
98
+ await handleErrorResponse(response);
99
+ }
100
+ const data = await response.json();
101
+ return data;
102
+ } catch (error) {
103
+ clearTimeout(timeoutId);
104
+ if (error instanceof ChannlizeError) {
105
+ throw error;
106
+ }
107
+ if (error instanceof Error && error.name === "AbortError") {
108
+ throw new ChannlizeError("Request timeout", 408, "TIMEOUT");
109
+ }
110
+ throw new ChannlizeError(
111
+ `Network error: ${error instanceof Error ? error.message : "Unknown error"}`
112
+ );
113
+ }
114
+ }
115
+ async function handleErrorResponse(response) {
116
+ const contentType = response.headers.get("content-type");
117
+ let errorData = {};
118
+ if (contentType?.includes("application/json")) {
119
+ try {
120
+ errorData = await response.json();
121
+ } catch {
122
+ }
123
+ }
124
+ const rawMessage = errorData.message;
125
+ const message = (Array.isArray(rawMessage) ? rawMessage.join(", ") : rawMessage) || `HTTP ${response.status}: ${response.statusText}`;
126
+ const code = errorData.code ?? errorData.error;
127
+ switch (response.status) {
128
+ case 401:
129
+ throw new AuthenticationError(message);
130
+ case 400:
131
+ throw new ValidationError(message, errorData.field);
132
+ case 429:
133
+ throw new RateLimitError(message);
134
+ default:
135
+ throw new ChannlizeError(message, response.status, code);
136
+ }
137
+ }
138
+
139
+ // src/notify.ts
140
+ var EVENT_KEY = /^[a-z0-9][a-z0-9._-]*$/;
141
+ var DEFAULT_BASE_URL = "https://api.channlize.com";
142
+ async function sendNotify(http, auth, event, data, options = {}) {
143
+ if (!auth.projectId) {
144
+ throw new ValidationError("projectId is required for notify", "projectId");
145
+ }
146
+ if (auth.serverApiKey.startsWith("wk_")) {
147
+ throw new ValidationError(
148
+ "notify needs a server API key (ch_live_\u2026, write scope), not the public widget key",
149
+ "serverApiKey"
150
+ );
151
+ }
152
+ if (typeof event !== "string" || event.length > 100 || !EVENT_KEY.test(event)) {
153
+ throw new ValidationError(
154
+ `Invalid event key "${event}": use lowercase letters, digits, dots, underscores or dashes (e.g. user.subscribed)`,
155
+ "event"
156
+ );
157
+ }
158
+ const headers = {
159
+ Authorization: `Bearer ${auth.serverApiKey}`
160
+ };
161
+ if (options.idempotencyKey) {
162
+ headers["Idempotency-Key"] = options.idempotencyKey;
163
+ }
164
+ const res = await requestJson(http, "/v1/notify", {
165
+ method: "POST",
166
+ headers,
167
+ body: JSON.stringify({
168
+ projectId: auth.projectId,
169
+ event,
170
+ data: data ?? {},
171
+ channel: options.channel
172
+ })
173
+ });
174
+ return res;
175
+ }
176
+ function readEnv(name) {
177
+ const env = typeof process !== "undefined" && process.env ? process.env : void 0;
178
+ const value = env?.[name];
179
+ return value && value.trim() ? value.trim() : void 0;
180
+ }
181
+ function createNotifier(config = {}) {
182
+ return (event, data, options) => {
183
+ const serverApiKey = config.serverApiKey ?? readEnv("CHANNLIZE_SERVER_API_KEY") ?? readEnv("CHANNLIZE_API_KEY");
184
+ const projectId = config.projectId ?? readEnv("CHANNLIZE_PROJECT_ID");
185
+ if (!serverApiKey) {
186
+ return Promise.reject(
187
+ new ValidationError(
188
+ "A server API key is required: pass serverApiKey or set CHANNLIZE_API_KEY (or CHANNLIZE_SERVER_API_KEY)",
189
+ "serverApiKey"
190
+ )
191
+ );
192
+ }
193
+ if (!projectId) {
194
+ return Promise.reject(
195
+ new ValidationError(
196
+ "A project ID is required: pass projectId or set CHANNLIZE_PROJECT_ID",
197
+ "projectId"
198
+ )
199
+ );
200
+ }
201
+ const baseUrl = config.baseUrl ?? readEnv("CHANNLIZE_BASE_URL") ?? DEFAULT_BASE_URL;
202
+ return sendNotify(
203
+ { baseUrl: baseUrl.replace(/\/$/, ""), timeout: config.timeout ?? 1e4 },
204
+ { serverApiKey, projectId },
205
+ event,
206
+ data,
207
+ options
208
+ );
209
+ };
210
+ }
211
+
77
212
  // src/client.ts
78
213
  var ChannlizeClient = class {
79
214
  config;
80
215
  constructor(config) {
81
216
  this.config = {
217
+ ...config,
218
+ // After the spread: an explicit `undefined` must not drop the defaults.
82
219
  baseUrl: config.baseUrl || "https://api.channlize.com",
83
- timeout: 1e4,
84
- ...config
220
+ timeout: config.timeout ?? 1e4
85
221
  };
86
222
  this.validateConfig();
87
223
  }
@@ -90,64 +226,8 @@ var ChannlizeClient = class {
90
226
  throw new ValidationError("Widget key is required");
91
227
  }
92
228
  }
93
- async makeRequest(endpoint, options = {}) {
94
- const url = `${this.config.baseUrl}${endpoint}`;
95
- const controller = new AbortController();
96
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
97
- try {
98
- const mergedHeaders = {
99
- "Content-Type": "application/json",
100
- ...options.headers
101
- };
102
- if (mergedHeaders["Content-Type"] === "") {
103
- delete mergedHeaders["Content-Type"];
104
- }
105
- const response = await (0, import_cross_fetch.default)(url, {
106
- ...options,
107
- signal: controller.signal,
108
- headers: mergedHeaders
109
- });
110
- clearTimeout(timeoutId);
111
- if (!response.ok) {
112
- await this.handleErrorResponse(response);
113
- }
114
- const data = await response.json();
115
- return data;
116
- } catch (error) {
117
- clearTimeout(timeoutId);
118
- if (error instanceof ChannlizeError) {
119
- throw error;
120
- }
121
- if (error instanceof Error && error.name === "AbortError") {
122
- throw new ChannlizeError("Request timeout", 408, "TIMEOUT");
123
- }
124
- throw new ChannlizeError(
125
- `Network error: ${error instanceof Error ? error.message : "Unknown error"}`
126
- );
127
- }
128
- }
129
- async handleErrorResponse(response) {
130
- const contentType = response.headers.get("content-type");
131
- let errorData = {};
132
- if (contentType?.includes("application/json")) {
133
- try {
134
- errorData = await response.json();
135
- } catch {
136
- }
137
- }
138
- const rawMessage = errorData.message;
139
- const message = (Array.isArray(rawMessage) ? rawMessage.join(", ") : rawMessage) || `HTTP ${response.status}: ${response.statusText}`;
140
- const code = errorData.code ?? errorData.error;
141
- switch (response.status) {
142
- case 401:
143
- throw new AuthenticationError(message);
144
- case 400:
145
- throw new ValidationError(message, errorData.field);
146
- case 429:
147
- throw new RateLimitError(message);
148
- default:
149
- throw new ChannlizeError(message, response.status, code);
150
- }
229
+ makeRequest(endpoint, options = {}) {
230
+ return requestJson(this.config, endpoint, options);
151
231
  }
152
232
  /**
153
233
  * Submit a contact form
@@ -164,6 +244,7 @@ var ChannlizeClient = class {
164
244
  message: data.message,
165
245
  email: data.email,
166
246
  name: data.name,
247
+ customFields: data.customFields && Object.keys(data.customFields).length > 0 ? data.customFields : void 0,
167
248
  pageUrl: data.pageUrl || (typeof window !== "undefined" ? window.location.href : void 0),
168
249
  userAgent: data.userAgent || (typeof navigator !== "undefined" ? navigator.userAgent : void 0)
169
250
  })
@@ -258,7 +339,8 @@ var ChannlizeClient = class {
258
339
  return response.data;
259
340
  }
260
341
  /**
261
- * Track a product or UX event from the browser (uses widget key → POST /public/events).
342
+ * Log tracking: record a log line from the browser (widget key →
343
+ * `POST /public/events`). Shown under Log tracking in the dashboard.
262
344
  */
263
345
  async trackEvent(name, options) {
264
346
  const res = await this.makeRequest(
@@ -280,7 +362,8 @@ var ChannlizeClient = class {
280
362
  return data;
281
363
  }
282
364
  /**
283
- * Track an event from a trusted server using the organization API key (POST /v1/events).
365
+ * Log tracking from a trusted server, using the organization API key
366
+ * (`POST /v1/events`). Shown under Log tracking in the dashboard.
284
367
  */
285
368
  async trackServerEvent(name, options) {
286
369
  if (!this.config.serverApiKey) {
@@ -306,6 +389,31 @@ var ChannlizeClient = class {
306
389
  const data = res.data ?? res;
307
390
  return data;
308
391
  }
392
+ /**
393
+ * Events: post a Slack message from your server when something happens
394
+ * (`POST /v1/notify`). The event key picks the channel and message
395
+ * template configured under Events in the dashboard; `data` fills the
396
+ * template's `{{field}}` placeholders. Needs `serverApiKey` (write scope)
397
+ * and `projectId` — never call it from browser code.
398
+ *
399
+ * An unknown key is saved as a disabled draft and answered with
400
+ * `status: 'skipped'`, so it never throws for a missing setup.
401
+ */
402
+ async notify(event, data, options) {
403
+ if (!this.config.serverApiKey) {
404
+ throw new ValidationError("serverApiKey is required for notify");
405
+ }
406
+ return sendNotify(
407
+ this.config,
408
+ {
409
+ serverApiKey: this.config.serverApiKey,
410
+ projectId: this.config.projectId
411
+ },
412
+ event,
413
+ data,
414
+ options
415
+ );
416
+ }
309
417
  };
310
418
  // Annotate the CommonJS export names for ESM import in node:
311
419
  0 && (module.exports = {
@@ -313,6 +421,7 @@ var ChannlizeClient = class {
313
421
  ChannlizeClient,
314
422
  ChannlizeError,
315
423
  RateLimitError,
316
- ValidationError
424
+ ValidationError,
425
+ createNotifier
317
426
  });
318
427
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +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 TrackEventOptions,\n EventSeverity,\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: ChannlizeConfig & {\n baseUrl: string;\n timeout: number;\n };\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 mergedHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers as Record<string, string>),\n };\n\n // When Content-Type is explicitly empty (e.g. FormData), remove it so the\n // browser / runtime can set the correct multipart boundary automatically.\n if (mergedHeaders['Content-Type'] === '') {\n delete mergedHeaders['Content-Type'];\n }\n\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: mergedHeaders,\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 // API error shape (api/lib/api/error.ts):\n // { statusCode, error: \"BAD_REQUEST\", message: string | string[] }\n // `error` is the machine-readable code; `message` is the human text\n // (an array of field messages for validation failures).\n const rawMessage = errorData.message;\n const message =\n (Array.isArray(rawMessage) ? rawMessage.join(', ') : rawMessage) ||\n `HTTP ${response.status}: ${response.statusText}`;\n const code: string | undefined = errorData.code ?? errorData.error;\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, code);\n }\n }\n\n /**\n * Submit a contact form\n */\n async submitContactForm(\n data: ContactFormData\n ): Promise<CreateContactResponse> {\n const response = await this.makeRequest<CreateContactResponse>(\n '/public/contact',\n {\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:\n data.pageUrl ||\n (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent:\n data.userAgent ||\n (typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined),\n }),\n }\n );\n\n return response.data || response;\n }\n\n /**\n * Create a new chat session\n */\n async createChatSession(\n metadata?: Record<string, unknown>\n ): Promise<CreateChatSessionResponse> {\n const response = await this.makeRequest<CreateChatSessionResponse>(\n '/v1/chat/sessions',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n metadata: {\n ...metadata,\n pageUrl:\n typeof window !== 'undefined' ? window.location.href : undefined,\n userAgent:\n typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined,\n },\n }),\n }\n );\n\n return response.data;\n }\n\n /**\n * Send a message in a chat session.\n * When `attachments` are provided the request is sent as multipart/form-data\n * so the files are uploaded alongside the message content.\n */\n async sendMessage(\n sessionId: string,\n content: string,\n attachments?: File[]\n ): Promise<SendMessageResponse> {\n const idempotencyKey = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n if (attachments && attachments.length > 0) {\n const formData = new FormData();\n formData.append('content', content);\n formData.append('idempotencyKey', idempotencyKey);\n for (const file of attachments) {\n formData.append('attachments', file, file.name);\n }\n\n const response = await this.makeRequest<SendMessageResponse>(\n `/v1/chat/sessions/${sessionId}/messages`,\n {\n method: 'POST',\n body: formData,\n // Let the browser set Content-Type with boundary for multipart\n headers: { 'Content-Type': '' },\n }\n );\n\n return response.data;\n }\n\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>(\n `/v1/chat/sessions/${sessionId}`\n );\n return response.data;\n }\n\n /**\n * Get messages for a chat session\n */\n async getChatMessages(\n sessionId: string,\n limit = 50,\n offset = 0\n ): 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 * Track a product or UX event from the browser (uses widget key → POST /public/events).\n */\n async trackEvent(\n name: string,\n options?: TrackEventOptions\n ): Promise<{ success: boolean; id: string }> {\n const res = await this.makeRequest<{ success: boolean; id: string }>(\n '/public/events',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey,\n name,\n properties: options?.properties,\n severity: options?.severity,\n distinctId: options?.distinctId,\n pageUrl:\n options?.pageUrl ??\n (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent:\n options?.userAgent ??\n (typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined),\n }),\n }\n );\n const data =\n (res as ApiResponse<{ success: boolean; id: string }>).data ??\n (res as unknown as { success: boolean; id: string });\n return data;\n }\n\n /**\n * Track an event from a trusted server using the organization API key (POST /v1/events).\n */\n async trackServerEvent(\n name: string,\n options?: { properties?: Record<string, unknown>; severity?: EventSeverity }\n ): Promise<{ success: boolean; id: string }> {\n if (!this.config.serverApiKey) {\n throw new ValidationError(\n 'serverApiKey is required for trackServerEvent'\n );\n }\n const res = await this.makeRequest<{ success: boolean; id: string }>(\n '/v1/events',\n {\n method: 'POST',\n body: JSON.stringify({\n projectId: this.config.projectId,\n name,\n properties: options?.properties,\n severity: options?.severity,\n }),\n headers: {\n Authorization: `Bearer ${this.config.serverApiKey}`,\n },\n }\n );\n const data =\n (res as ApiResponse<{ success: boolean; id: string }>).data ??\n (res as unknown as { success: boolean; id: string });\n return data;\n }\n}\n","/**\n * Core types for Channlize SDK\n */\n\n/** Severity for tracked events (Slack routing uses project settings). */\nexport type EventSeverity = 'info' | 'warning' | 'error';\n\nexport interface TrackEventOptions {\n properties?: Record<string, unknown>;\n severity?: EventSeverity;\n distinctId?: string;\n pageUrl?: string;\n userAgent?: string;\n}\n\nexport interface ChannlizeConfig {\n /** Widget key used for public SDK endpoints (contact form, chat, browser event tracking) */\n apiKey: string;\n /** Base URL for the Channlize API */\n baseUrl?: string;\n /** Project ID (required for server-side `trackServerEvent`) */\n projectId: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /**\n * Organization API key for server-side `trackServerEvent` (`POST /v1/events`).\n * Do not expose in browser bundles.\n */\n serverApiKey?: string;\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\n/** Response of `POST /public/contact` (api/app/api/public/contact/route.ts). */\nexport interface CreateContactResponse {\n /** Whether the submission was accepted */\n success: boolean;\n /** Conversation the submission was filed under */\n conversationId: string;\n /** Human-readable confirmation to show the visitor */\n message: string;\n /** @deprecated Never returned by the API (always undefined). Use `conversationId`. */\n id: string;\n /** @deprecated Never returned by the API (always undefined). */\n status: 'received' | 'processing' | 'delivered';\n /** @deprecated Never returned by the API (always undefined). */\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(\n message: string,\n public field?: string\n ) {\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;;;AC2IX,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACO,YACA,MACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AAAA,EALS;AAAA,EACA;AAKX;AAEO,IAAM,kBAAN,cAA8B,eAAe;AAAA,EAClD,YACE,SACO,OACP;AACA,UAAM,SAAS,KAAK,kBAAkB;AAF/B;AAGP,SAAK,OAAO;AAAA,EACd;AAAA,EAJS;AAKX;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;;;ADpJO,IAAM,kBAAN,MAAsB;AAAA,EACV;AAAA,EAKjB,YAAY,QAAyB;AACnC,SAAK,SAAS;AAAA,MACZ,SAAS,OAAO,WAAW;AAAA,MAC3B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UAAM,OACH,IAAsD,QACtD;AACH,WAAO;AAAA,EACT;AACF;","names":["fetch","response"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/http.ts","../src/types.ts","../src/notify.ts","../src/client.ts"],"sourcesContent":["/**\n * @channlize/core\n * Core TypeScript SDK for Channlize platform\n */\n\nexport { ChannlizeClient } from './client';\nexport { createNotifier } from './notify';\nexport type { Notifier } from './notify';\nexport * from './types';\n\n// Re-export for convenience\nexport { ChannlizeClient as default } from './client';\n","import fetch from 'cross-fetch';\nimport type { ApiResponse } from './types';\nimport {\n ChannlizeError,\n AuthenticationError,\n ValidationError,\n RateLimitError,\n} from './types';\n\n/**\n * Shared HTTP layer for `ChannlizeClient` and `createNotifier`: JSON\n * requests with a timeout, and the API's error shape mapped to typed errors.\n */\nexport async function requestJson<T>(\n http: { baseUrl: string; timeout: number },\n endpoint: string,\n options: RequestInit = {}\n): Promise<ApiResponse<T>> {\n const url = `${http.baseUrl}${endpoint}`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), http.timeout);\n\n try {\n const mergedHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers as Record<string, string>),\n };\n\n // When Content-Type is explicitly empty (e.g. FormData), remove it so the\n // browser / runtime can set the correct multipart boundary automatically.\n if (mergedHeaders['Content-Type'] === '') {\n delete mergedHeaders['Content-Type'];\n }\n\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: mergedHeaders,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n await 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\nexport async function handleErrorResponse(response: Response): Promise<never> {\n const contentType = response.headers.get('content-type');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 // API error shape (api/lib/api/error.ts):\n // { statusCode, error: \"BAD_REQUEST\", message: string | string[] }\n // `error` is the machine-readable code; `message` is the human text\n // (an array of field messages for validation failures).\n const rawMessage = errorData.message;\n const message =\n (Array.isArray(rawMessage) ? rawMessage.join(', ') : rawMessage) ||\n `HTTP ${response.status}: ${response.statusText}`;\n const code: string | undefined = errorData.code ?? errorData.error;\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, code);\n }\n}\n","/**\n * Core types for Channlize SDK\n */\n\n/** Severity for log tracking (`trackEvent` / `trackServerEvent`); Slack alerts use project settings. */\nexport type EventSeverity = 'info' | 'warning' | 'error';\n\n/** Options for log tracking (`trackEvent` / `trackServerEvent`). */\nexport interface TrackEventOptions {\n properties?: Record<string, unknown>;\n severity?: EventSeverity;\n distinctId?: string;\n pageUrl?: string;\n userAgent?: string;\n}\n\nexport interface ChannlizeConfig {\n /** Widget key used for public SDK endpoints (contact form, chat, browser log tracking) */\n apiKey: string;\n /** Base URL for the Channlize API */\n baseUrl?: string;\n /** Project ID (required for server-side `trackServerEvent` and `notify`) */\n projectId: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /**\n * Organization (server) API key, `ch_live_…`, for `trackServerEvent`\n * (`POST /v1/events`) and `notify` (`POST /v1/notify`, needs the `write`\n * scope). Do not expose in browser bundles.\n */\n serverApiKey?: string;\n}\n\n/**\n * Events (notify Slack from code). Augment this interface to type event\n * keys and their data across your app:\n *\n * ```ts\n * declare module '@channlize/core' {\n * interface ChannlizeEvents {\n * 'user.subscribed': { username: string; plan: string };\n * }\n * }\n * ```\n *\n * Or pass a map as a type argument: `createNotifier<AppEvents>()`.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ChannlizeEvents {}\n\n/** A declared event key (autocompleted) or any other key. */\nexport type NotifyEventName<TEvents extends object = ChannlizeEvents> =\n (keyof TEvents & string) | (string & {});\n\n/** The declared data for a key, or any object for undeclared keys. */\nexport type NotifyEventData<\n TEvents extends object = ChannlizeEvents,\n K = string,\n> = K extends keyof TEvents ? TEvents[K] : Record<string, unknown>;\n\nexport interface NotifyOptions {\n /**\n * Retry-safe sends: a key already used on the project returns the first\n * delivery (`duplicate: true`) and posts nothing. Sent as `Idempotency-Key`.\n */\n idempotencyKey?: string;\n /** Slack channel ID to post to instead of the event's channel, for this call. */\n channel?: string;\n}\n\nexport interface NotifyResponse {\n success: boolean;\n /** Delivery ID (see Events → Recent deliveries in the dashboard). */\n id: string;\n event: string;\n /**\n * `queued`: will be posted to Slack. `skipped`: not posted (see `reason`):\n * the event is disabled, is new (saved as a draft to configure), or there\n * is no Slack workspace / channel. With `duplicate`, the first call's status.\n */\n status: 'queued' | 'skipped' | 'sent' | 'failed';\n reason?: string;\n duplicate?: boolean;\n}\n\n/** `createNotifier` options; each falls back to an environment variable. */\nexport interface NotifierConfig {\n /**\n * Server API key (`ch_live_…`, write scope). Default:\n * `CHANNLIZE_SERVER_API_KEY`, else `CHANNLIZE_API_KEY`.\n */\n serverApiKey?: string;\n /** Project ID. Default: `CHANNLIZE_PROJECT_ID`. */\n projectId?: string;\n /** API base URL. Default: `CHANNLIZE_BASE_URL`, else `https://api.channlize.com`. */\n baseUrl?: string;\n /** Request timeout in ms (default 10000). */\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\n/** Response of `POST /public/contact` (api/app/api/public/contact/route.ts). */\nexport interface CreateContactResponse {\n /** Whether the submission was accepted */\n success: boolean;\n /** Conversation the submission was filed under */\n conversationId: string;\n /** Human-readable confirmation to show the visitor */\n message: string;\n /** @deprecated Never returned by the API (always undefined). Use `conversationId`. */\n id: string;\n /** @deprecated Never returned by the API (always undefined). */\n status: 'received' | 'processing' | 'delivered';\n /** @deprecated Never returned by the API (always undefined). */\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(\n message: string,\n public field?: string\n ) {\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","import { requestJson } from './http';\nimport type {\n ChannlizeEvents,\n NotifierConfig,\n NotifyEventData,\n NotifyEventName,\n NotifyOptions,\n NotifyResponse,\n} from './types';\nimport { ValidationError } from './types';\n\n/** Same rule as the API: `user.subscribed`, `invoice_paid`, `signup-done`. */\nconst EVENT_KEY = /^[a-z0-9][a-z0-9._-]*$/;\n\nconst DEFAULT_BASE_URL = 'https://api.channlize.com';\n\n/** `POST /v1/notify`, shared by `ChannlizeClient.notify` and `createNotifier`. */\nexport async function sendNotify(\n http: { baseUrl: string; timeout: number },\n auth: { serverApiKey: string; projectId: string },\n event: string,\n data: Record<string, unknown> | undefined,\n options: NotifyOptions = {}\n): Promise<NotifyResponse> {\n if (!auth.projectId) {\n throw new ValidationError('projectId is required for notify', 'projectId');\n }\n if (auth.serverApiKey.startsWith('wk_')) {\n throw new ValidationError(\n 'notify needs a server API key (ch_live_…, write scope), not the public widget key',\n 'serverApiKey'\n );\n }\n if (\n typeof event !== 'string' ||\n event.length > 100 ||\n !EVENT_KEY.test(event)\n ) {\n throw new ValidationError(\n `Invalid event key \"${event}\": use lowercase letters, digits, dots, underscores or dashes (e.g. user.subscribed)`,\n 'event'\n );\n }\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${auth.serverApiKey}`,\n };\n if (options.idempotencyKey) {\n headers['Idempotency-Key'] = options.idempotencyKey;\n }\n\n const res = await requestJson<NotifyResponse>(http, '/v1/notify', {\n method: 'POST',\n headers,\n body: JSON.stringify({\n projectId: auth.projectId,\n event,\n data: data ?? {},\n channel: options.channel,\n }),\n });\n // The API answers at the top level (no `data` envelope).\n return res as unknown as NotifyResponse;\n}\n\nfunction readEnv(name: string): string | undefined {\n // `process` is absent in browsers and some edge runtimes.\n const env =\n typeof process !== 'undefined' && process.env ? process.env : undefined;\n const value = env?.[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nexport type Notifier<TEvents extends object = ChannlizeEvents> = <\n K extends NotifyEventName<TEvents>,\n>(\n event: K,\n data?: NotifyEventData<TEvents, K>,\n options?: NotifyOptions\n) => Promise<NotifyResponse>;\n\n/**\n * Events: a standalone server-side `notify(event, data)` function. Reads\n * the server key from `CHANNLIZE_SERVER_API_KEY` or `CHANNLIZE_API_KEY`, and\n * `CHANNLIZE_PROJECT_ID`, unless given — when it is called, so creating it\n * at module load never throws.\n *\n * ```ts\n * const notify = createNotifier();\n * await notify('user.subscribed', { username: 'ada', plan: 'Pro' });\n * ```\n */\nexport function createNotifier<TEvents extends object = ChannlizeEvents>(\n config: NotifierConfig = {}\n): Notifier<TEvents> {\n return (event, data, options) => {\n const serverApiKey =\n config.serverApiKey ??\n readEnv('CHANNLIZE_SERVER_API_KEY') ??\n readEnv('CHANNLIZE_API_KEY');\n const projectId = config.projectId ?? readEnv('CHANNLIZE_PROJECT_ID');\n if (!serverApiKey) {\n return Promise.reject(\n new ValidationError(\n 'A server API key is required: pass serverApiKey or set CHANNLIZE_API_KEY (or CHANNLIZE_SERVER_API_KEY)',\n 'serverApiKey'\n )\n );\n }\n if (!projectId) {\n return Promise.reject(\n new ValidationError(\n 'A project ID is required: pass projectId or set CHANNLIZE_PROJECT_ID',\n 'projectId'\n )\n );\n }\n const baseUrl =\n config.baseUrl ?? readEnv('CHANNLIZE_BASE_URL') ?? DEFAULT_BASE_URL;\n return sendNotify(\n { baseUrl: baseUrl.replace(/\\/$/, ''), timeout: config.timeout ?? 10000 },\n { serverApiKey, projectId },\n event,\n data as Record<string, unknown> | undefined,\n options\n );\n };\n}\n","import { requestJson } from './http';\nimport { sendNotify } from './notify';\nimport type {\n ChannlizeConfig,\n ContactFormData,\n ChatMessage,\n ApiResponse,\n CreateContactResponse,\n CreateChatSessionResponse,\n SendMessageResponse,\n ChatSession,\n TrackEventOptions,\n EventSeverity,\n ChannlizeEvents,\n NotifyEventName,\n NotifyEventData,\n NotifyOptions,\n NotifyResponse,\n} from './types';\nimport { ValidationError } from './types';\n\n/**\n * Channlize API Client\n * Provides methods to interact with the Channlize platform.\n *\n * `TEvents` types `notify()` event keys and data (defaults to the\n * augmentable `ChannlizeEvents` interface; any string key is accepted).\n */\nexport class ChannlizeClient<TEvents extends object = ChannlizeEvents> {\n private readonly config: ChannlizeConfig & {\n baseUrl: string;\n timeout: number;\n };\n\n constructor(config: ChannlizeConfig) {\n this.config = {\n ...config,\n // After the spread: an explicit `undefined` must not drop the defaults.\n baseUrl: config.baseUrl || 'https://api.channlize.com',\n timeout: config.timeout ?? 10000,\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 makeRequest<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<ApiResponse<T>> {\n return requestJson<T>(this.config, endpoint, options);\n }\n\n /**\n * Submit a contact form\n */\n async submitContactForm(\n data: ContactFormData\n ): Promise<CreateContactResponse> {\n const response = await this.makeRequest<CreateContactResponse>(\n '/public/contact',\n {\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 customFields:\n data.customFields && Object.keys(data.customFields).length > 0\n ? data.customFields\n : undefined,\n pageUrl:\n data.pageUrl ||\n (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent:\n data.userAgent ||\n (typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined),\n }),\n }\n );\n\n return response.data || response;\n }\n\n /**\n * Create a new chat session\n */\n async createChatSession(\n metadata?: Record<string, unknown>\n ): Promise<CreateChatSessionResponse> {\n const response = await this.makeRequest<CreateChatSessionResponse>(\n '/v1/chat/sessions',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n metadata: {\n ...metadata,\n pageUrl:\n typeof window !== 'undefined' ? window.location.href : undefined,\n userAgent:\n typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined,\n },\n }),\n }\n );\n\n return response.data;\n }\n\n /**\n * Send a message in a chat session.\n * When `attachments` are provided the request is sent as multipart/form-data\n * so the files are uploaded alongside the message content.\n */\n async sendMessage(\n sessionId: string,\n content: string,\n attachments?: File[]\n ): Promise<SendMessageResponse> {\n const idempotencyKey = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n if (attachments && attachments.length > 0) {\n const formData = new FormData();\n formData.append('content', content);\n formData.append('idempotencyKey', idempotencyKey);\n for (const file of attachments) {\n formData.append('attachments', file, file.name);\n }\n\n const response = await this.makeRequest<SendMessageResponse>(\n `/v1/chat/sessions/${sessionId}/messages`,\n {\n method: 'POST',\n body: formData,\n // Let the browser set Content-Type with boundary for multipart\n headers: { 'Content-Type': '' },\n }\n );\n\n return response.data;\n }\n\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>(\n `/v1/chat/sessions/${sessionId}`\n );\n return response.data;\n }\n\n /**\n * Get messages for a chat session\n */\n async getChatMessages(\n sessionId: string,\n limit = 50,\n offset = 0\n ): 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 * Log tracking: record a log line from the browser (widget key →\n * `POST /public/events`). Shown under Log tracking in the dashboard.\n */\n async trackEvent(\n name: string,\n options?: TrackEventOptions\n ): Promise<{ success: boolean; id: string }> {\n const res = await this.makeRequest<{ success: boolean; id: string }>(\n '/public/events',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey,\n name,\n properties: options?.properties,\n severity: options?.severity,\n distinctId: options?.distinctId,\n pageUrl:\n options?.pageUrl ??\n (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent:\n options?.userAgent ??\n (typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined),\n }),\n }\n );\n const data =\n (res as ApiResponse<{ success: boolean; id: string }>).data ??\n (res as unknown as { success: boolean; id: string });\n return data;\n }\n\n /**\n * Log tracking from a trusted server, using the organization API key\n * (`POST /v1/events`). Shown under Log tracking in the dashboard.\n */\n async trackServerEvent(\n name: string,\n options?: { properties?: Record<string, unknown>; severity?: EventSeverity }\n ): Promise<{ success: boolean; id: string }> {\n if (!this.config.serverApiKey) {\n throw new ValidationError(\n 'serverApiKey is required for trackServerEvent'\n );\n }\n const res = await this.makeRequest<{ success: boolean; id: string }>(\n '/v1/events',\n {\n method: 'POST',\n body: JSON.stringify({\n projectId: this.config.projectId,\n name,\n properties: options?.properties,\n severity: options?.severity,\n }),\n headers: {\n Authorization: `Bearer ${this.config.serverApiKey}`,\n },\n }\n );\n const data =\n (res as ApiResponse<{ success: boolean; id: string }>).data ??\n (res as unknown as { success: boolean; id: string });\n return data;\n }\n\n /**\n * Events: post a Slack message from your server when something happens\n * (`POST /v1/notify`). The event key picks the channel and message\n * template configured under Events in the dashboard; `data` fills the\n * template's `{{field}}` placeholders. Needs `serverApiKey` (write scope)\n * and `projectId` — never call it from browser code.\n *\n * An unknown key is saved as a disabled draft and answered with\n * `status: 'skipped'`, so it never throws for a missing setup.\n */\n async notify<K extends NotifyEventName<TEvents>>(\n event: K,\n data?: NotifyEventData<TEvents, K>,\n options?: NotifyOptions\n ): Promise<NotifyResponse> {\n if (!this.config.serverApiKey) {\n throw new ValidationError('serverApiKey is required for notify');\n }\n return sendNotify(\n this.config,\n {\n serverApiKey: this.config.serverApiKey,\n projectId: this.config.projectId,\n },\n event,\n data as Record<string, unknown> | undefined,\n options\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAkB;;;ACgNX,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACO,YACA,MACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AAAA,EALS;AAAA,EACA;AAKX;AAEO,IAAM,kBAAN,cAA8B,eAAe;AAAA,EAClD,YACE,SACO,OACP;AACA,UAAM,SAAS,KAAK,kBAAkB;AAF/B;AAGP,SAAK,OAAO;AAAA,EACd;AAAA,EAJS;AAKX;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;;;ADpOA,eAAsB,YACpB,MACA,UACA,UAAuB,CAAC,GACC;AACzB,QAAM,MAAM,GAAG,KAAK,OAAO,GAAG,QAAQ;AAEtC,QAAM,aAAa,IAAI,gBAAgB;AACvC,QAAM,YAAY,WAAW,MAAM,WAAW,MAAM,GAAG,KAAK,OAAO;AAEnE,MAAI;AACF,UAAM,gBAAwC;AAAA,MAC5C,gBAAgB;AAAA,MAChB,GAAI,QAAQ;AAAA,IACd;AAIA,QA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