npm package: @gately/sdk
Description: Gately SDK for authentication, bookmarks, and CMS integration
Author: Gately Team
Latest version: 3.0.0

# @gately/sdk

The official Gately SDK for building authenticated web applications with member management, payments, forms, and more.

[![npm version](https://img.shields.io/npm/v/@gately/sdk.svg)](https://www.npmjs.com/package/@gately/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Installation

```bash
npm install @gately/sdk
# or
yarn add @gately/sdk
# or
pnpm add @gately/sdk
```

## Quick Start

### Get Your API Key

1. Go to your [Gately Dashboard](https://app.usegately.com)
2. Navigate to **Settings → API Keys**
3. Create a new **Public Key** for frontend apps

### React

```tsx
import { GatelyProvider, useGately } from '@gately/sdk';

function App() {
  return (
    <GatelyProvider apiKey="gately_pk_live_xxxxxxxx">
      <MyComponent />
    </GatelyProvider>
  );
}

function MyComponent() {
  const { user, login, logout, loading } = useGately();

  if (loading) return <div>Loading...</div>;

  if (!user) {
    return (
      <button onClick={() => login('user@example.com', 'password')}>
        Login
      </button>
    );
  }

  return (
    <div>
      <p>Welcome, {user.email}!</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
}
```

### Vanilla JavaScript

```html
<script 
  src="https://cdn.usegately.com/gately.min.js" 
  data-api-key="gately_pk_live_xxxxxxxx"
  defer
></script>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const gately = window.Gately;

    // Listen for auth changes
    gately.onAuthStateChange((user, session) => {
      if (user) {
        console.log('Logged in:', user.email);
      } else {
        console.log('Logged out');
      }
    });

    // Login
    gately.login('user@example.com', 'password')
      .then(({ user }) => console.log('Success:', user))
      .catch(err => console.error('Error:', err));
  });
</script>
```

### Node.js (Server-side)

```typescript
import { GatelyNodeClient } from '@gately/sdk/node';

// Use SECRET key for server-side only
const gately = new GatelyNodeClient({
  apiKey: process.env.GATELY_SECRET_KEY // gately_sk_live_xxxxxxxx
});

// Server-side operations
const members = await gately.listMembers();
const user = await gately.verifyToken(token);
```

## API Key Types

| Key Type | Prefix | Usage |
|----------|--------|-------|
| **Public Key** | `gately_pk_` | Browser/frontend apps (safe to expose) |
| **Secret Key** | `gately_sk_` | Server-side only (never expose) |

⚠️ **Never expose secret keys in client-side code.**

## Features

### Authentication

```typescript
import { GatelyClient } from '@gately/sdk';

const gately = new GatelyClient({
  apiKey: 'gately_pk_live_xxxxxxxx'
});

// Email login
await gately.login('user@example.com', 'password');

// Google SSO
await gately.loginWithGoogle({ redirectTo: '/dashboard' });

// Magic link
await gately.sendMagicLink('user@example.com');

// Password reset
await gately.resetPassword('user@example.com');

// Logout
await gately.logout();
```

### User Profiles

```typescript
// Get current user profile
const profile = await gately.getUserProfile();

// Update profile
await gately.updateUserProfile({
  full_name: 'John Doe',
  avatar_url: 'https://...',
  bio: 'Developer'
});

// Change password
await gately.changePassword('oldPassword', 'newPassword');
```

### Member Content Protection

```typescript
// Check if user has access to protected content
const access = await gately.checkMemberContentAccess('/premium-page');

if (!access.hasAccess) {
  console.log('Access denied:', access.reason);
}

// Auto-protect current page
await gately.autoProtectCurrentPage({
  onAccessDenied: (content, reason) => {
    window.location.href = '/login';
  }
});
```

### Payments (Stripe Integration)

```typescript
// Create a payment intent
const { payment_intent } = await gately.createPaymentIntent({
  amount: 2999, // $29.99 in cents
  currency: 'usd',
  description: 'Premium subscription'
});

// Confirm payment
await gately.confirmPaymentIntent(payment_intent.id, {
  payment_method_id: 'pm_...'
});
```

### Forms

```typescript
import { FormEmbed } from '@gately/sdk';

const form = new FormEmbed({
  formId: 'your-form-id',
  containerId: 'form-container',
  onSuccess: (submission) => {
    console.log('Form submitted:', submission);
  }
});
```

### Bookmarks

```typescript
await gately.addBookmark('page-slug');
await gately.removeBookmark('page-slug');
await gately.toggleBookmark('page-slug');
const bookmarks = await gately.getBookmarksByUser();
```

### Chat Widget

```typescript
import { createChatWidget } from '@gately/sdk';

const widget = createChatWidget({
  apiKey: 'gately_pk_live_xxxxxxxx',
  position: 'bottom-right',
  theme: 'light'
});

widget.open();
```

## React Hooks

```typescript
import { 
  useGately,      // Main auth hook
  useAuth,        // Auth state only
  useBookmarks,   // Bookmark management
  useGatelySDK    // Direct SDK access
} from '@gately/sdk';

function Component() {
  const { user, login, logout, loading, error } = useGately();
  const { bookmarks, addBookmark, removeBookmark } = useBookmarks();
  // ...
}
```

## Imports

```typescript
// Main entry (React hooks + browser client)
import { useGately, GatelyProvider, GatelyClient } from '@gately/sdk';

// Browser-specific
import { GatelyBrowserClient } from '@gately/sdk/browser';

// Node.js server
import { GatelyNodeClient } from '@gately/sdk/node';

// Core client (platform-agnostic)
import { GatelyCoreClient } from '@gately/sdk/core';
```

## TypeScript Support

Full TypeScript support with exported types:

```typescript
import type { 
  User,
  Session,
  AuthResponse,
  GatelyOptions,
  UserProfile,
  MemberContent,
  PaymentIntent,
  Form,
  Bookmark
} from '@gately/sdk';
```

## CDN Usage

```html
<!-- Full bundle -->
<script src="https://cdn.usegately.com/gately-full.min.js" data-api-key="YOUR_API_KEY"></script>

<!-- Core only (smaller) -->
<script src="https://cdn.usegately.com/gately.min.js" data-api-key="YOUR_API_KEY"></script>

<!-- Individual modules -->
<script src="https://cdn.usegately.com/gately-auth.min.js"></script>
<script src="https://cdn.usegately.com/gately-forms.min.js"></script>
<script src="https://cdn.usegately.com/gately-payments.min.js"></script>
<script src="https://cdn.usegately.com/gately-chat.min.js"></script>
```

## Configuration

```typescript
const gately = new GatelyClient({
  apiKey: 'gately_pk_live_xxxxxxxx',  // Required
  apiUrl: 'https://api.usegately.com', // Optional: custom API URL
  autoRefresh: true,                   // Optional: auto-refresh sessions
  suppressConsoleErrors: false         // Optional: suppress console errors
});
```

## Documentation

For full documentation, visit [usegately.com/docs](https://usegately.com/docs)

## Support

- 📧 Email: support@usegately.com
- 💬 Discord: [Join our community](https://discord.gg/gately)
- 🐛 Issues: [GitHub Issues](https://github.com/gately/gately-sdk/issues)

## License

MIT © [Gately](https://usegately.com)