# trama-sdk

> The official React SDK for [Trama](https://gotrama.com) — connect any custom React frontend to a Wix, Shopify, or Webflow backend (products, cart, checkout, CMS content, member identity) without migration.

[![npm](https://img.shields.io/npm/v/trama-sdk.svg)](https://www.npmjs.com/package/trama-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)

## Install

```bash
npm install trama-sdk @tanstack/react-query
```

## Quick start

Wrap your app with `TramaProvider` once:

```tsx
// app/layout.tsx (Next.js App Router)
import { TramaProvider } from 'trama-sdk';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <TramaProvider apiKey={process.env.NEXT_PUBLIC_TRAMA_KEY!} projectId="proj_xxx">
      {children}
    </TramaProvider>
  );
}
```

Then use the hooks anywhere:

```tsx
import { useProducts, useCart } from 'trama-sdk';

export default function StorePage() {
  // useProducts wraps TanStack Query, so the array arrives on `data`.
  const { data: products, isLoading } = useProducts({ collectionId: 'featured' });
  const { addItem, goToCheckout } = useCart();

  if (isLoading) return <div>Loading…</div>;

  return (
    <ul>
      {products?.map((p) => (
        <li key={p.id}>
          {p.name} — {p.price.formatted}
          <button onClick={() => addItem(p.id)}>Add to cart</button>
        </li>
      ))}
      <button onClick={goToCheckout}>Checkout →</button>
    </ul>
  );
}
```

## Hooks

| Hook | Purpose |
|---|---|
| `useProducts(options?)` | List products with filters + pagination |
| `useInfiniteProducts(options?)` | Cursor-style infinite list |
| `useProduct(id)` | Fetch a single product |
| `useCollections()` | List all product collections |
| `useCart()` | Cart state + add/remove/update/checkout |
| `useCheckout()` | Programmatic checkout creation |
| `useCmsItems(collectionId)` | Items from a content collection (Webflow CMS, Wix Data, Shopify metaobjects) |
| `useAgencyComponent(name)` | Load an agency-deployed React component bundle |

All hooks are powered by [TanStack Query](https://tanstack.com/query), so they de-duplicate, cache, and refetch on focus by default.

## Content & marketing sites (no storefront required)

Trama isn't commerce-only. If your Webflow/Wix site is a content or marketing
site, the CMS surface is the whole integration:

```ts
import { TramaClient } from 'trama-sdk';

const trama = new TramaClient({ apiKey: process.env.TRAMA_KEY!, projectId: 'proj_xxx' });

// Discover the site's content collections — Webflow CMS collections,
// Wix Data collections, or Shopify metaobject types.
const collections = await trama.getCmsCollections();
// → [{ id: '6512…', name: 'Blog Posts', slug: 'blog-posts' }, …]

// Then fetch items with the hook or the client:
const posts = await trama.request(`/api/v1/cms/collections/${collections[0].id}/items`);
```

## Member identity handoff (gated content)

Verify a platform end-user session against the platform and gate content in
your own backend. Your frontend logs the user in with the **platform's own
auth** (Wix member login, Shopify customer login); your backend forwards the
resulting token to Trama and trusts the verified result:

```ts
// Server-side only — this is where your API key lives.
import { TramaClient } from 'trama-sdk';

const trama = new TramaClient({ apiKey: process.env.TRAMA_KEY!, projectId: 'proj_xxx' });

export async function requireMember(platformToken: string) {
  const member = await trama.verifyMember(platformToken);
  if (!member) throw new Error('Not signed in');       // invalid/expired token
  return member;
  // → { platformId, platform, email, firstName, lastName,
  //     tags: ['vip', 'course-access'], verifiedAt, metadata }
}
```

Notes:

- Verification is **live** — a revoked platform session fails on the next check.
- Shopify customer `tags` come through for tier/entitlement gating.
- Trama is a **verifier, not an identity provider**: the platform stays the
  source of truth for accounts, passwords, and sessions.
- Webflow discontinued its native User Accounts product, so there is no
  platform token to verify — the API returns an explicit 501 with guidance.
  Keep your auth provider (Memberstack, Outseta, your own backend) as the
  identity source; Trama serves the content and commerce data around it.

## Architecture

```
Your React app ─► trama-sdk (this package) ─► Bridge API ─► Wix / Shopify / Webflow backend
```

The SDK is a thin HTTP client + React hooks. **It contains no platform credentials and no business logic.** All intelligence lives behind the Bridge API.

## What it does NOT do

- Bypass the platform's checkout (this would violate platform ToS — `goToCheckout` always redirects to the native checkout).
- Hold tenant secrets — the only secret it knows is your tenant's `tr_live_*` API key, which is rate-limited and rotatable.
- Mutate your backend in destructive ways without explicit calls.

## Versioning

This package follows [SemVer](https://semver.org/). Breaking changes only happen in major versions. See [CHANGELOG.md](./CHANGELOG.md).

## Contributing

This package is open source under MIT. The Bridge API and mapping engine are closed-source.

```bash
git clone https://github.com/gotrama-hq/trama-sdk
cd trama-sdk
pnpm install
pnpm build
```

PRs welcome for: new hooks, bug fixes, types, docs. Please open an issue first for larger changes.

## License

MIT — see [LICENSE](./LICENSE).
