npm package: @shopkit/ai-store-builder
Description: AI-powered store builder agent for merchant onboarding and customization
Latest version: 0.1.1

# @shopkit/ai-store-builder

AI-powered store builder agent for merchant onboarding and customization. Built on Claude (Anthropic) with a comprehensive tool system for managing Shopify storefronts.

## Features

- **AI-Powered Agent**: Claude-based agent for natural language store customization
- **Merchant Onboarding**: Scrape existing Shopify stores and migrate to your platform
- **Page Builder Tools**: Add, update, remove sections and widgets
- **Theme Tools**: Customize colors, typography, and spacing
- **Data Tools**: Fetch products and collections from Shopify Storefront API
- **Browser Automation**: Puppeteer-powered scraping with resource pooling
- **Type Safety**: Comprehensive Zod validation for all tool inputs
- **Production Ready**: Race condition prevention, resource cleanup, error handling

## Installation

```bash
bun add @shopkit/ai-store-builder
# or
npm install @shopkit/ai-store-builder
```

### Peer Dependencies

The following peer dependencies are optional depending on your use case:

```bash
# For image optimization during asset migration
bun add sharp

# For S3 asset hosting
bun add @aws-sdk/client-s3

# For Shopify Storefront API integration
bun add @shopkit/data-layer
```

## Quick Start

```typescript
import { StoreAgent, configure } from '@shopkit/ai-store-builder';

// Option 1: Configure programmatically (recommended)
configure({
  anthropic: {
    apiKey: 'sk-ant-xxx',
  },
  shopify: {
    storeDomain: 'mystore.myshopify.com',
    storefrontAccessToken: 'xxx',
  },
  paths: {
    themesBasePath: 'src/themes',
  },
});

// Option 2: Use environment variables (see below)

// Create an agent for a merchant
const agent = new StoreAgent('my-store');

// Chat with the agent
const response = await agent.chat('Add a hero banner section at the top of the homepage');
console.log(response);

// Clean up when done
await agent.dispose();
```

## Configuration

### Programmatic Configuration (Recommended)

The `configure()` function allows you to set all configuration in code, which is more flexible and testable:

```typescript
import { configure, resetConfig } from '@shopkit/ai-store-builder';

configure({
  // Anthropic API settings
  anthropic: {
    apiKey: 'sk-ant-xxx',           // Required
    model: 'claude-sonnet-4-20250514', // Optional (default)
    maxTokens: 4096,                   // Optional (default)
  },

  // Shopify Storefront API settings (for data tools)
  shopify: {
    storeDomain: 'mystore.myshopify.com',  // Required for data tools
    storefrontAccessToken: 'xxx',          // Required for data tools
    apiVersion: '2024-04',                 // Optional (default)
  },

  // File paths
  paths: {
    themesBasePath: 'apps/myapp/src/themes',           // Default: apps/wellversed/src/themes
    widgetsManifestPath: 'apps/myapp/src/widgets/.generated/manifest.ts',
    publicAssetsPath: 'public',                        // Default: public
  },
});

// Reset configuration (useful for testing)
resetConfig();
```

### Environment Variables (Fallback)

If not configured programmatically, the package will fall back to environment variables:

```bash
# Anthropic API
ANTHROPIC_API_KEY=sk-ant-...

# Shopify Storefront API
SHOPIFY_STORE_DOMAIN=mystore.myshopify.com
SHOPIFY_STOREFRONT_ACCESS_TOKEN=xxxxx
SHOPIFY_API_VERSION=2024-04

# File paths
THEMES_BASE_PATH=apps/wellversed/src/themes
WIDGETS_MANIFEST_PATH=apps/wellversed/src/widgets/.generated/manifest.ts
PUBLIC_ASSETS_PATH=public
```

### Configuration Priority

The package checks configuration in this order:
1. Programmatic config via `configure()`
2. Environment variables
3. Default values

### Checking Configuration Status

```typescript
import { isShopifyConfigured, isAnthropicConfigured, getConfig } from '@shopkit/ai-store-builder';

// Check if services are configured
if (!isShopifyConfigured()) {
  console.warn('Shopify not configured - data tools will not work');
}

if (!isAnthropicConfigured()) {
  throw new Error('Anthropic API key required');
}

// Get current config
const config = getConfig();
```

## API Reference

### StoreAgent

The main class for interacting with the AI store builder.

```typescript
import { StoreAgent } from '@shopkit/ai-store-builder';

const agent = new StoreAgent(merchantName?: string, apiKey?: string);

// Send a message and get a response
const response = await agent.chat(message: string);

// Get current state
const state = agent.getState();

// Update state
agent.setState({ merchantName: 'new-name' });

// Set current template being edited
agent.setCurrentTemplate('product'); // 'home' | 'product' | 'collection'

// Get chat history
const history = agent.getChatHistory();

// Clear conversation
agent.clearHistory();

// Check processing status
const isProcessing = agent.isAgentProcessing();

// Clean up resources
await agent.dispose();
```

### BrowserPool

Manages Puppeteer browser instances with automatic cleanup.

```typescript
import { BrowserPool, getBrowserPool, shutdownGlobalPool } from '@shopkit/ai-store-builder';

// Get global singleton pool
const pool = getBrowserPool();

// Or create a custom pool
const customPool = new BrowserPool({
  maxInstances: 3,       // Max concurrent browsers
  acquireTimeout: 30000, // Timeout waiting for browser
  pageTimeout: 30000,    // Default page timeout
});

// Safe browser usage with automatic cleanup
const result = await pool.withBrowser(async (browser) => {
  const page = await browser.newPage();
  await page.goto('https://example.com');
  return await page.content();
});

// Safe page usage with automatic cleanup
const content = await pool.withPage(async (page) => {
  await page.goto('https://example.com');
  return await page.content();
}, { viewport: { width: 1920, height: 1080 } });

// Get pool statistics
const stats = pool.getStats();
// { totalInstances, availableInstances, inUseInstances, waitingRequests }

// Shutdown
await pool.shutdown();         // Graceful
await pool.forceShutdown();    // Immediate
await shutdownGlobalPool();    // Global singleton
```

## Available Tools

The agent has access to 24+ tools organized by category:

### Page Tools
- `add_section` - Add a new section to the page
- `add_widget` - Add a widget to a section
- `update_widget` - Update widget settings
- `remove_widget` - Remove a widget
- `remove_section` - Remove a section
- `reorder_sections` - Change section order
- `move_widget` - Move widget between sections

### Theme Tools
- `update_theme_colors` - Update color tokens
- `update_theme_typography` - Update typography settings
- `update_theme_spacing` - Update spacing values

### Data Tools
- `get_products` - Fetch products from Shopify
- `get_collections` - Fetch collections from Shopify
- `add_data_source` - Add data source to page config

### State Tools
- `get_page_config` - Get current page configuration
- `get_theme_config` - Get current theme configuration
- `list_widgets` - List available widget types
- `save_changes` - Save changes to files

### Browser Tools
- `execute_browser_script` - Run JavaScript in browser context
- `capture_screenshots` - Capture multi-breakpoint screenshots
- `capture_hover_states` - Capture element hover states
- `extract_css_values` - Extract computed CSS values
- `analyze_mobile_menu` - Analyze mobile menu structure

### Onboarding Tools
- `scrape_store` - Scrape existing Shopify store
- `analyze_design` - Analyze scraped design
- `import_products` - Import products via Admin API
- `import_collections` - Import collections via Admin API
- `migrate_assets` - Download and migrate assets
- `create_merchant` - Create merchant folder structure

## Tool Input Validation

All tool inputs are validated using Zod schemas:

```typescript
import { validateToolInput, toolSchemas } from '@shopkit/ai-store-builder';

// Validate input
const result = validateToolInput('add_section', {
  name: 'Hero',
  position: 0,
  layout: 'full',
});

if (result.success) {
  console.log('Valid input:', result.data);
} else {
  console.log('Validation errors:', result.errors);
}

// Access individual schemas
import { addSectionSchema, hexColorSchema } from '@shopkit/ai-store-builder';

const colorResult = hexColorSchema.safeParse('#19a9f0');
```

## Types

```typescript
import type {
  // State types
  MerchantState,
  OnboardingProgress,
  ChatMessage,
  ToolCall,
  ToolResult,

  // Config types
  PageConfig,
  SectionConfig,
  WidgetConfig,
  ThemeConfig,

  // Tool input types
  AddSectionInput,
  AddWidgetInput,
  UpdateThemeColorsInput,
  // ... and more

  // Browser types
  ScreenshotResult,
  HoverStateResult,
  CssValuesResult,

  // Asset types
  ExtractedIcon,
  ExtractedImage,
  AssetExtractionResult,
} from '@shopkit/ai-store-builder';
```

## Example: Complete Page Building Workflow

```typescript
import { StoreAgent } from '@shopkit/ai-store-builder';

async function buildStorePage() {
  const agent = new StoreAgent('my-store');

  try {
    // 1. Set up theme
    await agent.chat(`
      Update the theme colors to:
      - Primary: #19a9f0
      - Secondary: #ff5733
      - Background: #ffffff
    `);

    // 2. Add hero section
    await agent.chat('Add a hero banner section at position 0 with full width layout');

    // 3. Add hero widget
    await agent.chat(`
      Add a HeroBanner widget to the hero section with:
      - Title: "Welcome to Our Store"
      - Subtitle: "Discover amazing products"
      - CTA: "Shop Now"
    `);

    // 4. Add products section
    await agent.chat('Add a Featured Products section below the hero');

    // 5. Add product grid
    await agent.chat(`
      Add a ProductGrid widget to the featured products section
      showing 8 products in a 4-column layout
    `);

    // 6. Save changes
    await agent.chat('Save all changes');

    console.log('Page built successfully!');
  } finally {
    await agent.dispose();
  }
}
```

## Testing

```bash
# Run tests
bun test

# Run with coverage
bun test:coverage

# Run in watch mode
bun test:watch

# Run with UI
bun test:ui
```

## Architecture

```
@shopkit/ai-store-builder/
├── src/
│   ├── agent/
│   │   ├── store-agent.ts      # Main agent class
│   │   ├── system-prompt.ts    # System prompt builder
│   │   └── pixel-perfect-prompt.ts
│   ├── tools/
│   │   ├── index.ts            # Tool registry & executor
│   │   ├── page-tools.ts       # Page modification tools
│   │   ├── theme-tools.ts      # Theme modification tools
│   │   ├── data-tools.ts       # Data fetching tools
│   │   ├── state-tools.ts      # State management tools
│   │   ├── browser-tools.ts    # Browser automation tools
│   │   ├── asset-tools.ts      # Asset extraction tools
│   │   └── onboarding-tools.ts # Onboarding tools
│   ├── services/
│   │   ├── browser-pool.ts     # Browser instance pooling
│   │   └── scraper.ts          # Website scraper
│   ├── types/
│   │   ├── index.ts            # Type definitions
│   │   └── validation.ts       # Zod schemas
│   └── index.ts                # Public exports
```

## License

MIT