@alore/auth-react-sdk 1.1.0-alpha.4 → 1.1.0-alpha.6

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.
@@ -1,4 +1,4 @@
1
- import { AuthMachineContext, AuthProviderConfig, FetchWithProgressiveBackoffConfig, ForgeData } from '../types';
1
+ import type { AuthMachineContext, AuthProviderConfig, FetchWithProgressiveBackoffConfig, ForgeData } from '../types';
2
2
  export declare class AloreAuth {
3
3
  protected readonly aloreBaseUrl: string;
4
4
  protected readonly emailTemplate: string;
@@ -266,4 +266,5 @@ export declare class AloreAuth {
266
266
  private delay;
267
267
  fetchWithProgressiveBackoff(url: RequestInfo | URL, options?: RequestInit, config?: FetchWithProgressiveBackoffConfig): Promise<Response>;
268
268
  private verifyBackendStatus;
269
+ private extractErrorInfo;
269
270
  }
@@ -533,8 +533,9 @@ export class AloreAuth {
533
533
  const { maxAttempts = 3, initialDelay = 200 } = config || {};
534
534
  let attempt = 0;
535
535
  let delayValue = initialDelay;
536
+ const isLocal = this.aloreBaseUrl.includes('localhost') || this.aloreBaseUrl.includes('127.0.0.1');
536
537
  // eslint-disable-next-line no-undef
537
- const init = Object.assign(Object.assign({}, options), { credentials: 'include', headers: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.headers), { 'X-CLIENT-ID': this.clientId, 'CF-Connecting-IP': '127.0.0.1' }) });
538
+ const init = Object.assign(Object.assign({}, options), { credentials: 'include', headers: Object.assign(Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.headers), { 'X-CLIENT-ID': this.clientId }), (isLocal && { 'CF-Connecting-IP': '127.0.0.1' })) });
538
539
  while (attempt < maxAttempts) {
539
540
  if (attempt > 0) {
540
541
  // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, no-loop-func
@@ -551,31 +552,72 @@ export class AloreAuth {
551
552
  }
552
553
  catch (error) {
553
554
  console.error(error);
554
- if (error instanceof TypeError &&
555
- error.message === 'Failed to fetch' &&
556
- attempt >= maxAttempts) {
557
- console.error('Connection refused, the backend is probably not running.');
558
- this.verifyBackendStatus();
555
+ // Treat any fetch TypeError as a network/CORS-style failure. Browsers localize the message.
556
+ const isFailedToFetch = error instanceof TypeError;
557
+ if (isFailedToFetch && attempt >= maxAttempts) {
558
+ // Determine whether backend is down or the request is likely blocked (e.g., CORS)
559
+ const origin = typeof window !== 'undefined' ? window.location.origin : undefined;
560
+ try {
561
+ // eslint-disable-next-line no-await-in-loop
562
+ const health = yield this.verifyBackendStatus();
563
+ const fullUrl = `${this.aloreBaseUrl}${url}`;
564
+ const message = origin
565
+ ? `Request blocked by CORS policy. Endpoint: ${fullUrl}. Please ensure origin ${origin} is allowed.`
566
+ : `Request blocked by CORS policy. Endpoint: ${fullUrl}.`;
567
+ const corsErr = new AloreAuthError(ErrorTypes.CORS_BLOCKED, message);
568
+ // Preserve original fetch error and health-check details for diagnostics
569
+ // @ts-ignore
570
+ corsErr.data = {
571
+ originalError: this.extractErrorInfo(error),
572
+ healthCheck: Object.assign({ reachable: true }, health),
573
+ };
574
+ throw corsErr;
575
+ }
576
+ catch (healthError) {
577
+ // Backend health-check failed → server likely down/unreachable
578
+ const downErr = new AloreAuthError(ErrorTypes.SERVER_DOWN, `Server is unreachable at ${this.aloreBaseUrl}. Please try again later.`);
579
+ // @ts-ignore
580
+ downErr.data = {
581
+ originalError: this.extractErrorInfo(error),
582
+ healthCheck: { reachable: false, error: this.extractErrorInfo(healthError) },
583
+ };
584
+ throw downErr;
585
+ }
559
586
  }
560
- else if (attempt < maxAttempts) {
587
+ if (attempt < maxAttempts) {
561
588
  console.error(`Attempt ${attempt} failed, retrying in ${delayValue}ms...`);
562
589
  }
563
590
  }
564
591
  }
565
- throw new Error(`Max attempts (${maxAttempts}) exceeded`);
592
+ // Final fallback (should rarely hit due to early throws above)
593
+ throw new AloreAuthError(ErrorTypes.FAILED_TO_FETCH, `Max attempts (${maxAttempts}) exceeded while contacting ${this.aloreBaseUrl}${url}`);
566
594
  });
567
595
  }
568
596
  verifyBackendStatus() {
569
597
  return __awaiter(this, void 0, void 0, function* () {
598
+ const endpoint = '/health/ready';
599
+ // eslint-disable-next-line no-undef
600
+ const init = { mode: 'no-cors', cache: 'no-store' };
570
601
  try {
571
- const res = yield fetch(`${this.aloreBaseUrl}/health-check`);
572
- if (!res.ok) {
573
- throw new Error('Failed to fetch');
574
- }
602
+ yield fetch(`${this.aloreBaseUrl}${endpoint}`, init);
603
+ return { checkedEndpoints: [endpoint] };
575
604
  }
576
605
  catch (_a) {
577
606
  throw new Error('Server down');
578
607
  }
579
608
  });
580
609
  }
610
+ // Capture a concise, serializable snapshot of an unknown error
611
+ // eslint-disable-next-line class-methods-use-this
612
+ extractErrorInfo(error) {
613
+ if (error instanceof Error) {
614
+ return { name: error.name, message: error.message, stack: error.stack };
615
+ }
616
+ try {
617
+ return JSON.parse(JSON.stringify(error));
618
+ }
619
+ catch (_a) {
620
+ return { error };
621
+ }
622
+ }
581
623
  }
@@ -10,6 +10,7 @@ export declare enum ErrorTypes {
10
10
  USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS",
11
11
  FAILED_TO_FETCH = "FAILED_TO_FETCH",
12
12
  SERVER_DOWN = "SERVER_DOWN",
13
+ CORS_BLOCKED = "CORS_BLOCKED",
13
14
  BAD_RESPONSE = "BAD_RESPONSE",
14
15
  UNKNOWN_ERROR = "UNKNOWN_ERROR",
15
16
  INVALID_CREDENTIALS = "INVALID_CREDENTIALS",
@@ -13,6 +13,7 @@ export var ErrorTypes;
13
13
  ErrorTypes["USER_ALREADY_EXISTS"] = "USER_ALREADY_EXISTS";
14
14
  ErrorTypes["FAILED_TO_FETCH"] = "FAILED_TO_FETCH";
15
15
  ErrorTypes["SERVER_DOWN"] = "SERVER_DOWN";
16
+ ErrorTypes["CORS_BLOCKED"] = "CORS_BLOCKED";
16
17
  ErrorTypes["BAD_RESPONSE"] = "BAD_RESPONSE";
17
18
  ErrorTypes["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
18
19
  ErrorTypes["INVALID_CREDENTIALS"] = "INVALID_CREDENTIALS";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alore/auth-react-sdk",
3
- "version": "1.1.0-alpha.4",
3
+ "version": "1.1.0-alpha.6",
4
4
  "repository": "https://github.com/0xCarbon/alore-js",
5
5
  "description": "SDK for Alore Auth",
6
6
  "main": "dist/index.js",