(
endpoint: string,
data?: any,
options?: RequestOptions
)
| 183 | |
| 184 | // Streaming method for AI responses |
| 185 | async stream( |
| 186 | endpoint: string, |
| 187 | data?: any, |
| 188 | options?: RequestOptions |
| 189 | ): Promise<Response> { |
| 190 | const { skipAuth = false, headers = {}, _retryCount = 0, ...restOptions } = options || {}; |
| 191 | |
| 192 | const authHeaders = skipAuth ? {} : await this.getAuthHeaders(); |
| 193 | |
| 194 | const finalHeaders = { |
| 195 | 'Content-Type': 'application/json', |
| 196 | ...authHeaders, |
| 197 | ...headers, |
| 198 | }; |
| 199 | |
| 200 | const url = `${this.baseURL}${endpoint}`; |
| 201 | |
| 202 | // Log API call in development |
| 203 | logApiCall('POST', url, data); |
| 204 | |
| 205 | console.log(`[ApiClient] POST ${endpoint} (stream) - skipAuth: ${skipAuth}, retryCount: ${_retryCount}`); |
| 206 | |
| 207 | try { |
| 208 | const response = await fetch(url, { |
| 209 | ...restOptions, |
| 210 | method: 'POST', |
| 211 | headers: finalHeaders, |
| 212 | credentials: 'include', |
| 213 | body: data ? JSON.stringify(data) : undefined, |
| 214 | }); |
| 215 | |
| 216 | if (!response.ok) { |
| 217 | if (response.status === 401 && !skipAuth) { |
| 218 | |
| 219 | // Prevent infinite loops - only retry once |
| 220 | if (_retryCount >= 1) { |
| 221 | throw new Error('Session expired. Please log in again.'); |
| 222 | } |
| 223 | |
| 224 | try { |
| 225 | // Attempt to refresh the token |
| 226 | await this.refreshToken(); |
| 227 | |
| 228 | // Retry the stream request with incremented retry count |
| 229 | const retryOptions = { |
| 230 | ...options, |
| 231 | _retryCount: _retryCount + 1 |
| 232 | }; |
| 233 | return this.stream(endpoint, data, retryOptions); |
| 234 | } catch (refreshError) { |
| 235 | console.log('[ApiClient] Token refresh failed:', refreshError); |
| 236 | throw new Error('Session expired. Please log in again.'); |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | let errorMessage = `Request failed with status ${response.status}`; |
| 241 | try { |
| 242 | const errorData = await response.json(); |
no test coverage detected