npm package: @onexapis/core
Description: OneX Core - Theme rendering system and registry for building multi-tenant websites with visual editing
Author: OneX Team
Latest version: 1.0.14

# @onex/core

Core package for the OneX theme marketplace - provides types, components, and utilities for building third-party themes.

## Installation

```bash
npm install @onex/core react react-dom
# or
pnpm add @onex/core react react-dom
# or
yarn add @onex/core react react-dom
```

## Quick Start

### For Theme Developers

Create a new theme using `@onex/core`:

```typescript
// src/index.ts
import type { ThemeModule, SectionComponentProps } from "@onex/core"
import { ButtonComponent, Heading } from "@onex/core/client"

// 1. Define your section components
export function HeroMinimal({ section }: SectionComponentProps) {
  return (
    <section className="hero">
      <Heading level={1}>{section.settings.title}</Heading>
      <ButtonComponent href={section.settings.ctaUrl}>
        {section.settings.ctaText}
      </ButtonComponent>
    </section>
  )
}

// 2. Create theme manifest
export const manifest = {
  id: "my-theme",
  name: "My Theme",
  version: "1.0.0",
  author: {
    name: "Your Name",
    email: "you@example.com"
  },
  engine: "^1.0.0",
  peerDependencies: {
    react: "^19.0.0",
    "react-dom": "^19.0.0"
  },
  sections: ["hero-minimal"],
  config: themeConfig,
  exports: {
    main: "./dist/index.mjs"
  }
}

// 3. Export theme module
export const theme: ThemeModule = {
  manifest,
  config: themeConfig,
  sections: {
    "hero-minimal": HeroMinimal
  }
}

export default theme
```

### Build Configuration

Use esbuild with externalized dependencies:

```javascript
// esbuild.config.js
const esbuild = require("esbuild");

esbuild.build({
  entryPoints: ["src/index.ts"],
  bundle: true,
  format: "esm",
  outfile: "dist/index.mjs",
  external: ["@onex/core", "@onex/core/client", "react", "react-dom"],
  minify: true,
  sourcemap: true,
});
```

## Package Exports

### Default Export (`@onex/core`)

```typescript
import { ... } from "@onex/core"
```

Re-exports everything from `@onex/core/client` for convenience.

### Client Export (`@onex/core/client`)

```typescript
import { ... } from "@onex/core/client"
```

Browser-safe exports with `"use client"` directive:

- ✅ All type definitions
- ✅ UI components (Button, Heading, Card, etc.)
- ✅ Rendering engine (SectionRenderer, BlockRenderer, ComponentRenderer)
- ✅ React contexts (ThemeContext, CartContext, ViewportContext, PageDataContext)
- ✅ Utilities (cn, generateId, block-finder, etc.)
- ✅ Registries (SectionRegistry, BlockRegistry, ComponentRegistry)

### Server Export (`@onex/core/server`)

```typescript
import { ... } from "@onex/core/server"
```

Server-only exports:

- ✅ ThemeRegistryManager (uses Node.js fs APIs)
- ✅ All types (re-exported for convenience)

## Available Types

### Theme Contract Types

```typescript
import type {
  ThemeManifest, // Theme metadata
  ThemeModule, // What themes export
  ThemeConfig, // Design tokens
  ThemeUpload, // Upload metadata
} from "@onex/core";
```

### Section Types

```typescript
import type {
  SectionComponentProps, // Props for section components
  SectionInstance, // Section data
  SectionSchema, // Section blueprint
  TemplateDefinition, // Template variant
} from "@onex/core";
```

### Component Types

```typescript
import type {
  ComponentInstance, // Component data
  ComponentDefinition, // Component blueprint
  StyleSettings, // Component styles
} from "@onex/core";
```

### Block Types

```typescript
import type {
  BlockInstance, // Block data (supports nesting)
  BlockDefinition, // Block blueprint
} from "@onex/core";
```

### Validation Types

```typescript
import type {
  ValidationResult, // Validation result
  ValidationError, // Validation error
  ValidationWarning, // Validation warning
} from "@onex/core";
```

## Available Components

35+ pre-built UI components ready to use:

### Layout Components

```typescript
import {
  GridContainer,
  FullWidthSection,
  Container,
  Grid,
  Columns,
} from "@onex/core/client";
```

### Text Components

```typescript
import { Heading, Paragraph, Quote, Badge } from "@onex/core/client";
```

### Interactive Components

```typescript
import { ButtonComponent, Link, Divider, Spacer } from "@onex/core/client";
```

### Media Components

```typescript
import { Image, Icon, Video, Gallery, Map } from "@onex/core/client";
```

### Form Components

```typescript
import { Input, Textarea, Checkbox, Select } from "@onex/core/client";
```

### Advanced Components

```typescript
import {
  Card,
  Alert,
  Accordion,
  Tabs,
  Rating,
  Progress,
  Timer,
  Table,
  Code,
} from "@onex/core/client";
```

## Utilities

### cn() - Class Name Merger

Combines Tailwind CSS classes with proper precedence:

```typescript
import { cn } from "@onex/core/client";

const className = cn(
  "text-base",
  "text-lg", // This wins (last one)
  condition && "font-bold",
  section.settings.customClass
);
```

### generateId() - UUID Generator

```typescript
import { generateId } from "@onex/core/client";

const id = generateId(); // "abc123-def456-..."
```

### Block Finder

Find and update nested blocks:

```typescript
import { findBlockInSection, updateBlockInSection } from "@onex/core/client"

const block = findBlockInSection(section, blockId)
const updated = updateBlockInSection(section, blockId, { settings: {...} })
```

## Contexts

### ThemeContext

Access theme configuration:

```typescript
import { useTheme } from "@onex/core/client"

function MyComponent() {
  const { config } = useTheme()
  return <div style={{ color: config.colors.light.primary }}>...</div>
}
```

### CartContext

Shopping cart state management:

```typescript
import { useCart } from "@onex/core/client"

function AddToCartButton() {
  const { addItem } = useCart()
  return <button onClick={() => addItem(product)}>Add to Cart</button>
}
```

### ViewportContext

Responsive breakpoint detection:

```typescript
import { useViewport } from "@onex/core/client"

function ResponsiveComponent() {
  const { isMobile, isTablet, isDesktop } = useViewport()
  return isMobile ? <MobileView /> : <DesktopView />
}
```

## Theme Development Workflow

1. **Setup**: Install `@onex/core` and create theme structure
2. **Develop**: Create section components using types and UI components
3. **Build**: Bundle with esbuild, externalize `@onex/core`
4. **Validate**: Run `onex theme validate` (CLI coming in Phase 4)
5. **Test**: Test with local storefront instance
6. **Publish**: Upload ZIP to OneX marketplace

## Security Constraints

### v1.0.0 - Static + Runtime Constraints

**Allowed**:

- ✅ Import from `@onex/core`, `react`, `react-dom`
- ✅ Standard JavaScript/TypeScript
- ✅ Tailwind CSS classes
- ✅ Fetch API for CDN resources

**Blocked** (detected via AST validation):

- ❌ `eval()` or `new Function()`
- ❌ Node.js APIs (`fs`, `path`, `child_process`, etc.)
- ❌ Dynamic imports except from CDN
- ❌ Bundle size > 1MB

**Runtime Protection**:

- Error boundaries catch render crashes
- Engine version enforcement
- Limited API surface

⚠️ **Note**: v1 does NOT provide true sandboxing against memory leaks, infinite loops, or network abuse. v2 will add iframe sandbox for stronger isolation.

## Engine Version Compatibility

Specify compatible `@onex/core` versions using semver:

```typescript
{
  "engine": "^1.0.0"  // Compatible with 1.x
}
```

The platform enforces compatibility at runtime:

```typescript
if (!semver.satisfies(platformVersion, theme.engine)) {
  throw new Error("Incompatible theme version");
}
```

## Documentation

- **API Reference**: See [`THEME_API.md`](./THEME_API.md)
- **Type Definitions**: See [`src/types/`](./src/types/)
- **Component Docs**: Coming soon
- **Examples**: See `onex-theme-template` repository

## Development

```bash
# Install dependencies
pnpm install

# Build package
pnpm build

# Watch mode
pnpm dev

# Type check
pnpm type-check

# Run tests
pnpm test
```

## Versioning

This package follows [Semantic Versioning](https://semver.org/):

- **Major** (2.0.0): Breaking changes to public API (`@public` types)
- **Minor** (1.1.0): New features, backward compatible
- **Patch** (1.0.1): Bug fixes, backward compatible

## License

MIT

---

**For theme developers**: Start with the [Theme API Reference](./THEME_API.md) for complete documentation.

**For platform developers**: See internal documentation in `/docs`.