@kivacore/api-client 0.0.0 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ import { type ApiClientConfig } from '../core/types';
2
+
3
+ import { BaseApiClient } from './base-client';
4
+
5
+ export class EdgeFunctionClient extends BaseApiClient {
6
+ constructor(config: ApiClientConfig = {}) {
7
+ if (!config.baseURL) {
8
+ throw new Error('EdgeFunctionClient requires a baseURL in the configuration');
9
+ }
10
+
11
+ super(config);
12
+ }
13
+ // Edge functions might have specific streaming capabilities
14
+ async* streamFunction(
15
+ functionName: string,
16
+ data?: unknown,
17
+ signal?: AbortSignal
18
+ ): AsyncGenerator<string, void, unknown> {
19
+ yield* this.stream(`/${functionName}`, {
20
+ method: 'POST',
21
+ body: data,
22
+ signal,
23
+ onMessage: () => {}
24
+ });
25
+ }
26
+ // Invoke edge function with typed response
27
+ async invokeFunction<T = unknown>(
28
+ functionName: string,
29
+ data?: unknown,
30
+ config?: ApiClientConfig
31
+ ): Promise<T> {
32
+ return this.post<T>(`/${functionName}`, data, config as any);
33
+ }
34
+ }
@@ -0,0 +1,58 @@
1
+ import { type ApiClientConfig, type Html2PdfOptions } from '../core/types';
2
+
3
+ import { BaseApiClient } from './base-client';
4
+ import { ApiError } from '../core/errors';
5
+
6
+ export class RestApiClient extends BaseApiClient {
7
+ constructor(config: ApiClientConfig = {}) {
8
+ if (!config.baseURL) {
9
+ throw new Error('RestApiClient requires a baseURL in the configuration');
10
+ }
11
+
12
+ super(config);
13
+ }
14
+ async html2pdf(options: Html2PdfOptions = {}): Promise<any> {
15
+ const token = await this.getAccessToken();
16
+
17
+ if (!token) {
18
+ throw new ApiError('No access token provided', 401, 'AUTH_REQUIRED');
19
+ }
20
+
21
+ const url = 'https://html2pdf.cf.docyrus.app/';
22
+
23
+ try {
24
+ const response = await this.fetchImpl(url, {
25
+ method: 'POST',
26
+ headers: {
27
+ 'Content-Type': 'application/json',
28
+ Authorization: `Bearer ${token}`
29
+ },
30
+ body: JSON.stringify(options)
31
+ });
32
+
33
+ if (!response.ok) {
34
+ let errorData: any = null;
35
+
36
+ try {
37
+ errorData = await response.json();
38
+ } catch {
39
+ // Ignore parse errors
40
+ }
41
+
42
+ throw this.createApiError(response, errorData);
43
+ }
44
+
45
+ return await response.json();
46
+ } catch (error) {
47
+ if (error instanceof ApiError) {
48
+ throw error;
49
+ }
50
+
51
+ throw new ApiError(
52
+ error instanceof Error ? error.message : 'PDF generation failed',
53
+ undefined,
54
+ 'PDF_GENERATION_ERROR'
55
+ );
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * CryptoProvider interface for abstracting platform-specific crypto operations.
3
+ * Enables PKCE and other crypto features to work across browsers, React Native, and Node.js.
4
+ */
5
+ export interface CryptoProvider {
6
+ /** Fill buffer with cryptographically random values */
7
+ getRandomValues(buffer: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer>;
8
+
9
+ /** Compute SHA-256 hash of the given data */
10
+ sha256(data: Uint8Array<ArrayBuffer>): Promise<ArrayBuffer>;
11
+
12
+ /** Base64 encode a binary string */
13
+ btoa(input: string): string;
14
+
15
+ /** Base64 decode to a binary string */
16
+ atob(input: string): string;
17
+ }
18
+
19
+ /**
20
+ * Default CryptoProvider that uses browser/global Web Crypto APIs.
21
+ * Works in browsers and Node.js 18+ (which provides globalThis.crypto).
22
+ */
23
+ export class BrowserCryptoProvider implements CryptoProvider {
24
+ getRandomValues(buffer: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {
25
+ if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
26
+ throw new Error('Web Crypto API (crypto.getRandomValues) not available');
27
+ }
28
+
29
+ return crypto.getRandomValues(buffer);
30
+ }
31
+ async sha256(data: Uint8Array<ArrayBuffer>): Promise<ArrayBuffer> {
32
+ if (typeof crypto === 'undefined' || !crypto.subtle?.digest) {
33
+ throw new Error('Web Crypto API (crypto.subtle.digest) not available');
34
+ }
35
+
36
+ return crypto.subtle.digest('SHA-256', data);
37
+ }
38
+ btoa(input: string): string {
39
+ if (typeof globalThis.btoa !== 'function') {
40
+ throw new Error('btoa() not available in this environment');
41
+ }
42
+
43
+ return globalThis.btoa(input);
44
+ }
45
+ atob(input: string): string {
46
+ if (typeof globalThis.atob !== 'function') {
47
+ throw new Error('atob() not available in this environment');
48
+ }
49
+
50
+ return globalThis.atob(input);
51
+ }
52
+ }
53
+
54
+ /** Shared default instance — lazily created on first use */
55
+ let defaultProvider: BrowserCryptoProvider | undefined;
56
+
57
+ export function getDefaultCryptoProvider(): CryptoProvider {
58
+ if (!defaultProvider) {
59
+ defaultProvider = new BrowserCryptoProvider();
60
+ }
61
+
62
+ return defaultProvider;
63
+ }
@@ -0,0 +1,183 @@
1
+ export class ApiError extends Error {
2
+ public readonly status?: number;
3
+ public readonly code?: string;
4
+ public readonly details?: Record<string, unknown>;
5
+ public readonly action?: string;
6
+ constructor(
7
+ message: string,
8
+ status?: number,
9
+ code?: string,
10
+ details?: Record<string, unknown>,
11
+ action?: string
12
+ ) {
13
+ super(message);
14
+ this.name = 'ApiError';
15
+ this.status = status;
16
+ this.code = code;
17
+ this.details = details;
18
+ this.action = action;
19
+
20
+ // Maintains proper stack trace for where our error was thrown (only available on V8)
21
+ if ((Error as any).captureStackTrace) {
22
+ (Error as any).captureStackTrace(this, ApiError);
23
+ }
24
+ }
25
+ toJSON() {
26
+ return {
27
+ name: this.name,
28
+ message: this.message,
29
+ status: this.status,
30
+ code: this.code,
31
+ details: this.details,
32
+ action: this.action
33
+ };
34
+ }
35
+ }
36
+
37
+ export class NetworkError extends ApiError {
38
+ constructor(message: string, details?: Record<string, unknown>) {
39
+ super(message, undefined, 'NETWORK_ERROR', details);
40
+ this.name = 'NetworkError';
41
+ }
42
+ }
43
+
44
+ export class TimeoutError extends ApiError {
45
+ constructor(message: string, timeout: number) {
46
+ super(message, undefined, 'TIMEOUT_ERROR', { timeout });
47
+ this.name = 'TimeoutError';
48
+ }
49
+ }
50
+
51
+ export class AbortError extends ApiError {
52
+ constructor(message = 'Request was aborted') {
53
+ super(message, undefined, 'ABORT_ERROR');
54
+ this.name = 'AbortError';
55
+ }
56
+ }
57
+
58
+ export class ValidationError extends ApiError {
59
+ constructor(message: string, details?: Record<string, unknown>) {
60
+ super(message, 400, 'VALIDATION_ERROR', details);
61
+ this.name = 'ValidationError';
62
+ }
63
+ }
64
+
65
+ export class AuthenticationError extends ApiError {
66
+ constructor(message = 'Authentication required') {
67
+ super(message, 401, 'AUTH_ERROR');
68
+ this.name = 'AuthenticationError';
69
+ }
70
+ }
71
+
72
+ export class AuthorizationError extends ApiError {
73
+ constructor(message = 'Insufficient permissions') {
74
+ super(message, 403, 'FORBIDDEN');
75
+ this.name = 'AuthorizationError';
76
+ }
77
+ }
78
+
79
+ export class NotFoundError extends ApiError {
80
+ constructor(resource: string) {
81
+ super(`Resource not found: ${resource}`, 404, 'NOT_FOUND', { resource });
82
+ this.name = 'NotFoundError';
83
+ }
84
+ }
85
+
86
+ export class ConflictError extends ApiError {
87
+ constructor(message: string, details?: Record<string, unknown>) {
88
+ super(message, 409, 'CONFLICT', details);
89
+ this.name = 'ConflictError';
90
+ }
91
+ }
92
+
93
+ export class RateLimitError extends ApiError {
94
+ constructor(retryAfter?: number) {
95
+ super('Rate limit exceeded', 429, 'RATE_LIMIT', { retryAfter });
96
+ this.name = 'RateLimitError';
97
+ }
98
+ }
99
+
100
+ export class ServerError extends ApiError {
101
+ constructor(message = 'Internal server error', status = 500, details?: Record<string, unknown>) {
102
+ super(message, status, 'SERVER_ERROR', details);
103
+ this.name = 'ServerError';
104
+ }
105
+ }
106
+
107
+ // Legacy GenericError for backwards compatibility
108
+ export class GenericError extends ApiError {
109
+ public readonly payload: Record<string, unknown>;
110
+ constructor(error: Error, action?: string, payload?: Record<string, unknown>) {
111
+ super(error.message, undefined, undefined, payload, action);
112
+ this.name = 'GenericError';
113
+ this.payload = payload || {};
114
+ }
115
+ }
116
+
117
+ // ===== OAuth2 Error Classes =====
118
+
119
+ export class OAuth2Error extends ApiError {
120
+ public readonly errorCode: string;
121
+ public readonly errorDescription?: string;
122
+ public readonly errorUri?: string;
123
+ constructor(
124
+ errorCode: string,
125
+ errorDescription?: string,
126
+ errorUri?: string
127
+ ) {
128
+ super(errorDescription || errorCode, undefined, errorCode);
129
+ this.name = 'OAuth2Error';
130
+ this.errorCode = errorCode;
131
+ this.errorDescription = errorDescription;
132
+ this.errorUri = errorUri;
133
+ }
134
+ }
135
+
136
+ export class InvalidGrantError extends OAuth2Error {
137
+ constructor(description?: string) {
138
+ super('invalid_grant', description || 'The authorization code or refresh token is invalid or expired');
139
+ this.name = 'InvalidGrantError';
140
+ }
141
+ }
142
+
143
+ export class InvalidClientError extends OAuth2Error {
144
+ constructor(description?: string) {
145
+ super('invalid_client', description || 'Client authentication failed');
146
+ this.name = 'InvalidClientError';
147
+ }
148
+ }
149
+
150
+ export class InvalidScopeError extends OAuth2Error {
151
+ constructor(description?: string) {
152
+ super('invalid_scope', description || 'The requested scope is invalid or unknown');
153
+ this.name = 'InvalidScopeError';
154
+ }
155
+ }
156
+
157
+ export class AuthorizationPendingError extends OAuth2Error {
158
+ constructor() {
159
+ super('authorization_pending', 'The user has not yet completed the authorization');
160
+ this.name = 'AuthorizationPendingError';
161
+ }
162
+ }
163
+
164
+ export class SlowDownError extends OAuth2Error {
165
+ constructor() {
166
+ super('slow_down', 'Polling too frequently, please slow down');
167
+ this.name = 'SlowDownError';
168
+ }
169
+ }
170
+
171
+ export class ExpiredTokenError extends OAuth2Error {
172
+ constructor() {
173
+ super('expired_token', 'The device code or user code has expired');
174
+ this.name = 'ExpiredTokenError';
175
+ }
176
+ }
177
+
178
+ export class AccessDeniedError extends OAuth2Error {
179
+ constructor(description?: string) {
180
+ super('access_denied', description || 'The user denied the authorization request');
181
+ this.name = 'AccessDeniedError';
182
+ }
183
+ }
@@ -0,0 +1,59 @@
1
+ import { type TokenManager } from './types';
2
+
3
+ export class MemoryTokenManager implements TokenManager {
4
+ private token: string | null = null;
5
+ getToken(): string | null {
6
+ return this.token;
7
+ }
8
+ setToken(token: string): void {
9
+ this.token = token;
10
+ }
11
+ clearToken(): void {
12
+ this.token = null;
13
+ }
14
+ }
15
+
16
+ export class StorageTokenManager implements TokenManager {
17
+ constructor(
18
+ private storage: Storage = typeof window !== 'undefined' ? window.localStorage : (null as unknown as Storage),
19
+ private key: string = 'api_token'
20
+ ) {}
21
+ getToken(): string | null {
22
+ if (!this.storage) return null;
23
+
24
+ return this.storage.getItem(this.key);
25
+ }
26
+ setToken(token: string): void {
27
+ if (!this.storage) return;
28
+ this.storage.setItem(this.key, token);
29
+ }
30
+ clearToken(): void {
31
+ if (!this.storage) return;
32
+ this.storage.removeItem(this.key);
33
+ }
34
+ }
35
+
36
+ export class AsyncTokenManager implements TokenManager {
37
+ constructor(
38
+ private getTokenFn: () => Promise<string | null>,
39
+ private setTokenFn: (token: string) => Promise<void>,
40
+ private clearTokenFn: () => Promise<void>,
41
+ private refreshTokenFn?: () => Promise<string>
42
+ ) {}
43
+ getToken(): Promise<string | null> {
44
+ return this.getTokenFn();
45
+ }
46
+ setToken(token: string): Promise<void> {
47
+ return this.setTokenFn(token);
48
+ }
49
+ clearToken(): Promise<void> {
50
+ return this.clearTokenFn();
51
+ }
52
+ refreshToken(): Promise<string> {
53
+ if (!this.refreshTokenFn) {
54
+ return Promise.reject(new Error('Token refresh not supported'));
55
+ }
56
+
57
+ return this.refreshTokenFn();
58
+ }
59
+ }
@@ -0,0 +1,96 @@
1
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
2
+
3
+ export type ApiBackend = 'api' | 'edge' | 'cf';
4
+
5
+ export type QueryParamPrimitive = string | number | boolean | null | undefined;
6
+ export type QueryParamValue = QueryParamPrimitive | QueryParamPrimitive[];
7
+
8
+ export interface RequestConfig extends Omit<RequestInit, 'method' | 'body'> {
9
+ params?: Record<string, QueryParamValue>;
10
+ responseType?: 'json' | 'blob' | 'text' | 'arrayBuffer' | 'formData';
11
+ timeout?: number;
12
+ retries?: number;
13
+ retryDelay?: number;
14
+ retryCondition?: (error: Error, attempt: number) => boolean;
15
+ }
16
+
17
+ export interface ApiResponse<T = unknown> {
18
+ data: T;
19
+ headers: Headers;
20
+ status: number;
21
+ statusText: string;
22
+ }
23
+
24
+ export interface ApiClientConfig {
25
+ baseURL?: string;
26
+ backend?: ApiBackend;
27
+ timeout?: number;
28
+ headers?: Record<string, string>;
29
+ tokenManager?: TokenManager;
30
+ storage?: Storage;
31
+ fetch?: typeof fetch;
32
+ FormData?: typeof FormData;
33
+ AbortController?: typeof AbortController;
34
+ /** Custom download handler for non-browser environments (e.g., React Native) */
35
+ downloadHandler?: (blob: Blob, filename: string) => Promise<void> | void;
36
+ }
37
+
38
+ export interface TokenManager {
39
+ getToken(): Promise<string | null> | string | null;
40
+ setToken(token: string): Promise<void> | void;
41
+ clearToken(): Promise<void> | void;
42
+ refreshToken?(): Promise<string>;
43
+ }
44
+
45
+ export interface Interceptor {
46
+ request?: (config: RequestConfig) => RequestConfig | Promise<RequestConfig>;
47
+ response?: <T>(response: ApiResponse<T>) => ApiResponse<T> | Promise<ApiResponse<T>>;
48
+ error?: (error: Error) => Error | Promise<Error> | never;
49
+ }
50
+
51
+ export interface SSEOptions {
52
+ onMessage: (data: unknown) => void;
53
+ onError?: (error: Error) => void;
54
+ onComplete?: () => void;
55
+ signal?: AbortSignal;
56
+ headers?: Record<string, string>;
57
+ }
58
+
59
+ export interface StreamOptions extends SSEOptions {
60
+ method?: 'GET' | 'POST';
61
+ body?: unknown;
62
+ }
63
+
64
+ // Html2Pdf options
65
+ export interface Html2PdfMargin {
66
+ top?: number;
67
+ right?: number;
68
+ bottom?: number;
69
+ left?: number;
70
+ }
71
+
72
+ export interface Html2PdfOptions {
73
+ body?: string;
74
+ headerTemplate?: string;
75
+ footerTemplate?: string;
76
+ format?: string;
77
+ landscape?: boolean;
78
+ margin?: Html2PdfMargin;
79
+ filename?: string;
80
+ bucket?: string;
81
+ style?: string;
82
+ [key: string]: unknown;
83
+ }
84
+
85
+ // Filter query types
86
+ export type SimpleRule = { field: string; operator: string; value: unknown };
87
+ export type GroupRule = { rules: FilterRule[]; condition?: 'and' | 'or' };
88
+ export type FilterRule = SimpleRule | GroupRule | FilterQuery;
89
+ export type FilterQuery = { rules?: FilterRule[]; condition?: 'and' | 'or' };
90
+
91
+ // Environment configuration
92
+ export interface EnvironmentConfig {
93
+ apiURL?: string;
94
+ edgeURL?: string;
95
+ cfURL?: string;
96
+ }
@@ -0,0 +1,138 @@
1
+ import { type FilterQuery, type QueryParamValue } from './types';
2
+
3
+ export function jsonToQueryString(data: Record<string, QueryParamValue> | null | undefined): string {
4
+ if (!data || Object.keys(data).length === 0) {
5
+ return '';
6
+ }
7
+
8
+ const params = new URLSearchParams();
9
+
10
+ Object.entries(data).forEach(([key, value]) => {
11
+ if (value === undefined) return;
12
+
13
+ if (value !== null && (typeof value === 'object' || Array.isArray(value))) {
14
+ params.append(key, JSON.stringify(value));
15
+ } else {
16
+ params.append(key, String(value));
17
+ }
18
+ });
19
+
20
+ const queryString = params.toString();
21
+
22
+ return queryString ? `?${queryString}` : '';
23
+ }
24
+
25
+ export async function withRetry<T>(
26
+ fn: () => Promise<T>,
27
+ retries = 3,
28
+ retryDelay = 1000,
29
+ retryCondition?: (error: Error, attempt: number) => boolean
30
+ ): Promise<T> {
31
+ let lastError: Error = new Error('All retry attempts failed');
32
+
33
+ for (let attempt = 0; attempt <= retries; attempt++) {
34
+ try {
35
+ return await fn();
36
+ } catch (error) {
37
+ lastError = error as Error;
38
+
39
+ if (attempt === retries) {
40
+ throw lastError;
41
+ }
42
+
43
+ if (retryCondition && !retryCondition(lastError, attempt)) {
44
+ throw lastError;
45
+ }
46
+
47
+ // Default retry condition: retry on network errors and 5xx status codes
48
+ if (!retryCondition) {
49
+ const isRetryable
50
+ = lastError.name === 'NetworkError'
51
+ || lastError.name === 'TimeoutError'
52
+ || (lastError.name === 'ApiError'
53
+ && 'status' in lastError
54
+ && typeof lastError.status === 'number'
55
+ && lastError.status >= 500);
56
+
57
+ if (!isRetryable) {
58
+ throw lastError;
59
+ }
60
+ }
61
+
62
+ // Exponential backoff
63
+ const delay = retryDelay * Math.pow(2, attempt);
64
+
65
+ await new Promise(resolve => setTimeout(resolve, delay));
66
+ }
67
+ }
68
+
69
+ throw lastError;
70
+ }
71
+
72
+ export function isAbortError(error: unknown): boolean {
73
+ return error instanceof Error
74
+ && (error.name === 'AbortError' || error.message === 'The user aborted a request.');
75
+ }
76
+
77
+ export function parseContentDisposition(header: string | null): string | null {
78
+ if (!header) return null;
79
+
80
+ const filenameMatch = header.match(/filename\*?=["']?(?:UTF-\d['"]*)?([^;"'\n]*)["']?/i);
81
+
82
+ return filenameMatch?.[1] || null;
83
+ }
84
+
85
+ export function buildUrl(baseURL: string, path: string, params?: Record<string, QueryParamValue>): string {
86
+ // Remove trailing slash from baseURL and leading slash from path
87
+ const cleanBase = baseURL.replace(/\/$/, '');
88
+ const cleanPath = path.replace(/^\//, '');
89
+
90
+ let url = `${cleanBase}/${cleanPath}`;
91
+
92
+ if (params) {
93
+ url += jsonToQueryString(params);
94
+ }
95
+
96
+ return url;
97
+ }
98
+
99
+ export function isFormData(data: unknown): data is FormData {
100
+ return typeof FormData !== 'undefined' && data instanceof FormData;
101
+ }
102
+
103
+ export function isBlob(data: unknown): data is Blob {
104
+ return typeof Blob !== 'undefined' && data instanceof Blob;
105
+ }
106
+
107
+ export function isStream(data: unknown): data is ReadableStream {
108
+ return typeof ReadableStream !== 'undefined' && data instanceof ReadableStream;
109
+ }
110
+
111
+ export function prepareFilterQueryForApi(query: FilterQuery): string {
112
+ return JSON.stringify(query);
113
+ }
114
+
115
+ export function createAbortSignal(timeout?: number, signal?: AbortSignal): {
116
+ signal: AbortSignal;
117
+ cleanup: () => void;
118
+ } {
119
+ const controller = new AbortController();
120
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
121
+
122
+ if (timeout) {
123
+ timeoutId = setTimeout(() => controller.abort(), timeout);
124
+ }
125
+
126
+ if (signal) {
127
+ signal.addEventListener('abort', () => controller.abort());
128
+ }
129
+
130
+ return {
131
+ signal: controller.signal,
132
+ cleanup: () => {
133
+ if (timeoutId) {
134
+ clearTimeout(timeoutId);
135
+ }
136
+ }
137
+ };
138
+ }