> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usehasp.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Initialization

> Loading the HASP JS SDK, constructor options, retry behavior, and cleanup.

## Loading the SDK

### Script Tag (Recommended)

```html theme={null}
<script src="https://sdk.usehasp.com/v1.js"></script>
<script>
  const sdk = new HaspSDK();
</script>
```

Always use the full CDN URL. Never use a relative path like `/sdk/v1.js`. The CDN version ensures you always run a compatible release.

### ES Module Import

```javascript theme={null}
import HaspSDK from 'https://sdk.usehasp.com/v1.js';
const sdk = new HaspSDK();
```

## Constructor Options

```javascript theme={null}
const sdk = new HaspSDK({
  // All options are optional — defaults work for most apps.

  appId: undefined,             // Auto-detected from window.__HASP__ — never set this manually
  baseUrl: '/api/hasp/v1',  // Data API base path — do not change (exposed for testing environments only)

  onUnauthorized: () => {
    // Called on 401. Default: redirect to /login.
    // Override to save draft state before redirecting.
  },

  onMaintenanceStart: (status) => {
    // Called with { status, message?, estimatedSeconds? } when maintenance begins.
  },

  onMaintenanceEnd: () => {
    // Called when maintenance ends (any request succeeds after a 503).
  },

  retry: {
    maxRetries: 3,      // Retries for 429/502 (default: 3)
    baseDelayMs: 500,   // Base delay before first retry (default: 500ms)
  },
});
```

## How `appId` is Resolved

The SDK reads `appId` from `window.__HASP__.appId`, which is injected by HASP when your app is served. You never set this yourself. If `appId` cannot be resolved, the constructor throws immediately with `ErrorCode.MissingAppId`.

## Retry Behavior

The SDK retries automatically for:

* `429 Rate Limited` — respects `Retry-After` header if present (integer seconds or HTTP-date)
* `502 Bad Gateway` — network infrastructure hiccups
* Network failures (device offline, DNS failure) — for `GET` and single-record `DELETE` only (idempotent)

`POST`, `PATCH`, and bulk `DELETE` are **not** retried on network failure to avoid double-writes. Single-record `DELETE` is retried because it is idempotent.

`503 Maintenance` is never retried — the SDK enters maintenance mode immediately.

## Cleanup

Call `destroy()` when your app unmounts to abort all in-flight requests and clear event handlers:

```javascript theme={null}
sdk.destroy();
```

Pending promises reject with an `AbortError`. After `destroy()`, maintenance event handlers are also cleared.
