@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,1534 @@
1
+ // src/react-native/rn-crypto.ts
2
+ var BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3
+ function uint8ToBase64(bytes) {
4
+ let result = "";
5
+ const len = bytes.length;
6
+ for (let i = 0; i < len; i += 3) {
7
+ const b0 = bytes[i];
8
+ const b1 = i + 1 < len ? bytes[i + 1] : 0;
9
+ const b2 = i + 2 < len ? bytes[i + 2] : 0;
10
+ result += BASE64_CHARS[b0 >> 2 & 63];
11
+ result += BASE64_CHARS[(b0 << 4 | b1 >> 4) & 63];
12
+ result += i + 1 < len ? BASE64_CHARS[(b1 << 2 | b2 >> 6) & 63] : "=";
13
+ result += i + 2 < len ? BASE64_CHARS[b2 & 63] : "=";
14
+ }
15
+ return result;
16
+ }
17
+ function base64ToUint8(base64) {
18
+ const lookup = new Uint8Array(128);
19
+ for (let i = 0; i < BASE64_CHARS.length; i++) {
20
+ lookup[BASE64_CHARS.charCodeAt(i)] = i;
21
+ }
22
+ let len = base64.length;
23
+ while (len > 0 && base64[len - 1] === "=") len--;
24
+ const bytes = new Uint8Array(Math.floor(len * 3 / 4));
25
+ let j = 0;
26
+ for (let i = 0; i < len; i += 4) {
27
+ const b0 = lookup[base64.charCodeAt(i)];
28
+ const b1 = i + 1 < len ? lookup[base64.charCodeAt(i + 1)] : 0;
29
+ const b2 = i + 2 < len ? lookup[base64.charCodeAt(i + 2)] : 0;
30
+ const b3 = i + 3 < len ? lookup[base64.charCodeAt(i + 3)] : 0;
31
+ bytes[j++] = b0 << 2 | b1 >> 4;
32
+ if (i + 2 < len) bytes[j++] = (b1 << 4 | b2 >> 2) & 255;
33
+ if (i + 3 < len) bytes[j++] = (b2 << 6 | b3) & 255;
34
+ }
35
+ return bytes;
36
+ }
37
+ var ReactNativeCryptoProvider = class {
38
+ expoCrypto;
39
+ constructor(expoCrypto) {
40
+ this.expoCrypto = expoCrypto;
41
+ }
42
+ getRandomValues(buffer) {
43
+ const random = this.expoCrypto.getRandomBytes(buffer.length);
44
+ buffer.set(random);
45
+ return buffer;
46
+ }
47
+ async sha256(data) {
48
+ return this.expoCrypto.digest("SHA-256", data);
49
+ }
50
+ btoa(input) {
51
+ const bytes = new Uint8Array(input.length);
52
+ for (let i = 0; i < input.length; i++) {
53
+ bytes[i] = input.charCodeAt(i);
54
+ }
55
+ return uint8ToBase64(bytes);
56
+ }
57
+ atob(input) {
58
+ const bytes = base64ToUint8(input);
59
+ let result = "";
60
+ for (let i = 0; i < bytes.length; i++) {
61
+ result += String.fromCharCode(bytes[i]);
62
+ }
63
+ return result;
64
+ }
65
+ };
66
+
67
+ // src/react-native/rn-helpers.ts
68
+ function createTokenStorage(adapter, prefix = "docyrus_oauth2") {
69
+ const tokensKey = `${prefix}_tokens`;
70
+ const pkceKey = `${prefix}_pkce`;
71
+ return {
72
+ async getTokens() {
73
+ const raw = await adapter.getItem(tokensKey);
74
+ if (!raw) return null;
75
+ try {
76
+ return JSON.parse(raw);
77
+ } catch {
78
+ return null;
79
+ }
80
+ },
81
+ async setTokens(tokens) {
82
+ await adapter.setItem(tokensKey, JSON.stringify(tokens));
83
+ },
84
+ async clearTokens() {
85
+ await adapter.removeItem(tokensKey);
86
+ },
87
+ async getPKCEState() {
88
+ const raw = await adapter.getItem(pkceKey);
89
+ if (!raw) return null;
90
+ try {
91
+ return JSON.parse(raw);
92
+ } catch {
93
+ return null;
94
+ }
95
+ },
96
+ async setPKCEState(state) {
97
+ await adapter.setItem(pkceKey, JSON.stringify(state));
98
+ },
99
+ async clearPKCEState() {
100
+ await adapter.removeItem(pkceKey);
101
+ }
102
+ };
103
+ }
104
+
105
+ // src/core/errors.ts
106
+ var ApiError = class _ApiError extends Error {
107
+ status;
108
+ code;
109
+ details;
110
+ action;
111
+ constructor(message, status, code, details, action) {
112
+ super(message);
113
+ this.name = "ApiError";
114
+ this.status = status;
115
+ this.code = code;
116
+ this.details = details;
117
+ this.action = action;
118
+ if (Error.captureStackTrace) {
119
+ Error.captureStackTrace(this, _ApiError);
120
+ }
121
+ }
122
+ toJSON() {
123
+ return {
124
+ name: this.name,
125
+ message: this.message,
126
+ status: this.status,
127
+ code: this.code,
128
+ details: this.details,
129
+ action: this.action
130
+ };
131
+ }
132
+ };
133
+ var NetworkError = class extends ApiError {
134
+ constructor(message, details) {
135
+ super(message, void 0, "NETWORK_ERROR", details);
136
+ this.name = "NetworkError";
137
+ }
138
+ };
139
+ var TimeoutError = class extends ApiError {
140
+ constructor(message, timeout) {
141
+ super(message, void 0, "TIMEOUT_ERROR", { timeout });
142
+ this.name = "TimeoutError";
143
+ }
144
+ };
145
+ var AbortError = class extends ApiError {
146
+ constructor(message = "Request was aborted") {
147
+ super(message, void 0, "ABORT_ERROR");
148
+ this.name = "AbortError";
149
+ }
150
+ };
151
+ var ValidationError = class extends ApiError {
152
+ constructor(message, details) {
153
+ super(message, 400, "VALIDATION_ERROR", details);
154
+ this.name = "ValidationError";
155
+ }
156
+ };
157
+ var AuthenticationError = class extends ApiError {
158
+ constructor(message = "Authentication required") {
159
+ super(message, 401, "AUTH_ERROR");
160
+ this.name = "AuthenticationError";
161
+ }
162
+ };
163
+ var AuthorizationError = class extends ApiError {
164
+ constructor(message = "Insufficient permissions") {
165
+ super(message, 403, "FORBIDDEN");
166
+ this.name = "AuthorizationError";
167
+ }
168
+ };
169
+ var NotFoundError = class extends ApiError {
170
+ constructor(resource) {
171
+ super(`Resource not found: ${resource}`, 404, "NOT_FOUND", { resource });
172
+ this.name = "NotFoundError";
173
+ }
174
+ };
175
+ var ConflictError = class extends ApiError {
176
+ constructor(message, details) {
177
+ super(message, 409, "CONFLICT", details);
178
+ this.name = "ConflictError";
179
+ }
180
+ };
181
+ var RateLimitError = class extends ApiError {
182
+ constructor(retryAfter) {
183
+ super("Rate limit exceeded", 429, "RATE_LIMIT", { retryAfter });
184
+ this.name = "RateLimitError";
185
+ }
186
+ };
187
+ var ServerError = class extends ApiError {
188
+ constructor(message = "Internal server error", status = 500, details) {
189
+ super(message, status, "SERVER_ERROR", details);
190
+ this.name = "ServerError";
191
+ }
192
+ };
193
+ var GenericError = class extends ApiError {
194
+ payload;
195
+ constructor(error, action, payload) {
196
+ super(error.message, void 0, void 0, payload, action);
197
+ this.name = "GenericError";
198
+ this.payload = payload || {};
199
+ }
200
+ };
201
+ var OAuth2Error = class extends ApiError {
202
+ errorCode;
203
+ errorDescription;
204
+ errorUri;
205
+ constructor(errorCode, errorDescription, errorUri) {
206
+ super(errorDescription || errorCode, void 0, errorCode);
207
+ this.name = "OAuth2Error";
208
+ this.errorCode = errorCode;
209
+ this.errorDescription = errorDescription;
210
+ this.errorUri = errorUri;
211
+ }
212
+ };
213
+ var InvalidGrantError = class extends OAuth2Error {
214
+ constructor(description) {
215
+ super("invalid_grant", description || "The authorization code or refresh token is invalid or expired");
216
+ this.name = "InvalidGrantError";
217
+ }
218
+ };
219
+ var InvalidClientError = class extends OAuth2Error {
220
+ constructor(description) {
221
+ super("invalid_client", description || "Client authentication failed");
222
+ this.name = "InvalidClientError";
223
+ }
224
+ };
225
+ var InvalidScopeError = class extends OAuth2Error {
226
+ constructor(description) {
227
+ super("invalid_scope", description || "The requested scope is invalid or unknown");
228
+ this.name = "InvalidScopeError";
229
+ }
230
+ };
231
+ var AuthorizationPendingError = class extends OAuth2Error {
232
+ constructor() {
233
+ super("authorization_pending", "The user has not yet completed the authorization");
234
+ this.name = "AuthorizationPendingError";
235
+ }
236
+ };
237
+ var SlowDownError = class extends OAuth2Error {
238
+ constructor() {
239
+ super("slow_down", "Polling too frequently, please slow down");
240
+ this.name = "SlowDownError";
241
+ }
242
+ };
243
+ var ExpiredTokenError = class extends OAuth2Error {
244
+ constructor() {
245
+ super("expired_token", "The device code or user code has expired");
246
+ this.name = "ExpiredTokenError";
247
+ }
248
+ };
249
+ var AccessDeniedError = class extends OAuth2Error {
250
+ constructor(description) {
251
+ super("access_denied", description || "The user denied the authorization request");
252
+ this.name = "AccessDeniedError";
253
+ }
254
+ };
255
+
256
+ // src/core/utils.ts
257
+ function jsonToQueryString(data) {
258
+ if (!data || Object.keys(data).length === 0) {
259
+ return "";
260
+ }
261
+ const params = new URLSearchParams();
262
+ Object.entries(data).forEach(([key, value]) => {
263
+ if (value === void 0) return;
264
+ if (value !== null && (typeof value === "object" || Array.isArray(value))) {
265
+ params.append(key, JSON.stringify(value));
266
+ } else {
267
+ params.append(key, String(value));
268
+ }
269
+ });
270
+ const queryString = params.toString();
271
+ return queryString ? `?${queryString}` : "";
272
+ }
273
+ async function withRetry(fn, retries = 3, retryDelay = 1e3, retryCondition) {
274
+ let lastError = new Error("All retry attempts failed");
275
+ for (let attempt = 0; attempt <= retries; attempt++) {
276
+ try {
277
+ return await fn();
278
+ } catch (error) {
279
+ lastError = error;
280
+ if (attempt === retries) {
281
+ throw lastError;
282
+ }
283
+ if (retryCondition && !retryCondition(lastError, attempt)) {
284
+ throw lastError;
285
+ }
286
+ if (!retryCondition) {
287
+ const isRetryable = lastError.name === "NetworkError" || lastError.name === "TimeoutError" || lastError.name === "ApiError" && "status" in lastError && typeof lastError.status === "number" && lastError.status >= 500;
288
+ if (!isRetryable) {
289
+ throw lastError;
290
+ }
291
+ }
292
+ const delay = retryDelay * Math.pow(2, attempt);
293
+ await new Promise((resolve) => setTimeout(resolve, delay));
294
+ }
295
+ }
296
+ throw lastError;
297
+ }
298
+ function isAbortError(error) {
299
+ return error instanceof Error && (error.name === "AbortError" || error.message === "The user aborted a request.");
300
+ }
301
+ function parseContentDisposition(header) {
302
+ if (!header) return null;
303
+ const filenameMatch = header.match(/filename\*?=["']?(?:UTF-\d['"]*)?([^;"'\n]*)["']?/i);
304
+ return filenameMatch?.[1] || null;
305
+ }
306
+ function buildUrl(baseURL, path, params) {
307
+ const cleanBase = baseURL.replace(/\/$/, "");
308
+ const cleanPath = path.replace(/^\//, "");
309
+ let url = `${cleanBase}/${cleanPath}`;
310
+ if (params) {
311
+ url += jsonToQueryString(params);
312
+ }
313
+ return url;
314
+ }
315
+ function isFormData(data) {
316
+ return typeof FormData !== "undefined" && data instanceof FormData;
317
+ }
318
+ function isBlob(data) {
319
+ return typeof Blob !== "undefined" && data instanceof Blob;
320
+ }
321
+ function isStream(data) {
322
+ return typeof ReadableStream !== "undefined" && data instanceof ReadableStream;
323
+ }
324
+ function prepareFilterQueryForApi(query) {
325
+ return JSON.stringify(query);
326
+ }
327
+ function createAbortSignal(timeout, signal) {
328
+ const controller = new AbortController();
329
+ let timeoutId = null;
330
+ if (timeout) {
331
+ timeoutId = setTimeout(() => controller.abort(), timeout);
332
+ }
333
+ if (signal) {
334
+ signal.addEventListener("abort", () => controller.abort());
335
+ }
336
+ return {
337
+ signal: controller.signal,
338
+ cleanup: () => {
339
+ if (timeoutId) {
340
+ clearTimeout(timeoutId);
341
+ }
342
+ }
343
+ };
344
+ }
345
+
346
+ // src/core/token-manager.ts
347
+ var MemoryTokenManager = class {
348
+ token = null;
349
+ getToken() {
350
+ return this.token;
351
+ }
352
+ setToken(token) {
353
+ this.token = token;
354
+ }
355
+ clearToken() {
356
+ this.token = null;
357
+ }
358
+ };
359
+ var AsyncTokenManager = class {
360
+ constructor(getTokenFn, setTokenFn, clearTokenFn, refreshTokenFn) {
361
+ this.getTokenFn = getTokenFn;
362
+ this.setTokenFn = setTokenFn;
363
+ this.clearTokenFn = clearTokenFn;
364
+ this.refreshTokenFn = refreshTokenFn;
365
+ }
366
+ getTokenFn;
367
+ setTokenFn;
368
+ clearTokenFn;
369
+ refreshTokenFn;
370
+ getToken() {
371
+ return this.getTokenFn();
372
+ }
373
+ setToken(token) {
374
+ return this.setTokenFn(token);
375
+ }
376
+ clearToken() {
377
+ return this.clearTokenFn();
378
+ }
379
+ refreshToken() {
380
+ if (!this.refreshTokenFn) {
381
+ return Promise.reject(new Error("Token refresh not supported"));
382
+ }
383
+ return this.refreshTokenFn();
384
+ }
385
+ };
386
+
387
+ // src/clients/base-client.ts
388
+ var BaseApiClient = class {
389
+ baseURL;
390
+ tokenManager;
391
+ interceptors = [];
392
+ defaultHeaders = {};
393
+ fetchImpl;
394
+ FormDataImpl;
395
+ AbortControllerImpl;
396
+ storage;
397
+ defaultTimeout;
398
+ downloadHandler;
399
+ constructor(config = {}) {
400
+ this.baseURL = config.baseURL || "";
401
+ this.tokenManager = config.tokenManager || new MemoryTokenManager();
402
+ this.defaultHeaders = config.headers || {};
403
+ this.defaultTimeout = config.timeout;
404
+ this.downloadHandler = config.downloadHandler;
405
+ const rawFetch = config.fetch || globalThis.fetch;
406
+ if (!rawFetch) {
407
+ throw new Error("Fetch API is not available. Please provide a fetch implementation.");
408
+ }
409
+ this.fetchImpl = rawFetch.bind(globalThis);
410
+ this.FormDataImpl = config.FormData || globalThis.FormData;
411
+ this.AbortControllerImpl = config.AbortController || globalThis.AbortController;
412
+ this.storage = config.storage;
413
+ if (!this.fetchImpl) {
414
+ throw new Error("Fetch API is not available. Please provide a fetch implementation.");
415
+ }
416
+ }
417
+ addInterceptor(interceptor) {
418
+ this.interceptors.push(interceptor);
419
+ }
420
+ removeInterceptor(interceptor) {
421
+ const index = this.interceptors.indexOf(interceptor);
422
+ if (index !== -1) {
423
+ this.interceptors.splice(index, 1);
424
+ }
425
+ }
426
+ async setAccessToken(token) {
427
+ const result = this.tokenManager.setToken(token);
428
+ if (result instanceof Promise) {
429
+ await result;
430
+ }
431
+ }
432
+ async getAccessToken() {
433
+ const result = this.tokenManager.getToken();
434
+ return result instanceof Promise ? await result : result;
435
+ }
436
+ async clearAccessToken() {
437
+ const result = this.tokenManager.clearToken();
438
+ if (result instanceof Promise) {
439
+ await result;
440
+ }
441
+ }
442
+ async applyRequestInterceptors(config) {
443
+ let currentConfig = config;
444
+ for (const interceptor of this.interceptors) {
445
+ if (interceptor.request) {
446
+ currentConfig = await interceptor.request(currentConfig);
447
+ }
448
+ }
449
+ return currentConfig;
450
+ }
451
+ async applyResponseInterceptors(response) {
452
+ let currentResponse = response;
453
+ for (const interceptor of this.interceptors) {
454
+ if (interceptor.response) {
455
+ currentResponse = await interceptor.response(currentResponse);
456
+ }
457
+ }
458
+ return currentResponse;
459
+ }
460
+ async applyErrorInterceptors(error) {
461
+ let currentError = error;
462
+ for (const interceptor of this.interceptors) {
463
+ if (interceptor.error) {
464
+ try {
465
+ const result = await interceptor.error(currentError);
466
+ if (result instanceof Error) {
467
+ currentError = result;
468
+ }
469
+ } catch (e) {
470
+ currentError = e;
471
+ }
472
+ }
473
+ }
474
+ throw currentError;
475
+ }
476
+ async prepareHeaders(config) {
477
+ const headers = new Headers(this.defaultHeaders);
478
+ const token = await this.getAccessToken();
479
+ if (token) {
480
+ headers.set("Authorization", `Bearer ${token}`);
481
+ }
482
+ if (config.headers) {
483
+ const configHeaders = config.headers instanceof Headers ? config.headers : new Headers(config.headers);
484
+ configHeaders.forEach((value, key) => {
485
+ headers.set(key, value);
486
+ });
487
+ }
488
+ if (this.storage && typeof globalThis.sessionStorage !== "undefined") {
489
+ try {
490
+ const tid = globalThis.sessionStorage.getItem("tid");
491
+ if (tid) {
492
+ headers.set("X-Tid", tid);
493
+ }
494
+ } catch {
495
+ }
496
+ }
497
+ return headers;
498
+ }
499
+ prepareBody(data, headers) {
500
+ if (!data) return void 0;
501
+ if (isFormData(data) || isBlob(data) || isStream(data)) {
502
+ return data;
503
+ }
504
+ if (typeof data === "string") {
505
+ headers.set("Content-Type", "text/plain");
506
+ return data;
507
+ }
508
+ headers.set("Content-Type", "application/json");
509
+ return JSON.stringify(data);
510
+ }
511
+ createApiError(response, errorData) {
512
+ const { status } = response;
513
+ let message = errorData?.message || errorData?.error || response.statusText;
514
+ const details = errorData?.details || errorData;
515
+ if (errorData && typeof errorData === "object") {
516
+ if (errorData.error && typeof errorData.error === "object") {
517
+ message = errorData.error.message || JSON.stringify(errorData.error);
518
+ } else if (errorData.message) {
519
+ ({ message } = errorData);
520
+ }
521
+ }
522
+ switch (status) {
523
+ case 400:
524
+ return new ValidationError(message, details);
525
+ case 401:
526
+ return new AuthenticationError(message);
527
+ case 403:
528
+ return new AuthorizationError(message);
529
+ case 404:
530
+ return new NotFoundError(response.url);
531
+ case 409:
532
+ return new ConflictError(message, details);
533
+ case 429:
534
+ return new RateLimitError(details?.retryAfter);
535
+ default:
536
+ if (status >= 500) {
537
+ return new ServerError(message, status, details);
538
+ }
539
+ return new ApiError(message, status, void 0, details);
540
+ }
541
+ }
542
+ async request(method, endpoint, data, config = {}) {
543
+ config = await this.applyRequestInterceptors(config);
544
+ const url = buildUrl(this.baseURL, endpoint, config.params);
545
+ const headers = await this.prepareHeaders(config);
546
+ const body = ["GET", "HEAD"].includes(method) ? void 0 : this.prepareBody(data, headers);
547
+ const { signal, cleanup } = createAbortSignal(
548
+ config.timeout || this.defaultTimeout,
549
+ config.signal || void 0
550
+ );
551
+ const fetchOptions = {
552
+ ...config,
553
+ method,
554
+ headers,
555
+ body,
556
+ signal
557
+ };
558
+ const executeRequest = async () => {
559
+ const response = await this.fetchImpl(url, fetchOptions);
560
+ if (!response.ok) {
561
+ let errorData;
562
+ try {
563
+ const contentType = response.headers.get("Content-Type") || "";
564
+ if (contentType.includes("application/json")) {
565
+ errorData = await response.json();
566
+ } else {
567
+ errorData = await response.text();
568
+ }
569
+ } catch {
570
+ }
571
+ throw this.createApiError(response, errorData);
572
+ }
573
+ const responseType = config.responseType || "json";
574
+ let responseData;
575
+ switch (responseType) {
576
+ case "blob":
577
+ responseData = await response.blob();
578
+ break;
579
+ case "text":
580
+ responseData = await response.text();
581
+ break;
582
+ case "arrayBuffer":
583
+ responseData = await response.arrayBuffer();
584
+ break;
585
+ case "formData":
586
+ responseData = await response.formData();
587
+ break;
588
+ default:
589
+ try {
590
+ responseData = await response.json();
591
+ } catch {
592
+ responseData = null;
593
+ }
594
+ }
595
+ const apiResponse = {
596
+ data: responseData,
597
+ headers: response.headers,
598
+ status: response.status,
599
+ statusText: response.statusText
600
+ };
601
+ return await this.applyResponseInterceptors(apiResponse);
602
+ };
603
+ try {
604
+ if (config.retries !== void 0 && config.retries > 0) {
605
+ return await withRetry(
606
+ executeRequest,
607
+ config.retries,
608
+ config.retryDelay,
609
+ config.retryCondition
610
+ );
611
+ }
612
+ return await executeRequest();
613
+ } catch (error) {
614
+ cleanup();
615
+ if (isAbortError(error)) {
616
+ throw new AbortError();
617
+ }
618
+ if (error instanceof TypeError && error.message === "Failed to fetch") {
619
+ throw new NetworkError("Network request failed");
620
+ }
621
+ if (error instanceof AuthenticationError && this.tokenManager.refreshToken) {
622
+ let refreshSucceeded = false;
623
+ try {
624
+ const newToken = await this.tokenManager.refreshToken();
625
+ headers.set("Authorization", `Bearer ${newToken}`);
626
+ refreshSucceeded = true;
627
+ } catch {
628
+ }
629
+ if (refreshSucceeded) {
630
+ return await executeRequest();
631
+ }
632
+ }
633
+ if (error instanceof ApiError) {
634
+ return this.applyErrorInterceptors(error);
635
+ }
636
+ throw new ApiError(
637
+ error instanceof Error ? error.message : "Unknown error occurred",
638
+ void 0,
639
+ "UNKNOWN_ERROR"
640
+ );
641
+ } finally {
642
+ cleanup();
643
+ }
644
+ }
645
+ async get(endpoint, params, config) {
646
+ const response = await this.request("GET", endpoint, void 0, { ...config, params });
647
+ return response.data;
648
+ }
649
+ async post(endpoint, data, config) {
650
+ const response = await this.request("POST", endpoint, data, config);
651
+ return response.data;
652
+ }
653
+ async put(endpoint, data, config) {
654
+ const response = await this.request("PUT", endpoint, data, config);
655
+ return response.data;
656
+ }
657
+ async runCustomQuery(customQueryId, options, config) {
658
+ return this.put(`reports/custom-queries/${customQueryId}/run`, options, config);
659
+ }
660
+ async patch(endpoint, data, config) {
661
+ const response = await this.request("PATCH", endpoint, data, config);
662
+ return response.data;
663
+ }
664
+ async delete(endpoint, data, config) {
665
+ const response = await this.request("DELETE", endpoint, data, config);
666
+ return response.data;
667
+ }
668
+ async download(endpoint, data, config) {
669
+ const response = await this.request("POST", endpoint, data, {
670
+ ...config,
671
+ responseType: "blob"
672
+ });
673
+ const contentDisposition = response.headers.get("content-disposition");
674
+ let filename = "download";
675
+ if (contentDisposition) {
676
+ const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
677
+ if (match && match[1]) {
678
+ filename = match[1].replace(/['"]/g, "");
679
+ }
680
+ }
681
+ if (this.downloadHandler) {
682
+ await this.downloadHandler(response.data, filename);
683
+ return;
684
+ }
685
+ if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
686
+ throw new Error("File download requires a browser environment or a custom downloadHandler");
687
+ }
688
+ const url = URL.createObjectURL(response.data);
689
+ const link = document.createElement("a");
690
+ link.href = url;
691
+ link.download = filename;
692
+ document.body.appendChild(link);
693
+ link.click();
694
+ document.body.removeChild(link);
695
+ setTimeout(() => URL.revokeObjectURL(url), 100);
696
+ }
697
+ async *stream(endpoint, options) {
698
+ const {
699
+ method = "POST",
700
+ body,
701
+ headers = {},
702
+ signal,
703
+ onError
704
+ } = options;
705
+ try {
706
+ const authHeader = await this.getAccessToken();
707
+ const response = await this.fetchImpl(buildUrl(this.baseURL, endpoint, {}), {
708
+ method,
709
+ headers: {
710
+ ...headers,
711
+ Accept: "text/event-stream",
712
+ "Cache-Control": "no-cache",
713
+ ...authHeader ? { Authorization: `Bearer ${authHeader}` } : {},
714
+ ...method === "POST" ? { "Content-Type": "application/json" } : {}
715
+ },
716
+ body: method === "POST" && body ? JSON.stringify(body) : void 0,
717
+ signal
718
+ });
719
+ if (!response.ok) {
720
+ throw this.createApiError(response);
721
+ }
722
+ if (!response.body) {
723
+ throw new ApiError("Response body is empty");
724
+ }
725
+ const reader = response.body.getReader();
726
+ const decoder = new TextDecoder();
727
+ let buffer = "";
728
+ try {
729
+ while (true) {
730
+ const { done, value } = await reader.read();
731
+ if (done) break;
732
+ buffer += decoder.decode(value, { stream: true });
733
+ const lines = buffer.split("\n");
734
+ buffer = lines.pop() || "";
735
+ for (const line of lines) {
736
+ if (line.startsWith("data: ")) {
737
+ const data = line.slice(6);
738
+ if (data === "[DONE]") {
739
+ return;
740
+ }
741
+ yield data;
742
+ }
743
+ }
744
+ }
745
+ } finally {
746
+ reader.releaseLock();
747
+ }
748
+ } catch (error) {
749
+ if (onError) {
750
+ onError(error);
751
+ }
752
+ throw error;
753
+ }
754
+ }
755
+ async postStream(endpoint, data, onMessage, onError, onComplete) {
756
+ try {
757
+ const generator = this.stream(endpoint, {
758
+ method: "POST",
759
+ body: data,
760
+ onMessage: onMessage || (() => {
761
+ }),
762
+ onError
763
+ });
764
+ for await (const chunk of generator) {
765
+ if (onMessage) {
766
+ try {
767
+ const parsed = JSON.parse(chunk);
768
+ onMessage(parsed);
769
+ } catch {
770
+ onMessage(chunk);
771
+ }
772
+ }
773
+ }
774
+ if (onComplete) {
775
+ onComplete();
776
+ }
777
+ } catch (error) {
778
+ if (onError) {
779
+ onError(error);
780
+ }
781
+ throw error;
782
+ }
783
+ }
784
+ };
785
+
786
+ // src/clients/rest-client.ts
787
+ var RestApiClient = class extends BaseApiClient {
788
+ constructor(config = {}) {
789
+ if (!config.baseURL) {
790
+ throw new Error("RestApiClient requires a baseURL in the configuration");
791
+ }
792
+ super(config);
793
+ }
794
+ async html2pdf(options = {}) {
795
+ const token = await this.getAccessToken();
796
+ if (!token) {
797
+ throw new ApiError("No access token provided", 401, "AUTH_REQUIRED");
798
+ }
799
+ const url = "https://html2pdf.cf.docyrus.app/";
800
+ try {
801
+ const response = await this.fetchImpl(url, {
802
+ method: "POST",
803
+ headers: {
804
+ "Content-Type": "application/json",
805
+ Authorization: `Bearer ${token}`
806
+ },
807
+ body: JSON.stringify(options)
808
+ });
809
+ if (!response.ok) {
810
+ let errorData = null;
811
+ try {
812
+ errorData = await response.json();
813
+ } catch {
814
+ }
815
+ throw this.createApiError(response, errorData);
816
+ }
817
+ return await response.json();
818
+ } catch (error) {
819
+ if (error instanceof ApiError) {
820
+ throw error;
821
+ }
822
+ throw new ApiError(
823
+ error instanceof Error ? error.message : "PDF generation failed",
824
+ void 0,
825
+ "PDF_GENERATION_ERROR"
826
+ );
827
+ }
828
+ }
829
+ };
830
+
831
+ // src/clients/edge-client.ts
832
+ var EdgeFunctionClient = class extends BaseApiClient {
833
+ constructor(config = {}) {
834
+ if (!config.baseURL) {
835
+ throw new Error("EdgeFunctionClient requires a baseURL in the configuration");
836
+ }
837
+ super(config);
838
+ }
839
+ // Edge functions might have specific streaming capabilities
840
+ async *streamFunction(functionName, data, signal) {
841
+ yield* this.stream(`/${functionName}`, {
842
+ method: "POST",
843
+ body: data,
844
+ signal,
845
+ onMessage: () => {
846
+ }
847
+ });
848
+ }
849
+ // Invoke edge function with typed response
850
+ async invokeFunction(functionName, data, config) {
851
+ return this.post(`/${functionName}`, data, config);
852
+ }
853
+ };
854
+
855
+ // src/clients/cf-client.ts
856
+ var CloudflareWorkerClient = class extends BaseApiClient {
857
+ constructor(config = {}) {
858
+ if (!config.baseURL) {
859
+ throw new Error("CloudflareWorkerClient requires a baseURL in the configuration");
860
+ }
861
+ super(config);
862
+ }
863
+ async request(method, endpoint, data, config = {}) {
864
+ const functionName = endpoint.split("/")[1] || endpoint;
865
+ const remainingPath = endpoint.includes("/") ? endpoint.substring(endpoint.indexOf("/", 1)) : "";
866
+ const originalBaseURL = this.baseURL;
867
+ if (this.baseURL.includes("{{function}}")) {
868
+ this.baseURL = this.baseURL.replace("{{function}}", functionName);
869
+ }
870
+ try {
871
+ return await super.request(method, remainingPath, data, config);
872
+ } finally {
873
+ this.baseURL = originalBaseURL;
874
+ }
875
+ }
876
+ // Worker-specific method to invoke functions
877
+ async invokeWorker(workerName, route = "", data, config) {
878
+ const endpoint = route ? `${workerName}/${route}` : workerName;
879
+ return this.post(endpoint, data, config);
880
+ }
881
+ // Durable Object binding support
882
+ async durableObject(namespace, id, method, data) {
883
+ return this.post(`durable/${namespace}/${id}/${method}`, data);
884
+ }
885
+ // KV namespace support
886
+ async kvGet(namespace, key) {
887
+ return this.get(`kv/${namespace}/${key}`);
888
+ }
889
+ async kvPut(namespace, key, value, metadata) {
890
+ await this.put(`kv/${namespace}/${key}`, { value, metadata });
891
+ }
892
+ async kvDelete(namespace, key) {
893
+ await this.delete(`kv/${namespace}/${key}`);
894
+ }
895
+ async kvList(namespace, options) {
896
+ return this.get(`kv/${namespace}`, options);
897
+ }
898
+ };
899
+
900
+ // src/core/crypto.ts
901
+ var BrowserCryptoProvider = class {
902
+ getRandomValues(buffer) {
903
+ if (typeof crypto === "undefined" || !crypto.getRandomValues) {
904
+ throw new Error("Web Crypto API (crypto.getRandomValues) not available");
905
+ }
906
+ return crypto.getRandomValues(buffer);
907
+ }
908
+ async sha256(data) {
909
+ if (typeof crypto === "undefined" || !crypto.subtle?.digest) {
910
+ throw new Error("Web Crypto API (crypto.subtle.digest) not available");
911
+ }
912
+ return crypto.subtle.digest("SHA-256", data);
913
+ }
914
+ btoa(input) {
915
+ if (typeof globalThis.btoa !== "function") {
916
+ throw new Error("btoa() not available in this environment");
917
+ }
918
+ return globalThis.btoa(input);
919
+ }
920
+ atob(input) {
921
+ if (typeof globalThis.atob !== "function") {
922
+ throw new Error("atob() not available in this environment");
923
+ }
924
+ return globalThis.atob(input);
925
+ }
926
+ };
927
+ var defaultProvider;
928
+ function getDefaultCryptoProvider() {
929
+ if (!defaultProvider) {
930
+ defaultProvider = new BrowserCryptoProvider();
931
+ }
932
+ return defaultProvider;
933
+ }
934
+
935
+ // src/oauth2/pkce.ts
936
+ function generateCodeVerifier(length = 64, cryptoProvider) {
937
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
938
+ const unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
939
+ const randomValues = new Uint8Array(length);
940
+ provider.getRandomValues(randomValues);
941
+ let verifier = "";
942
+ for (let i = 0; i < length; i++) {
943
+ verifier += unreserved[randomValues[i] % unreserved.length];
944
+ }
945
+ return verifier;
946
+ }
947
+ function base64UrlEncode(buffer, cryptoProvider) {
948
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
949
+ let base64 = "";
950
+ const bytes = new Uint8Array(buffer);
951
+ const len = bytes.byteLength;
952
+ for (let i = 0; i < len; i++) {
953
+ base64 += String.fromCharCode(bytes[i]);
954
+ }
955
+ return provider.btoa(base64).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
956
+ }
957
+ function base64UrlDecode(input, cryptoProvider) {
958
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
959
+ let base64 = input.replace(/-/g, "+").replace(/_/g, "/");
960
+ while (base64.length % 4) {
961
+ base64 += "=";
962
+ }
963
+ const binary = provider.atob(base64);
964
+ const bytes = new Uint8Array(binary.length);
965
+ for (let i = 0; i < binary.length; i++) {
966
+ bytes[i] = binary.charCodeAt(i);
967
+ }
968
+ return bytes;
969
+ }
970
+ async function generateCodeChallenge(codeVerifier, cryptoProvider) {
971
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
972
+ const encoder = new TextEncoder();
973
+ const data = encoder.encode(codeVerifier);
974
+ const digest = await provider.sha256(data);
975
+ return base64UrlEncode(new Uint8Array(digest), provider);
976
+ }
977
+ async function generatePKCEChallenge(cryptoProvider) {
978
+ const codeVerifier = generateCodeVerifier(64, cryptoProvider);
979
+ const codeChallenge = await generateCodeChallenge(codeVerifier, cryptoProvider);
980
+ return {
981
+ codeVerifier,
982
+ codeChallenge,
983
+ codeChallengeMethod: "S256"
984
+ };
985
+ }
986
+ function generateState(length = 32, cryptoProvider) {
987
+ return generateCodeVerifier(length, cryptoProvider);
988
+ }
989
+ function generateNonce(length = 32, cryptoProvider) {
990
+ return generateCodeVerifier(length, cryptoProvider);
991
+ }
992
+
993
+ // src/oauth2/oauth2-token-manager.ts
994
+ var MemoryOAuth2TokenStorage = class {
995
+ tokens = null;
996
+ pkceState = null;
997
+ getTokens() {
998
+ return this.tokens;
999
+ }
1000
+ setTokens(tokens) {
1001
+ this.tokens = tokens;
1002
+ }
1003
+ clearTokens() {
1004
+ this.tokens = null;
1005
+ }
1006
+ getPKCEState() {
1007
+ return this.pkceState;
1008
+ }
1009
+ setPKCEState(state) {
1010
+ this.pkceState = state;
1011
+ }
1012
+ clearPKCEState() {
1013
+ this.pkceState = null;
1014
+ }
1015
+ };
1016
+ var OAuth2TokenManagerAdapter = class {
1017
+ constructor(oauth2Storage, onTokenExpired) {
1018
+ this.oauth2Storage = oauth2Storage;
1019
+ this.onTokenExpired = onTokenExpired;
1020
+ }
1021
+ oauth2Storage;
1022
+ onTokenExpired;
1023
+ getToken() {
1024
+ const tokens = this.oauth2Storage.getTokens();
1025
+ if (tokens instanceof Promise) {
1026
+ return tokens.then((t) => this.extractToken(t));
1027
+ }
1028
+ return this.extractToken(tokens);
1029
+ }
1030
+ extractToken(tokens) {
1031
+ if (!tokens) return null;
1032
+ if (tokens.expiresAt && Date.now() >= (tokens.expiresAt - 60) * 1e3) {
1033
+ return null;
1034
+ }
1035
+ return tokens.accessToken;
1036
+ }
1037
+ setToken(token) {
1038
+ const result = this.oauth2Storage.setTokens({
1039
+ accessToken: token,
1040
+ expiresAt: Math.floor(Date.now() / 1e3) + 3600,
1041
+ // Default 1 hour
1042
+ scope: ""
1043
+ });
1044
+ if (result instanceof Promise) {
1045
+ return result;
1046
+ }
1047
+ }
1048
+ clearToken() {
1049
+ return this.oauth2Storage.clearTokens();
1050
+ }
1051
+ refreshToken() {
1052
+ if (!this.onTokenExpired) {
1053
+ return Promise.reject(new Error("Token refresh not configured"));
1054
+ }
1055
+ return this.onTokenExpired();
1056
+ }
1057
+ };
1058
+
1059
+ // src/oauth2/oauth2-client.ts
1060
+ var REFRESHED_ELSEWHERE_MIN_VALIDITY_SECONDS = 30;
1061
+ async function withRefreshLock(name, fn) {
1062
+ const locks = globalThis.navigator?.locks;
1063
+ return locks ? await locks.request(name, fn) : await fn();
1064
+ }
1065
+ var OAuth2Client = class {
1066
+ config;
1067
+ fetchImpl;
1068
+ storage;
1069
+ cryptoProvider;
1070
+ /** Shared in-flight refresh, so concurrent callers don't each spend the refresh token. */
1071
+ refreshInFlight = null;
1072
+ constructor(config) {
1073
+ if (!config.baseURL) {
1074
+ throw new Error("OAuth2Client requires a baseURL");
1075
+ }
1076
+ if (!config.clientId) {
1077
+ throw new Error("OAuth2Client requires a clientId");
1078
+ }
1079
+ this.config = {
1080
+ ...config,
1081
+ baseURL: config.baseURL,
1082
+ clientId: config.clientId,
1083
+ usePKCE: config.usePKCE ?? true,
1084
+ defaultScopes: config.defaultScopes ?? []
1085
+ };
1086
+ const rawFetch = config.fetch || globalThis.fetch;
1087
+ if (!rawFetch) {
1088
+ throw new Error("Fetch API not available");
1089
+ }
1090
+ this.fetchImpl = rawFetch.bind(globalThis);
1091
+ this.storage = config.tokenStorage || new MemoryOAuth2TokenStorage();
1092
+ this.cryptoProvider = config.cryptoProvider;
1093
+ }
1094
+ // ===== Authorization Code Flow =====
1095
+ /**
1096
+ * Generate authorization URL for the authorization code flow
1097
+ * Handles PKCE automatically if enabled
1098
+ */
1099
+ async getAuthorizationUrl(options = {}) {
1100
+ const state = options.state || generateState(32, this.cryptoProvider);
1101
+ const scope = options.scope || this.config.defaultScopes?.join(" ") || "openid";
1102
+ const redirectUri = options.redirectUri || this.config.redirectUri;
1103
+ if (!redirectUri) {
1104
+ throw new Error("redirectUri is required for authorization code flow");
1105
+ }
1106
+ const params = {
1107
+ client_id: this.config.clientId,
1108
+ redirect_uri: redirectUri,
1109
+ response_type: "code",
1110
+ state,
1111
+ scope
1112
+ };
1113
+ if (scope.includes("openid")) {
1114
+ params.nonce = options.nonce || generateNonce(32, this.cryptoProvider);
1115
+ }
1116
+ let codeVerifier;
1117
+ if (this.config.usePKCE) {
1118
+ const pkce = await generatePKCEChallenge(this.cryptoProvider);
1119
+ params.code_challenge = pkce.codeChallenge;
1120
+ params.code_challenge_method = pkce.codeChallengeMethod;
1121
+ ({ codeVerifier } = pkce);
1122
+ if (this.storage.setPKCEState) {
1123
+ await Promise.resolve(this.storage.setPKCEState({
1124
+ codeVerifier,
1125
+ state,
1126
+ nonce: params.nonce
1127
+ }));
1128
+ }
1129
+ }
1130
+ const url = buildUrl(this.config.baseURL, "/v1/oauth2/authorize", params);
1131
+ return { url, state, codeVerifier };
1132
+ }
1133
+ /**
1134
+ * Handle the authorization callback and exchange code for tokens
1135
+ */
1136
+ async handleCallback(callbackUrl, options = {}) {
1137
+ let code;
1138
+ let state;
1139
+ if (typeof callbackUrl === "string") {
1140
+ const url = new URL(callbackUrl);
1141
+ code = url.searchParams.get("code") || "";
1142
+ state = url.searchParams.get("state") || "";
1143
+ const error = url.searchParams.get("error");
1144
+ if (error) {
1145
+ const errorDescription = url.searchParams.get("error_description") || void 0;
1146
+ throw this.createOAuth2Error(error, errorDescription);
1147
+ }
1148
+ } else {
1149
+ ({ code, state } = callbackUrl);
1150
+ }
1151
+ let storedPKCE = null;
1152
+ if (this.storage.getPKCEState) {
1153
+ storedPKCE = await Promise.resolve(this.storage.getPKCEState());
1154
+ }
1155
+ const expectedState = options.expectedState || storedPKCE?.state;
1156
+ if (expectedState && state !== expectedState) {
1157
+ throw new OAuth2Error("invalid_state", "State mismatch - possible CSRF attack");
1158
+ }
1159
+ const codeVerifier = options.codeVerifier || storedPKCE?.codeVerifier;
1160
+ const tokens = await this.exchangeCode(code, codeVerifier);
1161
+ if (this.storage.clearPKCEState) {
1162
+ await Promise.resolve(this.storage.clearPKCEState());
1163
+ }
1164
+ return tokens;
1165
+ }
1166
+ /**
1167
+ * Exchange authorization code for tokens
1168
+ */
1169
+ async exchangeCode(code, codeVerifier, redirectUri) {
1170
+ const body = {
1171
+ grant_type: "authorization_code",
1172
+ client_id: this.config.clientId,
1173
+ code,
1174
+ redirect_uri: redirectUri || this.config.redirectUri
1175
+ };
1176
+ if (codeVerifier) {
1177
+ body.code_verifier = codeVerifier;
1178
+ } else if (this.config.clientSecret) {
1179
+ body.client_secret = this.config.clientSecret;
1180
+ }
1181
+ return this.requestToken(body);
1182
+ }
1183
+ // ===== Refresh Token Flow =====
1184
+ /**
1185
+ * Refresh the access token using a refresh token.
1186
+ *
1187
+ * Concurrent calls share a single in-flight request. Without this, several
1188
+ * requests crossing the expiry buffer at once each fire their own refresh;
1189
+ * with refresh-token rotation only the first succeeds and the losers can
1190
+ * leave the client holding an already-expired token (surfacing as backend
1191
+ * "JWTExpired" errors on subsequent calls).
1192
+ */
1193
+ async refreshAccessToken(refreshToken) {
1194
+ if (this.refreshInFlight) return this.refreshInFlight;
1195
+ this.refreshInFlight = this.performRefresh(refreshToken).finally(() => {
1196
+ this.refreshInFlight = null;
1197
+ });
1198
+ return this.refreshInFlight;
1199
+ }
1200
+ /**
1201
+ * Refresh tokens rotate, and the Docyrus API refuses a rotated refresh token presented again (and can end
1202
+ * the whole sign-in for it). Tabs and windows sharing one token storage therefore refresh one at a time,
1203
+ * under a Web Lock, and with the token as stored *now*: if another tab refreshed while this one waited, its
1204
+ * tokens are used instead of refreshing again. Outside browsers (no Web Locks) only the per-instance
1205
+ * single-flight above applies.
1206
+ */
1207
+ async performRefresh(refreshToken) {
1208
+ const seenRefreshToken = refreshToken || (await Promise.resolve(this.storage.getTokens()))?.refreshToken;
1209
+ return await withRefreshLock(`docyrus-oauth2-refresh:${this.config.baseURL}:${this.config.clientId}`, async () => {
1210
+ const stored = await Promise.resolve(this.storage.getTokens());
1211
+ if (stored?.refreshToken && seenRefreshToken && stored.refreshToken !== seenRefreshToken && !await this.isTokenExpired(REFRESHED_ELSEWHERE_MIN_VALIDITY_SECONDS)) {
1212
+ return stored;
1213
+ }
1214
+ return await this.requestRefresh(stored?.refreshToken || refreshToken);
1215
+ });
1216
+ }
1217
+ async requestRefresh(token) {
1218
+ if (!token) {
1219
+ throw new InvalidGrantError("No refresh token available");
1220
+ }
1221
+ const body = {
1222
+ grant_type: "refresh_token",
1223
+ client_id: this.config.clientId,
1224
+ refresh_token: token
1225
+ };
1226
+ if (this.config.clientSecret) {
1227
+ body.client_secret = this.config.clientSecret;
1228
+ }
1229
+ return this.requestToken(body);
1230
+ }
1231
+ // ===== Client Credentials Flow =====
1232
+ /**
1233
+ * Get access token using client credentials
1234
+ */
1235
+ async getClientCredentialsToken(options) {
1236
+ const body = {
1237
+ grant_type: "client_credentials",
1238
+ client_id: this.config.clientId,
1239
+ scope: options.scope,
1240
+ delegated_user_id: options.delegatedUserId
1241
+ };
1242
+ if (options.clientAssertion) {
1243
+ body.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1244
+ body.client_assertion = options.clientAssertion;
1245
+ } else if (this.config.clientSecret) {
1246
+ body.client_secret = this.config.clientSecret;
1247
+ } else {
1248
+ throw new InvalidClientError("Client credentials flow requires client_secret or client_assertion");
1249
+ }
1250
+ return this.requestToken(body);
1251
+ }
1252
+ // ===== Device Authorization Flow (RFC 8628) =====
1253
+ /**
1254
+ * Start device authorization flow
1255
+ */
1256
+ async startDeviceAuthorization(scope) {
1257
+ const body = {
1258
+ client_id: this.config.clientId,
1259
+ scope: scope || this.config.defaultScopes?.join(" ")
1260
+ };
1261
+ const response = await this.fetchImpl(
1262
+ buildUrl(this.config.baseURL, "/v1/oauth2/device/authorize", {}),
1263
+ {
1264
+ method: "POST",
1265
+ headers: { "Content-Type": "application/json" },
1266
+ body: JSON.stringify(body)
1267
+ }
1268
+ );
1269
+ if (!response.ok) {
1270
+ await this.handleErrorResponse(response);
1271
+ }
1272
+ return response.json();
1273
+ }
1274
+ /**
1275
+ * Poll for device authorization completion
1276
+ * Returns tokens when user completes authorization
1277
+ */
1278
+ async pollDeviceAuthorization(deviceCode, interval = 5, expiresIn = 1800, options = {}) {
1279
+ const startTime = Date.now();
1280
+ const expiresAt = startTime + expiresIn * 1e3;
1281
+ let currentInterval = interval * 1e3;
1282
+ while (Date.now() < expiresAt) {
1283
+ if (options.signal?.aborted) {
1284
+ throw new Error("Device authorization polling was aborted");
1285
+ }
1286
+ await this.sleep(currentInterval);
1287
+ try {
1288
+ const body = {
1289
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1290
+ client_id: this.config.clientId,
1291
+ device_code: deviceCode
1292
+ };
1293
+ return await this.requestToken(body);
1294
+ } catch (error) {
1295
+ if (error instanceof AuthorizationPendingError) {
1296
+ continue;
1297
+ }
1298
+ if (error instanceof SlowDownError) {
1299
+ currentInterval += 5e3;
1300
+ continue;
1301
+ }
1302
+ if (error instanceof ExpiredTokenError) {
1303
+ options.onExpired?.();
1304
+ throw error;
1305
+ }
1306
+ throw error;
1307
+ }
1308
+ }
1309
+ options.onExpired?.();
1310
+ throw new ExpiredTokenError();
1311
+ }
1312
+ /**
1313
+ * Verify a device user code
1314
+ */
1315
+ async verifyDeviceCode(userCode) {
1316
+ const body = { user_code: userCode };
1317
+ const response = await this.fetchImpl(
1318
+ buildUrl(this.config.baseURL, "/v1/oauth2/device/verify", {}),
1319
+ {
1320
+ method: "POST",
1321
+ headers: { "Content-Type": "application/json" },
1322
+ body: JSON.stringify(body)
1323
+ }
1324
+ );
1325
+ if (!response.ok) {
1326
+ await this.handleErrorResponse(response);
1327
+ }
1328
+ return response.json();
1329
+ }
1330
+ // ===== Token Revocation =====
1331
+ /**
1332
+ * Revoke a refresh token
1333
+ */
1334
+ async revokeToken(refreshToken, clientAssertion) {
1335
+ const body = {
1336
+ client_id: this.config.clientId,
1337
+ refresh_token: refreshToken
1338
+ };
1339
+ if (clientAssertion) {
1340
+ body.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1341
+ body.client_assertion = clientAssertion;
1342
+ } else if (this.config.clientSecret) {
1343
+ body.client_secret = this.config.clientSecret;
1344
+ }
1345
+ const response = await this.fetchImpl(
1346
+ buildUrl(this.config.baseURL, "/v1/oauth2/revoke", {}),
1347
+ {
1348
+ method: "POST",
1349
+ headers: { "Content-Type": "application/json" },
1350
+ body: JSON.stringify(body)
1351
+ }
1352
+ );
1353
+ if (!response.ok && response.status !== 204) {
1354
+ await this.handleErrorResponse(response);
1355
+ }
1356
+ }
1357
+ // ===== Token Introspection =====
1358
+ /**
1359
+ * Introspect a token to check its validity and metadata
1360
+ */
1361
+ async introspectToken(token, tokenTypeHint, clientAssertion) {
1362
+ const body = {
1363
+ token,
1364
+ client_id: this.config.clientId,
1365
+ token_type_hint: tokenTypeHint
1366
+ };
1367
+ if (clientAssertion) {
1368
+ body.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1369
+ body.client_assertion = clientAssertion;
1370
+ } else if (this.config.clientSecret) {
1371
+ body.client_secret = this.config.clientSecret;
1372
+ }
1373
+ const response = await this.fetchImpl(
1374
+ buildUrl(this.config.baseURL, "/v1/oauth2/introspect", {}),
1375
+ {
1376
+ method: "POST",
1377
+ headers: { "Content-Type": "application/json" },
1378
+ body: JSON.stringify(body)
1379
+ }
1380
+ );
1381
+ if (!response.ok) {
1382
+ await this.handleErrorResponse(response);
1383
+ }
1384
+ return response.json();
1385
+ }
1386
+ // ===== Rate Limit Check =====
1387
+ /**
1388
+ * Check rate limit status without consuming units
1389
+ */
1390
+ async checkRateLimit() {
1391
+ const currentTokens = await Promise.resolve(this.storage.getTokens());
1392
+ const headers = {};
1393
+ if (currentTokens?.accessToken) {
1394
+ headers["Authorization"] = `Bearer ${currentTokens.accessToken}`;
1395
+ }
1396
+ const response = await this.fetchImpl(
1397
+ buildUrl(this.config.baseURL, "/v1/oauth2", {}),
1398
+ {
1399
+ method: "HEAD",
1400
+ headers
1401
+ }
1402
+ );
1403
+ return {
1404
+ policy: response.headers.get("RateLimit-Policy") || "",
1405
+ reset: parseInt(response.headers.get("RateLimit-Reset") || "0", 10),
1406
+ remaining: parseInt(response.headers.get("RateLimit-Remaining") || "0", 10),
1407
+ limit: parseInt(response.headers.get("RateLimit-Limit") || "0", 10)
1408
+ };
1409
+ }
1410
+ // ===== Token Management =====
1411
+ /**
1412
+ * Get current stored tokens
1413
+ */
1414
+ async getTokens() {
1415
+ return Promise.resolve(this.storage.getTokens());
1416
+ }
1417
+ /**
1418
+ * Check if the current access token is expired
1419
+ */
1420
+ async isTokenExpired(bufferSeconds = 60) {
1421
+ const tokens = await this.getTokens();
1422
+ if (!tokens) return true;
1423
+ const expiresAt = (tokens.expiresAt || 0) > 0 ? tokens.expiresAt : this.parseJwtExp(tokens.accessToken);
1424
+ if (!expiresAt || !Number.isFinite(expiresAt)) return false;
1425
+ return Date.now() >= (expiresAt - bufferSeconds) * 1e3;
1426
+ }
1427
+ /**
1428
+ * Get a valid access token, refreshing if necessary
1429
+ */
1430
+ async getValidAccessToken() {
1431
+ const tokens = await this.getTokens();
1432
+ if (!tokens) {
1433
+ throw new InvalidGrantError("No tokens available");
1434
+ }
1435
+ if (await this.isTokenExpired()) {
1436
+ if (!tokens.refreshToken) {
1437
+ throw new InvalidGrantError("Access token expired and no refresh token available");
1438
+ }
1439
+ const newTokens = await this.refreshAccessToken(tokens.refreshToken);
1440
+ return newTokens.accessToken;
1441
+ }
1442
+ return tokens.accessToken;
1443
+ }
1444
+ /**
1445
+ * Clear all stored tokens (logout)
1446
+ */
1447
+ async logout() {
1448
+ const tokens = await this.getTokens();
1449
+ if (tokens?.refreshToken) {
1450
+ try {
1451
+ await this.revokeToken(tokens.refreshToken);
1452
+ } catch {
1453
+ }
1454
+ }
1455
+ await Promise.resolve(this.storage.clearTokens());
1456
+ }
1457
+ // ===== Private Methods =====
1458
+ async requestToken(body) {
1459
+ const response = await this.fetchImpl(
1460
+ buildUrl(this.config.baseURL, "/v1/oauth2/token", {}),
1461
+ {
1462
+ method: "POST",
1463
+ headers: { "Content-Type": "application/json" },
1464
+ body: JSON.stringify(body)
1465
+ }
1466
+ );
1467
+ if (!response.ok) {
1468
+ await this.handleErrorResponse(response);
1469
+ }
1470
+ const tokenResponse = await response.json();
1471
+ const expiresIn = tokenResponse.expires_in;
1472
+ const expiresAt = Number.isFinite(expiresIn) && expiresIn > 0 ? Math.floor(Date.now() / 1e3) + expiresIn : this.parseJwtExp(tokenResponse.access_token) ?? 0;
1473
+ const tokens = {
1474
+ accessToken: tokenResponse.access_token,
1475
+ refreshToken: tokenResponse.refresh_token,
1476
+ idToken: tokenResponse.id_token,
1477
+ expiresAt,
1478
+ scope: tokenResponse.scope
1479
+ };
1480
+ await Promise.resolve(this.storage.setTokens(tokens));
1481
+ return tokens;
1482
+ }
1483
+ async handleErrorResponse(response) {
1484
+ let errorData;
1485
+ try {
1486
+ errorData = await response.json();
1487
+ } catch {
1488
+ throw new OAuth2Error("unknown_error", response.statusText);
1489
+ }
1490
+ throw this.createOAuth2Error(
1491
+ errorData.error || "unknown_error",
1492
+ errorData.error_description,
1493
+ errorData.error_uri
1494
+ );
1495
+ }
1496
+ createOAuth2Error(error, description, uri) {
1497
+ switch (error) {
1498
+ case "invalid_grant":
1499
+ return new InvalidGrantError(description);
1500
+ case "invalid_client":
1501
+ return new InvalidClientError(description);
1502
+ case "authorization_pending":
1503
+ return new AuthorizationPendingError();
1504
+ case "slow_down":
1505
+ return new SlowDownError();
1506
+ case "expired_token":
1507
+ return new ExpiredTokenError();
1508
+ case "access_denied":
1509
+ return new AccessDeniedError(description);
1510
+ default:
1511
+ return new OAuth2Error(error, description, uri);
1512
+ }
1513
+ }
1514
+ sleep(ms) {
1515
+ return new Promise((resolve) => setTimeout(resolve, ms));
1516
+ }
1517
+ /** Extract exp claim from a JWT access token as a fallback for expires_in. */
1518
+ parseJwtExp(accessToken) {
1519
+ const parts = accessToken.split(".");
1520
+ if (parts.length < 2) return void 0;
1521
+ try {
1522
+ const payload = JSON.parse(
1523
+ atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
1524
+ );
1525
+ return typeof payload["exp"] === "number" ? payload["exp"] : void 0;
1526
+ } catch {
1527
+ return void 0;
1528
+ }
1529
+ }
1530
+ };
1531
+
1532
+ export { AbortError, AccessDeniedError, ApiError, AsyncTokenManager, AuthenticationError, AuthorizationError, AuthorizationPendingError, BaseApiClient, BrowserCryptoProvider, CloudflareWorkerClient, ConflictError, EdgeFunctionClient, ExpiredTokenError, GenericError, InvalidClientError, InvalidGrantError, InvalidScopeError, MemoryOAuth2TokenStorage, MemoryTokenManager, NetworkError, NotFoundError, OAuth2Client, OAuth2Error, OAuth2TokenManagerAdapter, RateLimitError, ReactNativeCryptoProvider, RestApiClient, ServerError, SlowDownError, TimeoutError, ValidationError, base64UrlDecode, base64UrlEncode, buildUrl, createAbortSignal, createTokenStorage, RestApiClient as default, generateCodeChallenge, generateCodeVerifier, generateNonce, generatePKCEChallenge, generateState, getDefaultCryptoProvider, isAbortError, isBlob, isFormData, isStream, jsonToQueryString, parseContentDisposition, prepareFilterQueryForApi, withRetry };
1533
+ //# sourceMappingURL=index.js.map
1534
+ //# sourceMappingURL=index.js.map