# Installation

The LiquidCommerce Elements SDK can be integrated into your website using either a CDN script tag or as an NPM package.

## Browser Requirements

The SDK requires:
- Modern browser with Web Components support (Chrome 66+, Firefox 60+, Safari 12+, Edge 79+)
- Shadow DOM support
- JavaScript enabled

For older browsers, you'll need to include Web Components and Shadow DOM polyfills.

## CDN Installation (Recommended)

The simplest way to get started is by adding the SDK script tag to your HTML.

### Basic Setup

Add the following script tag to your page's `<head>` section:

```html
<script
  defer
  data-liquid-commerce-elements
  data-token="YOUR_API_KEY"
  data-env="production"
  type="text/javascript"
  src="https://elements.reservebar-worker.workers.dev/all/elements.js"
></script>
```

### Script Attributes

| Attribute | Required | Description |
|-----------|----------|-------------|
| `data-liquid-commerce-elements` | Yes | Identifies this as the Elements SDK script |
| `data-token` | Yes | Your LiquidCommerce API key |
| `data-env` | Yes | Environment: `development`, `staging`, or `production` |
| `defer` | Recommended | Allows non-blocking script loading |

### Where to Place the Script

While the `<head>` section is recommended, the script can be placed anywhere on your page:

```html
<!DOCTYPE html>
<html>
<head>
  <title>My Store</title>
  <!-- SDK script in head (recommended) -->
  <script
    defer
    data-liquid-commerce-elements
    data-token="YOUR_API_KEY"
    data-env="production"
    type="text/javascript"
    src="https://elements.reservebar-worker.workers.dev/all/elements.js"
  ></script>
</head>
<body>
  <!-- Your content -->
</body>
</html>
```

The `defer` attribute ensures the script loads asynchronously without blocking page content, keeping your site fast regardless of placement.

### Checkout-Only Build

If you only need checkout functionality (without product displays or cart), use the lighter checkout-only build:

```html
<script
  defer
  data-liquid-commerce-elements-checkout
  data-token="YOUR_API_KEY"
  data-env="production"
  type="text/javascript"
  src="https://elements.reservebar-worker.workers.dev/checkout/elements.js"
></script>
```

This build is tree-shaken and significantly smaller, ideal for dedicated checkout pages.

## NPM Installation

For JavaScript/TypeScript projects using a bundler (Webpack, Rollup, Vite, etc.), install via NPM:

```bash
npm install @liquidcommerce/elements-sdk
```

### Basic Usage

```javascript
import { Elements } from '@liquidcommerce/elements-sdk';

// Initialize the client
const client = await Elements('YOUR_API_KEY', {
  env: 'production'
});

// Client is ready to use
console.log('Elements SDK initialized');
```

### Checkout-Only Import

For tree-shaking benefits in checkout-only scenarios:

```javascript
import { ElementsCheckout } from '@liquidcommerce/elements-sdk/checkout';

const client = await ElementsCheckout('YOUR_API_KEY', {
  env: 'production'
});
```

### TypeScript Support

The SDK includes full TypeScript definitions. Import types as needed:

```typescript
import { Elements } from '@liquidcommerce/elements-sdk';
import type {
  ILiquidCommerceElementsClient,
  ILiquidCommerceElementsConfig,
  IInjectProductElement
} from '@liquidcommerce/elements-sdk';

const config: ILiquidCommerceElementsConfig = {
  env: 'production',
  customTheme: {
    global: {
      theme: {
        primaryColor: '#007bff'
      }
    }
  }
};

const client: ILiquidCommerceElementsClient = await Elements('YOUR_API_KEY', config);
```

## Framework Integration

### React

```jsx
import { Elements } from '@liquidcommerce/elements-sdk';
import { useEffect, useState } from 'react';

function App() {
  const [elementsClient, setElementsClient] = useState(null);

  useEffect(() => {
    async function initElements() {
      const client = await Elements('YOUR_API_KEY', {
        env: 'production'
      });
      setElementsClient(client);
    }
    
    initElements();
  }, []);

  useEffect(() => {
    if (elementsClient) {
      elementsClient.injectProductElement([
        { containerId: 'product-1', identifier: '00619947000020' }
      ]);
    }
  }, [elementsClient]);

  return (
    <div>
      <div id="product-1"></div>
    </div>
  );
}
```

### Vue

```vue
<template>
  <div id="product-1"></div>
</template>

<script>
import { Elements } from '@liquidcommerce/elements-sdk';

export default {
  async mounted() {
    const client = await Elements('YOUR_API_KEY', {
      env: 'production'
    });
    
    await client.injectProductElement([
      { containerId: 'product-1', identifier: '00619947000020' }
    ]);
  }
}
</script>
```

### Next.js

In Next.js, initialize the SDK in a client component:

```jsx
'use client';

import { Elements } from '@liquidcommerce/elements-sdk';
import { useEffect } from 'react';

export default function ProductPage() {
  useEffect(() => {
    async function init() {
      const client = await Elements('YOUR_API_KEY', {
        env: 'production',
        proxy: {
          baseUrl: '/api/elements-proxy'
        }
      });
      
      await client.injectProductElement([
        { containerId: 'product', identifier: '00619947000020' }
      ]);
    }
    
    init();
  }, []);

  return <div id="product"></div>;
}
```

> **Note:** The SDK is SSR-safe. When imported in a Node.js / SSR environment, a lightweight stub is resolved automatically — factory functions return `null` and no browser APIs are accessed. Initialize on the client (e.g., `useEffect`, `onMounted`) to get the real client.

## Configuration Options

The SDK accepts a configuration object during initialization:

```javascript
const client = await Elements('YOUR_API_KEY', {
  env: 'production',           // Required: 'development' | 'staging' | 'production'
  debugMode: 'console',         // Optional: 'none' | 'console' | 'panel'
  customTheme: { /* ... */ },   // Optional: Theme customization
  promoTicker: [ /* ... */ ],   // Optional: Promo ticker configuration
  proxy: { /* ... */ },         // Optional: Proxy configuration
  checkout: { /* ... */ },      // Optional: Checkout configuration
  development: { /* ... */ }    // Optional: Development/testing options
});
```

See [Configuration Reference](../api/configuration.md) for complete configuration options.

## Verification

After installation, verify the SDK is loaded correctly:

### CDN Verification

Open your browser's console and check for:

```javascript
// The client is available globally
console.log(window.LiquidCommerce.elements);
// Should output: { injectProductElement: ƒ, ui: {...}, actions: {...}, ... }
```

### NPM Verification

```javascript
const client = await Elements('YOUR_API_KEY', { env: 'production' });
console.log(client); // Should output the client object
```

## Troubleshooting Installation

### Script Not Loading

If the SDK script fails to load:

1. **Check the network tab** in browser DevTools for 404 or CORS errors
2. **Verify the script URL** is correct and accessible
3. **Check ad blockers** - they may block scripts with "commerce" in the name (see [Proxy Setup](../integration/proxy-setup.md))

### Web Components Not Supported

If you see an error about Web Components:

```
[LiquidCommerce Elements] SDK requires support for Web Components
```

Include a Web Components polyfill before the SDK script:

```html
<script src="https://cdn.jsdelivr.net/npm/@webcomponents/webcomponentsjs@2/webcomponents-bundle.js"></script>
<script defer data-liquid-commerce-elements ...></script>
```

### TypeScript Errors

If you encounter TypeScript errors:

1. Ensure TypeScript version is 4.5 or higher
2. Check that `@liquidcommerce/elements-sdk` is in your `dependencies` (not `devDependencies`)
3. Verify your `tsconfig.json` includes:

```json
{
  "compilerOptions": {
    "moduleResolution": "node",
    "esModuleInterop": true
  }
}
```

## Next Steps

- **Quick Start**: [Build your first product page in 5 minutes](./quick-start.md)
- **Core Concepts**: [Understand how the SDK works](./concepts.md)
- **Component Guides**: [Product](../guides/product-component.md), [Cart](../guides/cart-component.md), [Checkout](../guides/checkout-component.md)
- **API Reference**: [Full API documentation](../api/client.md)
