# SlugKit: Full Documentation

> SlugKit generates human-readable, collision-free identifiers from configurable patterns such as {adjective}-{noun}-{number:3d}. It offers a SaaS API and a self-hostable lite build, with deterministic series, slicing, forging, and URL shortening.

---

# Dictionary & Tag Reference (Agent Guide)
Source: https://dev.slugkit.dev/docs/agent-dictionary-and-tag-reference

# SlugKit Dictionary & Tag Reference (Agent Guide)

**Complete guide to SlugKit's word dictionaries, content tags, and filtering strategies.**

## Word Dictionaries Overview

SlugKit provides 6 main word dictionaries with rich tagging for precise content control:

```
📊 Use dictionary_info() to see current word counts
📋 Use dictionary_tags() to see all available tags
```

### Available Dictionaries

| Dictionary | Count | Description | Examples |
|------------|-------|-------------|----------|
| **adjective** | ~17,082 | Descriptive words | fast, brilliant, secure, broken |
| **noun** | ~41,469 | Objects, concepts, people | server, database, user, platform |
| **verb** | ~8,405 | Action words | deploy, connect, analyze, configure |
| **adverb** | ~3,619 | Manner descriptors | quickly, efficiently, securely |
| **domain** | ~9,183 | Internet domains | com, org, tech, dev, aws |
| **shell** | ~2,137 | Command-line tools | git, docker, npm, curl, ssh |

## Tag System

Tags allow precise filtering of word content by theme, emotion, appropriateness, and domain.

### Emotional Tags

Control the emotional tone of generated content:

#### Adjectives & Adverbs
```
+pos    → Positive: amazing, brilliant, secure, fast
+neg    → Negative: broken, failed, slow, unstable  
+emo    → Emotional: passionate, thrilling, devastating
+neut   → Neutral: standard, regular, basic, normal
+det    → Detached: systematic, mechanical, procedural
+obj    → Objective: stable, logical, factual, direct
```

#### Nouns & Verbs
```
+pos    → Positive concepts: success, achievement, growth
+neg    → Negative concepts: failure, error, breakdown
+emo    → Emotional concepts: passion, excitement, fear
+neut   → Neutral concepts: system, process, method
+det    → Detached concepts: mechanism, procedure, protocol
+obj    → Objective concepts: data, analysis, structure
```

### Content Appropriateness

Control content suitability for different audiences:

```
+nsfw   → Not Safe For Work (opt-in only): explicit content
-nsfw   → Exclude NSFW content (recommended for production)
+obj    → Objective, professional tone
```

**⚠️ NSFW Content**: NSFW-tagged words are opt-in only. Use `+nsfw` explicitly to include them.

### Object Categories (Nouns)

#### Main Categories
```
+object   → Physical objects: server, desk, car, building (18,861 words)
+artifact → Human-made items: software, document, tool (6,787 words)
+device   → Electronic devices: phone, laptop, router (1,673 words)
+machine  → Mechanical devices: engine, motor, generator (141 words)
+person   → People: manager, developer, user, admin (6,273 words)
+animal   → Animals: dolphin, eagle, tiger, wolf (2,437 words)
```

#### Specialized Categories
```
+activity → Actions/processes: deployment, analysis, testing (2,663 words)
+event    → Occurrences: meeting, launch, update (6,644 words)
+location → Places: office, warehouse, factory, home (882 words)
+building → Structures: office, warehouse, factory, home (231 words)
+vehicle  → Transportation: car, truck, plane, ship (198 words)
+substance → Materials: metal, wood, plastic, liquid (2,407 words)
+material → Raw materials: steel, concrete, fabric (1,856 words)
+food     → Food items: pizza, coffee, bread, salad (826 words)
+drink    → Beverages: coffee, tea, water, juice (23 words)
+plant    → Flora: tree, flower, grass, leaf (25 words)
+currency → Money/financial: dollar, euro, bitcoin, cash (57 words)
+fantasy  → Fantasy elements: dragon, magic, wizard, quest (59 words)
```

#### Abstract Categories
```
+content  → Information content: article, document, data (1,446 words)
+information → Data/knowledge: facts, statistics, records (133 words)
+concept  → Abstract ideas: theory, principle, philosophy (203 words)
+idea     → Thoughts: concept, notion, plan, strategy (380 words)
+emotion  → Feelings: joy, anger, fear, excitement (229 words)
+feeling  → Sensations: warmth, pain, comfort, tension (683 words)
+music    → Musical terms: song, rhythm, melody, beat (255 words)
+art      → Artistic concepts: painting, sculpture, design (63 words)
+action   → Actions: deployment, execution, processing (1,693 words)
+creation → Created things: product, design, solution (492 words)
+unit     → Measurement units: meter, kilogram, byte (528 words)
+number   → Numeric concepts: count, total, percentage (239 words)
```

#### Technical Categories
```
+chemical → Chemicals: compound, element, solution (904 words)
+drug     → Pharmaceuticals: medicine, treatment, dose (644 words)
+surface  → Surfaces: interface, boundary, layer (128 words)
+furniture → Furniture: desk, chair, table, shelf (107 words)
+situation → Circumstances: context, scenario, case (78 words)
+state    → Conditions: status, mode, phase (4 words)
+shop     → Commercial places: store, market, outlet (38 words)
```

### Action Categories (Verbs)

#### Primary Actions
```
+change   → Transformation: convert, modify, update, evolve (2,583 words)
+act      → Physical actions: run, jump, build, move (1,246 words)
+travel   → Movement: navigate, journey, migrate, explore (463 words)
```

#### State & Possession
```
+be       → State of being: exist, remain, become, stay (215 words)
+have     → Possession: own, contain, include, hold (119 words)
```

#### Creation & Destruction
```
+make     → Creation: build, generate, create, produce (5 words)
+create   → Creative actions: design, compose, invent (2 words)
+become   → Transformation into state: turn, grow, develop (4 words)
+destroy  → Destructive actions: delete, remove, break (29 words)
+take     → Taking actions: grab, acquire, capture (1 word)
+give     → Giving actions: provide, share, offer (1 word)
+imagine  → Mental actions: think, dream, visualize (20 words)
```

### Domain Categories

#### Domains by Type
```
+com      → Commercial domains (.com sites) (989 words)
+org      → Organization domains (.org sites) (175 words)
+net      → Network domains (.net sites) (225 words)
+tld      → Top-level domains: com, org, net, gov (1,281 words)
+sld      → Second-level domains: company, product names (4,853 words)
+sub      → Subdomain parts: www, api, blog, shop (3,049 words)
```

#### Modern Tech Domains
```
+io       → Tech domains (.io sites) (91 words)
+dev      → Developer domains (.dev sites) (62 words)
+app      → Application domains (.app sites) (49 words)
+cloud    → Cloud domains (.cloud sites) (65 words)
+tech     → Technology domains (.tech sites) (2 words)
```

#### Regional Domains
```
+us       → United States domains (.us) (245 words)
+uk       → United Kingdom domains (.uk) (43 words)
+de       → German domains (.de) (76 words)
+jp       → Japanese domains (.jp) (1,890 words)
+au       → Australian domains (.au) (35 words)
+ca       → Canadian domains (.ca) (22 words)
+fr       → French domains (.fr) (33 words)
```

## Tag Filtering Strategies

### Include Multiple Tags
```
{noun:+device+object}         → Technical objects: server, router, database
{adjective:+pos+obj}          → Positive objective terms: excellent, stable, reliable
{verb:+change+act}            → Active transformation verbs: modify, improve, enhance
```

### Exclude Unwanted Content
```
{adjective:-neg-nsfw}         → No negative or NSFW words
{noun:+device-animal}         → Tech devices, but no animals
{verb:-destroy-neg}           → No destructive or negative actions
```

### Complex Combinations
```
{adjective:+pos+obj-emo<8}    → Positive objective adjectives, not emotional, max 7 chars
{noun:+object+device-nsfw>=4} → Tech objects, family-friendly, min 4 chars
{verb:+change+act-destroy}    → Change-related action verbs, not destructive
```

## Content Strategy by Use Case

### Professional/Business Content
```
# Recommended tags
{adjective:+pos+obj-nsfw}     → professional, positive, appropriate
{noun:+device+artifact-nsfw}  → business/tech focused, clean
{verb:+change+act-destroy}    → constructive actions only

# Example pattern
"{adjective:+pos+obj} {noun:+device} {verb:+change} {adverb:+pos}"
→ "secure platform deploys efficiently"
```

### Family-Friendly Content
```
# Always exclude NSFW
{adjective:-nsfw+pos}         → positive, clean adjectives
{noun:+animal+object-nsfw}    → animals and objects, family-safe
{verb:+act+change-destroy-nsfw} → constructive, clean verbs

# Example pattern  
"{adjective:+pos-nsfw} {noun:+animal-nsfw} {verb:+act-nsfw}"
→ "happy dolphin jumps"
```

### Technical Documentation
```
# Focus on objective, technical terms
{adjective:+obj-emo}          → objective, unemotional
{noun:+device+object+artifact} → tech equipment and systems  
{verb:+change+act}            → technical operations

# Example pattern
"{verb:+change} {adjective:+obj} {noun:+device}"
→ "configure secure server"
```

### Creative/Marketing Content
```
# Allow emotional, positive language
{adjective:+pos+emo}          → exciting, emotional positivity
{noun:+concept+idea+object}   → broad creative concepts
{verb:+create+act+change}     → dynamic, creative actions

# Example pattern
"The {adjective:+pos+emo} {noun:+concept} will {verb:+create} {adjective:+pos} {noun:+object}"
→ "The amazing platform will generate brilliant solutions"
```

### Gaming/Fantasy Content
```
# Include fantasy and creative elements
{adjective:+pos+emo}          → dramatic, positive descriptors
{noun:+fantasy+animal+person} → fantasy characters and creatures
{verb:+act+imagine+destroy}   → dramatic fantasy actions

# Example pattern
"{adjective:+pos} {noun:+fantasy} {verb:+act} the {adjective:+neg} {noun:+fantasy}"
→ "Mighty wizard defeats the evil dragon"
```

## Language Support

### Current Language Tags
```
@en    → English (default)
@es    → Spanish (if available)
@fr    → French (if available)  
@de    → German (if available)
```

**Note**: Language support varies by dictionary. Use `dictionary_info()` to check availability.

### Usage Examples
```
{adjective@en}-{noun@en}      → Force English words
{noun@es} and {noun@fr}       → Mix Spanish and French
{adjective}-{noun}[@de]       → German words globally
```

## Best Practices

### Production Applications
1. **Always exclude NSFW**: Use `-nsfw` in all patterns
2. **Use positive/neutral tone**: `+pos` or `+neut` for user-facing content
3. **Be specific with categories**: `+device` for technical contexts, `+person` for user references
4. **Control length**: Use length constraints for UI/database limits

### Testing & Development  
1. **Use diverse tags**: Test with different emotional tones
2. **Include edge cases**: Try `+neg` content for error scenarios
3. **Validate thoroughly**: Check capacity impact of tag combinations
4. **Consider caching**: Tag filtering can impact performance

### Content Strategy
1. **Match your audience**: Family-friendly vs. professional vs. technical
2. **Consistent theming**: Use global settings for pattern-wide consistency
3. **Cultural sensitivity**: Consider international audiences with language tags
4. **Brand alignment**: Choose tags that match your brand voice

## Advanced Tag Techniques

### Tag Hierarchies
Some tags work better together:
```
+device+obj      → Technical devices, objective (great for APIs)
+pos+person      → Positive people language (user-friendly)
+change+act      → Dynamic transformation language
+animal+fantasy  → Mythical creatures and magical animals
```

### Performance Considerations
```
# More specific = better performance
{noun:+device+object<8}       → Highly filtered, fast
{noun}                        → Broad selection, slower with large sets
{noun:+animal+fantasy+emo}    → Multiple tags, moderate performance
```

### Capacity Impact
```
# Check capacity before using
validate_pattern("{noun:+device}")   → Smaller subset (1,673 words)
validate_pattern("{noun}")           → Full dictionary (41,469 words)
validate_pattern("{noun:+fantasy}")  → Very specific (59 words)
```

## Real Examples with Actual Tags

### ✅ Working Examples
```
// Valid adjective tags
{adjective:+pos}    → positive words (710 available)
{adjective:+obj}    → objective words (8,382 available)
{adjective:+neg}    → negative words (1,395 available)

// Valid noun tags  
{noun:+device}      → devices (1,673 available)
{noun:+person}      → people (6,273 available)
{noun:+animal}      → animals (2,437 available)
{noun:+object}      → objects (18,861 available)

// Valid verb tags
{verb:+change}      → change actions (2,583 available)
{verb:+act}         → general actions (1,246 available)

// Valid domain tags
{domain:+com}       → .com domains (989 available)
{domain:+tld}       → top-level domains (1,281 available)
```

### ❌ Common Invalid Tags
```
// These DON'T exist - will cause errors
{adjective:+tech}     → ❌ No tech tag for adjectives
{noun:+tech}          → ❌ No tech tag for nouns  
{adjective:+business} → ❌ No business tag
{verb:+tech}          → ❌ No tech tag for verbs
{noun:+professional}  → ❌ No professional tag
{adjective:+security} → ❌ No security tag
```

## Tag Availability Summary

### Adjectives (7 tags total)
- `det` (14,138 words) - Detached/analytical
- `obj` (8,382 words) - Objective  
- `neut` (6,595 words) - Neutral
- `emo` (2,944 words) - Emotional
- `neg` (1,395 words) - Negative
- `pos` (710 words) - Positive
- `nsfw` (35 words) - Not safe for work

### Nouns (44 tags total)
Most useful:
- `object` (18,861) - General objects
- `det` (39,391) - Detached concepts
- `obj` (26,812) - Objective things
- `artifact` (6,787) - Human-made items
- `event` (6,644) - Events/occurrences
- `person` (6,273) - People and roles
- `activity` (2,663) - Activities
- `animal` (2,437) - Animals
- `substance` (2,407) - Materials
- `material` (1,856) - Raw materials
- `action` (1,693) - Actions
- `device` (1,673) - Electronic devices
- `content` (1,446) - Information content

### Verbs (17 tags total)
Most useful:
- `det` (8,172) - Detached actions
- `obj` (5,689) - Objective actions  
- `neut` (2,597) - Neutral actions
- `change` (2,583) - Change actions
- `act` (1,246) - Physical actions
- `travel` (463) - Movement
- `emo` (233) - Emotional actions
- `be` (215) - State of being

### Domains (195+ tags)
Including country codes, TLDs, and special categories like `com`, `org`, `tld`, `dev`, `io`, etc.

## Pattern Testing Examples

Test these working patterns:

```
// Simple professional patterns
validate_pattern("{adjective:+pos}-{noun:+device}")
forge("{adjective:+pos}-{noun:+device}", count=3)
→ ["amazing-server", "brilliant-database", "excellent-platform"]

// User-friendly IDs  
validate_pattern("{adjective:+pos}-{noun:+animal}-{number:3d}")
forge("{adjective:+pos}-{noun:+animal}-{number:3d}", count=3)
→ ["happy-dolphin-142", "smart-eagle-738", "bright-tiger-395"]

// Technical naming
validate_pattern("{noun:+device}-{adjective:+obj}-{number:2x}")
forge("{noun:+device}-{adjective:+obj}-{number:2x}", count=3)
→ ["server-stable-a3", "database-secure-f7", "router-direct-2c"]

// Domain examples
validate_pattern("{adjective:+pos}.{domain:+tld}")
forge("{adjective:+pos}.{domain:+tld}", count=3)
→ ["amazing.com", "brilliant.org", "excellent.net"]
```

---

**💡 Key Takeaways:**
- **Always use `dictionary_tags()` first** to see what's actually available
- **Most "expected" tags don't exist** - SlugKit has a specific, limited set
- **Focus on emotional tags** (`+pos`, `+neg`, `+obj`) and category tags (`+device`, `+person`, `+animal`)
- **Test patterns before using** with `validate_pattern()` 
- **Start simple** and add constraints gradually
- **The documentation had many invalid examples** - always verify against the actual API

Use `dictionary_info()` and `dictionary_tags()` as your source of truth, not documentation examples!

---

# Pattern Examples by Use Case (Agent Guide)
Source: https://dev.slugkit.dev/docs/agent-pattern-examples

# SlugKit Pattern Examples by Use Case (Agent Guide)

## Web Development

### URL Slugs
```
// Blog posts
"{adjective:+pos}-{noun}-{number:4d}"
→ "amazing-tutorial-2024"

// Product pages  
"{adjective:<8}-{noun:+device}-{verb:<6}"
→ "smart-server-deploy"

// Category slugs
"{adjective:+pos}/{noun:+object}"
→ "advanced/database"
```

### User Handles & IDs
```
// Readable user handles
"{adjective:<7}{noun:<8}{number:2d}"
→ "smartuser42"

// Anonymous usernames
"{adjective:+pos}-{noun:+animal}-{number:3d}"
→ "happy-dolphin-127"

// API keys (readable part)
"{adjective}-{noun}-{number:4x}"
→ "secure-token-a1b2"
```

### CSS & JavaScript
```
// CSS class names
"{adjective:<6}-{noun:<8}-component"
→ "smart-button-component"

// JavaScript variables
"{verb}<6{Noun}<8Config"
→ "loadButtonConfig"

// Component names
"{Adjective}{Noun}Widget"
→ "SmartDatabaseWidget"
```

### API Endpoints
```
// RESTful endpoints
"/api/{noun:+person}/{adjective:<6}-{noun:<8}/{number:4d}"
→ "/api/users/active-sessions/2024"

// Webhook URLs
"/hooks/{adjective:+pos}-{noun}/{number:8x}"
→ "/hooks/secure-payment/a1b2c3d4"
```

## DevOps & Infrastructure

### Server & Service Naming
```
// Server hostnames
"{adjective:+obj}<6-{noun:+device}<8-{number:2d}"
→ "prod-database-01"

// Kubernetes pods
"{noun:+device}-{adjective}-{number:4x}"
→ "webapp-stable-f3a7"

// Docker containers
"{adjective:+pos}/{noun:+artifact}:{number:1d}.{number:1d}"
→ "stable/webapp:2.1"
```

### Environment & Configuration
```
// Environment names
"{ADJECTIVE:+obj}_{NOUN}_ENV"
→ "STABLE_DATABASE_ENV"

// Config files
"{noun:<8}-{adjective:+obj}.{domain:+tld}"
→ "database-secure.conf"

// Backup naming
"backup-{noun:+device}-{number:2d}{number:2d}{number:4d}-{number:4x}"
→ "backup-postgres-31122024-a1f3"
```

### Monitoring & Logging
```
// Log files
"{noun:+device}-{adjective:+obj}-{number:2d}{number:2d}.log"
→ "webapp-error-1225.log"

// Metric names
"{noun:+device}.{adjective}.{verb}.count"
→ "database.active.connections.count"

// Alert names
"{ADJECTIVE:+neg} {NOUN:+device} {verb:+neg}"
→ "CRITICAL DATABASE FAILURE"
```

## Database & Data

### Table & Column Names
```
// Table names
"{noun:+device}_{adjective:+obj}"
→ "users_active"

// Column identifiers  
"{noun:<8}_{verb:<6}_at"
→ "account_created_at"

// Index names
"idx_{noun:+device}_{adjective:+obj}_{number:2d}"
→ "idx_users_active_01"
```

### Test Data Generation
```
// User emails
"{adjective:<7}.{noun:<8}@{noun:<6}.{domain:+com}"
→ "smart.database@test.com"

// Phone numbers (template)
"+1-{number:3d}-{number:3d}-{number:4d}"
→ "+1-555-123-4567"

// Addresses
"{number:3d} {Adjective} {Noun} Street"
→ "123 Smart Database Street"
```

### Database Seeding
```
// Company names
"{Adjective} {Noun} {noun:+artifact}"
→ "Smart Database Solutions"

// Product names
"{adjective:+pos} {noun:+device} {number:1d}.{number:1d}"
→ "Amazing Platform 2.1"

// Department codes
"{ADJECTIVE:<4}_{NOUN:+device:<6}"
→ "PROD_WEBAPP"
```

## Testing & QA

### Test Case IDs
```
// Test identifiers
"test_{noun:+device}_{verb}_{number:3d}"
→ "test_database_connect_042"

// Scenario names
"Given {adjective} {noun}, when {verb}, then {verb}"
→ "Given active user, when login, then succeed"

// Mock data labels
"{adjective:+pos}_{noun:+device}_{number:2d}"
→ "valid_account_01"
```

### Performance Testing
```
// Load test names
"load_{noun:+device}_{number:3d}_{adjective:+obj}"
→ "load_api_100_concurrent"

// Benchmark IDs
"bench_{verb}_{noun:+device}_{number:4x}"
→ "bench_query_database_a1f3"
```

### Error Simulation
```
// Error messages
"Error {number:3d}: {adjective:+neg} {noun:+device} {verb:+neg}"
→ "Error 500: broken database connection failed"

// Exception names
"{Adjective}{Noun}Exception"
→ "InvalidDatabaseException"

// Failure scenarios
"{noun:+device} {verb:+neg} after {number:2d} {noun:+event}"
→ "connection timeout after 30 seconds"
```

## Documentation & Content

### Technical Writing
```
// Guide titles
"## {Adjective:+pos} {Noun} Guide"
→ "## Complete Database Guide"

// Tutorial steps
"Step {number:1d}: {Verb} the {noun:+device}"
→ "Step 3: Configure the server"

// Code examples
"// {Adjective} {noun:+device} implementation"
→ "// Simple database implementation"
```

### Blog & Marketing
```
// Article titles
"How to {verb} {adjective:+pos} {noun:+artifact} in {number:2d} minutes"
→ "How to deploy amazing applications in 15 minutes"

// Social media
"{Adjective:+pos} {noun:+device}! {verb:+pos} your {noun} {adverb:+pos} 🚀"
→ "Amazing platform! Scale your business efficiently 🚀"

// Newsletter subjects
"{Adjective:+pos} {noun}: {verb:+pos} {number:2d}% {adjective:+pos}"
→ "Weekly Update: Boost 25% performance"
```

## Gaming & Entertainment

### Character & World Generation
```
// Character names
"{adjective:+pos} {noun:+person} the {adjective:+pos}"
→ "Mighty Warrior the Brave"

// Location names
"The {adjective:+pos} {noun:+location} of {noun:+fantasy}"
→ "The Ancient Castle of Dragons"

// Item names
"{adjective:+pos} {noun:+fantasy} of {noun:+concept}"
→ "Legendary Sword of Power"
```

### Game Development
```
// Asset names
"{adjective}_{noun:+object}_{number:3d}"
→ "rusty_sword_042"

// Level identifiers
"level_{number:2d}_{adjective:+neg}_{noun:+location}"
→ "level_05_hard_dungeon"

// Achievement names
"{adjective:+pos} {noun:+action}"
→ "Ultimate Victory"
```

## E-commerce & Business

### Product Management
```
// SKUs
"{adjective:<4}-{noun:+artifact}<6-{number:4d}"
→ "FAST-LAPTOP-2024"

// Inventory codes
"{ADJECTIVE:+obj:<4}_{NOUN:<6}_{NUMBER:6x}"
→ "STABLE_SERVER_A1B2C3"

// Coupon codes
"{adjective:+pos}{number:2d}{adjective:+obj}"
→ "SAVE25STABLE"
```

### Customer Service
```
// Ticket IDs
"TKT-{adjective:+obj}-{number:6d}"
→ "TKT-URGENT-123456"

// Case numbers
"{noun:+device}-{number:4d}-{adjective:+pos}"
→ "BILLING-4567-HIGH"

// Reference codes
"REF_{ADJECTIVE:<4}_{NUMBER:8x}"
→ "REF_HELP_A1B2C3D4"
```

## Security & Authentication

### Access Control
```
// Permission names
"{verb}_{noun:+device}_{adjective:+obj}"
→ "read_database_secure"

// Role identifiers
"{adjective:+obj}_{noun:+person}"
→ "admin_user"

// Session tokens (readable part)
"sess_{adjective:+obj}_{number:8x}"
→ "sess_secure_a1b2c3d4"
```

### Audit & Compliance
```
// Log entries
"[{number:2d}/{number:2d}/{number:4d}] {ADJECTIVE} {noun:+device} {verb:+neg}"
→ "[31/12/2024] FAILED database authentication"

// Compliance codes
"{ADJECTIVE:+obj}_{NOUN:+device}_{NUMBER:4d}"
→ "GDPR_DATA_2024"
```

## Advanced Pattern Techniques

### Multi-line Templates
```
"version: {number:1d}.{number:1d}.{number:2d}
name: {adjective}-{noun}
description: {adjective:+pos} {noun:+device} for {verb}<6
maintainer: {Noun:+person} Team
status: {adjective:+obj}"

→ "version: 2.1.15
name: secure-platform
description: amazing solution for deploy
maintainer: Engineering Team  
status: stable"
```

### Conditional-like Patterns with Global Settings
```
// All positive objective terms
"{noun} {verb} {adjective} {noun}[+pos+obj]"
→ "platform deploys amazing solution"

// German terms (if supported)
"{noun} {verb} {noun}[@de+obj]"
→ "Datenbank verwendet System"

// Short positive terms
"{adjective} {noun} {verb}[+pos<6]"
→ "smart system works"
```

### Complex Casing Scenarios
```
// PascalCase components
"{Adjective}{Noun}{Verb}Component"
→ "SmartDatabaseQueryComponent"

// snake_case variables
"{adjective}_{noun}_{verb}_config"
→ "secure_database_connect_config"

// SCREAMING_SNAKE_CASE constants
"{ADJECTIVE}_{NOUN}_{NUMBER:4d}"
→ "MAX_DATABASE_1000"

// Mixed enterprise naming
"{AdJeCtIvE}_{nOuN}_v{NUMBER:1d}"
→ "SmArT_sErVeR_v2"
```

## Performance & Capacity Planning

### High-Volume Patterns (Large Capacity)
```
// Billions of combinations
"{adjective}-{noun}-{number:6x}"
→ Capacity: ~17,000 × 41,000 = 11+ trillion combinations

// Moderate capacity with constraints
"{adjective:<6}-{noun:+device<8}-{number:3d}"  
→ More manageable capacity with better performance
```

### Low-Volume Patterns (Specific Use Cases)
```
// Limited but meaningful
"{adjective:+pos<5}-{noun:+device==4}-{number:2d}"
→ Fewer combinations, highly constrained output
```

### Capacity Impact Examples
```
// Standard casing
"{noun}-{adjective}" 
→ ~708M combinations

// Mixed casing (capacity multiplier)
"{NoUn}-{AdJeCtIvE}"
→ Exponentially more combinations (2^8 × 708M+)
```

---

**Pro Tips:**
- Use `validate_pattern()` to check capacity before generation
- Combine `dictionary_info()` and `dictionary_tags()` to understand available words  
- Test patterns with small `count` values first
- Consider length constraints for UI/database field limits
- Use global settings for consistent theming across complex patterns

---

# Pattern Syntax Reference (Agent Guide)
Source: https://dev.slugkit.dev/docs/agent-pattern-syntax-reference

# SlugKit Pattern Syntax Reference (Agent Guide)

## Overview

SlugKit patterns are powerful template strings that can generate anything from simple slugs to complex structured text. Patterns combine **placeholders** (words in curly braces) with **arbitrary literal text** including whitespace, punctuation, and complete sentences.

## Basic Structure [^1]

```ebnf
pattern := ARBITRARY, { placeholder, ARBITRARY }, [ global_settings ]
```

**Key Principle**: Any text outside placeholders is preserved exactly as written.

- **ARBITRARY**: Any text except `{`, `}`, `\` (unless escaped)
- **placeholder**: Word generators in `{}`
- **global_settings**: Pattern-wide settings in `[]`

## Placeholders

### Basic Syntax
```ebnf
placeholder := '{' (selector | number_gen | special_char_gen) '}'
selector    := kind ['@' lang] [':', [tags] [length_constraint] [options]]
```

Three types of placeholders:
1. **Word selectors**: `{adjective}`, `{noun}`, etc. [^2]
2. **Number generators**: `{number:4d}`, `{number:3x}`
3. **Special character generators**: `{special:2}`, `{special:1-4}`

### Word Types
| Type | Description | Examples |
|------|-------------|----------|
| `{adjective}` | Descriptive words | fast, brilliant, complex |
| `{noun}` | Objects, concepts, people | server, database, manager |
| `{verb}` | Action words | deploy, analyze, configure |
| `{adverb}` | Manner descriptors | quickly, efficiently, carefully |
| `{domain}` | Internet domains | com, org, tech, dev |
| `{shell}` | Command-line tools | git, docker, npm, curl |

### Casing Control
The case of the dictionary name controls the output casing:

```
{noun}     → lowercase: "server"
{NOUN}     → UPPERCASE: "SERVER" 
{Noun}     → Title Case: "Server"
{nOuN}     → Mixed case following pattern: "SeRvEr"
```

**Impact on Capacity**: Mixed casing dramatically increases pattern capacity as all possible case combinations are generated. Capacity calculation for mixed case patterns is not yet fully implemented.

Examples:
```
{adjective}-{NOUN}     → "fast-SERVER"
{Verb} the {noun}      → "Deploy the database"  
{AdJeCtIvE} {nOuN}     → "FaSt sErVeR"
```

### Constraints (Inside Braces)

**Important**: For word selectors, constraints must follow this exact order:
```
{word_type:tags length_constraints options}
```

#### Tag Filters [^2]
```ebnf
tags        := (include_tag | exclude_tag)*
include_tag := '+' tag
exclude_tag := '-' tag
```

```
{adjective:+pos}               // Include positive words
{noun:-nsfw}                   // Exclude NSFW words
{adjective:+obj-neg}           // Include objective, exclude negative
{noun:+animal+object}          // Include both animal and object tags
```

**Tag syntax**: Tags are identifiers (letters, numbers, underscores). Multiple tags can be combined with `+` for inclusion and `-` for exclusion.

**Available Tags by Category:**

**Adjectives:**
- **Emotional**: `+pos`, `+neg`, `+emo`, `+neut`
- **Content**: `+obj`, `+det`
- **Content Warning**: `+nsfw` (opt-in)

**Nouns:**
- **Objects**: `+object`, `+artifact`, `+device`, `+machine`
- **Living**: `+person`, `+animal`
- **Places**: `+location`, `+building`
- **Abstract**: `+concept`, `+idea`, `+emotion`, `+feeling`
- **Activities**: `+activity`, `+action`, `+event`
- **Substances**: `+substance`, `+material`, `+chemical`, `+drug`, `+food`, `+drink`
- **Content**: `+content`, `+information`, `+music`, `+art`
- **Fantasy**: `+fantasy` (59 words available)
- **Other**: `+creation`, `+unit`, `+number`, `+currency`, `+plant`, `+state`, `+shop`

**Verbs:**
- **Types**: `+change`, `+act`, `+travel`, `+be`, `+have`, `+make`, `+become`, `+create`, `+take`, `+give`
- **Actions**: `+destroy`, `+imagine`

**Domains:**
- **Common TLDs**: `+com`, `+org`, `+net`, `+tld`
- **Tech**: `+dev`, `+io`, `+app`, `+cloud`, `+tech`
- **Geographic**: Country codes like `+us`, `+uk`, `+de`, etc.

#### Length Constraints
```ebnf
length_constraint := comparison_op length
comparison_op     := '==' | '!=' | '<' | '<=' | '>' | '>='
```

```
{word:<8}      // Maximum 7 characters (less than 8)
{word:>3}      // Minimum 4 characters (greater than 3)
{word:<=6}     // 6 characters or fewer  
{word:>=4}     // 4 characters or more
{word:==5}     // Exactly 5 characters
{word:!=7}     // Not 7 characters
```

**Note**: `<8` means "less than 8", so max 7 characters. `>3` means "greater than 3", so min 4 characters.

#### Options
```ebnf
options      := option (',' option)*
option       := identifier '=' option_value
option_value := tag | number
```

⚠️ **Note**: Options are currently not supported and are reserved for future releases.

Options will provide additional configuration for word selectors:
```
{noun:option1=value1,option2=value2}    // Future functionality
```

#### Combined Constraints
Currently supported constraints must be in the exact order: **tags → length** (options reserved for future)
```
{adjective:+pos<6}              // ✅ Correct: tags first, then length
{noun:+device-nsfw>=4}          // ✅ Correct: tags, then length  
{verb:<8+act}                   // ❌ Wrong: length before tags
{noun:>=4+animal}               // ❌ Wrong: length before tags
{adjective:+pos<6,opt=val}      // ❌ Not yet supported: options
```

### Number Generators
```ebnf
number_gen := 'number' ':' length [(',' number_base) | number_base_short]
```

```
{number:3d}     // 3-digit decimal: 123
{number:4x}     // 4-digit lowercase hex: a1b2  
{number:4X}     // 4-digit uppercase hex: A1B2
{number:2r}     // 2-character lowercase Roman: ii
{number:3R}     // 3-character uppercase Roman: XII
```

**Long form with comma**:
```
{number:3,dec}   // Same as {number:3d}
{number:4,hex}   // Same as {number:4x}
{number:2,HEX}   // Same as {number:2X}
{number:3,roman} // Same as {number:3r}
{number:2,ROMAN} // Same as {number:2R}
```

**Supported bases**: `dec`, `hex`, `HEX`, `roman`, `ROMAN`

### Special Character Generators
```ebnf
special_char_gen := 'special' [':' number ['-' length]]
```

```
{special}        // Single special character: @
{special:2}      // Exactly 2 special characters: @#
{special:1-4}    // 1 to 4 special characters: &!@
```

### Global Settings
```ebnf
global_settings := '[' ['@' lang] [tags] [length_constraint] [options] ']'
```

Apply settings to ALL placeholders in the pattern:
```
{adjective}-{noun}[@en:+pos-nsfw<6]
{verb} {noun} {adverb}[+obj>=4]
```

**Components**:
- `@en` - Language for all word selectors
- `+pos-nsfw` - Include positive, exclude NSFW for all words  
- `<6` - Maximum 5 characters for all words (< 6)
- Options apply to all compatible placeholders

**Note**: Global settings don't affect number or special character generators, only word selectors.

## Escaping

```ebnf
ESCAPED_CHAR  := escape_symbol ('{' | '}' | escape_symbol)
escape_symbol := '\'
```

Use backslash `\` to include literal braces and backslashes:
```
\{            // Literal { character
\}            // Literal } character  
\\            // Literal \ character
```

Examples:
```
"The \{system\} uses {noun}"     → "The {system} uses database"
"Path: C:\\{noun}\\file"         → "Path: C:\server\file"  
"Price: \$\{number:2d\}"         → "Price: ${42}"
```

**Important**: Only `{`, `}`, and `\` need escaping. All other characters are literal.

## Pattern Examples

### Simple Slugs
```
{adjective}-{noun}                    → "fast-server"
{adjective:<6}-{noun:<8}-{number:3d}  → "quick-database-127"  
{verb:>=5}-{noun:+device}             → "deploy-microservice"
```

### Natural Language
```
"The {adjective:+pos} {noun:+animal} {verb} {adverb}"
→ "The brilliant cat leaps gracefully"

"Error {number:3d}: {ADJECTIVE} {NOUN} could not {verb} the {Noun}"  
→ "Error 404: BROKEN CONNECTION could not reach the Server"
```

### Structured Templates
```
"server_name: {adjective}-{noun}
port: {number:4d}
debug: {adjective:+obj}"

→ "server_name: fast-proxy
port: 8080
debug: verbose"
```

### Command-Line Examples
```
"git {verb:<6} {adjective}-{noun}-{number:4x}"
→ "git commit feature-auth-a1b2"

"docker run -p {number:4d}:{number:4d} {adjective}/{noun}"
→ "docker run -p 8080:3000 stable/webapp"
```

### Email Addresses
```
"{adjective:<6}.{noun:<8}@{noun:<6}.{domain:+com}"
→ "smart.database@tech.com"
```

### Configuration Files
```
"[database]
host = {noun:<8}.local
port = {number:4d}
timeout = {number:2d}s
ssl = {adjective:+obj}"

→ "[database]
host = postgres.local  
port = 5432
timeout = 30s
ssl = enabled"
```

## Best Practices

### 1. Always Validate First
```
Use validate_pattern() before forge(), mint(), or other operations
```

### 2. Use Length Constraints for Predictable Output
```
{noun:<8}-{adjective:<6}    // Bounded length (max 7 + max 5 + 1 = 13 chars)
vs
{noun}-{adjective}          // Variable length (could be very long)
```

**Remember**: `<8` means "less than 8", so maximum 7 characters.

### 3. Apply Appropriate Tags
```
{adjective:+pos}-{noun:+device}     // Positive words with device nouns
{noun:+animal}-{verb:+act}          // Animal action combinations
```

### 4. Leverage Global Settings for Consistency
```
{adjective}-{noun}-{verb}[+obj<8]   // All objective words, max 7 chars (< 8)
{noun} and {noun}[@en:>=4]          // English words, min 4 chars
```

### 5. Consider Your Use Case
- **Slugs**: Short, constrained patterns
- **Sentences**: Natural language with appropriate tags
- **Templates**: Mix literals with strategic placeholders
- **Commands**: Realistic tool names and parameters

## Common Patterns

### Web Development
```
"{adjective}-{noun}-api"              → "fast-user-api"
"{NOUN:<6}-v{number:1d}.{number:1d}"  → "WEBAPP-v2.1"  
"{Adjective}{Noun}Service"            → "FastUserService"
```

### DevOps
```
"deploy {Noun} to {adjective}-env"           → "deploy Service to staging-env"
"backup-{noun}-{number:2d}{number:2d}{number:4d}" → "backup-db-15122024"
"{ADJECTIVE}_{NOUN}_CONFIG"                  → "STABLE_DATABASE_CONFIG"
```

### Testing Data
```
"user_{number:4d}@{noun}.{domain:+com}"     → "user_1234@test.com"
"The {Adjective} test {verb} {adverb}"      → "The Comprehensive test passes successfully"
"{FirstName} {LastName}"                    → "Smart Database" (using mixed casing)
```

### Documentation
```
"## {adjective:+pos} {noun} Guide
This {noun} will help you {verb} {adverb}."

→ "## Comprehensive Database Guide
This tutorial will help you deploy efficiently."
```

## Error Prevention

### Common Mistakes
```
❌ {adjective}<8      // Length constraint outside braces (becomes literal "<8")
✅ {adjective:<8}     // Correct: constraint inside braces

❌ {noun}+device      // Tag outside braces (becomes literal "+device")  
✅ {noun:+device}     // Correct: tag inside braces

❌ {adjective:+tech}  // Non-existent tag
✅ {adjective:+obj}   // Valid tag
```

### Validation Tips
- Constraints go INSIDE braces: `{word:constraint}`
- Arbitrary text goes OUTSIDE braces: `{word} literal text`
- Use `validate_pattern()` to verify syntax and see capacity
- Use `dictionary_tags()` to see available tag filters
- Use `dictionary_info()` to understand word categories

## Advanced Features

### Language Selection
```
{adjective@en}-{noun@en}    // Force English words
{noun@es}-{verb@fr}         // Mix languages (if supported)  
{noun}[@de]                 // German words globally
```

### Complex Filtering
```
{adjective:+pos+obj-nsfw<6>=3}    // Positive objective adjectives, 3-5 chars
{noun:+animal+fantasy!=5}         // Animal/fantasy nouns, not exactly 5 chars
{verb:+act<=8,option1=value}      // Action verbs, max 8 chars, with future option
```

### Sequence Control  
When using forge() with `sequence` parameter for number generators:
```
{number:3d} generates 3-digit zero-padded numbers in pseudorandom sequence
sequence=0   → 383, 766, 149, 532, 915...
sequence=100 → 630, 664, 498, 322, 15...
sequence=1000 → 383, 766, 149... (same as sequence=0 due to wrapping)
```

**Wrapping**: Sequence values wrap at the generator's capacity (e.g., 1000 for 3-digit decimals). So `sequence=1000` equals `sequence=0` for `{number:3d}`.

## Available Tags Reference

Use `dictionary_tags()` to get the complete, up-to-date list. Here are the main categories:

### Adjectives (7 tags)
- `pos` (710 words) - Positive words
- `neg` (1,395 words) - Negative words  
- `obj` (8,382 words) - Objective words
- `det` (14,138 words) - Detached words
- `neut` (6,595 words) - Neutral words
- `emo` (2,944 words) - Emotional words
- `nsfw` (35 words) - Not safe for work (opt-in)

### Nouns (44 tags)
Most commonly used:
- `object` (18,861 words) - General objects
- `device` (1,673 words) - Technical devices  
- `artifact` (6,787 words) - Man-made objects
- `person` (6,273 words) - People and roles
- `animal` (2,437 words) - Animals
- `location` (882 words) - Places
- `fantasy` (59 words) - Fantasy terms

### Verbs (17 tags) 
- `change` (2,583 words) - Change actions
- `act` (1,246 words) - General actions
- `travel` (463 words) - Movement
- And more...

### Domains (195+ tags)
- Common: `com`, `org`, `net`, `tld`  
- Tech: `dev`, `io`, `app`, `cloud`, `tech`
- Geographic: `us`, `uk`, `de`, `jp`, etc.

---

[^1]: *For formal grammar specification, see the EBNF grammar documentation.*
[^2]: *For complete available word types and tags, use `dictionary_info()` and `dictionary_tags()`.*

---

# SlugKit Quick Start Guide (Agent Guide)
Source: https://dev.slugkit.dev/docs/agent-quick-start-guide

# SlugKit Quick Start Guide (Agent Guide)

**Get started with SlugKit in 5 minutes for AI agents! Generate human-readable IDs, slugs, and structured content.**

## Step 1: Check Your Access (30 seconds)

Before you begin, verify your API key and subscription limits:

```
📋 Use: limits()
→ Shows your organization's features and quotas
→ Missing fields = feature unavailable
→ -1 = unlimited

📋 Use: key_info()
→ Shows your API key capabilities and scopes
```

**Example:**
```
limits()
→ {
  "forge_enabled": true,
  "max_forge_per_request": 100,
  "mint_enabled": true,
  "series_create": true,
  ...
}
```

## Step 2: Understand the Basics (30 seconds)

SlugKit uses **patterns** - templates with placeholders that generate random but readable content:

```
{adjective}-{noun}           → "fast-server"
{verb} {adjective} {noun}    → "deploy amazing platform" 
Error {number:3d}: {noun}    → "Error 404: database"
```

**Key Point**: Anything outside `{}` is kept exactly as written. Anything inside `{}` gets replaced.

## Step 3: Validate Your First Pattern (1 minute)

**Before creating a pattern** always start your session with obtaining actual available dictionary and tag data (`dictionary_info()`, `dictionary_tags()`)
**Always start with validation** to check syntax and see what you'll get:

```
📚 Use: validate_pattern(pattern)
```

**Try these examples:**

```
✅ validate_pattern("{adjective}-{noun}")
→ Capacity: 708M combinations, max length: 55 chars

✅ validate_pattern("user-{number:4d}@example.com") 
→ Capacity: 10K combinations, max length: 25 chars

❌ validate_pattern("{adjective<6}-{noun}")
→ Invalid: constraints go INSIDE braces after a colon: {adjective:<6}
```

**Advanced Analysis:**

```
🔍 Use: analyze_pattern(pattern)
→ Detailed breakdown of pattern complexity, capacity, and components

🔍 Use: compare_patterns([pattern1, pattern2, ...])
→ Side-by-side comparison with sample outputs
```

## Step 4: Generate Content (2 minutes)

### Option A: Custom Generation (`forge`)
Perfect for one-off generation or custom patterns:

```
🔨 forge(pattern, count=5, seed="test")
```

**Examples:**
```
forge("{adjective}-{noun}", count=3, seed="demo")
→ ["smart-server", "fast-database", "secure-platform"]

forge("deploy {noun} to {adjective} environment", count=2)
→ ["deploy webapp to staging environment", "deploy api to production environment"]
```

### Option B: Series Generation (`mint`)
Perfect for production apps needing guaranteed unique IDs:

```
⚡ mint(count=5, series_slug="your-series")
```

**First, check available series:**
```
series_list()
→ {"hotly-curly-gouge-d4ac": "Production IDs", "wanly-final-adobo-b55f": "Test IDs", ...}

series_info("hotly-curly-gouge-d4ac")  
→ Pattern: "{adjective:<8}-{noun:<8}-{number:3d}"
→ Capacity: 38.8 billion combinations
→ Generated: 1,234 IDs
```

**Then mint from series:**
```
mint(count=3, series_slug="hotly-curly-gouge-d4ac")
→ ["soupy-stoop-142", "bobtail-ousting-083", "imposed-gramps-024"]
```

**Preview before minting:**
```
slice(count=3, series_slug="hotly-curly-gouge-d4ac")
→ Preview what the next 3 IDs would be without consuming them
```

## Step 5: Manage Series (1 minute)

### Create a New Series
```
✨ series_create(name="Production User IDs", pattern="{adjective}-{noun}-{number:4d}")
→ Creates a new series with the specified pattern
→ Returns series slug for future use
```

### Update Existing Series
```
🔄 series_update(series_slug="your-series", name="New Name", pattern="{new}-{pattern}")
→ Updates series (only if not locked)
→ Fails safely if series is in use
```

### Delete Series
```
🗑️ series_delete(series_slug="your-series")
→ Deletes series and all associated API keys
→ Use with caution!
```

## Step 6: Essential Pattern Syntax (2 minutes)

### Basic Placeholders
```
{adjective}    → descriptive words: fast, smart, secure
{noun}         → things: server, database, user  
{verb}         → actions: deploy, connect, analyze
{number:4d}    → 4-digit numbers: 0123, 5678, 9999
```

### Control Output Length
```
{adjective:<8}     → max 7 chars (< 8): "smart", "secure"
{noun:>=4}         → min 4 chars: "server", "platform" 
{noun:==5}         → exactly 5 chars: "users", "login"
```

### Filter by Theme
```
{adjective:+pos}      → positive words: amazing, brilliant
{noun:+device}        → device words: server, database, API
{adjective:+obj-neg}  → objective words, not negative
```

### Control Casing
```
{noun}      → lowercase: "server"
{NOUN}      → UPPERCASE: "SERVER"  
{Noun}      → Title Case: "Server"
{nOuN}      → Mixed case: "SeRvEr"
```

## Step 7: Your First Real Patterns

### Web Development
```
// URL slugs
forge("{adjective:+pos}-{noun:+device}-{number:4d}", count=3)
→ ["amazing-platform-2024", "brilliant-server-1847", "smart-database-9032"]

// API endpoints  
forge("/api/{noun:+person}/{adjective:<6}-{noun:+object}", count=2)
→ ["/api/users/active-session", "/api/data/secure-token"]
```

### User-Friendly IDs
```
// Customer support tickets
forge("TKT-{adjective:+pos}-{number:6d}", count=3, seed="support")
→ ["TKT-amazing-123456", "TKT-brilliant-789012", "TKT-smart-345678"]

// Readable user handles
forge("{adjective:+pos}<6{noun:+animal}<8", count=3)  
→ ["smart<6dolphin<8", "happy<6eagle<8", "bright<6tiger<8"]
```

### Configuration & DevOps
```
// Server names
forge("{adjective:+obj}<6-{noun:+device}<8-{number:2d}", count=3)
→ ["stable<6-database<8-01", "secure<6-webapp<8-02", "active<6-cache<8-03"]

// Environment variables
forge("{ADJECTIVE:+obj}_{NOUN:+device}_CONFIG", count=2)
→ ["STABLE_DATABASE_CONFIG", "SECURE_WEBAPP_CONFIG"]
```

## Common Mistakes to Avoid

### ❌ Wrong Constraint Placement
```
{adjective}<8          → This adds literal "<8" text
{adjective:+obj<8+pos} → Wrong order: length before tags
```

### ✅ Correct Syntax
```
{adjective:<8}         → Correct: max 7 characters  
{adjective:+obj+pos<8} → Correct: tags first, then length
```

### ❌ Using Non-Existent Tags
```
{adjective:+tech}      → Invalid: +tech tag doesn't exist for adjectives
{noun:+professional}   → Invalid: +professional tag doesn't exist
```

### ✅ Use Valid Tags
```
{adjective:+pos}       → Valid: positive adjectives
{adjective:+obj}       → Valid: objective adjectives  
{noun:+device}         → Valid: device nouns
{noun:+artifact}       → Valid: artifact nouns
```

### ❌ Forgetting Validation
```
forge("{adjective-noun}")  → Invalid syntax, will error
```

### ✅ Always Validate First
```
validate_pattern("{adjective}-{noun}")  → Check first!
forge("{adjective}-{noun}")             → Then generate
```

## Next Steps

### Explore Available Words
```
dictionary_info()    → See all word types (adjective, noun, verb, etc.)
dictionary_tags()    → See all available tags (+pos, +obj, +animal, etc.)
```

### Preview Before Using Series
```
slice(count=5, series_slug="your-series")  → Preview without consuming
mint(count=5, series_slug="your-series")   → Actually generate and consume
```

### Check Performance
```
series_info("your-series")  → See capacity and current usage
```

## Advanced Quick Examples

### Multi-line Templates
```
pattern = """server: {adjective:+obj}-{noun:+device}
port: {number:4d}  
status: {adjective:+pos}
debug: {adjective:+obj}"""

forge(pattern, count=1)
→ ["server: secure-database\nport: 5432\nstatus: amazing\ndebug: stable"]
```

### Mixed Casing for Code
```
// PascalCase components
forge("{Adjective}{Noun}Component", count=2)
→ ["SmartDatabaseComponent", "FastServerComponent"]

// camelCase variables  
forge("{adjective}{Noun}Config", count=2)
→ ["smartDatabaseConfig", "fastServerConfig"]
```

### Natural Language
```
forge("The {adjective:+pos} {noun:+animal} {verb} over the {adjective} {noun}", count=2)
→ ["The brilliant dolphin leaps over the rusty fence", 
   "The amazing eagle soars over the broken tower"]
```

## Available Tags Quick Reference

### Adjectives
- `+pos` - Positive words (amazing, brilliant, smart)
- `+neg` - Negative words (broken, failed, error)
- `+obj` - Objective words (stable, secure, active)
- `+det` - Detached words (analytical, systematic)
- `+neut` - Neutral words (standard, normal, basic)
- `+emo` - Emotional words (excited, worried, happy)

### Nouns  
- `+object` - General objects (18K words)
- `+device` - Technical devices (1.6K words)
- `+artifact` - Man-made objects (6.7K words)
- `+person` - People and roles (6.2K words)
- `+animal` - Animals (2.4K words)
- `+location` - Places (880 words)
- `+fantasy` - Fantasy terms (59 words)

### Verbs
- `+change` - Change actions (deploy, update, modify)
- `+act` - General actions (run, execute, process)
- `+travel` - Movement (navigate, move, flow)

### Domains
- `+com` - .com domains
- `+org` - .org domains
- `+tld` - Top-level domains
- `+dev` - .dev domains
- `+io` - .io domains

Use `dictionary_tags()` for the complete list!

## Essential Commands Summary

```
# Check access and limits
limits()                         # See your subscription features
key_info()                       # See your API key details

# Pattern development
validate_pattern("{your-pattern}")        # Check syntax
analyze_pattern("{your-pattern}")         # Detailed analysis
compare_patterns(["{p1}", "{p2}"])        # Compare options

# Generate custom content  
forge("{pattern}", count=N, seed="optional")

# Manage series
series_list()                    # See available series
series_create(name, pattern)     # Create new series
series_info("series-slug")       # Check series details  
series_update(slug, name, pattern)  # Update series
series_delete("series-slug")     # Delete series

# Use series for unique IDs
slice(count=N, series_slug="name")    # Preview
mint(count=N, series_slug="name")     # Generate unique IDs

# Understand your options
dictionary_info()                # Available word types
dictionary_tags(kind="noun")     # Available tag filters for a kind
```

**You're ready! Start with simple patterns like `{adjective}-{noun}` and gradually add constraints and complexity as needed.**

---
📚 **Full Documentation**: Use `get_help_topic("pattern-syntax-reference")` for complete syntax guide
🎯 **More Examples**: Use `get_help_topic("pattern-examples")` for use-case specific patterns

---

# API Authentication
Source: https://dev.slugkit.dev/docs/api-authentication

# Authentication

Secure your SlugKit API requests with API keys or SDK-based signature authentication. This guide covers everything you need to authenticate successfully and follow security best practices.

## Overview

SlugKit requires authentication for all API requests to:
- **Track usage and enforce quotas** based on your subscription tier
- **Secure your organisation's data** and series configurations
- **Enable rate limiting** to ensure fair resource allocation
- **Provide audit trails** for generated identifiers

SlugKit offers two authentication methods optimised for different environments:

**API Keys** are traditional secret tokens used for server-side applications, CLI tools, and backend services. They're available starting from the Free tier and provide straightforward bearer-token authentication.

**SDK Keys** use signature-based authentication designed for client-side applications like browsers and mobile apps. The TypeScript SDK handles the complex signing process automatically. SDK keys are available on paid tiers - see the [feature matrix](/products/feature-matrix) for availability.

## Authentication Methods

### API Keys (Server-Side)

API keys are secret tokens that identify your application and authorise access to SlugKit's API. They're designed for server-to-server communication where the key can be kept secure.

**Use API keys for:**
- Backend services and APIs
- Server-side scripts and automation
- CLI tools and development workflows
- Any environment where secrets can be securely stored

**Availability:** Free tier and above

API keys are passed using the `X-API-Key` header:

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

### SDK Keys (Client-Side Signature-Based)

SDK keys use cryptographic signatures to authenticate requests without exposing secret credentials in client-side code. Each request is signed with headers that prove authenticity without transmitting the private key.

**Use SDK keys for:**
- Browser-based single-page applications
- Mobile applications (iOS, Android, React Native)
- Desktop applications with embedded browsers
- Any client-side environment

**Availability:** Paid tiers - see [feature matrix](/products/feature-matrix) for details

The TypeScript SDK automatically handles signature generation. **Implementation is handled entirely by the SDK** - you don't need to manually generate signatures. See the [TypeScript SDK documentation](sdk-typescript-installation) for setup and usage.

## Understanding Key Scopes

SlugKit API keys can be scoped to different levels of your organisation, providing flexibility and security through the principle of least privilege.

### Organisation-Scoped Keys

Organisation-scoped keys can access **all series** within your organisation. They provide maximum flexibility but require careful handling.

**Managed at:** Dashboard → Organisation → API Keys

**When to use:**
- Applications that work with multiple series
- Administrative tools and dashboards
- Development and testing across different series
- Centralised slug generation services

**Important:** When using organisation-scoped keys with series-specific operations (mint, slice, reset), you **must include the series slug** in your request.

### Series-Scoped Keys

Series-scoped keys are restricted to a **single series**, making them more secure for focused use cases.

**Managed at:** Dashboard → Organisation → [Series Name] → API Keys

**When to use:**
- Production applications with single-purpose identifier needs
- Microservices focused on specific domains
- Third-party integrations with limited scope
- Maximum security through restricted access

**Benefit:** No need to specify `series_slug` in requests - the key automatically targets its associated series.

For a deeper understanding of organisations and series, see [Core Concepts](developer-core-concepts).

## API Key Permissions (Scopes)

Each API key can be granted specific permissions that control which operations it can perform. These scopes provide fine-grained access control based on your application's needs.

### Generation Scopes

**forge** - Generate custom slugs with explicit pattern control
- **Use cases:** Marketing campaigns, themed content, reproducible testing
- **Required for:** `/api/v1/gen/forge` and `/api/v1/gen/forge/stream` endpoints
- **Series required:** No - works without any series

**mint** - Generate guaranteed unique slugs from series
- **Use cases:** User handles, product IDs, order numbers, any uniqueness-critical identifiers
- **Required for:** `/api/v1/gen/mint` and `/api/v1/gen/mint/stream` endpoints
- **Series required:** Yes (unless using series-scoped key)

**slice** - Preview series slugs without consuming them
- **Use cases:** Testing, staging previews, distributed coordination, planning
- **Required for:** `/api/v1/gen/slice` and `/api/v1/gen/slice/stream` endpoints
- **Series required:** Yes (unless using series-scoped key)

### Administrative Scopes

**stats** - Access statistics, limits, and key information
- **Use cases:** Monitoring, analytics, capacity planning, debugging
- **Required for:** `/api/v1/gen/stats/latest`, `/api/v1/key-info`, `/api/v1/limits` endpoints
- **Series required:** Optional (provide for series-specific stats)

**reset** - Reset series counters ⚠️ **Destructive Operation**
- **Use cases:** Development environment resets, recovery operations, pattern updates
- **Required for:** `/api/v1/gen/reset` endpoint
- **Series required:** Yes (unless using series-scoped key)
- **Warning:** Can cause duplicate identifiers if misused

### Series Management Scopes

**series:read** - Read series information and list available series
- **Use cases:** Application initialisation, monitoring, configuration discovery
- **Required for:** `/api/v1/gen/series` (GET), `/api/v1/gen/series-info` endpoints
- **Availability:** Organisation-scoped keys only

**series:create** - Create new series
- **Use cases:** Application setup, dynamic series creation, CI/CD pipelines
- **Required for:** `/api/v1/gen/series` (POST) endpoint
- **Availability:** Organisation-scoped keys only

**series:update** - Modify existing series configuration
- **Use cases:** Pattern updates, capacity increases, name changes
- **Required for:** `/api/v1/gen/series` (PUT) endpoint
- **Availability:** Organisation-scoped keys only
- **Limitation:** Series must be unlocked (reset if needed)

**series:delete** - Permanently remove series ⚠️ **Irreversible Operation**
- **Use cases:** Cleanup, decommissioning, security incidents
- **Required for:** `/api/v1/gen/series` (DELETE) endpoint
- **Availability:** Organisation-scoped keys only
- **Warning:** Invalidates all series-scoped keys for that series

### Scope Combinations and Best Practices

**Development Keys:**
```
Recommended scopes: ["forge", "mint", "slice", "stats", "series:read", "series:create"]
Use case: Full development and testing capabilities
Environment: Development, staging
```

**Production Application Keys:**
```
Recommended scopes: ["mint", "slice", "stats"]
Use case: Live application slug generation
Environment: Production
```

**Analytics/Monitoring Keys:**
```
Recommended scopes: ["stats", "series:read"]
Use case: Monitoring dashboards, capacity planning
Environment: All environments
```

**Administrative Keys:**
```
Recommended scopes: ["forge", "mint", "slice", "stats", "reset", "series:read", "series:update"]
Use case: Emergency operations, maintenance
Environment: Production (restricted access)
```

**CI/CD Pipeline Keys:**
```
Recommended scopes: ["stats", "series:read", "series:create", "reset"]
Use case: Automated deployment, environment setup
Environment: All environments
```

## Getting Your First API Key

### For Free Tier Users

API keys are available starting from the Free tier. Follow these steps to create your first key:

1. **Log in** to your SlugKit dashboard at https://slugkit.com/dashboard
2. **Navigate** to Dashboard → Organisation
3. **Click** "Create API Key" or "New API Key"
4. **Configure** your key:
   - **Name:** Choose a descriptive name (e.g., "Production Backend", "Development CLI")
   - **Permissions:** Select the operations you need (forge, mint, slice, reset)
   - **Scope:** Organisation-wide access
5. **Create** and immediately **copy your key** - it will only be shown once
6. **Store securely** using environment variables or a secrets manager

### For Developer Tier and Above

With paid tiers, you can create both organisation-scoped and series-scoped keys:

**Organisation-Scoped Keys:**
- Navigate to Dashboard → Organisation → API Keys
- Follow the same creation process as above

**Series-Scoped Keys:**
- Navigate to Dashboard → Organisation → [Your Series] → API Keys
- Create keys limited to that specific series
- Benefit from automatic series context in requests

### SDK Keys (Paid Tiers)

SDK keys for signature-based authentication are configured differently:

1. Navigate to Dashboard → Organisation → SDK Configuration
2. Create an SDK configuration with a unique slug
3. The TypeScript SDK will use this slug to fetch signing keys
4. See [TypeScript SDK Installation](sdk-typescript-installation) for integration details

**Availability:** See [feature matrix](/products/feature-matrix) for tier availability

## Making Authenticated Requests

### Basic Examples

**Generate custom slugs without a series:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

**Mint with organisation-scoped key (specify series):**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "user-handles", "count": 10}'
```

**Mint with series-scoped key (automatic targeting):**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_series_xyz789..." \
  -H "Content-Type: application/json" \
  -d '{"count": 10}'
```

For complete API documentation and all endpoint examples, see the [API Reference](api-reference).

## Series Management

Series CRUD operations (create, read, update, delete) are available through both the REST API and SDKs. For detailed examples and programmatic series management, see the [Python SDK API Reference](sdk-python-api-reference).

**Available operations:**
- **List series** - Get all series in your organisation
- **Get series info** - Detailed information about a specific series
- **Create series** - Add new series with patterns
- **Update series** - Modify existing series configuration
- **Delete series** - Permanently remove series
- **Reset series** - Clear series counters

**Required scopes:** `series:read`, `series:create`, `series:update`, `series:delete`, `reset`

## Inspecting Your Key

Use the `/api/v1/key-info` endpoint to check your current key's configuration and permissions:

```bash
curl -X GET https://api.slugkit.com/api/v1/key-info \
  -H "X-API-Key: sk_live_abc123..."
```

**Response for Organisation-Scoped Key:**
```json
{
  "key_type": "api-key",
  "key_scope": "org",
  "slug": "production-backend",
  "org_slug": "my-organisation",
  "series_slug": null,
  "scopes": ["forge", "mint", "slice", "stats"],
  "enabled": true
}
```

**Response Fields:**
- **key_type:** `api-key` or `sdk-key`
- **key_scope:** `org` (organisation-scoped) or `series` (series-scoped)
- **slug:** Your key's identifier
- **org_slug:** Your organisation identifier
- **series_slug:** Target series (null for org-scoped keys)
- **scopes:** Permitted operations (forge, mint, slice, reset, stats, series:*)
- **enabled:** Whether the key is currently active

Use this endpoint to debug authentication issues, verify key permissions, confirm series targeting, and check if a key is still enabled.

## Security Best Practices

### ⚠️ CRITICAL: Never Expose API Keys in Client-Side Code

**API keys are secret credentials** that must never be embedded in client-side applications. Exposing keys in browsers or mobile apps allows anyone to use your quota, access your series, and potentially exhaust your rate limits.

**Never include API keys in:**
- Frontend JavaScript bundles or source code
- Mobile application binaries (iOS, Android, React Native)
- Public Git repositories or version control
- Client-side configuration files
- Browser localStorage or sessionStorage
- URLs or query parameters
- HTML source code or inline scripts

**For client-side applications, always use SDK keys** with signature-based authentication instead. The TypeScript SDK ensures private keys never leave your build environment.

### General Security Practices

**Environment Variables**

Store API keys in environment variables, never in code:

```bash
# .env file (never commit this)
SLUGKIT_API_KEY=sk_live_abc123...

# Use in your application
const apiKey = process.env.SLUGKIT_API_KEY;
```

**Secrets Managers**

For production systems, use dedicated secrets management:
- AWS Secrets Manager
- HashiCorp Vault
- Google Cloud Secret Manager
- Azure Key Vault
- Kubernetes Secrets

**Key Rotation**

Rotate API keys regularly to minimise exposure risk:
- **Development keys:** Rotate monthly
- **Production keys:** Rotate quarterly
- **After security incidents:** Rotate immediately
- **When team members leave:** Rotate within 24 hours

**Principle of Least Privilege**

Grant only the permissions each key needs:
- Use series-scoped keys when accessing a single series
- Avoid granting `reset` permission unless absolutely necessary
- Don't grant series management scopes unless required
- Create separate keys for different applications or environments
- Use read-only permissions (slice, stats) for analytics tools

**Revoke Compromised Keys Immediately**

If a key is exposed:
1. **Revoke** the compromised key in your dashboard immediately
2. **Create** a new key with the same permissions
3. **Update** your application with the new key
4. **Investigate** how the exposure occurred
5. **Review** access logs for unauthorised usage

**Version Control Hygiene**

Never commit secrets to version control:
- Add `.env` and secret files to `.gitignore`
- Use environment-specific configuration
- Scan repositories for accidentally committed secrets
- Use pre-commit hooks to catch secrets before they're committed

**IP Allowlisting (Enterprise)**

Enterprise plans may offer IP allowlisting for additional security:
- Restrict API key usage to specific IP ranges
- Limit access to your VPN or office networks
- Add deployment server IPs to allowlists
- Contact support for IP allowlisting setup

## SDK Keys for Client-Side Applications

For browser and mobile applications, SDK keys provide secure authentication without exposing secret credentials. The TypeScript SDK handles all complexity automatically.

### How SDK Keys Work

Instead of sending a secret API key with each request, SDK keys use:
1. **Public/private key pairs** stored securely during build time
2. **Request signatures** generated on-the-fly for each API call
3. **Timestamp validation** to prevent replay attacks
4. **SDK slug identification** to link requests to your configuration

The private key signs each request but never leaves your build environment. The SlugKit API verifies signatures using your public key.

### Setting Up SDK Keys

1. **Create an SDK configuration** in Dashboard → Organisation → SDK Configuration
2. **Choose a unique slug** for your SDK config (e.g., "web-app-prod")
3. **Install the TypeScript SDK** in your project
4. **Configure the SDK** with your slug
5. **Deploy** - the SDK handles authentication automatically

### Integration Example

```typescript
import { SlugKitClient } from '@slugkit/typescript-sdk';

const client = new SlugKitClient({
  sdkSlug: 'web-app-prod'
});

// The SDK automatically signs all requests
const slugs = await client.mint({
  seriesSlug: 'user-handles',
  count: 10
});
```

### When to Use SDK Keys

**Perfect for:**
- React, Vue, Angular, and other frontend frameworks
- Progressive web applications (PWAs)
- Mobile apps built with React Native, Flutter, or native code
- Electron and desktop applications
- Any client-side environment

**Availability:** See [feature matrix](/products/feature-matrix) for tier availability

**Learn more:**
- [TypeScript SDK Installation](sdk-typescript-installation)
- [Browser Usage Guide](sdk-typescript-browser)
- [React Integration](sdk-typescript-react)

## Common Issues & Troubleshooting

### 401 Unauthorised

**Possible causes:**
- Missing `X-API-Key` header
- Invalid API key format
- Expired or revoked key
- Key from different environment (test key on production)

**Solutions:**
- Verify your key is correctly formatted (starts with `sk_live_` or `sk_test_`)
- Check that the key is enabled in your dashboard
- Ensure you're using the correct environment's base URL
- Confirm the `X-API-Key` header is being sent

### 403 Forbidden

**Possible causes:**
- Valid key but insufficient permissions for the operation
- Attempting to access a series outside your organisation
- Using a series-scoped key with a different series
- Operation not allowed on your subscription tier

**Solutions:**
- Check your key's permissions using `/api/v1/key-info`
- Verify you're accessing a series within your organisation
- Ensure series-scoped keys match the target series
- Review your subscription tier's feature access

### 429 Too Many Requests

**Possible causes:**
- Exceeded your subscription tier's rate limits
- Too many requests in a short time window
- Burst capacity exhausted

**Solutions:**
- Check rate limit headers in the response: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
- Implement exponential backoff in your retry logic
- Consider upgrading your subscription tier for higher limits
- See [Rate Limits & Quotas](api-rate-limits) for tier-specific limits

### CORS Errors (Browser Applications)

**Possible causes:**
- Attempting to use API keys from browser JavaScript
- Missing CORS configuration
- Wrong authentication method for client-side code

**Solutions:**
- **Never use API keys in browsers** - switch to SDK keys
- SDK keys are designed for client-side use with proper CORS support
- See [TypeScript Browser Guide](sdk-typescript-browser) for correct setup
- Check browser console for specific CORS error messages

### Missing series_slug Parameter

**Possible causes:**
- Using organisation-scoped key without specifying target series
- Forgetting to include `series_slug` in mint/slice/reset requests

**Solutions:**
- Always include `series_slug` when using org-scoped keys for mint/slice/reset
- Or use series-scoped keys for automatic series targeting
- Forge requests never require `series_slug`

## Next Steps

Now that you understand authentication, explore how to generate slugs:

**Learn Generation Methods:**
- [Choosing Between Forge, Mint, and Slice](choosing-generation-method) - Decision guide for selecting the right operation
- [Core Concepts](developer-core-concepts) - Understand patterns, series, and uniqueness guarantees

**API Endpoints:**
- [API Reference](api-reference) - Complete endpoint documentation with scope requirements
- [Rate Limits & Quotas](api-rate-limits) - Understanding tier-specific limits
- [Error Handling](api-error-handling) - Comprehensive error handling guide

**SDK Integration:**
- [Python SDK Quickstart](sdk-python-quickstart) - Server-side Python integration
- [Python SDK API Reference](sdk-python-api-reference) - Complete Python SDK documentation including series management
- [TypeScript SDK Installation](sdk-typescript-installation) - Client and server TypeScript setup
- [React Integration](sdk-typescript-react) - Using SlugKit in React applications

**Advanced Topics:**
- [Pattern Language Basics](pattern-syntax-basics) - Master SlugKit's pattern system
- [Advanced Pattern Features](pattern-advanced-features) - Complex filtering and transformations

---

# Error Handling
Source: https://dev.slugkit.dev/docs/api-error-handling

# Error Handling

*Comprehensive guide to understanding, handling, and debugging SlugKit API errors*

---

## Overview

SlugKit provides structured error responses with detailed information to help you handle failures gracefully and debug issues effectively. This guide covers common error scenarios, response formats, retry strategies, and best practices for production applications.

## Error Response Format

All SlugKit API errors follow a consistent JSON structure:

### Standard Error Response
```json
{
  "error": "error_type",
  "message": "Human-readable error description",
  "details": {
    "field": "parameter_name",
    "value": "invalid_value",
    "constraint": "validation_rule"
  }
}
```

### Response Fields
- **error**: Machine-readable error type for programmatic handling
- **message**: Human-readable description suitable for logging or user display
- **details**: Additional context specific to the error type (optional)

## HTTP Status Codes

SlugKit uses standard HTTP status codes with specific meanings:

### 2xx Success
- **200 OK**: Request successful, response contains data
- **201 Created**: Resource created successfully (mint operations)

### 4xx Client Errors
- **400 Bad Request**: Invalid request parameters or malformed data
- **401 Unauthorized**: Missing or invalid authentication
- **403 Forbidden**: Valid authentication but insufficient permissions
- **404 Not Found**: Requested resource (series, organisation) doesn't exist
- **416 Range Not Satisfiable**: Slice window exceeded
- **429 Too Many Requests**: Rate limit or quota exceeded

### 5xx Server Errors
- **500 Internal Server Error**: Unexpected server-side issue
- **502 Bad Gateway**: Upstream service unavailable
- **503 Service Unavailable**: Temporary service maintenance
- **504 Gateway Timeout**: Request timeout

## Common Error Types

### Authentication Errors (401)

**Missing API Key:**
```json
{
  "error": "unauthorized",
  "message": "API key missing or invalid"
}
```

**Invalid API Key Format:**
```json
{
  "error": "unauthorized", 
  "message": "Invalid API key format",
  "details": {
    "expected_format": "sk_live_* or sk_test_*"
  }
}
```

**Expired or Revoked Key:**
```json
{
  "error": "unauthorized",
  "message": "API key has been revoked or expired"
}
```

### Permission Errors (403)

**Insufficient Scopes:**
```json
{
  "error": "insufficient_scope",
  "message": "API key does not have 'mint' scope",
  "required_scopes": ["mint"]
}
```

**Series Access Denied:**
```json
{
  "error": "access_denied",
  "message": "Cannot access series outside your organisation",
  "details": {
    "series_slug": "unauthorized-series",
    "your_org": "your-organisation"
  }
}
```

**Plan Limitation:**
```json
{
  "error": "plan_limitation",
  "message": "Forge operations not available on Free plan",
  "upgrade_suggestion": "Upgrade to Developer plan for forge access"
}
```

### Validation Errors (400)

**Missing Required Parameters:**
```json
{
  "error": "validation_error",
  "message": "Missing required parameter 'pattern'",
  "details": {
    "field": "pattern",
    "constraint": "required"
  }
}
```

**Invalid Parameter Values:**
```json
{
  "error": "validation_error",
  "message": "Count must be between 1 and 500",
  "details": {
    "field": "count",
    "value": 1000,
    "constraint": "max_value",
    "max_allowed": 500
  }
}
```

**Pattern Validation Errors:**
```json
{
  "error": "pattern_validation_error",
  "message": "Invalid pattern syntax",
  "details": {
    "position": 15,
    "expected": "closing brace '}'",
    "found": "end of string"
  }
}
```

**Unknown Dictionary or Tag:**
```json
{
  "error": "validation_error",
  "message": "Unknown tag 'invalid' for dictionary 'adjective'",
  "details": {
    "dictionary": "adjective",
    "invalid_tag": "invalid",
    "available_tags": ["pos", "neg", "emo", "det", "obj", "neut", "nsfw"]
  }
}
```

### Resource Errors (404)

**Series Not Found:**
```json
{
  "error": "series_not_found",
  "message": "No active series found for this organisation",
  "suggestion": "Create a series first or check series configuration"
}
```

**Organisation Not Found:**
```json
{
  "error": "organisation_not_found",
  "message": "Organisation not found or access denied"
}
```

### Rate Limiting Errors (429)

**Request Rate Exceeded:**
```json
{
  "error": "rate_limit_exceeded",
  "message": "Request rate limit exceeded",
  "retry_after": 60
}
```

**Daily Quota Exceeded:**
```json
{
  "error": "quota_exceeded",
  "message": "Daily mint quota exceeded",
  "resets_at": "2024-01-02T00:00:00Z"
}
```

**Monthly Quota Exceeded:**
```json
{
  "error": "quota_exceeded",
  "message": "Monthly operation limit reached",
  "upgrade_suggestion": "Consider upgrading your plan"
}
```

### Slice Window Errors (416)

**Window Exceeded:**
```json
{
  "error": "slice_window_exceeded",
  "message": "Requested sequence outside allowed slice window",
  "details": {
    "requested_sequence": 50000,
    "current_position": 1000,
    "window_back": 10000,
    "window_forward": 10000,
    "allowed_range": {
      "min": -9000,
      "max": 11000
    }
  }
}
```

### Server Errors (5xx)

**Internal Server Error:**
```json
{
  "error": "internal_server_error",
  "message": "An unexpected error occurred",
  "request_id": "req_abc123...",
  "suggestion": "Please try again or contact support if the issue persists"
}
```

**Service Unavailable:**
```json
{
  "error": "service_unavailable",
  "message": "Service temporarily unavailable for maintenance",
  "retry_after": 300
}
```

## SDK Error Handling

The TypeScript and Python SDKs provide rich error handling with automatic retry logic:

### TypeScript SDK
```typescript
import { SlugKitClient, SlugKitError } from '@slugkit/typescript-sdk';

const client = new SlugKitClient({ apiKey: 'sk_live_...' });

try {
  const slugs = await client.mint({ count: 10 });
} catch (error) {
  if (error instanceof SlugKitError) {
    console.log('Error type:', error.type);
    console.log('Message:', error.message);
    console.log('Status code:', error.statusCode);
    
    // Check specific error types
    if (error.isRateLimited) {
      console.log('Rate limited, retry after:', error.retryAfter);
    }
    
    if (error.isQuotaExceeded) {
      console.log('Quota exceeded, resets at:', error.resetsAt);
    }
    
    if (error.isValidationError) {
      console.log('Validation details:', error.validationDetails);
    }
  }
}
```

### Python SDK
```python
from slugkit import SlugKitClient, SlugKitError, RateLimitError, ValidationError

client = SlugKitClient(api_key='sk_live_...')

try:
    slugs = client.mint(count=10)
except RateLimitError as e:
    print(f"Rate limited: {e.retry_after}s")
    print(f"Quota remaining: {e.quota_remaining}")
except ValidationError as e:
    print(f"Validation error: {e.message}")
    print(f"Field: {e.field}, Value: {e.value}")
except SlugKitError as e:
    print(f"SlugKit error: {e.message}")
    print(f"Error type: {e.error_type}")
    print(f"Status code: {e.status_code}")
```

## Direct API Error Handling

For direct API usage, implement proper error handling in your HTTP client:

### JavaScript/Node.js Example
```javascript
async function handleSlugKitRequest(endpoint, data) {
  try {
    const response = await fetch(`https://api.slugkit.dev${endpoint}`, {
      method: 'POST',
      headers: {
        'X-API-Key': process.env.SLUGKIT_API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new SlugKitAPIError(response.status, errorData);
    }
    
    return await response.json();
  } catch (error) {
    if (error instanceof SlugKitAPIError) {
      return handleSlugKitError(error);
    }
    throw error; // Re-throw network errors
  }
}

class SlugKitAPIError extends Error {
  constructor(statusCode, errorData) {
    super(errorData.message);
    this.statusCode = statusCode;
    this.errorType = errorData.error;
    this.details = errorData.details;
  }
}

function handleSlugKitError(error) {
  switch (error.statusCode) {
    case 400:
      console.log('Validation error:', error.details);
      break;
    case 401:
      console.log('Authentication error - check API key');
      break;
    case 403:
      console.log('Permission error:', error.message);
      break;
    case 404:
      console.log('Resource not found:', error.message);
      break;
    case 416:
      console.log('Slice window exceeded:', error.details);
      break;
    case 429:
      console.log('Rate limited, retry after:', error.details?.retry_after);
      break;
    case 500:
      console.log('Server error:', error.message);
      break;
    default:
      console.log('Unexpected error:', error.message);
  }
}
```

### Python Requests Example
```python
import requests
import time
from typing import Dict, Any

class SlugKitAPIError(Exception):
    def __init__(self, status_code: int, error_data: Dict[str, Any]):
        self.status_code = status_code
        self.error_type = error_data.get('error')
        self.message = error_data.get('message')
        self.details = error_data.get('details', {})
        super().__init__(self.message)

def make_slugkit_request(endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
    url = f"https://api.slugkit.dev{endpoint}"
    headers = {
        'X-API-Key': os.environ['SLUGKIT_API_KEY'],
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.post(url, json=data, headers=headers)
        
        if not response.ok:
            error_data = response.json()
            raise SlugKitAPIError(response.status_code, error_data)
            
        return response.json()
        
    except SlugKitAPIError:
        raise  # Re-raise SlugKit errors
    except requests.RequestException as e:
        raise RuntimeError(f"Network error: {e}")

def handle_slugkit_error(error: SlugKitAPIError):
    if error.status_code == 400:
        print(f"Validation error: {error.details}")
    elif error.status_code == 401:
        print("Authentication error - check API key")
    elif error.status_code == 403:
        print(f"Permission error: {error.message}")
    elif error.status_code == 404:
        print(f"Resource not found: {error.message}")
    elif error.status_code == 416:
        print(f"Slice window exceeded: {error.details}")
    elif error.status_code == 429:
        retry_after = error.details.get('retry_after', 60)
        print(f"Rate limited, retry after: {retry_after}s")
    elif error.status_code >= 500:
        print(f"Server error: {error.message}")
    else:
        print(f"Unexpected error: {error.message}")
```

## Retry Strategies

### Exponential Backoff Implementation
```javascript
async function requestWithRetry(endpoint, data, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await handleSlugKitRequest(endpoint, data);
    } catch (error) {
      if (error instanceof SlugKitAPIError) {
        // Don't retry on client errors (4xx) except rate limits
        if (error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429) {
          throw error;
        }
        
        // For rate limits, use the retry-after header
        if (error.statusCode === 429) {
          const retryAfter = error.details?.retry_after || Math.pow(2, attempt);
          console.log(`Rate limited, waiting ${retryAfter}s...`);
          await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
          continue;
        }
        
        // For server errors, use exponential backoff
        if (error.statusCode >= 500) {
          const delay = Math.pow(2, attempt) * 1000;
          console.log(`Server error, retrying in ${delay}ms...`);
          await new Promise(resolve => setTimeout(resolve, delay));
          continue;
        }
      }
      
      // For network errors, retry with backoff
      const delay = Math.pow(2, attempt) * 1000;
      console.log(`Network error, retrying in ${delay}ms...`);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  
  throw new Error(`Request failed after ${maxRetries} attempts`);
}
```

### Retry Policy Guidelines

**Always retry:**
- 429 (Rate Limited) - with proper delay
- 500 (Internal Server Error)
- 502 (Bad Gateway)
- 503 (Service Unavailable)
- 504 (Gateway Timeout)
- Network timeouts and connection errors

**Never retry:**
- 400 (Bad Request) - fix the request first
- 401 (Unauthorized) - fix authentication
- 403 (Forbidden) - fix permissions
- 404 (Not Found) - resource doesn't exist
- 416 (Range Not Satisfiable) - adjust slice parameters

**Consider retrying with fixes:**
- Pattern validation errors - fix pattern syntax
- Parameter validation errors - adjust parameters

## Best Practices

### 1. Structured Error Handling
```javascript
// Create specific error classes for different scenarios
class SlugKitValidationError extends SlugKitAPIError {
  constructor(statusCode, errorData) {
    super(statusCode, errorData);
    this.field = errorData.details?.field;
    this.value = errorData.details?.value;
    this.constraint = errorData.details?.constraint;
  }
}

class SlugKitRateLimitError extends SlugKitAPIError {
  constructor(statusCode, errorData) {
    super(statusCode, errorData);
    this.retryAfter = errorData.details?.retry_after || errorData.retry_after;
    this.quotaType = this.extractQuotaType(errorData.message);
  }
  
  extractQuotaType(message) {
    if (message.includes('daily')) return 'daily';
    if (message.includes('monthly')) return 'monthly';
    if (message.includes('rate')) return 'rate';
    return 'unknown';
  }
}
```

### 2. Comprehensive Logging
```javascript
function logSlugKitError(error, context = {}) {
  const logData = {
    timestamp: new Date().toISOString(),
    error_type: error.errorType,
    message: error.message,
    status_code: error.statusCode,
    details: error.details,
    context: context,
    request_id: error.details?.request_id
  };
  
  // Log to your monitoring system
  console.error('SlugKit API Error:', JSON.stringify(logData, null, 2));
  
  // Send to error tracking service
  if (typeof reportError === 'function') {
    reportError(error, logData);
  }
}
```

### 3. User-Friendly Error Messages
```javascript
function getDisplayMessage(error) {
  switch (error.errorType) {
    case 'validation_error':
      return `Please check your input: ${error.message}`;
    case 'rate_limit_exceeded':
      return 'Too many requests. Please try again in a moment.';
    case 'quota_exceeded':
      return 'Daily limit reached. Please try again tomorrow or upgrade your plan.';
    case 'series_not_found':
      return 'The requested series could not be found. Please check your configuration.';
    case 'pattern_validation_error':
      return 'The pattern format is invalid. Please check the pattern syntax.';
    default:
      return 'An unexpected error occurred. Please try again.';
  }
}
```

### 4. Circuit Breaker Pattern
```javascript
class CircuitBreaker {
  constructor(threshold = 5, timeout = 60000) {
    this.threshold = threshold;
    this.timeout = timeout;
    this.failureCount = 0;
    this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
    this.nextAttempt = null;
  }
  
  async execute(operation) {
    if (this.state === 'OPEN') {
      if (Date.now() < this.nextAttempt) {
        throw new Error('Circuit breaker is OPEN');
      }
      this.state = 'HALF_OPEN';
    }
    
    try {
      const result = await operation();
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      throw error;
    }
  }
  
  onSuccess() {
    this.failureCount = 0;
    this.state = 'CLOSED';
  }
  
  onFailure() {
    this.failureCount++;
    if (this.failureCount >= this.threshold) {
      this.state = 'OPEN';
      this.nextAttempt = Date.now() + this.timeout;
    }
  }
}
```

## Debugging Common Issues

### Authentication Problems
**Check these common issues:**
- API key format (should start with `sk_live_` or `sk_test_`)
- Header name (`X-API-Key`, not `Authorization`)
- Key permissions and scopes
- Organisation and series access rights

### Pattern Validation Issues
**Use the validation endpoint:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"pattern": "YOUR_PATTERN_HERE"}'
```

### Rate Limiting Problems
**Monitor these indicators:**
- Rate limit headers in responses
- 429 error frequency
- Time of day patterns
- Burst vs sustained usage

### Series and Slice Issues
**Common troubleshooting:**
- Verify series exists and is accessible
- Check slice window limits
- Confirm current series position
- Validate sequence parameters

## Production Monitoring

### Error Rate Monitoring
Track these key metrics:
- **Error rate by status code** (4xx vs 5xx)
- **Error rate by endpoint** (forge, mint, slice)
- **Error rate by error type** (validation, auth, rate limit)
- **Recovery time** after errors

### Alerting Thresholds
- **5xx error rate > 1%**: Critical alert
- **4xx error rate > 10%**: Warning alert
- **Authentication errors**: Immediate alert
- **Quota exceeded**: Planning alert

### Health Checks
Implement regular health checks:
```javascript
async function healthCheck() {
  try {
    const response = await fetch('https://api.slugkit.dev/api/v1/key-info', {
      headers: { 'X-API-Key': process.env.SLUGKIT_API_KEY }
    });
    
    if (response.ok) {
      return { status: 'healthy', timestamp: new Date().toISOString() };
    } else {
      throw new Error(`Health check failed: ${response.status}`);
    }
  } catch (error) {
    return { 
      status: 'unhealthy', 
      error: error.message, 
      timestamp: new Date().toISOString() 
    };
  }
}
```

## Related Documentation

- [Authentication](./api-authentication) - API key setup and scopes
- [Rate Limits & Quotas](./api-rate-limits) - Understanding limits and quotas
- [Validation Endpoints](./api-validation-endpoints) - Pattern validation and debugging
- [Forge Endpoint](./api-forge-endpoint) - Custom pattern generation
- [Mint Endpoint](./api-mint-endpoint) - Series-based unique generation
- [Slice Endpoint](./api-slice-endpoint) - Preview and coordination
- [TypeScript SDK](./sdk-typescript-installation) - Client and server integration
- [Python SDK](./sdk-python-installation) - Server-side integration

---

# Rate Limits & Quotas
Source: https://dev.slugkit.dev/docs/api-rate-limits

# Rate Limits & Quotas

*Understanding SlugKit's rate limiting system, subscription-based quotas, and optimal usage patterns*

---

## Overview

SlugKit implements a comprehensive rate limiting system designed to ensure fair usage and optimal performance across all subscription tiers. Rate limits protect the service while providing predictable capacity for your applications.

## Rate Limiting Headers

All API responses include rate limiting information via standard headers:

### Standard Rate Limit Headers
```
X-Slug-Rpm-Remaining: 95
X-Slug-Daily-Remaining: 8750
X-Slug-Monthly-Remaining: 245000
X-Slug-Lifetime-Remaining: 995000
```

### Header Definitions
- **X-Slug-Rpm-Remaining**: Requests remaining per minute (-1 = unlimited)
- **X-Slug-Daily-Remaining**: Requests remaining today (-1 = unlimited)
- **X-Slug-Monthly-Remaining**: Requests remaining this month (-1 = unlimited)
- **X-Slug-Lifetime-Remaining**: Lifetime requests remaining (-1 = unlimited)

### When Rate Limited
```
X-Slug-Rate-Limit-Reason: "Rate limit reached"
X-Slug-Retry-After: 3600
```

## SDK Automatic Rate Limit Handling

The **TypeScript and Python SDKs automatically monitor rate limit headers** and provide intelligent handling:

- **Automatic retry logic** with exponential backoff for 429 responses
- **Verbose exceptions** with detailed rate limit information when retries are exhausted
- **Header monitoring** to proactively avoid rate limits when possible
- **Built-in best practices** for batch operations and request timing

**For SDK users:** Rate limiting is handled automatically. Focus on application logic rather than manual retry implementation.

**For direct API users:** Implement proper retry logic and header monitoring as shown in the examples below.

## Subscription-Based Limits

Rate limits and quotas vary significantly by subscription plan. Each plan offers different:

- **Request rates** (requests per minute, sustained and burst)
- **Daily generation quotas** (forge and mint operations)
- **Monthly generation quotas** (total operations per month)
- **Series limits** (maximum series per organisation)
- **Slice windows** (back/forward access ranges)
- **Per-request limits** (maximum slugs per request)
- **Available methods** (forge, mint, slice availability)

**For current plan details and pricing:** Visit the [feature matrix](/products/feature-matrix) for comprehensive plan comparisons.

**To check your current limits:** Use the `/api/v1/limits` endpoint or visit your dashboard to see your specific quotas and usage.

## Rate Limiting Types

### 1. Request Rate Limits
Control the frequency of API calls to ensure service stability.

**Sustained Rate:**
- **Purpose:** Prevent sustained high-frequency usage
- **Measurement:** Requests per minute over rolling window
- **Plan-dependent:** Varies from low-volume to enterprise scale

**Burst Rate:**
- **Purpose:** Allow temporary spikes in traffic
- **Measurement:** Maximum requests in short burst periods
- **Typically:** Multiple times the sustained rate
- **Resets:** Quickly after burst period ends

### 2. Generation Quotas
Limit the total number of slugs generated within time periods.

**Daily Quotas:**
- **Forge operations:** Custom pattern generation
- **Mint operations:** Unique series-based generation
- **Resets:** Daily at midnight UTC
- **Separate tracking:** Forge and mint counted independently

**Monthly Quotas:**
- **Combined tracking:** All operations within calendar month
- **Rollover:** No unused quota carries to next month
- **Alerts:** Notifications at 80% and 95% usage

### 3. Structural Limits
Control organisational complexity and access patterns.

**Series Limits:**
- **Per-organisation:** Maximum series you can create
- **Active series:** All series count toward limit
- **Management:** Create/delete via dashboard or API

**Slice Windows:**
- **Back/forward access:** How far from current position you can slice
- **Position-based:** Relative to series counter position
- **Prevents abuse:** Stops excessive historical/future access

**Per-Request Limits:**
- **Batch size:** Maximum slugs per single request
- **Efficiency:** Encourages appropriate batch sizes
- **Plan-dependent:** May vary by subscription tier

## Understanding Rate Limit Responses

### 429 Too Many Requests
```json
{
  "error": "rate_limit_exceeded",
  "message": "Daily mint quota exceeded", 
  "limits": {
    "daily_mint_limit": 10000,
    "used": 10000,
    "resets_at": "2024-01-02T00:00:00Z"
  }
}
```

### Rate Limit Headers in 429 Response
```
X-Slug-Rate-Limit-Reason: "Daily quota exceeded"
X-Slug-Retry-After: 3600
X-Slug-Daily-Remaining: 0
```

### Common Rate Limit Scenarios
**Request frequency exceeded:**
```json
{
  "error": "rate_limit_exceeded",
  "message": "Request rate limit exceeded",
  "retry_after": 60
}
```

**Daily quota exhausted:**
```json
{
  "error": "quota_exceeded", 
  "message": "Daily forge quota exceeded",
  "resets_at": "2024-01-02T00:00:00Z"
}
```

**Monthly quota exhausted:**
```json
{
  "error": "quota_exceeded",
  "message": "Monthly operation limit reached",
  "upgrade_suggestion": "Consider upgrading your plan"
}
```

## Direct API Usage Best Practices

### Monitor Rate Limit Headers
Always check rate limit headers in API responses:

```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"count": 10}' \
  -i
```

Look for these headers in the response:
```
X-Slug-Daily-Remaining: 8750
X-Slug-Rpm-Remaining: 95
```

### Implement Exponential Backoff
For direct API usage, implement proper retry logic:

```bash
# Example using curl with retry logic in shell script
retry_request() {
  local max_attempts=3
  local delay=1
  
  for attempt in $(seq 1 $max_attempts); do
    response=$(curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
      -H "X-API-Key: $SLUGKIT_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"count": 10}' \
      -w "%{http_code}" \
      -s)
    
    if [ "$response" != "429" ]; then
      echo "Success: $response"
      return 0
    fi
    
    echo "Rate limited, waiting ${delay}s..."
    sleep $delay
    delay=$((delay * 2))
  done
  
  echo "Failed after $max_attempts attempts"
  return 1
}
```

### Optimise Batch Operations
Use efficient batch sizes for your subscription tier:

```bash
# Good: Request batch sizes appropriate for your plan
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"count": 500}'  # Check your plan's per-request limit

# Less efficient: Multiple small requests
# curl requests for count: 1, 1, 1... (uses request quota faster)
```

### Cache Deterministic Operations
For forge operations with the same pattern and seed:

```bash
# These requests will always return identical results - cache them
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective}-{noun}",
    "seed": "campaign-2025",
    "count": 100
  }'

# Note: Don't cache mint operations (they're unique every time)
```

## Monitoring and Alerting

### Track Usage Patterns
Monitor these key metrics:
- **Daily usage trends:** Identify peak hours and usage patterns
- **Monthly consumption:** Plan for quota exhaustion
- **Request distribution:** Monitor forge vs mint vs slice usage
- **Error rates:** Track 429 responses and retry success

### Set Up Alerts
**Quota alerts:**
- 70% of daily/monthly quota: Planning alert
- 85% of quota: Warning alert
- 95% of quota: Critical alert

**Rate limit alerts:**
- High 429 response rates
- Frequent retry scenarios
- Sustained high request volumes

### Check Quotas Programmatically
Use the limits endpoint to monitor usage:

```bash
curl -X GET https://api.slugkit.dev/api/v1/limits \
  -H "X-API-Key: sk_live_abc123..."
```

Response includes current limits and usage:
```json
{
  "daily_forge_limit": 10000,
  "daily_forge_used": 2500,
  "daily_mint_limit": 10000,
  "daily_mint_used": 5750,
  "monthly_limit": 600000,
  "monthly_used": 125000
}
```

## Understanding Your Current Limits

### Check Your Plan Information
Use the key info endpoint to understand your current configuration:

```bash
curl -X GET https://api.slugkit.dev/api/v1/key-info \
  -H "X-API-Key: sk_live_abc123..."
```

This returns information about your key's permissions and organisation details.

### Check Current Quotas
Use the limits endpoint to see your specific limits:

```bash
curl -X GET https://api.slugkit.dev/api/v1/limits \
  -H "X-API-Key: sk_live_abc123..."
```

This returns your actual rate limits, quotas, and current usage.

## Plan Upgrade Considerations

### When You Might Need to Upgrade

**Common upgrade triggers:**
- Consistently hitting daily quotas before end of day
- Frequent rate limit responses (429 errors)
- Need for additional series beyond current limit
- Requirement for larger slice windows
- Need for methods not available on current plan (forge/slice on Free plan)

**Planning for growth:**
- Monitor usage trends over time
- Project future needs based on application growth
- Consider seasonal or campaign-driven usage spikes
- Plan for development and staging environment needs

### Comparing Plans
For detailed plan comparisons including current limits and pricing, visit the [feature matrix](/products/feature-matrix).

## Troubleshooting Rate Limits

### Common Issues

**Hitting daily quotas early:**
- Monitor usage patterns throughout the day
- Implement request queuing for non-urgent operations
- Consider upgrading to a higher-tier plan

**Frequent rate limit hits:**
- Reduce request frequency
- Implement proper retry logic with exponential backoff
- Batch operations more efficiently

**Series or slice limitations:**
- Check your plan's series limits
- Review slice window constraints
- Upgrade for additional capacity if needed

### Using SDKs for Better Error Handling

The TypeScript and Python SDKs provide detailed error information:

**TypeScript SDK:**
```typescript
import { SlugKitClient } from '@slugkit/typescript-sdk';

try {
  const slugs = await client.mint({ count: 10 });
} catch (error) {
  if (error.isRateLimited) {
    console.log('Rate limited:', error.retryAfter);
    console.log('Quota remaining:', error.quotaRemaining);
  }
}
```

**Python SDK:**
```python
from slugkit import SlugKitClient, RateLimitError

try:
    slugs = client.mint(count=10)
except RateLimitError as e:
    print(f"Rate limited: {e.retry_after}s")
    print(f"Quota remaining: {e.quota_remaining}")
```

## Related Documentation

- [Authentication](./api-authentication) - API key setup and scopes
- [Forge Endpoint](./api-forge-endpoint) - Custom pattern generation
- [Mint Endpoint](./api-mint-endpoint) - Series-based unique generation
- [Slice Endpoint](./api-slice-endpoint) - Preview and coordination
- [Error Handling](./api-error-handling) - Comprehensive error management
- [TypeScript SDK](./sdk-typescript-installation) - Client and server integration
- [Python SDK](./sdk-python-installation) - Server-side integration
- [Feature Matrix](/products/feature-matrix) - Plan comparison and current pricing

---

# API Reference
Source: https://dev.slugkit.dev/docs/api-reference

# SlugKit API Reference

*Complete reference for SlugKit's REST API endpoints and authentication*

## Table of Contents
- [Authentication](#authentication)
- [Rate Limits & Headers](#rate-limits--headers)  
- [Error Handling](#error-handling)
- [Endpoints](#endpoints)
  - [Forge - Custom Generation](#forge---custom-generation)
  - [Mint - Series Generation](#mint---series-generation)
  - [Slice - Preview Generation](#slice---preview-generation)
  - [Series Management](#series-management)
  - [Validation & Analysis](#validation--analysis)
- [Best Practices](#best-practices)
- [SDKs & Code Examples](#sdks--code-examples)

---

## Authentication

SlugKit uses **API keys** for server-side authentication and **SDK keys** for client-side signature-based authentication. All API requests require authentication to track usage and enforce quotas.

### Quick Reference

**Server-side with API keys:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

**Client-side with SDK keys:**
```typescript
import { SlugKitClient } from '@slugkit/typescript-sdk';

const client = new SlugKitClient({
  sdkSlug: 'web-app-prod'
});

const slugs = await client.forge({
  pattern: '{adjective}-{noun}',
  count: 5
});
```

**Complete authentication setup and scopes:** See the [Authentication Guide](api-authentication) for detailed instructions on getting API keys, SDK configuration, scope management, security best practices, and troubleshooting.

---

## Rate Limits & Headers

### Response Headers

All responses include rate limit information:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95  
X-RateLimit-Reset: 1640000000
```

### Subscription Limits

Rate limits vary by subscription tier - see the [feature matrix](/products/feature-matrix) for complete details.

### Rate Limit Errors

When rate limited, you'll receive a 429 response:

```json
{
  "error": "Rate limit exceeded",
  "retry_after": 42,
  "limit": "100 requests per minute"
}
```

Use the `Retry-After` header to implement proper backoff.

---

## Error Handling

### Standard Error Format

```json
{
  "error": "error_type",
  "message": "Human-readable description",
  "details": {
    "field": "parameter_name",
    "value": "invalid_value"
  }
}
```

### HTTP Status Codes

| Code | Error Type | Description | Action |
|------|------------|-------------|---------|
| 400 | Bad Request | Invalid parameters | Fix request parameters |
| 401 | Unauthorized | Missing/invalid key | Check authentication |
| 403 | Forbidden | Insufficient permissions | Update key scopes |
| 429 | Rate Limited | Quota exceeded | Wait and retry |
| 500 | Server Error | Internal error | Retry with backoff |

---

## Endpoints

### Forge - Custom Generation

**Generate custom slugs with explicit pattern control**

```http
POST /api/v1/gen/forge
POST /api/v1/gen/forge/stream
```

**Required Scopes:** `forge`

**Use cases:**
- Marketing campaigns with themed patterns
- Testing with reproducible results  
- One-off identifier generation
- Custom branding requirements

#### Request Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `pattern` | string | Yes | SlugKit pattern string |
| `count` | integer | No | Number of slugs (default: 1) |
| `seed` | string | No | Deterministic seed |
| `sequence` | integer | No | Starting offset (default: 0) |

#### Example Request

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective}-{noun}-{number:2x}",
    "count": 10,
    "seed": "campaign-2025"
  }'
```

#### Response

```json
[
  "brilliant-keyboard-a4",
  "cosmic-telescope-f7", 
  "elegant-framework-2c"
]
```

#### Streaming Endpoint

For bulk operations (1000+ slugs), use the streaming endpoint:

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/forge/stream \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5000}'
```

Responds with one slug per line.

---

### Mint - Series Generation

**Generate guaranteed unique slugs from configured series**

```http
POST /api/v1/gen/mint
POST /api/v1/gen/mint/stream
```

**Required Scopes:** `mint`

**Use cases:**
- User handles and social identifiers
- Production systems requiring uniqueness
- Long-running identifier sequences
- Database primary keys

#### Request Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `series_slug` | string | Conditional | Required for org-scoped keys |
| `count` | integer | No | Number of slugs (default: 1) |

#### Example Request

```bash
# Organization-scoped key (must specify series)
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "series_slug": "user-handles",
    "count": 5
  }'

# Series-scoped key (automatic targeting)
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_series_xyz789..." \
  -H "Content-Type: application/json" \
  -d '{"count": 5}'
```

#### Response

```json
[
  "clever-dolphin-42",
  "wise-tiger-67",
  "brave-eagle-23"
]
```

#### Streaming Endpoint

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/mint/stream \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "user-handles", "count": 1000}'
```

---

### Slice - Preview Generation

**Preview slugs without consuming them from series**

```http
POST /api/v1/gen/slice
POST /api/v1/gen/slice/stream
```

**Required Scopes:** `slice`

**Use cases:**
- Testing without affecting production state
- Coordinating across distributed systems
- Previewing upcoming identifiers
- Development environment synchronization

#### Request Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `series_slug` | string | Conditional | Required for org-scoped keys |
| `sequence` | integer | No | Starting position (default: 0) |
| `count` | integer | No | Number of slugs (default: 1) |

#### Example Request

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/slice \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "series_slug": "user-handles", 
    "sequence": 1000,
    "count": 10
  }'
```

#### Response

```json
[
  "preview-slug-1000",
  "preview-slug-1001",
  "preview-slug-1002"
]
```

#### Slice Windows

Most subscription plans limit how far you can slice from the current series position. Enterprise plans often have unlimited slice windows.

---

### Series Management

**Manage series configurations and lifecycle**

#### List Series

```http
GET /api/v1/gen/series
```

**Required Scopes:** `series:read`

List all series accessible to your API key.

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_abc123..."
```

**Response:**
```json
{
  "user-handles": "User Handle Generation",
  "product-skus": "Product SKU Series",
  "campaign-ids": "Marketing Campaign IDs"
}
```

#### Get Series Information

```http
POST /api/v1/gen/series-info
```

**Required Scopes:** `series:read`

Get detailed information about a specific series.

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/series-info \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"series": "user-handles"}'
```

**Response:**
```json
{
  "slug": "user-handles",
  "org_slug": "my-organization",
  "name": "User Handle Generation",
  "pattern": "{adjective}-{noun}-{number:2d}",
  "max_slug_length": 25,
  "capacity": "17082000000",
  "generated_count": "1247",
  "mtime": "2024-12-15T10:30:00Z"
}
```

#### Create Series

```http
POST /api/v1/gen/series
```

**Required Scopes:** `series:create`

Create a new series with specified pattern.

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Product SKUs",
    "pattern": "{adjective:+tech}-{noun:+product}-{number:3x}"
  }'
```

#### Update Series

```http
PUT /api/v1/gen/series
```

**Required Scopes:** `series:update`

Update an existing series. Note that updating resets the series counter.

```bash
curl -X PUT https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "product-skus",
    "name": "Enhanced Product SKUs",
    "pattern": "{adjective:+premium}-{noun:+product}-{number:4x}"
  }'
```

#### Delete Series

```http
DELETE /api/v1/gen/series
```

**Required Scopes:** `series:delete`

Delete a series and all associated API keys.

```bash
curl -X DELETE https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"series": "old-series"}'
```

#### Reset Series

```http
POST /api/v1/gen/reset
```

**Required Scopes:** `reset`

Reset series counter to initial state. This operation is irreversible.

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/reset \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"series": "user-handles"}'
```

#### Generation Statistics

```http
POST /api/v1/gen/stats/latest
```

**Required Scopes:** `stats`

Get generation statistics for series.

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/stats/latest \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"series": "user-handles"}'
```

---

### Validation & Analysis

**Validate patterns and analyze capacity (no special scopes required)**

#### Pattern Information

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/pattern-info \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}"}'
```

**Response:**
```json
{
  "pattern": "{adjective}-{noun}",
  "capacity": "708339294",
  "max_slug_length": 30,
  "complexity": 2,
  "components": 3
}
```

#### Dictionary Information

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/dictionary-info \
  -H "X-API-Key: sk_live_abc123..."
```

#### Dictionary Tags

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/dictionary-tags?kind=adjective \
  -H "X-API-Key: sk_live_abc123..."
```

#### Key Information

Check your current key's configuration:

```bash
curl -X POST https://api.slugkit.com/api/v1/key-info \
  -H "X-API-Key: sk_live_abc123..."
```

**Response:**
```json
{
  "key_type": "api-key",
  "key_scope": "org",
  "slug": "production-backend",
  "org_slug": "my-organization",
  "series_slug": null,
  "scopes": ["forge", "mint", "slice", "series:read"],
  "enabled": true
}
```

#### Subscription Limits

Check your organization's limits:

```bash
curl -X GET https://api.slugkit.com/api/v1/limits \
  -H "X-API-Key: sk_live_abc123..."
```

---

## Best Practices

### Authentication Security

**Server-Side (API Keys):**
- Store keys in environment variables only
- Use different keys per environment
- Rotate keys quarterly
- Monitor usage via dashboard
- Use series-scoped keys when accessing single series
- Request minimal required scopes for each key

**Client-Side (SDK Keys):**
- Configure strict origin restrictions
- Use automatic key rotation
- Monitor SDK configuration usage
- Never embed API keys in client code

### Performance Optimization

- Use streaming endpoints for bulk operations (1000+ slugs)
- Batch requests when possible (generate multiple slugs per request)
- Implement exponential backoff for retries
- Monitor rate limit headers in responses
- Cache pattern validation results

### Pattern Design

**Check capacity before production use:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/pattern-info \
  -H "X-API-Key: sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}-{number:3x}"}'
```

Plan for 10x growth in your capacity requirements.

### Error Handling

Always implement proper retry logic with exponential backoff:

```bash
# Check retry-after header on 429 responses
# Implement circuit breaker patterns for 500 errors
# Log all errors with request IDs for debugging
```

---

## SDKs & Code Examples

For production applications, use our official SDKs instead of direct HTTP calls:

### Python SDK
- **Installation:** [Python SDK Installation](sdk-python-installation)
- **Quickstart:** [Python SDK Quickstart](sdk-python-quickstart)
- **Advanced:** [Python SDK Advanced Usage](sdk-python-advanced)

### TypeScript SDK
- **Installation:** [TypeScript SDK Installation](sdk-typescript-installation)
- **Browser:** [Browser Usage](sdk-typescript-browser)
- **Node.js:** [Node.js Usage](sdk-typescript-nodejs)
- **React:** [React Integration](sdk-typescript-react)

### Direct HTTP Examples
- **cURL Examples:** [REST API cURL Examples](rest-api-curl-examples)
- **Postman Collection:** [Postman Collection](rest-api-postman)

---

## Related Documentation

**Getting Started:**
- [Authentication Guide](api-authentication) - Complete authentication setup and security
- [Core Concepts](developer-core-concepts) - Understanding patterns and series
- [Choosing Generation Methods](choosing-generation-method) - When to use forge vs mint vs slice
- [Developer Quickstart Guide](developer-quickstart-guide) - Your first API call

**Pattern Language:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Learn pattern fundamentals
- [Advanced Features](pattern-advanced-features) - Case transformations and filtering
- [Pattern Cookbook](pattern-cookbook) - Real-world examples
- [Dictionary Reference](pattern-dictionary-reference) - Available words and tags

**Advanced Topics:**
- [Rate Limits & Quotas](api-rate-limits) - Understanding limits
- [Error Handling](api-error-handling) - Comprehensive error guide
- [Performance Optimization](pattern-performance-optimization) - Scale efficiently

---

# Series Management API
Source: https://dev.slugkit.dev/docs/api-series-management

# API Series Management

*Programmatically create, update, and manage SlugKit series through the API*

---

## Overview

Series are the foundation of SlugKit's unique slug generation. This guide covers how to programmatically manage series through the API, including creation, updates, monitoring, and deletion. Series provide guaranteed uniqueness within their scope and enable mint and slice operations.

**Important:** Series slugs are automatically generated by SlugKit and cannot be customized. The platform ensures globally unique series identifiers.

## Understanding Series

A **series** is a configured slug generator with:
- **Unique slug**: Auto-generated identifier (e.g., `cosmic-generator-a4f`)
- **Pattern**: Template for slug generation (e.g., `{adjective}-{noun}-{number:2x}`)
- **Seed**: Deterministic generation seed
- **Counter**: Current position for mint operations
- **Capacity**: Maximum unique slugs available

**Key Benefits:**
- **Guaranteed uniqueness**: No duplicates within series scope
- **Scalable generation**: Handle millions of requests
- **Deterministic output**: Same inputs produce same results
- **State management**: Automatic counter tracking

---

## Required API Key Scopes

Series management requires specific API key permissions:

| Operation | Required Scope | Description |
|-----------|----------------|-------------|
| **List series** | `series:read` | View available series |
| **Get series info** | `series:read` | Read series configuration and stats |
| **Create series** | `series:create` | Create new series |
| **Update series** | `series:update` | Modify series configuration |
| **Delete series** | `series:delete` | Remove series permanently |

**Note:** Only **organization-scoped** API keys can manage series. Series-scoped keys cannot create or modify other series.

---

## Creating Series

### Basic Series Creation

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "User Handles",
    "pattern": "{adjective:+pos}-{noun:+person}-{number:2x}"
  }'
```

**Response:**
```json
{
  "slug": "cosmic-generator-a4f",
  "org_slug": "my-organization", 
  "name": "User Handles",
  "pattern": "{adjective:+pos}-{noun:+person}-{number:2x}",
  "max_slug_length": 40,
  "capacity": "570090240",
  "generated_count": "0",
  "mtime": "2025-01-15T10:30:00Z"
}
```

**Key Points:**
- **Series slug is auto-generated**: You cannot specify the slug
- **Pattern is validated**: Invalid patterns return validation errors
- **Capacity is calculated**: Shown for planning purposes
- **Counter starts at 0**: Ready for mint operations

### Business-Focused Examples

**Product identifier series:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Product Identifiers",
    "pattern": "{adjective:+pos}-{noun:+artifact}-{number:3x}"
  }'
```

**Order tracking series:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Order Numbers", 
    "pattern": "{adjective:+pos}-order-{number:4x}"
  }'
```

**Team service names:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Microservice Names",
    "pattern": "{noun:+activity}-{verb:+act}-service"
  }'
```

---

## Listing and Inspecting Series

### List All Available Series

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..."
```

**Response:**
```json
{
  "cosmic-generator-a4f": "User Handles",
  "stellar-creator-b7d": "Product Identifiers", 
  "brilliant-maker-c2a": "Order Numbers"
}
```

### Get Detailed Series Information

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/series-info \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "cosmic-generator-a4f"
  }'
```

**Response:**
```json
{
  "slug": "cosmic-generator-a4f",
  "org_slug": "my-organization",
  "name": "User Handles", 
  "pattern": "{adjective:+pos}-{noun:+person}-{number:2x}",
  "max_slug_length": 40,
  "capacity": "570090240",
  "generated_count": "1247",
  "mtime": "2025-01-15T14:22:00Z"
}
```

**Key Metrics:**
- **generated_count**: Number of slugs minted so far
- **capacity**: Total unique slugs available
- **max_slug_length**: Longest possible slug
- **mtime**: Last modification time

---

## Updating Series Configuration

### Modifying Series Pattern

**Important:** Series can only be updated if they haven't started generating slugs, or after being reset.

```bash
curl -X PUT https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "cosmic-generator-a4f",
    "name": "Updated User Handles",
    "pattern": "{adjective:+pos}-{noun:+person}-{number:3x}"
  }'
```

**When Updates Fail:**
```json
{
  "error": "series_locked",
  "message": "Series has generated slugs and is locked. Reset to unlock.",
  "generated_count": "1247"
}
```

**Solution:** Reset the series first (⚠️ **destructive operation**):
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/reset \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "cosmic-generator-a4f"
  }'
```

### Update Use Cases

**Increase capacity for growth:**
```bash
# Original: {adjective}-{noun} → 708M capacity
# Updated: {adjective}-{noun}-{number:2x} → 181B capacity
curl -X PUT https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "product-series-slug",
    "name": "Product Identifiers",
    "pattern": "{adjective:+pos}-{noun:+artifact}-{number:2x}"
  }'
```

**Refine word selection:**
```bash
# Add filtering for brand consistency
curl -X PUT https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "user-handles-slug",
    "name": "User Handles",
    "pattern": "{adjective:+pos-neg}-{noun:+person<10}"
  }'
```

---

## Monitoring Series Usage

### Get Series Statistics

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/stats/latest \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "cosmic-generator-a4f"
  }'
```

**Response:**
```json
[
  {
    "event_type": "mint",
    "date_part": "total",
    "total_count": 1247,
    "request_count": 89,
    "total_duration_us": 89234,
    "avg_duration_us": 71.6
  },
  {
    "event_type": "slice", 
    "date_part": "total",
    "total_count": 500,
    "request_count": 12,
    "total_duration_us": 12045,
    "avg_duration_us": 24.1
  }
]
```

### Capacity Planning

**Check remaining capacity:**
```bash
# Calculate usage percentage
current_usage = generated_count / capacity * 100

# Example: 1,247 / 570,090,240 = 0.0002% used
```

**Monitor growth rate:**
```bash
# Track daily/weekly generation trends
curl -X POST https://api.slugkit.com/api/v1/gen/stats/latest \
  -H "X-API-Key: sk_live_..." \
  -d '{"series": "series-slug"}'

# Plan for capacity exhaustion
estimated_days_to_capacity = remaining_capacity / daily_generation_rate
```

---

## Resetting Series

### When to Reset

**⚠️ Destructive Operation Warning:** Resetting a series:
- Sets counter back to 0
- Allows previously generated slugs to be generated again
- **May create duplicate identifiers** if used carelessly
- Cannot be undone

**Safe reset scenarios:**
- **Development/testing**: Reinitialize test environments
- **Pattern updates**: Unlock series for configuration changes
- **Data recovery**: After restoring from backup
- **Environment migration**: Moving between dev/staging/prod

**Unsafe reset scenarios:**
- **Production series with external references**: Will create duplicates
- **Series used in URLs**: May break existing links
- **Database foreign keys**: May violate constraints

### Reset Operation

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/reset \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "cosmic-generator-a4f"
  }'
```

**Response:**
```json
{
  "slug": "cosmic-generator-a4f",
  "org_slug": "my-organization",
  "name": "User Handles",
  "pattern": "{adjective:+pos}-{noun:+person}-{number:2x}",
  "max_slug_length": 40,
  "capacity": "570090240", 
  "generated_count": "0",
  "mtime": "2025-01-15T16:45:00Z"
}
```

**Safe Reset Workflow:**
1. **Document current state**: Record generated_count and mtime
2. **Verify safety**: Ensure no external dependencies
3. **Backup if needed**: Export current slug list if required
4. **Reset series**: Perform reset operation
5. **Update patterns**: Make necessary configuration changes
6. **Validate**: Test generation before production use

---

## Deleting Series

### Permanent Series Removal

**⚠️ Irreversible Operation:** Deleting a series:
- Removes all series configuration
- Invalidates all series-scoped API keys
- Cannot be undone
- Does not affect already-generated slugs in your applications

```bash
curl -X DELETE https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series": "cosmic-generator-a4f"
  }'
```

**Response:** `204 No Content` (success)

### Before Deleting

**Check dependencies:**
1. **API keys**: List series-scoped keys that will be invalidated
2. **Applications**: Verify no code references the series
3. **Documentation**: Update any references to the series
4. **Monitoring**: Remove alerts and dashboards

**Alternative to deletion:**
- Consider keeping unused series for reference
- Series don't consume resources when not actively used
- Deletion is primarily for organization and security

---

## Error Handling

### Common Errors

**Invalid pattern:**
```json
{
  "error": "invalid_pattern", 
  "message": "Pattern contains unsupported syntax: {invalid:+tag}",
  "details": {
    "field": "pattern",
    "value": "{invalid:+tag}"
  }
}
```

**Insufficient permissions:**
```json
{
  "error": "forbidden",
  "message": "API key lacks required scope: series:create",
  "details": {
    "required_scope": "series:create",
    "current_scopes": ["forge", "mint", "slice"]
  }
}
```

**Series not found:**
```json
{
  "error": "series_not_found",
  "message": "Series 'invalid-slug' does not exist",
  "details": {
    "series_slug": "invalid-slug"
  }
}
```

**Series locked:**
```json
{
  "error": "series_locked",
  "message": "Series has generated slugs and cannot be modified. Reset to unlock.",
  "details": {
    "generated_count": "1247",
    "locked": true
  }
}
```

### Best Practices

**Error handling in code:**
```python
try:
    response = requests.post('/api/v1/gen/series', json={
        'name': 'My Series',
        'pattern': '{adjective}-{noun}'
    }, headers={'X-API-Key': api_key})
    
    if response.status_code == 403:
        print("Insufficient API key permissions")
    elif response.status_code == 400:
        error_data = response.json()
        if error_data.get('error') == 'invalid_pattern':
            print(f"Pattern error: {error_data['message']}")
    elif response.status_code == 201:
        series_info = response.json()
        print(f"Created series: {series_info['slug']}")
        
except requests.RequestException as e:
    print(f"Request failed: {e}")
```

---

## Integration Examples

### CI/CD Pipeline Series Setup

```bash
#!/bin/bash
# setup-series.sh - Create series for different environments

API_KEY="sk_live_..."
BASE_URL="https://api.slugkit.com/api/v1"

# Create development series
curl -X POST "$BASE_URL/gen/series" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Development User Handles",
    "pattern": "dev-{adjective:+pos}-{noun:+person}-{number:2x}"
  }'

# Create production series  
curl -X POST "$BASE_URL/gen/series" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production User Handles", 
    "pattern": "{adjective:+pos}-{noun:+person}-{number:3x}"
  }'
```

### Application Initialization

```python
import requests

class SlugKitSeriesManager:
    def __init__(self, api_key, base_url="https://api.slugkit.com/api/v1"):
        self.api_key = api_key
        self.base_url = base_url
        self.headers = {
            'X-API-Key': api_key,
            'Content-Type': 'application/json'
        }
    
    def ensure_series_exists(self, name, pattern):
        """Create series if it doesn't exist, return series slug"""
        
        # List existing series
        response = requests.get(f"{self.base_url}/gen/series", headers=self.headers)
        existing_series = response.json()
        
        # Check if series with this name already exists
        for slug, series_name in existing_series.items():
            if series_name == name:
                return slug
        
        # Create new series
        response = requests.post(f"{self.base_url}/gen/series", 
                               headers=self.headers,
                               json={'name': name, 'pattern': pattern})
        
        if response.status_code == 201:
            series_info = response.json()
            return series_info['slug']
        else:
            raise Exception(f"Failed to create series: {response.text}")
    
    def get_series_health(self, series_slug):
        """Check series capacity and usage"""
        
        response = requests.post(f"{self.base_url}/gen/series-info",
                               headers=self.headers, 
                               json={'series': series_slug})
        
        if response.status_code == 200:
            info = response.json()
            capacity_used = int(info['generated_count']) / int(info['capacity'])
            
            return {
                'series_slug': series_slug,
                'capacity_used_percent': capacity_used * 100,
                'remaining_capacity': int(info['capacity']) - int(info['generated_count']),
                'health_status': 'healthy' if capacity_used < 0.8 else 'warning'
            }

# Usage
manager = SlugKitSeriesManager('sk_live_...')

# Ensure required series exist
user_series = manager.ensure_series_exists(
    "User Handles", 
    "{adjective:+pos}-{noun:+person}-{number:2x}"
)

product_series = manager.ensure_series_exists(
    "Product Identifiers",
    "{adjective:+pos}-{noun:+artifact}-{number:3x}"
)

# Monitor series health
health = manager.get_series_health(user_series)
if health['health_status'] == 'warning':
    print(f"Series {health['series_slug']} approaching capacity limit")
```

---

## Security Considerations

### API Key Management

**Use organization-scoped keys for series management:**
```
✅ sk_live_org_... (can manage all series)
❌ sk_series_...   (cannot create/modify other series)
```

**Principle of least privilege:**
- **Development keys**: `series:read`, `series:create`
- **Production keys**: `series:read` only
- **Admin keys**: All series scopes for emergency operations

### Safe Production Practices

**Series lifecycle:**
1. **Development**: Create and test series with dev patterns
2. **Staging**: Test with production-like patterns and data volumes
3. **Production**: Create final series with validated patterns
4. **Monitoring**: Track usage and capacity continuously

**Backup strategies:**
- Document all series configurations
- Export generated slug lists before major changes
- Keep series creation scripts in version control
- Test recovery procedures regularly

---

## Related Documentation

- [Authentication](api-authentication) - API key scopes and security
- [API Reference](api-reference) - Complete endpoint documentation
- [Choosing Generation Methods](choosing-generation-method) - When to use mint vs forge vs slice
- [Pattern Syntax Basics](pattern-syntax-basics) - Creating effective patterns
- [Rate Limits & Quotas](api-rate-limits) - Usage limits and monitoring

---

# URL Shortener API
Source: https://dev.slugkit.dev/docs/api-url-shortener

# URL Shortener API

*Exchange long, arbitrary URLs for short, human-readable slugs — and resolve them back again.*

---

## Overview

The URL Shortener turns any URL into a memorable slug generated from one of your series, and resolves that slug back to the original URL on demand. Unlike `mint`, which produces sequential slugs from a counter, the shortener maps a *specific URL* to a slug and remembers the association, so the same URL always yields the same slug within a series.

It is exposed by the generation service alongside `mint`, `slice`, and `forge`, and is governed by its own entitlement and rate limits.

**Key properties:**

- **Deterministic slugs** — slugs are generated from the series' stable seed, exactly like `mint`. No salt is mixed in.
- **Idempotent within a series** — re-shortening the same URL in the same series returns the existing slug (deduplicated by a SHA-256 hash of the normalised URL).
- **Resolution returns data, not a redirect** — `expand` returns the original URL and metadata as JSON. Performing the actual HTTP redirect is the caller's responsibility; SlugKit does not serve a `302`.
- **Usage tracking** — each mapping records how many times it has been expanded and when it was last used.

---

## How It Works

1. You send a URL to **shorten**, optionally specifying which series to use.
2. SlugKit normalises the URL, hashes it, and checks whether that URL already has a slug in the series.
   - If it does, the existing slug is returned (idempotent).
   - If not, a new slug is generated from the series pattern and stored.
3. Callers later **expand** the slug to retrieve the original URL.
4. You can read **stats** for all mappings in a series.

### Series binding

Like `mint` and `slice`, the shortener needs a series to generate slugs from. The series is resolved in this order:

- **Series-scoped API key** — the bound series is used automatically; you do not pass `series`.
- **Organisation-scoped API key** — pass `series` in the request body to choose which series to use.

---

## Required API Key Scopes

The shortener uses dedicated scopes, separate from the generation scopes (`mint`, `slice`, `forge`):

| Operation | Required Scope | Description |
|-----------|----------------|-------------|
| **Shorten a URL** | `url:shorten` | Create (or reuse) a slug for a URL |
| **Expand a slug** | `url:expand` | Resolve a slug back to its original URL |
| **Read statistics** | `url:stats` | List shortened URLs and their expansion counts |

**Note:** The URL Shortener must be enabled for your subscription plan. If the entitlement is disabled, requests return `403` regardless of scopes.

---

## Shortening URLs

Create a slug for a URL.

**Endpoint:** `POST /api/v1/gen/shorten` · **Scope:** `url:shorten`

### Request

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `url` | string | yes | The URL to shorten |
| `series` | string | conditional | Series slug to generate from. Required for organisation-scoped keys; omitted for series-scoped keys |

### Example (series-scoped key)

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/shorten \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/some/very/long/path?with=params"
  }'
```

### Example (organisation-scoped key)

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/shorten \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/some/very/long/path?with=params",
    "series": "cosmic-generator-a4f"
  }'
```

### Response

```json
{
  "slug": "strictly-hidden-rheostat-857",
  "url": "https://example.com/some/very/long/path?with=params",
  "expand_count": 0,
  "created_at": "2026-06-22T11:40:17.887188+00:00"
}
```

| Field | Type | Description |
|-------|------|-------------|
| `slug` | string | The slug mapped to this URL |
| `url` | string | The URL that was shortened |
| `expand_count` | integer | How many times the slug has been expanded |
| `created_at` | string (ISO-8601) | When the mapping was created |
| `last_expanded_at` | string (ISO-8601) | Present only once the slug has been expanded at least once |

### Deduplication

Shortening the same URL in the same series again returns the **same** slug — the call is idempotent:

```bash
# Both calls return the same slug for the same (series, url) pair
curl -X POST https://api.slugkit.com/api/v1/gen/shorten \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/page/one"}'
```

Deduplication is scoped to the series: the same URL shortened in two different series produces two independent slugs.

---

## Expanding Slugs

Resolve a slug back to its original URL. Each successful expansion increments the slug's `expand_count` and updates `last_expanded_at`.

**Endpoint:** `GET /api/v1/gen/expand/{slug}` · **Scope:** `url:expand`

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/expand/strictly-hidden-rheostat-857 \
  -H "X-API-Key: sk_live_..."
```

### Response

```json
{
  "url": "https://example.com/some/very/long/path?with=params",
  "expand_count": 1,
  "created_at": "2026-06-22T11:40:17.887188+00:00",
  "last_expanded_at": "2026-06-22T11:41:11.922269+00:00"
}
```

An unknown slug returns `404`.

**Redirecting is your responsibility.** `expand` deliberately returns JSON rather than an HTTP redirect, so you remain in control of caching, analytics, and the redirect status code. A minimal redirect handler in your application might look like:

```python
import requests
from flask import Flask, redirect, abort

app = Flask(__name__)
API_KEY = "sk_live_..."
BASE_URL = "https://api.slugkit.com/api/v1"

@app.route("/<slug>")
def follow(slug):
    resp = requests.get(f"{BASE_URL}/gen/expand/{slug}",
                        headers={"X-API-Key": API_KEY})
    if resp.status_code == 404:
        abort(404)
    resp.raise_for_status()
    return redirect(resp.json()["url"], code=302)
```

---

## Statistics

List the shortened URLs in a series together with their expansion counts.

**Endpoint:** `POST /api/v1/gen/shorten/stats` (also accepts `GET` with query parameters) · **Scope:** `url:stats`

### Request

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `series` | string | conditional | — | Series slug. Required for organisation-scoped keys; omitted for series-scoped keys |
| `limit` | integer | no | `100` | Maximum mappings to return. Clamped to the range `1`–`1000` |
| `offset` | integer | no | `0` | Number of mappings to skip (pagination) |

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/shorten/stats \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "limit": 10,
    "offset": 0
  }'
```

### Response

A JSON array of mappings:

```json
[
  {
    "slug": "strictly-hidden-rheostat-857",
    "url": "https://example.com/some/very/long/path?with=params",
    "expand_count": 2,
    "created_at": "2026-06-22T11:40:17.887188+00:00",
    "last_expanded_at": "2026-06-22T11:41:11.922269+00:00"
  },
  {
    "slug": "plenty-sublittoral-lighting-714",
    "url": "https://example.com/page/two",
    "expand_count": 0,
    "created_at": "2026-06-22T11:40:37.182379+00:00"
  }
]
```

As with the other endpoints, `last_expanded_at` is only present for slugs that have been expanded at least once.

---

## Quotas, Storage, and Retention

The shortener is metered separately from generation, with three kinds of limit defined by your subscription plan:

### Rate limits

Shorten and expand operations are rate-limited per day, per month, and per request:

- `max_shorten_per_day`, `max_shorten_per_month`, `max_shorten_per_request`
- `max_expand_per_day`, `max_expand_per_month`, `max_expand_per_request`

Exceeding a limit returns `429 Too Many Requests` with the standard rate-limit headers (see [Rate Limits & Quotas](api-rate-limits)).

### Storage cap

`max_shortener_urls` caps how many mappings an organisation may retain at once. When you exceed the cap, the **least recently used** mappings are evicted to make room for new ones. "Recently used" is measured by the last shorten or expand of a mapping, not by when it was created — actively used links survive, stale ones are displaced first.

### Retention window

If `shortener_retention_days` is set, mappings that have not been used (shortened or expanded) within that window are pruned periodically. A value of `-1` means mappings are retained indefinitely. Because retention is measured from **last usage**, expanding a slug refreshes its lifetime.

---

## Error Handling

### Missing scope

```json
{
  "code": "401",
  "message": "Missing required scopes: url:shorten"
}
```

### Shortener not enabled for the plan

```json
{
  "code": "403",
  "message": "URL shortener is not enabled for this subscription"
}
```

### Unknown slug (expand)

```json
{
  "code": "404",
  "message": "Slug not found"
}
```

### Rate limit exceeded

```json
{
  "code": "429",
  "message": "Rate limit exceeded for operation: shorten"
}
```

---

## Integration Example

A small client wrapping shorten, expand, and stats:

```python
import requests

class SlugKitShortener:
    def __init__(self, api_key, series=None,
                 base_url="https://api.slugkit.com/api/v1"):
        self.base_url = base_url
        self.series = series  # required for organisation-scoped keys
        self.headers = {
            "X-API-Key": api_key,
            "Content-Type": "application/json",
        }

    def shorten(self, url):
        body = {"url": url}
        if self.series:
            body["series"] = self.series
        resp = requests.post(f"{self.base_url}/gen/shorten",
                             headers=self.headers, json=body)
        resp.raise_for_status()
        return resp.json()["slug"]

    def expand(self, slug):
        resp = requests.get(f"{self.base_url}/gen/expand/{slug}",
                            headers=self.headers)
        if resp.status_code == 404:
            return None
        resp.raise_for_status()
        return resp.json()["url"]

    def stats(self, limit=100, offset=0):
        body = {"limit": limit, "offset": offset}
        if self.series:
            body["series"] = self.series
        resp = requests.post(f"{self.base_url}/gen/shorten/stats",
                             headers=self.headers, json=body)
        resp.raise_for_status()
        return resp.json()

# Usage (series-scoped key)
shortener = SlugKitShortener("sk_live_...")
slug = shortener.shorten("https://example.com/launch/announcement")
print("short slug:", slug)

original = shortener.expand(slug)
print("resolves to:", original)
```

---

## Related Documentation

- [Authentication](api-authentication) - API key scopes and security
- [Series Management API](api-series-management) - Creating and managing the series slugs are generated from
- [Rate Limits & Quotas](api-rate-limits) - Usage limits, quotas, and monitoring
- [Choosing Generation Methods](choosing-generation-method) - When to use mint, slice, or forge
- [Error Handling](api-error-handling) - Error response formats and retry strategies


---

# SlugKit Generator Benchmark - Aug 28 2025
Source: https://dev.slugkit.dev/docs/axiomatic-tutor-mcx

# The Big Difference 

### Dictionary Filtering

| Benchmark | 20250827 |20250828 | Δ | Details |
| --- | --- |--- | --- | --- |
| FilterDictionary/0 | 202.000 µs | 91.931 µs | 🔽 -54.49% -110.069 µs | word  |
| FilterDictionary/1 | 150.000 µs | 84.200 ns | 🔽 -99.94% -149.916 µs | word:==5  |
| FilterDictionary/2 | 200.000 µs | 821.580 µs | 🔼 310.79% 621.580 µs | word:==10  |
| FilterDictionary/3 | 150.000 µs | 208.000 ns | 🔽 -99.86% -149.792 µs | word:==15  |
| FilterDictionary/4 | 150.000 µs | 209.000 ns | 🔽 -99.86% -149.791 µs | word:==20  |
| FilterDictionary/5 | 183.000 µs | 83.391 µs | 🔽 -54.43% -99.609 µs | word:<10  |
| FilterDictionary/6 | 153.000 µs | 306.000 ns | 🔽 -99.80% -152.694 µs | word:>10  |
| FilterDictionary/7 | 152.000 µs | 6.011 µs | 🔽 -96.05% -145.989 µs | word:<=8  |
| FilterDictionary/8 | 174.000 µs | 304.000 ns | 🔽 -99.83% -173.696 µs | word:>=12  |
| FilterDictionary/9 | 156.000 µs | 83.341 µs | 🔽 -46.58% -72.659 µs | word:!=10  |
| FilterDictionary/10 | 204.000 µs | 889.553 µs | 🔼 336.06% 685.553 µs | word:!=15  |
| FilterDictionary/11 | 695.000 µs | 91.481 µs | 🔽 -86.84% -603.519 µs | word:+tag1  |
| FilterDictionary/12 | 629.000 µs | 45.762 µs | 🔽 -92.72% -583.238 µs | word:+tag2  |
| FilterDictionary/13 | 598.000 µs | 22.684 µs | 🔽 -96.21% -575.316 µs | word:+tag3  |
| FilterDictionary/14 | 601.000 µs | 8.802 µs | 🔽 -98.54% -592.198 µs | word:+tag4  |
| FilterDictionary/15 | 692.000 µs | 62.215 µs | 🔽 -91.01% -629.785 µs | word:-tag1  |
| FilterDictionary/16 | 706.000 µs | 126.590 µs | 🔽 -82.07% -579.410 µs | word:-tag2  |
| FilterDictionary/17 | 752.000 µs | 173.317 µs | 🔽 -76.95% -578.683 µs | word:-tag3  |
| FilterDictionary/18 | 766.000 µs | 193.085 µs | 🔽 -74.79% -572.915 µs | word:-tag4  |
| FilterDictionary/19 | 1.140 ms | 127.259 µs | 🔽 -88.84% -1.013 ms | word:+tag1-tag2  |
| FilterDictionary/20 | 1.001 ms | 134.685 µs | 🔽 -86.54% -866.315 µs | word:+tag1+tag2  |
| FilterDictionary/21 | 1.011 ms | 142.409 µs | 🔽 -85.91% -868.591 µs | word:+tag1+tag2+tag3  |
| FilterDictionary/22 | 900.000 µs | 126.262 µs | 🔽 -85.97% -773.738 µs | word:+tag1+tag2+tag4-tag3  |
| FilterDictionary/23 | 648.000 µs | 93.300 ns | 🔽 -99.99% -647.907 µs | word:+tag1==5  |
| FilterDictionary/24 | 1.006 ms | 158.384 µs | 🔽 -84.26% -847.616 µs | word:+tag1+tag2==10  |
| FilterDictionary/25 | 966.000 µs | 148.810 µs | 🔽 -84.60% -817.190 µs | word:+tag1+tag2!=10  |
| FilterDictionary/26 | 1.002 ms | 241.000 ns | 🔽 -99.98% -1.002 ms | word:+tag1+tag2+tag3==15  |
| FilterDictionary/27 | 890.000 µs | 246.000 ns | 🔽 -99.97% -889.754 µs | word:+tag1+tag2+tag4-tag3==20  |
| FilterDictionary/28 | 709.000 µs | 135.213 µs | 🔽 -80.93% -573.787 µs | word:+tag1<8  |

### Pattern Calculation

| Benchmark | 20250827 |20250828 | Δ | Details |
| --- | --- |--- | --- | --- |
| CalculateSettings/0 | 73.940 µs | 27.460 µs | 🔽 -62.86% -46.480 µs | {verb}-{adverb}  |
| CalculateSettings/1 | 301.710 µs | 139.169 µs | 🔽 -53.87% -162.541 µs | {adverb}-{noun}-{verb}  |
| CalculateSettings/2 | 301.914 µs | 140.671 µs | 🔽 -53.41% -161.243 µs | {adverb}-{noun}-{verb}-{number:4x}  |
| CalculateSettings/3 | 301.136 µs | 139.909 µs | 🔽 -53.54% -161.227 µs | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}  |
| CalculateSettings/4 | 302.194 µs | 140.210 µs | 🔽 -53.60% -161.984 µs | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}  |

### Slug Generation

| Benchmark | 20250827 |20250828 | Δ | Details |
| --- | --- |--- | --- | --- |
| GenerateSlugs/0 | 73.533 µs | 28.222 µs | 🔽 -61.62% -45.311 µs | {verb}-{adverb}  |
| GenerateSlugs/1 | 303.032 µs | 138.858 µs | 🔽 -54.18% -164.174 µs | {adverb}-{noun}-{verb}  |
| GenerateSlugs/2 | 301.868 µs | 140.090 µs | 🔽 -53.59% -161.778 µs | {adverb}-{noun}-{verb}-{number:4x}  |
| GenerateSlugs/3 | 613.231 µs | 283.689 µs | 🔽 -53.74% -329.542 µs | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}  |
| GenerateSlugs/4 | 916.800 µs | 423.584 µs | 🔽 -53.80% -493.216 µs | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}  |

## Full Report

### Seed Hash Calculation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FNV1aHash/1 | 0.699 ns | 0.699 ns | 994698499 |  |
| FNV1aHash/2 | 0.943 ns | 0.943 ns | 744120125 |  |
| FNV1aHash/4 | 1.420 ns | 1.420 ns | 498513809 |  |
| FNV1aHash/8 | 2.520 ns | 2.520 ns | 288517124 |  |
| FNV1aHash/16 | 5.090 ns | 5.080 ns | 100000000 |  |
| FNV1aHash/32 | 10.600 ns | 10.600 ns | 62052016 |  |
| FNV1aHash/64 | 27.600 ns | 27.600 ns | 25255426 |  |


</details>


### Permutation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| PermutePowerOf2/1 | 3.400 ns | 3.400 ns | 205762779 | 2^1 |
| PermutePowerOf2/2 | 3.400 ns | 3.400 ns | 204904237 | 2^2 |
| PermutePowerOf2/4 | 3.390 ns | 3.390 ns | 206445348 | 2^4 |
| PermutePowerOf2/8 | 3.400 ns | 3.400 ns | 206065869 | 2^8 |
| PermutePowerOf2/16 | 3.410 ns | 3.410 ns | 204835983 | 2^16 |
| PermutePowerOf2/18 | 3.450 ns | 3.450 ns | 205240625 | 2^18 |
| Permute/1 | 1.960 ns | 1.960 ns | 359193331 | 10^1 |
| Permute/2 | 2.020 ns | 2.020 ns | 344955458 | 10^2 |
| Permute/4 | 2.960 ns | 2.960 ns | 237652671 | 10^4 |
| Permute/8 | 7.880 ns | 7.880 ns | 86852497 | 10^8 |
| Permute/16 | 15.600 ns | 15.600 ns | 43809828 | 10^16 |
| Permute/18 | 20.500 ns | 20.500 ns | 33947034 | 10^18 |


</details>


### Pattern Parsing


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| ParsePattern/0 | 47.900 ns | 47.900 ns | 14838938 | {number:8d} |
| ParsePattern/1 | 47.000 ns | 47.000 ns | 14805387 | {special:8} |
| ParsePattern/2 | 61.000 ns | 61.000 ns | 10565101 | {special:8-12} |
| ParsePattern/3 | 53.600 ns | 53.600 ns | 12811420 | {noun} |
| ParsePattern/4 | 53.200 ns | 53.200 ns | 13389815 | {Noun} |
| ParsePattern/5 | 52.300 ns | 52.300 ns | 13229138 | {NOUN} |
| ParsePattern/6 | 53.400 ns | 53.400 ns | 13087649 | {nOun} |
| ParsePattern/7 | 57.900 ns | 57.900 ns | 11950772 | {adjective} |
| ParsePattern/8 | 59.200 ns | 59.200 ns | 11379870 | {ADJECTIVE} |
| ParsePattern/9 | 57.100 ns | 57.100 ns | 12103607 | {Adjective} |
| ParsePattern/10 | 57.200 ns | 57.200 ns | 11858118 | {aDjective} |
| ParsePattern/11 | 99.800 ns | 99.800 ns | 7028974 | {adjective:+tag} |
| ParsePattern/12 | 143.000 ns | 143.000 ns | 4994087 | {adjective:+tag1-tag2} |
| ParsePattern/13 | 81.200 ns | 81.200 ns | 8582726 | {adjective:==10} |
| ParsePattern/14 | 167.000 ns | 167.000 ns | 4222932 | {adjective:+tag1-tag2==10} |
| ParsePattern/15 | 117.000 ns | 117.000 ns | 6000900 | {adjective}-{noun} |
| ParsePattern/16 | 172.000 ns | 172.000 ns | 4093416 | {adjective}-{noun}-{verb} |
| ParsePattern/17 | 216.000 ns | 216.000 ns | 3180743 | {adverb}-{adjective}-{noun}-{number:4x} |


</details>


### Pattern Formatting


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FormatPattern/1 | 17.500 ns | 17.500 ns | 39450696 | 1 components |
| FormatPattern/2 | 24.500 ns | 24.500 ns | 28511405 | 2 components |
| FormatPattern/3 | 33.100 ns | 33.000 ns | 21275526 | 3 components |
| FormatPattern/4 | 40.000 ns | 40.000 ns | 17205177 | 4 components |
| FormatPattern/5 | 47.600 ns | 47.600 ns | 14651786 | 5 components |
| FormatPattern/6 | 54.500 ns | 54.500 ns | 12924101 | 6 components |
| FormatPattern/7 | 61.600 ns | 61.600 ns | 11392403 | 7 components |
| FormatPattern/8 | 67.200 ns | 67.200 ns | 10270047 | 8 components |
| FormatPattern/9 | 74.100 ns | 74.100 ns | 9373666 | 9 components |
| FormatPattern/10 | 80.900 ns | 80.900 ns | 8540322 | 10 components |


</details>


### Value Generation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| GenerateHexNumbers/1 | 23.500 ns | 23.500 ns | 30053431 | number:1x |
| GenerateHexNumbers/2 | 25.400 ns | 25.400 ns | 27306195 | number:2x |
| GenerateHexNumbers/4 | 26.500 ns | 26.500 ns | 26553226 | number:4x |
| GenerateHexNumbers/8 | 27.400 ns | 27.400 ns | 25562847 | number:8x |
| GenerateHexNumbers/16 | 32.400 ns | 32.400 ns | 20720021 | number:16x |
| GenerateHexNumbersUppercase/1 | 23.800 ns | 23.800 ns | 29381499 | number:1X |
| GenerateHexNumbersUppercase/2 | 25.600 ns | 25.600 ns | 27498982 | number:2X |
| GenerateHexNumbersUppercase/4 | 26.600 ns | 26.600 ns | 26749569 | number:4X |
| GenerateHexNumbersUppercase/8 | 27.700 ns | 27.700 ns | 25343881 | number:8X |
| GenerateHexNumbersUppercase/16 | 32.500 ns | 32.500 ns | 21444031 | number:16X |
| GenerateDecNumbers/1 | 51.500 ns | 51.500 ns | 13483103 | number:1d |
| GenerateDecNumbers/2 | 61.300 ns | 61.300 ns | 11269390 | number:2d |
| GenerateDecNumbers/4 | 60.900 ns | 60.900 ns | 11327052 | number:4d |
| GenerateDecNumbers/8 | 56.800 ns | 56.800 ns | 12341145 | number:8d |
| GenerateDecNumbers/16 | 81.700 ns | 81.700 ns | 8541616 | number:16d |
| GenerateDecNumbers/18 | 98.400 ns | 98.200 ns | 7541895 | number:18d |
| GenerateRomanNumbersUppercase/1 | 17.900 ns | 17.900 ns | 39085693 | number:1R |
| GenerateRomanNumbersUppercase/2 | 14.400 ns | 14.400 ns | 48265225 | number:2R |
| GenerateRomanNumbersUppercase/4 | 11.600 ns | 11.600 ns | 60876734 | number:4R |
| GenerateRomanNumbersUppercase/8 | 31.500 ns | 31.500 ns | 21675498 | number:8R |
| GenerateRomanNumbersUppercase/15 | 24.800 ns | 24.800 ns | 27987788 | number:15R |
| GenerateRomanNumbersLowercase/1 | 64.600 ns | 64.600 ns | 10779202 | number:1r |
| GenerateRomanNumbersLowercase/2 | 60.400 ns | 60.400 ns | 11584633 | number:2r |
| GenerateRomanNumbersLowercase/4 | 65.300 ns | 65.300 ns | 10747873 | number:4r |
| GenerateRomanNumbersLowercase/8 | 103.000 ns | 103.000 ns | 6761050 | number:8r |
| GenerateRomanNumbersLowercase/15 | 95.600 ns | 95.600 ns | 7364480 | number:15r |
| GenerateFromDictionary/1000 | 193.000 ns | 193.000 ns | 3611881 |  |
| GenerateFromDictionary/10000 | 200.000 ns | 200.000 ns | 3487510 |  |
| GenerateFromDictionary/100000 | 204.000 ns | 204.000 ns | 3485116 |  |
| GenerateFromDictionary/1000000 | 316.000 ns | 316.000 ns | 2197158 |  |
| GenerateFromDictionaryUppercase/1000 | 339.000 ns | 339.000 ns | 2085393 |  |
| GenerateFromDictionaryUppercase/10000 | 355.000 ns | 354.000 ns | 2018183 |  |
| GenerateFromDictionaryUppercase/100000 | 349.000 ns | 349.000 ns | 2004096 |  |
| GenerateFromDictionaryUppercase/1000000 | 469.000 ns | 469.000 ns | 1488585 |  |
| GenerateFromDictionaryTitleCase/1000 | 6.481 µs | 6.481 µs | 107925 |  |
| GenerateFromDictionaryTitleCase/10000 | 6.513 µs | 6.513 µs | 108274 |  |
| GenerateFromDictionaryTitleCase/100000 | 6.503 µs | 6.503 µs | 104883 |  |
| GenerateFromDictionaryTitleCase/1000000 | 6.656 µs | 6.656 µs | 106608 |  |
| GenerateFromDictionaryMixedCase/1000 | 359.000 ns | 359.000 ns | 1950344 |  |
| GenerateFromDictionaryMixedCase/10000 | 404.000 ns | 404.000 ns | 1742191 |  |
| GenerateFromDictionaryMixedCase/100000 | 443.000 ns | 443.000 ns | 1561743 |  |
| GenerateFromDictionaryMixedCase/1000000 | 629.000 ns | 629.000 ns | 1099083 |  |


</details>


### Dictionary Building [^1]


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| BuildLengthIndex | 8.818 ms | 8.818 ms | 75 |  |
| BuildTagIndex | 1.795 ms | 1.795 ms | 371 |  |
| BuildCombinedIndex | 11.697 ms | 11.667 ms | 60 |  |
| BuildDictionary | 18.235 ms | 18.191 ms | 38 |  |


</details>


### IndexQuery [^1]


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| QueryLengthIndex/0 | 7.900 ns | 7.900 ns | 93682196 | word:==5 |
| QueryLengthIndex/1 | 126.000 ns | 126.000 ns | 5424545 | word:==10 |
| QueryLengthIndex/2 | 41.000 ns | 41.000 ns | 17731531 | word:==15 |
| QueryLengthIndex/3 | 39.300 ns | 39.300 ns | 17233307 | word:==20 |
| QueryLengthIndex/4 | 17.600 ns | 17.600 ns | 39269393 | word:<10 |
| QueryLengthIndex/5 | 94.700 ns | 94.700 ns | 7346591 | word:>10 |
| QueryLengthIndex/6 | 17.500 ns | 17.500 ns | 40126494 | word:<=8 |
| QueryLengthIndex/7 | 95.000 ns | 95.000 ns | 7438707 | word:>=12 |
| QueryLengthIndex/8 | 161.000 ns | 161.000 ns | 4574169 | word:!=10 |
| QueryLengthIndex/9 | 197.000 ns | 197.000 ns | 3574629 | word:!=15 |
| QueryTagIndex/0 | 13.069 µs | 13.069 µs | 57060 | word:+tag1 |
| QueryTagIndex/1 | 6.638 µs | 6.638 µs | 104888 | word:+tag2 |
| QueryTagIndex/2 | 3.384 µs | 3.384 µs | 204262 | word:+tag3 |
| QueryTagIndex/3 | 976.000 ns | 976.000 ns | 741047 | word:+tag4 |
| QueryTagIndex/4 | 61.988 µs | 61.987 µs | 11332 | word:-tag1 |
| QueryTagIndex/5 | 84.047 µs | 84.046 µs | 8213 | word:-tag2 |
| QueryTagIndex/6 | 107.410 µs | 107.404 µs | 6502 | word:-tag3 |
| QueryTagIndex/7 | 118.707 µs | 118.706 µs | 5879 | word:-tag4 |
| QueryTagIndex/8 | 84.266 µs | 84.265 µs | 8344 | word:+tag1-tag2 |
| QueryTagIndex/9 | 95.293 µs | 95.293 µs | 6961 | word:+tag1+tag2 |
| QueryTagIndex/10 | 117.648 µs | 117.641 µs | 5901 | word:+tag1+tag2+tag3 |
| QueryTagIndex/11 | 127.223 µs | 127.222 µs | 5658 | word:+tag1+tag2+tag4-tag3 |
| QueryCombinedIndex/0 | 92.374 µs | 92.373 µs | 7548 | word |
| QueryCombinedIndex/1 | 8.450 ns | 8.450 ns | 88154270 | word:==5 |
| QueryCombinedIndex/2 | 837.062 µs | 837.056 µs | 836 | word:==10 |
| QueryCombinedIndex/3 | 43.900 ns | 43.900 ns | 16822086 | word:==15 |
| QueryCombinedIndex/4 | 42.700 ns | 42.700 ns | 16056788 | word:==20 |
| QueryCombinedIndex/5 | 84.793 µs | 84.793 µs | 8207 | word:<10 |
| QueryCombinedIndex/6 | 97.700 ns | 97.700 ns | 6831818 | word:>10 |
| QueryCombinedIndex/7 | 5.898 µs | 5.898 µs | 116763 | word:<=8 |
| QueryCombinedIndex/8 | 99.100 ns | 99.100 ns | 7009264 | word:>=12 |
| QueryCombinedIndex/9 | 85.370 µs | 85.369 µs | 8197 | word:!=10 |
| QueryCombinedIndex/10 | 905.720 µs | 905.714 µs | 768 | word:!=15 |
| QueryCombinedIndex/11 | 92.608 µs | 92.607 µs | 7504 | word:+tag1 |
| QueryCombinedIndex/12 | 47.494 µs | 47.494 µs | 14811 | word:+tag2 |
| QueryCombinedIndex/13 | 22.864 µs | 22.864 µs | 31001 | word:+tag3 |
| QueryCombinedIndex/14 | 8.552 µs | 8.552 µs | 84128 | word:+tag4 |
| QueryCombinedIndex/15 | 61.959 µs | 61.799 µs | 11251 | word:-tag1 |
| QueryCombinedIndex/16 | 127.051 µs | 127.050 µs | 5489 | word:-tag2 |
| QueryCombinedIndex/17 | 171.215 µs | 171.214 µs | 4047 | word:-tag3 |
| QueryCombinedIndex/18 | 193.657 µs | 193.656 µs | 3559 | word:-tag4 |
| QueryCombinedIndex/19 | 127.249 µs | 127.248 µs | 5450 | word:+tag1-tag2 |
| QueryCombinedIndex/20 | 142.007 µs | 142.006 µs | 4967 | word:+tag1+tag2 |
| QueryCombinedIndex/21 | 141.659 µs | 141.658 µs | 5049 | word:+tag1+tag2+tag3 |
| QueryCombinedIndex/22 | 122.774 µs | 122.774 µs | 5227 | word:+tag1+tag2+tag4-tag3 |
| QueryCombinedIndex/23 | 8.410 ns | 8.410 ns | 88670872 | word:+tag1==5 |
| QueryCombinedIndex/24 | 127.535 µs | 127.535 µs | 5460 | word:+tag1==10 |
| QueryCombinedIndex/25 | 161.572 µs | 161.570 µs | 4455 | word:+tag1+tag2==10 |
| QueryCombinedIndex/26 | 148.458 µs | 148.457 µs | 4511 | word:+tag1+tag2!=10 |
| QueryCombinedIndex/27 | 41.100 ns | 41.100 ns | 17445256 | word:+tag1+tag2+tag3==15 |
| QueryCombinedIndex/28 | 41.100 ns | 41.100 ns | 16278904 | word:+tag1+tag2+tag4-tag3==20 |
| QueryCombinedIndex/29 | 135.517 µs | 135.515 µs | 5109 | word:+tag1<8 |
| QueryCombinedIndex/30 | 150.304 µs | 150.303 µs | 4667 | word:+tag1>=8 |


</details>


### Index Estimation [^1]


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| EstimateTagIndexWordCount/0 | 15.400 ns | 15.400 ns | 45328286 | word:+tag1 |
| EstimateTagIndexWordCount/1 | 15.400 ns | 15.400 ns | 44780488 | word:+tag2 |
| EstimateTagIndexWordCount/2 | 13.100 ns | 13.100 ns | 51629622 | word:+tag3 |
| EstimateTagIndexWordCount/3 | 13.100 ns | 13.100 ns | 54241474 | word:+tag4 |
| EstimateTagIndexWordCount/4 | 16.000 ns | 16.000 ns | 44405537 | word:-tag1 |
| EstimateTagIndexWordCount/5 | 15.200 ns | 15.200 ns | 44674827 | word:-tag2 |
| EstimateTagIndexWordCount/6 | 13.600 ns | 13.600 ns | 52539586 | word:-tag3 |
| EstimateTagIndexWordCount/7 | 13.200 ns | 13.200 ns | 53393541 | word:-tag4 |
| EstimateTagIndexWordCount/8 | 29.000 ns | 29.000 ns | 23997580 | word:+tag1-tag2 |
| EstimateTagIndexWordCount/9 | 29.700 ns | 29.700 ns | 24453049 | word:+tag1+tag2 |
| EstimateTagIndexWordCount/10 | 43.900 ns | 43.900 ns | 15500770 | word:+tag1+tag2+tag3 |
| EstimateTagIndexWordCount/11 | 56.500 ns | 56.500 ns | 12061107 | word:+tag1+tag2+tag4-tag3 |


</details>


### Dictionary Filtering [^1]


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FilterDictionary/0 | 91.931 µs | 91.930 µs | 7657 | word |
| FilterDictionary/1 | 84.200 ns | 84.200 ns | 8395219 | word:==5 |
| FilterDictionary/2 | 821.580 µs | 821.575 µs | 832 | word:==10 |
| FilterDictionary/3 | 208.000 ns | 208.000 ns | 3319564 | word:==15 |
| FilterDictionary/4 | 209.000 ns | 209.000 ns | 3365281 | word:==20 |
| FilterDictionary/5 | 83.391 µs | 83.390 µs | 8460 | word:<10 |
| FilterDictionary/6 | 306.000 ns | 306.000 ns | 2268747 | word:>10 |
| FilterDictionary/7 | 6.011 µs | 6.011 µs | 116386 | word:<=8 |
| FilterDictionary/8 | 304.000 ns | 304.000 ns | 2266346 | word:>=12 |
| FilterDictionary/9 | 83.341 µs | 83.329 µs | 8408 | word:!=10 |
| FilterDictionary/10 | 889.553 µs | 889.547 µs | 786 | word:!=15 |
| FilterDictionary/11 | 91.481 µs | 91.480 µs | 7645 | word:+tag1 |
| FilterDictionary/12 | 45.762 µs | 45.762 µs | 14765 | word:+tag2 |
| FilterDictionary/13 | 22.684 µs | 22.684 µs | 30622 | word:+tag3 |
| FilterDictionary/14 | 8.802 µs | 8.802 µs | 79711 | word:+tag4 |
| FilterDictionary/15 | 62.215 µs | 62.215 µs | 11316 | word:-tag1 |
| FilterDictionary/16 | 126.590 µs | 126.589 µs | 5497 | word:-tag2 |
| FilterDictionary/17 | 173.317 µs | 172.815 µs | 4050 | word:-tag3 |
| FilterDictionary/18 | 193.085 µs | 193.084 µs | 3620 | word:-tag4 |
| FilterDictionary/19 | 127.259 µs | 127.258 µs | 5524 | word:+tag1-tag2 |
| FilterDictionary/20 | 134.685 µs | 134.683 µs | 4903 | word:+tag1+tag2 |
| FilterDictionary/21 | 142.409 µs | 142.405 µs | 4793 | word:+tag1+tag2+tag3 |
| FilterDictionary/22 | 126.262 µs | 126.261 µs | 5029 | word:+tag1+tag2+tag4-tag3 |
| FilterDictionary/23 | 93.300 ns | 93.300 ns | 7440480 | word:+tag1==5 |
| FilterDictionary/24 | 158.384 µs | 158.383 µs | 4687 | word:+tag1+tag2==10 |
| FilterDictionary/25 | 148.810 µs | 148.809 µs | 4811 | word:+tag1+tag2!=10 |
| FilterDictionary/26 | 241.000 ns | 240.000 ns | 2935955 | word:+tag1+tag2+tag3==15 |
| FilterDictionary/27 | 246.000 ns | 246.000 ns | 2838020 | word:+tag1+tag2+tag4-tag3==20 |
| FilterDictionary/28 | 135.213 µs | 135.212 µs | 5144 | word:+tag1<8 |
| FilterDictionary/29 | 150.981 µs | 150.980 µs | 4657 | word:+tag1>=8 |


</details>


### Pattern Calculation [^2]


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| CalculateSettings/0 | 27.460 µs | 27.460 µs | 24998 | {verb}-{adverb} |
| CalculateSettings/1 | 139.169 µs | 139.168 µs | 5147 | {adverb}-{noun}-{verb} |
| CalculateSettings/2 | 140.671 µs | 140.670 µs | 5025 | {adverb}-{noun}-{verb}-{number:4x} |
| CalculateSettings/3 | 139.909 µs | 139.909 µs | 5022 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| CalculateSettings/4 | 140.210 µs | 139.856 µs | 4975 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |


</details>


### Slug Generation [^2]


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| GenerateSlugInternal/0 | 462.000 ns | 462.000 ns | 1504968 | {verb}-{adverb} |
| GenerateSlugInternal/1 | 690.000 ns | 690.000 ns | 1039834 | {adverb}-{noun}-{verb} |
| GenerateSlugInternal/2 | 720.000 ns | 720.000 ns | 979188 | {adverb}-{noun}-{verb}-{number:4x} |
| GenerateSlugInternal/3 | 1.313 µs | 1.313 µs | 535804 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| GenerateSlugInternal/4 | 1.986 µs | 1.985 µs | 352096 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| GenerateSlugs/0 | 28.222 µs | 28.222 µs | 24642 | {verb}-{adverb} |
| GenerateSlugs/1 | 138.858 µs | 138.857 µs | 5027 | {adverb}-{noun}-{verb} |
| GenerateSlugs/2 | 140.090 µs | 140.089 µs | 5031 | {adverb}-{noun}-{verb}-{number:4x} |
| GenerateSlugs/3 | 283.689 µs | 283.660 µs | 2500 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| GenerateSlugs/4 | 423.584 µs | 423.582 µs | 1665 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |

</details>

---

[^1]: A synthetic dictionary was used. 100K words with length from 3 to 20 characters. `tag1` has probability of 100%, `tag2` has probability of 50%, `tag3` has probability of 25% and `tag4` has probability of 10%. For consistent benchmarks stable permutations were used to generate tags and word length jitter.

[^2]: Synthetic dictionaries were used with numbers close to reality. Nouns: 100K, adjectives: 30K, verbs: 20K, adverbs: 10K. 


---

# Choosing Generation Methods
Source: https://dev.slugkit.dev/docs/choosing-generation-method

# Choosing Generation Methods

SlugKit offers three distinct generation methods: **Forge**, **Mint**, and **Slice**. Each is optimized for different scenarios and comes with specific trade-offs. This guide helps you choose the right method for your use case.

**Prerequisites:** Understanding from [Core Concepts](developer-core-concepts)  
**Reading Time:** 8 minutes

## Quick Decision Tree

Start here for a fast decision:

```
Are you experimenting or need custom patterns?
├─ YES → Use FORGE
└─ NO: Do you have or can set up a series?
   ├─ NO → Use FORGE (series setup required for mint/slice)
   └─ YES: Do you need to consume slugs for production use?
      ├─ YES → Use MINT (advances counter, guarantees uniqueness)
      └─ NO → Use SLICE (preview only, no counter advancement)
```

**Key Point:** Both MINT and SLICE require a configured series. The difference is that MINT advances the series counter while SLICE does not.

## Method Comparison Overview

| Feature | Forge | Mint | Slice |
|---------|-------|------|-------|
| **Uniqueness** | Pattern + seed scoped | Guaranteed within series | Same as mint (preview only) |
| **State Management** | Stateless | Advances series counter | No counter changes |
| **Setup Required** | None | Series configuration | Series configuration |
| **Performance** | Fast (3-20μs) | Fastest (3-20μs) | Fastest (3-20μs) |
| **Use Complexity** | Simple | Simple | Simple |
| **Scalability** | Pattern-dependent | Series capacity limited | Unlimited preview |
| **Production Ready** | With careful design | Yes | Preview/testing only |


---

# Contacts
Source: https://dev.slugkit.dev/docs/contacts

## Legal Information

* Company name: **Sergei Fedorov pr Računarsko Programiranje cpp Beograd**
* Matični broj (Registration number): **68137870**
* PIB (TIN): **115150397**
* Address: **Studentski trg 4/7, Beograd, Serbia 11000**

## Contacts

* Email: sergei@slugkit.dev
* Phone: +381677454700
* LinkedIn: 
  - [SlugKit](https://www.linkedin.com/company/slugkit/)
  - [Sergei Fedorov](https://www.linkedin.com/in/sergei-fedorov/)

---

# Cookie Policy - 2025-08
Source: https://dev.slugkit.dev/docs/cookie-policy-2025-08

# Cookie Policy
**Effective Date:** 10 August 2025  
**Version:** 2025-08

This Cookie Policy explains how **[Your Company Name]** (“we”, “us”, “our”) uses cookies and similar technologies when you use our website and services.

---

## 1. What Are Cookies?
Cookies are small text files stored in your browser. They allow websites to remember information between pages or visits. Similar technologies, such as local storage, store information in your browser for a specific purpose.

---

## 2. Types of Cookies We Use

We only use **strictly necessary cookies**. These are essential for our website to function and for you to log in securely. They cannot be disabled without affecting the core functionality of the site.

| Cookie Name Pattern | Purpose | Type | Expiry |
|---------------------|---------|------|--------|
| `auth0.*.is.authenticated`<br>`_legacy_auth0.*.is.authenticated` | Maintains your secure login session through the Auth0 authentication service | HTTP-only, Secure, SameSite | Session or until logout |

> **Note:** Cookie names include dynamic identifiers generated by the Auth0 SDK. The patterns above cover all such cookies used for authentication.

---

## 3. Local Storage Use
We also store your **light/dark theme preference** in your browser’s local storage.  
- This is used only to display the site in your preferred appearance.  
- It does not contain personal data, is not shared with third parties, and does not track you.  
- This setting remains until you clear your browser storage.

---

## 4. No Tracking or Advertising Cookies
We do **not** use cookies for:
- Analytics or performance tracking  
- Advertising or marketing  
- Profiling or cross-site tracking

---

## 5. How to Control Cookies
- **Essential cookies**: Cannot be disabled if you want to log in, as they are required for authentication. If you do not wish to accept them, you may still browse the public parts of our site without logging in.
- **Local storage**: You can delete your theme preference at any time via your browser’s settings.

---

## 6. Changes to This Policy
We may update this Cookie Policy from time to time to reflect changes in technology or legal requirements. Updates will be posted here with a revised effective date.

---

**Contact**  
If you have questions about this Cookie Policy, contact us at:  
**[support@slugkit.dev]**

---

# Core Value Proposition
Source: https://dev.slugkit.dev/docs/core-value-proposition

## Blazing Performance & Astronomical Scale *

Sub-millisecond generation at 3-20μs per slug with capacities reaching beyond 10^18 unique combinations. A simple `{adjective}-{noun}-{number:4x}` pattern alone provides over 23 trillion possibilities. Built in C++ with the userver framework for production workloads that scale.

## Mathematical Uniqueness

No collisions, no guesswork. Series provide mathematical guarantees for uniqueness within defined domains. Capacity calculations tell you exactly how many combinations are available before you start.

## Powerful Pattern Language

From simple `{adjective}-{noun}` combinations to sophisticated filtering with `{adjective:+pos}-{noun:<8}`. Add semantic tags, length constraints, and multiple number formats. Then take it further with arbitrary text placement and mathematical case transformations - create anything from `user-{Noun}-{number:3d}` to `🚀 {AdJeCtIvE} {noun}` launched! whilst maintaining uniqueness guarantees.

* *No AI or LLMs involved. Just good old-fashioned deterministic algorithms, mathematical precision, and carefully curated dictionaries totalling 80,000+ words that won't embarrass you in production.*


---

# Core Concepts
Source: https://dev.slugkit.dev/docs/developer-core-concepts

# Core Concepts

Understanding the key concepts behind SlugKit will help you make better decisions about patterns, generation methods, and integration strategies. This guide covers the fundamental ideas that power SlugKit's unique approach to human-readable ID generation.

## What Are Slugs?

**Slugs** are human-readable identifiers that replace traditional UUIDs, sequential numbers, or random strings with meaningful, memorable text.

### The Problem with Traditional IDs

```
UUIDs:           f47ac10b-58cc-4372-a567-0e02b2c3d479
Sequential IDs:  1, 2, 3, 4, 5...
Random Strings:  x8j2k9m4n7q1
```

**Problems:**
- Hard to remember and communicate
- No semantic meaning
- Difficult to debug and trace
- Poor user experience
- Sequential IDs reveal business metrics

### The SlugKit Solution

```
SlugKit Slugs:   smart-database-247
                 user-clever-dolphin-42
                 deploy-secure-platform@v12
```

**Benefits:**
- Easy to remember: "the smart database project"
- Meaningful context: users understand what they refer to
- Debugging friendly: logs are readable
- Professional appearance: suitable for customer-facing systems
- Mathematically unique: no collisions within defined domains

## Patterns: The Heart of SlugKit

**Patterns** are templates that define the structure of your slugs. They combine static text with dynamic placeholders.

### Basic Pattern Structure

```
Pattern:  {adjective}-{noun}-{number:3d}
Output:   smart-database-247
          brilliant-server-891
          secure-platform-456
```

**Key Rules:**
- **Static text** (like `-` or `@`) appears exactly as written
- **Placeholders** (like `{adjective}`) get replaced with generated content
- **Constraints** (like `:3d` or `:+pos`) control what gets generated

### Pattern Examples by Use Case

**Web Development:**
```
{adjective}-{noun}                    → smart-database
api/{noun:+object}/{adjective}-{verb} → api/users/secure-login
{Adjective}{Noun}Component            → SmartDatabaseComponent
```

**User Systems:**
```
user-{adjective:+pos}-{noun:+animal}-{number:2d} → user-clever-dolphin-42
{adjective:+pos}<6@{noun:+person}<8               → smart@creator
team-{ADJECTIVE}-{NOUN}                          → team-BRILLIANT-TIGERS
```

**Infrastructure:**
```
{adjective:+obj}-{noun:+device}-{env}-{number:2d} → stable-server-prod-01
{ADJECTIVE}_{NOUN}_CONFIG                        → SECURE_DATABASE_CONFIG
deploy-{adjective}-{noun}@v{number:2d}           → deploy-smart-platform@v12
```

## Three Generation Methods

SlugKit offers three distinct approaches to slug generation, each optimised for different use cases.

### 1. Forge: Custom Pattern Generation

**Best for:** Testing, custom formats, themed content, one-off generation

**How it works:** You provide a pattern, and SlugKit generates slugs based on that pattern with optional seeding for reproducibility.

```python
# Custom product names
client.forge(
    pattern="{adjective:+pos}-{noun:+device}-{number:4x}",
    count=10,
    seed="product-launch-2024"
)
# Output: ['brilliant-laptop-a1b2', 'amazing-server-c3d4', ...]
```

**Key Features:**
- Complete pattern control
- Deterministic with seeds
- No state management
- Ideal for experimentation

### 2. Mint: Managed Series Generation

**Best for:** Production applications, guaranteed uniqueness, user handles, product IDs

**How it works:** You create a "series" with a predefined pattern, and SlugKit manages counters to ensure every minted slug is unique within that series.

```python
# Production user handles (requires series setup)
client.mint(
    series_slug="user-handles",
    count=100
)
# Output: guaranteed unique slugs following the series pattern
```

**Key Features:**
- Guaranteed uniqueness within series
- Automatic counter management
- Distributed-safe
- Production-ready
- State management included
- **Automatic rotation** when capacity is reached

### 3. Slice: Preview Generation

**Best for:** Planning, coordination, previews, testing upcoming slugs

**How it works:** Extract specific ranges from a series sequence without advancing the counter. See what's coming without consuming the slugs.

```python
# Preview upcoming user handles
client.slice(
    series_slug="user-handles",
    sequence=1000,
    count=50
)
# Output: shows slugs 1000-1050 without consuming them
```

**Key Features:**
- No state modification
- Deterministic access to any position
- Perfect for distributed coordination
- Preview upcoming slugs

## Understanding Uniqueness

SlugKit provides different types of uniqueness guarantees depending on how you use it.

### Pattern-Based Uniqueness (Forge)

With `forge()`, uniqueness depends on your pattern and seed:

```python
# Same pattern + seed = same results
client.forge(pattern="{adjective}-{noun}", seed="test")
# Always produces: ['wise-server', 'smart-database', 'secure-platform']

# Different seed = different results  
client.forge(pattern="{adjective}-{noun}", seed="prod")
# Produces: ['brilliant-network', 'active-system', 'stable-cache']
```

**Uniqueness scope:** Within the same pattern and seed combination

### Series-Based Uniqueness (Mint)

With `mint()`, uniqueness is guaranteed within the series domain:

```python
# Every mint call returns never-before-seen slugs
client.mint(series_slug="user-handles", count=5)
# First call:  ['user-clever-dolphin-01', 'user-smart-tiger-02', ...]
client.mint(series_slug="user-handles", count=5)  
# Second call: ['user-wise-eagle-06', 'user-active-bear-07', ...]
```

**Uniqueness scope:** Within the entire series, across all time

### Mathematical Capacity

Every pattern has a finite capacity - the total number of unique slugs it can generate:

```python
# Check pattern capacity
capacity_info = client.validate_pattern("{adjective}-{noun}")
# Result: ~708 million combinations

# Higher capacity with numbers
capacity_info = client.validate_pattern("{adjective}-{noun}-{number:4x}")  
# Result: ~46 trillion combinations
```

## Series: Managed Slug Domains

A **series** is a configured slug generator that manages uniqueness and state for production applications.

### Series Components

**Pattern Template:** Defines the structure of generated slugs
```yaml
pattern: "{adjective:+pos<8}-{noun:+animal<8}-{number:2d}"
```

**Counter State:** Tracks the next slug to be generated
```yaml
current_position: 15347
```

**Capacity Calculation:** Total unique slugs available
```yaml
capacity: 2,441,406,720  # combinations possible
```

### Series Lifecycle

1. **Creation:** Define pattern, seed, and initial counter position
2. **Minting:** Generate unique slugs, advancing the counter
3. **Monitoring:** Track usage against capacity
4. **Automatic Rotation:** Seamless transition when capacity is reached
5. **Management:** Reset, modify, or archive as needed

### Automatic Series Rotation

When a series reaches its mathematical capacity, SlugKit automatically rotates to continue providing unique slugs:

**How Rotation Works:**
- **Seamless transition:** No interruption in slug generation
- **Maintained uniqueness:** Each rotation cycle maintains uniqueness guarantees
- **No manual intervention:** Rotation happens automatically in the background
- **Performance consistency:** Generation speed remains constant through rotation
- **Continued service:** Applications never experience "capacity exhausted" errors

**Practical Example:**
```python
# Series with 1 million capacity reaches position 1,000,000
client.mint(series_slug="user-handles", count=1)  
# Returns: ['user-smart-dolphin-01']  (rotation cycle 2 begins)

client.mint(series_slug="user-handles", count=1)  
# Returns: ['user-clever-tiger-02']   (different from cycle 1)
```

**Benefits:**
- **Infinite scalability:** Series never "run out" of slugs
- **Zero downtime:** No service interruption during rotation
- **Predictable behaviour:** Applications don't need special handling
- **Continued variety:** Each rotation cycle provides fresh slug combinations

**Monitoring Rotations:**
- Track rotation cycles via usage analytics
- Monitor capacity utilisation trends
- Plan for rotation frequency based on usage patterns
- No alerting needed for rotation events (they're seamless)

## Word Dictionaries and Filtering

SlugKit includes comprehensive word dictionaries with sophisticated filtering capabilities.

### Available Word Types

```python
# Get dictionary information
client.dictionary_info()
# Returns: adjectives (17,082), nouns (41,469), verbs (8,405), etc.
```

### Tag-Based Filtering

**Emotional Tone:**
```
{adjective:+pos}  → positive words: brilliant, amazing, clever
{adjective:+neg}  → negative words: broken, failed, slow
{adjective:+neut} → neutral words: standard, normal, basic
```

**Content Categories:**
```
{noun:+animal}    → animals: dolphin, tiger, eagle
{noun:+device}    → technology: server, database, laptop
{noun:+person}    → people: user, admin, developer
```

**Length Constraints:**
```
{adjective:<6}    → max 5 characters: smart, wise, quick
{noun:>=4}        → min 4 characters: server, platform
{noun:==5}        → exactly 5 characters: admin, tiger
```

### Combining Filters

```python
# Positive tech words under 6 characters
pattern = "{adjective:+pos+obj<6}-{noun:+device<8}"
# Result: "smart-server", "wise-laptop", "quick-tablet"
```

## Case Transformations

SlugKit supports mathematical case transformations where the case pattern defines the output:

### Standard Cases
```
{noun}      → lowercase: "database"
{NOUN}      → UPPERCASE: "DATABASE"  
{Noun}      → Title Case: "Database"
```

### Mixed Case Patterns
```
{nOuN}      → Mixed case: "dAtAbAsE"
{NoUn}      → Mixed case: "DaTaBase"
{NouN}      → Mixed case: "DatAbasE"
```

**Use Cases:**
- **Component naming:** `{Adjective}{Noun}Component`
- **Environment variables:** `{ADJECTIVE}_{NOUN}_CONFIG`
- **Visual distinction:** `{aDjEcTiVe}-{NoUn}` for unique appearance

## Performance and Scaling

### Generation Performance

SlugKit is optimised for high-throughput scenarios:

- **Individual slugs:** 3-20μs generation time
- **Bulk operations:** Improved per-slug performance
- **Streaming:** Available for large batches

### Capacity Planning

**Consider pattern complexity:**
```python
# Simple = fast, high capacity
"{adjective}-{noun}"                    # 708M combinations

# Complex = slower, massive capacity  
"{adjective:+pos<6}-{noun:+device<8}-{number:4x}"  # 10B+ combinations
```

**Monitor series usage:**
```python
# Check series capacity and usage
series_info = client.series_info("user-handles")
print(f"Used: {series_info.current_position}")
print(f"Capacity: {series_info.total_capacity}")
print(f"Remaining: {series_info.remaining_capacity}")
```

## Best Practices

### Pattern Design

**Start simple, add complexity as needed:**
```python
# Start: {adjective}-{noun}
# Add numbers: {adjective}-{noun}-{number:3d}  
# Add filtering: {adjective:+pos}-{noun:+device}-{number:3d}
# Add constraints: {adjective:+pos<6}-{noun:+device<8}-{number:3d}
```

**Consider your audience:**
```python
# Customer-facing: use +pos (positive) tags
# Internal tools: +obj (objective) tags acceptable
# Gaming: +animal tags for memorable handles
```

### Generation Method Selection

**Use Forge for:**
- Prototyping and testing
- Custom one-off requirements
- Themed content generation
- Deterministic seeding needs

**Use Mint for:**
- Production user handles
- Product IDs and SKUs
- Transaction identifiers
- Any system requiring uniqueness guarantees

**Use Slice for:**
- Planning and capacity estimation
- Distributed system coordination
- Preview generation
- Testing without state changes

### Production Considerations

**API Key Management:**
- Use environment variables
- Rotate keys regularly
- Monitor usage and quotas
- Implement proper error handling

**Monitoring and Alerting:**
- Track series capacity usage
- Monitor generation performance
- Set up quota alerts
- Log pattern validation errors
- **No need to alert on series rotations** (they're automatic and seamless)

## Understanding the Mathematics

SlugKit uses sophisticated mathematical models to ensure optimal slug distribution and capacity utilisation.

### LCM-Based Capacity Calculation

Instead of simple multiplication, SlugKit uses the Least Common Multiple (LCM) of all pattern components to maximise unique combinations:

```
Pattern: {adjective}-{noun}-{number:2x}
Components: 17,082 adjectives × 41,469 nouns × 256 hex numbers
Capacity: LCM(17,082, 41,469, 256) = optimised for maximum variety
```

### Prime Optimisation

Dictionary sizes are optimised to nearby primes when beneficial, improving the LCM calculation and ensuring better distribution of word combinations.

This mathematical foundation ensures that your slugs remain varied and unpredictable even at scale, and enables seamless rotation when capacity limits are reached.

## Next Steps

Now that you understand SlugKit's core concepts:

**Practice with Patterns:** [Pattern Language Basics](pattern-syntax-basics)
**Choose Your Use Case:** [Integration Guides](guide-web-development)
**Plan for Production:** [Using Mint for Guaranteed Uniqueness](api-mint-endpoint)
**Optimise Performance:** [Pattern Performance Guide](pattern-performance-optimization)

Ready to dive deeper? **[Learn Advanced Pattern Features](pattern-advanced-features)** or **[Explore Real-World Examples](examples-use-cases)**.


---

# Quick Start
Source: https://dev.slugkit.dev/docs/developer-onboarding-journey

## Get Started in Minutes

Ready to generate beautiful, unique identifiers? Follow these three steps to go from idea to implementation.

### 1. Explore Patterns
**Try before you commit.** Use our interactive playground to test patterns, see capacity calculations, and generate sample slugs without any setup.

[**Open Pattern Playground →**](/playground)

*No registration required - experiment with any pattern and see live results instantly.*

---

### 2. Get Your API Key
**Choose your integration method.** Register for free and get the credentials that work best for your project.

[**Get API Key →**](/auth/register) | [**Get SDK Config →**](/articles/sdk-setup)

*Free tier includes generous quotas for development and small projects.*

---

### 3. Start Generating
**Pick your tools.** Use our REST API directly or integrate with our SDKs and tools for your preferred environment.

#### REST API
```bash
curl -X POST https://api.slugkit.dev/v1/forge \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

#### Python SDK
```python
from slugkit import SlugKit
slugs = SlugKit("YOUR_API_KEY").forge("{adjective}-{noun}", count=5)
```

#### TypeScript SDK  
```typescript
import { SlugKit } from '@slugkit/sdk';
const slugs = await new SlugKit('YOUR_API_KEY')
  .forge({pattern: '{adjective}-{noun}', count: 5});
```

#### MCP Server
```json
{
  "name": "slugkit",
  "server": {
    "command": "npx", 
    "args": ["@slugkit/mcp-server"]
  }
}
```

[**View Complete Documentation →**](/articles/getting-started) | [**API Reference →**](/articles/api-reference)

---

**Need help choosing?** Check out our [**integration guide**](/articles/integration-guide) to find the best approach for your use case.


---

# SlugKit Developer Portal
Source: https://dev.slugkit.dev/docs/developer-portal-home

# SlugKit Developer Portal

**Generate beautiful, unique IDs that humans actually want to read**

Replace UUIDs with human-readable slugs like `smart-database-42`, `deploy-amazing-platform`, or `clever-dolphin-247`. SlugKit provides mathematically guaranteed uniqueness with the aesthetics of human language.

## Why SlugKit?

**Human-Readable**: Easy to remember, communicate, and debug
- `user-clever-dolphin-247` vs `f47ac10b-58cc-4372-a567-0e02b2c3d479`
- `deploy-secure-database-prod` vs `build-2847391847`

**Mathematically Unique**: Billions of combinations with collision-free guarantees
- 708+ million combinations from basic patterns
- Series-based generation for production uniqueness
- Deterministic seeding for reproducible results

**Production-Ready**: Sub-millisecond generation with enterprise features
- 3-20μs generation time
- Distributed-safe counter management
- Comprehensive rate limiting and quotas

## Quick Start

### Python
```bash
pip install slugkit
```

```python
from slugkit import SyncClient

client = SyncClient(api_key="your-api-key")
slugs = client.forge(
    pattern="{adjective}-{noun}-{number:3d}",
    count=5
)
# ['smart-database-247', 'brilliant-server-891', ...]
```

### TypeScript
```bash
npm install slugkit
```

```typescript
import { SlugKit } from 'slugkit';

const client = new SlugKit({
    apiKey: process.env.SLUGKIT_API_KEY
});

const slugs = await client.forge({
    pattern: '{adjective}-{noun}-{number:3d}',
    count: 5
});
```

### REST API
```bash
curl -X POST https://slugkit.dev/api/v1/forge \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}-{number:3d}", "count": 5}'
```

## Pattern Examples

Try these patterns to see SlugKit's flexibility:

```
{adjective}-{noun}                    → smart-database
{adjective:+pos}-{noun:+device}       → brilliant-server
user-{noun:+animal}-{number:2d}       → user-dolphin-42
{ADJECTIVE}_{NOUN}_CONFIG             → STABLE_DATABASE_CONFIG
deploy-{adjective}-{noun}@v{number:2d} → deploy-secure-platform@v12
```

## Three Generation Methods

**Forge**: Custom patterns with full control
- Best for: Testing, custom formats, themed content
- Example: `client.forge(pattern="{adjective}-{noun}", count=10)`

**Mint**: Managed series with guaranteed uniqueness  
- Best for: Production apps, user handles, product IDs
- Example: `client.mint(series_slug="user-handles", count=100)`

**Slice**: Preview generation without consuming  
- Best for: Planning, coordination, demonstrations
- Example: `client.slice(series_slug="user-handles", count=50)`

## Popular Use Cases

- **Web Development**: URL slugs, API endpoints, component names
- **User Handles**: Gaming usernames, social handles, account IDs  
- **DevOps**: Server names, container tags, environment configs
- **Data Processing**: Job names, file naming, batch identifiers

## Getting Started

**New to SlugKit?** → [5-Minute Quickstart](developer-quickstart-guide)

**Choose Your SDK**: [Python](sdk-python-quickstart) | [TypeScript](sdk-typescript-quickstart) | [REST API](rest-api-curl-examples)

**Learn Patterns**: [Pattern Basics](pattern-syntax-basics) | [Advanced Features](pattern-advanced-features) | [Pattern Cookbook](pattern-cookbook)

**Integration Guides**: [Web Development](guide-web-development) | [User Handles](guide-user-handles) | [DevOps](guide-devops-infrastructure)

**API Reference**: [Forge Endpoint](api-forge-endpoint) | [Mint Endpoint](api-mint-endpoint) | [Authentication](api-authentication)

## Need Help?

**Common Issues**: [Troubleshooting Guide](troubleshooting-common-errors)  
**Examples**: [Real-world Use Cases](examples-use-cases)  
**Support**: [Get Help](troubleshooting-support)

---

Ready to generate your first slugs? **[Start with the Quickstart Guide](developer-quickstart-guide)** and get your first API call working in under 5 minutes.

---

# 5-Minute Quickstart
Source: https://dev.slugkit.dev/docs/developer-quickstart-guide

# 5-Minute Quickstart

Get your first SlugKit API call working in under 5 minutes. By the end of this guide, you'll have generated beautiful, unique slugs and understand the basics of SlugKit's pattern system.

## Step 1: Get Your API Key (1 minute)

1. **Sign up** at [slugkit.dev](/)
2. **Create an organization** (or use existing one)
3. **Generate an API key** from your dashboard
4. **Save it securely** - you'll need it for all API calls

```bash
# Store your API key as an environment variable
export SLUGKIT_API_KEY="sk_live_your_api_key_here"
```

**Security Note**: Never commit API keys to version control. Use environment variables or secure key management.

## Step 2: Choose Your Method (30 seconds)

Pick the approach that fits your stack:

**Python SDK** (Recommended for Python developers)
**TypeScript SDK** (Recommended for JS/TS developers)  
**REST API** (Works with any language)

## Step 3: Install & Setup (2 minutes)

### Python SDK

```bash
# Install the SDK
pip install slugkit

# Verify installation
python -c "import slugkit; print(slugkit.__version__)"
```

```python
from slugkit import SyncClient

# Initialize client
client = SyncClient(api_key="your-api-key-here")
# Or use environment variable:
# client = SyncClient()  # Reads SLUGKIT_API_KEY automatically
```

### TypeScript SDK

```bash
# Install the SDK
npm install @slugkit/sdk
# or
yarn add slugkit
```

```typescript
import { SlugKit } from '@slugkit/sdk';

// Initialize client
const client = new SlugKit({
    baseUrl: 'https://slugkit.dev',
    apiKey: process.env.SLUGKIT_API_KEY
});
```

### REST API

```bash
# Test connection with key info
curl -H "X-API-Key: $SLUGKIT_API_KEY" \
     https://slugkit.dev/api/v1/key-info
```

## Step 4: Generate Your First Slugs (1 minute)

### Python

```python
# Generate custom slugs with forge
slugs = client.forge(
    pattern="{adjective}-{noun}-{number:3d}",
    count=5
)
print(slugs)
# Output: ['smart-database-247', 'brilliant-server-891', 'secure-platform-456', ...]

# Try different patterns
user_handles = client.forge(
    pattern="user-{adjective:+pos}-{noun:+animal}-{number:2d}",
    count=3
)
print(user_handles)
# Output: ['user-clever-dolphin-42', 'user-brilliant-tiger-67', ...]
```

### TypeScript

```typescript
// Generate custom slugs with forge
const slugs = await client.forge({
    pattern: '{adjective}-{noun}-{number:3d}',
    count: 5
});
console.log(slugs.slugs);
// Output: ['smart-database-247', 'brilliant-server-891', ...]

// Try different patterns
const userHandles = await client.forge({
    pattern: 'user-{adjective:+pos}-{noun:+animal}-{number:2d}',
    count: 3
});
console.log(userHandles.slugs);
```

### REST API

```bash
# Generate basic slugs
curl -X POST https://slugkit.dev/api/v1/gen/forge \
  -H "X-API-Key: $SLUGKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective}-{noun}-{number:3d}",
    "count": 5
  }'

# Try user handles pattern
curl -X POST https://slugkit.dev/api/v1/gen/forge \
  -H "X-API-Key: $SLUGKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "user-{adjective:+pos}-{noun:+animal}-{number:2d}",
    "count": 3
  }'
```

## Step 5: Understanding Patterns (1 minute)

SlugKit patterns are templates with placeholders in `{}` that get replaced with words or numbers:

```
{adjective}        → smart, brilliant, secure
{noun}             → database, server, platform  
{number:3d}        → 247, 891, 456 (3-digit numbers)
{adjective:+pos}   → positive words: brilliant, amazing
{noun:+animal}     → animal words: dolphin, tiger, eagle
```

**Key Rules**:
- Text outside `{}` stays exactly as written
- Text inside `{}` gets replaced with generated content
- Use `:` for constraints like `+pos` (positive words) or `3d` (3 digits)

## Success! 🎉

You've successfully:
- ✅ Set up SlugKit authentication
- ✅ Generated your first slugs
- ✅ Learned basic pattern syntax
- ✅ Seen multiple generation examples

Your generated slugs are:
- **Unique**: No duplicates within the same pattern/seed combination
- **Human-readable**: Easy to remember and communicate
- **Scalable**: Millions of combinations available

## Next Steps

Now that you have SlugKit working, explore these guides based on your use case:

**Learn More Patterns**: [Pattern Language Basics](pattern-syntax-basics)
- Master advanced constraints and filtering
- Explore case transformations and global settings
- Understand capacity and performance optimization

**Integration Guides**:
- **Web Development**: [URL Slugs & Component Naming](guide-web-development)
- **User Systems**: [Gaming Handles & Social Media](guide-user-handles)
- **Infrastructure**: [Server Naming & DevOps](guide-devops-infrastructure)

**Production Usage**:
- **Unique IDs**: [Using Mint for Production Apps](api-mint-endpoint)
- **Error Handling**: [Debugging & Troubleshooting](troubleshooting-common-errors)
- **Rate Limits**: [Understanding Quotas](api-rate-limits)

**SDK Deep Dives**:
- **Python**: [Advanced Python Usage](sdk-python-advanced)
- **TypeScript**: [React Integration](sdk-typescript-react)

## Common First Questions

**Q: How many unique slugs can I generate?**
A: It depends on your pattern. Basic patterns like `{adjective}-{noun}` provide 708+ million combinations. Use the pattern info endpoint to check capacity.

**Q: Are slugs truly unique?**
A: Within the same pattern and seed, yes. For production uniqueness across your entire app, use `mint()` with series instead of `forge()`.

**Q: Can I customize the word lists?**
A: Yes! Use tag filters like `+pos` (positive), `+animal` (animals). Check available tags with the dictionary endpoints.

**Q: What about rate limits?**
A: Free tier includes 1,000 slugs per month. See [Rate Limits](api-rate-limits) for details and upgrade options.

**Q: Having issues?**
A: Check [Common Errors](troubleshooting-common-errors) or [get support](troubleshooting-support).

## Example Integration

Here's a complete example integrating SlugKit into a user registration system:

### Python Example
```python
from slugkit import SyncClient
import os

def create_user_handle():
    client = SyncClient(api_key=os.getenv('SLUGKIT_API_KEY'))
    
    # Generate family-friendly gaming handle
    handles = client.forge(
        pattern="user-{adjective:+pos}-{noun:+animal}-{number:2d}",
        count=1
    )
    
    return handles[0]

# Usage
new_handle = create_user_handle()
print(f"Welcome, {new_handle}!")
# Output: "Welcome, user-clever-dolphin-42!"
```

### TypeScript Example
```typescript
import { SlugKit } from 'slugkit';

async function createUserHandle(): Promise<string> {
    const client = new SlugKit({
        apiKey: process.env.SLUGKIT_API_KEY
    });
    
    const result = await client.forge({
        pattern: 'user-{adjective:+pos}-{noun:+animal}-{number:2d}',
        count: 1
    });
    
    return result.slugs[0];
}

// Usage
const newHandle = await createUserHandle();
console.log(`Welcome, ${newHandle}!`);
```

Ready to build something amazing? **[Explore Integration Guides](guide-web-development)** or **[Learn Advanced Patterns](pattern-syntax-basics)**.


---

# Your First Slugs: Interactive Tutorial
Source: https://dev.slugkit.dev/docs/developer-tutorial

# Your First Slugs: Interactive Tutorial

This hands-on tutorial walks you through creating real-world slug patterns step by step. By the end, you'll understand how to design patterns for your specific use case and debug common issues.

**Prerequisites:** Complete the [5-Minute Quickstart](developer-quickstart-guide) and read [Core Concepts](developer-core-concepts).

**Time Required:** 15 minutes

## Setup

Make sure you have SlugKit working from the quickstart guide:

```python
from slugkit import SyncClient

client = SyncClient(api_key="your-api-key")

# Test connection
test_slug = client.forge(pattern="{adjective}", count=1)
print(f"✅ Connected! Generated: {test_slug[0]}")
```

## Exercise 1: Basic Blog URL Slugs (3 minutes)

**Goal:** Create URL-friendly slugs for blog posts.

**Requirements:**
- Format: `adjective-noun`
- URL-safe (no spaces or special characters)
- Professional tone

### Step 1: Start Simple

```python
# Try the basic pattern
slugs = client.forge(
    pattern="{adjective}-{noun}",
    count=5
)
print("Basic blog slugs:")
for slug in slugs:
    print(f"  /blog/{slug}")
```

**Expected output:**
```
/blog/smart-database
/blog/brilliant-server
/blog/secure-platform
```

### Step 2: Make It Content-Focused

The basic pattern might generate `smart-elephant` - not ideal for a tech blog. Let's improve:

```python
# Focus on content and technology
slugs = client.forge(
    pattern="{adjective:+obj}-{noun:+content}",
    count=5
)
print("Content-focused blog slugs:")
for slug in slugs:
    print(f"  /blog/{slug}")
```

**What we learned:**
- `+obj` gives objective adjectives (professional tone)
- `+content` gives content-related nouns
- Tags filter word lists to match your domain

### Step 3: Add Uniqueness

For a real blog, you need unique URLs:

```python
# Add numbers for uniqueness
slugs = client.forge(
    pattern="{adjective:+obj}-{noun:+content}-{number:3d}",
    count=5
)
print("Unique blog slugs:")
for slug in slugs:
    print(f"  /blog/{slug}")
```

**Exercise Result:** You now have professional, unique, content-focused blog URLs!

## Exercise 2: Gaming Usernames (4 minutes)

**Goal:** Create family-friendly gaming handles.

**Requirements:**
- Positive, fun tone
- Include animals (memorable)
- Short enough for most gaming platforms
- Include numbers for uniqueness

### Step 1: Basic Gaming Handle

```python
# Start with positive words and animals
slugs = client.forge(
    pattern="{adjective:+pos}-{noun:+animal}",
    count=5
)
print("Basic gaming handles:")
for slug in slugs:
    print(f"  {slug}")
```

**Sample output:**
```
brilliant-dolphin
amazing-tiger
clever-eagle
```

### Step 2: Add Numbers and Constraints

Gaming platforms often have length limits. Let's optimize:

```python
# Add length constraints and numbers
slugs = client.forge(
    pattern="{adjective:+pos<7}-{noun:+animal<8}-{number:2d}",
    count=5
)
print("Optimized gaming handles:")
for slug in slugs:
    print(f"  {slug} (length: {len(slug)})")
```

**What we learned:**
- `<7` means "less than 7 characters" (max 6)
- `<8` means "less than 8 characters" (max 7)  
- `2d` gives 2-digit numbers (01-99)
- Total length is predictable: max 6 + 1 + max 7 + 1 + 2 = 17 characters

### Step 3: User-Friendly Prefix

Add a prefix to make it clear these are user handles:

```python
# Add user prefix
slugs = client.forge(
    pattern="user-{adjective:+pos<6}-{noun:+animal<7}-{number:2d}",
    count=3
)
print("Final gaming handles:")
for slug in slugs:
    print(f"  {slug}")
```

**Exercise Result:** You created memorable, family-friendly, length-controlled gaming usernames!

## Exercise 3: API Endpoint Names (3 minutes)

**Goal:** Generate REST API endpoint patterns.

**Requirements:**
- RESTful structure
- Action-oriented
- Professional naming
- Consistent format

### Step 1: Basic API Structure

```python
# API endpoint pattern
slugs = client.forge(
    pattern="/api/{noun:+object}/{verb}-{noun:+object}",
    count=5
)
print("API endpoints:")
for slug in slugs:
    print(f"  {slug}")
```

**Sample output:**
```
/api/users/create-profile
/api/data/update-record
/api/files/delete-backup
```

### Step 2: Add Version and Constraints

Real APIs need versioning and consistency:

```python
# Versioned API with constraints
slugs = client.forge(
    pattern="/api/v1/{noun:+object<8}/{verb:+change<6}-{noun:+object<8}",
    count=5
)
print("Versioned API endpoints:")
for slug in slugs:
    print(f"  {slug}")
```

### Step 3: Different HTTP Methods

Create patterns for different REST operations:

```python
# Different endpoint patterns
patterns = {
    "GET": "/api/v1/{noun:+object<8}",
    "POST": "/api/v1/{noun:+object<8}/create-{noun:+object<8}",
    "PUT": "/api/v1/{noun:+object<8}/update-{noun:+object<8}",
    "DELETE": "/api/v1/{noun:+object<8}/delete-{noun:+object<8}"
}

for method, pattern in patterns.items():
    endpoint = client.forge(pattern=pattern, count=1)[0]
    print(f"  {method:6} {endpoint}")
```

**Exercise Result:** You generated consistent, RESTful API endpoint patterns!

## Exercise 4: Infrastructure Naming (3 minutes)

**Goal:** Create server and resource names for DevOps.

**Requirements:**
- Environment indication
- Resource type clarity
- Sequential numbering
- Professional naming

### Step 1: Basic Server Names

```python
# Basic server naming
slugs = client.forge(
    pattern="{adjective:+obj}-{noun:+device}-{number:2d}",
    count=5
)
print("Server names:")
for slug in slugs:
    print(f"  {slug}")
```

**Sample output:**
```
stable-server-01
secure-database-02
active-cache-03
```

### Step 2: Add Environment Context

Production systems need environment indication:

```python
# Environment-aware naming
environments = ["dev", "staging", "prod"]

for env in environments:
    slug = client.forge(
        pattern=f"{{adjective:+obj<7}}-{{noun:+device<8}}-{env}-{{number:2d}}",
        count=1
    )[0]
    print(f"  {slug}")
```

### Step 3: Configuration Variables

Create environment variable patterns:

```python
# Environment variables
slugs = client.forge(
    pattern="{ADJECTIVE:+obj}_{NOUN:+device}_CONFIG",
    count=5
)
print("Environment variables:")
for slug in slugs:
    print(f"  export {slug}=value")
```

**Sample output:**
```
export STABLE_DATABASE_CONFIG=value
export SECURE_CACHE_CONFIG=value
export ACTIVE_SERVER_CONFIG=value
```

**Exercise Result:** You created a consistent infrastructure naming scheme!

## Exercise 5: Debugging Patterns (2 minutes)

Learn to troubleshoot common pattern issues.

### Problem 1: Pattern Too Restrictive

```python
# This pattern might fail - too restrictive
try:
    slugs = client.forge(
        pattern="{adjective:+pos+obj-neg<4==3}-{noun:+animal+device<5==4}",
        count=5
    )
    print("Restrictive pattern worked!")
except Exception as e:
    print(f"❌ Pattern too restrictive: {e}")
    
    # Fix: Simplify constraints
    slugs = client.forge(
        pattern="{adjective:+pos<5}-{noun:+animal<6}",
        count=5
    )
    print("✅ Simplified pattern:")
    for slug in slugs:
        print(f"  {slug}")
```

### Problem 2: Invalid Tag

```python
# This will fail - invalid tag
try:
    slugs = client.forge(
        pattern="{adjective:+awesome}-{noun}",
        count=1
    )
except Exception as e:
    print(f"❌ Invalid tag: {e}")
    
    # Fix: Use valid tags
    slugs = client.forge(
        pattern="{adjective:+pos}-{noun}",
        count=1
    )
    print(f"✅ Valid tag: {slugs[0]}")
```

### Problem 3: Check Available Tags

```python
# Always check what tags are available
dictionary_info = client.dictionary_info()
for dict_info in dictionary_info:
    if dict_info['kind'] == 'adjective':
        print(f"Adjective dictionary: {dict_info['word_count']} words")
        
# Get available tags for a specific dictionary
tags_info = client.dictionary_tags(kind='adjective')
print("Available adjective tags:")
for tag in tags_info[:5]:  # Show first 5
    print(f"  +{tag['tag']}: {tag['description']} ({tag['word_count']} words)")
```

## Real-World Integration Example

Here's how to integrate these patterns into a real application:

```python
class SlugGenerator:
    def __init__(self, api_key):
        self.client = SyncClient(api_key=api_key)
        
    def blog_url(self, title_hint=None):
        """Generate SEO-friendly blog URL slug"""
        if title_hint:
            # Use title hint as seed for consistency
            return self.client.forge(
                pattern="{adjective:+obj}-{noun:+content}-guide",
                count=1,
                seed=title_hint
            )[0]
        else:
            return self.client.forge(
                pattern="{adjective:+obj}-{noun:+content}-{number:3d}",
                count=1
            )[0]
    
    def user_handle(self):
        """Generate family-friendly user handle"""
        return self.client.forge(
            pattern="user-{adjective:+pos<6}-{noun:+animal<7}-{number:2d}",
            count=1
        )[0]
    
    def server_name(self, environment="prod"):
        """Generate server name for specific environment"""
        return self.client.forge(
            pattern=f"{{adjective:+obj<6}}-{{noun:+device<7}}-{environment}-{{number:2d}}",
            count=1
        )[0]
    
    def api_endpoint(self, resource, action):
        """Generate API endpoint path"""
        return f"/api/v1/{resource}/{action}-{self.client.forge(pattern='{noun:+object<8}', count=1)[0]}"

# Usage example
generator = SlugGenerator("your-api-key")

print("Generated identifiers:")
print(f"Blog URL: /blog/{generator.blog_url()}")
print(f"User handle: {generator.user_handle()}")
print(f"Server name: {generator.server_name('staging')}")
print(f"API endpoint: {generator.api_endpoint('users', 'create')}")
```

## Tutorial Summary

**🎉 Congratulations!** You've successfully:

- ✅ Created professional blog URL slugs
- ✅ Generated family-friendly gaming usernames  
- ✅ Designed RESTful API endpoint patterns
- ✅ Built infrastructure naming schemes
- ✅ Debugged common pattern issues
- ✅ Integrated patterns into a reusable class

### Key Lessons Learned

**Pattern Design:**
- Start simple, add constraints gradually
- Use appropriate tags for your domain (+pos, +obj, +animal, etc.)
- Consider length constraints for platform compatibility
- Add numbers for uniqueness when needed

**Tag Usage:**
- `+pos` for positive, user-facing content
- `+obj` for professional, objective content  
- `+animal` for memorable, fun identifiers
- `+device` for technical/infrastructure terms

**Debugging:**
- Check available tags with `dictionary_tags()`
- Validate patterns before production use
- Simplify constraints if generation fails
- Use appropriate word counts for your needs

**Production Tips:**
- Use seeds for deterministic results
- Implement error handling for invalid patterns
- Consider length limits of target systems
- Create reusable pattern functions

## Next Steps

Ready to go deeper? Choose your path:

**Advanced Patterns:** [Pattern Language Advanced Features](pattern-advanced-features)
- Case transformations and global settings
- Complex filtering and constraints
- Performance optimization techniques

**Production Usage:** [Using Mint for Guaranteed Uniqueness](api-mint-endpoint)
- Series setup and management
- Production-scale slug generation
- Counter management and monitoring

**Integration Guides:** Choose your use case:
- [Web Development Integration](guide-web-development)
- [User Handle Systems](guide-user-handles)  
- [DevOps and Infrastructure](guide-devops-infrastructure)

**Pattern Reference:** [Complete Pattern Cookbook](pattern-cookbook)
- Production-tested patterns
- Industry-specific examples
- Best practice recommendations

Ready to build something amazing? **[Explore Real-World Integration Examples](examples-use-cases)** or **[Set Up Production Series](api-mint-endpoint)**!


---

# SlugKit Dictionary & Tag Reference
Source: https://dev.slugkit.dev/docs/dictionary-and-tag-reference-for-agents

# SlugKit Dictionary & Tag Reference

**Complete guide to SlugKit's word dictionaries, content tags, and filtering strategies.**

## Word Dictionaries Overview

SlugKit provides 6 main word dictionaries with rich tagging for precise content control:

```
📊 Use dictionary_info() to see current word counts
📋 Use dictionary_tags() to see all available tags
```

### Available Dictionaries

| Dictionary | Count | Description | Examples |
|------------|-------|-------------|----------|
| **adjective** | ~17,082 | Descriptive words | fast, brilliant, secure, broken |
| **noun** | ~41,469 | Objects, concepts, people | server, database, user, platform |
| **verb** | ~8,405 | Action words | deploy, connect, analyze, configure |
| **adverb** | ~3,619 | Manner descriptors | quickly, efficiently, securely |
| **domain** | ~9,183 | Internet domains | com, org, tech, dev, aws |
| **shell** | ~2,137 | Command-line tools | git, docker, npm, curl, ssh |

## Tag System

Tags allow precise filtering of word content by theme, emotion, appropriateness, and domain.

### Emotional Tags

Control the emotional tone of generated content:

#### Adjectives & Adverbs
```
+pos    → Positive: amazing, brilliant, secure, fast
+neg    → Negative: broken, failed, slow, unstable  
+emo    → Emotional: passionate, thrilling, devastating
+neut   → Neutral: standard, regular, basic, normal
+det    → Detached: systematic, mechanical, procedural
```

#### Nouns & Verbs
```
+pos    → Positive concepts: success, achievement, growth
+neg    → Negative concepts: failure, error, breakdown
+emo    → Emotional concepts: passion, excitement, fear
+neut   → Neutral concepts: system, process, method
+det    → Detached concepts: mechanism, procedure, protocol
```

### Content Appropriateness

Control content suitability for different audiences:

```
+nsfw   → Not Safe For Work (opt-in only): explicit content
-nsfw   → Exclude NSFW content (recommended for production)
+obj    → Objective, professional tone
```

**⚠️ NSFW Content**: NSFW-tagged words are opt-in only. Use `+nsfw` explicitly to include them.

### Domain-Specific Tags

#### Technology & Business
```
+tech     → Technology: server, database, API, cloud, deploy
+business → Business: revenue, client, strategy, market
+science  → Scientific: research, analysis, hypothesis, data
+medical  → Medical: diagnosis, treatment, patient, clinic
```

#### Object Categories (Nouns)
```
+animal   → Animals: dolphin, eagle, tiger, wolf
+person   → People: manager, developer, user, admin  
+object   → Physical objects: server, desk, car, building
+artifact → Human-made items: software, document, tool
+substance → Materials: metal, wood, plastic, liquid
+food     → Food items: pizza, coffee, bread, salad
+building → Structures: office, warehouse, factory, home
+vehicle  → Transportation: car, truck, plane, ship
+device   → Electronic devices: phone, laptop, router
+material → Raw materials: steel, concrete, fabric
+currency → Money/financial: dollar, euro, bitcoin, cash
+plant    → Flora: tree, flower, grass, leaf
+drink    → Beverages: coffee, tea, water, juice
```

#### Action Categories (Verbs)
```
+action   → Physical actions: run, jump, build, move
+change   → Transformation: convert, modify, update, evolve  
+travel   → Movement: navigate, journey, migrate, explore
+be       → State of being: exist, remain, become, stay
+have     → Possession: own, contain, include, hold
+make     → Creation: build, generate, create, produce
+create   → Creative actions: design, compose, invent
+destroy  → Destructive actions: delete, remove, break
+take     → Taking actions: grab, acquire, capture
+give     → Giving actions: provide, share, offer
+imagine  → Mental actions: think, dream, visualize
```

#### Content Categories
```
+content  → Information content: article, document, data
+information → Data/knowledge: facts, statistics, records
+concept  → Abstract ideas: theory, principle, philosophy  
+idea     → Thoughts: concept, notion, plan, strategy
+emotion  → Feelings: joy, anger, fear, excitement
+feeling  → Sensations: warmth, pain, comfort, tension
+music    → Musical terms: song, rhythm, melody, beat
+art      → Artistic concepts: painting, sculpture, design
+fantasy  → Fantasy elements: dragon, magic, wizard, quest
```

#### Domains & Technology
```
+com      → Commercial domains: business, corporate TLDs
+org      → Organization domains: non-profit, community TLDs
+io       → Tech domains: developer-friendly TLDs
+edu      → Educational domains: academic institutions
+gov      → Government domains: official organizations
+tld      → Top-level domains: com, org, net, gov
+sld      → Second-level domains: company, product names
+sub      → Subdomain parts: www, api, blog, shop
```

## Tag Filtering Strategies

### Include Multiple Tags
```
{noun:+tech+object}           → Tech objects: server, router, database
{adjective:+pos+tech}         → Positive tech terms: amazing, secure, fast
{verb:+action+tech}           → Tech actions: deploy, configure, optimize
```

### Exclude Unwanted Content
```
{adjective:-neg-nsfw}         → No negative or NSFW words
{noun:+tech-animal}           → Tech terms, but no animals
{verb:-destroy-neg}           → No destructive or negative actions
```

### Complex Combinations
```
{adjective:+pos+tech-emo<8}   → Positive tech adjectives, not emotional, max 7 chars
{noun:+object+tech-nsfw>=4}   → Tech objects, family-friendly, min 4 chars
{verb:+change+tech-destroy}   → Change-related tech verbs, not destructive
```

## Content Strategy by Use Case

### Professional/Business Content
```
# Recommended tags
{adjective:+pos+obj-nsfw}     → professional, positive, appropriate
{noun:+business+tech-nsfw}    → business/tech focused, clean
{verb:+action+change-destroy} → constructive actions only

# Example pattern
"{adjective:+pos+obj} {noun:+tech} {verb:+action} {adverb:+pos}"
→ "secure platform deploys efficiently"
```

### Family-Friendly Content
```
# Always exclude NSFW
{adjective:-nsfw+pos}         → positive, clean adjectives
{noun:+animal+object-nsfw}    → animals and objects, family-safe
{verb:+action+change-destroy-nsfw} → constructive, clean verbs

# Example pattern  
"{adjective:+pos-nsfw} {noun:+animal-nsfw} {verb:+action-nsfw}"
→ "happy dolphin jumps"
```

### Technical Documentation
```
# Focus on objective, technical terms
{adjective:+tech+obj-emo}     → technical, unemotional
{noun:+tech+object+device}    → tech equipment and systems  
{verb:+tech+change+action}    → technical operations

# Example pattern
"{verb:+tech} {adjective:+tech} {noun:+tech+object}"
→ "configure secure server"
```

### Creative/Marketing Content
```
# Allow emotional, positive language
{adjective:+pos+emo}          → exciting, emotional positivity
{noun:+concept+idea+object}   → broad creative concepts
{verb:+create+action+change}  → dynamic, creative actions

# Example pattern
"The {adjective:+pos+emo} {noun:+concept} will {verb:+create} {adjective:+pos} {noun:+object}"
→ "The amazing platform will generate brilliant solutions"
```

### Gaming/Fantasy Content
```
# Include fantasy and creative elements
{adjective:+fantasy+emo}      → magical, dramatic descriptors
{noun:+fantasy+animal+person} → fantasy characters and creatures
{verb:+action+imagine+destroy} → dramatic fantasy actions

# Example pattern
"{adjective:+fantasy} {noun:+fantasy+person} {verb:+action} the {adjective:+neg} {noun:+fantasy}"
→ "Mystical wizard defeats the evil dragon"
```

## Language Support

### Current Language Tags
```
@en    → English (default)
@es    → Spanish (if available)
@fr    → French (if available)  
@de    → German (if available)
```

**Note**: Language support varies by dictionary. Use `dictionary_info()` to check availability.

### Usage Examples
```
{adjective@en}-{noun@en}      → Force English words
{noun@es} and {noun@fr}       → Mix Spanish and French
{adjective}-{noun}[@de]       → German words globally
```

## Special Dictionary Features

### Domain Dictionary Categories
The domain dictionary includes real internet domains organized by:

#### By Level
```
+tld     → Top-level: com, org, net, edu, gov
+sld     → Second-level: company names, brands
+sub     → Subdomain parts: www, api, mail, blog  
```

#### By Type
```
+com     → Commercial: business domains
+org     → Organization: non-profits, communities
+edu     → Educational: schools, universities
+gov     → Government: official agencies
+io      → Tech: developer-focused domains
+aws     → Cloud: AWS service domains
+cloud   → Cloud providers: various cloud services
```

#### By Region
```
+us, +uk, +de, +fr, +jp, +cn, +au → Country-specific TLDs
```

### Shell Dictionary Organization
Command-line tools organized by category:

```
+dev     → Development: git, npm, pip, cargo
+system  → System admin: systemctl, crontab, mount
+network → Networking: curl, wget, ssh, ping
+data    → Data processing: awk, sed, grep, sort
+archive → Compression: tar, zip, gzip, unzip
```

## Best Practices

### Production Applications
1. **Always exclude NSFW**: Use `-nsfw` in all patterns
2. **Use positive/neutral tone**: `+pos` or `+neut` for user-facing content
3. **Be domain-specific**: `+tech` for technical contexts, `+business` for corporate
4. **Control length**: Use length constraints for UI/database limits

### Testing & Development  
1. **Use diverse tags**: Test with different emotional tones
2. **Include edge cases**: Try `+neg` content for error scenarios
3. **Validate thoroughly**: Check capacity impact of tag combinations
4. **Consider caching**: Tag filtering can impact performance

### Content Strategy
1. **Match your audience**: Family-friendly vs. professional vs. technical
2. **Consistent theming**: Use global settings for pattern-wide consistency
3. **Cultural sensitivity**: Consider international audiences with language tags
4. **Brand alignment**: Choose tags that match your brand voice

## Advanced Tag Techniques

### Tag Hierarchies
Some tags work better together:
```
+tech+obj        → Technical, objective (great for APIs)
+pos+business    → Positive business language (marketing)
+action+change   → Dynamic transformation language
+animal+fantasy  → Mythical creatures and magical animals
```

### Performance Considerations
```
# More specific = better performance
{noun:+tech+object<8}         → Highly filtered, fast
{noun}                        → Broad selection, slower with large sets
{noun:+animal+fantasy+emo}    → Multiple tags, moderate performance
```

### Capacity Impact
```
# Check capacity before using
validate_pattern("{noun:+tech}")     → Smaller subset, lower capacity
validate_pattern("{noun}")           → Full dictionary, higher capacity
validate_pattern("{noun:+rare+specific}") → Very specific, very low capacity
```

---

**💡 Pro Tips:**
- Start broad, then add constraints: `{noun}` → `{noun:+tech}` → `{noun:+tech-nsfw<8}`
- Use `dictionary_tags()` regularly to discover new filtering options
- Test tag combinations with small `count` values first
- Consider your content strategy when choosing emotional tags
- Remember that more tags = smaller word selection but more targeted content

---

# SlugKit Developer Portal Navigation Structure
Source: https://dev.slugkit.dev/docs/doc-toc-developer-portal

# SlugKit Developer Portal Navigation Structure
# This document defines the complete navigation hierarchy for SlugKit's developer documentation

title: "Developer Portal Navigation"
slug: "doc-toc-developer-portal"
description: "Navigation structure for SlugKit developer documentation"
version: "1.0"
audience: "developer"
last_updated: "2025-10-02"
schema_version: "1.0"

navigation:
  - id: "home"
    title: "Home"
    slug: "developer-portal-home"
    icon: "🏠"
    description: "SlugKit developer portal homepage"
    order: 0
    featured: true

  - id: "getting-started"
    title: "Getting Started"
    icon: "🚀"
    description: "Get started with SlugKit in 5 minutes"
    order: 10
    children:
      - id: "quickstart"
        title: "Quickstart"
        slug: "developer-quickstart-guide"
        description: "5-minute setup and first API call"
        order: 10
        featured: true
        tags: ["essential", "beginner"]
        estimated_time: "5 minutes"
        
      - id: "concepts"
        title: "Core Concepts"
        slug: "developer-core-concepts"
        description: "Understanding slugs, patterns, and generation methods"
        order: 20
        tags: ["fundamental", "beginner"]
        estimated_time: "10 minutes"
        
      - id: "tutorial"
        title: "Your First Slugs"
        slug: "developer-tutorial"
        description: "Interactive tutorial with step-by-step exercises"
        order: 30
        tags: ["interactive", "hands-on"]
        estimated_time: "15 minutes"
        
      - id: "choosing-method"
        title: "Choosing Generation Methods"
        slug: "choosing-generation-method"
        description: "Forge vs Mint vs Slice decision guide"
        order: 40
        tags: ["decision-guide", "beginner"]
        estimated_time: "8 minutes"

  - id: "guides"
    title: "Guides"
    icon: "🛠️"
    description: "Integration guides for common use cases"
    order: 20
    children:
      - id: "web-development"
        title: "Web Development"
        slug: "guide-web-development"
        description: "URL slugs, API endpoints, component naming"
        order: 10
        tags: ["popular", "web", "frontend"]
        frameworks: ["react", "nextjs", "vue", "angular"]
        estimated_time: "20 minutes"
        
      - id: "user-handles"
        title: "User Handles & Social"
        slug: "guide-user-handles"
        description: "Gaming usernames, social handles, email aliases"
        order: 20
        tags: ["social", "gaming", "user-experience"]
        use_cases: ["gaming", "social-media", "user-registration"]
        estimated_time: "15 minutes"
        
      - id: "mcp-integration"
        title: "MCP Integration"
        slug: "guide-mcp-integration"
        description: "Enable AI agents with SlugKit's Model Context Protocol server"
        order: 25
        tags: ["mcp", "ai-agents", "claude", "llm", "tools"]
        estimated_time: "12 minutes"
        
      - id: "devops"
        title: "DevOps & Infrastructure"
        slug: "guide-devops-infrastructure"
        description: "Server naming, configs, container orchestration"
        order: 30
        tags: ["devops", "enterprise", "infrastructure"]
        tools: ["kubernetes", "docker", "terraform"]
        estimated_time: "25 minutes"
        
      - id: "data-processing"
        title: "Data Processing & ETL"
        slug: "guide-data-processing"
        description: "Batch jobs, file naming, schema versioning"
        order: 40
        tags: ["data", "batch", "etl"]
        tools: ["apache-spark", "airflow", "pandas"]
        estimated_time: "18 minutes"
        
      - id: "enterprise"
        title: "Enterprise Integration"
        slug: "guide-enterprise-integration"
        description: "SSO, API gateways, monitoring, compliance"
        order: 50
        tags: ["enterprise", "security", "compliance"]
        topics: ["sso", "monitoring", "audit-logs"]
        estimated_time: "30 minutes"

  - id: "api-reference"
    title: "API Reference"
    icon: "📖"
    description: "Complete API documentation and reference"
    order: 30
    children:
      - id: "api-reference"
        title: "API Reference"
        slug: "api-reference"
        description: "REST API for generating slugs"
        order: 5
        tags: ["core-api", "popular", "essential"]
        
      - id: "api-series-management"
        title: "API for series management"
        slug: "api-series-management"
        description: "REST API for managing series"
        order: 10
        tags: ["core-api"]

      - id: "api-url-shortener"
        title: "URL Shortener"
        slug: "api-url-shortener"
        description: "Shorten URLs into slugs and resolve them back"
        order: 12
        tags: ["core-api"]

      - id: "authentication"
        title: "Authentication"
        slug: "api-authentication"
        description: "API keys, SDK keys, and security best practices"
        order: 15
        tags: ["security", "essential", "auth"]
        
      - id: "rate-limits"
        title: "Rate Limits & Quotas"
        slug: "api-rate-limits"
        description: "Understanding limits and subscription tiers"
        order: 20
        tags: ["quotas", "billing"]
        
      - id: "errors"
        title: "Error Handling"
        slug: "api-error-handling"
        description: "Error codes, retry logic, debugging"
        order: 30
        tags: ["debugging", "troubleshooting"]

  - id: "sdks"
    title: "SDKs"
    icon: "🧩"
    description: "Language-specific SDKs and integration guides"
    order: 40
    children:
      - id: "python"
        title: "Python SDK"
        description: "Complete Python integration guide"
        order: 10
        language: "python"
        children:
          - id: "python-install"
            title: "Installation & Setup"
            slug: "sdk-python-installation"
            description: "Install and configure Python SDK"
            order: 10
            tags: ["setup"]
            
          - id: "python-quickstart"
            title: "Quickstart"
            slug: "sdk-python-quickstart"
            description: "Generate your first slugs with Python"
            order: 20
            tags: ["quickstart", "popular"]
            
          - id: "python-advanced"
            title: "Advanced Usage"
            slug: "sdk-python-advanced"
            description: "Async, error handling, custom configurations"
            order: 30
            tags: ["advanced"]
            
          - id: "python-cli"
            title: "CLI Reference"
            slug: "slugkit-cli-reference"
            description: "Command-line tool documentation"
            order: 35
            tags: ["cli", "tools", "reference"]
            
          - id: "python-api"
            title: "API Reference"
            slug: "sdk-python-api-reference"
            description: "Complete Python SDK API documentation"
            order: 40
            tags: ["reference"]
            
      - id: "typescript"
        title: "TypeScript SDK"
        description: "Browser and Node.js TypeScript integration"
        order: 20
        language: "typescript"
        children:
          - id: "ts-install"
            title: "Installation & Setup"
            slug: "sdk-typescript-installation"
            description: "Install and configure TypeScript SDK"
            order: 10
            tags: ["setup"]
            
          - id: "ts-browser"
            title: "Browser Usage"
            slug: "sdk-typescript-browser"
            description: "Using SlugKit in browser applications"
            order: 20
            tags: ["browser", "frontend"]
            
          - id: "ts-nodejs"
            title: "Node.js Usage"
            slug: "sdk-typescript-nodejs"
            description: "Server-side TypeScript integration"
            order: 30
            tags: ["nodejs", "backend"]
            
          - id: "ts-react"
            title: "React Integration"
            slug: "sdk-typescript-react"
            description: "Using SlugKit in React applications"
            order: 40
            tags: ["react", "popular"]
            
      - id: "rest-api"
        title: "REST API"
        description: "Direct HTTP API usage"
        order: 30
        children:
          - id: "curl-examples"
            title: "cURL Examples"
            slug: "rest-api-curl-examples"
            description: "Command-line API usage examples"
            order: 10
            tags: ["cli", "examples"]
            
          - id: "postman"
            title: "Postman Collection"
            slug: "rest-api-postman"
            description: "Ready-to-use Postman collection"
            order: 20
            tags: ["postman", "testing"]
            
          - id: "language-examples"
            title: "Language Examples"
            slug: "rest-api-language-examples"
            description: "HTTP client examples in various languages"
            order: 30
            tags: ["examples", "multi-language"]

  - id: "pattern-language"
    title: "Pattern Language"
    icon: "🎨"
    description: "Master SlugKit's powerful pattern system"
    order: 50
    children:
      - id: "syntax-basics"
        title: "Syntax Basics"
        slug: "pattern-syntax-basics"
        description: "Learn pattern fundamentals"
        order: 10
        tags: ["fundamental", "patterns"]
        estimated_time: "15 minutes"
        
      - id: "advanced-features"
        title: "Advanced Features"
        slug: "pattern-advanced-features"
        description: "Case transformations, constraints, global settings"
        order: 20
        tags: ["advanced", "patterns"]
        estimated_time: "25 minutes"
        
      - id: "dictionary-reference"
        title: "Dictionary Reference"
        slug: "pattern-dictionary-reference"
        description: "Word types, tags, and filtering options"
        order: 30
        tags: ["reference", "dictionaries"]
        
      - id: "performance"
        title: "Performance Optimization"
        slug: "pattern-performance-optimization"
        description: "Capacity planning and pattern efficiency"
        order: 40
        tags: ["performance", "optimization"]
        estimated_time: "20 minutes"
        
      - id: "cookbook"
        title: "Pattern Cookbook"
        slug: "pattern-cookbook"
        description: "Common patterns and real-world examples"
        order: 50
        tags: ["examples", "cookbook", "popular"]

  - id: "deployment"
    title: "Deployment"
    icon: "🚀"
    description: "Deploy SlugKit in your environment"
    order: 60
    hidden: true
    children:
      - id: "saas"
        title: "SaaS Deployment"
        description: "Using SlugKit's managed service"
        order: 10
        children:
          - id: "saas-setup"
            title: "Account Setup"
            slug: "deployment-saas-setup"
            order: 10
            tags: ["setup", "saas"]
            
          - id: "saas-organization"
            title: "Organization Management"
            slug: "deployment-saas-organization"
            order: 20
            tags: ["management", "teams"]
            
          - id: "saas-billing"
            title: "Billing & Usage"
            slug: "deployment-saas-billing"
            order: 30
            tags: ["billing", "quotas"]
            
      - id: "on-premise"
        title: "On-Premise"
        description: "Self-hosted SlugKit deployment"
        order: 20
        children:
          - id: "on-premise-core"
            title: "Core Setup"
            slug: "deployment-on-premise-core"
            description: "PostgreSQL-based deployment"
            order: 10
            tags: ["postgresql", "enterprise"]
            
          - id: "on-premise-lite"
            title: "Lite Setup"
            slug: "deployment-on-premise-lite"
            description: "Docker-based stateless deployment"
            order: 20
            tags: ["docker", "simple"]
            
          - id: "scaling"
            title: "Scaling"
            slug: "deployment-scaling"
            description: "Multi-instance and load balancing"
            order: 30
            tags: ["scaling", "performance"]
            
          - id: "monitoring"
            title: "Monitoring"
            slug: "deployment-monitoring"
            description: "Health checks and observability"
            order: 40
            tags: ["monitoring", "observability"]
            
      - id: "security"
        title: "Security"
        description: "Security considerations and best practices"
        order: 30
        children:
          - id: "security-auth"
            title: "Authentication & Authorization"
            slug: "deployment-security-auth"
            order: 10
            tags: ["security", "auth"]
            
          - id: "security-api"
            title: "API Security"
            slug: "deployment-security-api"
            order: 20
            tags: ["security", "api"]
            
          - id: "security-compliance"
            title: "Compliance"
            slug: "deployment-security-compliance"
            order: 30
            tags: ["compliance", "enterprise"]

  - id: "troubleshooting"
    title: "Troubleshooting"
    icon: "❓"
    description: "Solve common issues and get help"
    order: 70
    children:
      - id: "common-errors"
        title: "Common Errors"
        slug: "troubleshooting-common-errors"
        description: "Solutions to frequent problems"
        order: 10
        tags: ["errors", "debugging"]
        
      - id: "performance-issues"
        title: "Performance Issues"
        slug: "troubleshooting-performance"
        description: "Diagnosing and fixing performance problems"
        order: 20
        tags: ["performance", "optimization"]
        
      - id: "api-debugging"
        title: "API Debugging"
        slug: "troubleshooting-api-debugging"
        description: "Debug API calls and responses"
        order: 30
        tags: ["api", "debugging"]
        
      - id: "support"
        title: "Getting Support"
        slug: "troubleshooting-support"
        description: "How to get help and report issues"
        order: 40
        tags: ["support", "community"]

  - id: "examples"
    title: "Examples"
    icon: "💡"
    description: "Real-world examples and use cases"
    order: 80
    children:
      - id: "use-cases"
        title: "Use Cases"
        description: "Common implementation scenarios"
        order: 10
        children:
          - id: "ecommerce"
            title: "E-commerce Platform"
            slug: "example-ecommerce-platform"
            order: 10
            tags: ["ecommerce", "popular"]
            
          - id: "gaming"
            title: "Gaming Usernames"
            slug: "example-gaming-usernames"
            order: 20
            tags: ["gaming", "social"]
            
          - id: "microservices"
            title: "Microservices Naming"
            slug: "example-microservices-naming"
            order: 30
            tags: ["microservices", "devops"]
            
          - id: "content-management"
            title: "Content Management"
            slug: "example-content-management"
            order: 40
            tags: ["cms", "content"]
            
      - id: "integration-recipes"
        title: "Integration Recipes"
        description: "Step-by-step integration guides"
        order: 20
        children:
          - id: "nextjs-app"
            title: "Next.js Application"
            slug: "recipe-nextjs-app"
            order: 10
            tags: ["nextjs", "react", "popular"]
            
          - id: "django-backend"
            title: "Django Backend"
            slug: "recipe-django-backend"
            order: 20
            tags: ["django", "python"]
            
          - id: "kubernetes-deployments"
            title: "Kubernetes Deployments"
            slug: "recipe-kubernetes-deployments"
            order: 30
            tags: ["kubernetes", "devops"]
            
          - id: "cicd-pipelines"
            title: "CI/CD Pipelines"
            slug: "recipe-cicd-pipelines"
            order: 40
            tags: ["cicd", "automation"]

collections:
  popular:
    title: "Popular Guides"
    description: "Most viewed and helpful content"
    icon: "⭐"
    items:
      - "developer-quickstart-guide"
      - "guide-web-development"
      - "pattern-syntax-basics"
      - "api-reference"
      - "api-authentication"
      - "sdk-python-quickstart"
      - "sdk-typescript-react"
      
  beginner:
    title: "New to SlugKit?"
    description: "Perfect starting point for beginners"
    icon: "🌱"
    items:
      - "developer-quickstart-guide"
      - "developer-core-concepts"
      - "api-authentication"
      - "pattern-syntax-basics"
      - "developer-tutorial"
      - "choosing-generation-method"
      
  featured:
    title: "Featured Content"
    description: "Highlighted guides and examples"
    icon: "🎯"
    items:
      - "developer-quickstart-guide"
      - "guide-web-development"
      - "pattern-advanced-features"
      - "api-authentication"
      
  essential:
    title: "Essential Reading"
    description: "Must-read documentation"
    icon: "📚"
    items:
      - "developer-quickstart-guide"
      - "developer-core-concepts"
      - "api-reference"
      - "api-authentication"
      - "pattern-syntax-basics"

relationships:
  "developer-quickstart-guide":
    prerequisites: []
    next_steps:
      - "developer-core-concepts"
      - "api-authentication"
      - "pattern-syntax-basics"
      - "guide-web-development"
    related:
      - "api-reference"
      - "sdk-python-quickstart"
      - "sdk-typescript-react"
      
  "api-authentication":
    prerequisites:
      - "developer-quickstart-guide"
    next_steps:
      - "api-reference"
      - "api-rate-limits"
      - "api-error-handling"
    related:
      - "developer-core-concepts"
      - "sdk-python-installation"
      - "sdk-typescript-installation"
      
  "developer-core-concepts":
    prerequisites:
      - "developer-quickstart-guide"
    next_steps:
      - "pattern-syntax-basics"
      - "choosing-generation-method"
      - "api-authentication"
    related:
      - "api-reference"
      
  "pattern-syntax-basics":
    prerequisites:
      - "developer-core-concepts"
    next_steps:
      - "pattern-advanced-features"
      - "pattern-dictionary-reference"
      - "pattern-cookbook"
    related:
      - "api-reference"
      - "troubleshooting-common-errors"
      
  "guide-web-development":
    prerequisites:
      - "developer-quickstart-guide"
      - "api-authentication"
    next_steps:
      - "sdk-typescript-react"
      - "recipe-nextjs-app"
    related:
      - "pattern-cookbook"
      - "api-reference"
      
  "guide-mcp-integration":
    prerequisites:
      - "developer-quickstart-guide"
      - "api-authentication"
    next_steps:
      - "pattern-syntax-basics"
      - "api-reference"
    related:
      - "developer-core-concepts"
      - "choosing-generation-method"

search:
  boost_sections:
    - "getting-started"
    - "guides"
    - "api-reference"
  
  boost_tags:
    - "popular"
    - "featured"
    - "essential"
    - "quickstart"
  
  facets:
    - field: "section"
      title: "Section"
      type: "hierarchical"
    - field: "tags"
      title: "Topics"
      type: "multi-select"
    - field: "language"
      title: "Programming Language"
      type: "single-select"
    - field: "estimated_time"
      title: "Reading Time"
      type: "range"

analytics:
  events:
    - "page_view"
    - "section_expand"
    - "link_click"
    - "search_query"
    - "document_complete"
  
  properties:
    - "user_type"
    - "subscription_tier"
    - "documentation_version"



---

# End-User License Agreement (EULA) - 2025-06
Source: https://dev.slugkit.dev/docs/eula-2025-06

**Effective Date:** June 21, 2025  
**Version:** 2025-06

This End-User License Agreement ("Agreement") is a legal agreement between you ("User") and **Sergei Fedorov pr Računarsko programiranje cpp Beograd** ("Provider") regarding the use of the SlugKit service ("Service").

## 1. Definitions

- **Service** refers to the hosted platform that generates unique, human-readable identifiers.
- **Slug** means a human-readable identifier generated by the Service according to a user-defined or system-provided pattern.

## 2. Acceptance of Terms

By accessing or using the Service, you agree to be bound by the terms of this Agreement. If you do not agree to these terms, do not use the Service.

## 3. License Grant

Subject to your compliance with this Agreement, the Provider grants you a limited, non-exclusive, non-transferable, revocable license to access and use the Service for your internal or commercial use.

## 4. User-Defined Patterns

Users may define custom Slug generation patterns for use within their projects. While these patterns influence the structure of generated Slugs, they are **not exclusive or proprietary**. Due to the limited variability in pattern syntax, multiple users may define and use identical or similar patterns.

The Provider retains all rights to the underlying generation engine, dictionaries, and algorithms. Use of the Service does not grant any ownership or intellectual property rights over the tools used to generate Slugs.

## 5. Data Usage

We collect and store your email address for identification and notification purposes. We also collect non-personal usage statistics to monitor system health and improve the Service. No user-generated content is stored.

For more details, please refer to our [Privacy Policy](/articles/privacy).

## 6. Subscription and Usage Limits

The Service is available in both free and paid subscription tiers. Each tier may differ in:
- Usage quotas (e.g., Slugs per month)
- Feature availability
- Service level guarantees (e.g., latency, uptime)

Quotas are enforced at the organizational level via API or SDK keys. Commercial use is permitted under all tiers, including the free tier, subject to the applicable limits.

## 7. Restrictions

You agree not to:
- Reverse-engineer or attempt to derive the source code of the Service;
- Use the Service in violation of any applicable laws;
- Interfere with or disrupt the integrity or performance of the Service.

## 8. Termination

The Provider may suspend or terminate your access to the Service at its discretion, especially in the case of misuse or violation of this Agreement.

## 9. Disclaimer of Warranty

The Service is provided “as is” and “as available” for users of the free tier, without warranties of any kind, either express or implied.  
For paid tiers, specific service levels and performance guarantees may apply as described in the relevant service plan or SLA documentation.

## 10. Limitation of Liability

To the fullest extent permitted by law, the Provider shall not be liable for any indirect, incidental, or consequential damages arising from your use of the Service.

## 11. Changes to Agreement

The Provider may update this Agreement from time to time. If material changes are made, users will be notified. Continued use of the Service after such changes constitutes acceptance of the updated Agreement.

## 12. Governing Law

This Agreement shall be governed by and construed in accordance with the laws of the Republic of Serbia, without regard to its conflict of law principles.

## 13. Legal Capacity

By using the Service, you confirm that you have the legal capacity to enter into binding agreements under the laws of your jurisdiction. If you are accessing the Service on behalf of an organization, you represent that you are authorized to bind that organization to this Agreement.

## 14. Contact

If you have any questions or concerns regarding this Privacy Policy, please contact us at:

**Sergei Fedorov pr Računarsko programiranje cpp Beograd**  
Email: sergei@slugkit.dev


---

**By using the Service, you acknowledge that you have read, understood, and agreed to be bound by this End-User License Agreement.**

---

# Content Management
Source: https://dev.slugkit.dev/docs/example-content-management

# Content Management

*Generate SEO-friendly, memorable identifiers for content management systems that enhance discoverability and user experience*

## Overview

Content management systems require systematic identifier generation that balances SEO optimisation, editorial workflow efficiency, and user experience. SlugKit transforms content identifiers into branded, discoverable, and memorable assets that enhance discoverability across blogs, documentation, media assets, and marketing content.

## The Content Management Challenge

Traditional content management systems suffer from poor identifier strategies that hurt discoverability and user experience:

**Problems with conventional approaches:**
- **Auto-generated URLs:** `/article/12847/content-management-systems` - unmemorable and non-descriptive
- **WordPress defaults:** `/2024/10/01/hello-world-3/` - date-heavy with duplicate content issues
- **UUID-based systems:** `/content/f47ac10b-58cc-4372-a567-0e02b2c3d479` - completely unmemorable
- **Technical focus:** `/blog-post-cms-comparison-updated-final-v2/` - verbose and unprofessional

**Critical content management issues:**
- **Poor SEO performance** - URLs lack keyword relevance and semantic meaning
- **Editorial confusion** - Writers can't remember or share content URLs easily
- **Broken mental models** - URLs don't reflect content hierarchy or relationships
- **Social sharing problems** - Unmemorable URLs reduce social media engagement
- **Content discovery friction** - Users struggle to find related content
- **Brand inconsistency** - No cohesive content identity across touchpoints

## SlugKit Content Management Solution

SlugKit transforms content identifiers into branded, discoverable, and memorable assets:

**Example transformations:**
- Blog articles: `enhanced-democracy-0a`, `pleasant-heroine-f8`
- Creative content: `respectful-metalwork-92`, `considerate-booklet-75`
- Information resources: `dignified-playbill-07`, `majestic-basics-3f`
- Visual content: `unstrung-seascape-c0`, `tickling-icon-c2`

**Content-specific benefits:**
- **SEO optimisation** - URLs contain relevant keywords and semantic meaning
- **Editorial efficiency** - Writers can predict and remember content URLs
- **Brand consistency** - Cohesive content identity across all touchpoints
- **Social amplification** - Memorable URLs encourage sharing and engagement
- **Content discovery** - Intuitive content relationships and navigation
- **Multi-channel publishing** - Consistent identifiers across platforms

## Strategic Implementation Guide

### When to Use Forge vs Mint/Slice

**Use Forge for:**
- **Themed content campaigns** with specific branding requirements
- **Marketing landing pages** with temporary promotional content
- **Content series** where thematic consistency matters more than uniqueness
- **Testing and preview content** where uniqueness isn't critical

**Use Series + Mint/Slice for:**
- **Permanent articles and posts** requiring guaranteed uniqueness
- **Documentation systems** with systematic identifier requirements
- **Media assets** needing unique identification across systems
- **Content that must be cited** or referenced long-term

### Blog and Editorial Content

**Blog Posts (Use Series + Mint)**

Blog posts represent permanent content that requires guaranteed uniqueness for SEO and referencing.

**Series Configuration:**
- **Series name:** `blog-content`
- **Pattern:** `{adjective:+pos}-{noun:+content}-{number:2x}`
- **Capacity:** ~130 million unique combinations
- **Use case:** Permanent blog articles and editorial content

```bash
# Create series for blog content
curl -X POST https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Blog Content",
    "pattern": "{adjective:+pos}-{noun:+content}-{number:2x}"
  }'

# Generate unique blog post slugs
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "blog-content", "count": 10}'
```

**Example Results:** `enhanced-democracy-0a`, `pleasant-heroine-f8`, `tasteful-activism-5f`

**Content Series (Use Forge)**

Content series like weekly newsletters or themed collections don't require uniqueness across different publications.

```bash
# Generate themed content series
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "weekly-digest-{adjective:+pos}-{number:3d}",
    "seed": "newsletter-2025",
    "sequence": 1,
    "count": 52
  }'
```

**Example Results:** `weekly-digest-enhanced-001`, `weekly-digest-pleasant-002`

### Documentation and Knowledge Management

**Documentation (Use Series + Mint)**

Technical documentation requires unique, persistent identifiers for linking and referencing.

**Series Configuration:**
- **Series name:** `documentation`
- **Pattern:** `{adjective:+pos}-{noun:+information}-{number:2x}`
- **Capacity:** ~12 million unique combinations
- **Use case:** Technical guides, API documentation, help articles

**Example Results:** `dignified-playbill-07`, `majestic-basics-3f`

**Help Articles (Use Forge)**

FAQ and help articles can use themed patterns for better content organisation.

```bash
# Generate help article identifiers
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective:+pos}-{noun}-guide",
    "seed": "help-articles",
    "count": 20
  }'
```

**Example Results:** `improving-fen-guide`, `mellow-wincey-guide`, `choice-excruciation-guide`

### Marketing and Campaign Content

**Landing Pages (Use Forge)**

Marketing landing pages are often temporary and campaign-specific, making thematic consistency more important than global uniqueness.

```bash
# Generate campaign landing pages
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "campaign-{adjective:+pos}-{noun:+content}",
    "seed": "product-launch-2025",
    "count": 10
  }'
```

**Example Results:** `campaign-enhanced-democracy`, `campaign-pleasant-heroine`

**Email Campaigns (Use Forge)**

Email marketing campaigns benefit from memorable, branded identifiers that reflect campaign themes.

```bash
# Generate email campaign identifiers
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "email-{adjective:+pos}-{number:2x}",
    "seed": "quarterly-newsletter",
    "count": 4
  }'
```

**Example Results:** `email-enhanced-0a`, `email-pleasant-f8`

### Media and Asset Management

**Media Collections (Use Series + Mint)**

Media assets require unique identification for proper asset management and copyright tracking.

**Series Configuration:**
- **Series name:** `media-assets`
- **Pattern:** `{adjective}-{noun:+art}-{number:2x}`
- **Capacity:** ~133 million unique combinations
- **Use case:** Images, videos, graphics, and multimedia content

**Example Results:** `unstrung-seascape-c0`, `undrawn-mural-68`, `tickling-icon-c2`

**Creative Projects (Use Series + Mint)**

Creative works and design projects need permanent, unique identifiers for portfolio and client management.

**Series Configuration:**
- **Series name:** `creative-projects`
- **Pattern:** `{adjective:+pos}-{noun:+creation}-{number:2x}`
- **Capacity:** ~44 million unique combinations
- **Use case:** Design projects, client work, creative portfolios

**Example Results:** `respectful-metalwork-92`, `considerate-booklet-75`, `absolved-overprint-fc`

### Content Categorisation and Taxonomy

**Category Systems (Use Forge)**

Content categories and taxonomies can use thematic patterns for better content organisation.

```bash
# Generate content category identifiers
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "category-{adjective:+pos}-{noun:+content}",
    "seed": "content-taxonomy",
    "count": 15
  }'
```

**Example Results:** `category-enhanced-democracy`, `category-tasteful-activism`

## Platform-Specific Adaptations

### WordPress Integration

**Post Types:** 
- **Posts:** Use series + mint for blog articles
- **Pages:** Use forge for static content like About, Contact
- **Custom post types:** Use series + mint for unique content types

**URL Structure:**
- Default: `enhanced-democracy-0a`
- With categories: `/blog/enhanced-democracy-0a`
- With dates: `/2025/enhanced-democracy-0a`

### Drupal Integration

**Content Types:**
- **Articles:** Series + mint for news and blog content
- **Basic pages:** Forge for static informational content
- **Custom entities:** Series + mint for unique content entities

### Headless CMS Integration

**API-First Content:**
- **Content entries:** Series + mint for API-delivered content
- **Static assets:** Series + mint for media and file management
- **Configuration:** Forge for system configuration and settings

## SEO and Content Strategy

### SEO-Optimised Patterns

**Blog Content SEO Strategy:**
- Pattern: `{adjective:+pos}-{noun:+content}-{number:2x}`
- Benefits: Positive sentiment, content relevance, uniqueness
- Example: `enhanced-democracy-0a` (positive + content + unique)

**Documentation SEO Strategy:**
- Pattern: `{adjective:+pos}-{noun:+information}-{number:2x}`
- Benefits: Helpful tone, information focus, clear identification
- Example: `dignified-playbill-07` (helpful + informative + unique)

### Content Discoverability

**Social Media Optimisation:**
- Memorable slugs increase social sharing
- Branded patterns improve recognition
- Consistent identifiers enhance brand recall

**Search Engine Benefits:**
- Semantic relevance improves rankings
- Keyword-rich patterns boost discoverability
- Unique identifiers prevent duplicate content issues

## Series Management

For programmatic series creation and management in content systems, see:

- **[Core Concepts](developer-core-concepts)** - Understanding series and uniqueness guarantees
- **[API Series Management](api-series-management)** - Programmatically managing series via REST API
- **[Python SDK API Reference](sdk-python-api-reference)** - Complete series CRUD operations

**Example series setup for content platform:**

1. **Create blog content series** with `{adjective:+pos}-{noun:+content}-{number:2x}` pattern
2. **Create documentation series** with `{adjective:+pos}-{noun:+information}-{number:2x}` pattern
3. **Create media asset series** with `{adjective}-{noun:+art}-{number:2x}` pattern
4. **Create creative project series** with `{adjective:+pos}-{noun:+creation}-{number:2x}` pattern

Each series provides millions of unique combinations whilst maintaining thematic consistency and SEO benefits.

## Content Safety and Quality

SlugKit's curated dictionaries ensure content-appropriate identifiers:

**Built-in Content Safety:**
- Curated word lists exclude inappropriate combinations
- Positive sentiment tags (`+pos`) for public-facing content
- Professional vocabulary for business content

**Content Quality Guidelines:**
- Use `+pos` tags for public content to ensure positive sentiment
- Avoid negative sentiment tags for marketing and promotional content
- Consider brand voice when selecting adjective modifiers

## Performance Considerations

### High-Volume Content Platforms

**Bulk Content Generation:**
Use mint with larger counts for content migration or bulk imports:

```bash
# Generate 1000 unique content identifiers
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "blog-content", "count": 1000}'
```

**Streaming for Large-Scale Publishing:**
Use streaming endpoints for major content migrations:

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/mint/stream \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "blog-content", "count": 10000}'
```

### Preview and Editorial Workflow

**Use Slice for Content Planning:**
Preview upcoming content identifiers without consuming them:

```bash
# Preview next 50 content identifiers for editorial planning
curl -X POST https://api.slugkit.com/api/v1/gen/slice \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series_slug": "blog-content",
    "sequence": 1000,
    "count": 50
  }'
```

This enables editorial teams to plan content calendars and preview URL structures without affecting live content series.

## Analytics and Content Performance

### Content Performance Tracking

Monitor which content patterns resonate with your audience:

- **SEO performance** - Which patterns rank better in search results?
- **Social sharing** - Do memorable patterns get shared more?
- **User engagement** - How do different patterns affect time on page?
- **Editorial efficiency** - Which patterns are easier for writers to remember?

### A/B Testing Content Patterns

Test different content patterns with audience segments:

**Pattern A (Information-focused):** `{adjective:+pos}-{noun:+information}-{number:2x}`
**Pattern B (Content-focused):** `{adjective:+pos}-{noun:+content}-{number:2x}`
**Pattern C (Creative-focused):** `{adjective:+pos}-{noun:+creation}-{number:2x}`

Use forge with different seeds to generate test samples, then measure SEO performance, social sharing, and user engagement.

## Implementation Examples

### Blog Content Management

```typescript
// Generate unique blog post identifier
const blogSlug = await client.mint({
  seriesSlug: 'blog-content',
  count: 1
});

// Generate themed newsletter series (non-unique across publishers)
const newsletterSeries = await client.forge({
  pattern: 'weekly-digest-{adjective:+pos}-{number:3d}',
  seed: 'newsletter-2025',
  sequence: 1,
  count: 52
});
```

### Documentation System

```python
# Unique documentation identifiers
doc_slug = client.mint(
    series_slug='documentation',
    count=1
)[0]

# Themed help article patterns
help_articles = client.forge(
    pattern='{adjective:+pos}-{noun}-guide',
    seed='help-system',
    count=20
)
```

### Media Asset Management

```javascript
// Permanent media asset identifier
const mediaAsset = await client.mint({
  seriesSlug: 'media-assets',
  count: 1
});

// Creative project portfolio
const creativeProject = await client.mint({
  seriesSlug: 'creative-projects',
  count: 1
});
```

## Related Documentation

**Core Concepts:**
- [Developer Core Concepts](developer-core-concepts) - Understanding series and uniqueness guarantees
- [Choosing Generation Methods](choosing-generation-method) - When to use forge vs mint vs slice

**API Documentation:**
- [API Series Management](api-series-management) - Programmatic series management
- [API Reference](api-reference) - Complete endpoint documentation
- [Python SDK API Reference](sdk-python-api-reference) - Series CRUD operations

**Pattern Language:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Master pattern fundamentals
- [Advanced Pattern Features](pattern-advanced-features) - Case transformations and filtering
- [Dictionary Reference](pattern-dictionary-reference) - Content-specific word tags
- [Pattern Cookbook](pattern-cookbook) - Real-world content pattern examples

**Advanced Topics:**
- [Performance Optimisation](pattern-performance-optimisation) - Scale to millions of content items
- [Rate Limits & Quotas](api-rate-limits) - Optimise costs for content platforms
- [Web Development Guide](guide-web-development) - Strategic web application naming principles


---

# E-commerce Platform
Source: https://dev.slugkit.dev/docs/example-ecommerce-platform

# E-commerce Platform

*Apply SlugKit's forge, mint, and slice methods to create memorable e-commerce identifiers*

---

## Overview

E-commerce platforms need human-readable identifiers across product URLs, order numbers, promotional codes, and customer handles. This guide shows when and how to use SlugKit's three generation methods for different e-commerce scenarios.

## Product URLs (Forge Method)

**Scenario:** Create SEO-friendly product URLs that are consistent but not sequential.

**Why Forge:** Products need branded, themed URLs that won't reveal business information through sequential patterns. Forge allows deterministic generation with custom seeds.

**Pattern Selection:**
```
Electronics:    {adjective:+pos}-{noun:+artifact}
Home & Garden:  {adjective:+pos}-{noun:+object}  
Fashion:        {adjective:+pos}-{noun:+material}
```

**Implementation:**
```bash
# Generate product URL for "Wireless Bluetooth Headphones"
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "{adjective:+pos}-{noun:+artifact}",
    "seed": "product-electronics-wireless-headphones", 
    "count": 1
  }'
```

**Example Results:**
```
engaging-storefront
pivotal-quadrangle
animating-manufactory
```

**Why This Works:**
- **Deterministic**: Same product always gets same URL (using seed)
- **SEO-friendly**: Contains relevant keywords
- **Brand-appropriate**: Positive, professional terminology
- **No business intel**: Doesn't reveal product volumes or timing

---

## Order Numbers (Mint Method)

**Scenario:** Generate unique customer-facing order tracking numbers.

**Why Mint:** Orders must be absolutely unique and customers need them for support. Mint provides guaranteed uniqueness with memorable format.

**Series Setup:**
```bash
# Create order tracking series
curl -X POST https://api.slugkit.com/api/v1/series \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "slug": "order-tracking",
    "pattern": "{adjective:+pos}-order-{number:3x}",
    "seed": "orders-2025"
  }'
```

**Daily Generation:**
```bash
# Generate order numbers for new orders
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "series_slug": "order-tracking",
    "count": 50
  }'
```

**Example Results:**
```
halal-order-452
waggish-order-f4c
good-order-4b2
```

**Why This Works:**
- **Absolutely unique**: No duplicates ever within series
- **Customer-friendly**: Easy to communicate over phone/chat
- **Professional**: Sounds premium and trustworthy
- **Trackable**: Can monitor series capacity and usage

---

## Promotional Codes (Forge Method)

**Scenario:** Create branded campaign codes for marketing.

**Why Forge:** Campaigns need themed, branded codes that reflect the promotion. Forge allows custom patterns that match marketing messaging.

**Campaign-Specific Patterns:**
```bash
# Black Friday campaign  
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "BF2025-{adjective:+pos}-{number:2X}",
    "seed": "blackfriday-2025-deals",
    "count": 100
  }'

# Product launch campaign
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "LAUNCH-{adjective:+pos}-{noun:+artifact}",
    "seed": "product-launch-headphones",
    "count": 50
  }'
```

**Example Results:**
```
BF2025-abdicable-4B
BF2025-aberrant-01
BF2025-abient-0D
```

**Why This Works:**
- **Brand consistency**: Codes match campaign messaging
- **Marketing appeal**: Positive language enhances brand
- **Reproducible**: Same campaign = same codes (useful for planning)
- **Fraud prevention**: Unique codes prevent duplicate usage

---

## Customer Handles (Slice + Mint Method)

**Scenario:** Offer customers optional memorable account handles.

**Why Slice Then Mint:** Preview options for customer choice, then mint the selected handle for uniqueness.

**Preview Generation (Slice):**
```bash
# Show 5 handle options to customer
curl -X POST https://api.slugkit.com/api/v1/gen/slice \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "series_slug": "customer-handles",
    "sequence": 1000,
    "count": 5
  }'
```

**Handle Selection (Mint):**
```bash
# Customer selected option 3, mint it for uniqueness
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "series_slug": "customer-handles", 
    "count": 1
  }'
```

**Example Flow:**
```
Preview Options:    inviting-theatregoer-d3, better-siamese-26, delicate-optician-6a
Customer Chooses:   delicate-optician-6a
Final Handle:       delicate-optician-6a (now unique and reserved)
```

**Why This Works:**
- **Customer choice**: Users pick from appealing options
- **Guaranteed unique**: Selected handle is minted for exclusivity
- **Optional feature**: Not required but enhances user experience
- **Consistent series**: All handles follow same pattern

---

## When to Use Each Method

| Scenario | Method | Reason |
|----------|--------|---------|
| **Product URLs** | Forge | Deterministic, SEO-friendly, brandable |
| **Order Numbers** | Mint | Must be unique, customer-facing |
| **Promo Codes** | Forge | Campaign-themed, reproducible batches |
| **Customer Handles** | Slice → Mint | Preview options, guarantee uniqueness |
| **Internal IDs** | Mint | High volume, uniqueness critical |
| **Campaign Planning** | Slice | Preview codes before campaign launch |

---

## Pattern Selection Guide

**Positive Brand Image:**
```
{adjective:+pos}-{noun:+artifact}     # engaging-storefront
{adjective:+pos}-{noun:+object}       # delightful-creation
```

**Customer-Facing:**
```
{adjective:+pos}-{noun:+person}       # delicate-optician
{adjective:+pos}-{noun:+animal}       # cheerful-dolphin
```

**Campaign Codes:**
```
EVENT-{adjective:+pos}-{number:2X}    # EVENT-amazing-A4F
{SEASON}-{adjective:+pos}-{number:3x} # SPRING-fresh-2a7
```

**Order Tracking:**
```
{adjective:+pos}-order-{number:3x}    # good-order-4b2
ORDER-{adjective:+pos}-{number:4X}    # ORDER-delightful-A4F2
```

---

## Capacity Planning

**Check pattern capacity before production:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/pattern-info \
  -H "X-API-Key: sk_live_..." \
  -d '{"pattern": "{adjective:+pos}-{noun:+artifact}-{number:2x}"}'
```

**Validated capacity results:**
- `{adjective:+pos}-{noun:+artifact}`: 4.8M combinations
- `{adjective:+pos}-order-{number:3x}`: 1.4M combinations  
- `{adjective:+pos}-{noun:+person}-{number:2x}`: 570M combinations

**Rule of thumb:** Plan for 10x your expected usage.

---

## Available Tags Reference

**Adjective tags:**
- `+pos`: Positive words (710 words)
- `+emo`: Emotional words (2,944 words)
- `+obj`: Objective words (8,382 words)
- `+det`: Detached/neutral words (14,138 words)

**Noun tags:**
- `+artifact`: Human-made objects (6,787 words)
- `+object`: General objects (18,861 words)
- `+person`: People and roles (6,273 words)
- `+device`: Devices and tools (1,673 words)
- `+animal`: Animals (2,437 words)
- `+material`: Materials and substances (1,856 words)

---

## Related Documentation

- [Pattern Syntax Basics](pattern-syntax-basics) - Learn pattern fundamentals
- [Choosing Generation Methods](choosing-generation-method) - Forge vs Mint vs Slice
- [API Reference](api-reference) - Complete endpoint documentation
- [Dictionary Reference](pattern-dictionary-reference) - Available tags and filters
- [Advanced Pattern Features](pattern-advanced-features) - Complex filtering and case transformations


---

# Gaming Usernames
Source: https://dev.slugkit.dev/docs/example-gaming-usernames

# Gaming Usernames

*Generate unforgettable gaming handles that players actually remember and want to use*

## Overview

Gaming usernames are the foundation of player identity across gaming platforms, streaming services, esports competitions, and gaming communities. SlugKit transforms the traditional username struggle into a delightful experience, providing memorable, unique, and brandable gaming handles that enhance player engagement.

## The Gaming Username Challenge

Traditional gaming username systems create frustration and poor user experience:

**Problems with current approaches:**
- **Random generation:** `DarkSlayer47392847` - unmemorable number suffixes
- **User-chosen (taken):** `DarkSlayer` (already exists) - popular names instantly unavailable
- **Auto-suggestions:** `DarkSlayer_2847_xX` - unprofessional and hard to remember
- **Platform defaults:** `Player_847392048` - completely generic and forgettable

**Critical issues:**
- **Availability crisis** - Popular names instantly taken
- **Poor memorability** - Random numbers impossible to remember  
- **Toxic namespace pollution** - Inappropriate combinations slip through
- **Brand inconsistency** - No cohesive identity across platforms
- **User frustration** - Endless searching for available names

## SlugKit Gaming Solution

SlugKit transforms gaming usernames into memorable, available, and brandable identities:

**Example transformations:**
- Fantasy characters: `righteous-adjutant-50`, `affectionate-augur-cf`
- Action-focused gaming: `bacteriolytic-lurch-0e`, `colourful-arrival-0c`  
- Friendly gaming: `advisable-sauropod-08`, `becoming-blackfly-29`
- Tech gaming: `pixilated-dowel-4a`, `downstage-nickelodeon-02`

**Gaming-specific benefits:**
- **Guaranteed availability** - Unique within your platform scope
- **Perfect memorability** - Human-readable, pronounceable combinations
- **Cross-platform consistency** - Same generation logic everywhere
- **Content-safe** - Curated dictionaries prevent inappropriate combinations
- **Scalable uniqueness** - Millions of variations without repetition

## Strategic Implementation Guide

### When to Use Forge vs Mint/Slice

**Use Forge for:**
- **Transient identifiers** that don't require uniqueness guarantees
- **Themed campaigns** with specific branding requirements
- **Marketing handles** for temporary events or promotions
- **Testing and development** where uniqueness isn't critical

**Use Series + Mint/Slice for:**
- **Player usernames** requiring guaranteed uniqueness
- **Permanent identifiers** that represent user identity
- **Cross-platform handles** that must be consistent
- **Production systems** serving real players

### Fantasy MMO Implementation

**Character Names (Use Series + Mint)**

Fantasy MMOs need guaranteed unique character names. Set up series for character generation:

**Series Configuration:**
- **Series name:** `fantasy-characters`
- **Pattern:** `{adjective:+pos}-{noun:+fantasy}-{number:2x}`
- **Capacity:** ~5.4 million unique combinations
- **Use case:** Permanent player character identities

```bash
# Create series for fantasy characters
curl -X POST https://api.slugkit.com/api/v1/gen/series \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Fantasy Character Names",
    "pattern": "{adjective:+pos}-{noun:+fantasy}-{number:2x}"
  }'

# Generate unique character names
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "fantasy-characters", "count": 10}'
```

**Example Results:** `recuperative-firedrake-3a`, `irreverent-medusa-61`, `blameless-cockatrice-8c`

**Guild Names (Use Forge)**

Guild names are chosen by players and don't require system-wide uniqueness - multiple servers can have guilds with similar themes.

```bash
# Generate themed guild suggestions
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective:+pos}-{noun:+person}",
    "seed": "guild-suggestions",
    "count": 5
  }'
```

**Example Results:** `righteous-adjutant`, `copacetic-argonaut`, `affectionate-augur`

### Competitive Gaming Implementation

**Player Tags (Use Series + Mint)**

Competitive gaming requires unique player tags for tournaments and rankings.

**Series Configuration:**
- **Series name:** `esports-handles`  
- **Pattern:** `{adjective}-{noun:+action}-{number:2x}`
- **Capacity:** ~3.7 billion unique combinations
- **Use case:** Permanent competitive identities

**Example Results:** `bacteriolytic-lurch-0e`, `debonair-enlargement-5a`, `colourful-arrival-0c`

**Team Names (Use Forge)**

Team names are chosen by teams and can be similar across different tournaments or leagues.

```bash
# Generate team name suggestions
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective:+pos}-{noun:+person}",
    "seed": "team-dragonforce",
    "count": 3
  }'
```

**Example Results:** `majuscular-allegorizer`, `fevered-announcer`, `copacetic-argonaut`

### Streaming and Content Creation

**Streamer Handles (Use Series + Mint)**

Streamer handles represent permanent brand identity and must be unique.

**Series Configuration:**
- **Series name:** `streamer-handles`
- **Pattern:** `{adjective:+pos}-{noun:+content}-{number:2x}`
- **Capacity:** ~130 million unique combinations
- **Use case:** Permanent creator identities

**Example Results:** `discernible-engineering-12`, `lucky-metacentre-ce`, `immaculate-forestry-9f`

**Content Series (Use Forge)**

Content series names are thematic and don't require uniqueness across creators.

```bash
# Generate content series names
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "ProTips-{adjective:+pos}-{noun:+content}-EP{number:3d}",
    "seed": "tutorial-series",
    "sequence": 1,
    "count": 5
  }'
```

**Example Results:** `ProTips-contrived-average-EP001`, `ProTips-lucky-metacentre-EP002`

### Social and Casual Gaming

**Family-Safe Handles (Use Series + Mint)**

Family gaming platforms need guaranteed appropriate content and uniqueness.

**Series Configuration:**
- **Series name:** `family-safe-handles`
- **Pattern:** `{adjective:+pos}-{noun:+animal}-{number:2d}`
- **Capacity:** ~17 million unique combinations
- **Use case:** Safe, permanent family identities

**Example Results:** `advisable-sauropod-08`, `becoming-blackfly-29`, `boon-stenopterygius-36`

**Party Codes (Use Forge)**

Temporary party codes for game sessions don't require permanent uniqueness.

```bash
# Generate party invite codes
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "JOIN-{adjective:+pos}-{noun:+action}-{number:3X}",
    "seed": "party-session",
    "count": 1
  }'
```

**Example Results:** `JOIN-gracious-debut-A7F`

## Platform-Specific Adaptations

### Cross-Platform Identity Strategy

**Core Identity (Use Series + Mint)**

Establish a unique core identity that can be adapted across platforms:

```bash
# Generate core gaming identity
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "core-gaming-identity", "count": 1}'
```

**Pattern:** `{adjective}-{noun}-{number:2x}`
**Example Result:** `solemn-understanding-57`

**Platform Adaptations:**
- **Steam:** `solemn-understanding-57` (supports hyphens)
- **Discord:** `solemn-understanding-57` (32 char limit - fits perfectly)
- **Twitch:** `solemn_understanding_57` (replace hyphens with underscores)
- **Xbox:** `solemnunderstanding57` (no special characters)
- **PlayStation:** `solemn_understanding_57` (underscore format)

### Platform-Specific Considerations

**Steam Integration:**
- Length: 2-64 characters
- Characters: Alphanumeric + hyphens/underscores
- Strategy: Use core SlugKit patterns directly

**Discord Integration:**  
- Length: 2-32 characters
- Strategy: Ensure patterns stay under limit with `{adjective<7}-{noun<7}`

**Twitch Integration:**
- Length: 4-25 characters  
- Characters: Alphanumeric + underscores only
- Strategy: Convert hyphens to underscores post-generation

## Advanced Gaming Features

### Tournament and League Systems

**Tournament IDs (Use Forge)**

Tournament identifiers are unique to specific events and don't need global uniqueness.

```bash
# Generate tournament bracket codes
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "TOURNEY-{adjective:+pos}-{number:4X}",
    "seed": "world-championship-2025",
    "count": 4
  }'
```

**Example Results:** `TOURNEY-righteous-A4F2`, `TOURNEY-copacetic-B7D9`

### Guild and Clan Management

**Guild IDs (Use Series + Mint)**

Guild identifiers need to be unique within the game ecosystem.

**Series Configuration:**
- **Series name:** `guild-identifiers`
- **Pattern:** `{adjective:+pos}-{noun:+person}-{number:3x}`
- **Capacity:** ~570 million combinations
- **Use case:** Unique guild identification system

**Recruitment Codes (Use Forge)**

Temporary recruitment codes for guild invitations.

```bash
# Generate recruitment codes
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "JOIN-{adjective:+pos}-{number:4X}",
    "seed": "guild-recruitment",
    "count": 3
  }'
```

**Example Results:** `JOIN-copacetic-C8A3`, `JOIN-righteous-F2D7`

## Pattern Optimisation for Gaming

### Gaming-Specific Tag Combinations

Based on available dictionary tags, here are optimal gaming patterns:

**Fantasy Gaming:**
- `{adjective:+pos}-{noun:+fantasy}` - Positive fantasy creatures
- `{adjective}-{noun:+fantasy}-{number:2x}` - General fantasy with unique suffix
- `{adjective:+pos}-{noun:+person}-{number:2x}` - Heroic character archetypes

**Action Gaming:**  
- `{adjective}-{noun:+action}-{number:2x}` - Action-focused handles
- `{adjective:+pos}-{noun:+action}` - Positive action words
- `{adjective}-{noun:+device}-{number:2x}` - Tech/gadget themed

**Family-Friendly Gaming:**
- `{adjective:+pos}-{noun:+animal}-{number:2d}` - Positive animals
- `{adjective:+pos}-{noun:+content}` - Safe, positive content
- `{adjective}-{noun:+person}-{number:2x}` - Character archetypes

**Content Creation:**
- `{adjective:+pos}-{noun:+content}-{number:2x}` - Positive content themes
- `{adjective}-{noun:+creation}-{number:2x}` - Creative/artistic themes
- `{adjective:+pos}-{noun:+art}` - Artistic and creative

### Case Transformations for Branding

**Professional Esports:**
```
{ADJECTIVE}-{NOUN}-{number:2X}    → SOLEMN-UNDERSTANDING-57
```

**Fantasy Immersion:**
```
{Adjective}-{Noun}-{number:2x}    → Righteous-Adjutant-50
```

**Casual Gaming:**
```
{adjective}-{noun}-{number:2d}    → advisable-sauropod-08
```

## Series Management

For programmatic series creation and management in gaming applications, see:

- **[Core Concepts](developer-core-concepts)** - Understanding series and uniqueness guarantees
- **[API Series Management](api-series-management)** - Programmatically managing series via REST API
- **[Python SDK API Reference](sdk-python-api-reference)** - Complete series CRUD operations

**Example series setup for gaming platform:**

1. **Create character name series** with `{adjective:+pos}-{noun:+fantasy}-{number:2x}` pattern
2. **Create streamer handle series** with `{adjective:+pos}-{noun:+content}-{number:2x}` pattern  
3. **Create competitive tag series** with `{adjective}-{noun:+action}-{number:2x}` pattern
4. **Create family-safe series** with `{adjective:+pos}-{noun:+animal}-{number:2d}` pattern

Each series provides millions of unique combinations whilst maintaining thematic consistency.

## Content Safety and Moderation

SlugKit's curated dictionaries provide baseline content safety, but gaming platforms can add additional filtering:

**Built-in Safety:**
- Curated word lists exclude inappropriate content
- Tag filtering prevents toxic combinations (exclude `-nsfw` tag)
- Family-friendly patterns with `+pos` adjectives and safe noun categories

**Available Safety Tags:**
- **Include:** `+pos` (positive adjectives), `+obj` (objective), `+neut` (neutral)
- **Exclude:** `-nsfw` (inappropriate content), `-neg` (negative words)

**Additional Platform Safety:**
- Custom blocked word lists
- Age-appropriate pattern selection
- Community reporting integration
- Real-time content validation

## Performance Considerations

### High-Volume Gaming Platforms

**Batch Generation:**
Use mint with larger counts for bulk user onboarding:

```bash
# Generate 1000 unique handles for new users
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "gaming-handles", "count": 1000}'
```

**Streaming for Massive Scale:**
Use streaming endpoints for very large batches:

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/mint/stream \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"series_slug": "gaming-handles", "count": 10000}'
```

### Preview and Testing

**Use Slice for Development:**
Preview upcoming handles without consuming them from series:

```bash
# Preview next 100 handles without affecting production
curl -X POST https://api.slugkit.com/api/v1/gen/slice \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "series_slug": "gaming-handles",
    "sequence": 5000,
    "count": 100
  }'
```

This enables testing handle quality and user acceptance without impacting live series counters.

## Analytics and Optimisation

### Handle Usage Tracking

Monitor which patterns resonate with your gaming community:

- **User acceptance rates** - Which handles do players keep vs change?
- **Cross-platform adoption** - Do players use the same handle everywhere?
- **Memorability metrics** - How easily do players remember their handles?
- **Social sharing** - Which handle styles get shared most?

### A/B Testing Handle Patterns

Test different patterns with user segments:

**Pattern A (Fantasy):** `{adjective:+pos}-{noun:+fantasy}-{number:2x}`
**Pattern B (Action):** `{adjective}-{noun:+action}-{number:2x}`
**Pattern C (Friendly):** `{adjective:+pos}-{noun:+animal}-{number:2d}`

Use forge with different seeds to generate test samples, then measure user satisfaction and retention.

## Implementation Examples

### MMO Character Creation

```typescript
// Generate unique character name
const characterName = await client.mint({
  seriesSlug: 'fantasy-characters',
  count: 1
});

// Generate themed guild suggestions (non-unique)
const guildSuggestions = await client.forge({
  pattern: '{adjective:+pos}-{noun:+person}',
  seed: `guild-${playerClass}`,
  count: 5
});
```

### Competitive Gaming Registration

```python
# Unique esports handle
esports_handle = client.mint(
    series_slug='esports-handles',
    count=1
)[0]

# Team coordination codes (temporary)
team_codes = client.forge(
    pattern='TEAM-{adjective:+pos}-{number:3X}',
    seed=f'team-{team_name}',
    count=team_size
)
```

### Streaming Platform Setup

```javascript
// Permanent streamer identity
const streamerHandle = await client.mint({
  seriesSlug: 'streamer-handles', 
  count: 1
});

// Themed content series
const contentSeries = await client.forge({
  pattern: 'ProTips-{adjective:+pos}-EP{number:3d}',
  seed: 'tutorial-series',
  sequence: 1,
  count: 50
});
```

## Related Documentation

**Core Concepts:**
- [Developer Core Concepts](developer-core-concepts) - Understanding series and uniqueness guarantees
- [Choosing Generation Methods](choosing-generation-method) - When to use forge vs mint vs slice

**API Documentation:**
- [API Series Management](api-series-management) - Programmatic series management  
- [API Reference](api-reference) - Complete endpoint documentation
- [Python SDK API Reference](sdk-python-api-reference) - Series CRUD operations

**Pattern Language:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Master pattern fundamentals
- [Advanced Pattern Features](pattern-advanced-features) - Case transformations and filtering
- [Dictionary Reference](pattern-dictionary-reference) - Available word tags and filtering
- [Pattern Cookbook](pattern-cookbook) - Real-world pattern examples

**Advanced Topics:**
- [Performance Optimisation](pattern-performance-optimization) - Scale to millions of players
- [Rate Limits & Quotas](api-rate-limits) - Optimise costs for gaming platforms


---

# Microservices Naming
Source: https://dev.slugkit.dev/docs/example-microservices-naming

# Microservices Naming

*Apply SlugKit's forge, mint, and slice methods to create memorable, domain-driven microservice identifiers*

---

## Overview

Microservices architectures require systematic naming conventions that scale across teams and environments. This guide shows when and how to use SlugKit's three generation methods for different microservice scenarios, from business services to infrastructure components.

## Business Services (Mint Method)

**Scenario:** Generate unique service names for domain-driven business capabilities.

**Why Mint:** Business services need guaranteed uniqueness across your organization. Mint ensures no naming conflicts as teams scale and new services are added.

**Pattern Selection:**
```
Domain Services:      {noun:+activity}-{verb:+act}-service
Business Logic:       {adjective:+obj}-{noun:+activity}-handler  
Data Services:        {adjective:+obj}-data-{noun:+device}
```

**Implementation:**
```bash
# Create business services series
curl -X POST https://api.slugkit.com/api/v1/series \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "slug": "business-services",
    "pattern": "{noun:+activity}-{verb:+act}-service",
    "seed": "domain-services-2025"
  }'
```

**Daily Generation:**
```bash
# Generate new business service names
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "series_slug": "business-services",
    "count": 10
  }'
```

**Example Results:**
```
yoga-prepare-service
xerography-finger-service
xenotransplant-apostrophize-service
```

**Why This Works:**
- **Domain alignment**: Services reflect business activities
- **Guaranteed unique**: No naming conflicts across teams
- **Memorable**: Easy to remember and communicate
- **Scalable**: Supports rapid service proliferation

---

## Infrastructure Services (Forge Method)

**Scenario:** Create themed infrastructure component names that reflect their purpose.

**Why Forge:** Infrastructure services often need to match specific architectural patterns or deployment environments. Forge allows deterministic generation based on service type and environment.

**Pattern Selection:**
```
API Gateways:         {adjective:+obj}-{noun:+information}-gateway
Load Balancers:       {adjective:+obj}-traffic-balancer
Cache Services:       {adjective:+obj}-data-{noun:+device}
Message Queues:       {adjective:+obj}-message-broker
```

**Implementation:**
```bash
# Generate API gateway for production environment
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "{adjective:+obj}-{noun:+information}-gateway",
    "seed": "infrastructure-api-gateway-prod",
    "count": 1
  }'

# Generate cache service for user data
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "{adjective:+obj}-data-{noun:+device}",
    "seed": "infrastructure-cache-user-data",
    "count": 1
  }'
```

**Example Results:**
```
gigantic-shahadah-gateway
stuffy-qabalah-gateway
distal-data-grab
onside-data-sluicegate
```

**Why This Works:**
- **Environment-specific**: Same pattern produces consistent names per environment
- **Purpose-driven**: Name reflects infrastructure function
- **Deterministic**: Same service type + environment = same name
- **Architecture clarity**: Easy to identify service roles

---

## Team-Based Services (Slice + Mint Method)

**Scenario:** Allow teams to preview and select service names that match their domain.

**Why Slice Then Mint:** Teams want input on service names while maintaining uniqueness. Slice lets teams see options, mint reserves the chosen name.

**Preview Generation (Slice):**
```bash
# Show team options for their new service
curl -X POST https://api.slugkit.com/api/v1/gen/slice \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "series_slug": "team-services",
    "sequence": 500,
    "count": 5
  }'
```

**Service Selection (Mint):**
```bash
# Team selected option 2, mint it for uniqueness
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "series_slug": "team-services",
    "count": 1
  }'
```

**Example Flow:**
```
Preview Options:    team-campanulate-proration, team-executed-harassment, team-matricentric-boodle
Team Chooses:       team-executed-harassment
Final Service:      team-executed-harassment (now unique and reserved)
```

**Why This Works:**
- **Team ownership**: Teams participate in naming decisions
- **Guaranteed unique**: Selected name is minted for exclusivity
- **Consistent prefix**: All team services follow same pattern
- **Scalable process**: Works across multiple teams

---

## Environment-Specific Deployment (Forge Method)

**Scenario:** Create environment-specific service instances with consistent naming.

**Why Forge:** Different environments (dev, staging, prod) need predictable naming schemes. Forge ensures the same service gets the same name in each environment.

**Environment Patterns:**
```bash
# Development environment
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "dev-{noun:+activity}-{verb:+act}-service",
    "seed": "payment-service-development",
    "count": 1
  }'

# Production environment  
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "prod-{noun:+activity}-{verb:+act}-service",
    "seed": "payment-service-production", 
    "count": 1
  }'

# Staging environment
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "staging-{noun:+activity}-{verb:+act}-service",
    "seed": "payment-service-staging",
    "count": 1
  }'
```

**Example Results:**
```
dev-payment-process-service
prod-payment-process-service  
staging-payment-process-service
```

**Why This Works:**
- **Environment clarity**: Names clearly indicate deployment target
- **Consistent mapping**: Same core service across environments
- **Deployment automation**: Predictable names for CI/CD pipelines
- **Debugging efficiency**: Clear environment identification

---

## When to Use Each Method

| Scenario | Method | Reason |
|----------|--------|---------|
| **Business Services** | Mint | Guaranteed uniqueness across teams |
| **Infrastructure** | Forge | Environment-specific, deterministic |
| **Team Services** | Slice → Mint | Team input, guaranteed uniqueness |
| **Environment Deployment** | Forge | Predictable cross-environment naming |
| **Service Discovery** | Mint | Unique identifiers for service mesh |
| **Planning/Architecture** | Slice | Preview naming schemes before implementation |

---

## Pattern Selection Guide

**Business Domain Services:**
```
{noun:+activity}-{verb:+act}-service         # yoga-prepare-service
{adjective:+obj}-{noun:+activity}-handler    # visible-fling-handler
```

**Infrastructure Components:**
```
{adjective:+obj}-{noun:+information}-gateway # gigantic-shahadah-gateway
{adjective:+obj}-data-{noun:+device}         # distal-data-grab
{adjective:+obj}-traffic-balancer            # efficient-traffic-balancer
```

**Team-Based Services:**
```
team-{adjective:+obj}-{noun:+activity}       # team-campanulate-proration
{team-name}-{noun:+activity}-service         # platform-activity-service
```

**Environment-Specific:**
```
{env}-{noun:+activity}-{verb:+act}-service   # prod-payment-process-service
{env}-{adjective:+obj}-{noun:+device}        # dev-efficient-data-cache
```

---

## Capacity Planning

**Check pattern capacity for organizational scale:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/pattern-info \
  -H "X-API-Key: sk_live_..." \
  -d '{"pattern": "{noun:+activity}-{verb:+act}-service"}'
```

**Validated capacity results:**
- `{noun:+activity}-{verb:+act}-service`: 3.3M combinations
- `{adjective:+obj}-{noun:+activity}-handler`: 22.3M combinations
- `{adjective:+obj}-data-{noun:+device}`: 14.0M combinations
- `team-{adjective:+obj}-{noun:+activity}`: 22.3M combinations

**Enterprise planning:** Even large organizations rarely exceed 10,000 microservices.

---

## Kubernetes Integration

**Service naming for Kubernetes resources:**
```bash
# Generate Kubernetes-compatible service names
curl -X POST https://api.slugkit.com/api/v1/gen/mint \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "series_slug": "k8s-services",
    "count": 1
  }'
```

**Resource naming pattern:**
```
Service:      payment-process-service
Deployment:   payment-process-service-deployment  
ConfigMap:    payment-process-service-config
Secret:       payment-process-service-secret
Ingress:      payment-process-service-ingress
```

**Why This Works:**
- **DNS-compatible**: Follows Kubernetes naming rules
- **Resource clarity**: Easy to identify related components
- **Automation-friendly**: Predictable names for tooling
- **Team coordination**: Clear ownership and responsibility

---

## Monitoring and Observability

**Generate monitoring component names:**
```bash
# Create monitoring identifiers
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -d '{
    "pattern": "{service-name}-{component}-monitor",
    "seed": "monitoring-infrastructure",
    "count": 1
  }'
```

**Observability naming:**
```
Metrics:      payment-process-service-metrics
Logs:         payment-process-service-logs  
Traces:       payment-process-service-traces
Alerts:       payment-process-service-alerts
Dashboard:    payment-process-service-dashboard
```

**Benefits:**
- **Component tracking**: Easy to correlate monitoring data
- **Alert clarity**: Obvious service association
- **Dashboard organization**: Logical grouping
- **Incident response**: Fast service identification

---

## Available Tags Reference

**Noun tags for services:**
- `+activity`: Business activities (2,663 words)
- `+object`: General objects (18,861 words)
- `+device`: Devices and tools (1,673 words)
- `+information`: Information types (133 words)

**Verb tags for actions:**
- `+act`: Action verbs (1,246 words)
- `+change`: Change-related verbs (2,583 words)
- `+obj`: Objective verbs (5,689 words)

**Adjective tags for characteristics:**
- `+obj`: Objective descriptors (8,382 words)
- `+det`: Detached/neutral words (14,138 words)
- `+pos`: Positive words (710 words)

---

## Related Documentation

- [Pattern Syntax Basics](pattern-syntax-basics) - Learn pattern fundamentals
- [Choosing Generation Methods](choosing-generation-method) - Forge vs Mint vs Slice
- [API Reference](api-reference) - Complete endpoint documentation
- [Dictionary Reference](pattern-dictionary-reference) - Available tags and filters
- [DevOps Integration Guide](guide-devops-infrastructure) - Strategic infrastructure naming


---

# SlugKit Generator Benchmark - Aug 27 2025
Source: https://dev.slugkit.dev/docs/governing-faculty-mli

Machine running the benchmark: arm64 ubuntu image running on MacBook M4 Max 48Gb RAM host

## Seed Hash Calculation

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FNV1aHash/1 | 0.710 ns | 0.710 ns | 921441116 |  |
| FNV1aHash/2 | 0.964 ns | 0.964 ns | 733653608 |  |
| FNV1aHash/4 | 1.44 ns | 1.44 ns | 485777702 |  |
| FNV1aHash/8 | 2.51 ns | 2.50 ns | 293386083 |  |
| FNV1aHash/16 | 4.97 ns | 4.97 ns | 138698088 |  |
| FNV1aHash/32 | 10.6 ns | 10.6 ns | 64218883 |  |
| FNV1aHash/64 | 27.8 ns | 27.8 ns | 25193522 |  |

</details>

## Permutations

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| PermutePowerOf2/1 | 3.45 ns | 3.45 ns | 202300738 | 2^1 |
| PermutePowerOf2/2 | 3.44 ns | 3.44 ns | 203448723 | 2^2 |
| PermutePowerOf2/4 | 3.44 ns | 3.44 ns | 204280305 | 2^4 |
| PermutePowerOf2/8 | 3.47 ns | 3.47 ns | 203780641 | 2^8 |
| PermutePowerOf2/16 | 3.47 ns | 3.47 ns | 200099813 | 2^16 |
| PermutePowerOf2/18 | 3.46 ns | 3.46 ns | 203496999 | 2^18 |
| Permute/1 | 1.74 ns | 1.74 ns | 400163020 | 10^1 |
| Permute/2 | 2.07 ns | 2.07 ns | 339638412 | 10^2 |
| Permute/4 | 3.06 ns | 3.06 ns | 228591396 | 10^4 |
| Permute/8 | 8.09 ns | 8.09 ns | 86644744 | 10^8 |
| Permute/16 | 16.1 ns | 16.1 ns | 42681702 | 10^16 |
| Permute/18 | 20.5 ns | 20.5 ns | 33777983 | 10^18 |

</details>

## Pattern parsing

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| ParsePattern/0 | 47.3 ns | 47.3 ns | 14588729 | {number:8d} |
| ParsePattern/1 | 47.1 ns | 47.1 ns | 14897991 | {special:8} |
| ParsePattern/2 | 65.4 ns | 65.4 ns | 11137327 | {special:8-12} |
| ParsePattern/3 | 52.6 ns | 52.6 ns | 13018674 | {noun} |
| ParsePattern/4 | 52.7 ns | 52.7 ns | 13348928 | {Noun} |
| ParsePattern/5 | 52.0 ns | 52.0 ns | 13084866 | {NOUN} |
| ParsePattern/6 | 52.5 ns | 52.5 ns | 13590012 | {nOun} |
| ParsePattern/7 | 58.2 ns | 58.2 ns | 11705816 | {adjective} |
| ParsePattern/8 | 57.0 ns | 57.0 ns | 12329407 | {ADJECTIVE} |
| ParsePattern/9 | 57.1 ns | 57.1 ns | 12384193 | {Adjective} |
| ParsePattern/10 | 57.5 ns | 57.5 ns | 12138562 | {aDjective} |
| ParsePattern/11 | 96.7 ns | 96.7 ns | 7090277 | {adjective:+tag} |
| ParsePattern/12 | 133 ns | 133 ns | 5197656 | {adjective:+tag1-tag2} |
| ParsePattern/13 | 80.9 ns | 80.9 ns | 8607845 | {adjective:==10} |
| ParsePattern/14 | 158 ns | 158 ns | 4460496 | {adjective:+tag1-tag2==10} |
| ParsePattern/15 | 114 ns | 114 ns | 6402224 | {adjective}-{noun} |
| ParsePattern/16 | 171 ns | 171 ns | 4136135 | {adjective}-{noun}-{verb} |
| ParsePattern/17 | 214 ns | 214 ns | 3271819 | {adverb}-{adjective}-{noun}-{number:4x} |

</details>

## Pattern Formattings

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FormatPattern/1 | 17.8 ns | 17.8 ns | 38671069 | 1 components |
| FormatPattern/2 | 24.8 ns | 24.8 ns | 28105339 | 2 components |
| FormatPattern/3 | 32.7 ns | 32.7 ns | 21385705 | 3 components |
| FormatPattern/4 | 39.7 ns | 39.7 ns | 17407353 | 4 components |
| FormatPattern/5 | 47.7 ns | 47.7 ns | 14599787 | 5 components |
| FormatPattern/6 | 54.5 ns | 54.5 ns | 12422406 | 6 components |
| FormatPattern/7 | 60.8 ns | 60.8 ns | 11477934 | 7 components |
| FormatPattern/8 | 67.2 ns | 67.2 ns | 10347829 | 8 components |
| FormatPattern/9 | 74.9 ns | 74.9 ns | 9268469 | 9 components |
| FormatPattern/10 | 81.2 ns | 81.2 ns | 8572465 | 10 components |

</details>

## Generating Values

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| GenerateHexNumbers/1 | 23.7 ns | 23.7 ns | 29600228 | number:1x |
| GenerateHexNumbers/2 | 25.8 ns | 25.8 ns | 26996569 | number:2x |
| GenerateHexNumbers/4 | 26.4 ns | 26.4 ns | 26204703 | number:4x |
| GenerateHexNumbers/8 | 27.4 ns | 27.4 ns | 25370489 | number:8x |
| GenerateHexNumbers/16 | 32.7 ns | 32.7 ns | 21690834 | number:16x |
| GenerateHexNumbersUppercase/1 | 24.4 ns | 24.4 ns | 29197958 | number:1X |
| GenerateHexNumbersUppercase/2 | 25.6 ns | 25.6 ns | 27273427 | number:2X |
| GenerateHexNumbersUppercase/4 | 26.7 ns | 26.7 ns | 26269937 | number:4X |
| GenerateHexNumbersUppercase/8 | 27.1 ns | 27.1 ns | 24933618 | number:8X |
| GenerateHexNumbersUppercase/16 | 32.3 ns | 32.3 ns | 21996090 | number:16X |
| GenerateDecNumbers/1 | 53.1 ns | 53.1 ns | 13137676 | number:1d |
| GenerateDecNumbers/2 | 62.0 ns | 62.0 ns | 11020267 | number:2d |
| GenerateDecNumbers/4 | 61.5 ns | 61.5 ns | 11267780 | number:4d |
| GenerateDecNumbers/8 | 57.8 ns | 57.8 ns | 11721555 | number:8d |
| GenerateDecNumbers/16 | 81.6 ns | 81.6 ns | 8495975 | number:16d |
| GenerateDecNumbers/18 | 95.1 ns | 95.1 ns | 7423016 | number:18d |
| GenerateRomanNumbersUppercase/1 | 18.6 ns | 18.6 ns | 37532196 | number:1R |
| GenerateRomanNumbersUppercase/2 | 14.9 ns | 14.9 ns | 46977672 | number:2R |
| GenerateRomanNumbersUppercase/4 | 12.0 ns | 12.0 ns | 59216753 | number:4R |
| GenerateRomanNumbersUppercase/8 | 32.9 ns | 32.9 ns | 21482395 | number:8R |
| GenerateRomanNumbersUppercase/15 | 25.7 ns | 25.6 ns | 27407411 | number:15R |
| GenerateRomanNumbersLowercase/1 | 65.0 ns | 65.0 ns | 10604648 | number:1r |
| GenerateRomanNumbersLowercase/2 | 61.1 ns | 61.1 ns | 11372898 | number:2r |
| GenerateRomanNumbersLowercase/4 | 65.4 ns | 65.4 ns | 10757226 | number:4r |
| GenerateRomanNumbersLowercase/8 | 104 ns | 104 ns | 6710809 | number:8r |
| GenerateRomanNumbersLowercase/15 | 96.5 ns | 96.5 ns | 7291240 | number:15r |
| GenerateFromDictionary/1000 | 193 ns | 193 ns | 3628202 |  |
| GenerateFromDictionary/10000 | 202 ns | 202 ns | 3463411 |  |
| GenerateFromDictionary/100000 | 201 ns | 201 ns | 3478886 |  |
| GenerateFromDictionary/1000000 | 354 ns | 354 ns | 2034558 |  |
| GenerateFromDictionaryUppercase/1000 | 341 ns | 341 ns | 2080563 |  |
| GenerateFromDictionaryUppercase/10000 | 346 ns | 346 ns | 2007091 |  |
| GenerateFromDictionaryUppercase/100000 | 348 ns | 348 ns | 2022727 |  |
| GenerateFromDictionaryUppercase/1000000 | 503 ns | 502 ns | 1309848 |  |
| GenerateFromDictionaryTitleCase/1000 | 6539 ns | 6539 ns | 108670 |  |
| GenerateFromDictionaryTitleCase/10000 | 6559 ns | 6559 ns | 105645 |  |
| GenerateFromDictionaryTitleCase/100000 | 6689 ns | 6689 ns | 105084 |  |
| GenerateFromDictionaryTitleCase/1000000 | 6670 ns | 6670 ns | 105205 |  |
| GenerateFromDictionaryMixedCase/1000 | 359 ns | 359 ns | 1950292 |  |
| GenerateFromDictionaryMixedCase/10000 | 402 ns | 402 ns | 1749132 |  |
| GenerateFromDictionaryMixedCase/100000 | 442 ns | 442 ns | 1370841 |  |
| GenerateFromDictionaryMixedCase/1000000 | 664 ns | 664 ns | 1033152 |  |

</details>

## Filter Dictionaries

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FilterDictionary/0 | 237672 ns | 237658 ns | 2964 | word |
| FilterDictionary/1 | 680540 ns | 680531 ns | 1014 | word:+tag1 |
| FilterDictionary/2 | 615504 ns | 615497 ns | 1143 | word:+tag2 |
| FilterDictionary/3 | 594529 ns | 594521 ns | 1194 | word:+tag3 |
| FilterDictionary/4 | 597221 ns | 597153 ns | 1194 | word:+tag4 |
| FilterDictionary/5 | 663979 ns | 663971 ns | 1051 | word:-tag1 |
| FilterDictionary/6 | 684307 ns | 684254 ns | 1016 | word:-tag2 |
| FilterDictionary/7 | 728133 ns | 728124 ns | 947 | word:-tag3 |
| FilterDictionary/8 | 759104 ns | 759020 ns | 922 | word:-tag4 |
| FilterDictionary/9 | 1136285 ns | 1136270 ns | 612 | word:+tag1-tag2 |

</details>

## Estimate Pattern Capacity

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| CalculateSettings/0 | 73940 ns | 73767 ns | 9488 | {verb}-{adverb} |
| CalculateSettings/1 | 301710 ns | 301705 ns | 2304 | {adverb}-{noun}-{verb} |
| CalculateSettings/2 | 301914 ns | 301913 ns | 2293 | {adverb}-{noun}-{verb}-{number:4x} |
| CalculateSettings/3 | 301136 ns | 301135 ns | 2311 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| CalculateSettings/4 | 302194 ns | 302193 ns | 2306 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |

</details>

## Generate Slugs

### Internal

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| GenerateSlugInternal/0 | 455 ns | 455 ns | 1531790 | {verb}-{adverb} |
| GenerateSlugInternal/1 | 677 ns | 677 ns | 1044044 | {adverb}-{noun}-{verb} |
| GenerateSlugInternal/2 | 717 ns | 717 ns | 973663 | {adverb}-{noun}-{verb}-{number:4x} |
| GenerateSlugInternal/3 | 1315 ns | 1315 ns | 533727 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| GenerateSlugInternal/4 | 1990 ns | 1990 ns | 351967 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |

</details>

### Final

<details>

<summary>Benchmark results</summary>

| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| GenerateSlugs/0 | 73533 ns | 73532 ns | 9426 | {verb}-{adverb} |
| GenerateSlugs/1 | 303032 ns | 303031 ns | 2317 | {adverb}-{noun}-{verb} |
| GenerateSlugs/2 | 301868 ns | 301867 ns | 2310 | {adverb}-{noun}-{verb}-{number:4x} |
| GenerateSlugs/3 | 613231 ns | 613229 ns | 1128 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| GenerateSlugs/4 | 916800 ns | 916798 ns | 757 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |

</details>


---

# DevOps & Infrastructure Naming Guide
Source: https://dev.slugkit.dev/docs/guide-devops-infrastructure

# DevOps & Infrastructure Naming Guide

Learn how to create consistent, meaningful names for servers, containers, configurations, and infrastructure resources using SlugKit. This guide focuses on naming strategies, organizational patterns, and operational best practices.

**Prerequisites:** [Core Concepts](developer-core-concepts) and [Choosing Generation Methods](choosing-generation-method)  
**Reading Time:** 25 minutes

## Why Infrastructure Naming Matters

Poor infrastructure naming creates operational challenges:

```
❌ Poor Naming Examples:
server-1, server-2, server-3     → No context or purpose
web-prod-db-backup-temp-final    → Confusing and unmaintainable
k8s-deployment-abc123            → Generated but meaningless
vm-47291847                      → Sequential reveals infrastructure scale
```

SlugKit generates meaningful, organized infrastructure names:

```
✅ SlugKit Infrastructure Names:
stable-database-prod-01          → Clear role, environment, sequence
secure-api-gateway-staging-03    → Service type, environment, instance
active-worker-queue-dev-02       → Function, component, environment
smart-cache-cluster-prod-05      → Purpose, type, environment
```

## Infrastructure Naming Principles

### 1. Hierarchical Information Architecture

**Information Priority Order:**
1. **Function/Role**: What does it do?
2. **Environment**: Where does it run?
3. **Instance**: Which specific instance?

**Pattern Structure:**
```
{adjective:+obj}-{noun:+device}-{environment}-{number:2d}
→ stable-database-prod-01
→ secure-gateway-staging-02
→ active-worker-dev-03
```

### 2. Environment Consistency

**Standard Environment Naming:**
```
dev        → Development and testing
staging    → Pre-production validation  
prod       → Production systems
test       → Automated testing
sandbox    → Experimental environments
```

**Environment-Specific Patterns:**
```
Development:  {adjective:+obj}-{noun:+device}-dev-{number:2d}
Staging:      {adjective:+obj}-{noun:+device}-staging-{number:2d}
Production:   {adjective:+obj}-{noun:+device}-prod-{number:2d}
```

### 3. Operational Context

**Use objective adjectives for operational clarity:**
```
{adjective:+obj}  → stable, secure, active, primary, backup
                     reliable, efficient, robust, scalable
```

**Avoid subjective or temporary adjectives:**
```
❌ {adjective:+pos}  → brilliant, amazing, clever (too casual)
❌ {adjective:+neg}  → broken, failed, slow (negative implications)
```

## Server and Virtual Machine Naming

### Traditional Server Naming

**Physical Servers:**
```
Pattern: {adjective:+obj<6}-{noun:+device<8}-{location}-{number:2d}
Examples: 
- stable-server-nyc-01 (New York data center, server 1)
- secure-database-aws-03 (AWS region, database server 3)
- active-compute-gcp-07 (Google Cloud, compute server 7)
```

**Virtual Machines:**
```
Pattern: vm-{adjective:+obj<7}-{noun:+device<8}-{env}-{number:2d}
Examples:
- vm-reliable-webapp-prod-01
- vm-secure-database-staging-02
- vm-active-worker-dev-03
```

### Role-Based Server Naming

**Web Servers:**
```
Pattern: web-{adjective:+obj<6}-{noun:+content<7}-{env}-{number:2d}
Examples: web-fast-api-prod-01, web-secure-portal-staging-02
```

**Database Servers:**
```
Pattern: db-{adjective:+obj<7}-{noun:+data<8}-{env}-{number:2d}
Examples: db-primary-postgres-prod-01, db-backup-mysql-staging-02
```

**Application Servers:**
```
Pattern: app-{adjective:+obj<6}-{noun:+service<7}-{env}-{number:2d}
Examples: app-scalable-api-prod-01, app-reliable-worker-dev-02
```

## Container and Kubernetes Naming

### Container Naming Strategies

**Docker Container Names:**
```
Pattern: {adjective:+obj<7}-{noun:+device<8}-{version}
Examples: 
- stable-webapp-v2-1
- secure-database-v1-8
- active-cache-v3-2
```

**Container Registry Naming:**
```
Pattern: {organization}/{adjective:+obj}-{noun:+device}:{version}
Examples:
- myorg/reliable-api:v2.1
- myorg/secure-worker:v1.5
- myorg/fast-cache:v3.0
```

### Kubernetes Resource Naming

**Deployment Names:**
```
Pattern: {adjective:+obj<8}-{noun:+device<8}-{env}
Examples: reliable-webapp-prod, secure-database-staging
```

**Service Names:**
```
Pattern: {adjective:+obj<7}-{noun:+service<8}-svc
Examples: stable-api-svc, secure-auth-svc, active-queue-svc
```

**ConfigMap and Secret Names:**
```
Pattern: {adjective:+obj<7}-{noun:+device<8}-{config-type}
Examples: 
- secure-database-config
- stable-webapp-secrets
- active-cache-settings
```

**Namespace Organization:**
```
Pattern: {env}-{adjective:+obj<6}-{noun:+service<7}
Examples: prod-secure-api, staging-reliable-web, dev-active-worker
```

## Configuration and Environment Management

### Environment Variables

**System Configuration:**
```
Pattern: {ADJECTIVE:+obj}_{NOUN:+device}_CONFIG
Examples:
- STABLE_DATABASE_CONFIG=postgresql://...
- SECURE_API_CONFIG=https://...
- ACTIVE_CACHE_CONFIG=redis://...
```

**Application Settings:**
```
Pattern: {ADJECTIVE:+obj}_{NOUN:+service}_{SETTING}
Examples:
- RELIABLE_AUTH_URL=https://auth.example.com
- SECURE_PAYMENT_KEY=sk_live_...
- ACTIVE_QUEUE_WORKERS=10
```

### Configuration File Naming

**Application Configs:**
```
Pattern: {adjective:+obj}-{noun:+service}.{env}.{ext}
Examples:
- secure-database.prod.yml
- reliable-api.staging.json
- active-worker.dev.conf
```

**Infrastructure as Code:**
```
Pattern: {adjective:+obj}-{noun:+device}-{env}.tf
Examples:
- stable-compute-prod.tf
- secure-network-staging.tf
- active-storage-dev.tf
```

## Network and Security Naming

### Network Resource Naming

**Subnets and VPCs:**
```
Pattern: {adjective:+obj<7}-{noun:+network<8}-{env}-{region}
Examples:
- secure-private-prod-us-east
- reliable-public-staging-eu-west
- isolated-mgmt-prod-ap-south
```

**Load Balancers:**
```
Pattern: lb-{adjective:+obj<6}-{noun:+service<7}-{env}
Examples: lb-stable-api-prod, lb-secure-web-staging
```

**Security Groups:**
```
Pattern: sg-{adjective:+obj<7}-{noun:+service<8}-{env}
Examples: sg-secure-database-prod, sg-reliable-webapp-staging
```

### SSL Certificates and Secrets

**Certificate Naming:**
```
Pattern: cert-{adjective:+obj<6}-{noun:+service<7}-{env}
Examples: cert-secure-api-prod, cert-trusted-web-staging
```

**Secret Management:**
```
Pattern: secret-{adjective:+obj<6}-{noun:+service<7}-{type}
Examples: 
- secret-secure-database-password
- secret-reliable-api-token
- secret-trusted-auth-key
```

## Monitoring and Logging

### Log File Organization

**Application Logs:**
```
Pattern: {adjective:+obj}-{noun:+service}-{env}-{date}.log
Examples:
- reliable-api-prod-2024-12-01.log
- secure-auth-staging-2024-12-01.log
- active-worker-dev-2024-12-01.log
```

**System Logs:**
```
Pattern: {adjective:+obj}-{noun:+device}-{env}-{type}.log
Examples:
- stable-server-prod-access.log
- secure-database-prod-error.log
- active-cache-staging-debug.log
```

### Monitoring Resource Names

**Prometheus Metrics:**
```
Pattern: {adjective:+obj}_{noun:+device}_{metric_type}
Examples:
- reliable_api_response_time
- secure_database_connections
- active_worker_queue_size
```

**Grafana Dashboards:**
```
Pattern: {adjective:+obj}-{noun:+service}-{env}-dashboard
Examples:
- stable-api-prod-dashboard
- secure-database-staging-dashboard
- active-queue-dev-dashboard
```

**Alert Rules:**
```
Pattern: alert-{adjective:+obj}-{noun:+service}-{condition}
Examples:
- alert-reliable-api-high-latency
- alert-secure-database-low-space
- alert-active-worker-queue-full
```

## Cloud Resource Naming

### AWS Resource Naming

**EC2 Instances:**
```
Pattern: ec2-{adjective:+obj<7}-{noun:+device<8}-{env}-{az}
Examples: ec2-reliable-webapp-prod-1a, ec2-secure-database-staging-1b
```

**S3 Buckets:**
```
Pattern: {org}-{adjective:+obj<6}-{noun:+storage<7}-{env}
Examples: myorg-secure-backup-prod, myorg-reliable-assets-staging
```

**RDS Instances:**
```
Pattern: rds-{adjective:+obj<7}-{noun:+data<8}-{env}
Examples: rds-primary-postgres-prod, rds-replica-mysql-staging
```

### Google Cloud Resource Naming

**Compute Instances:**
```
Pattern: gce-{adjective:+obj<7}-{noun:+device<8}-{env}-{zone}
Examples: gce-stable-webapp-prod-a, gce-secure-worker-staging-b
```

**Cloud Storage Buckets:**
```
Pattern: {org}-{adjective:+obj<6}-{noun:+storage<7}-{env}
Examples: myorg-reliable-backup-prod, myorg-secure-assets-staging
```

### Azure Resource Naming

**Virtual Machines:**
```
Pattern: vm-{adjective:+obj<7}-{noun:+device<8}-{env}-{region}
Examples: vm-reliable-webapp-prod-east, vm-secure-database-staging-west
```

**Storage Accounts:**
```
Pattern: st{org}{adjective:+obj<5}{noun:+storage<6}{env}
Examples: stmyorgreliablebackupprod, stmyorgsecureassetsstaging
Note: Azure storage names have specific constraints
```

## CI/CD Pipeline Naming

### Pipeline and Job Naming

**Jenkins Jobs:**
```
Pattern: {adjective:+obj<7}-{noun:+service<8}-{env}-{action}
Examples:
- reliable-api-prod-deploy
- secure-webapp-staging-test
- stable-database-prod-backup
```

**GitHub Actions Workflows:**
```
Pattern: {adjective:+obj<7}-{noun:+service<8}-{workflow}.yml
Examples:
- reliable-api-deploy.yml
- secure-webapp-test.yml
- stable-database-backup.yml
```

**GitLab CI Pipelines:**
```
Pattern: {adjective:+obj<6}-{noun:+service<7}-{env}
Examples: reliable-api-prod, secure-webapp-staging, stable-worker-dev
```

### Artifact and Build Naming

**Build Artifacts:**
```
Pattern: {adjective:+obj<6}-{noun:+service<7}-{version}-{build}
Examples:
- reliable-api-v2.1-build-247
- secure-webapp-v1.8-build-891
- stable-worker-v3.0-build-456
```

**Container Tags:**
```
Pattern: {adjective:+obj<6}-{noun:+service<7}:{version}-{build}
Examples:
- reliable-api:v2.1-247
- secure-webapp:v1.8-891
- stable-worker:v3.0-456
```

## Backup and Disaster Recovery

### Backup Naming Strategies

**Database Backups:**
```
Pattern: backup-{adjective:+obj<6}-{noun:+data<7}-{env}-{timestamp}
Examples:
- backup-primary-postgres-prod-20241201-0300
- backup-replica-mysql-staging-20241201-0600
```

**File System Backups:**
```
Pattern: backup-{adjective:+obj<6}-{noun:+storage<7}-{env}-{type}
Examples:
- backup-reliable-assets-prod-full
- backup-secure-configs-staging-incremental
```

**Snapshot Naming:**
```
Pattern: snap-{adjective:+obj<6}-{noun:+device<7}-{env}-{date}
Examples:
- snap-stable-webapp-prod-20241201
- snap-secure-database-staging-20241201
```

### Disaster Recovery Resources

**DR Site Naming:**
```
Pattern: dr-{adjective:+obj<6}-{noun:+device<7}-{region}
Examples: dr-stable-webapp-west, dr-secure-database-east
```

**Failover Resources:**
```
Pattern: fo-{adjective:+obj<6}-{noun:+service<7}-{env}
Examples: fo-reliable-api-prod, fo-secure-auth-staging
```

## Operational Best Practices

### Naming Convention Documentation

**Standard Documentation Should Include:**
- Pattern definitions for each resource type
- Environment abbreviation standards
- Numbering and sequencing conventions
- Reserved words and forbidden patterns
- Update and migration procedures

### Team Coordination

**Naming Governance:**
- Establish naming standards before infrastructure deployment
- Create naming convention templates for common resources
- Implement validation tools for naming compliance
- Regular audits of naming consistency

**Tool Integration:**
- Use SlugKit forge() for design-time naming
- Implement naming validation in IaC tools
- Create naming templates for terraform modules
- Automate compliance checking in CI/CD

### Migration and Evolution

**Handling Naming Changes:**
- Plan for naming standard evolution
- Maintain backward compatibility during transitions
- Document legacy naming patterns
- Implement gradual migration strategies

**Capacity Planning:**
- Choose patterns with sufficient capacity for growth
- Plan numbering sequences for scale
- Consider regional and availability zone expansion
- Monitor naming pattern utilization

## Multi-Environment Strategy

### Environment Isolation

**Development Environments:**
```
Pattern Focus: {adjective:+obj<7}-{noun:+device<8}-dev-{developer-id}
Purpose: Individual developer environments
Example: stable-webapp-dev-alice-01
```

**Testing Environments:**
```
Pattern Focus: {adjective:+obj<7}-{noun:+device<8}-test-{test-type}
Purpose: Automated and manual testing
Example: reliable-api-test-integration-01
```

**Staging Environments:**
```
Pattern Focus: {adjective:+obj<7}-{noun:+device<8}-staging-{number:2d}
Purpose: Production-like validation
Example: secure-database-staging-01
```

**Production Environments:**
```
Pattern Focus: {adjective:+obj<7}-{noun:+device<8}-prod-{number:2d}
Purpose: Live production systems
Example: stable-webapp-prod-01
```

### Cross-Environment Consistency

**Naming Alignment:**
- Use identical patterns across environments
- Only change environment identifier
- Maintain resource relationships
- Enable easy environment comparison

**Resource Mapping:**
- Document resource relationships across environments
- Create environment promotion procedures
- Maintain configuration parity
- Plan for environment-specific variations

## Security and Compliance

### Security-Focused Naming

**Sensitive Resource Identification:**
```
Pattern: secure-{noun:+data<8}-{env}-{security-level}
Examples: secure-database-prod-pci, secure-storage-prod-hipaa
```

**Access Control Resources:**
```
Pattern: access-{adjective:+obj<6}-{noun:+person<7}-{env}
Examples: access-admin-users-prod, access-readonly-analysts-staging
```

### Compliance Documentation

**Audit Trail Naming:**
- Include compliance frameworks in naming
- Document security level requirements
- Maintain naming standard versioning
- Create compliance mapping documentation

**Change Management:**
- Document all naming standard changes
- Require approval for naming pattern modifications
- Maintain historical naming documentation
- Implement change notification procedures

## Next Steps

**Ready to implement infrastructure naming?**

**Implementation**: [Web Development Guide](guide-web-development) for SDK integration
**Pattern Testing**: [Interactive Tutorial](developer-tutorial) for pattern experimentation
**Production Setup**: [Using Mint for Guaranteed Uniqueness](api-mint-endpoint)
**Advanced Patterns**: [Pattern Language Advanced Features](pattern-advanced-features)

**Need help with specific infrastructure?** Check [Troubleshooting Guide](troubleshooting-common-errors) or [get support](troubleshooting-support).

---

# MCP Integration Guide
Source: https://dev.slugkit.dev/docs/guide-mcp-integration

# MCP Integration Guide

Enable AI agents like Claude to generate truly unique, collision-free slugs directly within their workflows using SlugKit's Model Context Protocol (MCP) server.

## What is MCP?

The Model Context Protocol (MCP) is an open standard that allows AI assistants to connect to external data sources and tools. SlugKit's MCP server gives AI agents direct access to SlugKit's slug generation capabilities, enabling them to create human-readable identifiers as part of their reasoning and coding workflows.

## Why Use SlugKit MCP?

When building applications with AI assistance, agents can now:

- **Generate unique identifiers** on-demand without writing boilerplate code
- **Validate patterns** before implementing them in your codebase
- **Test slug generation** interactively during development
- **Access dictionary information** to understand available word types and tags
- **Create and manage series** for guaranteed uniqueness across distributed systems
- **Track slug generation** with full series lifecycle management

This is particularly valuable when AI agents are helping you build:
- User registration systems requiring unique handles
- Content management systems needing URL-friendly slugs
- DevOps tooling with human-readable resource names
- API endpoints with aesthetic, memorable identifiers

## Installation

Install the SlugKit MCP server globally via npm:

```bash
npm install -g @slugkit/mcp
```

## Configuration

### Claude Desktop

Add the SlugKit MCP server to your Claude Desktop configuration file:

**macOS/Linux:** `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "slugkit-generator": {
      "command": "slugkit-mcp",
      "args": [],
      "env": {
        "SLUGKIT_API_KEY": "your-api-key-here",
        "SLUGKIT_BASE_URL": "https://api.slugkit.dev"
      }
    }
  }
}
```

Replace `your-api-key-here` with your actual SlugKit API key from https://slugkit.dev/dashboard.

### Claude Code

Create or edit `.claude/mcp.json` in your project directory:

```json
{
  "mcpServers": {
    "slugkit-generator": {
      "command": "slugkit-mcp",
      "args": [],
      "env": {
        "SLUGKIT_API_KEY": "your-api-key-here",
        "SLUGKIT_BASE_URL": "https://api.slugkit.dev"
      }
    }
  }
}
```

After adding the configuration, restart Claude Desktop or reload Claude Code to enable the MCP server.

## API Key Requirements

### Basic Access

All SlugKit API keys provide access to:
- Pattern validation and analysis
- Dictionary information
- Slug generation via `forge`
- Reading series information

### Series Management Access

To enable AI agents to **create, update, and delete series**, your API key must include series management scopes:

- `series:create` - Create new series
- `series:update` - Update existing series
- `series:delete` - Delete series

**Creating a key with series management:**

1. Go to https://slugkit.dev/dashboard
2. Navigate to API Keys
3. Create a new API key with the required scopes
4. Update your MCP configuration with the new key

For detailed information about API key scopes and authentication, see the [Authentication Guide](api-authentication).

**Important:** Series management requires appropriate permissions. If your agent receives permission errors when creating or managing series, verify your API key includes the necessary scopes.

## Available MCP Functions

Once configured, AI agents have access to these SlugKit functions:

### Core Functions
- `ping` - Verify API connectivity
- `key_info` - Check API key capabilities and scopes
- `limits` - View organization subscription limits and features
- `list_help_topics` - Browse available documentation
- `get_help_topic` - Access specific documentation

### Pattern Functions
- `validate_pattern` - Validate pattern syntax and check capacity
- `forge` - Generate slugs from a pattern (stateless, suitable for non-critical use)
- `analyze_pattern` - Deep analysis of pattern characteristics
- `compare_patterns` - Compare multiple patterns side-by-side

### Dictionary Functions
- `dictionary_info` - Get information about available word dictionaries
- `dictionary_tags` - List available tags for filtering words

### Series Functions
- `mint` - Generate tracked, collision-free slugs from a series
- `slice` - Preview slugs from a series without consuming them
- `series_list` - List all series accessible to your API key
- `series_info` - Get detailed information about a specific series
- `series_create` - Create a new series with a pattern (requires `series:create` scope)
- `series_update` - Update an existing series (requires `series:update` scope, fails if series is locked)
- `series_delete` - Delete a series and all associated data (requires `series:delete` scope)

## Example Workflows

### Building a User Registration System

When an AI agent helps you build user registration, it can:

1. **Check API key capabilities**:
   ```
   Agent uses: key_info()
   Result: Verifies series:create scope is available
   ```

2. **Validate your pattern** to ensure it works:
   ```
   Agent uses: validate_pattern("{adjective}-{noun}")
   Result: ~708M unique combinations, max length 55 chars
   ```

3. **Create a dedicated series** for user handles:
   ```
   Agent uses: series_create("User Handles", "{adjective}-{noun}")
   Result: Series created with slug "user-handles"
   ```

4. **Generate tracked usernames** with guaranteed uniqueness:
   ```
   Agent uses: mint(series_slug: "user-handles", count: 5)
   Result: motherly-horridness, audacious-starvation, periphrastic-dry
   ```

5. **Implement the integration** in your code with confidence

### Enabling Series Management for Agents

For agents to manage series lifecycle, ensure proper setup:

1. **Verify API key scopes**:
   ```
   Agent uses: key_info()
   Result: Check that scopes include series:create, series:update, series:delete
   ```

2. **Check organization limits**:
   ```
   Agent uses: limits()
   Result: Verify max_series and other quotas
   ```

3. **Agent can now create series**:
   ```
   Agent uses: series_create("API Endpoints", "{noun:+device}-{verb:+change}")
   Result: New series ready for use
   ```

4. **Agent manages series lifecycle**:
   ```
   Agent uses: series_info("api-endpoints")
   Agent uses: series_update("api-endpoints", "API Endpoints v2", "{new-pattern}")
   Agent uses: series_delete("old-test-series")
   ```

This enables agents to autonomously set up and manage slug generation infrastructure as part of application development workflows.

### Managing Multiple Series

For applications with different identifier types:

1. **List existing series** to see what's already configured:
   ```
   Agent uses: series_list()
   Result: {"user-handles": "User Handles", "api-keys": "API Key Names"}
   ```

2. **Check series information** before generating:
   ```
   Agent uses: series_info("user-handles")
   Result: Pattern, capacity, generated count, creation date
   ```

3. **Update series patterns** if needed (only works if no IDs generated yet):
   ```
   Agent uses: series_update("user-handles", "User Handles", "{adjective:>5}-{noun:>5}")
   Result: Updated series with new pattern constraints
   ```

### Creating API Endpoint Slugs

For a content API requiring unique slugs:

1. **Agent analyzes your requirements** and suggests patterns
2. **Creates a series** for your content type
3. **Tests patterns** using `slice` to preview without consuming
4. **Implements the slug generation** in your API handlers

### DevOps Resource Naming

When setting up infrastructure:

1. **Agent validates naming patterns** for servers, containers, or deployments
2. **Creates series** for different resource types
3. **Checks capacity** to ensure patterns won't exhaust in production
4. **Generates names** using `mint` for actual resources

## Series Management Best Practices

### Creating Series

**Choose descriptive names** - Series names should clearly indicate their purpose:
```
series_create("User Account Handles", "{adjective}-{noun}")
series_create("Blog Post URLs", "{noun:3-8}-{number:3d}")
series_create("Server Names", "{adjective@en:+obj}-{noun@en:+device}")
```

**Validate patterns first** - Always use `validate_pattern` before creating a series:
```
1. validate_pattern("{your-pattern}")
2. Review capacity and max length
3. series_create("Series Name", "{your-pattern}")
```

### Understanding Series Locks

Once you mint even a single slug from a series, it becomes **locked** - you cannot update the pattern anymore. This ensures consistency:

- **Locked series**: Have `generated_ids_count > 0`, pattern cannot be changed
- **Unlocked series**: No IDs generated yet, pattern can be updated
- **Delete and recreate**: Only way to change a locked series pattern

### Monitoring Series

Use `series_info` to track your series health:

```
series_info("user-handles")

Returns:
- Total capacity of the pattern
- Number of IDs already generated
- Percentage utilised
- Creation and modification times
```

**Set up alerts** when series reach 80% capacity.

### Deleting Series

`series_delete` removes the series and **all tracking data**:

- Use with caution in production
- Cannot be undone
- All generated IDs are untracked afterward
- Best used for development/testing series

## Series vs Forge

The MCP server provides both **forge** (stateless generation) and **mint** (series-based tracked generation):

**Use `forge` when:**
- Prototyping and testing patterns
- Generating examples for documentation
- Non-critical identifiers where collisions are acceptable
- You want maximum performance (no database lookups)

**Use `mint` when:**
- Building production user registration systems
- Creating guaranteed-unique API resource identifiers
- Distributed systems requiring collision-free IDs
- Audit trails matter (series track all generated slugs)
- You need to monitor capacity and usage

**Example with series:**

```
Agent uses: mint(series_slug: "user-handles", count: 3)
Result: clever-dolphin, bright-horizon, noble-falcon
(These are guaranteed unique and tracked in your series)
```

## Getting Your API Key

1. Sign up at https://slugkit.dev
2. Navigate to your dashboard
3. Create an API key for your application
4. Select appropriate scopes (include `series:create`, `series:update`, `series:delete` for full series management)
5. Add the key to your MCP configuration

Free tier includes generous limits for development and testing.

## Best Practices

### Pattern Design
- **Start simple** - Use basic patterns like `{adjective}-{noun}` first
- **Test patterns** - Have the agent validate before implementing
- **Check capacity** - Ensure patterns have sufficient unique combinations
- **Consider aesthetics** - Generate examples to verify readability

### API Usage
- **Verify scopes** - Use `key_info()` to confirm your API key has necessary permissions
- **Check limits** - Use `limits()` to understand your organization's quotas
- **Use series for production** - Mint from series when uniqueness matters
- **Validate before creating** - Always validate patterns before creating series
- **Monitor series health** - Regularly check `series_info` for capacity
- **Handle locks gracefully** - Check if series is locked before attempting updates
- **Cache pattern validation** - Patterns don't change, validation results are stable
- **Handle errors gracefully** - Invalid patterns should fail fast during development

### Development Workflow
- **Let agents explore** - MCP allows agents to test patterns interactively
- **Create test series** - Use separate series for development vs production
- **Review generated slugs** - Ensure aesthetic quality matches your brand
- **Document chosen patterns** - Agents can help document why patterns were selected
- **Clean up test series** - Delete development series when no longer needed
- **Test edge cases** - Have agents validate patterns with constraints

## Troubleshooting

### MCP Server Not Connecting

**Check your configuration:**
- Verify the API key is correct
- Ensure the base URL is `https://api.slugkit.dev`
- Confirm the configuration file path is correct
- Restart Claude Desktop/Code after configuration changes

**Test the connection:**
Ask Claude to use the `ping` function to verify connectivity.

### Pattern Validation Failures

**Common issues:**
- Invalid tag names (use `dictionary_tags` to see available tags)
- Incompatible tag combinations (e.g., `+pos+neg`)
- Syntax errors in pattern (use `validate_pattern` to diagnose)

### Series Management Permission Errors

**"Permission denied" or "Insufficient scopes" error:**
- Your API key lacks required scopes for series management
- Use `key_info()` to check current scopes
- Create a new API key with `series:create`, `series:update`, `series:delete` scopes
- See [Authentication Guide](api-authentication) for detailed scope information

### Series Update Failures

**"Series is locked" error:**
- Series has generated IDs and cannot be updated
- Check `series_info` to see `generated_ids_count`
- Delete and recreate the series if pattern must change
- Use `slice` to preview changes before committing

### No Matching Words Found

This occurs when tag filters are too restrictive:
- Check tags exist for the word type using `dictionary_tags`
- Reduce the number of tag filters
- Try alternative tag combinations
- Remove length constraints that may be too strict

## Next Steps

- **Explore patterns** - Ask your AI agent to test different patterns
- **Create your first series** - Set up tracked slug generation for your application
- **Monitor series health** - Check capacity and usage regularly
- **Read the Pattern Language docs** - Understand advanced features like case transformations and global settings
- **Check the API Reference** - Learn about REST API endpoints for direct integration

## Related Documentation

- [Authentication Guide](api-authentication) - API key scopes and security
- [Pattern Syntax Basics](pattern-syntax-basics) - Learn the pattern language
- [API Reference](api-reference) - Complete API documentation  
- [Dictionary Reference](pattern-dictionary-reference) - Available word types and tags
- [Choosing Generation Methods](choosing-generation-method) - Forge vs Mint vs Slice guide
- [API Series Management](api-series-management) - Deep dive into series lifecycle


---

# User Handles & Social Integration Guide
Source: https://dev.slugkit.dev/docs/guide-user-handles

# User Handles & Social Integration Guide

Learn how to design memorable, family-friendly user handles and social identifiers using SlugKit patterns. This guide focuses on pattern design, user experience principles, and platform-specific considerations.

**Prerequisites:** [Core Concepts](developer-core-concepts) and [Choosing Generation Methods](choosing-generation-method)  
**Reading Time:** 15 minutes

## Why User Handles Matter

Traditional user ID systems create poor user experiences:

```
❌ Poor UX Examples:
user_847291847      → Hard to remember
uuid-a1b2-c3d4     → Impossible to share verbally  
john.doe.1847      → Generic and impersonal
user47291          → Sequential (reveals user count)
```

SlugKit generates memorable, brandable handles:

```
✅ SlugKit User Handles:
clever-dolphin-42    → Easy to remember and share
wise-tiger-67        → Conversation starter
brave-eagle-23       → Positive, aspirational
active-panda-91      → Family-friendly
```

## Handle Design Principles

### 1. Memorability First

**Good handle patterns create mental images:**
```
{adjective:+pos}-{noun:+animal}-{number:2d}
→ clever-dolphin-42, wise-tiger-67, brave-eagle-23
```

**Why this works:**
- **Adjective creates personality**: "clever" suggests intelligence
- **Animal creates imagery**: dolphins are relatable and memorable  
- **Number provides uniqueness**: keeps handles short and practical

### 2. Positive Brand Association

**Use positive emotional tags:**
```
{adjective:+pos}     → brilliant, amazing, clever, wise, brave
{adjective:+obj}     → stable, secure, active, smart, quick
{adjective:+neut}    → standard, normal, basic, simple, clean
```

**Avoid negative associations:**
```
❌ {adjective:+neg}  → broken, failed, slow, weak, old
❌ Words that imply temporary states or problems
```

### 3. Age-Appropriate Content

**Child-safe patterns (ages 6-12):**
```
{adjective:+pos<6}-{noun:+animal<7}
→ happy-puppy, kind-bunny, brave-bear
```

**Teen-friendly patterns (ages 13-17):**
```
{adjective:+pos<7}-{noun:+animal<8}-{number:1d}
→ clever-dolphin-7, smart-eagle-3, cool-tiger-9
```

**Adult patterns (18+):**
```
{adjective:+pos<8}-{noun:+animal<8}-{number:2d}
→ brilliant-elephant-42, awesome-falcon-67
```

## Platform-Specific Pattern Design

### Gaming Platforms

**Casual Gaming (family-friendly):**
```
Pattern: player-{adjective:+pos<6}-{noun:+animal<7}-{number:2d}
Examples: player-happy-panda-23, player-brave-tiger-67
Length: ~20 characters
Audience: All ages
```

**Competitive Gaming:**
```
Pattern: {adjective:+obj<7}-{noun:+fantasy<8}-{number:3d}
Examples: fierce-warrior-247, swift-ranger-891
Length: ~18 characters  
Audience: Teens and adults
```

**Professional Esports:**
```
Pattern: {adjective:+obj<6}-{noun:+device<7}
Examples: cyber-master, quick-strike
Length: ~13 characters
Audience: Competitive players
```

### Social Media Platforms

**Professional Networks (LinkedIn):**
```
Pattern: {adjective:+obj<8}-{noun:+person<9}
Examples: smart-developer, wise-consultant, active-manager
Focus: Professional credibility
```

**Creative Platforms (Instagram, TikTok):**
```
Pattern: {adjective:+pos<7}-{noun:+art<8}
Examples: creative-maker, bright-artist, bold-designer
Focus: Creative expression
```

**Microblogging (Twitter):**
```
Pattern: {adjective:+obj<6}-{noun:+content<8}
Examples: smart-writer, quick-thinker, wise-blogger
Constraint: 15 character limit
```

## Handle Pattern Categories

### 1. Animal-Based Handles

**Best for:** Gaming, casual social platforms, family-friendly communities

```
Basic: {adjective:+pos}-{noun:+animal}
→ clever-dolphin, wise-tiger, brave-eagle

Numbered: {adjective:+pos<6}-{noun:+animal<7}-{number:2d}
→ smart-panda-42, kind-bunny-67

Themed: {adjective:+pos}-{noun:+animal}-{noun:+fantasy}
→ brave-tiger-knight, wise-eagle-mage
```

**Why animals work:**
- Universal appeal across cultures
- Easy to visualize and remember
- Positive associations (strength, intelligence, grace)
- Large vocabulary prevents repetition

### 2. Professional Handles

**Best for:** Business networks, professional platforms, work environments

```
Role-based: {adjective:+obj}-{noun:+person}
→ smart-developer, wise-consultant, active-manager

Skill-based: {adjective:+obj}-{noun:+skill}
→ expert-coder, creative-designer, strategic-planner

Industry: {adjective:+obj}-{noun:+industry}
→ innovative-tech, reliable-finance, creative-media
```

### 3. Creative Handles

**Best for:** Artistic platforms, content creation, personal branding

```
Artistic: {adjective:+pos}-{noun:+art}
→ creative-painter, bold-musician, bright-writer

Action-oriented: {adjective:+pos}-{noun:+action}
→ dynamic-creator, active-builder, inspiring-teacher

Abstract: {adjective:+pos}-{noun:+concept}
→ brilliant-vision, amazing-dream, wise-thought
```

## User Experience Guidelines

### 1. Handle Selection Flow

**Recommended UX Pattern:**
1. **Generate 4-6 options** using client-side preview
2. **Show visual preview** of profile with each handle
3. **Allow regeneration** if options don't appeal
4. **Server-side generation** for final selection (guaranteed unique)

**Pattern Selection Strategy:**
```
First attempt:  {adjective:+pos<6}-{noun:+animal<7}-{number:2d}
If rejected:    {adjective:+obj<7}-{noun:+device<8}-{number:2d}
If rejected:    {adjective:+pos<7}-{noun:+person<8}-{number:2d}
```

### 2. Handle Display Guidelines

**Display Name Creation:**
```
Handle: clever-dolphin-42
Display Name: Clever Dolphin (remove number, capitalize)
Username: @clever-dolphin-42 (add @ prefix)
Profile URL: /users/clever-dolphin-42 (full handle)
```

**Visual Representation:**
- **Avatar generation**: Use handle as seed for consistent avatar
- **Color theming**: Derive profile colors from handle
- **Badge creation**: First letters for profile badges (CD for Clever Dolphin)

### 3. Handle Validation Guidelines

**Length Constraints:**
```
Gaming: 8-20 characters (including numbers)
Social: 6-15 characters (platform dependent)
Professional: 8-25 characters (readable emphasis)
```

**Character Validation:**
```
Allowed: letters, numbers, hyphens
Restricted: underscores (platform dependent)
Forbidden: special characters, spaces, unicode
```

**Content Moderation:**
- Use positive tag filters (`+pos`, `+obj`)
- Avoid ambiguous words that could be misinterpreted
- Implement platform-specific blocked word lists

## Platform-Specific Considerations

### Gaming Platform Requirements

| Platform | Max Length | Numbers | Special Chars | Recommended Pattern |
|----------|------------|---------|---------------|-------------------|
| Steam | 32 | ✅ | Limited | `{adj:+pos<8}-{noun:+animal<8}-{num:3d}` |
| Xbox | 15 | ✅ | ❌ | `{adj:+pos<5}-{noun:+animal<6}` |
| PlayStation | 16 | ✅ | ❌ | `{adj:+pos<6}-{noun:+animal<7}` |
| Nintendo | 10 | ❌ | ❌ | `{adj:+pos<5}-{noun:+animal<5}` |

### Social Media Constraints

| Platform | Max Length | Valid Chars | Reserved Words | Pattern Focus |
|----------|------------|-------------|----------------|--------------|
| Twitter | 15 | a-z, 0-9, _ | admin, api, www | Professional/Creative |
| Instagram | 30 | a-z, 0-9, _, . | instagram, admin | Visual/Creative |
| TikTok | 24 | a-z, 0-9, _, . | tiktok, official | Fun/Creative |
| LinkedIn | 50 | a-z, 0-9, - | admin, linkedin | Professional |

## Age and Cultural Considerations

### Child-Safe Pattern Design

**Ages 6-12 (supervised accounts):**
```
Pattern: {adjective:+pos<6}-{noun:+animal<7}
Focus: Simple, positive, no numbers
Examples: happy-puppy, kind-bear, sweet-bunny
```

**Ages 13-17 (teen accounts):**
```
Pattern: {adjective:+pos<7}-{noun:+animal<8}-{number:1d}
Focus: Age-appropriate with minimal numbers
Examples: cool-tiger-7, smart-eagle-3, brave-wolf-9
```

### Cultural Sensitivity

**Global-Friendly Patterns:**
- Use universally positive adjectives
- Choose animals known across cultures
- Avoid cultural-specific references
- Test patterns with international teams

**Language Considerations:**
- English patterns work globally for gaming/tech
- Consider local language variants for regional platforms
- Avoid words that translate poorly
- Test pronunciation across languages

## Handle Lifecycle Management

### 1. Creation Strategies

**Preview-First Approach:**
- Generate multiple options with `forge()` client-side
- User selects preferred style/theme
- Final generation uses `mint()` server-side for uniqueness

**Direct Generation:**
- Immediate unique handle with `mint()`
- Best for bulk account creation
- Reduce user choice paralysis

### 2. Handle Migration

**When users outgrow handles:**
- Allow handle changes with proper migration
- Maintain old handle redirects
- Update all associated content and URLs
- Notify connections of handle change

**Pattern evolution:**
```
Child account: happy-bunny → teen account: clever-bunny-67 → adult: clever-developer-42
```

### 3. Handle Retirement

**Inactive account handling:**
- Consider handle recycling policies
- Preserve handles for notable accounts
- Clear guidelines on handle availability

## Performance and Scale Considerations

### Bulk Generation Strategies

**For user imports:**
- Generate handles in batches using `mint()`
- Plan series capacity for expected growth
- Consider multiple series for different user types

**For testing environments:**
- Use `forge()` with consistent seeds
- Separate test patterns from production
- Easy cleanup and regeneration

### Capacity Planning

**Estimate your needs:**
```
Small community: 10K-100K users
Pattern: {adj:+pos<6}-{noun:+animal<7}-{num:2d}
Capacity: ~2.4M handles (sufficient)

Large platform: 1M+ users  
Pattern: {adj:+pos<7}-{noun:+animal<8}-{num:3d}
Capacity: ~708M handles (excellent)

Enterprise: 10M+ users
Pattern: {adj:+pos<8}-{noun:+animal<8}-{num:4d}
Capacity: ~7B+ handles (massive scale)
```

## Testing and Quality Assurance

### Pattern Testing Guidelines

**Test for diversity:**
- Generate 1000+ samples from your pattern
- Check for unwanted repetition or clustering
- Verify appropriate tone and brand alignment

**User acceptance testing:**
- Test handle selection flow with real users
- Measure selection vs. regeneration rates
- Gather feedback on handle appeal and memorability

**Technical validation:**
- Verify handles meet platform constraints
- Test database uniqueness constraints
- Validate URL safety and encoding

## Next Steps

**Ready to implement user handle systems?**

**Implementation Details**: [Web Development Guide](guide-web-development) for SDK integration
**Production Setup**: [Using Mint for Guaranteed Uniqueness](api-mint-endpoint)
**Advanced Patterns**: [Pattern Language Advanced Features](pattern-advanced-features)
**Real Examples**: [User Handle Examples](examples-gaming-usernames)

**Need platform-specific guidance?** Check [Troubleshooting Guide](troubleshooting-common-errors) or [get support](troubleshooting-support).

---

# Web Development Integration Guide
Source: https://dev.slugkit.dev/docs/guide-web-development

# Web Development Integration Guide

Learn how to integrate SlugKit into modern web applications with proper security models, pattern selection, and architecture decisions. This guide focuses on strategic choices and best practices for web development.

**Prerequisites:** [Core Concepts](developer-core-concepts) and [Choosing Generation Methods](choosing-generation-method)  
**Reading Time:** 20 minutes

## Security Models for Web Applications

SlugKit uses different authentication methods depending on where your code runs:

| Environment | Authentication | Security Model | Use Cases |
|-------------|----------------|----------------|-----------|
| **Browser** | SDK Config + JWK | Public, origin-restricted | UI previews, temporary IDs, demos |
| **Server** | API Keys | Private, secure | Production IDs, user handles, critical data |

**Critical Security Rule:** Never expose API keys to browser environments. Always use SDK configs for client-side code.

## Architecture Patterns

### Pattern 1: Preview Client, Generate Server (Recommended)

**Use Case:** User registration, content creation, any system requiring guaranteed uniqueness

**Client-Side (Browser):**
- Uses `slugkit-sdk` package with SDK config
- Generates preview options for user selection
- No critical ID generation

**Server-Side (Backend):**
- Uses `slugkit` package with API keys
- Generates final, guaranteed unique identifiers
- Handles database persistence

**Benefits:**
- Secure (no API key exposure)
- Good UX (user sees options)
- Guaranteed uniqueness

### Pattern 2: Pure Server Generation

**Use Case:** Bulk operations, background processing, system-generated IDs

**Implementation:**
- All generation happens server-side
- Users see final generated result
- No client-side generation

**Benefits:**
- Maximum security
- Simple architecture
- Optimal for bulk operations

### Pattern 3: Hybrid Architecture

**Use Case:** Complex applications with multiple ID types

**Strategy:**
- Client previews for user-facing IDs
- Server generation for critical IDs
- Clear separation of concerns

## Common Web Development Use Cases

### 1. URL Slugs and SEO

**Blog Post URLs:**
```
Pattern: {adjective:+obj}-{noun:+content}-guide
Examples: comprehensive-tutorial-guide, essential-documentation-guide
Strategy: Server-side generation with SEO optimization
```

**Product Pages:**
```
Pattern: {adjective:+pos}-{noun:+device}-{number:3d}
Examples: smart-laptop-247, secure-server-891
Strategy: Database-driven with URL redirects
```

**Category Slugs:**
```
Pattern: {noun:+object}-{adjective:+obj}
Examples: laptops-premium, servers-enterprise
Strategy: Content-driven patterns
```

### 2. User-Facing Identifiers

**User Handles:**
```
Pattern: user-{adjective:+pos}-{noun:+animal}-{number:2d}
Strategy: Preview client-side, mint server-side
Security: Use mint() for guaranteed uniqueness
```

**Session IDs:**
```
Pattern: session-{adjective:+obj}-{number:8x}
Strategy: Server-side generation only
Security: Short-lived, logged for debugging
```

**Temporary File Names:**
```
Pattern: temp-{adjective:+obj}-{noun:+object}-{number:6x}
Strategy: Server-side during upload processing
Security: Prevent file name conflicts
```

### 3. API and Component Naming

**RESTful Endpoints:**
```
Pattern: /api/{noun:+object}/{verb:+change}-{noun:+object}
Examples: /api/users/create-profile, /api/data/update-record
Strategy: Design-time generation, not runtime
```

**Component Names:**
```
Pattern: {Adjective}{Noun}Component
Examples: SmartDatabaseComponent, SecureAuthComponent
Strategy: Development-time generation
```

**CSS Class Names:**
```
Pattern: {adjective}-{noun}--{modifier}
Examples: smart-button--primary, secure-form--validated
Strategy: Build-time generation
```

## Framework-Specific Considerations

### Next.js Applications

**Client-Side Setup:**
- Use `slugkit-sdk` with SDK config in React components
- Configure allowed origins in SlugKit dashboard
- Store SDK config slug in `NEXT_PUBLIC_` environment variable

**Server-Side Setup:**
- Use `slugkit` with API keys in API routes
- Store API keys in server-only environment variables
- Handle generation in `/pages/api/` or `/app/api/` routes

**Recommended Architecture:**
- Client components: Preview generation with SDK config
- API routes: Production generation with API keys
- Static generation: Build-time slug creation for content

### React Applications

**State Management:**
- Store generated slugs in component state or global state
- Cache frequently used slug patterns
- Handle loading and error states appropriately

**Component Patterns:**
- Custom hooks for slug generation
- Higher-order components for slug-enabled forms
- Context providers for slug configuration

### Node.js Backends

**Express.js Integration:**
- Middleware for slug generation
- Route handlers with proper error handling
- Database integration patterns

**Database Considerations:**
- Store generated slugs with proper indexing
- Handle slug uniqueness constraints
- Plan for slug migration and updates

## Security Best Practices

### SDK Config Management

**Browser Security:**
- Create SDK configs with minimal required scopes
- Set strict origin restrictions (avoid wildcards)
- Use automatic key rotation for production
- Monitor SDK config usage and errors

**Configuration Example:**
```
SDK Config Settings:
- Scopes: forge (only what's needed)
- Origins: https://yourapp.com, https://staging.yourapp.com
- Key Rotation: Automatic (24 hours)
- Rate Limiting: Per-origin limits
```

### API Key Security

**Server Environment:**
- Store API keys in environment variables only
- Never commit API keys to version control
- Use different keys for different environments
- Rotate keys regularly and monitor usage

**Access Control:**
- Principle of least privilege for API key scopes
- Separate keys for different services/teams
- Audit API key usage regularly
- Implement proper logging and monitoring

### Environment Separation

**Development:**
```
- SDK Config: development-only origins
- API Keys: development tier with limited quotas
- Patterns: test-friendly patterns
```

**Staging:**
```
- SDK Config: staging-specific origins
- API Keys: staging tier with production-like limits
- Patterns: production patterns for testing
```

**Production:**
```
- SDK Config: production origins only
- API Keys: production tier with full quotas
- Patterns: optimized for scale and performance
```

## Performance Optimization

### Client-Side Performance

**Caching Strategies:**
- Cache generated slug previews for user sessions
- Implement debouncing for real-time preview generation
- Use browser storage for temporary slug storage

**Network Optimization:**
- Batch slug generation requests when possible
- Implement request retries with exponential backoff
- Handle offline scenarios gracefully

### Server-Side Performance

**Bulk Operations:**
- Use `mint()` for bulk user creation
- Generate slugs in batches for data imports
- Plan series capacity for expected growth

**Database Integration:**
- Index slug columns for fast lookups
- Use database constraints for uniqueness
- Implement slug-based routing efficiently

### Monitoring and Observability

**Key Metrics:**
- Slug generation latency and success rates
- API quota usage and approaching limits
- Error rates and common failure patterns
- User behavior in slug selection flows

**Alerting:**
- Monitor API quota approaching limits
- Alert on high error rates or latency spikes
- Track series capacity utilization
- Monitor security events (invalid origins, etc.)

## Testing Strategies

### Client-Side Testing

**Mock Strategy:**
- Mock SlugKit SDK for unit tests
- Use deterministic patterns for consistent testing
- Test error handling and retry logic

**Integration Testing:**
- Use test SDK configs with appropriate origins
- Verify slug generation flows end-to-end
- Test user interaction patterns

### Server-Side Testing

**API Testing:**
- Mock SlugKit client for unit tests
- Use test API keys for integration tests
- Verify database integration and constraints

**Load Testing:**
- Test bulk slug generation performance
- Verify rate limiting behavior
- Test error recovery scenarios

## Development Workflow

### Local Development

**Setup Recommendations:**
- Use development SDK configs for local testing
- Set up environment variables for different stages
- Use consistent slug patterns across team

**Testing Patterns:**
- Deterministic slugs for reproducible tests
- Separate test series from production series
- Easy reset and cleanup for development databases

### Deployment Considerations

**Environment Configuration:**
- Automate SDK config and API key setup
- Use infrastructure as code for consistency
- Implement proper secret management

**Migration Strategies:**
- Plan for slug pattern changes over time
- Handle existing slug migration carefully
- Maintain backward compatibility when possible

## Error Handling Patterns

### Client-Side Error Handling

**Common Scenarios:**
- Network connectivity issues
- SDK config permission errors
- Rate limiting and quota exceeded
- Invalid pattern or constraint errors

**Best Practices:**
- Implement graceful degradation
- Provide meaningful error messages to users
- Retry with exponential backoff
- Log errors for debugging

### Server-Side Error Handling

**Error Categories:**
- API authentication failures
- Quota exceeded errors
- Series capacity exhaustion
- Network and timeout errors

**Recovery Strategies:**
- Implement circuit breaker patterns
- Use fallback slug generation methods
- Queue slug generation for retry
- Alert on persistent failures

## Scalability Planning

### Growth Considerations

**User Base Growth:**
- Plan series capacity for 2-3x expected users
- Monitor series utilization rates
- Have migration plans for capacity expansion

**Traffic Scaling:**
- Design for peak load scenarios
- Implement proper caching strategies
- Use CDN for static slug-related assets

### Architecture Evolution

**Microservices:**
- Separate slug generation into dedicated services
- Use proper service-to-service authentication
- Implement distributed caching strategies

**Global Distribution:**
- Consider regional SlugKit deployment options
- Plan for cross-region slug consistency
- Handle network latency appropriately

## Next Steps

**Ready to implement?** Choose your integration approach:

**SDK Integration**: [Python SDK Guide](sdk-python-quickstart) or [TypeScript SDK Guide](sdk-typescript-quickstart)
**API Direct**: [REST API Examples](rest-api-curl-examples)
**User Systems**: [User Handles Guide](guide-user-handles)
**Production Setup**: [Using Mint for Guaranteed Uniqueness](api-mint-endpoint)

**Need help with specific frameworks?** Check [Troubleshooting Guide](troubleshooting-common-errors) or [get support](troubleshooting-support).

---

# Generate slugs with forge
Source: https://dev.slugkit.dev/docs/integration-examples

## Choose Your Stack

SlugKit integrates seamlessly with your existing workflow. Pick your preferred language and toolchain to get started immediately.

### REST API

Perfect for any language or platform that can make HTTP requests.

```bash
# Generate slugs with forge
curl -X POST https://api.slugkit.dev/v1/forge \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective}-{noun}-{number:3d}",
    "count": 10,
    "seed": "production"
  }'

# Mint from a series
curl -X POST https://api.slugkit.dev/v1/mint \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "series_slug": "user-handles",
    "count": 5
  }'
```

[**API Reference →**](/articles/api-reference)

---

### Python SDK

Native Python integration with full type support and async capabilities.

```python
from slugkit import SlugKit

# Initialize client
client = SlugKit(api_key="YOUR_API_KEY")

# Generate custom slugs
slugs = client.forge(
    pattern="{adjective:+pos}-{noun:<8}",
    count=10,
    seed="campaign-2024"
)

# Mint from series
user_handles = client.mint(
    series_slug="user-handles",
    count=5
)

# Async support
import asyncio
async def generate_async():
    async_client = SlugKit(api_key="YOUR_API_KEY", async_mode=True)
    return await async_client.forge("{verb}-{noun}", count=100)
```

[**Python SDK Documentation →**](https://github.com/slugkit/slugkit-py-sdk) | [**Install via pip →**](https://pypi.org/project/slugkit/)

---

### TypeScript SDK

Full TypeScript support with modern ESM and CommonJS compatibility.

```typescript
import { SlugKit } from '@slugkit/sdk';

// Initialize client
const client = new SlugKit('YOUR_API_KEY');

// Generate with full type safety
const slugs = await client.forge({
  pattern: '{adjective}-{noun}-{number:4x}',
  count: 20,
  seed: 'development'
});

// Mint from series
const handles = await client.mint({
  seriesSlug: 'user-handles',
  count: 10
});

// Slice for preview
const preview = await client.slice({
  seriesSlug: 'api-tokens',
  count: 5,
  sequence: 1000
});

// Error handling
try {
  const result = await client.forge({ pattern: '{invalid}' });
} catch (error) {
  console.error('Pattern validation failed:', error.message);
}
```

[**TypeScript SDK Documentation →**](https://github.com/slugkit/slugkit-ts-sdk) | [**Install via npm →**](https://www.npmjs.com/package/@slugkit/sdk)

---

### MCP Server

Use SlugKit directly in Claude and other MCP-compatible AI assistants.

```json
{
  "mcpServers": {
    "slugkit": {
      "command": "npx",
      "args": ["@slugkit/mcp-server"],
      "env": {
        "SLUGKIT_API_KEY": "YOUR_API_KEY"
      }
    }
  }
}
```

**Example Claude conversation:**
```
You: Generate 5 user handles with positive adjectives
Claude: I'll generate some positive user handles for you using SlugKit.

[Uses MCP to call SlugKit forge with pattern {adjective:+pos}-{noun}]

Here are 5 positive user handles:
- cheerful-butterfly
- brilliant-sunrise  
- optimistic-garden
- radiant-mountain
- joyful-ocean
```

[**MCP Server Setup →**](/articles/mcp-setup) | [**Claude Integration Guide →**](/articles/claude-integration)

---

### More Integrations

**CLI Tool** - Generate slugs directly from your terminal
```bash
npm install -g @slugkit/cli
slugkit forge "{adjective}-{noun}" --count=10 --api-key=YOUR_KEY
```

**GitHub Actions** - Generate slugs in your CI/CD pipeline
```yaml
- uses: slugkit/github-action@v1
  with:
    api-key: ${{ secrets.SLUGKIT_API_KEY }}
    pattern: '{adjective}-{noun}-{number:3d}'
```

[**All Integrations →**](/articles/integrations)


---

# 🎉 TypeScript SDK is Live!
Source: https://dev.slugkit.dev/docs/jocund-clay-mmx

Remember when I mentioned the TypeScript SDK was "almost production-ready... for an API version that only exists on my laptop"? Well, it finally escaped the laptop and made it to npm!

**What's in the box:**

* Full TypeScript support with comprehensive type definitions
* Pattern parsing and validation using the complete EBNF grammar
* Dictionary management and statistics
* Pattern shortening/expansion for shareable configs
* Built-in caching and error handling
* Autocompletion helpers for building pattern editors

**Get started:**
```
npm install @slugkit/sdk
```

**Quick example:**
```typescript
import { SlugKit } from '@slugkit/sdk';

const slugkit = await SlugKit.fromBackend(
  'https://api.slugkit.dev',
  'your-api-key'
);

const slugs = await slugkit.forgeSlugs(
  '{adjective}-{noun}-{number:4x}', 
  5
);
// → ['cheerful-penguin-42a7', 'curious-robot-91f3', ...]
```

**The good stuff:**

* Parse patterns like `{adjective@en:+formal-nsfw<8}` with full validation
* Get dictionary stats and available tags  
* Pattern autocompletion for building editors
* Sub-millisecond slug generation (thanks to those recent optimizations)
* Comprehensive error handling

From weekend slug fix → monolith → microservices → open source engine → TypeScript SDK. The evolution continues!

Next up: proper documentation website and maybe some React components for pattern builders.

🔗 **GitHub:** https://github.com/slugkit/slugkit-ts-sdk

📦 **npm:** @slugkit/sdk

#typescript #sdk #npm #developer #api

---

# From 300µs to Sub-Microsecond: Building SlugKit While Falling Down the Performance Rabbit Hole
Source: https://dev.slugkit.dev/docs/laughing-fetishism-cxx

## It Started With Someone Else's Terrible Code

There I was, innocently profiling our account management system, trying to figure out why creating a new organization took forever. What I found made me simultaneously frustrated and fascinated.

The code was generating organization slugs. Simple enough, right? Except it was doing something spectacularly inefficient: it would fetch *every single organization from the database*, count them in memory, and then generate a slug like `personal-organization-47`. For the 47th organization. By fetching all 46 previous ones. And filtering by a regex.

Not only was this painfully slow, but it was also racing against itself. Two simultaneous requests? Congratulations, you might get duplicate slugs.

## The "Good Enough" Fix

I needed something fast, so I threw together a Python-based dictionary generator. Pick a random adjective, pick a random noun, smash them together with a number. `brave-falcon-23`. `clever-symphony-891`. Simple, memorable, and most importantly—it didn't fetch the entire database.

For uniqueness, I used the naïve approach: try to insert into the database, regenerate on conflict. With a capacity of roughly 10 million possible combinations and far fewer expected users, the collision probability was acceptably low.

It worked. It was fast enough. I moved on to other things.

## Then I Got Curious

A few weeks later, I started thinking: what if I could make this *actually good*? What if the slug generation could be:
- **Deterministic** - same seed and sequence always produces the same result
- **Unique** - guaranteed no collisions within a series
- **Fast** - because why not?
- **Configurable** - let users define their own patterns

I wanted a pattern language. Something like `{adjective}-{noun}-{number:2x}` that would generate `brave-falcon-7a` or `clever-symphony-3f`. And I wanted it to be *fun*.

Let me show you what I mean by fun. Here are some real patterns SlugKit can generate:

**(Almost) fake shell commands:**
```
djpeg bathe --neurogenic
sha224sum endeavor --statistical
```

**Royalty titles:**
```
Conjectural Palooka XII the Numskull
Supersonic Maturation CI the Fraud
```

**Case mutations just because I can:**
```
uNFLUctUAtiNg-AbioTRopHy-55
sUBLiMe-ABsolUtioN-00
```

I won't post here the slugs that are results of `+nsfw` tag, but id does swear like a drunk pirate.

This is when SlugKit stopped being a quick fix and became a project.

## The Performance Journey: Python → PostgreSQL → C++

### Python: The Prototype

My first real experiments were in Python. I built a simple pattern parser, added dictionary filtering, implemented Fisher-Yates shuffling for uniqueness. It *worked*.

Then I loaded a 40,000-word noun dictionary.

The shuffling became noticeably slow. Not catastrophically slow, but slow enough to bother me. And caching the shuffled results meant storing massive arrays in memory.

### PostgreSQL: The "Database Will Save Me" Phase

"Maybe the database can do this faster?" I thought, with the optimism of someone about to learn a lesson.

I moved the permutation logic into PostgreSQL functions. PL/pgSQL handling the pseudo-random generation, indices speeding up lookups.

It was... marginally better? But still not *fast*. And now I had complicated database functions to maintain.

### C++: The "Fine, I'll Do It Properly" Decision

I was frustrated. I wanted performance. And honestly? I *missed* writing C++.

So I rewrote the entire thing in C++ using the userver framework. No more database functions. No more Python dictionaries. Just pure, compiled, optimized code handling slug generation.

This is when things got interesting.

## The Algorithm Evolution

### Fisher-Yates: Simple But Slow

The Fisher-Yates shuffle is elegant: shuffle the entire dictionary once, then iterate through it for guaranteed uniqueness. Perfect for small dictionaries.

Terrible for large ones. With a 40K-word dictionary, the initial shuffle was expensive, and caching the results consumed significant memory. I needed something better.

### Feistel Networks: Beautiful But Limited

Feistel networks are cryptographically sound permutation algorithms. They work by applying multiple rounds of transformations, producing pseudo-random but deterministic mappings. Perfect for my needs!

Except for one problem: they work beautifully with powers of 2 (256, 1024, 65536), but most dictionaries aren't power-of-2 sized. I had 41,872 nouns. The classic Feistel approach didn't directly apply.

I experimented with cycle walking (keep generating until you hit a valid value), but the variable-time nature bothered me.

### Linear Congruential Generators: The Pragmatic Choice

For non-power-of-2 dictionary sizes, I ended up using Linear Congruential Generators (LCGs). They're simple, fast, and produce good-enough permutations for my use case:

```
output = (multiplier * sequence + increment) % dictionary_size
```

The key insight: derive the multiplier and increment from the seed using a hash function. Same seed always produces the same sequence. Different seeds produce different sequences. Constant time. Constant space.

For power-of-2 dictionaries, I kept Feistel networks — they're faster and cryptographically stronger.

### The Sequential Slug Problem

There was another challenge I hadn't anticipated: capacity calculation and slug quality.

The naïve approach would be to treat each placeholder like a digit in a number system. With pattern `{adjective}-{noun}-{number:2x}`, you'd cycle through all adjectives first (keeping noun and number constant), then increment noun, cycle through adjectives again, and so on.

This maximizes capacity (multiply all placeholder sizes together), but it creates a terrible user experience. You'd generate thousands of sequential slugs that differ by only one word:

```
happy-falcon-7a
sad-falcon-7a
brave-falcon-7a
clever-falcon-7a
...
(17,000 more adjectives later)
happy-penguin-7a
```

Not fun. Not random-looking. Just boring.

**The solution:** Advance all placeholders simultaneously. Each new slug changes *every* component. The sequence feels unpredictable and interesting.

**The catch:** Capacity drops from multiplication to LCM (Least Common Multiple) of all placeholder capacities. With 17K adjectives, 41K nouns, and 256 hex numbers, you'd lose significant capacity.

**The fix:** Between pattern parsing and generation, the generator selectively adjusts dictionary sizes to the nearest prime number less than their actual size—but only when this adjustment actually improves the overall LCM. Primes have no common factors, so this optimization recovers much of the lost capacity while keeping the sequence fun and unpredictable.

It's a small optimization that makes a huge difference in the quality of generated slugs. Performance matters, but so does the experience of using them.

## The Breakthrough: Caching

The real performance win came from an embarrassingly simple optimization: dictionary caching.

Every time someone requested `{adjective:+pos}` or `{noun:==5}` (5-letter nouns), I was filtering the dictionary from scratch. Even with optimized indexing, this was expensive.

So I added a cache. Filter once, store the result, reuse it forever.

The results were dramatic:

**Dictionary Filtering:**
- Before: 200µs average
- After: **68-79ns**
- **Improvement: 99.96%**

**Full Slug Generation:**
- Simple pattern (`{verb}-{adverb}`): 73µs → **903ns**
- Complex pattern (9 components): 916µs → **3.9µs**

Suddenly, slug generation wasn't just "fast enough." It was *fast*.

## Current Performance

Today, SlugKit generates slugs in **0.5-5µs** depending on pattern complexity. That's **200,000+ slugs per second *per core***. With C++ at my disposal, I can scale across all available cores — though currently it's limited to 10% CPU in the development environment, CPU limits don't come cheap (production can burn through all the cycles it needs).

The individual operations are even faster:
- **FNV1a hashing:** 0.7-11ns depending on string length
- **Feistel permutation:** 3.5ns (constant time regardless of dictionary size!)
- **Dictionary lookup:** 191-344ns (barely scales with dictionary size)
- **Hex number generation:** 22-26ns

For the curious, detailed benchmarks are available [here](https://dev.slugkit.dev/articles/smitten-mileage-mdx).

## The DSL Evolution

While optimizing performance, the pattern language kept growing. What started as `{adjective}-{noun}` evolved into:

**Number formats:**
- Decimal: `{number:8d}` → `00042891`
- Hex: `{number:4x}` → `7a3f`
- Roman: `{number:3R}` → `XLII` (because why not?)

**Case transformations:**
- Title: `{Adjective}` → `Brave`
- Upper: `{NOUN}` → `FALCON`
- Mixed: `{AdJeCtIvE}` → `BrAvE` (using Feistel-based deterministic randomization)

**Semantic filtering:**
- `{adjective:+pos}` - only positive adjectives
- `{noun:==7}` - only 7-letter nouns
- `{verb:+emo}` - emotional verbs

*(Funny story: Every AI agent that tries SlugKit immediately wants `{noun:+tech}`. The tag doesn't exist yet, but given the consistent demand, re-tagging dictionaries with technical terminology just jumped up my priority list.)*

**Special sequences:**
- `{special:4-8}` - random special characters
- `{emoji:+face}` - emoji with face-related semantics

The latest addition is emoji support with semantic tagging. You can generate `{emoji:+happy}` or `{emoji:+animal}` and get contextually appropriate emoji in your slugs.

## From Generator to SaaS

At some point, I realized: this is actually useful. Not just for me, but for anyone who's ever stared at a UUID and thought "there has to be a better way."

So SlugKit became a service. Multi-tenant infrastructure, API with streaming support, Python and TypeScript SDKs, comprehensive documentation. The full treatment.

The infrastructure and frontend development is a whole other story (involving 5 C++ microservices, monitoring, and my ongoing battle with making frontend behave). But the core generator—the part I'm genuinely proud of—can pump out hundreds of thousands of unique, memorable, human-readable identifiers per second.

## What I Learned

**Performance optimization is addictive.** It started as "this should be faster" and became "how fast can I *actually* make this?"

**Simple optimizations have massive impact.** The dictionary cache was maybe 50 lines of code. It improved performance by 99.96%.

**Fun matters.** I spent time implementing Roman numerals and emoji support because they made me laugh. Turns out, they can make users happy too.

**The right language matters.** Python was perfect for prototyping. PostgreSQL seemed clever but wasn't. C++ was the right choice for the performance I wanted — even if it meant more development complexity.

**Deterministic chaos is beautiful.** There's something elegant about generating seemingly random results that are actually perfectly predictable and reproducible.

## Check It Out

SlugKit is live at [dev.slugkit.dev](https://dev.slugkit.dev). Free beta with generous limits (10,000 operations/day), and the generator engine is open source at [github.com/slugkit/slugkit-generator](https://github.com/slugkit/slugkit-generator).

Want to try it without signing up? The [browser-based playground](https://dev.slugkit.dev/playground) lets you experiment with pattern syntax and see results instantly. It's the fastest way to understand what SlugKit can do.

Whether you need memorable URLs, user handles, order IDs, or just want to generate ridiculous fantasy names, give it a try. And if you find bugs or have feedback, you might just earn one of the 50 unlimited Friends & Family plans I'm giving to early contributors.

Because ultimately, SlugKit exists because someone wrote `personal-organization-N` and made me frustrated enough to fall down a rabbit hole. Sometimes the best projects start with someone else's terrible code.

---

# SlugKit On-Premise Core
Source: https://dev.slugkit.dev/docs/on-premise-core

> **Expected Q1 2026** — Our team is working hard to deliver a robust, production-ready self-hosted solution. We appreciate your patience as we ensure everything meets our quality standards.

# SlugKit On-Premise Core

Production-ready containerised slug generation with PostgreSQL backend, automatic migrations, and multi-container support. Requires external PostgreSQL database setup for scalable on-premises deployment with advanced capabilities.

## What's Included

### **Production Container Architecture**
- **Docker image distribution** - `ghcr.io/slugkit/slugkit-core:latest`
- **External PostgreSQL v15+ required** - you provide and manage the database server (v16+ recommended)
- **Automatic migrations** - container handles database schema and dictionary loading
- **Multi-container deployment** - horizontal scaling across multiple container instances

### **Advanced Generation Capabilities**
- **All core functions** - forge, mint, and slice with full streaming support
- **Unlimited pattern complexity** - no restrictions on pattern sophistication
- **Advanced case transformations** - mathematical mixed-case patterns
- **Distributed coordination** - series management across multiple containers via PostgreSQL

### **Enterprise Container Features**
- **Role-based access control** - fine-grained permissions and user management
- **API key management** - scope-based access with organisational controls
- **Comprehensive monitoring** - Prometheus metrics and structured logging
- **Health checks** - container-native health monitoring and readiness probes

### **Database-Backed Scalability**
- **Multi-container scaling** - number of concurrent containers based on your subscription plan
- **High-throughput generation** - millions of slugs per day capability
- **Persistent series management** - mint counters and slice windows maintained in PostgreSQL
- **ACID compliance** - guaranteed consistency across distributed container instances

## Prerequisites

### **PostgreSQL Database Required**
You must provide and manage a PostgreSQL server:
- **Database server** - PostgreSQL v15+ (v16+ recommended for optimal performance)
- **Database creation** - create dedicated database for SlugKit
- **User permissions** - database user with standard database privileges
- **Network connectivity** - container must reach PostgreSQL server

### **Database Setup Example**
```sql
-- Create database and user for SlugKit
CREATE DATABASE slugkit_production;
CREATE USER slugkit_user WITH PASSWORD 'secure_password_here';
GRANT ALL PRIVILEGES ON DATABASE slugkit_production TO slugkit_user;

-- SlugKit handles its own schema management - no additional grants needed
```

### **SSL Configuration**
```sql
-- Enable SSL on PostgreSQL (recommended for production)
-- In postgresql.conf:
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'

-- In pg_hba.conf:
hostssl slugkit_production slugkit_user 0.0.0.0/0 md5
```

## Container Specifications

### **Required Configuration**
```bash
# Essential deployment - license file and database URL required
docker run -d -p 8080:8080 \
  -v /path/to/license.yaml:/usr/local/etc/slugkit/license.yaml:ro \
  -e DATABASE_URL="postgresql://slugkit_user:secure_password@postgres.example.com:5432/slugkit_production?sslmode=required" \
  ghcr.io/slugkit/slugkit-core:latest
```

### **Docker Compose Production Setup**
```yaml
version: '3.8'
services:
  # External PostgreSQL - you manage this
  # This example shows a containerised PostgreSQL for development
  postgres:
    image: postgres:16
    environment:
      POSTGRES_DB: slugkit_production
      POSTGRES_USER: slugkit_user
      POSTGRES_PASSWORD: secure_password_here
      POSTGRES_INITDB_ARGS: "--encoding=UTF8 --lc-collate=en_US.UTF-8 --lc-ctype=en_US.UTF-8"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./postgresql.conf:/etc/postgresql/postgresql.conf
    ports:
      - "5432:5432"
    command: postgres -c config_file=/etc/postgresql/postgresql.conf

  slugkit-core-1:
    image: ghcr.io/slugkit/slugkit-core:latest
    ports:
      - "8080:8080"
    volumes:
      - ./license.yaml:/usr/local/etc/slugkit/license.yaml:ro
    environment:
      - DATABASE_URL=postgresql://slugkit_user:secure_password_here@postgres:5432/slugkit_production?sslmode=disable
      - SLUGKIT_NODE_ID=core-node-1
    depends_on:
      - postgres
    restart: unless-stopped

  slugkit-core-2:
    image: ghcr.io/slugkit/slugkit-core:latest
    ports:
      - "8081:8080"
    volumes:
      - ./license.yaml:/usr/local/etc/slugkit/license.yaml:ro
    environment:
      - DATABASE_URL=postgresql://slugkit_user:secure_password_here@postgres:5432/slugkit_production?sslmode=disable
      - SLUGKIT_NODE_ID=core-node-2
    depends_on:
      - postgres
    restart: unless-stopped

volumes:
  postgres_data:
```

### **Kubernetes Production Deployment**
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: slugkit-core
spec:
  replicas: 3
  selector:
    matchLabels:
      app: slugkit-core
  template:
    metadata:
      labels:
        app: slugkit-core
    spec:
      containers:
      - name: slugkit-core
        image: ghcr.io/slugkit/slugkit-core:latest
        ports:
        - containerPort: 8080
        - containerPort: 9090  # Metrics
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: slugkit-database
              key: connection-string
        - name: SLUGKIT_NODE_ID
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        volumeMounts:
        - name: license
          mountPath: /usr/local/etc/slugkit/license.yaml
          subPath: license.yaml
          readOnly: true
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 10
          periodSeconds: 5
        resources:
          requests:
            cpu: 2
            memory: 4Gi
          limits:
            cpu: 4
            memory: 8Gi
      volumes:
      - name: license
        secret:
          secretName: slugkit-license
---
apiVersion: v1
kind: Secret
metadata:
  name: slugkit-database
type: Opaque
stringData:
  connection-string: "postgresql://slugkit_user:secure_password@postgres.production.svc.cluster.local:5432/slugkit_production?sslmode=required"
```

## Database Management

### **Automatic Migration & Setup**
The SlugKit Core container automatically handles:
- **Schema migrations** - creates and updates database tables in its own schema
- **Dictionary loading** - loads all pattern dictionaries into PostgreSQL
- **Index creation** - optimizes database for slug generation workloads
- **Version management** - tracks schema versions for safe upgrades

### **First-Time Setup Process**
```bash
# Container startup sequence:
# 1. Connects to PostgreSQL using DATABASE_URL
# 2. Checks for existing SlugKit schema
# 3. Runs migrations if needed (first-time or upgrades)
# 4. Loads dictionaries into database (if not present)
# 5. Starts API server once database is ready

# Monitor the setup process
docker logs -f slugkit-core-container
```

### **Database URL Formats**
```bash
# Production with SSL (recommended)
DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=required"

# Development without SSL
DATABASE_URL="postgresql://user:password@localhost:5432/slugkit_dev?sslmode=disable"

# With connection pool settings
DATABASE_URL="postgresql://user:password@host:5432/database?sslmode=required&max_conns=20&max_idle_conns=5"

# AWS RDS example
DATABASE_URL="postgresql://slugkit:password@slugkit-prod.abc123.us-east-1.rds.amazonaws.com:5432/slugkit?sslmode=required"

# Google Cloud SQL example
DATABASE_URL="postgresql://slugkit:password@10.1.2.3:5432/slugkit?sslmode=required"
```

## High Availability & Clustering

### **PostgreSQL High Availability**
SlugKit automatically handles PostgreSQL cluster topology discovery. Simply provide a comma-separated list of database URLs and SlugKit will determine the cluster configuration:

```bash
# Multiple PostgreSQL nodes - SlugKit discovers topology automatically
DATABASE_URL="postgresql://user:pass@pg1.internal:5432/slugkit?sslmode=required,postgresql://user:pass@pg2.internal:5432/slugkit?sslmode=required,postgresql://user:pass@pg3.internal:5432/slugkit?sslmode=required"
```

### **Cluster Configuration Examples**
```yaml
# Master-replica setup
database_urls:
  primary_and_replicas: |
    postgresql://slugkit:pass@postgres-primary.internal:5432/slugkit?sslmode=required,
    postgresql://slugkit:pass@postgres-replica-1.internal:5432/slugkit?sslmode=required,
    postgresql://slugkit:pass@postgres-replica-2.internal:5432/slugkit?sslmode=required

# Multi-master cluster (if supported by your PostgreSQL setup)
database_urls:
  multi_master: |
    postgresql://slugkit:pass@postgres-node-1.internal:5432/slugkit?sslmode=required,
    postgresql://slugkit:pass@postgres-node-2.internal:5432/slugkit?sslmode=required,
    postgresql://slugkit:pass@postgres-node-3.internal:5432/slugkit?sslmode=required
```

### **Docker Compose with HA PostgreSQL**
```yaml
version: '3.8'
services:
  slugkit-core:
    image: ghcr.io/slugkit/slugkit-core:latest
    ports:
      - "8080:8080"
    volumes:
      - ./license.yaml:/usr/local/etc/slugkit/license.yaml:ro
    environment:
      # Comma-separated list of PostgreSQL URLs
      - DATABASE_URL=postgresql://slugkit:pass@postgres-primary:5432/slugkit,postgresql://slugkit:pass@postgres-replica:5432/slugkit
    restart: unless-stopped
```

### **Kubernetes with HA Database**
```yaml
apiVersion: v1
kind: Secret
metadata:
  name: slugkit-database-ha
type: Opaque
stringData:
  connection-string: |
    postgresql://slugkit:password@postgres-primary.db.svc.cluster.local:5432/slugkit?sslmode=required,
    postgresql://slugkit:password@postgres-replica-1.db.svc.cluster.local:5432/slugkit?sslmode=required,
    postgresql://slugkit:password@postgres-replica-2.db.svc.cluster.local:5432/slugkit?sslmode=required
```

## Production Database Configurations

### **PostgreSQL Version Requirements**
- **Minimum**: PostgreSQL v15.0 - fully supported with all features
- **Recommended**: PostgreSQL v16+ - optimal performance and latest features
- **Managed services**: Most cloud providers offer v15+ with v16+ recommended

### **Managed Database Services**
```yaml
# AWS RDS PostgreSQL
aws_rds:
  engine: postgres
  version: "16.1"
  instance_class: db.r6g.xlarge
  allocated_storage: 500
  max_allocated_storage: 1000
  backup_retention_period: 7
  deletion_protection: true
  encryption_at_rest: true
  multi_az: true

# Google Cloud SQL
gcp_sql:
  database_version: POSTGRES_16
  tier: db-standard-4
  disk_size: 500
  disk_type: PD_SSD
  backup_enabled: true
  high_availability: true
  ssl_mode: REQUIRE

# Azure Database for PostgreSQL
azure_postgresql:
  sku_name: GP_Standard_D4s_v3
  version: "16"
  storage_mb: 512000
  backup_retention_days: 7
  geo_redundant_backup: Enabled
  ssl_enforcement: Enabled
```

### **Self-Hosted PostgreSQL Configuration**
```ini
# postgresql.conf optimizations for SlugKit
# Memory settings
shared_buffers = 2GB
effective_cache_size = 6GB
work_mem = 64MB
maintenance_work_mem = 512MB

# Connection settings
max_connections = 200
superuser_reserved_connections = 3

# WAL and checkpoint settings
wal_buffers = 64MB
checkpoint_completion_target = 0.9
checkpoint_timeout = 15min

# Query planner
random_page_cost = 1.1  # For SSD storage
effective_io_concurrency = 200

# Logging (for production monitoring)
log_statement = 'mod'
log_min_duration_statement = 1000
log_checkpoints = on
log_connections = on
log_disconnections = on
```

## Container Scaling & Performance

### **Horizontal Scaling**
The number of concurrent SlugKit Core containers depends on your subscription plan:
- **Subscription-based scaling** - container count determined by your plan tier
- **Automatic coordination** - containers coordinate via PostgreSQL without manual configuration
- **Load balancing** - distribute requests across multiple container instances
- **Shared state** - mint counters and series management synchronized via database

### **Performance Characteristics**
```yaml
# Per-container performance
single_container:
  cpu: 2_vcpu_recommended
  memory: 4GB_recommended
  throughput: ~100k_slugs_per_minute
  
# Multi-container scaling
multiple_containers:
  throughput: linear_scaling_per_container
  coordination: automatic_via_postgresql
  state_sharing: seamless_mint_counter_synchronization
```

### **Database Performance & Monitoring**
```sql
-- Monitor SlugKit database performance
SELECT 
  schemaname,
  tablename,
  n_tup_ins,
  n_tup_upd,
  n_tup_del,
  n_live_tup,
  n_dead_tup
FROM pg_stat_user_tables 
WHERE schemaname LIKE 'slugkit%';

-- Monitor active connections
SELECT count(*) as active_connections 
FROM pg_stat_activity 
WHERE state = 'active';

-- Check database size
SELECT 
  pg_database.datname,
  pg_size_pretty(pg_database_size(pg_database.datname)) AS size
FROM pg_database 
WHERE datname = 'slugkit_production';
```

## Getting Started

### **Quick Setup Process**
1. **Setup PostgreSQL** - create database and user with standard privileges
2. **Configure DATABASE_URL** - format connection string with SSL settings (or comma-separated list for HA)
3. **Obtain license file** - download from SlugKit dashboard
4. **Deploy container** - with license file mount and DATABASE_URL environment variable
5. **Monitor startup** - container will handle migrations and dictionary loading

### **Step-by-Step Database Setup**
```bash
# 1. Create PostgreSQL database and user
psql -h your-postgres-server -U postgres << EOF
CREATE DATABASE slugkit_production;
CREATE USER slugkit_user WITH PASSWORD 'your-secure-password';
GRANT ALL PRIVILEGES ON DATABASE slugkit_production TO slugkit_user;
EOF

# 2. Test database connection
psql "postgresql://slugkit_user:your-secure-password@your-postgres-server:5432/slugkit_production?sslmode=required"

# 3. Deploy SlugKit Core container
docker run -d -p 8080:8080 \
  -v $(pwd)/license.yaml:/usr/local/etc/slugkit/license.yaml:ro \
  -e DATABASE_URL="postgresql://slugkit_user:your-secure-password@your-postgres-server:5432/slugkit_production?sslmode=required" \
  --name slugkit-core \
  ghcr.io/slugkit/slugkit-core:latest

# 4. Monitor container startup and database setup
docker logs -f slugkit-core
```

### **Verification & Testing**
```bash
# Wait for container to complete database setup (check logs)
docker logs slugkit-core | grep "Database ready"

# Test API functionality
curl -X POST http://localhost:8080/api/mint \
  -H "Content-Type: application/json" \
  -d '{"series": "test-series", "count": 5}'

# Expected response: ["unique-slug-1", "unique-slug-2", ...]
```

## Container Upgrade Path

### **When to Consider Enterprise**
- **Air-gapped database deployment** - complete network isolation with custom database setup
- **Unlimited container scaling** - scale beyond subscription plan limits
- **Custom database architectures** - specialized database configurations and optimizations
- **Dedicated database support** - white-glove database deployment and management assistance

### **Database Migration Support**
- **Schema versioning** - automatic migrations handle version upgrades
- **Data preservation** - all existing series and generated slugs preserved
- **Backup strategies** - comprehensive database backup and recovery procedures
- **Professional services** - assistance with complex database migrations

---

**Ready for production-scale database-backed slug generation?** Deploy SlugKit On-Premise Core from `ghcr.io/slugkit/slugkit-core` with your PostgreSQL v15+ database for enterprise features, multi-container scaling, and persistent series management.


---

# SlugKit On-Premise Enterprise
Source: https://dev.slugkit.dev/docs/on-premise-enterprise

> **Expected Q1 2026** — Our team is working hard to deliver a robust, production-ready self-hosted solution. We appreciate your patience as we ensure everything meets our quality standards.

# SlugKit On-Premise Enterprise

Custom-tailored self-hosted slug generation solutions for unique requirements. Whether you need air-gapped deployment, unlimited scale, or specialized features, Enterprise delivers bespoke solutions designed specifically for your needs.

## What's Included

### **Completely Customizable Solution**
- **Unlimited everything** - nodes, generation, complexity, series (all negotiable)
- **Bespoke feature development** - functionality built specifically for your requirements
- **Custom container architectures** - tailored Docker deployments from private or public registries
- **Flexible deployment models** - air-gapped, hybrid, multi-region, or specialized configurations

### **Air-Gap & Isolated Deployment Excellence**
- **Complete network isolation** - operates without any external connectivity
- **Offline licensing management** - hardware tokens, certificates, or custom validation
- **Private container registries** - deploy from your internal registry (`your-registry.com/slugkit-enterprise`)
- **Classified environment ready** - suitable for government, defense, and high-security applications

### **Advanced Container Solutions**
- **Custom container images** - tailored builds with your specific requirements
- **Private registry distribution** - `ghcr.io/slugkit/slugkit-enterprise` or your internal registry
- **Kubernetes operators** - custom controllers for advanced orchestration
- **Multi-architecture support** - AMD64, ARM64, or specialized hardware platforms

### **White-Glove Service Experience**
- **Dedicated solution architects** - design custom deployments for your environment
- **Feature request process** - submit requirements for bespoke development
- **On-site deployment** - security-cleared engineers for sensitive environments
- **Ongoing customization** - evolving solutions as your needs change

## Perfect For

### **Unique Requirements Beyond Standard Plans**
- **Specialized compliance** - custom regulatory frameworks (FISMA, FedRAMP, industry-specific)
- **Unusual deployment environments** - edge computing, IoT, embedded systems
- **Custom integration needs** - bespoke APIs, protocols, or data formats
- **Specialized security requirements** - beyond standard air-gap needs

### **Traditional Enterprise Use Cases**
- **Fortune 500 corporations** - unlimited scale with custom features
- **Government and defense** - classified deployment with security clearance
- **Financial services** - microsecond latency with custom compliance
- **Global enterprises** - multi-region coordination with local regulations

### **Non-Traditional Enterprise Users**
- **Research institutions** - specialized academic or scientific requirements
- **Technology companies** - embedding SlugKit into products or platforms
- **Startups with unique needs** - custom solutions that don't fit standard tiers
- **Creative agencies** - specialized branding or identifier requirements

## Custom Solutions & Feature Requests

### **Getting Started Process**
1. **Submit feature request form** - describe your unique requirements and constraints
2. **Solution design consultation** - work with architects to design custom solution
3. **Proposal and pricing** - receive tailored solution with transparent pricing
4. **Development and deployment** - bespoke implementation with ongoing support

### **Example Custom Solutions**

#### **Specialized Air-Gap Deployment**
```yaml
# Custom air-gapped architecture
deployment:
  registry: customer-internal.registry.com/slugkit
  licensing: offline_hardware_tokens
  networking: complete_isolation
  updates: secure_courier_delivery
  
custom_features:
  - specialized_compliance_logging
  - custom_dictionary_integration
  - hardware_security_module_support
  - multi_classification_levels
```

#### **Embedded IoT Solution**
```yaml
# Custom embedded deployment
target_platform: arm64_embedded
container_size: minimal_footprint
custom_features:
  - offline_only_operation
  - battery_optimized_performance
  - custom_hardware_integration
  - specialized_pattern_languages
```

#### **Academic Research Platform**
```yaml
# Research institution requirements
custom_features:
  - unlimited_experimentation_modes
  - custom_statistical_analysis
  - research_data_export_formats
  - academic_license_integration
deployment:
  multi_campus: global_coordination
  compliance: academic_data_governance
```

### **Feature Request Categories**
- **Custom compliance frameworks** - industry-specific regulatory requirements
- **Specialized deployment environments** - unique infrastructure or platform needs
- **Custom integration protocols** - bespoke APIs, message formats, or data structures  
- **Performance optimizations** - specific latency, throughput, or resource requirements
- **Custom user interfaces** - specialized dashboards, APIs, or management tools

## Advanced Custom Architectures

### **Private Container Registry Solutions**
```bash
# Custom registry deployment
your-registry.internal.com/slugkit/enterprise:custom-v1.0.0

# Air-gapped registry sync
./slugkit-registry-sync \
  --source ghcr.io/slugkit/slugkit-enterprise \
  --target your-registry.internal.com/slugkit/enterprise \
  --offline-mode
```

### **Custom Kubernetes Operators**
```yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: slugkitclusters.slugkit.io
spec:
  group: slugkit.io
  versions:
  - name: v1
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              airgap:
                type: boolean
              customFeatures:
                type: array
                items:
                  type: string
              nodeCount:
                type: integer
                minimum: 1
```

### **Specialized Hardware Integration**
```yaml
# Custom hardware support
hardware_integration:
  hsm_support: true
  custom_accelerators: fpga_pattern_matching
  specialized_storage: high_performance_nvme
  network_cards: rdma_enabled
  
performance_targets:
  latency: sub_microsecond
  throughput: millions_per_second
  availability: 99.999_percent
```

## Custom Pricing & Licensing Models

### **Flexible Commercial Terms**
- **Feature-based pricing** - pay only for the capabilities you need
- **Deployment-based pricing** - structured for your specific infrastructure
- **Usage-based models** - scaling pricing with actual consumption
- **Hybrid pricing** - combination of fixed and variable components

### **Example Pricing Scenarios**
```yaml
# Academic institution
pricing_model: academic_discount
features: [unlimited_nodes, research_tools, academic_compliance]
cost_structure: annual_educational_rate

# Government agency
pricing_model: government_contract
features: [air_gap, classified_deployment, clearance_support]
cost_structure: multi_year_fixed_price

# Technology startup
pricing_model: growth_oriented
features: [custom_apis, embedded_licensing, white_label]
cost_structure: success_based_scaling

# Fortune 500 enterprise
pricing_model: enterprise_unlimited
features: [everything_unlimited, dedicated_team, custom_development]
cost_structure: strategic_partnership
```

### **Licensing Flexibility**
- **Site-based licensing** - unlimited within specified locations
- **Feature-specific licensing** - modular pricing for specific capabilities
- **Time-based licensing** - project-specific or seasonal arrangements
- **Revenue sharing** - for customers offering SlugKit to their users

## Feature Request Process

### **Submit Your Requirements**
Use our Enterprise feature request form to describe:
- **Specific use case** - detailed description of your requirements
- **Technical constraints** - infrastructure, security, or performance requirements
- **Compliance needs** - regulatory, legal, or industry-specific requirements
- **Timeline and budget** - project timelines and budget considerations

### **Solution Design Phase**
1. **Requirements analysis** - detailed technical and business requirements review
2. **Architecture design** - custom solution architecture and implementation plan  
3. **Feasibility assessment** - technical feasibility and development effort estimation
4. **Proposal generation** - detailed solution proposal with transparent pricing

### **Development & Deployment**
1. **Custom development** - bespoke feature and integration development
2. **Testing and validation** - comprehensive testing in your environment
3. **Deployment assistance** - on-site deployment and configuration support
4. **Training and documentation** - comprehensive knowledge transfer

## Support for Non-Enterprise Users

### **Small Teams with Unique Needs**
Enterprise solutions aren't just for large corporations. Consider Enterprise if you:
- **Have specialized requirements** that don't fit standard plans
- **Need custom features** not available in other tiers
- **Require unique deployment models** beyond standard offerings
- **Want long-term strategic partnership** for evolving needs

### **Startup-Friendly Custom Solutions**
```yaml
# Example startup custom solution
use_case: unique_social_platform
requirements:
  - custom_user_handle_algorithms
  - specialized_branding_integration
  - rapid_scaling_architecture
pricing: growth_based_model
timeline: rapid_deployment
```

### **Creative and Specialized Use Cases**
- **Gaming companies** - custom algorithms for character and asset naming
- **Marketing agencies** - specialized campaign and brand identifier tools
- **Research projects** - academic or scientific identifier requirements
- **Content creators** - unique branding and identifier solutions

## Getting Started

### **Feature Request Form**
Submit your requirements through our Enterprise feature request process:
1. **Describe your use case** - detailed explanation of your needs
2. **Technical requirements** - infrastructure, performance, and integration needs
3. **Compliance and security** - regulatory and security requirements
4. **Timeline and budget** - project parameters and constraints

### **Consultation Process**
- **Initial consultation** - free discussion of your requirements and potential solutions
- **Solution design** - collaborative architecture design and feature planning
- **Proposal review** - detailed proposal with pricing and timeline
- **Decision and development** - begin custom development and deployment

### **SaaS Enterprise Alternative**
For some custom requirements, **SaaS Enterprise** with dedicated deployment might be more suitable:
- **Custom cloud deployment** - dedicated infrastructure in your preferred region
- **Managed air-gap solutions** - SlugKit-managed private cloud deployment
- **Hybrid cloud-premises** - combination of SaaS and on-premises deployment

---

**Have unique requirements that don't fit standard plans?** Submit a feature request to explore custom SlugKit Enterprise solutions designed specifically for your needs. From air-gapped deployment to specialized features, we create bespoke solutions for organizations of any size with unique requirements.


---

# SlugKit On-Premise Lite
Source: https://dev.slugkit.dev/docs/on-premise-lite

> **Expected Q1 2026** — Our team is working hard to deliver a robust, production-ready self-hosted solution. We appreciate your patience as we ensure everything meets our quality standards.

# SlugKit On-Premise Lite

The most affordable way to bring SlugKit's pattern-powered slug generation to your own infrastructure via Docker. Perfect for custom batch generation, themed identifier creation, and private network environments requiring complete data sovereignty.

## What's Included

### **Forge-Focused Generation**
- **Forge enabled**: Complete pattern control with custom seeds and sequences
- **Mint disabled**: Focus on batch and themed generation rather than unique sequences
- **Slice disabled**: Simplified deployment without counter management complexity
- **Perfect for**: Campaign codes, themed batches, testing, and offline generation

### **Self-Contained Docker Architecture**
- **SQLite database baked-in** - dictionaries and pattern data embedded in container
- **No data volumes required** - completely self-contained deployment
- **License file mounting only** - single file mount for licensing
- **Docker image distribution** - `ghcr.io/slugkit/slugkit-lite:latest`

### **Complete Pattern Power**
- **Unlimited daily generation** - no artificial quotas or restrictions
- **Full pattern language** - access to all dictionary selectors and generators embedded in container
- **Mathematical case transformations** - advanced typography and branding
- **Custom seeds** - reproducible, themed identifier generation

### **Self-Hosted Benefits**
- **Complete data privacy** - all generation happens in your environment
- **Zero external dependencies** - except for licensing validation
- **Predictable costs** - simple monthly/annual licensing with no per-slug charges
- **Stateless operation** - perfect for container orchestration and scaling

## Perfect For

### **Custom Batch Generation**
- Marketing teams needing themed campaign identifiers
- Development teams requiring reproducible test data
- Content creators wanting branded identifier schemes
- Anyone needing custom slug batches with specific aesthetics

### **Container-First Environments**
- **Kubernetes deployments** - stateless container orchestration
- **Docker Compose stacks** - simple single-container deployment
- **CI/CD pipelines** - containerised slug generation for automated workflows
- **Serverless containers** - ephemeral container instances for batch processing

### **Stateless & Ephemeral Workloads**
- **Batch processing jobs** - generate identifier sets and terminate
- **Temporary deployments** - short-lived environments for specific projects
- **Testing environments** - reproducible test data generation
- **Event-driven processing** - respond to triggers with identifier generation

## Container Specifications

### **Simple Docker Deployment**
```bash
# Minimal deployment - only license file required
docker run -d -p 8080:8080 \
  -v /path/to/license.yaml:/usr/local/etc/slugkit/license.yaml:ro \
  ghcr.io/slugkit/slugkit-lite:latest
```

### **Container Configuration**
```yaml
# Docker Compose - minimal configuration
version: '3.8'
services:
  slugkit-lite:
    image: ghcr.io/slugkit/slugkit-lite:latest
    ports:
      - "8080:8080"
    volumes:
      - ./license.yaml:/usr/local/etc/slugkit/license.yaml:ro
    restart: unless-stopped
```

### **Kubernetes Deployment**
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: slugkit-lite
spec:
  replicas: 1
  selector:
    matchLabels:
      app: slugkit-lite
  template:
    metadata:
      labels:
        app: slugkit-lite
    spec:
      containers:
      - name: slugkit-lite
        image: ghcr.io/slugkit/slugkit-lite:latest
        ports:
        - containerPort: 8080
        volumeMounts:
        - name: license
          mountPath: /usr/local/etc/slugkit/license.yaml
          subPath: license.yaml
          readOnly: true
        resources:
          requests:
            cpu: 0.5
            memory: 256Mi
          limits:
            cpu: 1
            memory: 512Mi
      volumes:
      - name: license
        secret:
          secretName: slugkit-license
```

### **License File Management**
```yaml
# Kubernetes Secret for license
apiVersion: v1
kind: Secret
metadata:
  name: slugkit-license
type: Opaque
data:
  license.yaml: <base64-encoded-license-content>
```

## Self-Contained Architecture Benefits

### **No Persistent Storage Required**
- **Dictionaries embedded** - 17,000+ adjectives, 41,000+ nouns baked into container
- **Pattern data included** - all language processing capabilities built-in
- **Stateless operation** - perfect for ephemeral container deployments
- **No volume management** - simplified deployment and orchestration

### **Container Optimization**
```yaml
# Container specifications
image_size: ~150MB  # Optimized with embedded dictionaries
base_image: distroless  # Minimal attack surface
architecture: [linux/amd64, linux/arm64]
startup_time: <2_seconds  # Fast container startup

# Resource requirements
resources:
  cpu: 0.5_vcpu_minimum
  memory: 256MB_minimum
  storage: none_required  # Completely stateless
```

### **Perfect for Scaling Scenarios**
```bash
# Horizontal scaling - no coordination needed
docker service create --replicas 5 \
  --mount type=bind,source=/path/to/license.yaml,target=/usr/local/etc/slugkit/license.yaml,readonly \
  -p 8080:8080 \
  ghcr.io/slugkit/slugkit-lite:latest
```

## Real-World Use Cases

### **CI/CD Pipeline Integration**
```yaml
# GitHub Actions example
name: Generate Campaign Codes
on:
  workflow_dispatch:
    inputs:
      campaign_name:
        required: true
      count:
        required: true

jobs:
  generate-codes:
    runs-on: ubuntu-latest
    steps:
    - name: Generate Campaign Identifiers
      run: |
        docker run --rm \
          -v ${{ github.workspace }}/license.yaml:/usr/local/etc/slugkit/license.yaml:ro \
          ghcr.io/slugkit/slugkit-lite:latest \
          curl -X POST http://localhost:8080/api/forge \
            -H "Content-Type: application/json" \
            -d '{
              "pattern": "${{ inputs.campaign_name }}-{adjective}-{number:4x}",
              "count": ${{ inputs.count }},
              "seed": "${{ github.run_id }}"
            }'
```

### **Serverless Container Deployment**
```yaml
# AWS Fargate task definition
{
  "family": "slugkit-lite-batch",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "512",
  "memory": "1024",
  "containerDefinitions": [
    {
      "name": "slugkit-lite",
      "image": "ghcr.io/slugkit/slugkit-lite:latest",
      "portMappings": [
        {
          "containerPort": 8080,
          "protocol": "tcp"
        }
      ],
      "mountPoints": [
        {
          "sourceVolume": "license",
          "containerPath": "/usr/local/etc/slugkit/license.yaml",
          "readOnly": true
        }
      ]
    }
  ],
  "volumes": [
    {
      "name": "license",
      "host": {
        "sourcePath": "/opt/slugkit/license.yaml"
      }
    }
  ]
}
```

### **Batch Processing Jobs**
```bash
# Kubernetes Job for one-time batch generation
apiVersion: batch/v1
kind: Job
metadata:
  name: campaign-code-generation
spec:
  template:
    spec:
      containers:
      - name: slugkit-batch
        image: ghcr.io/slugkit/slugkit-lite:latest
        command: ["/bin/sh"]
        args: ["-c", "curl -X POST http://localhost:8080/api/forge -d '{\"pattern\":\"PROMO-{adjective}-{number:3x}\",\"count\":10000}' > /tmp/codes.json"]
        volumeMounts:
        - name: license
          mountPath: /usr/local/etc/slugkit/license.yaml
          subPath: license.yaml
          readOnly: true
      restartPolicy: Never
      volumes:
      - name: license
        secret:
          secretName: slugkit-license
```

## License File Configuration

### **License File Structure**
```yaml
# license.yaml structure (example)
license:
  key: "your-license-key"
  plan: "on-premise-lite"
  expires: "2025-12-31"
  features:
    - "forge"
  validation:
    url: "https://licensing.slugkit.com/validate"
    interval: "1h"
```

### **License File Security**
```bash
# Secure license file permissions
chmod 600 license.yaml
chown root:root license.yaml

# Container mount with read-only access
-v /secure/path/license.yaml:/usr/local/etc/slugkit/license.yaml:ro
```

### **License Management in Production**
```yaml
# Kubernetes ConfigMap for license (if not sensitive)
apiVersion: v1
kind: ConfigMap
metadata:
  name: slugkit-license-config
data:
  license.yaml: |
    license:
      key: "your-license-key"
      plan: "on-premise-lite"

# Or Secret for sensitive license data
apiVersion: v1
kind: Secret
metadata:
  name: slugkit-license-secret
type: Opaque
stringData:
  license.yaml: |
    license:
      key: "sensitive-license-key"
      plan: "on-premise-lite"
```

## Why Stateless Architecture Matters

### **Container Orchestration Benefits**
- **Easy scaling** - spin up multiple instances without coordination
- **Zero state management** - no persistent storage or coordination complexity
- **Fast startup** - containers start in seconds with embedded data
- **Deployment simplicity** - only license file mounting required

### **Perfect for Modern Workloads**
- **Microservices** - lightweight slug generation sidecar
- **Event-driven** - respond to events with identifier generation
- **Batch processing** - generate large sets and terminate cleanly
- **Testing** - identical behavior across all environments

### **When to Consider Other Plans**
- **Need persistent counters** - On-Premise Core offers mint with state management
- **Multi-container coordination** - Core provides distributed series management
- **Production user handles** - mint ensures collision-free generation
- **Air-gapped requirements** - Enterprise supports completely isolated deployment

## Container Security & Compliance

### **Security Features**
- **Distroless base image** - minimal attack surface with no shell
- **Non-root execution** - container runs with unprivileged user
- **Read-only license mount** - license file mounted with read-only permissions
- **No network listeners** - only outbound connections for licensing

### **Compliance Ready**
- **Stateless processing** - no persistent data storage
- **Embedded dictionaries** - no external data dependencies
- **Audit-friendly** - all processing happens within container boundaries
- **Reproducible builds** - identical container behavior across environments

## Getting Started

### **Quick Deployment**
1. **Obtain license file** - download from SlugKit dashboard
2. **Pull container image** - `docker pull ghcr.io/slugkit/slugkit-lite:latest`
3. **Mount license file** - to `/usr/local/etc/slugkit/license.yaml:ro`
4. **Start generating** - container ready with embedded dictionaries

### **License File Setup**
```bash
# Download license from SlugKit dashboard
curl -H "Authorization: Bearer YOUR_API_TOKEN" \
  https://api.slugkit.com/license/download > license.yaml

# Secure the license file
chmod 600 license.yaml

# Deploy container
docker run -d -p 8080:8080 \
  -v $(pwd)/license.yaml:/usr/local/etc/slugkit/license.yaml:ro \
  ghcr.io/slugkit/slugkit-lite:latest
```

### **Verification**
```bash
# Test the deployment
curl -X POST http://localhost:8080/api/forge \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "test-{adjective}-{noun}",
    "count": 5
  }'

# Expected response: ["test-clever-keyboard", "test-swift-database", ...]
```

## Affordable Stateless Solution

### **Exceptional Value**
- **$3 per month** or **$30 per year** (incredible affordability)
- **Zero infrastructure overhead** - no persistent storage or data volumes
- **Complete feature set** - full pattern language embedded in container
- **Perfect for automation** - ideal for CI/CD and batch processing

### **Cost Benefits**
- **No storage costs** - no persistent volumes or data management
- **Simplified operations** - only license file to manage
- **Easy scaling** - horizontal scaling without coordination complexity
- **Container-optimized** - designed for modern deployment practices

---

**Ready for stateless containerised slug generation?** Deploy SlugKit On-Premise Lite from `ghcr.io/slugkit/slugkit-lite` with just a license file mount for powerful pattern-based identifier creation at just $3/month.


---

# On-Premises Products
Source: https://dev.slugkit.dev/docs/on-prem-products

**SlugKit On-Prem** – A self-hosted version of SlugKit for environments that require local control or offline operation (*fully air-gapped solution will be available later*). Available in lightweight and full-featured tiers, it offers the same powerful pattern engine and APIs as the SaaS platform. Pricing is per concurrent node to match your deployment size and scalability needs.


---

# SlugKit Pattern Examples by Use Case
Source: https://dev.slugkit.dev/docs/patter-examples-for-agents

# SlugKit Pattern Examples by Use Case

## Web Development

### URL Slugs
```
// Blog posts
"{adjective:+pos}-{noun}-{number:4d}"
→ "amazing-tutorial-2024"

// Product pages  
"{adjective:<8}-{noun:+tech}-{verb:<6}"
→ "smart-server-deploy"

// Category slugs
"{adjective:+tech}/{noun:+object}"
→ "advanced/database"
```

### User Handles & IDs
```
// Readable user handles
"{adjective:<7}{noun:<8}{number:2d}"
→ "smartuser42"

// Anonymous usernames
"{adjective:+pos}-{noun:+animal}-{number:3d}"
→ "happy-dolphin-127"

// API keys (readable part)
"{adjective}-{noun}-{number:4x}"
→ "secure-token-a1b2"
```

### CSS & JavaScript
```
// CSS class names
"{adjective:<6}-{noun:<8}-component"
→ "smart-button-component"

// JavaScript variables
"{verb}<6{Noun}<8Config"
→ "loadButtonConfig"

// Component names
"{Adjective}{Noun}Widget"
→ "SmartDatabaseWidget"
```

### API Endpoints
```
// RESTful endpoints
"/api/{noun:+tech}/{adjective:<6}-{noun:<8}/{number:4d}"
→ "/api/users/active-sessions/2024"

// Webhook URLs
"/hooks/{adjective:+tech}-{noun}/{number:8x}"
→ "/hooks/secure-payment/a1b2c3d4"
```

## DevOps & Infrastructure

### Server & Service Naming
```
// Server hostnames
"{adjective:+tech}<6-{noun:+tech}<8-{number:2d}"
→ "prod-database-01"

// Kubernetes pods
"{noun:+tech}-{adjective}-{number:4x}"
→ "webapp-stable-f3a7"

// Docker containers
"{adjective:+tech}/{noun:+tech}:{number:1d}.{number:1d}"
→ "stable/webapp:2.1"
```

### Environment & Configuration
```
// Environment names
"{ADJECTIVE:+tech}_{NOUN}_ENV"
→ "PROD_DATABASE_ENV"

// Config files
"{noun:<8}-{adjective:+tech}.{domain:+tld}"
→ "database-secure.conf"

// Backup naming
"backup-{noun:+tech}-{number:2d}{number:2d}{number:4d}-{number:4x}"
→ "backup-postgres-31122024-a1f3"
```

### Monitoring & Logging
```
// Log files
"{noun:+tech}-{adjective:+tech}-{number:2d}{number:2d}.log"
→ "webapp-error-1225.log"

// Metric names
"{noun:+tech}.{adjective}.{verb}.count"
→ "database.active.connections.count"

// Alert names
"{ADJECTIVE:+neg} {NOUN:+tech} {verb:+neg}"
→ "CRITICAL DATABASE FAILURE"
```

## Database & Data

### Table & Column Names
```
// Table names
"{noun:+tech}_{adjective:+tech}"
→ "users_active"

// Column identifiers  
"{noun:<8}_{verb:<6}_at"
→ "account_created_at"

// Index names
"idx_{noun:+tech}_{adjective:+tech}_{number:2d}"
→ "idx_users_active_01"
```

### Test Data Generation
```
// User emails
"{adjective:<7}.{noun:<8}@{noun:<6}.{domain:+com}"
→ "smart.database@test.com"

// Phone numbers (template)
"+1-{number:3d}-{number:3d}-{number:4d}"
→ "+1-555-123-4567"

// Addresses
"{number:3d} {Adjective} {Noun} Street"
→ "123 Smart Database Street"
```

### Database Seeding
```
// Company names
"{Adjective} {Noun} {noun:+tech}"
→ "Smart Database Solutions"

// Product names
"{adjective:+pos} {noun:+tech} {number:1d}.{number:1d}"
→ "Amazing Platform 2.1"

// Department codes
"{ADJECTIVE:<4}_{NOUN:+tech:<6}"
→ "PROD_WEBAPP"
```

## Testing & QA

### Test Case IDs
```
// Test identifiers
"test_{noun:+tech}_{verb}_{number:3d}"
→ "test_database_connect_042"

// Scenario names
"Given {adjective} {noun}, when {verb}, then {verb}"
→ "Given active user, when login, then succeed"

// Mock data labels
"{adjective:+pos}_{noun:+tech}_{number:2d}"
→ "valid_account_01"
```

### Performance Testing
```
// Load test names
"load_{noun:+tech}_{number:3d}_{adjective:+tech}"
→ "load_api_100_concurrent"

// Benchmark IDs
"bench_{verb}_{noun:+tech}_{number:4x}"
→ "bench_query_database_a1f3"
```

### Error Simulation
```
// Error messages
"Error {number:3d}: {adjective:+neg} {noun:+tech} {verb:+neg}"
→ "Error 500: broken database connection failed"

// Exception names
"{Adjective}{Noun}Exception"
→ "InvalidDatabaseException"

// Failure scenarios
"{noun:+tech} {verb:+neg} after {number:2d} {noun:+time}"
→ "connection timeout after 30 seconds"
```

## Documentation & Content

### Technical Writing
```
// Guide titles
"## {Adjective:+pos} {Noun} Guide"
→ "## Complete Database Guide"

// Tutorial steps
"Step {number:1d}: {Verb} the {noun:+tech}"
→ "Step 3: Configure the server"

// Code examples
"// {Adjective} {noun:+tech} implementation"
→ "// Simple database implementation"
```

### Blog & Marketing
```
// Article titles
"How to {verb} {adjective:+pos} {noun:+tech} in {number:2d} minutes"
→ "How to deploy amazing applications in 15 minutes"

// Social media
"{Adjective:+pos} {noun:+tech}! {verb:+pos} your {noun} {adverb:+pos} 🚀"
→ "Amazing platform! Scale your business efficiently 🚀"

// Newsletter subjects
"{Adjective:+pos} {noun}: {verb:+pos} {number:2d}% {adjective:+pos}"
→ "Weekly Update: Boost 25% performance"
```

## Gaming & Entertainment

### Character & World Generation
```
// Character names
"{adjective:+fantasy} {noun:+person} the {adjective:+pos}"
→ "Mighty Warrior the Brave"

// Location names
"The {adjective:+fantasy} {noun:+location} of {noun:+fantasy}"
→ "The Ancient Castle of Dragons"

// Item names
"{adjective:+pos} {noun:+fantasy} of {noun:+concept}"
→ "Legendary Sword of Power"
```

### Game Development
```
// Asset names
"{adjective}_{noun:+object}_{number:3d}"
→ "rusty_sword_042"

// Level identifiers
"level_{number:2d}_{adjective:+difficulty}_{noun:+location}"
→ "level_05_hard_dungeon"

// Achievement names
"{adjective:+pos} {noun:+action}"
→ "Ultimate Victory"
```

## E-commerce & Business

### Product Management
```
// SKUs
"{adjective:<4}-{noun:+product}<6-{number:4d}"
→ "FAST-LAPTOP-2024"

// Inventory codes
"{ADJECTIVE:+tech:<4}_{NOUN:<6}_{NUMBER:6x}"
→ "PROD_SERVER_A1B2C3"

// Coupon codes
"{adjective:+pos}{number:2d}{adjective:+tech}"
→ "SAVE25SECURE"
```

### Customer Service
```
// Ticket IDs
"TKT-{adjective:+tech}-{number:6d}"
→ "TKT-URGENT-123456"

// Case numbers
"{noun:+tech}-{number:4d}-{adjective:+priority}"
→ "BILLING-4567-HIGH"

// Reference codes
"REF_{ADJECTIVE:<4}_{NUMBER:8x}"
→ "REF_HELP_A1B2C3D4"
```

## Security & Authentication

### Access Control
```
// Permission names
"{verb}_{noun:+tech}_{adjective:+security}"
→ "read_database_secure"

// Role identifiers
"{adjective:+tech}_{noun:+person}"
→ "admin_user"

// Session tokens (readable part)
"sess_{adjective:+tech}_{number:8x}"
→ "sess_secure_a1b2c3d4"
```

### Audit & Compliance
```
// Log entries
"[{number:2d}/{number:2d}/{number:4d}] {ADJECTIVE} {noun:+tech} {verb:+security}"
→ "[31/12/2024] FAILED database authentication"

// Compliance codes
"{ADJECTIVE:+security}_{NOUN:+tech}_{NUMBER:4d}"
→ "GDPR_DATA_2024"
```

## Advanced Pattern Techniques

### Multi-line Templates
```
"version: {number:1d}.{number:1d}.{number:2d}
name: {adjective}-{noun}
description: {adjective:+pos} {noun:+tech} for {verb}<6
maintainer: {Noun:+person} Team
status: {adjective:+tech}"

→ "version: 2.1.15
name: secure-platform
description: amazing solution for deploy
maintainer: Engineering Team  
status: stable"
```

### Conditional-like Patterns with Global Settings
```
// All positive tech terms
"{noun} {verb} {adjective} {noun}[+pos+tech]"
→ "platform deploys amazing solution"

// German technical terms (if supported)
"{noun} {verb} {noun}[@de+tech]"
→ "Datenbank verwendet System"

// Short professional terms
"{adjective} {noun} {verb}[+professional<6]"
→ "smart system works"
```

### Complex Casing Scenarios
```
// PascalCase components
"{Adjective}{Noun}{Verb}Component"
→ "SmartDatabaseQueryComponent"

// snake_case variables
"{adjective}_{noun}_{verb}_config"
→ "secure_database_connect_config"

// SCREAMING_SNAKE_CASE constants
"{ADJECTIVE}_{NOUN}_{NUMBER:4d}"
→ "MAX_DATABASE_1000"

// Mixed enterprise naming
"{AdJeCtIvE}_{nOuN}_v{NUMBER:1d}"
→ "SmArT_sErVeR_v2"
```

## Performance & Capacity Planning

### High-Volume Patterns (Large Capacity)
```
// Billions of combinations
"{adjective}-{noun}-{number:6x}"
→ Capacity: ~708M × 16M = 11+ trillion combinations

// Moderate capacity with constraints
"{adjective:<6}-{noun:+tech<8}-{number:3d}"  
→ More manageable capacity with better performance
```

### Low-Volume Patterns (Specific Use Cases)
```
// Limited but meaningful
"{adjective:+pos<5}-{noun:+tech==4}-{number:2d}"
→ Fewer combinations, highly constrained output
```

### Capacity Impact Examples
```
// Standard casing
"{noun}-{adjective}" 
→ ~708M combinations

// Mixed casing (capacity multiplier)
"{NoUn}-{AdJeCtIvE}"
→ Exponentially more combinations (2^8 × 708M+)
```

---

**Pro Tips:**
- Use `validate_pattern()` to check capacity before generation
- Combine `dictionary_info()` and `dictionary_tags()` to understand available words
- Test patterns with small `count` values first
- Consider length constraints for UI/database field limits
- Use global settings for consistent theming across complex patterns

---

# Pattern Advanced Features
Source: https://dev.slugkit.dev/docs/pattern-advanced-features

# Advanced Pattern Features

Master SlugKit's most powerful capabilities: mathematical case transformations, complex filtering strategies, global modifiers, and pattern optimization techniques for production-scale applications.

## Overview

This guide explores advanced pattern features that give you fine-grained control over slug generation. You'll learn how to:

- Create sophisticated case transformation patterns
- Combine multiple filtering strategies
- Use global modifiers for pattern-wide control
- Optimize patterns for capacity and performance
- Handle edge cases and complex requirements

**Prerequisites:** Familiarity with [Pattern Syntax Basics](pattern-syntax-basics)

## Mathematical Case Transformations

SlugKit's most distinctive feature is **mathematical case transformation** - the ability to apply arbitrary capitalisation patterns to dictionary words with mathematical precision.

### How It Works

The case pattern of your placeholder defines a transformation rule. SlugKit applies this rule **position-by-position** to each generated word:

1. Take the placeholder's case pattern: `{aDjEcTiVe}`
2. Extract positions: lowercase at 0,2,4,6... uppercase at 1,3,5,7...
3. Apply to generated word: `brilliant` → `bRiLlIaNt`

**This is not random** - the same pattern always produces the same transformation.

### Standard Transformations

**Lowercase (all letters lowercase):**
```
{adjective}    → brilliant
{noun}         → telescope
{verb}         → generate
```

**Title Case (first letter uppercase):**
```
{Adjective}    → Brilliant
{Noun}         → Telescope
{Verb}         → Generate
```

**UPPERCASE (all letters uppercase):**
```
{ADJECTIVE}    → BRILLIANT
{NOUN}         → TELESCOPE
{VERB}         → GENERATE
```

### Custom Mixed Case Patterns

Create any case pattern you can imagine:

**Alternating lowercase/uppercase:**
```
{aDjEcTiVe}    → bRiLlIaNt
{NoUn}         → TeLeSCoPe
{VeRb}         → GeNeRaTe
```

**Start uppercase, then alternate:**
```
{AdJeCtIvE}    → BrIlLiAnT
{NoUn}         → TeLeSCoPe
```

**Custom patterns:**
```
{ADJective}    → BRIlliant    (first 3 uppercase)
{adjECTive}    → briLLIant    (middle uppercase)
{adjectIVE}    → brilliANT    (last 3 uppercase)
```

**Complex patterns:**
```
{aDJecTIve}    → bRIllATnt
{NOun}         → TElesCope
{vERb}         → gENerate
```

### Position-Based Rules

The transformation follows these rules:

1. **Pattern repeats** - If word is longer than pattern, pattern cycles
2. **Pattern truncates** - If word is shorter, only part of pattern is used
3. **Non-letters preserved** - Hyphens, numbers stay unchanged

**Example with long word:**
```
Pattern:  {aBc}
Word:     magnificent
Result:   mAgnIfIcEnT
          ↑↑↑↑↑↑↑↑↑↑↑
          aB caB caBc
```

**Example with short word:**
```
Pattern:  {aBcDeFg}
Word:     cat
Result:   cAt
          ↑↑↑
          aBc
```

### Practical Applications

**Brand Consistency:**
```
{Adjective}-{NOUN}
→ Brilliant-TELESCOPE, Cosmic-SYMPHONY

Pattern: {AdJeCtIvE}-{noun}
→ BrIlLiAnT-telescope, CoSmIc-symphony
```

**Visual Hierarchy:**
```
{NOUN}::{Adjective}::{noun}
→ DATABASE::Brilliant::framework
```

**Product Lines:**
```
{Adjective:+pos}-{NOUN:+artifact}-{number:3X}
→ Brilliant-GADGET-A4F, Excellent-DEVICE-B7D
```

**Distinctive Handles:**
```
{aDjEcTiVe}-{NoUn}-{number:2x}
→ bRiLlIaNt-TeLeSCoPe-3a, cOsMiC-sYmPhOnY-f7
```

### Testing Case Patterns

Always test case transformations with actual words:

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{aDjEcTiVe}-{NoUn}",
    "count": 10
  }'
```

**Result:**
```json
[
  "bRiLlIaNt-TeLeSCoPe",
  "cOsMiC-sYmPhOnY",
  "eLeGaNt-FrAmEwOrK"
]
```

### Best Practices

**Readability:**
- Use standard cases (lowercase, Title, UPPERCASE) for maximum readability
- Reserve mixed case for distinctive branding or visual impact
- Test with real users to ensure comprehension

**Consistency:**
- Apply the same case pattern across related identifiers
- Document your case conventions for team consistency
- Use global modifiers to enforce patterns

**Performance:**
- Case transformations don't affect capacity
- No performance penalty for complex patterns
- Same generation speed regardless of case complexity

## Advanced Tag Filtering

Combine multiple filtering strategies for precise word selection.

### Multi-Tag Inclusion

Require words to have **all** specified tags:

```
{adjective:+pos+emo}
→ Only words tagged BOTH positive AND emotional
→ wonderful, delightful, joyful
```

**Use cases:**
- Highly specific tone requirements
- Brand-appropriate language
- Context-specific identifiers

### Multi-Tag Exclusion

Exclude words with **any** of the specified tags:

```
{adjective:-neg-nsfw}
→ Excludes words tagged negative OR nsfw
→ Safe, neutral-to-positive words only
```

**Use cases:**
- Family-friendly content
- Professional environments
- Safe-for-work identifiers

### Combining Inclusion and Exclusion

Mix include and exclude tags for maximum control:

```
{adjective:+pos-nsfw}
→ Include positive, exclude nsfw
→ brilliant, excellent (not offensive positive words)

{noun:+device+concept-nsfw}
→ Technical devices + conceptual terms, but not inappropriate
→ processor, algorithm, framework (not explicit terms)
```

### Tag Priority Rules

When combining tags:

1. **Exclusions take precedence** - If a word has any excluded tag, it's filtered out
2. **All inclusions required** - Word must have all included tags
3. **No tags means all tags** - Empty tag list includes all words

**Examples:**
```
{adjective:+pos+emo-neg}
→ Must be positive AND emotional, but NOT negative
→ Words like "bittersweet" (pos+emo+neg) are excluded

{noun:+device-nsfw}
→ Must be technical devices, but exclude inappropriate terms
→ processor ✓, server ✓, framework ✓
```

### Discovering Available Tags

Use the dictionary tags endpoint to explore options:

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/dictionary-tags?kind=adjective \
  -H "X-API-Key: sk_live_..."
```

**Response:**
```json
{
  "data": [
    {
      "kind": "adjective",
      "tag": "pos",
      "description": "Positive word",
      "opt_in": false,
      "word_count": 710
    },
    {
      "kind": "adjective",
      "tag": "neg",
      "description": "Negative word",
      "opt_in": false,
      "word_count": 1395
    }
  ]
}
```

### Opt-In Tags

Some tags require explicit inclusion:

```
{adjective:+nsfw}    → Explicitly include NSFW words
{adjective}          → Excludes NSFW by default
{adjective:-nsfw}    → Redundant (already excluded)
```

**Opt-in tags:**
- `nsfw` - Inappropriate or offensive content
- May expand in future versions

### Practical Examples

**Professional SaaS identifiers:**
```
{adjective:+obj+det-nsfw<10}-{noun:+device-nsfw}
→ efficient-processor, stable-compiler
```

**Positive social handles:**
```
{adjective:+pos+emo-neg<8}-{noun:+nature}
→ joyful-mountain, bright-ocean
```

**Technical documentation:**
```
{adjective:+obj-emo}-{noun:+device}-{verb:+act}
→ standard-processor-execute
```

## Length Constraints

Control word length with precision.

### Single Length Constraints

Use one comparison operator per selector:

```
{adjective:<8}       → Maximum 7 characters
{noun:>5}            → Minimum 6 characters  
{verb:>=6}           → Minimum 6 characters (inclusive)
{adjective:<=10}     → Maximum 10 characters (inclusive)
{noun:==7}           → Exactly 7 characters
{adjective:!=5}      → Not exactly 5 characters
```

### Common Length Patterns

**Short names (mobile-friendly):**
```
{adjective:<7}-{noun:<10}
→ swift-app, bold-code
```

**Medium names (readable):**
```
{adjective:>5}-{noun:>6}
→ brilliant-telescope, cosmic-symphony
```

**Long names (descriptive):**
```
{adjective:>10}-{noun:>12}
→ spectacular-infrastructure
```

### Exact Length Matching

Use `==` for fixed-width identifiers:

```
{adjective:==7}-{noun:==9}
→ perfect-framework (both exact length)
→ Creates very specific constraints
```

**Warning:** Exact matching significantly reduces capacity. Use sparingly.

### Combining with Tags

Length and tag constraints work together:

```
{adjective:+pos<8}-{noun:+device>=6}
→ Positive adjectives (max 7 chars) + device nouns (min 6 chars)
→ joyful-processor, bright-compiler
```

### Capacity Impact

Length constraints **reduce capacity**:

```
{adjective}           → 17,082 options
{adjective:<8}        → ~8,000 options (estimated)
{adjective:==5}       → ~500 options (estimated)
```

**Best practices:**
- Use inequality operators (<, >, <=, >=) rather than exact (==) when possible
- Test capacity impact with pattern-info endpoint
- Balance readability with capacity requirements

## Global Modifiers

Apply settings to all placeholders at once.

### Syntax

```
{placeholder1}-{placeholder2}[MODIFIERS]
```

Modifiers at the end (in square brackets) apply to all dictionary selectors.

### Language Modifier

Set language for all selectors:

```
{adjective}-{noun}[@en]
→ Both use English

{adjective}-{noun}-{verb}[@en]
→ All three use English
```

**Current support:** Only `@en` is currently available for most dictionaries.

### Global Tag Filtering

Apply tags to all selectors:

```
{adjective}-{noun}[:+positive]
→ Both must be positive
→ brilliant-telescope, joyful-mountain

{adjective}-{noun}-{verb}[:-nsfw]
→ All exclude NSFW (redundant with defaults)

{adjective}-{noun}[:+pos+emo-neg]
→ All must be positive AND emotional, NOT negative
```

### Global Length Constraints

Apply length limits to all selectors:

```
{adjective}-{noun}[<8]
→ Both max 7 characters
→ swift-app, bold-code

{adjective}-{noun}[>5]
→ Both min 6 characters
→ brilliant-telescope
```

### Combining Global Modifiers

Stack multiple global modifiers:

```
{adjective}-{noun}[@en:+positive<10]
→ English, positive words, max 9 characters

{adjective}-{noun}-{verb}[:+pos+emo-neg-nsfw<8]
→ Positive, emotional, not negative, not nsfw, max 7 chars
```

### Local vs Global Precedence

Local (per-placeholder) settings override global settings:

```
{adjective:+neg}-{noun}[:+pos]
→ adjective is negative (local overrides)
→ noun is positive (global applies)
→ broken-telescope

{adjective:<6}-{noun}[<10]
→ adjective max 5 (local overrides)
→ noun max 9 (global applies)
→ swift-framework
```

### Practical Examples

**Brand consistency:**
```
{Adjective}-{Noun}-{Verb}[:+pos+obj<12]
→ All positive, objective, max 11 chars
→ Brilliant-Framework-Execute
```

**Family-friendly content:**
```
{adjective}-{noun}-{verb}[:-nsfw:+pos]
→ All safe, all positive
→ brilliant-telescope-generate
```

**Compact identifiers:**
```
{adjective}-{noun}[<7]
→ All max 6 characters
→ swift-code
```

### When to Use Global Modifiers

**Use global when:**
- Same constraints apply to all placeholders
- Enforcing brand consistency
- Simplifying pattern maintenance
- Creating systematic naming schemes

**Use local when:**
- Different requirements per placeholder
- Mixing tones or contexts
- Fine-grained control needed
- Testing specific combinations

## Pattern Composition Strategies

Techniques for building complex, maintainable patterns.

### Hierarchical Naming

Create visual hierarchy with case:

```
{NOUN}::{Adjective}::{noun}
→ DATABASE::Brilliant::framework
→ Top-level (ALL CAPS), mid-level (Title), detail (lowercase)

{NOUN}/{Noun}/{noun}
→ SERVER/Database/instance
→ Clear hierarchy with separators
```

### Semantic Grouping

Group related elements:

```
api-{verb:+act}/{noun:+device}
→ api-generate/processor
→ Action verbs for operations, device nouns for resources

{adjective:+obj}-{noun:+device}-{adjective:+obj}
→ stable-processor-efficient
→ Object quality, resource type, current characteristic
```

### Progressive Specificity

Move from general to specific:

```
{noun:+device}-{adjective:+obj}-{number:4x}
→ processor-primary-3a2f
→ Type → characteristic → instance ID

{adjective:+obj}-{noun:+device}-{number:2d}
→ digital-processor-42
→ Category → specific → identifier
```

### Contextual Prefixes

Add context with literal text:

```
prod-{adjective:+obj}-{noun:+device}
→ prod-stable-processor

user-{adjective:+pos}-{noun:+nature}
→ user-cosmic-dragon

temp-{adjective}-{noun}-{number:6x}
→ temp-swift-cache-3a2f4b
```

### Namespacing Strategies

**Environment prefixes:**
```
{env}-{adjective}-{noun}
→ dev-brilliant-api, prod-stable-service
```

**Organisation structure:**
```
{org}/{team}/{adjective}-{noun}
→ acme/platform/swift-framework
```

**Resource types:**
```
{type}_{adjective}_{noun}
→ db_stable_primary, app_swift_worker
```

## Pattern Optimisation

Maximise capacity, performance, and maintainability.

### Capacity Planning

Every pattern has a finite capacity. Plan for growth:

**Calculate minimum capacity:**
```
Required IDs = Users × Resources × Growth Factor × Safety Margin

Example:
100K users × 10 resources × 5x growth × 2x safety = 100M IDs needed
```

**Check pattern capacity:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/pattern-info \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}"}'
```

**Response:**
```json
{
  "capacity": "708339294",
  "max_slug_length": 55,
  "complexity": 10,
  "components": 2
}
```

### Increasing Capacity

**Add more selectors:**
```
{adjective}-{noun}              → 708M capacity
{adjective}-{noun}-{verb}       → 5.95T capacity
{adj}-{noun}-{verb}-{adverb}    → 21.5T capacity
```

**Use longer numbers:**
```
{adjective}-{noun}-{number:2x}  → 181B capacity
{adjective}-{noun}-{number:4x}  → 46.5T capacity
{adjective}-{noun}-{number:6x}  → 11.9P capacity
```

**Reduce constraints:**
```
{adjective:==5}-{noun:==7}      → ~250K capacity
{adjective:<8}-{noun:<10}       → ~40M capacity
{adjective}-{noun}              → 708M capacity
```

### Balancing Readability and Capacity

**High readability (lower capacity):**
```
{adjective:+pos<8}-{noun:+device<10}
→ brilliant-router, cosmic-server
→ Capacity: ~5M
```

**Balanced (good capacity, readable):**
```
{adjective}-{noun}-{number:3x}
→ brilliant-telescope-3a2
→ Capacity: 181B
```

**Maximum capacity (less readable):**
```
{adj}-{noun}-{verb}-{number:6x}
→ brilliant-telescope-generate-3a2f4b
→ Capacity: 5.95P
```

### Performance Considerations

**Generation speed:**
- Dictionary lookups: 3-20μs per slug
- Number generation: <1μs per slug
- Case transformation: negligible overhead
- Filtering: minimal impact (<5% slower)

**Optimisation tips:**
- Avoid overly complex tag filtering
- Use simpler patterns for high-volume generation
- Streaming endpoints for bulk operations
- Cache pattern analysis results

### Maintainability

**Document your patterns:**
```python
# User handle pattern
# Target capacity: 100M
# Tone: Positive, family-friendly
# Length: Mobile-optimised (<20 chars)
HANDLE_PATTERN = "{adjective:+pos<8}-{noun:+nature<10}"
```

**Version your patterns:**
```python
PATTERNS = {
    "v1": "{adjective}-{noun}",
    "v2": "{adjective:+pos}-{noun}",
    "v3": "{adjective:+pos<8}-{noun:+nature}"
}
```

**Test systematically:**
```python
def test_pattern_capacity():
    result = analyze_pattern("{adjective}-{noun}-{number:3x}")
    assert int(result["capacity"]) > 100_000_000
    
def test_pattern_readability():
    slugs = forge_slugs("{adjective:+pos<8}-{noun:+nature<10}", count=100)
    assert all(len(s) < 20 for s in slugs)
```

## Advanced Use Cases

### Multi-Environment Identification

Different patterns for different environments:

```python
PATTERNS = {
    "dev": "{adjective}-{noun}-dev-{number:2x}",
    "staging": "{adjective:+obj}-{noun:+device}-stg",
    "prod": "{Adjective}-{Noun}-{number:4X}"
}
```

### Hierarchical Resource Naming

```
{CATEGORY}/{adjective}-{noun}/{instance}

Examples:
DATABASE/stable-primary/001
COMPUTE/swift-worker/a3f
STORAGE/persistent-cache/x7b
```

### Branded Product Lines

```
{Brand}{Adjective:+pos}-{NOUN:+artifact}-{number:3X}

Examples:
PremiumBrilliant-GADGET-A4F
EssentialExcellent-DEVICE-B7D
UltimateWonderful-SYSTEM-C2A
```

### Multilingual Support (Future)

When multiple languages become available:

```
{adjective@en}-{noun@en}        → English
{adjective@es}-{noun@es}        → Spanish
{adjective@fr}-{noun@fr}        → French
```

## Troubleshooting Advanced Patterns

### No Matching Words Found

**Problem:**
```
{adjective:+pos+neg}
→ Error: No matching words
```

**Reason:** No words are both positive AND negative

**Solution:** Check tag logic - ensure tags are compatible

### Capacity Too Low

**Problem:**
```
{adjective:==5}-{noun:==7}
→ Capacity: 250,000 (too low)
```

**Solution:** Relax constraints or add components
```
{adjective:<8}-{noun:<10}-{number:3x}
→ Capacity: 10B+ (much better)
```

### Unexpected Case Output

**Problem:**
```
{aDjEcTiVe} → Expected: bRiLlIaNt, Got: bRiLlIaNt
```

**Solution:** Check word length - pattern cycles for long words
```
# For consistent results with long words, use standard cases
{Adjective} or {ADJECTIVE}
```

### Global Modifiers Not Applied

**Problem:**
```
{adjective:+neg}-{noun}[:+pos]
→ Both not positive
```

**Solution:** Local settings override global - remove local to use global

### Invalid Tag References

**Problem:**
```
{noun:+tech}
→ Error: No matching words found for: noun:+tech
```

**Reason:** The `tech` tag doesn't exist for nouns

**Solution:** Use valid alternatives - check available tags first
```
{noun:+device}        → Technical devices (1,673 words)
{noun:+artifact}      → Human-made objects (6,787 words)
{noun:+obj}           → Objective things (26,812 words)
```

## Best Practices Summary

### Case Transformations
- ✅ Use standard cases for maximum readability
- ✅ Test mixed case patterns with real words
- ✅ Document case conventions for consistency
- ❌ Don't overuse complex mixed case patterns

### Tag Filtering
- ✅ Always exclude NSFW for user-facing content
- ✅ Use positive tags for welcoming identifiers
- ✅ Combine tags thoughtfully (check compatibility)
- ✅ Validate tag existence before using
- ❌ Don't over-filter (hurts capacity)

### Length Constraints
- ✅ Use single constraints per selector
- ✅ Test capacity impact before production
- ✅ Consider mobile/display limitations
- ❌ Don't use exact length unless required

### Global Modifiers
- ✅ Use for consistent brand voice
- ✅ Simplify pattern maintenance
- ✅ Document global vs local precedence
- ❌ Don't mix with too many local overrides

### Pattern Optimisation
- ✅ Plan for 10x growth in capacity
- ✅ Test with pattern-info endpoint
- ✅ Version patterns for migrations
- ✅ Always validate patterns before documenting
- ❌ Don't sacrifice readability for marginal capacity gains

## Next Steps

Explore related advanced topics:

**Deep Dives:**
- [Dictionary Reference](pattern-dictionary-reference) - Complete word lists and tags
- [Pattern Cookbook](pattern-cookbook) - Real-world pattern examples
- [Performance Optimisation](pattern-performance-optimization) - Capacity and efficiency

**API Integration:**
- [Forge Endpoint](api-reference) - Test advanced patterns
- [Validation Endpoints](api-reference) - Analyse pattern capacity
- [Mint Endpoint](api-reference) - Use patterns in production

**Fundamentals:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Foundation concepts
- [Core Concepts](developer-core-concepts) - Understanding SlugKit
- [Choosing Generation Methods](choosing-generation-method) - Forge vs Mint vs Slice


---

# Pattern Cookbook
Source: https://dev.slugkit.dev/docs/pattern-cookbook

# Pattern Cookbook

Real-world pattern examples for common use cases. Each recipe includes the pattern, example output, use cases, and a link to try it in the interactive playground.

## How to Use This Cookbook

Each pattern recipe includes:
- **Pattern** - The complete pattern syntax
- **Example Output** - Real generated slugs
- **Use Cases** - When to use this pattern
- **Capacity** - Approximate uniqueness potential
- **Try It** - Direct link to test in the playground

**Tip:** Click "Try in Playground" to experiment with any pattern and see live results.

## Web Development

### Blog Post URLs

**Pattern:**
```
{adjective}-{noun}
```

**Example Output:**
```
brilliant-telescope
cosmic-symphony
elegant-framework
swift-compass
```

**Use Cases:**
- Blog post slugs
- Article URLs
- Content identifiers
- Documentation pages

**Capacity:** ~700M unique slugs

[**Try in Playground →**](/playground?pattern={adjective}-{noun})

---

### Blog Posts with Numbers

**Pattern:**
```
{adjective}-{noun}-{number:2d}
```

**Example Output:**
```
brilliant-telescope-42
cosmic-symphony-17
elegant-framework-93
```

**Use Cases:**
- Blog posts needing guaranteed uniqueness
- Article series with same titles
- Timestamped content

**Capacity:** ~70B unique slugs

[**Try in Playground →**](/playground?pattern={adjective}-{noun}-{number:2d})

---

### Product Page URLs

**Pattern:**
```
{adjective:+pos<10}-{noun:+artifact}
```

**Example Output:**
```
excellent-device
wonderful-gadget
brilliant-tool
```

**Use Cases:**
- E-commerce product pages
- Service offering pages
- Premium product identifiers

**Capacity:** ~5M unique slugs

[**Try in Playground →**](/playground?pattern={adjective:+pos<10}-{noun:+artifact})

---

### API Endpoints

**Pattern:**
```
{verb:+act}/{noun:+device}
```

**Example Output:**
```
execute/processor
generate/compiler
process/router
```

**Use Cases:**
- RESTful API endpoints
- Resource operations
- Microservice routes

**Capacity:** ~2M unique combinations

[**Try in Playground →**](/playground?pattern={verb:+act}/{noun:+device})

---

### Component Names

**Pattern:**
```
{Adjective:+obj}-{Noun:+device}-Component
```

**Example Output:**
```
Stable-Router-Component
Efficient-Processor-Component
Reliable-Server-Component
```

**Use Cases:**
- React/Vue component names
- UI library components
- Design system elements

**Capacity:** ~14M unique names

[**Try in Playground →**](/playground?pattern={Adjective:+obj}-{Noun:+device}-Component)

## User Handles & Social

### Social Media Handles

**Pattern:**
```
{adjective:+pos<8}-{noun:+animal}
```

**Example Output:**
```
cosmic-dragon
swift-phoenix
bright-falcon
```

**Use Cases:**
- Twitter/X handles
- Instagram usernames
- TikTok identifiers
- Discord names

**Capacity:** ~1.7M unique handles

[**Try in Playground →**](/playground?pattern={adjective:+pos<8}-{noun:+animal})

---

### Gaming Usernames

**Pattern:**
```
{adjective:+pos}-{noun:+fantasy}-{number:2x}
```

**Example Output:**
```
fierce-warrior-3a
cosmic-wizard-f7
swift-dragon-2c
```

**Use Cases:**
- Gaming platforms
- MMO character names
- E-sports identifiers
- Game leaderboards

**Capacity:** ~180K unique names

[**Try in Playground →**](/playground?pattern={adjective:+pos}-{noun:+fantasy}-{number:2x})

---

### Professional Handles

**Pattern:**
```
{adjective:+obj<10}-{noun:+person}
```

**Example Output:**
```
efficient-developer
precise-designer
capable-engineer
```

**Use Cases:**
- LinkedIn identifiers
- Professional networks
- Portfolio URLs
- Business profiles

**Capacity:** ~50M unique handles

[**Try in Playground →**](/playground?pattern={adjective:+obj<10}-{noun:+person})

---

### Friendly Community Names

**Pattern:**
```
{adjective:+pos+emo}-{noun:+animal<10}
```

**Example Output:**
```
joyful-panda
delightful-koala
cheerful-otter
```

**Use Cases:**
- Community forums
- Chat platforms
- Social apps
- Family-friendly services

**Capacity:** ~1.4M unique names

[**Try in Playground →**](/playground?pattern={adjective:+pos+emo}-{noun:+animal<10})

## DevOps & Infrastructure

### Server Names

**Pattern:**
```
{noun:+device}-{adjective:+obj}-{number:2d}
```

**Example Output:**
```
server-stable-01
router-efficient-14
database-reliable-07
```

**Use Cases:**
- Server hostnames
- VM identifiers
- Cloud instances
- Infrastructure naming

**Capacity:** ~14M unique names

[**Try in Playground →**](/playground?pattern={noun:+device}-{adjective:+obj}-{number:2d})

---

### Container Names

**Pattern:**
```
{adjective:+obj}-{noun:+device}-{number:3x}
```

**Example Output:**
```
stable-processor-3a2
efficient-compiler-f7d
reliable-router-b4c
```

**Use Cases:**
- Docker containers
- Kubernetes pods
- Container registries
- Microservice instances

**Capacity:** ~14B unique names

[**Try in Playground →**](/playground?pattern={adjective:+obj}-{noun:+device}-{number:3x})

---

### Environment Names

**Pattern:**
```
{adjective:+obj}-{noun:+device}-{env}
```

**Example Output:**
```
stable-database-prod
testing-service-dev
secure-api-staging
```

**Use Cases:**
- Deployment environments
- CI/CD pipelines
- Infrastructure as Code
- Resource tagging

**Replace `{env}` with literal:** `prod`, `dev`, `staging`

[**Try in Playground →**](/playground?pattern={adjective:+obj}-{noun:+device}-prod)

---

### Kubernetes Resources

**Pattern:**
```
{verb:+act}-{noun:+device}-pod
```

**Example Output:**
```
process-worker-pod
execute-service-pod
manage-queue-pod
```

**Use Cases:**
- Pod naming
- Service mesh
- Ingress controllers
- StatefulSets

**Capacity:** ~2M unique names

[**Try in Playground →**](/playground?pattern={verb:+act}-{noun:+device}-pod)

## Product & E-commerce

### Product SKUs

**Pattern:**
```
{Adjective:+pos}-{NOUN:+artifact}-{number:3X}
```

**Example Output:**
```
Premium-GADGET-A4F
Essential-DEVICE-B7D
Superior-TOOL-C2A
```

**Use Cases:**
- Product SKUs
- Inventory codes
- Catalog identifiers
- Retail systems

**Capacity:** ~5B unique codes

[**Try in Playground →**](/playground?pattern={Adjective:+pos}-{NOUN:+artifact}-{number:3X})

---

### Order IDs

**Pattern:**
```
ORDER-{number:8d}
```

**Example Output:**
```
ORDER-28471902
ORDER-91026574
ORDER-45738291
```

**Use Cases:**
- Order numbers
- Transaction IDs
- Invoice numbers
- Reference codes

**Capacity:** 100M unique IDs

[**Try in Playground →**](/playground?pattern=ORDER-{number:8d})

---

### Campaign Codes

**Pattern:**
```
{adjective:+pos<8}-{number:2x}
```

**Example Output:**
```
brilliant-f3
cosmic-a7
swift-2c
```

**Use Cases:**
- Promo codes
- Campaign tracking
- Discount codes
- Marketing identifiers

**Capacity:** ~180K unique codes

[**Try in Playground →**](/playground?pattern={adjective:+pos<8}-{number:2x})

---

### Product Variants

**Pattern:**
```
{noun:+artifact}-{adjective:+obj}-{number:2d}
```

**Example Output:**
```
gadget-stable-01
device-premium-14
tool-standard-07
```

**Use Cases:**
- Product variations
- Model numbers
- Style identifiers
- Configuration codes

**Capacity:** ~7B unique variants

[**Try in Playground →**](/playground?pattern={noun:+artifact}-{adjective:+obj}-{number:2d})

## SaaS & Business

### Workspace Slugs

**Pattern:**
```
{adjective:+obj<10}-{noun:+activity}
```

**Example Output:**
```
efficient-workspace
stable-environment
reliable-platform
```

**Use Cases:**
- Workspace identifiers
- Team spaces
- Organization slugs
- Tenant IDs

**Capacity:** ~22M unique slugs

[**Try in Playground →**](/playground?pattern={adjective:+obj<10}-{noun:+activity})

---

### Project Names

**Pattern:**
```
{adjective}-{noun:+activity}-{number:4x}
```

**Example Output:**
```
brilliant-project-3a2f
cosmic-initiative-b7d4
elegant-program-c1e9
```

**Use Cases:**
- Project identifiers
- Initiative tracking
- Program management
- Portfolio items

**Capacity:** ~4.6T unique names

[**Try in Playground →**](/playground?pattern={adjective}-{noun:+activity}-{number:4x})

---

### Client Codes

**Pattern:**
```
CLIENT-{adjective:+obj<8}-{number:4d}
```

**Example Output:**
```
CLIENT-stable-2847
CLIENT-typical-9102
CLIENT-standard-5673
```

**Use Cases:**
- Client identifiers
- Customer codes
- Account numbers
- Reference IDs

**Capacity:** ~80M unique codes

[**Try in Playground →**](/playground?pattern=CLIENT-{adjective:+obj<8}-{number:4d})

---

### Feature Flags

**Pattern:**
```
{adjective:+obj}-{noun:+activity}-{verb:+act}
```

**Example Output:**
```
stable-process-execute
efficient-system-generate
reliable-platform-operate
```

**Use Cases:**
- Feature flags
- Configuration keys
- System toggles
- A/B test identifiers

**Capacity:** ~3B unique flags

[**Try in Playground →**](/playground?pattern={adjective:+obj}-{noun:+activity}-{verb:+act})

## Developer Tools

### Git Branch Names

**Pattern:**
```
feature/{adjective}-{noun:+activity}
```

**Example Output:**
```
feature/brilliant-refactor
feature/cosmic-optimization
feature/elegant-implementation
```

**Use Cases:**
- Feature branches
- Development workflows
- PR identifiers
- Release branches

**Capacity:** ~45M unique branches

[**Try in Playground →**](/playground?pattern=feature/{adjective}-{noun:+activity})

---

### Release Tags

**Pattern:**
```
v{number:1d}.{number:2d}-{adjective:+obj}
```

**Example Output:**
```
v2.14-stable
v3.07-reliable
v1.95-efficient
```

**Use Cases:**
- Version tags
- Release identifiers
- Build numbers
- Deployment tags

**Capacity:** 900K+ unique tags

[**Try in Playground →**](/playground?pattern=v{number:1d}.{number:2d}-{adjective:+obj})

---

### Test Data IDs

**Pattern:**
```
test-{adjective}-{noun}-{number:4x}
```

**Example Output:**
```
test-typical-data-3a2f
test-standard-case-b7d4
test-regular-scenario-c1e9
```

**Use Cases:**
- Test identifiers
- Mock data
- Fixture names
- Test scenarios

**Capacity:** ~11T unique IDs

[**Try in Playground →**](/playground?pattern=test-{adjective}-{noun}-{number:4x})

---

### CI/CD Pipeline Names

**Pattern:**
```
{verb:+act}-{noun:+activity}-pipeline
```

**Example Output:**
```
execute-deployment-pipeline
process-integration-pipeline
manage-testing-pipeline
```

**Use Cases:**
- CI/CD pipelines
- Build workflows
- Deployment processes
- Automation jobs

**Capacity:** ~3.3M unique pipelines

[**Try in Playground →**](/playground?pattern={verb:+act}-{noun:+activity}-pipeline)

## Data & Analytics

### Dataset Names

**Pattern:**
```
{adjective:+obj}-{noun:+information}-{number:6d}
```

**Example Output:**
```
typical-dataset-284719
standard-metrics-910265
regular-analytics-567384
```

**Use Cases:**
- Dataset identifiers
- Data collections
- Analytics tables
- Data warehouse naming

**Capacity:** ~8T unique names

[**Try in Playground →**](/playground?pattern={adjective:+obj}-{noun:+information}-{number:6d})

---

### Report IDs

**Pattern:**
```
RPT-{adjective:+obj<8}-{number:6x}
```

**Example Output:**
```
RPT-typical-3a2f4b
RPT-standard-b7d4e1
RPT-regular-c1e9a3
```

**Use Cases:**
- Report identifiers
- Analytics dashboards
- Export files
- BI tool references

**Capacity:** ~134B unique IDs

[**Try in Playground →**](/playground?pattern=RPT-{adjective:+obj<8}-{number:6x})

---

### ETL Job Names

**Pattern:**
```
{verb:+change}-{noun:+information}-job
```

**Example Output:**
```
transform-dataset-job
convert-metrics-job
process-analytics-job
```

**Use Cases:**
- ETL processes
- Data pipelines
- Batch jobs
- Scheduled tasks

**Capacity:** ~350K unique jobs

[**Try in Playground →**](/playground?pattern={verb:+change}-{noun:+information}-job)

## Marketing & Content

### Campaign Identifiers

**Pattern:**
```
{adjective:+pos+emo}-{number:4x}
```

**Example Output:**
```
delightful-3a2f
joyful-b7d4
wonderful-c1e9
```

**Use Cases:**
- Marketing campaigns
- Email tracking
- Ad campaign codes
- UTM parameters

**Capacity:** ~65K unique codes

[**Try in Playground →**](/playground?pattern={adjective:+pos+emo}-{number:4x})

---

### Content Slugs

**Pattern:**
```
{adjective:+emo}-{noun:+content}
```

**Example Output:**
```
passionate-article
loving-story
joyful-guide
```

**Use Cases:**
- Content management
- Media libraries
- Editorial systems
- Publishing platforms

**Capacity:** ~3M unique slugs

[**Try in Playground →**](/playground?pattern={adjective:+emo}-{noun:+content})

---

### Event Names

**Pattern:**
```
{adjective:+pos}-{noun:+event}-{number:2d}
```

**Example Output:**
```
brilliant-conference-24
excellent-summit-19
wonderful-meetup-07
```

**Use Cases:**
- Event identifiers
- Conference codes
- Meetup slugs
- Webinar IDs

**Capacity:** ~71M unique names

[**Try in Playground →**](/playground?pattern={adjective:+pos}-{noun:+event}-{number:2d})

## Mobile & Gaming

### Session IDs

**Pattern:**
```
{adjective}-{noun}-{number:6x}
```

**Example Output:**
```
brilliant-session-3a2f4b
cosmic-game-b7d4e1
elegant-match-c1e9a3
```

**Use Cases:**
- Game sessions
- Match identifiers
- Play sessions
- User instances

**Capacity:** ~11P unique IDs

[**Try in Playground →**](/playground?pattern={adjective}-{noun}-{number:6x})

---

### Achievement Codes

**Pattern:**
```
{adjective:+pos}-{noun:+activity}-{number:3X}
```

**Example Output:**
```
brilliant-victory-A4F
excellent-achievement-B7D
wonderful-triumph-C2A
```

**Use Cases:**
- Game achievements
- Reward codes
- Badge identifiers
- Trophy systems

**Capacity:** ~181M unique codes

[**Try in Playground →**](/playground?pattern={adjective:+pos}-{noun:+activity}-{number:3X})

---

### Level Names

**Pattern:**
```
{NOUN:+location}-{adjective:+obj}-{number:2d}
```

**Example Output:**
```
DUNGEON-stable-01
FORTRESS-reliable-14
CASTLE-efficient-07
```

**Use Cases:**
- Game levels
- Stage identifiers
- Map names
- Zone codes

**Capacity:** ~880K unique names

[**Try in Playground →**](/playground?pattern={NOUN:+location}-{adjective:+obj}-{number:2d})

## IoT & Hardware

### Device IDs

**Pattern:**
```
{noun:+device}-{adjective:+obj}-{number:8x}
```

**Example Output:**
```
sensor-stable-3a2f4b5c
router-reliable-b7d4e1f2
gateway-efficient-c1e9a3d8
```

**Use Cases:**
- IoT device IDs
- Hardware identifiers
- Sensor networks
- Edge devices

**Capacity:** ~29T unique IDs

[**Try in Playground →**](/playground?pattern={noun:+device}-{adjective:+obj}-{number:8x})

---

### Firmware Versions

**Pattern:**
```
{noun:+device}-fw-{number:2d}.{number:2d}.{number:3x}
```

**Example Output:**
```
sensor-fw-02.14.3a2
router-fw-03.07.f7d
gateway-fw-01.95.b4c
```

**Use Cases:**
- Firmware versions
- Software releases
- Update identifiers
- Patch numbers

**Capacity:** ~4.3B unique versions

[**Try in Playground →**](/playground?pattern={noun:+device}-fw-{number:2d}.{number:2d}.{number:3x})

## Security & Compliance

### API Keys (Public Identifiers)

**Pattern:**
```
sk_{adjective:+obj}__{number:16x}
```

**Example Output:**
```
sk_stable__3a2f4b5c6d7e8f9a
sk_reliable__b7d4e1f2g3h4i5j6
sk_efficient__c1e9a3d8b2f7e4k1
```

**Use Cases:**
- API key prefixes
- Token identifiers
- Access keys
- Secret prefixes

**Note:** Add cryptographic randomness for actual security

[**Try in Playground →**](/playground?pattern=sk_{adjective:+obj}__{number:16x})

---

### Audit Log IDs

**Pattern:**
```
AUDIT-{adjective:+obj}-{number:10x}
```

**Example Output:**
```
AUDIT-typical-3a2f4b5c6d
AUDIT-standard-b7d4e1f2g3
AUDIT-regular-c1e9a3d8b2
```

**Use Cases:**
- Audit trails
- Compliance logs
- Security events
- Access records

**Capacity:** ~17T unique IDs

[**Try in Playground →**](/playground?pattern=AUDIT-{adjective:+obj}-{number:10x})

## Pattern Design Tips

### Start Simple, Add Complexity

**Evolution:**
```
{adjective}-{noun}                     → Simple start
{adjective:+pos}-{noun}                → Add filtering
{adjective:+pos<8}-{noun:+tech}        → Add constraints
{Adjective:+pos<8}-{NOUN:+tech}-{number:2x}  → Full control
```

### Balance Readability & Capacity

**High Readability (Lower Capacity):**
```
{adjective:+pos<6}-{noun:+animal<8}
→ ~100K unique, very readable
```

**Balanced:**
```
{adjective:+pos}-{noun:+animal}-{number:2x}
→ ~43M unique, still readable
```

**High Capacity:**
```
{adjective}-{noun}-{verb}-{number:6x}
→ Trillions unique, less readable
```

### Test Before Production

Always test patterns in the playground:

1. Generate 20-50 samples
2. Check for appropriate tone
3. Verify length constraints
4. Test capacity with pattern-info

### Use Appropriate Separators

**Hyphens (most readable):**
```
{adjective}-{noun}
```

**Underscores (code-friendly):**
```
{adjective}_{noun}
```

**Slashes (hierarchical):**
```
{category}/{adjective}-{noun}
```

**Dots (domain-style):**
```
{adjective}.{noun}.{env}
```

## Next Steps

**Learn More:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Foundation concepts
- [Advanced Pattern Features](pattern-advanced-features) - Complex techniques
- [Dictionary Reference](pattern-dictionary-reference) - Available words and tags
- [Performance Optimization](pattern-performance-optimization) - Capacity planning

**Try Patterns:**
- [Interactive Playground](/playground) - Test any pattern live
- [Forge Endpoint](api-reference) - Generate via API
- [Mint Endpoint](api-reference) - Production generation

**Get Started:**
- [Quickstart Guide](developer-quickstart-guide) - First API call
- [Core Concepts](developer-core-concepts) - Understanding SlugKit


---

# Pattern Dictionary Reference
Source: https://dev.slugkit.dev/docs/pattern-dictionary-reference

# Dictionary Reference

Complete reference for SlugKit's word dictionaries, tags, and filtering options. Use this guide to discover available words and design patterns that match your brand voice and requirements.

## Overview

SlugKit provides rich dictionaries of carefully curated words across multiple categories. Each dictionary includes semantic tagging for precise filtering, allowing you to create identifiers that perfectly match your tone and context.

**Dictionary counts are approximate** and grow over time as we expand our vocabularies and add new languages.

## Available Dictionaries

### English Dictionaries

| Dictionary | Count | Description | Example Words |
|------------|-------|-------------|---------------|
| **noun** | ~40,000+ | Common and technical nouns | telescope, framework, algorithm, mountain |
| **adjective** | ~17,000+ | Descriptive adjectives | brilliant, cosmic, elegant, swift |
| **verb** | ~8,000+ | Action and state verbs | generate, create, transform, execute |
| **adverb** | ~3,500+ | Manner and degree adverbs | quickly, gently, boldly, clearly |

### Specialized Dictionaries

| Dictionary | Count | Description | Example Words |
|------------|-------|-------------|---------------|
| **domain** | ~9,000+ | Domain name components | example, api, app, dev, cloud |
| **shell** | ~2,000+ | Shell and command names | bash, zsh, fish, powershell, grep |
| **emoji** | ~1,200+ | Unicode emoji characters | 😀, 🚀, 💡, ⭐, 🎨 |

**Note:** Dictionary sizes are approximate and will increase as we continue to expand our vocabularies.

## Querying Dictionary Information

Use the dictionary info endpoint to get current counts:

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/dictionary-info \
  -H "X-API-Key: sk_live_..."
```

**Response:**
```json
[
  {
    "kind": "noun",
    "language": "en",
    "count": 41469
  },
  {
    "kind": "adjective",
    "language": "en",
    "count": 17082
  }
]
```

## Tag System

Tags provide semantic filtering to control tone, context, and appropriateness of generated words.

### Tag Types

**Tone Tags:**
- Control emotional quality (positive, negative, neutral)
- Filter by objectivity vs subjectivity
- Select emotional vs detached language

**Context Tags:**
- Category-specific tags (tech, nature, fantasy)
- Domain-specific terminology
- Semantic groupings

**Safety Tags:**
- NSFW filtering (opt-in only)
- Professional vs casual language
- Family-friendly content control

### Discovering Tags

Use the dictionary tags endpoint to explore available tags:

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/dictionary-tags?kind=adjective \
  -H "X-API-Key: sk_live_..."
```

**Response:**
```json
{
  "data": [
    {
      "kind": "adjective",
      "tag": "pos",
      "description": "Positive word",
      "opt_in": false,
      "word_count": 710
    },
    {
      "kind": "adjective",
      "tag": "nsfw",
      "description": "Obscene or offensive word",
      "opt_in": true,
      "word_count": 35
    }
  ]
}
```

## Adjective Dictionary

Descriptive words for qualities, states, and characteristics.

**Approximate size:** ~17,000+ words

### Common Tags

#### Tone & Emotion

| Tag | Description | ~Word Count | Opt-In | Example Words |
|-----|-------------|-------------|--------|---------------|
| `det` | Detached, neutral | ~14,000+ | No | standard, typical, regular |
| `obj` | Objective, factual | ~8,000+ | No | numeric, physical, measurable |
| `neut` | Neutral tone | ~6,500+ | No | average, medium, moderate |
| `emo` | Emotional, expressive | ~3,000+ | No | loving, angry, joyful |
| `pos` | Positive sentiment | ~700+ | No | brilliant, excellent, wonderful |
| `neg` | Negative sentiment | ~1,400+ | No | broken, failed, poor |
| `nsfw` | Inappropriate content | ~35+ | **Yes** | [filtered by default] |

### Usage Examples

**Positive, family-friendly:**
```
{adjective:+pos-nsfw}
→ brilliant, excellent, wonderful
```

**Professional, objective:**
```
{adjective:+obj+det-emo}
→ standard, typical, measurable
```

**Emotional, non-negative:**
```
{adjective:+emo-neg}
→ joyful, loving, passionate
```

## Noun Dictionary

Objects, concepts, places, and entities.

**Approximate size:** ~40,000+ words

### Common Tags

#### Core Categories

| Tag | Description | ~Word Count | Opt-In | Example Words |
|-----|-------------|-------------|--------|---------------|
| `det` | Detached concepts | ~39,000+ | No | object, system, structure |
| `obj` | Objective nouns | ~27,000+ | No | table, computer, building |
| `neut` | Neutral terms | ~13,000+ | No | thing, item, element |
| `object` | Physical objects | ~19,000+ | No | keyboard, telescope, chair |
| `emo` | Emotional concepts | ~2,000+ | No | love, anger, joy |
| `pos` | Positive concepts | ~400+ | No | success, achievement, victory |
| `neg` | Negative concepts | ~850+ | No | failure, loss, defeat |
| `nsfw` | Inappropriate terms | ~170+ | **Yes** | [filtered by default] |

#### Semantic Categories

| Tag | Description | ~Word Count | Example Words |
|-----|-------------|-------------|---------------|
| `artifact` | Man-made objects | ~6,800+ | tool, device, machine |
| `event` | Events & occurrences | ~6,600+ | conference, celebration, meeting |
| `person` | People & roles | ~6,300+ | developer, designer, engineer |
| `activity` | Actions & processes | ~2,700+ | programming, design, testing |
| `animal` | Animals & creatures | ~2,400+ | dragon, phoenix, eagle |
| `substance` | Materials & substances | ~2,400+ | metal, plastic, wood |
| `device` | Technical devices | ~1,700+ | computer, server, router |
| `location` | Places & spaces | ~880+ | office, datacenter, cloud |
| `food` | Food & beverages | ~830+ | coffee, tea, pizza |
| `feeling` | Emotions & feelings | ~680+ | happiness, excitement, calm |
| `vehicle` | Transportation | ~200+ | car, server, transport |
| `music` | Musical terms | ~250+ | symphony, melody, rhythm |
| `building` | Structures | ~230+ | tower, office, datacenter |
| `machine` | Machines & engines | ~140+ | processor, engine, compiler |
| `furniture` | Furniture items | ~100+ | desk, chair, table |
| `art` | Artistic concepts | ~60+ | design, painting, sculpture |
| `fantasy` | Fantasy concepts | ~60+ | dragon, wizard, magic |
| `plant` | Plants & vegetation | ~25+ | tree, flower, forest |

### Usage Examples

**Technology-focused:**
```
{noun:+artifact+device}
→ computer, server, framework
```

**Nature & animals:**
```
{noun:+animal+plant}
→ dragon, eagle, forest, mountain
```

**Professional context:**
```
{noun:+person+activity-nsfw}
→ developer, designer, programming
```

**Emotional & positive:**
```
{noun:+emo+pos-neg}
→ joy, success, achievement
```

## Verb Dictionary

Actions, states, and processes.

**Approximate size:** ~8,000+ words

### Common Tags

#### Core Categories

| Tag | Description | ~Word Count | Opt-In | Example Words |
|-----|-------------|-------------|--------|---------------|
| `det` | Detached actions | ~8,000+ | No | process, execute, function |
| `obj` | Objective actions | ~5,700+ | No | measure, calculate, define |
| `neut` | Neutral actions | ~2,600+ | No | move, change, use |
| `change` | Transformation verbs | ~2,600+ | No | transform, convert, modify |
| `act` | Action-oriented | ~1,200+ | No | execute, perform, operate |
| `travel` | Movement verbs | ~460+ | No | navigate, traverse, journey |
| `emo` | Emotional verbs | ~230+ | No | love, fear, celebrate |
| `be` | State of being | ~220+ | No | exist, remain, stay |
| `have` | Possession | ~120+ | No | possess, own, hold |
| `pos` | Positive actions | ~40+ | No | succeed, achieve, win |
| `neg` | Negative actions | ~80+ | No | fail, break, lose |
| `destroy` | Destructive actions | ~30+ | No | delete, remove, destroy |
| `imagine` | Creative thinking | ~20+ | No | imagine, design, create |
| `make` | Creation | ~5+ | No | make, build, construct |
| `create` | Creative actions | ~2+ | No | create, generate, design |
| `nsfw` | Inappropriate actions | ~50+ | **Yes** | [filtered by default] |

### Usage Examples

**Action-oriented, professional:**
```
{verb:+act+obj-emo}
→ execute, perform, process
```

**Transformation & change:**
```
{verb:+change-destroy}
→ transform, convert, evolve
```

**Creative & positive:**
```
{verb:+create+imagine+pos}
→ design, innovate, achieve
```

## Adverb Dictionary

Manner, degree, and modification words.

**Approximate size:** ~3,500+ words

### Common Tags

Adverbs use similar tone tags to adjectives:

| Tag | Description | Example Words |
|-----|-------------|---------------|
| `det` | Detached manner | typically, usually, normally |
| `obj` | Objective manner | precisely, exactly, accurately |
| `neut` | Neutral manner | simply, merely, barely |
| `emo` | Emotional manner | passionately, angrily, joyfully |
| `pos` | Positive manner | excellently, brilliantly, wonderfully |
| `neg` | Negative manner | poorly, badly, terribly |

### Usage Examples

**Professional & objective:**
```
{adverb:+obj+det}
→ precisely, accurately, systematically
```

**Quick & efficient:**
```
{adverb:+pos-emo}
→ quickly, efficiently, swiftly
```

## Domain Dictionary

Domain name components and web-related terms.

**Approximate size:** ~9,000+ words

**Characteristics:**
- Web-friendly words
- Short, memorable components
- Common TLD keywords
- API and cloud terminology

**Example words:**
```
api, app, dev, cloud, web, data, hub, io, 
example, demo, test, prod, staging
```

**Usage:**
```
{domain}
→ api, cloud, framework, hub

{domain}-{noun}
→ api-gateway, cloud-database, dev-environment
```

## Shell Dictionary

Command-line shells, tools, and utilities.

**Approximate size:** ~2,000+ words

**Characteristics:**
- Unix/Linux commands
- Shell names
- Common CLI tools
- System utilities

**Example words:**
```
bash, zsh, fish, powershell, grep, sed, awk,
git, docker, kubectl, terraform, ansible
```

**Usage:**
```
{shell}
→ bash, docker, kubectl

{shell}-{noun}
→ docker-container, kubectl-pod, git-repository
```

## Emoji Dictionary

Unicode emoji characters for visual distinctiveness.

**Approximate size:** ~1,200+ characters

**Categories include:**
- Smileys & emotion
- People & body
- Animals & nature
- Food & drink
- Travel & places
- Activities & events
- Objects & symbols
- Technology

**Example emojis:**
```
😀 🚀 💡 ⭐ 🎨 🔧 📝 🌟 💻 🎯
```

**Usage:**
```
{emoji}
→ 🚀, 💡, ⭐

{emoji}-{noun}
→ 🚀-launch, 💡-idea, ⭐-feature
```

**Note:** Emoji support depends on the target system's Unicode rendering capabilities.

## Opt-In Tags

Some tags are **opt-in only** - words with these tags are excluded by default and must be explicitly requested.

### NSFW Tag

**Tag:** `nsfw`  
**Description:** Obscene, offensive, or inappropriate content  
**Opt-in:** Required  
**Available in:** adjective, noun, verb

**Default behavior:**
```
{adjective}
→ Excludes NSFW words automatically
```

**Explicit inclusion:**
```
{adjective:+nsfw}
→ Includes NSFW words (use with caution)
```

**Explicit exclusion (redundant):**
```
{adjective:-nsfw}
→ Excludes NSFW words (same as default)
```

**Use cases for opt-in:**
- Internal tools where appropriate
- Adult-oriented applications
- Testing filtering systems

**Best practices:**
- Never use NSFW tags for user-facing identifiers
- Always exclude for professional environments
- Document clearly when NSFW content is included
- Consider legal and policy implications

## Multi-Language Support (Future)

SlugKit is designed to support multiple languages. Currently, English (`@en`) is the primary language for most dictionaries.

**Future language support:**
```
{adjective@es}-{noun@es}    → Spanish
{adjective@fr}-{noun@fr}    → French
{adjective@de}-{noun@de}    → German
{adjective@ja}-{noun@ja}    → Japanese
```

**Current usage:**
```
{adjective@en}-{noun@en}    → English (default)
{adjective}-{noun}          → English (language optional)
```

## Pattern Design Guidelines

### Choosing Dictionaries

**User-facing identifiers:**
```
{adjective:+pos}-{noun:+object}
→ brilliant-telescope, cosmic-keyboard
```

**Technical resources:**
```
{adjective:+obj}-{noun:+device+machine}
→ stable-server, efficient-processor
```

**Creative projects:**
```
{adjective:+emo+pos}-{noun:+fantasy+art}
→ passionate-dragon, joyful-painting
```

**API endpoints:**
```
{verb:+act}/{noun:+device}
→ execute/processor, generate/compiler
```

### Balancing Specificity

**Too specific (low capacity):**
```
{adjective:+pos+emo==5}-{noun:+fantasy==7}
→ Very few matching words, limited capacity
```

**Balanced (good capacity & tone):**
```
{adjective:+pos<10}-{noun:+nature<12}
→ Good variety, reasonable constraints
```

**Too broad (may include unwanted words):**
```
{adjective}-{noun}
→ Maximum capacity but inconsistent tone
```

### Testing Tag Combinations

Always test tag combinations before production:

```bash
# Test tag combination
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective:+pos+emo-neg}-{noun:+nature}",
    "count": 20
  }'
```

Review the results to ensure they match your expectations.

## Advanced Filtering Techniques

### Tag Intersection

Require multiple tags (AND logic):

```
{adjective:+pos+emo}
→ Words that are BOTH positive AND emotional
→ joyful, delightful, wonderful
```

### Tag Union (via separate selectors)

Get words from different tag groups:

```
{adjective:+pos}-{adjective:+emo}
→ First word positive, second emotional
→ brilliant-passionate, excellent-loving
```

### Complex Exclusions

Exclude multiple unwanted categories:

```
{noun:+object-nsfw-neg-emo}
→ Physical objects, exclude inappropriate, negative, emotional
→ Clean, neutral, objective nouns
```

### Hierarchical Filtering

Layer filters from broad to specific:

```
{adjective:+det+obj-nsfw<8}
→ Detached AND objective, exclude NSFW, max 7 chars
→ Highly refined selection
```

## Tag Performance Considerations

**Filtering impact:**
- Single tag: Minimal performance impact (<5%)
- Multiple tags: Still fast (<10% slower)
- Complex combinations: Slight reduction in capacity

**Optimization tips:**
- Use tags to improve quality, not just reduce size
- Test capacity impact with pattern-info endpoint
- Balance specificity with variety
- Document tag choices for maintainability

## Best Practices

### Always Exclude NSFW

For user-facing content:
```
{adjective:-nsfw}-{noun:-nsfw}
```

Or rely on defaults (NSFW excluded automatically):
```
{adjective}-{noun}
```

### Match Brand Voice

**Professional:**
```
{adjective:+obj+det}-{noun:+device+machine}
```

**Friendly:**
```
{adjective:+pos+emo}-{noun:+object}
```

**Technical:**
```
{adjective:+obj}-{noun:+device}-{verb:+act}
```

### Test Tag Compatibility

Some tag combinations may have few or no matching words:

```
{adjective:+pos+neg}
→ No words are both positive AND negative
```

Always test combinations:
```bash
curl -X GET https://api.slugkit.com/api/v1/gen/dictionary-tags?kind=adjective
```

### Document Your Choices

```python
# User handle pattern
# Tags: positive (friendly), no NSFW (safe)
# Length: mobile-friendly
PATTERN = "{adjective:+pos-nsfw<8}-{noun:+nature<10}"

# Tech resource pattern  
# Tags: objective (professional), technical focus
# No emotional or negative words
PATTERN = "{adjective:+obj-emo-neg}-{noun:+device+machine}"
```

## API Integration

### Dictionary Info Endpoint

Get current dictionary sizes:

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/dictionary-info \
  -H "X-API-Key: sk_live_..."
```

### Dictionary Tags Endpoint

List all tags for a dictionary:

```bash
curl -X GET https://api.slugkit.com/api/v1/gen/dictionary-tags?kind=noun&limit=100 \
  -H "X-API-Key: sk_live_..."
```

**Query parameters:**
- `kind`: Dictionary type (noun, adjective, verb, etc.)
- `limit`: Maximum tags to return (default: 100)
- `offset`: Pagination offset (default: 0)

### Pattern Validation

Test patterns with tags:

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/pattern-info \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective:+pos<8}-{noun:+nature<10}"
  }'
```

## Next Steps

**Pattern Design:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Foundation concepts
- [Advanced Pattern Features](pattern-advanced-features) - Complex filtering and case transformations
- [Pattern Cookbook](pattern-cookbook) - Real-world examples
- [Performance Optimization](pattern-performance-optimization) - Capacity planning

**API Reference:**
- [Forge Endpoint](api-reference) - Test patterns with tags
- [Validation Endpoints](api-reference) - Analyze tag combinations
- [Mint Endpoint](api-reference) - Use patterns in production

**Fundamentals:**
- [Core Concepts](developer-core-concepts) - Understanding SlugKit
- [Quickstart Guide](developer-quickstart-guide) - Get started in 5 minutes


---

# Pattern Performance Optimization
Source: https://dev.slugkit.dev/docs/pattern-performance-optimization

# Pattern Performance Optimization

*Master capacity planning, pattern efficiency, and production-ready strategies for high-performance slug generation*

---

## Overview

SlugKit's pattern system delivers sub-millisecond generation times, but pattern design significantly impacts both performance and capacity. This guide covers mathematical optimization strategies, capacity planning, and production deployment patterns that scale from thousands to billions of unique identifiers.

## Understanding Pattern Capacity

### Capacity Calculation Fundamentals

SlugKit calculates pattern capacity using the **Least Common Multiple (LCM)** of all component capacities, ensuring complete pattern element cycling without premature repetition.

```bash
# Example: {adjective}-{noun}-{number:2x}
# Adjectives: 17,082 words
# Nouns: 41,469 words  
# 2-digit hex: 256 (16²)
# Actual capacity: 90.67B unique slugs (verified via analyze endpoint)
```

### Component Capacity Reference

**Dictionary Components (Verified):**
- `{adjective}`: 17,082 words
- `{noun}`: 41,469 words
- `{verb}`: 8,405 words
- `{adverb}`: 3,619 words
- `{domain}`: 9,183 words
- `{shell}`: 2,137 words
- `{emoji}`: 1,200 words

**Tag-Filtered Components (Examples):**
- `{noun:+animal}`: 2,437 words
- `{noun:+person}`: 6,273 words
- `{adjective:+pos}`: 710 words
- `{adjective:+neg}`: 1,395 words
- `{noun:+food}`: 826 words

**Number Components:**
- `{number:1d}`: 10 (0-9)
- `{number:2d}`: 100 (00-99)
- `{number:3d}`: 1,000 (000-999)
- `{number:2x}`: 256 (00-FF)
- `{number:3x}`: 4,096 (000-FFF)
- `{number:4x}`: 65,536 (0000-FFFF)

**Special Character Components:**
- `{special:1}`: 32 characters
- `{special:2}`: 1,024 combinations
- `{special:1-3}`: 35,840 combinations

### Prime Optimization

SlugKit automatically optimizes capacity calculations using mathematical algorithms that maximize unique combinations whilst maintaining efficient generation patterns.

## Performance Characteristics

### Generation Speed by Method

**Mint/Slice Operations:**
- Single slug: 3-20μs
- Bulk operations: Improved per-slug performance
- Pattern complexity impact: Minimal for compiled patterns

**Forge Operations:**
- Simple patterns: 50-200μs per slug
- Complex patterns: 200-1000μs per slug
- Seed generation overhead: 10-50μs (one-time per request)

### Pattern Complexity Scoring

SlugKit uses internal complexity scoring for rate limiting:

**Base Costs:**
- Dictionary selector: 10 points
- Number generator: 5 points
- Special character generator: 8 points

**Multipliers:**
- Tag filtering: ×1.5 per include/exclude tag
- Length constraints: ×1.2
- Case transformations: ×1.1
- Global modifiers: ×1.3

```bash
# Example complexity calculation:
# {adjective:+pos-neg<8}-{noun}-{number:3x}
# = (10 × 1.5 × 1.5 × 1.2) + 10 + 5 = 42 complexity points
```

## Optimization Strategies

### 1. Maximize Capacity Efficiency

**Use Components with Different Scales:**
```bash
# Good: Large dictionary + smaller filtered subset + numbers
{adjective}-{noun:+animal}-{number:2x}    # 17K × 2.4K × 256 = ~10B capacity

# Avoid: Multiple large unfiltered dictionaries
{adjective}-{noun}-{verb}                  # Extremely large capacity, slow generation
```

**Layer Different Component Types:**
```bash
# Excellent capacity utilization
{noun}-{number:3d}                         # ~41K × 1K = ~41M capacity

# Good: Filtered dictionary combinations
{adjective:+pos}-{noun:+person}            # ~710 × 6.3K = ~4.5M capacity
```

### 2. Optimize for Performance

**Fast Pattern Design:**
```bash
# Fastest: Simple dictionary + number
{noun}-{number:3x}

# Fast: No filtering or constraints
{adjective}-{verb}

# Slower: Multiple filters and constraints
{adjective:+pos-neg<6}-{noun:+animal>4}
```

**Avoid Performance Antipatterns:**
```bash
# Slow: Excessive filtering
{noun:+animal+person+food-nsfw<5>8}

# Slow: Multiple special characters
{adjective}-{special:2-4}-{noun}-{special:1-3}

# Slow: Complex global modifiers
{adjective}-{noun}[@en:+pos-neg<6]
```

### 3. Balance Aesthetics and Efficiency

**Production-Ready Patterns:**
```bash
# User handles: Great balance of memorability and capacity
{adjective}-{noun:+animal}-{number:2d}     # ~4.4B capacity (17K × 2.4K × 100)

# API endpoints: Fast generation, thematic consistency
{verb}-{noun}                              # ~348M capacity (8.4K × 41K)

# Product SKUs: Business-friendly, deterministic
{adjective:+pos}-{number:3X}               # ~2.9M capacity (710 × 4K)
```

## Capacity Planning

### Verified Pattern Capacities

**Real-World Examples (Using analyze endpoint):**
```bash
# Basic patterns
{adjective}-{noun}                         # ~700M capacity
{noun:+animal}-{adjective}                 # ~41.6M capacity (verified)
{adjective}-{noun}-{number:2x}             # ~90.7B capacity (verified)

# Themed patterns
{adjective:+pos}-{noun:+person}            # ~4.5M capacity (verified: 8.75M)
{adjective:+pos}-{noun:+animal}            # ~1.7M capacity (verified)
{adjective:+neg}-{noun:+person}            # ~8.8M capacity (verified)
{emoji}-{noun:+animal}                     # ~2.9M capacity
```

**Application Scale Planning:**
```bash
# Startup (1M+ users): 10M-100M capacity needed
{noun:+animal}-{adjective}                 # 41.6M capacity ✓

# Growth Stage (10M+ users): 100M-1B capacity needed  
{adjective}-{noun}                         # 700M capacity ✓

# Enterprise (100M+ users): 1B+ capacity needed
{adjective}-{noun}-{number:2x}             # 90.7B capacity ✓
```

**Use Case Capacity Guidelines:**

| Use Case | Recommended Capacity | Example Pattern | Verified Capacity |
|----------|---------------------|-----------------|-------------------|
| Blog URLs | 1M-10M | `{adjective:+pos}-{noun:+object}` | ~TBD |
| User Handles | 10M-1B | `{noun:+animal}-{adjective}-{number:1d}` | ~416M |
| API Endpoints | 1K-100K | `{verb}-{noun}` | ~348M |
| Product SKUs | 100K-10M | `{adjective:+pos}-{number:3X}` | ~2.9M |
| Server Names | 1K-100K | `{adjective}-{noun:+device}` | ~28.6M |
| Session IDs | 1B+ | `{adjective}-{noun}-{number:3x}` | ~2.9T |

### Series vs Forge Strategy

**When to Use Series (Mint/Slice):**
- Need guaranteed uniqueness
- High-volume production workloads
- Distributed generation requirements
- Performance-critical applications

**When to Use Forge:**
- Themed or branded identifiers
- Testing and development
- Reproducible identifier sets
- Campaign-specific naming

## Production Deployment Patterns

### 1. High-Volume Applications

**Pattern Design:**
```bash
# Optimized for speed and capacity
{noun}-{number:4x}                         # Simple, fast, ~2.7B capacity
```

**Architecture:**
- Use dedicated series per application component
- Implement client-side caching for bulk operations
- Monitor capacity utilization via analytics endpoints

### 2. Multi-Tenant Systems

**Pattern Strategy:**
```bash
# Tenant isolation via series naming
# Series: "tenant-{tenant_id}-users"
# Pattern: {adjective}-{noun:+person}-{number:2d}
```

**Scaling Considerations:**
- Separate series per tenant for isolation
- Shared patterns with tenant-specific seeds
- Capacity monitoring per tenant

### 3. Distributed Microservices

**Service-Specific Patterns:**
```bash
# User service: Memorable handles
{adjective:+pos}-{noun:+animal}

# Order service: Business-friendly IDs  
{adjective:+pos}-{number:4X}

# Session service: High-entropy IDs
{adjective}-{noun}-{number:3x}
```

**Coordination Strategy:**
- Service-specific series for isolation
- Slice operations for preview/coordination
- Centralized capacity monitoring

## Monitoring and Analytics

### Key Metrics to Track

**Capacity Utilization:**
```bash
# Monitor via series analytics
current_position / total_capacity * 100
```

**Performance Metrics:**
- Generation latency (p50, p95, p99)
- Pattern compilation time
- Request rate vs capacity consumption

**Operational Metrics:**
- Series rotation frequency
- Pattern complexity distribution
- Error rates by pattern type

### Capacity Alerts

**Recommended Alert Thresholds:**
- 70% capacity: Planning alert
- 85% capacity: Warning alert  
- 95% capacity: Critical alert

**Mitigation Strategies:**
- Pattern complexity reduction
- Additional number components
- Series rotation planning
- Capacity expansion via new series

## Advanced Optimization Techniques

### 1. Pattern Compilation Caching

**Series Benefits:**
- One-time pattern compilation cost
- Amortized across millions of generations
- Optimal for production workloads

**Forge Optimization:**
- Cache compiled patterns client-side
- Reuse patterns across requests
- Batch operations when possible

### 2. Capacity Modeling

**Mathematical Analysis:**
```bash
# Use SlugKit's analyze endpoint for precise calculations
POST /api/analyze
{
  "pattern": "{adjective:+pos}-{noun:+animal}-{number:2d}",
  "include_capacity": true
}
```

**Growth Projections:**
- Model capacity consumption rates
- Plan series rotations in advance
- Design patterns for future scale

### 3. Performance Profiling

**Pattern Benchmarking:**
```bash
# Compare pattern performance
POST /api/compare
{
  "patterns": [
    "{adjective}-{noun}",
    "{adjective}-{noun}-{number:1d}",
    "{adjective:+pos}-{noun:+animal}"
  ],
  "count_per_pattern": 100
}
```

## Best Practices Summary

### ✅ Do

- **Verify capacity**: Use the analyze endpoint to confirm pattern capacity
- **Design for scale**: Choose patterns with capacity 10× your expected needs
- **Optimize early**: Use simple patterns for high-volume applications
- **Monitor capacity**: Track utilization and plan rotations
- **Use series for production**: Guaranteed uniqueness and optimal performance
- **Test pattern performance**: Benchmark before production deployment
- **Use correct tag names**: `+pos`/`+neg`, not `+positive`/`+negative`

### ❌ Don't

- **Assume dictionary availability**: Verify all dictionaries exist
- **Use incorrect tag names**: Check actual tag names (e.g. `+pos` not `+positive`)
- **Over-optimize prematurely**: Balance aesthetics with performance needs
- **Ignore capacity planning**: Running out of unique identifiers breaks systems
- **Use complex patterns for high-volume**: Keep production patterns simple
- **Forget about case sensitivity**: Consider downstream system requirements
- **Mix generation methods**: Use consistent approaches within applications

## Available Dictionaries

SlugKit currently provides these verified dictionaries:

- **adjective** (17,082 words) - with tags like `pos`, `neg`, `emo`, `det`
- **noun** (41,469 words) - with tags like `animal`, `person`, `food`, `device`
- **verb** (8,405 words) - for action-oriented identifiers
- **adverb** (3,619 words) - for descriptive modification
- **domain** (9,183 words) - for web-related patterns
- **shell** (2,137 words) - for system administration
- **emoji** (1,200 symbols) - for modern, visual identifiers

## Key Tag Reference

**Adjective Tags:**
- `+pos`: Positive words (710 words)
- `+neg`: Negative words (1,395 words)
- `+emo`: Emotional words (2,944 words)
- `+det`: Detached/objective words (14,138 words)

**Noun Tags:**
- `+animal`: Animal names (2,437 words)
- `+person`: Person-related words (6,273 words)
- `+food`: Food items (826 words)
- `+device`: Devices and machines (1,673 words)

## Conclusion

SlugKit's pattern system scales from prototype to enterprise through mathematical precision and thoughtful optimization. By understanding actual dictionary availability, correct tag names, and verified capacity calculations, you can design identifier systems that grow with your application whilst maintaining the human-readable aesthetics that make SlugKit unique.

Remember: the best pattern is one that meets your capacity needs, performs well at your scale, and creates identifiers your users actually enjoy reading. Always verify your assumptions using SlugKit's analyze endpoint and use correct tag names like `+pos`/`+neg`.


---

# Pattern Playground - Interactive Slug Generator
Source: https://dev.slugkit.dev/docs/pattern-playground-seo

# Pattern Playground - Interactive Slug Generator

Welcome to SlugKit's Pattern Playground, where you can experiment with our powerful pattern language to create the perfect slugs for your application. This interactive tool demonstrates the flexibility and sophistication of SlugKit's slug generation capabilities.

## What is the Pattern Playground?

The Pattern Playground is an interactive web interface that allows you to:

- **Test patterns in real-time** - See instant results as you modify pattern syntax
- **Explore pattern possibilities** - Discover the full range of SlugKit's pattern language
- **Generate sample slugs** - Create multiple examples to understand pattern behaviour
- **Learn by experimentation** - Perfect for developers learning SlugKit's capabilities

## Key Features

### Live Pattern Testing
Write any SlugKit pattern and immediately see generated results. Perfect for:
- Prototyping slug formats for your application
- Understanding how different pattern elements work together
- Testing edge cases and pattern complexity
- Validating patterns before implementing in production

### Pattern Examples Library
Explore pre-built patterns for common use cases:
- **User handles**: `{adjective}-{noun}-{number:3d}`
- **Product codes**: `{noun:+tech}-{number:4x}`
- **Project names**: `{adjective:+positive}-{noun:+abstract}`
- **API endpoints**: `{verb}/{noun}/{number:2x}`

### Advanced Pattern Features
Experiment with SlugKit's sophisticated pattern language:
- **Dictionary selectors** with language and tag filtering
- **Mathematical case transformations** for unique visual styles
- **Number generators** in multiple formats (decimal, hexadecimal, Roman)
- **Special character integration** for complex identifier schemes
- **Global modifiers** for consistent styling across pattern elements

## Pattern Language Overview

### Basic Syntax
```
{adjective}-{noun}-{number:4d}
```
Generates slugs like: `brilliant-keyboard-2847`

### Advanced Filtering
```
{adjective:+tech-outdated<8}-{noun:+hardware}
```
Uses only tech-related, non-outdated adjectives under 8 characters with hardware nouns.

### Case Transformations
```
{AdJeCtIvE}-{NOUN}-{number:3x}
```
Creates unique mixed-case patterns: `aMaZiNg-DATABASE-f4a`

### Complex Patterns
```
api/v{number:1d}/{verb:+action}/{noun:+data}@{number:2x}
```
Generates API-style identifiers: `api/v2/process/metrics@b3`

## Educational Benefits

### Learn Pattern Syntax
- Understand placeholder structure and syntax rules
- Explore the relationship between pattern complexity and output variety
- Master tag filtering and length constraints
- Discover mathematical case transformation possibilities

### Understand Slug Generation
- See how deterministic generation works with seeds
- Learn about slug uniqueness within series domains
- Explore the relationship between patterns and capacity
- Understand performance implications of different pattern types

### Real-World Applications
- Design slug patterns for your specific use case
- Test patterns with your application's requirements
- Validate accessibility and URL compatibility
- Plan for scale and capacity needs

## Getting Started

1. **Visit the Playground** - Navigate to the interactive pattern editor
2. **Try Basic Patterns** - Start with simple `{adjective}-{noun}` patterns
3. **Add Complexity** - Introduce numbers, filtering, and case transformations
4. **Generate Multiple Examples** - See how patterns behave across many generations
5. **Save Your Favourites** - Keep track of patterns that work for your needs

## Integration with SlugKit Services

The Pattern Playground demonstrates features available across SlugKit's generation methods:

### Forge Function
Perfect for testing custom patterns with specific seeds and counts. The playground shows exactly what you'll get when calling:
```
POST /api/forge
{
  "pattern": "{adjective:+tech}-{noun:+product}",
  "seed": 12345,
  "count": 10
}
```

### Mint Function
Understand how patterns work within series for production applications. See how your patterns will behave in continuous generation scenarios.

### Slice Function
Explore how deterministic range extraction works with your custom patterns. Perfect for distributed systems coordination.

## Best Practices Discovery

Use the playground to discover best practices for your application:

### Performance Optimisation
- Test pattern complexity and generation speed
- Understand capacity implications of different element combinations
- Find the balance between uniqueness and performance

### SEO and Accessibility
- Create URL-friendly patterns that work across platforms
- Test readability and user experience
- Ensure compatibility with various systems and databases

### Brand Consistency
- Develop patterns that reflect your brand voice
- Create consistent naming conventions across your application
- Balance creativity with professionalism

## API Integration Examples

The playground helps you understand how to integrate patterns with SlugKit's API:

```javascript
// Example: Using playground-tested patterns in production
const response = await fetch('/api/mint', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    series: 'user-handles',
    pattern: '{adjective:+positive}-{noun:+person}',
    count: 1
  })
});
```

## Advanced Features

### Mathematical Precision
Explore how SlugKit's mathematical approach to slug generation ensures:
- Predictable capacity calculations
- Uniform distribution across pattern elements
- Deterministic results with seed values
- Scalable generation for enterprise applications

### Linguistic Sophistication
Experiment with:
- Multi-language dictionary support
- Tag-based semantic filtering
- Length constraint optimisation
- Cultural and contextual appropriateness

## Use Cases and Applications

### Web Development
- Generate unique user identifiers
- Create SEO-friendly URL slugs
- Design memorable session tokens
- Build consistent naming schemes

### DevOps and Infrastructure
- Generate deployment identifiers
- Create container and service names
- Design configuration keys and values
- Build readable log identifiers

### API and Microservices
- Generate endpoint identifiers
- Create transaction IDs
- Design queue and topic names
- Build correlation identifiers

### Content Management
- Generate article and page slugs
- Create category and tag identifiers
- Design media file naming
- Build version and revision identifiers

## Technical Implementation

The Pattern Playground showcases SlugKit's technical capabilities:

### High Performance
- Sub-millisecond generation times
- Efficient pattern compilation and caching
- Optimised dictionary lookups
- Scalable concurrent generation

### Enterprise Features
- Series management for guaranteed uniqueness
- Distributed-safe counter management
- Comprehensive rate limiting and quotas
- Advanced pattern complexity controls

### Developer Experience
- Intuitive pattern syntax
- Comprehensive error messages
- Rich API responses with metadata
- Extensive documentation and examples

## Community and Learning

The Pattern Playground serves as:
- **Educational tool** for learning slug generation concepts
- **Experimentation environment** for pattern development
- **Showcase platform** for SlugKit's capabilities
- **Testing ground** for integration planning

## Get Started Today

Ready to explore the full potential of SlugKit's pattern language? Visit the Pattern Playground and start experimenting with patterns that will make your application's identifiers both functional and delightful.

Whether you're building the next great web application, designing a microservices architecture, or creating a content management system, the Pattern Playground will help you discover the perfect slug generation strategy for your needs.


---

# Pattern Syntax Basics
Source: https://dev.slugkit.dev/docs/pattern-syntax-basics

# Pattern Syntax Basics

Master SlugKit's powerful pattern language to create beautiful, human-readable identifiers. This guide covers the fundamentals of pattern construction, from basic placeholders to filtering and constraints.

## What Are Patterns?

Patterns are templates that define the structure and content of your slugs. They combine dictionary words, numbers, special characters, and arbitrary text to create identifiers that are:

- **Human-readable** - Easy to remember and communicate
- **Aesthetically pleasing** - Naturally flowing word combinations
- **Mathematically unique** - Predictable capacity and distribution
- **Flexible** - Adaptable to any naming convention

**Basic pattern:**
```
{adjective}-{noun}
```

**Generated slugs:**
```
brilliant-telescope
cosmic-symphony
elegant-framework
```

## Pattern Structure

Every pattern consists of two types of elements:

### 1. Placeholders

Placeholders wrapped in curly braces `{...}` generate dynamic content:

```
{adjective}    → brilliant, cosmic, elegant
{noun}         → telescope, keyboard, symphony  
{number:3x}    → a4f, b7d, c2a
```

### 2. Arbitrary Text

Any text outside placeholders appears literally in your slugs:

```
user-{noun}              → user-telescope
api/v1/{verb}            → api/v1/generate
config.{adjective}.prod  → config.brilliant.prod
```

**You can use any characters:**
- Letters and numbers: `abc`, `123`
- Separators: `-`, `_`, `.`, `/`, `@`
- Special characters: `!`, `#`, `*`, `%`
- Unicode and emoji: `🚀`, `📝`, `⭐`

## Dictionary Selectors

Dictionary selectors choose words from SlugKit's extensive vocabularies.

### Available Dictionaries

SlugKit includes rich dictionaries for different word types:

| Dictionary | Count | Example Words |
|------------|-------|---------------|
| **adjective** | 17,082 | brilliant, cosmic, elegant, swift |
| **noun** | 41,469 | telescope, keyboard, symphony, framework |
| **verb** | 8,405 | generate, create, transform, execute |
| **adverb** | 3,619 | quickly, gently, clearly, boldly |
| **domain** | 9,183 | example.com, api.dev, app.io |
| **shell** | 2,137 | bash, zsh, fish, powershell |
| **emoji** | 1,200 | 😀, 🚀, 💡, ⭐ |

### Basic Usage

Simply reference a dictionary by name:

```
{adjective}    → brilliant
{noun}         → telescope
{verb}         → generate
{adverb}       → quickly
```

**Common patterns:**
```
{adjective}-{noun}           → brilliant-telescope
{verb}-{noun}                → generate-framework
{adverb}-{adjective}-{noun}  → quickly-elegant-symphony
```

### Language Selection

Specify language for dictionary selectors (currently only `en` for most dictionaries):

```
{adjective@en}    → brilliant
{noun@en}         → telescope
```

**Note:** Language specification is optional and defaults to `en` for adjectives, nouns, verbs, and adverbs.

## Number Generators

Generate numeric components in various formats.

### Syntax

```
{number:LENGTH[FORMAT]}
```

- **LENGTH:** Number of digits (1-10)
- **FORMAT:** Output format (optional)

### Available Formats

**Decimal (d):**
```
{number:3d}    → 847, 239, 176
{number:4d}    → 2847, 9102, 5673
```

**Lowercase Hexadecimal (x):**
```
{number:2x}    → a3, f7, 2c
{number:4x}    → 3a2f, b7d4, c1e9
```

**Uppercase Hexadecimal (X):**
```
{number:3X}    → A4F, B7D, C2A
{number:4X}    → 3A2F, B7D4, C1E9
```

**Roman Numerals (lowercase r, uppercase R):**
```
{number:2r}    → xlii, xcv, lxvii
{number:2R}    → XLII, XCV, LXVII
```

**Default format is decimal:**
```
{number:3}     → Same as {number:3d}
```

### Practical Examples

**Version identifiers:**
```
v{number:1d}.{number:2d}    → v2.14, v3.07, v1.95
```

**Product SKUs:**
```
SKU-{number:6d}             → SKU-284719, SKU-910265
```

**Hexadecimal codes:**
```
#{number:6X}                → #3A2F4B, #B7D4E1, #C1E9A3
```

**Sequential IDs:**
```
ID-{number:8d}              → ID-00284719, ID-09102657
```

## Special Character Generators

Add special characters for visual distinctiveness.

### Syntax

```
{special:COUNT}
{special:MIN-MAX}
```

### Examples

**Fixed count:**
```
{special:2}    → !@, #$, *&
{special:3}    → !@#, $%^, &*!
```

**Variable length:**
```
{special:1-3}  → !, @#, $%^
{special:2-4}  → !@, #$%, ^&*!
```

### Available Characters

Special character pool includes: `! @ # $ % ^ & * ( ) - + = [ ] { } | ; : ' " , . < > / ?`

### Practical Examples

**Secure-looking codes:**
```
{adjective}-{special:2}-{number:4x}    → brilliant-!@-3a2f
```

**Database identifiers:**
```
db_{noun}_{special:1}{number:3d}       → db_keyboard_!847
```

## Case Transformations

Control capitalization by changing the case of placeholder letters. The placeholder's case pattern determines how words are transformed.

### Standard Cases

**Lowercase (default):**
```
{adjective}    → brilliant
{noun}         → telescope
```

**Title Case:**
```
{Adjective}    → Brilliant
{Noun}         → Telescope
```

**UPPERCASE:**
```
{ADJECTIVE}    → BRILLIANT
{NOUN}         → TELESCOPE
```

### Mixed Case Patterns

The case pattern of your placeholder defines the transformation rule. SlugKit applies your case pattern position-by-position to the generated word:

**Alternating case:**
```
{aDjEcTiVe}    → bRiLlIaNt
{NoUn}         → TeLeScOpE
```

**Custom patterns:**
```
{ADJective}    → BRIlliant
{nOUN}         → tELESCOPE
{VerB}         → GeneRate
```

### Practical Examples

**Brand identifiers:**
```
{Adjective}-{NOUN}                 → Brilliant-TELESCOPE
{ADJECTIVE}-{Noun}-{number:3d}     → BRILLIANT-Telescope-847
```

**Product codes:**
```
{Adjective:+premium}-{NOUN:+tech}  → Premium-FRAMEWORK
```

**Visual hierarchy:**
```
{NOUN}::{Adjective}::{noun}        → TELESCOPE::Brilliant::framework
```

## Tag Filtering

Filter dictionary words by semantic tags to control the tone and context of your slugs.

### Syntax

```
{dictionary:TAGS}
```

**Include tags (use only words with these tags):**
```
{adjective:+positive}       → brilliant, excellent, amazing
{noun:+tech}                → framework, algorithm, database
```

**Exclude tags (avoid words with these tags):**
```
{adjective:-negative}       → (excludes sad, broken, failed)
{noun:-nsfw}                → (excludes inappropriate words)
```

**Combine multiple tags:**
```
{adjective:+positive+emotional}     → wonderful, delightful
{noun:+tech-corporate}              → algorithm, framework (not synergy)
{verb:+action+creative}             → design, innovate, build
```

### Common Tags

**Adjectives:**
- `pos` - Positive words (brilliant, excellent)
- `neg` - Negative words (broken, failed)
- `emo` - Emotional words (loving, angry)
- `det` - Detached/neutral words (standard, typical)
- `obj` - Objective words (numeric, physical)
- `neut` - Neutral words (average, medium)
- `nsfw` - Inappropriate words (opt-in only)

**Nouns:**
- `tech` - Technology-related (algorithm, framework)
- `nature` - Natural world (mountain, ocean)
- `abstract` - Abstract concepts (freedom, justice)
- `corporate` - Business terms (synergy, paradigm)
- `nsfw` - Inappropriate words (opt-in only)

**Verbs:**
- `action` - Action-oriented (execute, generate)
- `creative` - Creative actions (design, innovate)
- `communication` - Communication (discuss, explain)
- `movement` - Physical movement (run, jump)

**Note:** To see all available tags for a dictionary, use the [dictionary tags endpoint](api-reference).

### Opt-In Tags

Some tags like `nsfw` are **opt-in only** - words with these tags are excluded by default. To include them, explicitly add the tag:

```
{adjective:+nsfw}    → Includes inappropriate adjectives
{noun:+nsfw}         → Includes inappropriate nouns
```

### Practical Examples

**Positive user handles:**
```
{adjective:+positive}-{noun:+nature}    → brilliant-mountain
```

**Professional business names:**
```
{adjective:+obj-nsfw}-{noun:+tech-corporate}    → efficient-framework
```

**Creative project names:**
```
{adjective:+creative+emo}-{noun:+abstract}    → innovative-freedom
```

## Length Constraints

Control word length with comparison operators.

### Syntax

```
{dictionary:OPERATOR LENGTH}
```

### Operators

| Operator | Meaning | Example |
|----------|---------|---------|
| `<` | Less than | `{adjective:<8}` → max 7 characters |
| `<=` | Less than or equal | `{noun:<=10}` → max 10 characters |
| `>` | Greater than | `{adjective:>5}` → min 6 characters |
| `>=` | Greater than or equal | `{noun:>=4}` → min 4 characters |
| `==` | Exactly equal | `{verb:==6}` → exactly 6 characters |
| `!=` | Not equal | `{adjective:!=5}` → not 5 characters |

### Practical Examples

**Short, punchy names:**
```
{adjective:<6}-{noun:<8}    → swift-app, bold-idea
```

**Professional medium-length:**
```
{adjective:>6<=12}-{noun:>5<=10}    → brilliant-telescope
```

**Fixed-width identifiers:**
```
{adjective:==7}-{noun:==9}    → perfect-framework
```

**Mobile-friendly handles:**
```
{adjective:<8}-{noun:<12}    → cosmic-symphony
```

## Combining Features

Combine filtering, constraints, and case for powerful pattern control.

### Complex Patterns

**Branded product SKUs:**
```
{Adjective:+premium<10}-{NOUN:+tech>4}-{number:3X}
→ Premium-TECH-A4F
```

**Professional user handles:**
```
{adjective:+positive-nsfw<8}-{noun:+nature>5<=12}
→ brilliant-mountain
```

**Marketing campaign codes:**
```
campaign-{Adjective:+emo+pos}-{number:2x}
→ campaign-Delightful-f3
```

### Systematic Examples

**Web development:**
```
api-{verb:+action<10}/{noun:+tech}    → api-generate/framework
{adjective:+obj}-{noun:+tech}-app     → efficient-database-app
```

**Gaming usernames:**
```
{adjective:+positive}-{noun:+nature}-{number:2d}
→ cosmic-dragon-47
```

**Infrastructure naming:**
```
{noun:+tech}-{adjective:+obj}-{adverb}<10
→ server-stable-quickly
```

## Global Modifiers

Apply settings to all placeholders in a pattern using global modifiers at the end.

### Syntax

```
{placeholder1}-{placeholder2}[@LANGUAGE:TAGS LENGTH]
```

Global modifiers affect all dictionary selectors in the pattern.

### Examples

**Apply language globally:**
```
{adjective}-{noun}[@en]
→ All selectors use English
```

**Global length constraint:**
```
{adjective}-{noun}[<8]
→ All words max 7 characters
```

**Global tag filtering:**
```
{adjective}-{noun}[:+positive-nsfw]
→ All words positive, no NSFW
```

**Combine global modifiers:**
```
{adjective}-{noun}[@en:+positive<10]
→ English, positive words, max 9 characters
```

### Practical Examples

**Brand-consistent identifiers:**
```
{Adjective}-{Noun}-{verb}[:+premium+professional<12]
```

**Family-friendly names:**
```
{adjective}-{noun}-{verb}[:-nsfw:+positive]
```

**Compact identifiers:**
```
{adjective}-{noun}[<6]
→ swift-app, bold-idea
```

## Pattern Validation

Before using patterns in production, validate them to ensure they work as expected.

### Using the Forge Endpoint

Test patterns with small counts:

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective:+positive}-{noun:+tech}",
    "count": 10
  }'
```

### Pattern Capacity

Every pattern has a finite capacity - the maximum number of unique slugs it can generate. Consider capacity when designing patterns for production use.

**Check capacity:**
```bash
curl -X POST https://api.slugkit.com/api/v1/gen/pattern-info \
  -H "X-API-Key: sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective}-{noun}"
  }'
```

**Response:**
```json
{
  "capacity": "708339294",
  "max_slug_length": 55,
  "complexity": 10,
  "components": 2
}
```

**Higher capacity patterns:**
- More dictionary selectors: `{adj}-{noun}-{verb}` > `{adj}-{noun}`
- Longer numbers: `{number:6d}` > `{number:3d}`
- Fewer constraints: `{adjective}` > `{adjective:<5}`

## Common Patterns

### URL Slugs

**Blog posts:**
```
{adjective}-{noun}              → brilliant-telescope
{adjective}-{noun}-{number:2d}  → cosmic-symphony-42
```

**Product pages:**
```
{adjective:+premium}-{noun:+product}    → premium-gadget
```

### User Handles

**Social media:**
```
{adjective:+positive}-{noun:+nature}           → cosmic-dragon
{adjective}-{noun}-{number:2d}                 → swift-phoenix-47
```

**Gaming:**
```
{adjective:+action}-{noun:+fantasy}-{number:3x}
→ fierce-warrior-a3f
```

### API Resources

**Endpoints:**
```
/{verb}/{noun}                     → /generate/framework
/api/v{number:1d}/{noun}          → /api/v2/users
```

**Resource identifiers:**
```
{noun}-{adjective}-{number:4x}    → database-stable-3a2f
```

### Infrastructure

**Server names:**
```
{noun:+tech}-{adjective:+obj}-{number:2d}    → server-stable-01
{adjective}-{noun}-prod                       → swift-compute-prod
```

**Container names:**
```
{verb:+action}-{noun:+tech}-{number:3d}    → process-worker-847
```

## Best Practices

### Start Simple

Begin with basic patterns and add complexity as needed:

```
{adjective}-{noun}                           → Simple, high capacity
{adjective:+positive}-{noun}                 → Add filtering
{adjective:+positive<8}-{noun:+tech}         → Add constraints
{Adjective:+positive<8}-{NOUN:+tech}-{number:2x}  → Full control
```

### Consider Capacity

Ensure your pattern capacity exceeds your needs:
- **Small projects:** 10,000+ unique slugs
- **Medium applications:** 1,000,000+ unique slugs
- **Large platforms:** 100,000,000+ unique slugs

**Capacity tips:**
- Avoid too many constraints (increases collisions)
- Use longer number generators for scale
- Combine multiple dictionaries
- Test capacity with pattern-info endpoint

### Match Your Brand

Use case transformations and filtering to match your brand voice:

**Professional:**
```
{Adjective:+obj}-{Noun:+tech}    → Efficient-Framework
```

**Playful:**
```
{adjective:+positive}-{noun:+nature}    → cosmic-dragon
```

**Technical:**
```
{noun:+tech}-{number:4x}    → algorithm-3a2f
```

### Test Before Production

Always test patterns before using them in production:

1. **Forge small samples** to verify output
2. **Check capacity** to ensure adequate scale
3. **Review generated slugs** for appropriateness
4. **Test with different seeds** for variety

### Use Appropriate Filtering

Exclude inappropriate content by default:

```
{adjective:-nsfw}-{noun:-nsfw}    → Safe for all audiences
```

Include positive words for user-facing identifiers:

```
{adjective:+positive}-{noun}    → brilliant-telescope
```

## Escaping Special Characters

To use literal curly braces in your patterns, escape them with backslash:

```
\{literal\}            → {literal}
{adjective}\{test\}    → brilliant{test}
api/\{{noun}\}         → api/{telescope}
```

## Pattern Examples by Use Case

### E-commerce

**Product codes:**
```
{Adjective:+premium}-{NOUN:+product}-{number:3X}
→ Premium-GADGET-A4F
```

**Order IDs:**
```
ORDER-{number:8d}    → ORDER-28471902
```

### SaaS Applications

**Workspace slugs:**
```
{adjective:+professional}-{noun:+tech}    → efficient-workspace
```

**Project identifiers:**
```
{adjective}-{noun}-{number:4x}    → brilliant-project-3a2f
```

### Developer Tools

**Branch names:**
```
feature/{adjective}-{noun}    → feature/cosmic-refactor
```

**Release tags:**
```
v{number:1d}.{number:2d}-{adjective}    → v2.14-stable
```

### Marketing

**Campaign codes:**
```
{adjective:+positive}-{number:2x}    → brilliant-f3
PROMO-{adjective:+emo}-{number:3d}   → PROMO-delightful-847
```

**Tracking codes:**
```
{noun}-{adjective}-{number:6x}    → email-cosmic-3a2f4b
```

## Next Steps

Now that you understand pattern basics, explore advanced features:

**Advanced Topics:**
- [Advanced Pattern Features](pattern-advanced-features) - Deep dive into case transformations and global modifiers
- [Dictionary Reference](pattern-dictionary-reference) - Complete list of words and tags
- [Pattern Cookbook](pattern-cookbook) - Real-world pattern examples
- [Performance Optimization](pattern-performance-optimization) - Capacity planning and efficiency

**API Integration:**
- [Forge Endpoint](api-reference) - Custom slug generation
- [Mint Endpoint](api-reference) - Series-based unique generation
- [Validation Endpoints](api-reference) - Pattern testing and analysis

**Getting Started:**
- [Core Concepts](developer-core-concepts) - Understanding SlugKit fundamentals
- [Quickstart Guide](developer-quickstart-guide) - Your first API call
- [Choosing Generation Methods](choosing-generation-method) - Forge vs Mint vs Slice


---

# SlugKit Pattern Syntax Reference
Source: https://dev.slugkit.dev/docs/pattern-syntax-reference-for-agents

# SlugKit Pattern Syntax Reference

## Overview

SlugKit patterns are powerful template strings that can generate anything from simple slugs to complex structured text. Patterns combine **placeholders** (words in curly braces) with **arbitrary literal text** including whitespace, punctuation, and complete sentences.

## Basic Structure

```ebnf
pattern := ARBITRARY, { placeholder, ARBITRARY }, [ global_settings ]
```

**Key Principle**: Any text outside placeholders is preserved exactly as written.

- **ARBITRARY**: Any text except `{`, `}`, `\` (unless escaped)
- **placeholder**: Word generators in `{}`
- **global_settings**: Pattern-wide settings in `[]`

## Placeholders

### Basic Syntax
```ebnf
placeholder := '{' (selector | number_gen | special_char_gen) '}'
selector    := kind ['@' lang] [':', [tags] [length_constraint] [options]]
```

Three types of placeholders:
1. **Word selectors**: `{adjective}`, `{noun}`, etc.
2. **Number generators**: `{number:4d}`, `{number:3x}`
3. **Special character generators**: `{special:2}`, `{special:1-4}`

### Word Types
| Type | Description | Examples |
|------|-------------|----------|
| `{adjective}` | Descriptive words | fast, brilliant, complex |
| `{noun}` | Objects, concepts, people | server, database, manager |
| `{verb}` | Action words | deploy, analyze, configure |
| `{adverb}` | Manner descriptors | quickly, efficiently, carefully |
| `{domain}` | Internet domains | com, org, tech, dev |
| `{shell}` | Command-line tools | git, docker, npm, curl |

### Casing Control
The case of the dictionary name controls the output casing:

```
{noun}     → lowercase: "server"
{NOUN}     → UPPERCASE: "SERVER" 
{Noun}     → Title Case: "Server"
{nOuN}     → Mixed case following pattern: "SeRvEr"
```

**Impact on Capacity**: Mixed casing dramatically increases pattern capacity as all possible case combinations are generated. Capacity calculation for mixed case patterns is not yet fully implemented.

Examples:
```
{adjective}-{NOUN}     → "fast-SERVER"
{Verb} the {noun}      → "Deploy the database"  
{AdJeCtIvE} {nOuN}     → "FaSt sErVeR"
```

### Constraints (Inside Braces)

**Important**: For word selectors, constraints must follow this exact order:
```
{word_type:tags length_constraints options}
```

#### Tag Filters
```ebnf
tags        := (include_tag | exclude_tag)*
include_tag := '+' tag
exclude_tag := '-' tag
```

```
{adjective:+positive}          // Include positive words
{noun:-nsfw}                   // Exclude NSFW words
{adjective:+tech-negative}     // Include tech, exclude negative
{noun:+animal+object}          // Include both animal and object tags
```

**Tag syntax**: Tags are identifiers (letters, numbers, underscores). Multiple tags can be combined with `+` for inclusion and `-` for exclusion.

Common tags:
- **Emotional**: `+pos`, `+neg`, `+emo`, `+neut`
- **Content**: `+nsfw` (opt-in), `+det`, `+obj`
- **Domain-specific**: `+tech`, `+animal`, `+food`, `+person`

#### Length Constraints
```ebnf
length_constraint := comparison_op length
comparison_op     := '==' | '!=' | '<' | '<=' | '>' | '>='
```

```
{word:<8}      // Maximum 7 characters (less than 8)
{word:>3}      // Minimum 4 characters (greater than 3)
{word:<=6}     // 6 characters or fewer  
{word:>=4}     // 4 characters or more
{word:==5}     // Exactly 5 characters
{word:!=7}     // Not 7 characters
```

**Note**: `<8` means "less than 8", so max 7 characters. `>3` means "greater than 3", so min 4 characters.

#### Options
```ebnf
options      := option (',' option)*
option       := identifier '=' option_value
option_value := tag | number
```

⚠️ **Note**: Options are currently not supported and are reserved for future releases.

Options will provide additional configuration for word selectors:
```
{noun:option1=value1,option2=value2}    // Future functionality
```

#### Combined Constraints
Currently supported constraints must be in the exact order: **tags → length** (options reserved for future)
```
{adjective:+pos<6}              // ✅ Correct: tags first, then length
{noun:+tech-nsfw>=4}            // ✅ Correct: tags, then length  
{verb:<8+action}                // ❌ Wrong: length before tags
{noun:>=4+animal}               // ❌ Wrong: length before tags
{adjective:+pos<6,opt=val}      // ❌ Not yet supported: options
```

### Number Generators
```ebnf
number_gen := 'number' ':' length [(',' number_base) | number_base_short]
```

```
{number:3d}     // 3-digit decimal: 123
{number:4x}     // 4-digit lowercase hex: a1b2  
{number:4X}     // 4-digit uppercase hex: A1B2
{number:2r}     // 2-character lowercase Roman: ii
{number:3R}     // 3-character uppercase Roman: XII
```

**Long form with comma**:
```
{number:3,dec}   // Same as {number:3d}
{number:4,hex}   // Same as {number:4x}
{number:2,HEX}   // Same as {number:2X}
{number:3,roman} // Same as {number:3r}
{number:2,ROMAN} // Same as {number:2R}
```

**Supported bases**: `dec`, `hex`, `HEX`, `roman`, `ROMAN`

### Special Character Generators
```ebnf
special_char_gen := 'special' [':' number ['-' length]]
```

```
{special}        // Single special character: @
{special:2}      // Exactly 2 special characters: @#
{special:1-4}    // 1 to 4 special characters: &!@
```

### Global Settings
```ebnf
global_settings := '[' ['@' lang] [tags] [length_constraint] [options] ']'
```

Apply settings to ALL placeholders in the pattern:
```
{adjective}-{noun}[@en:+pos-nsfw<6]
{verb} {noun} {adverb}[+tech>=4]
```

**Components**:
- `@en` - Language for all word selectors
- `+pos-nsfw` - Include positive, exclude NSFW for all words  
- `<6` - Maximum 5 characters for all words (< 6)
- Options apply to all compatible placeholders

**Note**: Global settings don't affect number or special character generators, only word selectors.

## Escaping

```ebnf
ESCAPED_CHAR  := escape_symbol ('{' | '}' | escape_symbol)
escape_symbol := '\'
```

Use backslash `\` to include literal braces and backslashes:
```
\{            // Literal { character
\}            // Literal } character  
\\            // Literal \ character
```

Examples:
```
"The \{system\} uses {noun}"     → "The {system} uses database"
"Path: C:\\{noun}\\file"         → "Path: C:\server\file"  
"Price: \$\{number:2d\}"         → "Price: ${42}"
```

**Important**: Only `{`, `}`, and `\` need escaping. All other characters are literal.

## Pattern Examples

### Simple Slugs
```
{adjective}-{noun}                    → "fast-server"
{adjective:<6}-{noun:<8}-{number:3d}  → "quick-database-127"  
{verb:>=5}-{noun:+tech}               → "deploy-microservice"
```

### Natural Language
```
"The {adjective:+pos} {noun:+animal} {verb} {adverb}"
→ "The brilliant cat leaps gracefully"

"Error {number:3d}: {ADJECTIVE} {NOUN} could not {verb} the {Noun}"  
→ "Error 404: BROKEN CONNECTION could not reach the Server"
```

### Structured Templates
```
"server_name: {adjective}-{noun}
port: {number:4d}
debug: {adjective:+tech}"

→ "server_name: fast-proxy
port: 8080
debug: verbose"
```

### Command-Line Examples
```
"git {verb:<6} {adjective}-{noun}-{number:4x}"
→ "git commit feature-auth-a1b2"

"docker run -p {number:4d}:{number:4d} {adjective}/{noun}"
→ "docker run -p 8080:3000 stable/webapp"
```

### Email Addresses
```
"{adjective:<6}.{noun:<8}@{noun:<6}.{domain:+com}"
→ "smart.database@tech.com"
```

### Configuration Files
```
"[database]
host = {noun:<8}.local
port = {number:4d}
timeout = {number:2d}s
ssl = {adjective:+tech}"

→ "[database]
host = postgres.local  
port = 5432
timeout = 30s
ssl = enabled"
```

## Best Practices

### 1. Always Validate First
```
Use validate_pattern() before forge(), mint(), or other operations
```

### 2. Use Length Constraints for Predictable Output
```
{noun:<8}-{adjective:<6}    // Bounded length (max 7 + max 5 + 1 = 13 chars)
vs
{noun}-{adjective}          // Variable length (could be very long)
```

**Remember**: `<8` means "less than 8", so maximum 7 characters.

### 3. Apply Appropriate Tags
```
{adjective:+pos}-{noun:+tech}     // Professional, positive tech terms
{noun:+animal}-{verb:+action}     // Animal action combinations
```

### 4. Leverage Global Settings for Consistency
```
{adjective}-{noun}-{verb}[+tech<8]   // All tech words, max 7 chars (< 8)
{noun} and {noun}[@en:>=4]           // English words, min 4 chars
```

### 5. Consider Your Use Case
- **Slugs**: Short, constrained patterns
- **Sentences**: Natural language with appropriate tags
- **Templates**: Mix literals with strategic placeholders
- **Commands**: Realistic tool names and parameters

## Common Patterns

### Common Patterns

### Web Development
```
"{adjective}-{noun}-api"              → "fast-user-api"
"{NOUN:<6}-v{number:1d}.{number:1d}"  → "WEBAPP-v2.1"  
"{Adjective}{Noun}Service"            → "FastUserService"
```

### DevOps
```
"deploy {Noun} to {adjective}-env"           → "deploy Service to staging-env"
"backup-{noun}-{number:2d}{number:2d}{number:4d}" → "backup-db-15122024"
"{ADJECTIVE}_{NOUN}_CONFIG"                  → "PROD_DATABASE_CONFIG"
```

### Testing Data
```
"user_{number:4d}@{noun}.{domain:+com}"     → "user_1234@test.com"
"The {Adjective} test {verb} {adverb}"      → "The Comprehensive test passes successfully"
"{FirstName} {LastName}"                    → "Smart Database" (using mixed casing)
```

### Documentation
```
"## {adjective:+pos} {noun} Guide
This {noun} will help you {verb} {adverb}."

→ "## Comprehensive Database Guide
This tutorial will help you deploy efficiently."
```

## Error Prevention

### Common Mistakes
```
❌ {adjective}<8      // Length constraint outside braces (becomes literal "<8")
✅ {adjective:<8}     // Correct: constraint inside braces

❌ {noun}+tech        // Tag outside braces (becomes literal "+tech")  
✅ {noun:+tech}       // Correct: tag inside braces
```

### Validation Tips
- Constraints go INSIDE braces: `{word:constraint}`
- Arbitrary text goes OUTSIDE braces: `{word} literal text`
- Use `validate_pattern()` to verify syntax and see capacity
- Use `dictionary_tags()` to see available tag filters

## Advanced Features

### Language Selection
```
{adjective@en}-{noun@en}    // Force English words
{noun@es}-{verb@fr}         // Mix languages (if supported)  
{noun}[@de]                 // German words globally
```

### Complex Filtering
```
{adjective:+pos+tech-nsfw<6>=3}    // Positive tech adjectives, 3-5 chars (< 6, >= 3)
{noun:+animal+fantasy!=5}         // Animal/fantasy nouns, not exactly 5 chars
{verb:+action<=8,option1=value}   // Action verbs, max 8 chars, with custom option
```

### Sequence Control  
When using forge() with `sequence` parameter for number generators:
```
{number:3d} generates 3-digit zero-padded numbers in pseudorandom sequence
sequence=0   → 383, 766, 149, 532, 915...
sequence=100 → 630, 664, 498, 322, 15...
sequence=1000 → 383, 766, 149... (same as sequence=0 due to wrapping)
```

**Wrapping**: Sequence values wrap at the generator's capacity (e.g., 1000 for 3-digit decimals). So `sequence=1000` equals `sequence=0` for `{number:3d}`.

---

*For formal grammar specification, see the EBNF grammar documentation.*
*For available word types and tags, use `dictionary_info()` and `dictionary_tags()`.*

---

# Pattern Playground Teaser
Source: https://dev.slugkit.dev/docs/pattern-teaser

## Design Your Perfect Pattern

SlugKit's pattern language gives you complete control over your identifiers. From simple combinations to sophisticated linguistic engineering - test your ideas with real-time feedback.

## Playground Features

**Smart Editor** - Real-time validation and code completion guide you through pattern syntax. Never guess if your pattern will work.

**Capacity Analysis** - See exactly how many unique combinations your pattern can generate. Plan for scale from the start.

**Live Generation** - Watch your patterns come to life with instant slug generation. Preview your aesthetic before committing to production.


---

# Privacy Policy - 2025-06
Source: https://dev.slugkit.dev/docs/privacy-policy-2025-06

**Effective Date:** June 21, 2025  
**Version:** 2025-06

This Privacy Policy explains how **Sergei Fedorov pr Računarsko programiranje cpp Beograd** ("Provider", "we", "us") collects, uses, and protects your personal data when you use the SlugKit service ("Service").

By using the Service, you agree to the practices described in this Privacy Policy.

## 1. Data We Collect

We collect the following data:
- **Email Address**: Used for account identification, notifications, and access control.
- **Usage Statistics**: Non-personal metrics related to the usage of the Service (e.g., slug generation counts, pattern use, request volume).

We do **not** collect or store user-generated content. The Service only generates Slugs based on system or user-defined patterns.

## 2. Purpose of Data Collection

We collect data to:
- Authenticate and identify users
- Enforce usage limits and track quota consumption
- Communicate with users about their account or service changes
- Monitor service health and usage trends
- Improve and optimize system performance

The Service itself does not use tracking cookies or analytics. However, we integrate third-party services for authentication (such as Auth0), which may use strictly necessary cookies or browser storage to manage secure logins. These are required for functionality and are not used for profiling, advertising, or marketing purposes.

## 3. Data Sharing

We do **not** share your personal data with third parties.  
We do **not** use third-party advertising platforms.
We do **not** share any of your data with third-party analytical platforms.

Your data is stored and processed solely for operating the Service and fulfilling legal obligations.

## 4. Data Security

We implement reasonable technical and organizational measures to protect your data from unauthorized access, loss, or misuse. These include secure storage, access controls, and encrypted connections.

## 5. Data Retention

We retain your data as long as your account remains active. If you delete your account or request deletion, we will remove your personal data within a reasonable period, subject to any legal or compliance obligations.

## 6. Your Rights

You have the right to:
- Access the data we hold about you
- Request corrections or updates
- Request deletion of your personal data
- Withdraw consent to processing (where applicable)

To exercise any of these rights, please contact us at [your email/contact link].

## 7. Changes to This Policy

We may update this Privacy Policy from time to time. Material changes will be communicated to users. Continued use of the Service after changes are posted constitutes your acceptance of the revised policy.

## 8. Intended Audience

The Service is designed for use by developers and businesses. It is not intended for general consumer use.

## 9. Contact

If you have any questions or concerns regarding this Privacy Policy, please contact us at:

**Sergei Fedorov pr Računarsko programiranje cpp Beograd**  
Email: sergei@slugkit.dev

---

**By using the Service, you consent to the collection and use of data as described in this Privacy Policy.**

---

# Product Description
Source: https://dev.slugkit.dev/docs/products

### SlugKit – Human-Readable ID Generation as a Service

**SlugKit** is a high-performance, developer-friendly service for generating unique, **human-readable identifiers** (“slugs”) based on flexible, user-defined patterns. Instead of opaque UUIDs or auto-incremented integers, SlugKit produces memorable IDs that align with your brand, product, or user experience goals.

With SlugKit, you can define **rich generation patterns** using placeholders like `{adjective}`, `{noun}`, `{number}`, and `{special}` – each drawing from curated, taggable dictionaries or configurable numeric/character sequences. Apply filters, length constraints, and semantic tags to fine-tune your output. Whether you need whimsical onboarding codes, deterministic distributed IDs, or branded asset names, SlugKit makes it simple.

⸻

#### Key Features
 * **Pattern-Driven Generation**<br>
Compose slugs using placeholders with filters, tags, and constraints, e.g.
`fast-fluffy-koala-42` or `{adverb}-{adjective}-{noun}-{number:6,hex}`.
 * **Multiple Generation Modes**
   * **Forge** – arbitrary pattern/seed/sequence input
   * **Mint** – persistent, counter-tracked unique IDs
   * **Slice** – generation without consuming counters
 * **Deterministic Uniqueness**<br>
Distributed generation without collisions using prime-adjusted dictionary sizes and stable pseudo-random permutations.
 * **Boring Slug Avoidance**<br>
Prevent repetitive or uninteresting results automatically.
 * **High-Performance API**<br>
Low-latency HTTP and gRPC (*work in progress*) endpoints, built for horizontal scaling.
 * **Capacity Insights**<br>
Query pattern capacity to plan ID space usage.
 * **Secure & Controlled Access**<br>
API keys tied to projects, role-based organisation membership, and optional Auth0 authentication.
 * **Flexible Deployment**
 * **SaaS** – instantly available, scales with your needs
 * **On-Prem** – self-hosted tiers from lightweight SQLite builds to full PostgreSQL-backed installations

⸻

Developer Benefits
 * **Integrates Anywhere** – Use with any language or stack via simple HTTP/gRPC calls.
 * **No More DIY Generators** – Skip writing and maintaining custom slug logic.
 * **User-Friendly IDs** – Improve UX with readable, brand-consistent identifiers.
 * **Safe for Concurrent Use** – Supports distributed, high-volume workloads without central bottlenecks.
 * **Customizable at Scale** – Adapt patterns instantly without downtime.

⸻

Common Use Cases
 * Public resource URLs (`/users/fuzzy-otter-92`)
 * Order or booking references
 * Marketing campaign codes
 * Invite links and promo codes
 * Game character or item names
 * IoT device identifiers
 * Distributed ID generation across microservices

⸻

**SlugKit turns your identifiers into an asset, not an afterthought** – giving your users and systems IDs that are unique, readable, and built for scale.


---

# Django Backend Integration Recipe
Source: https://dev.slugkit.dev/docs/recipe-django-backend

# Django Backend Integration Recipe

Transform your Django application with human-readable identifiers that enhance user experience, improve debugging, and create memorable URLs.

## The Django ID Problem

Traditional Django applications rely on auto-incrementing integers and random UUIDs:
```python
# Traditional approach
/blog/47/
/user/profile/8729f841-2b39-4a1c-9f7b-e3b4c5d6a7f8/
/product/SKU_938472984/
/api/endpoint/v2_auth_validate_token_987234/
```

These identifiers are forgettable, provide no context, and create poor user experiences.

## SlugKit's Django Solution

Create meaningful, beautiful identifiers throughout your Django application:
```python
# SlugKit approach
/blog/creative-storytelling-guide/
/user/profile/brave-designer/
/product/swift-productivity-toolkit/
/api/secure-auth-gateway/
```

Every identifier tells a story and enhances both user experience and developer productivity.

## Quick Start: 10-Minute Integration

```bash
pip install slugkit-py-sdk
```

```python
# settings.py
import os
from dotenv import load_dotenv

load_dotenv()

# SlugKit Configuration
SLUGKIT_API_KEY = os.getenv('SLUGKIT_API_KEY')
SLUGKIT_BASE_URL = os.getenv('SLUGKIT_BASE_URL', 'https://api.slugkit.com')

# Validate configuration
if not SLUGKIT_API_KEY:
    raise ValueError("SLUGKIT_API_KEY environment variable is required")
```

```python
# slugkit_client.py
from django.conf import settings
from slugkit import SyncClient

# Global client instance
client = SyncClient(
    base_url=settings.SLUGKIT_BASE_URL,
    api_key=settings.SLUGKIT_API_KEY
)
```

## Series Setup Required

**Important**: Before using `mint` operations in your Django application, you need to create SlugKit series. Series define the patterns and ensure uniqueness for your identifiers.

**Learn about series setup**: [Choosing Generation Methods](choosing-generation-method) and [Core Concepts](developer-core-concepts)

### Create Your Application Series

You'll need to create these series through the SlugKit dashboard or API before using them in your Django models:

```python
# Example series you'll need to create:
# - 'user-handles' with pattern: {adjective:+personality}-{noun:+animal}
# - 'blog-posts' with pattern: {adjective:+creative}-{noun:+content}  
# - 'product-skus' with pattern: {adjective:+tech}-{noun:+product}
# - 'product-urls' with pattern: {adjective:+positive}-{noun:+product}
# - 'api-endpoints' with pattern: {adjective:+tech}-{noun:+api}
```

**Series creation options:**
1. **SlugKit Dashboard**: Navigate to your organization → Series → Create New Series
2. **Python SDK**: Use `client.series.create()` (requires appropriate permissions)
3. **REST API**: POST to `/api/v1/series` endpoint

## Real-World Django Use Cases

### 1. User Profile System with Memorable Handles

Replace Django's default user system with SlugKit-powered handles using **mint** for guaranteed uniqueness:

```python
# models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from .slugkit_client import client

class User(AbstractUser):
    # SlugKit-generated handle instead of username
    handle = models.CharField(max_length=100, unique=True, blank=True)
    display_name = models.CharField(max_length=100)
    
    def save(self, *args, **kwargs):
        if not self.handle:
            # Use mint for guaranteed unique handles
            # Requires 'user-handles' series to be created first
            self.handle = client.series['user-handles'].mint(count=1)[0]
        super().save(*args, **kwargs)
    
    def get_absolute_url(self):
        return f'/user/{self.handle}/'
    
    def __str__(self):
        return f'@{self.handle}'
```

**Generated user handles:**
- `@brave-tiger` → `/user/brave-tiger/`
- `@clever-dolphin` → `/user/clever-dolphin/`
- `@swift-falcon` → `/user/swift-falcon/`

### 2. SEO-Friendly Blog Post URLs

Transform blog URLs from `/blog/47/` to meaningful, SEO-optimised paths:

```python
# models.py
class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=100, unique=True, blank=True)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    
    def save(self, *args, **kwargs):
        if not self.slug:
            # Use mint for guaranteed unique blog slugs
            # Requires 'blog-posts' series to be created first
            self.slug = client.series['blog-posts'].mint(count=1)[0]
        super().save(*args, **kwargs)
    
    def get_absolute_url(self):
        return f'/blog/{self.slug}/'
    
    class Meta:
        ordering = ['-created_at']
```

```python
# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('blog/<slug:slug>/', views.BlogPostDetailView.as_view(), name='blog-detail'),
    path('user/<str:handle>/', views.UserProfileView.as_view(), name='user-profile'),
]
```

**Generated blog URLs:**
- `/blog/innovative-design-principles/`
- `/blog/creative-storytelling-guide/`
- `/blog/inspiring-productivity-methods/`

### 3. E-commerce Product Management

Create memorable product SKUs and URLs using multiple series:

```python
# models.py
class Product(models.Model):
    name = models.CharField(max_length=200)
    sku = models.CharField(max_length=100, unique=True, blank=True)
    slug = models.SlugField(max_length=100, unique=True, blank=True)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.CharField(max_length=100)
    
    def save(self, *args, **kwargs):
        if not self.sku or not self.slug:
            # Generate both SKU and URL slug in one call for efficiency
            # Requires 'product-skus' and 'product-urls' series to be created first
            if not self.sku and not self.slug:
                # Generate both at once
                identifiers = (
                    client.series['product-skus'].mint(count=1) +
                    client.series['product-urls'].mint(count=1)
                )
                self.sku = identifiers[0]
                self.slug = identifiers[1]
            elif not self.sku:
                self.sku = client.series['product-skus'].mint(count=1)[0]
            elif not self.slug:
                self.slug = client.series['product-urls'].mint(count=1)[0]
        
        super().save(*args, **kwargs)
    
    def get_absolute_url(self):
        return f'/products/{self.slug}/'
    
    def __str__(self):
        return f'{self.name} ({self.sku})'
```

**Generated product identifiers:**
- SKU: `swift-toolkit-prime`, URL: `/products/innovative-productivity-suite/`
- SKU: `robust-solution-core`, URL: `/products/elegant-design-platform/`

### 4. API Endpoint Organisation

Create intuitive API endpoint names using mint for unique identifiers:

```python
# models.py
class APIEndpoint(models.Model):
    name = models.CharField(max_length=100)
    endpoint_id = models.CharField(max_length=100, unique=True, blank=True)
    path = models.CharField(max_length=200)
    method = models.CharField(max_length=10)
    description = models.TextField()
    
    def save(self, *args, **kwargs):
        if not self.endpoint_id:
            # Use mint for guaranteed unique API endpoint identifiers
            # Requires 'api-endpoints' series to be created first
            self.endpoint_id = client.series['api-endpoints'].mint(count=1)[0]
        super().save(*args, **kwargs)
    
    def get_api_url(self):
        return f'/api/{self.endpoint_id}/'
```

**Generated API endpoints:**
```
/api/secure-auth-gateway/
/api/swift-data-processor/
/api/reliable-notification-service/
/api/efficient-search-engine/
```

## Series Setup Strategy

### Create Series for Your Application

Set up dedicated series for different identifier types using the SlugKit dashboard or API:

```python
# Series creation (run once during setup)
# Note: This requires organization-level API key permissions

# User handles with personality + animal pattern
# Series slug: 'user-handles'
# Pattern: '{adjective:+personality}-{noun:+animal}'

# Blog posts with creative + content pattern  
# Series slug: 'blog-posts'
# Pattern: '{adjective:+creative}-{noun:+content}'

# Product SKUs with tech + product pattern
# Series slug: 'product-skus'
# Pattern: '{adjective:+tech}-{noun:+product}'

# Product URLs with positive + product pattern
# Series slug: 'product-urls'
# Pattern: '{adjective:+positive}-{noun:+product}'

# API endpoints with tech + api pattern
# Series slug: 'api-endpoints'
# Pattern: '{adjective:+tech}-{noun:+api}'
```

### Environment-Specific Series

Use different series for different environments:

```python
# settings.py
ENVIRONMENT = os.getenv('ENVIRONMENT', 'development')

SLUGKIT_SERIES_CONFIG = {
    'development': {
        'user_handles': 'dev-user-handles',
        'blog_posts': 'dev-blog-posts',
        'products': 'dev-products',
    },
    'staging': {
        'user_handles': 'staging-user-handles', 
        'blog_posts': 'staging-blog-posts',
        'products': 'staging-products',
    },
    'production': {
        'user_handles': 'user-handles',
        'blog_posts': 'blog-posts', 
        'products': 'products',
    }
}

SERIES_SLUGS = SLUGKIT_SERIES_CONFIG[ENVIRONMENT]
```

```python
# models.py
from django.conf import settings

def save(self, *args, **kwargs):
    if not self.handle:
        self.handle = client.series[settings.SERIES_SLUGS['user_handles']].mint(count=1)[0]
    super().save(*args, **kwargs)
```

## Advanced Django Patterns

### Bulk Operations with SlugKit

Efficiently generate multiple identifiers using mint's batch capability:

```python
# services.py
from .slugkit_client import client

class BulkProductService:
    def create_products_batch(self, products_data: list[dict]) -> list[Product]:
        """Create multiple products with efficient slug generation."""
        count = len(products_data)
        
        # Generate all identifiers in batch using mint
        skus = client.series['product-skus'].mint(count=count)
        slugs = client.series['product-urls'].mint(count=count)
        
        # Create products with pre-generated identifiers
        products = []
        for i, data in enumerate(products_data):
            product = Product(
                sku=skus[i],
                slug=slugs[i],
                **data
            )
            products.append(product)
        
        return Product.objects.bulk_create(products)
```

### Django REST Framework Integration

```python
# serializers.py
from rest_framework import serializers
from .slugkit_client import client

class UserRegistrationSerializer(serializers.ModelSerializer):
    handle = serializers.CharField(read_only=True)
    
    class Meta:
        model = User
        fields = ['email', 'display_name', 'handle']
    
    def create(self, validated_data):
        # Handle generation happens automatically in User.save()
        return User.objects.create_user(**validated_data)

class BlogPostSerializer(serializers.ModelSerializer):
    slug = serializers.CharField(read_only=True)
    author_handle = serializers.CharField(source='author.handle', read_only=True)
    url = serializers.URLField(source='get_absolute_url', read_only=True)
    
    class Meta:
        model = BlogPost
        fields = ['title', 'slug', 'content', 'author_handle', 'url', 'created_at']
        read_only_fields = ['slug', 'created_at']
```

### Custom Management Commands

```python
# management/commands/generate_slugs.py
from django.core.management.base import BaseCommand
from myapp.models import BlogPost
from myapp.slugkit_client import client

class Command(BaseCommand):
    help = 'Generate SlugKit slugs for existing blog posts'
    
    def handle(self, *args, **options):
        posts_without_slugs = BlogPost.objects.filter(slug='')
        count = posts_without_slugs.count()
        
        if count == 0:
            self.stdout.write('No posts need slug generation')
            return
        
        # Generate slugs in batch using mint
        slugs = client.series['blog-posts'].mint(count=count)
        
        # Update posts
        for i, post in enumerate(posts_without_slugs):
            post.slug = slugs[i]
            post.save(update_fields=['slug'])
        
        self.stdout.write(f'Generated slugs for {count} blog posts')
```

## Form Integration

### Dynamic Handle Selection

```python
# forms.py
from django import forms
from .slugkit_client import client

class UserRegistrationForm(forms.ModelForm):
    handle_options = forms.CharField(widget=forms.HiddenInput(), required=False)
    selected_handle = forms.CharField(max_length=100)
    
    class Meta:
        model = User
        fields = ['email', 'display_name']
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Generate handle options using forge for previews
        handles = client.forge(
            pattern='{adjective:+personality}-{noun:+animal}',
            count=8
        )
        self.fields['handle_options'].initial = ','.join(handles)
    
    def save(self, commit=True):
        user = super().save(commit=False)
        user.handle = self.cleaned_data['selected_handle']
        if commit:
            user.save()
        return user
```

```html
<!-- templates/registration.html -->
<form method="post">
    {% csrf_token %}
    {{ form.email }}
    {{ form.display_name }}
    
    <div class="handle-selection">
        <h3>Choose Your Handle:</h3>
        {% for handle in form.handle_options.value|split:',' %}
            <label>
                <input type="radio" name="selected_handle" value="{{ handle }}">
                @{{ handle }}
            </label>
        {% endfor %}
    </div>
    
    <button type="submit">Register</button>
</form>
```

## Performance and Caching

### Efficient Slug Generation with Caching

```python
# utils/slug_cache.py
from django.core.cache import cache
from .slugkit_client import client
import hashlib

class SlugCache:
    def get_cached_forge_slugs(self, pattern: str, count: int) -> list[str] | None:
        """Get cached forge slugs if available."""
        cache_key = self._make_cache_key(pattern, count)
        return cache.get(cache_key)
    
    def cache_forge_slugs(self, pattern: str, count: int, slugs: list[str]):
        """Cache forge-generated slugs for reuse."""
        cache_key = self._make_cache_key(pattern, count)
        cache.set(cache_key, slugs, timeout=300)  # 5 minutes
    
    def _make_cache_key(self, pattern: str, count: int) -> str:
        content = f"forge_slugs:{pattern}:{count}"
        return hashlib.md5(content.encode()).hexdigest()

    def generate_with_cache(self, pattern: str, count: int) -> list[str]:
        """Generate slugs with caching for forge operations."""
        cached = self.get_cached_forge_slugs(pattern, count)
        if cached:
            return cached
        
        # Generate new slugs using forge
        slugs = client.forge(pattern=pattern, count=count)
        self.cache_forge_slugs(pattern, count, slugs)
        return slugs

slug_cache = SlugCache()
```

### Database Indexing

```python
# Add indexes for SlugKit fields
class Meta:
    indexes = [
        models.Index(fields=['slug']),
        models.Index(fields=['handle']),
        models.Index(fields=['sku']),
    ]
```

## Testing SlugKit Integration

```python
# tests.py
from django.test import TestCase
from unittest.mock import patch, MagicMock
from myapp.models import User, BlogPost

class SlugKitIntegrationTest(TestCase):
    
    @patch('myapp.slugkit_client.client')
    def test_user_handle_generation(self, mock_client):
        mock_series = MagicMock()
        mock_series.mint.return_value = ['brave-tiger']
        mock_client.series.__getitem__.return_value = mock_series
        
        user = User.objects.create_user(
            email='test@example.com',
            display_name='Test User'
        )
        
        self.assertEqual(user.handle, 'brave-tiger')
        mock_client.series.__getitem__.assert_called_with('user-handles')
        mock_series.mint.assert_called_with(count=1)
    
    def test_user_profile_url(self):
        user = User(handle='swift-falcon')
        self.assertEqual(user.get_absolute_url(), '/user/swift-falcon/')
    
    @patch('myapp.slugkit_client.client')
    def test_blog_post_slug_generation(self, mock_client):
        mock_series = MagicMock()
        mock_series.mint.return_value = ['creative-writing-guide']
        mock_client.series.__getitem__.return_value = mock_series
        
        post = BlogPost.objects.create(
            title='My Blog Post',
            content='Content here',
            author_id=1
        )
        
        self.assertEqual(post.slug, 'creative-writing-guide')
        self.assertEqual(post.get_absolute_url(), '/blog/creative-writing-guide/')
```

## Error Handling and Fallbacks

```python
# robust_slugkit.py
from slugkit.base import SlugKitError, SlugKitRateLimitError
from .slugkit_client import client
import logging
import time

logger = logging.getLogger(__name__)

def safe_mint_generation(series_slug: str, fallback_prefix: str = 'item') -> str:
    """Generate slug with fallback for failures."""
    try:
        return client.series[series_slug].mint(count=1)[0]
    except SlugKitRateLimitError as e:
        logger.warning(f'SlugKit rate limited: {e.rate_limit_reason}')
        if e.retry_after and e.retry_after < 60:  # Only retry if wait is reasonable
            time.sleep(e.retry_after)
            return client.series[series_slug].mint(count=1)[0]
        # Fallback to timestamp-based ID
        return f'{fallback_prefix}-{int(time.time())}'
    except SlugKitError as e:
        logger.warning(f'SlugKit generation failed: {e}')
        return f'{fallback_prefix}-{int(time.time())}'

# Use in models
def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = safe_mint_generation(
            series_slug='blog-posts',
            fallback_prefix='post'
        )
    super().save(*args, **kwargs)
```

## Best Practices for Django + SlugKit

### 1. Use Mint for Unique Identifiers
Always use **mint** for production identifiers that need to be unique:
- **User handles**: `client.series['user-handles'].mint(count=1)[0]`
- **Blog post slugs**: `client.series['blog-posts'].mint(count=1)[0]`
- **Product SKUs**: `client.series['product-skus'].mint(count=1)[0]`
- **API endpoints**: `client.series['api-endpoints'].mint(count=1)[0]`

### 2. Use Forge for Prototyping and Testing
Use **forge** for generating test data or experimenting with patterns:
```python
# Testing patterns before creating series
test_slugs = client.forge(
    pattern='{adjective:+personality}-{noun:+animal}',
    count=10
)
```

### 3. Database Design
Always make SlugKit fields unique and indexed:
```python
class MyModel(models.Model):
    slug = models.SlugField(max_length=100, unique=True, db_index=True)
```

### 4. URL Patterns
Use descriptive URL patterns:
```python
urlpatterns = [
    path('blog/<slug:slug>/', views.BlogDetailView.as_view()),
    path('user/<str:handle>/', views.UserProfileView.as_view()),
    path('products/<slug:slug>/', views.ProductDetailView.as_view()),
]
```

### 5. Admin Integration
Make admin interface SlugKit-aware:
```python
class MyModelAdmin(admin.ModelAdmin):
    readonly_fields = ['slug']  # Prevent manual editing
    list_display = ['name', 'slug_link']  # Show clickable slugs
```

## Real-World Benefits

### 1. Developer Experience
- **Debugging**: "Check the brave-tiger user profile" vs "Check user ID 8472"
- **Logs**: Meaningful identifiers in error messages
- **Communication**: Teams can easily reference resources

### 2. User Experience  
- **Memorable URLs**: Users can guess and remember URLs
- **Sharing**: Beautiful URLs encourage social sharing
- **SEO**: Search engines love keyword-rich URLs

### 3. Business Impact
- **Support**: Customer service can easily find user profiles by handle
- **Analytics**: Meaningful names in reports and dashboards
- **Marketing**: Branded, professional-looking URLs

## Next Steps

This recipe transforms your Django application from a system of forgettable IDs to a platform of meaningful, memorable identifiers. Your users will love the readable URLs, your team will appreciate the debugging clarity, and search engines will reward your thoughtful approach.

**Before implementing**: Make sure to set up your SlugKit series first! Learn more about series creation and management:

**Related Guides:**
- **[Choosing Generation Methods](choosing-generation-method)** - **Essential**: Understanding Forge vs Mint vs Slice and series setup
- **[Core Concepts](developer-core-concepts)** - **Essential**: Series creation and management fundamentals
- [Python SDK Quickstart](sdk-python-quickstart) - Learn the complete SDK API
- [Python SDK Advanced Usage](sdk-python-advanced) - Async operations and error handling

**Core Concepts:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Master SlugKit pattern creation


---

# Next.js Application Integration Recipe
Source: https://dev.slugkit.dev/docs/recipe-nextjs-app

# Next.js Application Integration Recipe

Create beautiful, memorable URLs and identifiers in your Next.js application that users love and search engines reward.

## The URL Problem in Modern Web Apps

Traditional Next.js applications often struggle with URL aesthetics:
```
/blog/post-1647382941
/user/user_8k2n9x3m
/product/SKU_XYZ123456
/api/endpoint_v2_auth_token_validate
```

These URLs are forgettable, provide no context, and create poor user experiences.

## SlugKit's Next.js Solution

Transform your application with human-readable, SEO-friendly identifiers:
```
/blog/creative-storytelling-guide
/user/brave-designer  
/product/swift-productivity-toolkit
/api/secure-auth-gateway
```

Every URL tells a story and enhances both user experience and SEO performance.

## Quick Start: 5-Minute Integration

```bash
npm install @slugkit/sdk
```

```typescript
// lib/slugkit.ts
import { SlugKit } from '@slugkit/sdk';

// Server-side client with API key
export const slugkit = SlugKit.fromApiKey(
  process.env.SLUGKIT_BACKEND_URL || 'https://api.slugkit.com',
  process.env.SLUGKIT_API_KEY!
);

// Application-specific patterns
export const patterns = {
  blogPost: '{adjective:+creative}-{noun:+content}',
  userHandle: '{adjective:+personality}-{noun:+animal}',
  productSlug: '{adjective:+positive}-{noun:+product}',
  apiEndpoint: '{adjective:+tech}-{noun:+api}'
};
```

```bash
# .env.local
SLUGKIT_API_KEY=sk_api_your_key_here
SLUGKIT_BACKEND_URL=https://api.slugkit.com
```

## Series Setup Required

**Important**: Before using `mintSlugs()` operations in your Next.js application, you need to create SlugKit series. Series define the patterns and ensure uniqueness for your identifiers.

**Learn about series setup**: [Choosing Generation Methods](choosing-generation-method) and [Core Concepts](developer-core-concepts)

### Create Your Application Series

You'll need to create these series through the SlugKit dashboard or API before using them in your Next.js application:

```typescript
// Example series you'll need to create:
// - 'blog-posts' with pattern: {adjective:+creative}-{noun:+content}
// - 'user-handles' with pattern: {adjective:+personality}-{noun:+animal}  
// - 'product-skus' with pattern: {adjective:+tech}-{noun:+product}
// - 'product-urls' with pattern: {adjective:+positive}-{noun:+product}
// - 'api-endpoints' with pattern: {adjective:+tech}-{noun:+api}
```

**Series creation options:**
1. **SlugKit Dashboard**: Navigate to your organization → Series → Create New Series
2. **TypeScript SDK**: Use series creation methods (requires appropriate permissions)
3. **REST API**: POST to `/api/v1/series` endpoint

## Real-World Use Cases

### 1. Blog URL Generation

Transform your blog from generic URLs to SEO powerhouses using **mint** for guaranteed unique slugs:

**Traditional approach:**
```typescript
// pages/blog/[id].tsx - Generic numeric IDs
export async function getStaticPaths() {
  const posts = await getPosts();
  const paths = posts.map(post => ({ params: { id: post.id.toString() } }));
  return { paths, fallback: false };
}
```

**SlugKit approach:**
```typescript
// pages/blog/[slug].tsx - Beautiful, SEO-friendly URLs
import { slugkit } from '@/lib/slugkit';

export async function getStaticPaths() {
  const posts = await getPosts();
  
  // Generate unique slugs for posts without them using mint
  // Requires 'blog-posts' series to be created first
  const postsNeedingSlugs = posts.filter(post => !post.slug);
  if (postsNeedingSlugs.length > 0) {
    const slugs = await slugkit.mintSlugs('blog-posts', postsNeedingSlugs.length);
    
    // Assign slugs to posts
    for (let i = 0; i < postsNeedingSlugs.length; i++) {
      postsNeedingSlugs[i].slug = slugs[i];
      await updatePost(postsNeedingSlugs[i]);
    }
  }
  
  const paths = posts.map(post => ({ params: { slug: post.slug } }));
  return { paths, fallback: false };
}

export async function getStaticProps({ params }: { params: { slug: string } }) {
  const post = await getPostBySlug(params.slug);
  return { props: { post } };
}
```

**Result:**
- `/blog/creative-storytelling-guide`
- `/blog/innovative-design-principles`  
- `/blog/inspiring-productivity-methods`

### 2. User Profile System

Create memorable user handles that enhance social features using **mint** for uniqueness:

```typescript
// components/UserRegistration.tsx
import { useState } from 'react';
import { slugkit } from '@/lib/slugkit';

export function UserRegistration() {
  const [availableHandles, setAvailableHandles] = useState<string[]>([]);
  const [selectedHandle, setSelectedHandle] = useState<string>('');

  async function generateHandleOptions() {
    try {
      // Use forge for handle previews (don't consume mint quota for previews)
      const handles = await fetch('/api/generate-handles', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ preview: true, count: 8 })
      }).then(res => res.json());
      
      setAvailableHandles(handles.suggestions);
    } catch (error) {
      console.error('Handle generation failed:', error);
    }
  }

  async function selectHandle(handle: string) {
    try {
      // Reserve the handle using mint
      const response = await fetch('/api/generate-handles', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reserve: true, handle })
      });
      
      if (response.ok) {
        setSelectedHandle(handle);
      }
    } catch (error) {
      console.error('Handle reservation failed:', error);
    }
  }

  return (
    <div className="space-y-4">
      <button 
        onClick={generateHandleOptions}
        className="btn-primary"
      >
        Generate Handle Options
      </button>
      
      <div className="grid grid-cols-2 gap-2">
        {availableHandles.map(handle => (
          <button
            key={handle}
            onClick={() => selectHandle(handle)}
            className={`p-3 border rounded transition-colors ${
              selectedHandle === handle ? 'bg-blue-50 border-blue-500' : 'hover:bg-gray-50'
            }`}
          >
            @{handle}
          </button>
        ))}
      </div>
      
      {selectedHandle && (
        <div className="p-3 bg-green-50 border border-green-200 rounded">
          <strong>Your handle:</strong> @{selectedHandle}
          <br />
          <small>Profile URL: /user/{selectedHandle}</small>
        </div>
      )}
    </div>
  );
}
```

```typescript
// pages/api/generate-handles.ts
import { slugkit, patterns } from '@/lib/slugkit';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { preview, reserve, handle, count = 8 } = req.body;
    
    if (preview) {
      // Use forge for previews - doesn't consume mint quota
      const suggestions = await slugkit.forgeSlugs(patterns.userHandle, count);
      return res.json({ suggestions });
    }
    
    if (reserve && handle) {
      // Use mint to reserve a unique handle
      // Requires 'user-handles' series to be created first
      const reservedHandle = await slugkit.mintSlugs('user-handles', 1);
      // In production, you'd validate the handle matches one of the previews
      return res.json({ handle: reservedHandle[0] });
    }
    
    return res.status(400).json({ error: 'Invalid request' });
  } catch (error: any) {
    console.error('Handle generation error:', error);
    
    if ('retryAfter' in error) {
      return res.status(429).json({
        error: 'Rate limit exceeded',
        retryAfter: error.retryAfter
      });
    }

    res.status(500).json({ error: 'Failed to generate handles' });
  }
}
```

**Generated handles:**
- `@brave-tiger` → `/user/brave-tiger`
- `@clever-dolphin` → `/user/clever-dolphin`
- `@swift-falcon` → `/user/swift-falcon`

### 3. E-commerce Product URLs

Transform product pages into SEO-friendly, shareable URLs using mint for unique identifiers:

```typescript
// lib/products.ts
import { slugkit } from '@/lib/slugkit';

interface Product {
  id: string;
  name: string;
  slug?: string;
  sku?: string;
  description: string;
  price: number;
}

export async function createProduct(productData: Omit<Product, 'id' | 'slug' | 'sku'>) {
  // Generate both SKU and URL slug using mint for guaranteed uniqueness
  // Requires 'product-skus' and 'product-urls' series to be created first
  const [sku, slug] = await Promise.all([
    slugkit.mintSlugs('product-skus', 1),
    slugkit.mintSlugs('product-urls', 1)
  ]);
  
  const product: Product = {
    id: generateId(),
    sku: sku[0],
    slug: slug[0],
    ...productData
  };
  
  await saveProduct(product);
  return product;
}

export async function getProductBySlug(slug: string): Promise<Product | null> {
  return await db.products.findUnique({ where: { slug } });
}
```

```typescript
// pages/products/[slug].tsx
export async function getStaticProps({ params }: { params: { slug: string } }) {
  const product = await getProductBySlug(params.slug);
  
  if (!product) {
    return { notFound: true };
  }
  
  return {
    props: { product },
    revalidate: 60 // ISR for product updates
  };
}
```

**Product URLs:**
- `/products/swift-productivity-toolkit`
- `/products/elegant-design-suite`
- `/products/innovative-collaboration-platform`

### 4. API Route Organisation

Create intuitive API endpoints that developers love using mint for unique identifiers:

```typescript
// lib/api-generator.ts
import { slugkit } from '@/lib/slugkit';

export async function createApiEndpoint(endpointData: {
  name: string;
  method: string;
  description: string;
}) {
  // Use mint for guaranteed unique API endpoint identifiers
  // Requires 'api-endpoints' series to be created first
  const endpointId = await slugkit.mintSlugs('api-endpoints', 1);
  
  return {
    ...endpointData,
    endpointId: endpointId[0],
    path: `/api/${endpointId[0]}`,
    createdAt: new Date()
  };
}
```

**Generated API structure:**
```
/api/secure-auth-gateway
/api/swift-data-processor  
/api/reliable-notification-service
/api/efficient-search-engine
/api/robust-file-manager
/api/intelligent-analytics-hub
```

### 5. Dynamic Content Categories

Generate category systems that scale with your content:

```typescript
// lib/categories.ts
import { slugkit } from '@/lib/slugkit';

const categoryPatterns = {
  technology: '{adjective:+tech}-{noun:+innovation}',
  lifestyle: '{adjective:+positive}-{noun:+lifestyle}',
  business: '{adjective:+professional}-{noun:+business}',
  creative: '{adjective:+creative}-{noun:+art}'
};

export async function generateCategoryStructure() {
  const categories = {};
  
  for (const [type, pattern] of Object.entries(categoryPatterns)) {
    // Use forge for category suggestions (not requiring uniqueness)
    const slugs = await slugkit.forgeSlugs(pattern, 5);
    categories[type] = slugs.map(slug => ({
      slug,
      url: `/category/${type}/${slug}`,
      type
    }));
  }
  
  return categories;
}
```

**Generated category URLs:**
```
/category/technology/innovative-blockchain-solutions
/category/lifestyle/mindful-wellness-practices
/category/business/strategic-growth-methods
/category/creative/inspiring-visual-storytelling
```

## Series Setup Strategy

### Create Application Series

Set up dedicated series for your Next.js application using the SlugKit dashboard or API:

```typescript
// Example series configuration for your Next.js app:

// Blog posts with creative + content pattern  
// Series slug: 'blog-posts'
// Pattern: '{adjective:+creative}-{noun:+content}'

// User handles with personality + animal pattern
// Series slug: 'user-handles'  
// Pattern: '{adjective:+personality}-{noun:+animal}'

// Product SKUs with tech + product pattern
// Series slug: 'product-skus'
// Pattern: '{adjective:+tech}-{noun:+product}'

// Product URLs with positive + product pattern
// Series slug: 'product-urls'
// Pattern: '{adjective:+positive}-{noun:+product}'

// API endpoints with tech + api pattern
// Series slug: 'api-endpoints'
// Pattern: '{adjective:+tech}-{noun:+api}'
```

### Environment-Specific Series

Use different series for different environments:

```typescript
// lib/slugkit-config.ts
const getSlugKitConfig = () => {
  const env = process.env.NODE_ENV;
  
  const configs = {
    development: {
      backendUrl: 'http://localhost:8088',
      seriesPrefix: 'dev-'
    },
    staging: {
      backendUrl: 'https://staging-api.slugkit.com',
      seriesPrefix: 'staging-'
    },
    production: {
      backendUrl: 'https://api.slugkit.com',
      seriesPrefix: ''
    }
  };
  
  return configs[env] || configs.production;
};

export const config = getSlugKitConfig();

// Use in your slugkit client
export const getSeriesSlug = (baseName: string) => 
  `${config.seriesPrefix}${baseName}`;
```

```typescript
// Usage in your application
const blogSlugs = await slugkit.mintSlugs(getSeriesSlug('blog-posts'), 5);
```

## Advanced Next.js Patterns

### Server-Side Generation in API Routes

```typescript
// pages/api/generate-content-urls.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { slugkit, patterns } from '@/lib/slugkit';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { contentType, count = 5, unique = false } = req.body;
  
  try {
    const pattern = patterns[contentType] || patterns.blogPost;
    
    let slugs: string[];
    if (unique) {
      // Use mint for guaranteed unique content URLs
      // Requires series to be created first
      const seriesSlug = `${contentType}-urls`;
      slugs = await slugkit.mintSlugs(seriesSlug, Math.min(count, 20));
    } else {
      // Use forge for non-unique content (e.g., suggestions)
      slugs = await slugkit.forgeSlugs(pattern, Math.min(count, 20));
    }
    
    const urls = slugs.map(slug => ({
      slug,
      url: `/${contentType}/${slug}`,
      generated_at: new Date().toISOString()
    }));
    
    res.status(200).json({ success: true, urls });
  } catch (error: any) {
    if ('retryAfter' in error) {
      return res.status(429).json({
        error: 'Rate limit exceeded',
        retryAfter: error.retryAfter
      });
    }
    
    res.status(500).json({ error: 'Failed to generate URLs' });
  }
}
```

### Client-Side Pattern Testing

```typescript
// components/PatternPlayground.tsx
'use client';

import { useState } from 'react';
import { PatternParser } from '@slugkit/sdk';

export function PatternPlayground() {
  const [pattern, setPattern] = useState('{adjective}-{noun}');
  const [samples, setSamples] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [isValid, setIsValid] = useState(true);

  // Validate pattern client-side using SDK
  const validatePattern = (newPattern: string) => {
    try {
      const valid = PatternParser.validate(newPattern);
      setIsValid(valid);
      return valid;
    } catch (error) {
      setIsValid(false);
      return false;
    }
  };

  async function testPattern() {
    if (!validatePattern(pattern)) return;
    
    setLoading(true);
    try {
      const response = await fetch('/api/test-pattern', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pattern, count: 8 })
      });
      
      const data = await response.json();
      setSamples(data.samples || []);
    } catch (error) {
      console.error('Pattern test failed:', error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-1">
          SlugKit Pattern
        </label>
        <input
          type="text"
          value={pattern}
          onChange={(e) => {
            setPattern(e.target.value);
            validatePattern(e.target.value);
          }}
          className={`w-full border rounded px-3 py-2 font-mono ${
            isValid ? 'border-green-300' : 'border-red-300'
          }`}
          placeholder="Enter a SlugKit pattern"
        />
        {!isValid && (
          <p className="mt-1 text-sm text-red-600">Invalid pattern syntax</p>
        )}
      </div>
      
      <button
        onClick={testPattern}
        disabled={loading || !isValid}
        className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400"
      >
        {loading ? 'Testing...' : 'Test Pattern'}
      </button>
      
      {samples.length > 0 && (
        <div>
          <h3 className="font-medium mb-2">Generated Samples:</h3>
          <div className="grid grid-cols-2 gap-2">
            {samples.map((sample, i) => (
              <div key={i} className="p-2 bg-gray-50 border rounded font-mono text-sm">
                {sample}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
```

```typescript
// pages/api/test-pattern.ts
import { slugkit } from '@/lib/slugkit';
import { PatternParser } from '@slugkit/sdk';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { pattern, count = 8 } = req.body;
  
  try {
    // Validate pattern server-side
    if (!PatternParser.validate(pattern)) {
      return res.status(400).json({ error: 'Invalid pattern syntax' });
    }
    
    // Use forge for pattern testing (non-unique)
    const samples = await slugkit.forgeSlugs(pattern, Math.min(count, 20));
    
    res.status(200).json({ success: true, samples });
  } catch (error: any) {
    console.error('Pattern test error:', error);
    res.status(500).json({ error: 'Failed to test pattern' });
  }
}
```

## Client-Side Integration with SDK Keys

For browser-side slug generation (requires paid tier):

```typescript
// lib/client-slugkit.ts
'use client';

import { SlugKit } from '@slugkit/sdk';

let clientSlugKit: SlugKit | null = null;

export async function getClientSlugKit(): Promise<SlugKit> {
  if (!clientSlugKit) {
    // SDK keys are safe for client-side use
    clientSlugKit = await SlugKit.fromBackend(
      process.env.NEXT_PUBLIC_SLUGKIT_BACKEND_URL || 'https://api.slugkit.com',
      process.env.NEXT_PUBLIC_SLUGKIT_SDK_SLUG!
    );
  }
  return clientSlugKit;
}
```

```typescript
// components/ClientSideGenerator.tsx
'use client';

import { useState, useEffect } from 'react';
import { getClientSlugKit } from '@/lib/client-slugkit';

export function ClientSideGenerator() {
  const [slugs, setSlugs] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  async function generateClientSide() {
    setLoading(true);
    try {
      const slugkit = await getClientSlugKit();
      // Use forge for client-side generation (mint requires special permissions)
      const newSlugs = await slugkit.forgeSlugs('{adjective}-{noun}', 6);
      setSlugs(newSlugs);
    } catch (error) {
      console.error('Client-side generation failed:', error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="space-y-4">
      <button
        onClick={generateClientSide}
        disabled={loading}
        className="px-4 py-2 bg-purple-600 text-white rounded disabled:bg-gray-400"
      >
        {loading ? 'Generating...' : 'Generate Client-Side'}
      </button>
      
      {slugs.length > 0 && (
        <div className="grid grid-cols-2 gap-2">
          {slugs.map((slug, i) => (
            <div key={i} className="p-2 bg-purple-50 border rounded font-mono text-sm">
              {slug}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
```

## Performance Optimisation

### Caching Generated Slugs

```typescript
// lib/slug-cache.ts
const cache = new Map<string, { slugs: string[], timestamp: number }>();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

export async function getCachedSlugs(
  pattern: string, 
  count: number, 
  useForge: boolean = true
): Promise<string[]> {
  const key = `${useForge ? 'forge' : 'mint'}:${pattern}:${count}`;
  const cached = cache.get(key);
  
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.slugs;
  }
  
  let slugs: string[];
  if (useForge) {
    slugs = await slugkit.forgeSlugs(pattern, count);
  } else {
    // For mint, we can't cache since each call should be unique
    slugs = await slugkit.mintSlugs(pattern, count);
    return slugs; // Don't cache mint results
  }
  
  cache.set(key, { slugs, timestamp: Date.now() });
  return slugs;
}
```

### Batch URL Generation

```typescript
// lib/batch-operations.ts
export async function createMultipleProducts(productsData: ProductData[]) {
  // Generate all identifiers in batch using mint
  // Requires both series to be created first
  const [skus, slugs] = await Promise.all([
    slugkit.mintSlugs('product-skus', productsData.length),
    slugkit.mintSlugs('product-urls', productsData.length)
  ]);
  
  // Create products with pre-generated identifiers
  const products = productsData.map((data, index) => ({
    ...data,
    sku: skus[index],
    slug: slugs[index]
  }));
  
  return await db.products.createMany({ data: products });
}
```

## Error Handling and Fallbacks

```typescript
// lib/robust-slug-generation.ts
export async function generateSlugWithFallback(
  seriesSlug: string,
  fallbackPrefix: string = 'item'
): Promise<string> {
  try {
    const [slug] = await slugkit.mintSlugs(seriesSlug, 1);
    return slug;
  } catch (error: any) {
    console.warn('SlugKit mint failed, using fallback:', error);
    
    if ('retryAfter' in error && error.retryAfter < 60) {
      // Wait for reasonable retry period
      await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000));
      try {
        const [slug] = await slugkit.mintSlugs(seriesSlug, 1);
        return slug;
      } catch (retryError) {
        console.warn('SlugKit retry failed, using fallback');
      }
    }
    
    // Fallback to timestamp-based identifier
    return `${fallbackPrefix}-${Date.now()}`;
  }
}
```

## Best Practices for Next.js + SlugKit

### 1. Choose the Right Generation Method
- **Mint**: Production identifiers requiring guaranteed uniqueness (user handles, product SKUs, blog post slugs)
- **Forge**: Testing patterns, generating suggestions, non-unique content categories
- **Slice**: Previewing what will be generated without consuming quota

### 2. Use Server-Side Generation
Always generate production identifiers server-side with API keys:
```typescript
// ✅ Good: Server-side generation with mint
export async function getServerSideProps() {
  const userHandle = await slugkit.mintSlugs('user-handles', 1);
  return { props: { handle: userHandle[0] } };
}

// ❌ Avoid: Client-side generation for unique IDs
// SDK keys have limited mint permissions
```

### 3. Environment-Specific Configuration
```typescript
const getSlugKitConfig = () => {
  const env = process.env.NODE_ENV;
  
  return {
    development: {
      backendUrl: 'http://localhost:8088',
      seriesPrefix: 'dev-'
    },
    production: {
      backendUrl: 'https://api.slugkit.com',
      seriesPrefix: ''
    }
  }[env] || { backendUrl: 'https://api.slugkit.com', seriesPrefix: '' };
};
```

### 4. URL Structure
Maintain consistency across your application:
```
/blog/{creative-slug}
/user/{personality-handle}
/products/{positive-product-slug}
/category/{type}/{descriptive-category-slug}
```

## SEO Benefits with SlugKit URLs

### 1. Search Engine Optimisation
SlugKit URLs naturally contain relevant keywords:
```
/blog/effective-time-management → Contains "effective", "time", "management"
/products/professional-design-tools → Contains "professional", "design", "tools"
```

### 2. Social Media Sharing
Beautiful URLs encourage sharing:
```
"Check out this guide: yoursite.com/blog/creative-productivity-methods"
```

### 3. User Experience
Users can guess and remember URLs:
```
yoursite.com/user/swift-designer
yoursite.com/products/innovative-workflow-tools
```

## Next Steps

This recipe transforms your Next.js application into a user-friendly, SEO-optimised platform where every URL tells a story. Your users will love the memorable URLs, and search engines will reward your thoughtful approach to URL structure.

**Before implementing**: Make sure to set up your SlugKit series first! Learn more about series creation and management:

**Related Guides:**
- **[Choosing Generation Methods](choosing-generation-method)** - **Essential**: Understanding Forge vs Mint vs Slice and series setup
- **[Core Concepts](developer-core-concepts)** - **Essential**: Series creation and management fundamentals  
- [TypeScript SDK Installation](sdk-typescript-installation) - Complete SDK setup guide
- [TypeScript SDK Node.js Usage](sdk-typescript-nodejs) - Server-side patterns and best practices

**Core Concepts:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Master SlugKit pattern creation
- [Authentication Guide](api-authentication) - API keys vs SDK keys


---

# Refund Policy - 2025-08
Source: https://dev.slugkit.dev/docs/refund-policy-2025-08

# Refund and Cancellation Policy

**Effective Date:** August 15, 2025
**Version:** 2025-8

## 1. Refund Policy

### 1.1 Eligibility Period
Refunds for subscription purchases may be requested within **fourteen (14) business days** of the initial purchase date. After this period, all subscription fees are considered final and non-refundable.

### 1.2 Refund Processing
- All approved refunds will be processed through the original payment method and merchant used for the purchase
- Refund processing times depend on your payment provider and may take 3-10 business days to appear in your account
- We do not control the timing of refund processing once initiated by the payment merchant

### 1.3 Immediate Termination
Upon approval of a refund request, your subscription and access to the service will be terminated immediately. You will lose access to all subscription features and benefits without notice.

### 1.4 Trial Period Refunds
If you cancel your subscription during a free trial period and a payment has already been processed, a full refund will be issued provided the cancellation occurs within the fourteen (14) business day refund window.

## 2. Cancellation Policy

### 2.1 Subscription Cancellation
You may cancel your subscription at any time through your account settings or by contacting our support team. Cancelled subscriptions will remain active until the end of the current billing period.

### 2.2 End of Billing Period
- Cancelled subscriptions will not be automatically renewed or charged for subsequent billing periods
- You will retain full access to subscription features until the current paid period expires
- No prorated refunds will be provided for unused portions of cancelled subscriptions

### 2.3 Trial Cancellations
Subscriptions cancelled during free trial periods will not incur any charges unless payment has already been processed, in which case the refund policy outlined in Section 1.4 applies.

## 3. Refund Request Process

### 3.1 How to Request
To request a refund, you must:
- Contact our support team at support@slugkit.dev within the eligible period
- Provide your subscription details and reason for the refund request
- Confirm your understanding that service access will be terminated immediately

### 3.2 Processing Time
Refund requests will be reviewed within two (2) business days of receipt. You will be notified of the approval or denial of your request via email.

## 4. Exceptions and Limitations

### 4.1 No Refunds After Eligible Period
Refunds will not be provided for subscription fees paid more than fourteen (14) business days prior to the refund request, regardless of usage or circumstances.

### 4.2 Violation of Terms
Subscriptions terminated due to violation of our Terms of Service are not eligible for refunds under any circumstances.

### 4.3 Technical Issues
While we strive to provide reliable service, temporary technical issues or service interruptions do not constitute grounds for refunds outside the standard refund period.

## 5. Modifications to Policy

We reserve the right to modify this Refund and Cancellation Policy at any time. Changes will be effective immediately upon posting to our website. Continued use of our service after policy changes constitutes acceptance of the modified terms.

## 6. Contact Information

For questions about this policy or to request a refund or cancellation, please contact us at:

**Email:** support@slugkit.dev

## 7. Governing Law

This policy is governed by the laws of the Republic of Serbia without regard to conflict of law principles. Any disputes arising under this policy shall be subject to the exclusive jurisdiction of the courts of the Republic of Serbia.

---

**By subscribing to our service, you acknowledge that you have read, understood, and agree to be bound by this Refund and Cancellation Policy.**

---

# SlugKit Business Plan
Source: https://dev.slugkit.dev/docs/saas-business

# SlugKit Business Plan

Enterprise-ready slug generation for established companies and high-traffic applications. Get massive scale, unlimited slice capabilities, and business-critical support at an incredible value.

## What's Included

### **Enterprise-Scale Generation**
- **All core functions**: Forge, mint, and slice with unlimited streaming
- **50,000 forge slugs per day** - 2.5x more than Startup for themed generation
- **100,000 mint slugs per day** - 5x more than Startup for unique identifiers  
- **1,500,000 forge operations per month** - extensive campaign and batch capabilities
- **3,000,000 mint operations per month** - support massive user bases

### **High-Performance Infrastructure**
- **500 requests per minute** sustained rate - 2.5x more than Startup
- **5,000 requests per minute** burst capacity - handle any traffic scenario
- **Unlimited streaming** - continuous generation for any scenario
- **Priority processing** with guaranteed sub-millisecond response times

### **Advanced Enterprise Architecture**
- **Up to 20 series** per organisation - comprehensive multi-product and multi-environment support
- **Unlimited slice windows** - complete sequence access and management without restrictions
- **Advanced analytics** - detailed usage insights and performance monitoring
- **Enterprise integrations** - designed for complex organisational structures

### **Business-Critical Support**
- **Priority business support** with guaranteed SLA response times
- **Technical account guidance** for strategic planning and optimisation
- **Architecture consultation** for large-scale implementations
- **Direct escalation channels** for critical issues

## Perfect For

### **Established Enterprises**
- Companies with hundreds of thousands to millions of users
- Multi-product organisations requiring complex identifier hierarchies
- High-traffic applications where performance is critical
- Organisations requiring business-critical reliability and support

### **High-Volume Platforms**
- Social media platforms with extensive daily active users
- E-commerce marketplaces with large product catalogues
- SaaS platforms with significant customer bases
- Gaming platforms with active player communities

---

**Ready for enterprise-scale slug generation?** Get massive capacity, unlimited slice windows, and business-critical support for just $20/month.


---

# SlugKit Developer Plan
Source: https://dev.slugkit.dev/docs/saas-developer

# SlugKit Developer Plan

Unlock SlugKit's full power for individual developers and small teams. Get all three generation modes, higher quotas, and the flexibility you need for production applications at an incredibly affordable price.

## What's Included

### **Complete Generation Suite**
- **All three functions**: Forge, mint, and slice operations with full capabilities
- **Forge enabled**: Custom slug generation with complete pattern control
- **Mint enabled**: Auto-managed unique slug sequences with counter tracking
- **Slice enabled**: Deterministic range extraction without consuming counters

### **Production-Ready Quotas**
- **10,000 slugs per day** for both forge and mint - 10x more than Free
- **300,000 forge slugs per month** - perfect for campaign and batch generation
- **300,000 mint slugs per month** - support growing user bases
- **Up to 500 slugs per request** - efficient bulk operations

### **Enhanced Performance**
- **100 requests per minute** sustained rate - 10x more than Free  
- **1,000 requests per minute** burst capacity - handle significant traffic spikes
- **Full streaming support** - optimised for high-throughput scenarios
- **Sub-millisecond response times** for all generation methods

### **Advanced Project Management**
- **Up to 5 series** per organisation - separate concerns by application or environment
- **Slice window**: 5,000 positions back/forward for comprehensive sequence access
- **Complete pattern flexibility** - unlimited complexity and components
- **Series management** via dashboard and API

### **Professional Support**
- **Email support** - technical assistance when you need it
- **Priority response** - faster resolution for technical issues
- **Complete documentation** - comprehensive API and integration guides
- **Community access** - developer forums and shared knowledge

## Perfect For

### **Individual Developers**
- Building production applications with moderate scale requirements
- Freelancers working on multiple client projects
- Solo entrepreneurs creating SaaS applications
- Developers who need reliable, professional identifier generation

### **Small Development Teams**
- Startups in early production phases (100-10k users)
- Small agencies managing multiple client projects
- Development teams requiring all three generation modes
- Applications with diverse identifier needs across environments

### **Production Applications**
- Web applications with user-generated content
- E-commerce platforms needing product identifiers
- API services requiring readable resource names
- Mobile apps with social or community features

## Real-World Use Cases

### **User Handle Generation (Mint)**
```bash
# Generate unique user handles for social platform
POST /api/mint
{"series": "user-handles", "count": 100}
→ ["cosmic-developer", "clever-architect", "swift-engineer", ...]

# Perfect for: Social platforms, community sites, user directories
```

### **Marketing Campaign Codes (Forge)**
```bash
# Create themed campaign identifiers with custom seeds
POST /api/forge  
{
  "pattern": "launch-{adjective}-{number:2x}",
  "seed": "spring-2025",
  "count": 50
}
→ ["launch-brilliant-f3", "launch-dynamic-a8", "launch-creative-2d", ...]

# Perfect for: Marketing campaigns, promo codes, event identifiers
```

### **Development Environment Coordination (Slice)**
```bash
# Preview upcoming slugs without consuming them
POST /api/slice
{"series": "user-handles", "start": 1000, "count": 100}
→ [Preview of next 100 handles without advancing counter]

# Perfect for: Testing, staging environments, coordination between teams
```

### **Product SKU Generation (Forge)**
```bash
# Create branded product identifiers with consistent styling
POST /api/forge
{
  "pattern": "{Adjective:+premium}-{NOUN:+product}-{number:3X}",
  "count": 25
}
→ ["Premium-GADGET-A4F", "Essential-DEVICE-B7D", "Ultimate-SYSTEM-C2A", ...]

# Perfect for: E-commerce, inventory management, product catalogs
```

## Understanding the Three Functions

### **Mint: Guaranteed Uniqueness**
- **Automatic counter management** - no coordination needed
- **Series-scoped uniqueness** - no collisions within domain
- **Production-ready** - safe for user-facing identifiers
- **10,000 per day** - sufficient for growing applications

### **Forge: Custom Control**  
- **Pattern flexibility** - any pattern with custom seeds
- **Themed generation** - create cohesive identifier sets
- **Testing-friendly** - reproducible results with same parameters
- **10,000 per day** - perfect for campaigns and batch operations

### **Slice: Preview & Coordination**
- **Counter-independent** - explore without consuming quota
- **Range access** - get specific sequence segments  
- **Team coordination** - preview upcoming identifiers
- **5,000 position window** - comprehensive sequence exploration

## Technical Capabilities

### **Advanced Pattern Features**
With Developer plan, you get unlimited pattern complexity:

```bash
# Complex filtering and case transformations
POST /api/forge
{
  "pattern": "{adjective:+tech-corporate<8}-{Noun@en:+product>4}-{number:4x}",
  "count": 10
}
→ ["agile-Framework-3a2f", "robust-Platform-8b4d", ...]
```

### **Multi-Environment Setup**
Use different series for different environments:

```bash
# Development environment
POST /api/mint
{"series": "dev-user-handles", "count": 50}

# Staging environment  
POST /api/slice  
{"series": "prod-user-handles", "start": 0, "count": 50}

# Production environment
POST /api/mint
{"series": "prod-user-handles", "count": 10}
```

### **Efficient Bulk Operations**
Generate up to 500 slugs per request efficiently:

```bash
# Bulk user handle generation for data seeding
POST /api/mint
{"series": "user-handles", "count": 500}
→ [500 unique handles in single response]
```

## Performance & Reliability

### **Request Handling**
- **100 requests/minute** sustained - support multiple applications
- **1,000 requests/minute** burst - handle launch spikes confidently  
- **500 slugs per request** - efficient bulk operations
- **Consistent response times** - reliable performance under load

### **Monthly Capacity**  
- **300,000 total operations per month** across forge and mint
- **Predictable costs** - no overage charges or surprises
- **Usage monitoring** - track consumption via dashboard
- **Quota alerts** - notifications before limits are reached

### **Service Reliability**
- **99.9% uptime target** - reliable for production use
- **Multiple region deployment** - low latency worldwide
- **Automatic failover** - seamless handling of infrastructure issues
- **Status monitoring** - transparent service health reporting

## Pricing & Value

### **Incredible Affordability**
- **$5 per month** or **$50 per year** (2 months free)
- **Less than $0.20 per day** - extraordinary value for the capabilities
- **No hidden fees** - transparent, predictable pricing
- **Cancel anytime** - no long-term commitments required

### **Cost Comparison**
- **Alternative solutions**: Custom development costs hundreds of hours
- **UUID generators**: No human readability or branding
- **DIY approaches**: Ongoing maintenance and scaling challenges  
- **SlugKit Developer**: Complete solution for less than a coffee per month

## Migration & Scaling

### **Seamless Upgrades**
- **From Free**: Keep all existing series and configurations
- **To higher tiers**: Instant access to increased quotas
- **No code changes** - same API across all plans
- **Data preservation** - never lose generated slugs or series

### **When to Upgrade**
- **Startup Plan ($10/month)** - when you need 2x capacity and 10 series
- **Business Plan ($20/month)** - for high-traffic applications  
- **Enterprise** - unlimited scale with white-glove support

---

**Ready to unlock SlugKit's full potential?** Get all three generation modes, 10x more capacity, and professional support for just $5/month. Perfect for developers who demand reliability, flexibility, and exceptional value.


---

# SlugKit SaaS Enterprise
Source: https://dev.slugkit.dev/docs/saas-enterprise

# SlugKit SaaS Enterprise

Custom-tailored cloud slug generation solutions for unique requirements. Whether you need dedicated infrastructure, unlimited scale, specialised compliance, or custom features, SaaS Enterprise delivers bespoke cloud solutions designed specifically for your needs.

## What's Included

### **Completely Customizable Cloud Solution**
- **Unlimited everything** - requests, generation, series, complexity (all negotiable)
- **Dedicated infrastructure options** - private cloud deployment in your preferred regions
- **Bespoke feature development** - cloud-native functionality built for your requirements
- **Flexible deployment models** - multi-region, hybrid cloud, or specialised configurations

### **Dedicated Cloud Deployment Options**
- **Private cloud infrastructure** - dedicated SlugKit deployment isolated from other customers
- **Custom geographic placement** - deploy in specific regions for data residency requirements
- **Dedicated support teams** - white-glove service with dedicated account management
- **Custom SLA agreements** - negotiate availability, performance, and support terms

### **Advanced Cloud-Native Features**
- **Custom API development** - bespoke endpoints and integration patterns
- **Advanced analytics** - custom dashboards, reporting, and usage insights
- **Multi-tenant architectures** - sophisticated isolation and customer management
- **Global edge deployment** - ultra-low latency with custom edge locations

### **Enterprise Integration Suite**
- **Custom SSO integration** - bespoke authentication and authorisation systems
- **Advanced webhook systems** - real-time event streaming and notifications
- **Custom data pipelines** - specialised data export, import, and synchronisation
- **API gateway integration** - enterprise-grade traffic management and security

## Perfect For

### **Unique Cloud Requirements**
- **Specialised compliance** - custom regulatory frameworks (SOC 2+, FedRAMP, industry-specific)
- **Custom data residency** - specific geographic or jurisdictional requirements
- **Unusual scale requirements** - beyond standard plan capacities
- **Specialised integration needs** - bespoke cloud APIs or protocols

### **Traditional Enterprise Cloud Users**
- **Fortune 500 corporations** - unlimited cloud scale with dedicated infrastructure
- **Global enterprises** - multi-region deployment with custom coordination
- **Platform companies** - embedding SlugKit into cloud products and services
- **High-traffic applications** - millions of users with specialised performance requirements

### **Non-Traditional Enterprise Users**
- **Fast-growing startups** - custom solutions that scale beyond standard tiers
- **SaaS platforms** - white-label slug generation for their customers
- **API companies** - specialised identifier services as part of broader offerings
- **Research platforms** - academic or scientific cloud computing requirements

## Custom Cloud Solutions & Features

### **Dedicated Infrastructure Options**
```yaml
# Example dedicated deployment
deployment_type: dedicated_private_cloud
infrastructure:
  regions: [us-east-1, eu-west-1, ap-southeast-1]
  isolation: complete_customer_isolation  
  networking: private_vpc_with_custom_routes
  data_residency: strict_geographic_boundaries
  
performance:
  guaranteed_latency: sub_millisecond
  dedicated_capacity: unlimited
  custom_sla: 99.999_percent_uptime
```

### **Custom Cloud-Native Features**
```yaml
# Bespoke cloud functionality
custom_features:
  - real_time_slug_streaming
  - custom_analytics_dashboards
  - advanced_multi_tenant_isolation
  - specialized_caching_strategies
  - custom_rate_limiting_algorithms
  - bespoke_webhook_systems
```

### **Hybrid Cloud-Premises Solutions**
```yaml
# Combined cloud and on-premises deployment
architecture: hybrid_cloud_premises
components:
  cloud: high_availability_coordination_layer
  on_premises: sensitive_data_processing
  edge: ultra_low_latency_generation
coordination: encrypted_cross_boundary_sync
```

## Advanced Dedicated Deployment

### **Private Cloud Architecture**
```yaml
# Dedicated SlugKit cloud instance  
dedicated_deployment:
  isolation: complete_infrastructure_isolation
  custom_domains: your-slugs.company.com
  dedicated_ips: customer_specific_ip_ranges
  custom_ssl: your_certificates_and_ca
  
infrastructure:
  compute: dedicated_kubernetes_clusters
  storage: isolated_database_instances  
  networking: private_vpc_with_vpn_access
  monitoring: custom_observability_stack
```

### **Multi-Region Dedicated Deployment**
```yaml
# Global private cloud footprint
regions:
  primary: us-east-1
    role: primary_coordination
    capacity: unlimited
    features: full_feature_set
  secondary: eu-west-1  
    role: regional_processing
    compliance: gdpr_optimized
    data_residency: eu_only
  tertiary: ap-southeast-1
    role: low_latency_edge
    optimization: sub_millisecond_response
```

### **Custom Cloud APIs**
```bash
# Bespoke API endpoints for your dedicated deployment
POST https://your-slugs.company.com/api/v2/custom-endpoint
{
  "custom_parameters": {
    "your_specific_requirements": true,
    "bespoke_functionality": "tailored_to_your_needs"
  }
}

# White-label API for your customers
POST https://your-platform.com/api/identifiers
# Powered by SlugKit Enterprise, branded as your service
```

## Custom Pricing & Service Models

### **Flexible Commercial Terms**
- **Dedicated infrastructure pricing** - based on reserved capacity and isolation level
- **Feature-based pricing** - pay only for the custom capabilities you need  
- **Usage-based models** - scaling pricing with actual consumption patterns
- **Hybrid pricing** - combination of fixed infrastructure and variable usage costs

### **Example Pricing Scenarios**
```yaml
# SaaS platform with white-label slug generation
pricing_model: revenue_sharing
features: [white_label_apis, unlimited_scale, custom_branding]
cost_structure: percentage_of_customer_revenue

# Global enterprise with data residency requirements  
pricing_model: dedicated_multi_region
features: [private_cloud, custom_compliance, 24x7_support]
cost_structure: annual_fixed_plus_usage

# High-growth startup with unique requirements
pricing_model: success_based_scaling
features: [custom_apis, rapid_scaling, startup_support]
cost_structure: growth_milestone_pricing
```

### **Dedicated Infrastructure Pricing**
- **Reserved capacity** - guaranteed resources with predictable costs
- **Isolation premium** - additional cost for complete infrastructure isolation
- **Geographic placement** - pricing varies by region and data residency requirements
- **Custom SLA terms** - enhanced availability guarantees with transparent pricing

## Feature Request Process

### **Submit Your Cloud Requirements**
Use our SaaS Enterprise feature request form to describe:
- **Specific cloud use case** - detailed description of your requirements
- **Infrastructure needs** - geographic, performance, and isolation requirements
- **Compliance requirements** - regulatory, legal, or industry-specific needs
- **Integration requirements** - API, authentication, and data flow needs

### **Solution Design Phase**
1. **Requirements analysis** - cloud architecture and business requirements review
2. **Infrastructure design** - dedicated deployment architecture and resource planning
3. **Feature planning** - custom cloud-native functionality specification
4. **Proposal generation** - detailed solution proposal with transparent pricing

### **Deployment & Management**
1. **Infrastructure provisioning** - dedicated cloud resources and custom configuration
2. **Custom development** - bespoke features and integration development
3. **Testing and validation** - comprehensive testing in your dedicated environment
4. **Go-live support** - dedicated launch support and performance monitoring

## Dedicated vs Standard SaaS

### **When to Choose Dedicated SaaS Enterprise**
- **Data isolation requirements** - need complete separation from other customers
- **Custom performance requirements** - specific latency, throughput, or availability needs
- **Regulatory compliance** - specialised frameworks requiring infrastructure isolation
- **White-label requirements** - offering slug generation under your brand

### **Dedicated Infrastructure Benefits**
```yaml
# Advantages of dedicated deployment
benefits:
  complete_isolation: no_shared_infrastructure
  custom_performance: tailored_to_your_workloads  
  regulatory_compliance: meets_specialized_requirements
  brand_control: fully_customizable_experience
  predictable_performance: no_noisy_neighbor_issues
```

### **Hybrid Cloud-Premises Options**
- **Sensitive data on-premises** - keep critical data in your environment
- **Coordination in cloud** - use cloud for scaling and coordination
- **Edge processing** - ultra-low latency at network edge
- **Disaster recovery** - cross-boundary backup and failover

## Custom Integration Examples

### **Platform Integration**
```bash
# Your platform offering slug generation to customers
# Powered by dedicated SlugKit Enterprise

# Your customer's API call
POST https://your-platform.com/api/generate-identifiers
Authorization: Bearer your-customer-token
{
  "pattern": "{adjective}-{noun}",
  "count": 1000,
  "branding": "customer-preferred"
}

# Transparently powered by your dedicated SlugKit infrastructure
```

### **Advanced Analytics Integration**
```yaml
# Custom analytics and reporting
analytics:
  real_time_dashboards: customer_usage_patterns
  predictive_scaling: ai_powered_capacity_planning
  custom_reporting: tailored_business_intelligence
  data_export: flexible_format_support
```

## Support for All Organisation Sizes

### **Not Just for Large Enterprises**
SaaS Enterprise solutions work for any organisation with unique cloud requirements:
- **Growing startups** - custom solutions that scale beyond standard tiers
- **Specialised use cases** - unique requirements not met by standard plans
- **Compliance requirements** - specific regulatory or security needs
- **Strategic partnerships** - long-term collaboration and development

### **Custom Solutions for Unique Needs**
```yaml
# Example non-traditional enterprise use case
use_case: creative_agency_platform
requirements:
  - white_label_client_services
  - campaign_specific_branding  
  - creative_approval_workflows
  - client_isolation_and_billing
pricing: client_success_based_model
```

## Getting Started

### **Feature Request Process**
Submit your requirements through our SaaS Enterprise feature request:
1. **Describe your cloud use case** - detailed explanation of requirements
2. **Infrastructure preferences** - regions, isolation, and performance needs
3. **Compliance and integration** - regulatory and technical requirements
4. **Timeline and budget** - project parameters and business constraints

### **Consultation Options**
- **Cloud architecture consultation** - free discussion of your requirements
- **Dedicated deployment planning** - infrastructure design and cost modelling  
- **Custom feature planning** - collaborative development of bespoke functionality
- **Hybrid solution design** - combining cloud and on-premises deployment

### **Alternative: On-Premise Enterprise**
For some requirements, **On-Premise Enterprise** might be more suitable:
- **Complete air-gap deployment** - no cloud connectivity required
- **Maximum data sovereignty** - everything in your infrastructure
- **Custom hardware integration** - specialised deployment environments

---

**Need custom cloud slug generation beyond standard SaaS plans?** Submit a feature request to explore SaaS Enterprise solutions with dedicated infrastructure, unlimited scale, and bespoke cloud-native features designed specifically for your requirements.


---

# SlugKit Friends & Family Plan
Source: https://dev.slugkit.dev/docs/saas-fnf

# SlugKit Friends & Family Plan

Our most generous plan, awarded to early adopters who help shape SlugKit through valuable contributions during beta.

## What's Included

### **Unlimited Everything**
- **Unlimited forge operations** - no daily or monthly caps
- **Unlimited mint operations** - generate as many unique slugs as you need
- **Unlimited slice operations** - explore sequences without restrictions
- **Unlimited series** - manage as many identifier streams as your projects require
- **Unlimited streaming** - no caps on bulk generation requests

### **Enhanced Performance Access**
- **50 requests per minute** sustained rate
- **500 requests per minute** burst capacity
- **1,000 slugs per request** - efficient batch generation
- **Full streaming support** - truly unlimited bulk operations

### **Complete Feature Access**
- **All generation methods** - forge, mint, and slice
- **SDK access** - official Python and TypeScript SDKs
- **MCP integration** - full support for AI agent workflows
- **Advanced patterns** - complexity up to 60, up to 6 components
- **Full API access** - complete series management and statistics

### **Forever Guarantee**
- **Free for life** - no expiration, no billing, ever
- **Survives platform changes** - grandfathered through all updates
- **Transfers to production** - your F&F status moves with you when beta ends
- **No strings attached** - truly unlimited, genuinely free

## How to Earn F&F Status

This plan isn't available for purchase and can't be requested directly. It's awarded to contributors who actively help make SlugKit better.

### **Valuable Feedback Contributors**
Provide substantive feedback that shapes SlugKit's development:
- Detailed use case descriptions and integration experiences
- Thoughtful feature suggestions with clear reasoning
- Documentation improvements and clarity suggestions
- UX/API design feedback that influences decisions
- Real-world usage patterns that inform development priorities

**Note:** "It's cool" or "works fine" doesn't count. We're looking for the kind of feedback that makes us rethink our approach or reveals important use cases we hadn't considered.

### **Bug Hunters**
Find and report genuine issues that improve SlugKit's reliability:
- Reproducible bugs with clear steps
- Edge cases that break expected behaviour
- Performance issues with profiling data
- Documentation errors or misleading examples
- Security concerns or potential vulnerabilities

**Note:** Minor typos or cosmetic issues don't qualify. We're rewarding discovery of real problems that affect functionality.

### **Early Adopter Excellence**
Go above and beyond in helping test and validate SlugKit:
- Integrate SlugKit into production projects during beta
- Share detailed integration stories or case studies
- Help other users in community discussions
- Contribute to open source components
- Create tutorials, examples, or tools that benefit the community

## recognition Process

### **How Awards Work**
- **Manual review** - we evaluate contributions individually
- **Direct contact** - we'll reach out if you've earned F&F status
- **No application** - don't ask for it, earn it through contribution
- **Limited availability** - only awarded to truly exceptional contributors

### **What Happens When Awarded**
1. **We contact you** via email with F&F plan offer
2. **Plan upgrade** happens immediately in beta environment
3. **Status documented** for production migration
4. **Permanent record** ensures you're grandfathered forever

### **Fair Evaluation**
We track contributions across:
- GitHub issues and discussions
- Email feedback and bug reports
- Community forum participation
- Public advocacy and content creation
- Integration depth and production usage

Quality matters more than quantity. One excellent bug report beats ten trivial comments.

## Why F&F Exists

### **Building with the Community**
Early adopters take real risks using beta software. F&F status rewards those who don't just use SlugKit, but actively help make it better.

### **Learning from Production Use**
The best feedback comes from real integration challenges. F&F unlimited access enables ambitious projects that stress-test our infrastructure and reveal important insights.

### **Creating Advocates**
Users who genuinely contribute become natural advocates. F&F status recognises this relationship and ensures we grow together.

### **Sustainable Gratitude**
We can't make SlugKit free for everyone, but we can make it free forever for those who help build it. F&F is our way of saying thank you with something meaningful.

## Comparing to Other Plans

### **vs Beta Tester Plan**
- **Unlimited operations** (vs 10k/day)
- **Unlimited series** (vs 10)
- **Unlimited streaming** (vs 10k per request)
- **Forever free** (vs temporary beta access)
- **Must be earned** (vs automatic enrollment)

### **vs Paid Plans**
F&F provides unlimited access that exceeds even our highest paid tiers, but it's not a paid plan alternative - it's recognition of community contribution.

### **vs Free Plan**
When beta ends and free tier launches, F&F holders keep unlimited access while free users get basic limits.

## F&F Philosophy

This isn't a marketing gimmick or limited-time offer. F&F status is genuine recognition that certain users made SlugKit better through their contributions during its most vulnerable stage.

If you're thinking "how do I get F&F status?" - you're asking the wrong question. The right question is "how can I help make SlugKit better?" Answer that through meaningful contribution, and F&F status might follow naturally.

**Focus on contribution, not rewards.** The best F&F recipients are those who never asked for it.

---

**Currently in beta?** Use SlugKit, share real feedback, report actual bugs, build something interesting. If your contributions stand out, we'll notice.


---

# SlugKit Free Plan
Source: https://dev.slugkit.dev/docs/saas-free

# SlugKit Free Plan

Get started with SlugKit at no cost and discover the power of human-readable identifier generation. Perfect for personal projects, learning, and small-scale applications.

## What's Included

### **Core Generation Capability**
- **Mint enabled**: Generate unique slugs with automatic counter management
- **Forge and slice disabled**: Focus on the essential unique identifier generation
- **Up to 3 series per organisation** - manage multiple identifier streams
- **Full pattern language access** - create sophisticated slug patterns

### **Generous Usage Quotas**
- **1,000 mint slugs per day** - perfect for personal projects and learning
- **25,000 mint slugs per month** - sufficient for small applications  
- **Up to 500 slugs per request** - efficient batch generation
- **25 requests per request limit** - structured API usage

### **Essential Performance**
- **10 requests per minute** sustained rate - reliable for development use
- **100 requests per minute** burst capacity - handle occasional spikes
- **Sub-millisecond response times** for individual slug generation
- **Full streaming support** - efficient bulk operations

### **Complete Pattern Access**
- **Full pattern language** - access to all dictionary selectors and generators
- **17,000+ adjectives, 41,000+ nouns** - rich vocabulary for diverse slugs  
- **Number and special character generators** - complete flexibility
- **Mathematical case transformations** - create branded identifier styles

## Perfect For

### **Getting Started**
- Learning SlugKit's powerful pattern language
- Prototyping new applications and services
- Personal projects and side ventures
- Exploring unique identifier generation concepts

### **Small-Scale Applications**
- Personal websites and blogs needing readable URLs
- Small internal tools requiring friendly identifiers
- Educational projects and tutorials
- Open source projects with moderate ID needs

### **Development & Testing**
- Understanding SlugKit's capabilities before upgrading
- Building proofs of concept for larger projects
- Testing integration approaches in development environments
- Demonstrating human-readable IDs to stakeholders

## Real-World Examples

### **Personal Blog Post URLs**
```bash
# Generate memorable post identifiers
POST /api/mint
{"series": "blog-posts", "count": 5}
→ ["witty-telescope", "clever-symphony", "bright-adventure", ...]
```

### **Project Repository Names**  
```bash
# Create engaging repository identifiers
POST /api/mint
{"series": "personal-repos", "count": 10}
→ ["cosmic-framework", "elegant-toolkit", "swift-engine", ...]
```

### **User Handle Generation**
```bash
# Generate friendly user handles for small community
POST /api/mint  
{"series": "community-handles", "count": 25}
→ ["creative-developer", "thoughtful-designer", "innovative-writer", ...]
```

### **Learning Pattern Design**
With access to SlugKit's full pattern language, you can experiment with sophisticated patterns:

```bash
# Test complex patterns with mathematical case transformations
POST /api/mint
{"series": "pattern-experiments"}
# With series pattern: "{AdJeCtIvE}-{noun}-{number:2x}"
→ ["InNoVaTiVe-keyboard-f3", "CrEaTiVe-telescope-a7", ...]
```

## Understanding Mint Operation

The Free plan focuses on **mint** - SlugKit's core unique identifier generation:

### **How Mint Works**
- **Series-based**: Each series maintains its own counter and pattern
- **Guaranteed uniqueness**: No collisions within a series domain
- **Automatic progression**: Counter advances with each generation
- **Deterministic**: Same series configuration produces predictable sequences

### **Series Management**
- **Up to 3 series** - organise by project, purpose, or pattern type
- **Pattern per series** - each series can have its own identifier style
- **Counter tracking** - automatic management of uniqueness state
- **Pattern flexibility** - full access to SlugKit's pattern language

## Why Start with Mint?

Mint is SlugKit's most essential function because it provides:
- **Production reliability** - guaranteed unique identifiers
- **Scalability foundation** - learn patterns that work at any scale  
- **Real-world applicability** - exactly what most applications need
- **Upgrade readiness** - skills transfer directly to paid plans

## Getting Started

### **Quick Setup**
1. **Sign up** for your free SlugKit account
2. **Create your first series** with a pattern like `{adjective}-{noun}`
3. **Generate unique slugs** using the mint operation
4. **Experiment with patterns** to find your preferred style

### **Learning Path**
1. **Basic patterns** - start with `{adjective}-{noun}` 
2. **Add numbers** - try `{adjective}-{noun}-{number:2x}`
3. **Explore case transformations** - experiment with `{AdJeCtIvE}-{NOUN}`
4. **Advanced filtering** - use tags like `{adjective:+positive}-{noun:+tech}`

### **Integration Example**
```bash
# Simple integration for blog post slugs
curl -X POST https://api.slugkit.com/api/mint \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"series": "blog-posts", "count": 1}'
```

## Upgrade When You're Ready

### **Natural Progression**
- **Developer Plan ($5/month)** - adds forge and slice, 5x more capacity
- **All paid plans** include forge for custom slug batches
- **All paid plans** include slice for sequence exploration
- **Higher quotas** for growing applications

### **Seamless Migration**
- **Keep existing series** - all your configurations transfer
- **Same API** - no code changes required
- **Immediate access** to expanded features
- **Predictable pricing** - transparent cost progression

## Support & Resources

### **Learning Resources**
- **Complete documentation** - comprehensive API and pattern guides
- **Community support** - GitHub discussions and developer forums
- **Pattern examples** - real-world use cases and implementations
- **Integration tutorials** - step-by-step guides for popular frameworks

### **Getting Help**
- **Community forums** - connect with other SlugKit developers  
- **Documentation** - comprehensive guides and API reference
- **Email support** - technical assistance for account and billing issues
- **Upgrade assistance** - help choosing the right paid plan

---

**Ready to generate beautiful, unique identifiers?** Start with SlugKit Free and discover how human-readable slugs can enhance your applications and user experience.


---

# SaaS products
Source: https://dev.slugkit.dev/docs/saas-products

**SlugKit SaaS** – A fully managed, horizontally scalable slug generation service with instant availability. Define custom patterns, generate unique human-readable IDs via low-latency HTTP or gRPC (*gRPC API is currently WIP*) APIs, and manage projects through a secure web dashboard. No hosting or maintenance required – simply connect and start generating.


---

# SlugKit Beta Tester Plan
Source: https://dev.slugkit.dev/docs/saas-promo

# SlugKit Beta Tester Plan

Help us battle-test SlugKit in production and get 10x the capacity of our Free plan.

## What's Included

### **Generous Quotas**
- **10,000 forge operations per day** (vs 1,000 on Free)
- **10,000 mint operations per day** (vs 1,000 on Free)
- **250,000 operations per month** (vs 25,000 on Free)
- **100 requests per minute** sustained (vs 10 on Free)
- **1,000 requests per minute** burst (vs 100 on Free)

### **All Features Unlocked**
- **Forge, mint, and slice** - all three generation methods
- **SDK access** - official Python and TypeScript SDKs
- **10 series** - manage multiple identifier streams (vs 3 on Free)
- **Unlimited slice windows** - full sequence exploration
- **Advanced patterns** - higher complexity limits
- **Full API access** - complete series management

## What We Ask

- **Use SlugKit in real projects** - help us find issues under real load
- **Report bugs and share feedback** - via [GitHub](https://github.com/slugkit/slugkit-issues/tree/main) or email support@slugkit.dev
- **Optional testimonials** - if you find it valuable

## Beta Terms

**Duration:** Available until billing integration launches (we'll give plenty of notice)

**Transition:** Beta users receive preferential pricing when we launch paid plans

**Fair Use:** Designed for real production usage. We may contact exceptionally high-volume users to understand use cases and help optimise integrations.


---

# SlugKit Startup Plan
Source: https://dev.slugkit.dev/docs/saas-startup

# SlugKit Startup Plan

Designed for growing startups and scaling teams who need increased capacity and advanced features. Get double the generation power of Developer plan with expanded series management and comprehensive slice capabilities.

## What's Included

### **Enhanced Generation Power**
- **All three functions**: Forge, mint, and slice with full streaming capabilities
- **20,000 slugs per day** for both forge and mint - double the Developer capacity
- **600,000 forge slugs per month** - perfect for extensive campaign and batch operations
- **600,000 mint slugs per month** - support significant user growth
- **Up to 500 slugs per request** - efficient bulk operations

### **Startup-Scale Performance**
- **200 requests per minute** sustained rate - double the Developer throughput
- **2,000 requests per minute** burst capacity - handle substantial traffic spikes
- **Full streaming support** - optimised for high-volume scenarios
- **Sub-millisecond response times** across all generation methods

### **Advanced Project Management**
- **Up to 10 series** per organisation - double the organisational capacity
- **Slice window**: 10,000 positions back/forward - comprehensive sequence exploration
- **Advanced series coordination** - manage complex multi-project architectures
- **Unlimited pattern complexity** - no restrictions on sophistication

### **Business-Grade Support**
- **Priority business support** - faster response times for growing companies
- **Technical consultation** - guidance for scaling and optimisation
- **Implementation assistance** - help with complex integration scenarios
- **Growth planning** - capacity and architecture recommendations

## Perfect For

### **Scaling Startups**
- Companies experiencing rapid user growth (1k-50k+ users)
- Startups with multiple products or services requiring separate identifier domains
- Teams with 5-20 developers needing coordinated slug generation
- Applications requiring high-availability identifier generation

### **Multi-Project Organisations**
- **Product companies** - separate series for different applications
- **Agency environments** - isolated identifier domains per client
- **Multi-environment operations** - comprehensive dev/staging/production setups
- **Feature experimentation** - A/B testing with separate identifier streams

### **High-Growth Applications**
- Social platforms with expanding user bases
- E-commerce applications with growing product catalogues
- SaaS platforms with increasing customer acquisition
- Gaming platforms with active player communities

## Advanced Use Cases

### **Multi-Product Platform**
```bash
# Separate series for different product lines
POST /api/mint
{"series": "product-alpha-users", "count": 5000}
→ ["innovative-creator", "dynamic-builder", ...]

POST /api/mint
{"series": "product-beta-projects", "count": 2000}
→ ["scalable-framework", "robust-solution", ...]

POST /api/mint
{"series": "product-gamma-assets", "count": 3000}
→ ["premium-resource", "essential-tool", ...]
```

### **Comprehensive Campaign Management (Forge)**
```bash
# Large-scale themed campaign generation
POST /api/forge
{
  "pattern": "LAUNCH25-{Adjective:+dynamic+innovative}-{number:3X}",
  "seed": "product-launch-spring",
  "count": 10000
}
→ ["LAUNCH25-Dynamic-A4F", "LAUNCH25-Innovative-B7D", ...]

# Perfect for: Large marketing campaigns, event management, promotional codes
```

### **Advanced Sequence Management (Slice)**
```bash
# Explore extensive ranges without consuming quota
POST /api/slice
{"series": "user-handles", "start": 5000, "count": 1000}
→ [Preview 1000 handles starting at position 5000]

# With 10k back/forward window, explore sequences comprehensively
POST /api/slice  
{"series": "user-handles", "start": -5000, "count": 10000}
→ [Access 10k handles from 5000 positions behind current counter]
```

### **Multi-Environment Coordination**
```bash
# Development environment
POST /api/mint
{"series": "dev-user-handles", "count": 1000}

# Staging environment (preview production sequences)
POST /api/slice
{"series": "prod-user-handles", "start": 0, "count": 1000}

# Production environment  
POST /api/mint
{"series": "prod-user-handles", "count": 500}

# Quality assurance (test upcoming production handles)
POST /api/slice
{"series": "prod-user-handles", "start": 500, "count": 500}
```

## Technical Excellence

### **High-Performance Architecture**
- **200 requests/minute** sustained - support multiple applications and teams
- **2,000 requests/minute** burst - handle viral growth and launch spikes
- **20,000 daily operations** for forge and mint each
- **Advanced caching** - optimised performance for repeated patterns

### **Advanced Series Management**
With 10 series and 10k slice windows, you can:
- **Separate by environment** - dev, staging, production series per product
- **Isolate by feature** - different identifier domains for different app areas
- **Coordinate across teams** - shared series with comprehensive preview access
- **Plan for growth** - explore future sequences without consuming quota

### **Bulk Operations Excellence**
```bash
# Efficient high-volume generation
POST /api/mint
{"series": "user-onboarding", "count": 500}
→ [500 unique handles optimised for new user experience]

POST /api/forge
{
  "pattern": "promo-{adjective:+exciting}-{number:3x}",
  "count": 500,
  "seed": "holiday-campaign"
}
→ [500 themed promotional codes for holiday campaign]
```

## Growth & Scaling Features

### **Capacity Planning**
- **600,000 monthly operations** across forge and mint
- **Predictable scaling** - understand your growth trajectory
- **Usage analytics** - detailed insights into generation patterns
- **Quota monitoring** - proactive alerts before limits

### **Team Collaboration**
- **Shared organisation access** for development teams
- **Series-level coordination** - multiple teams working with shared resources
- **Preview capabilities** - slice operations for planning and coordination
- **Development workflow integration** - support CI/CD and testing scenarios

### **Performance Optimisation**
- **Pattern compilation caching** - faster repeated operations
- **Dictionary caching** - optimised word selection performance
- **Bulk operation efficiency** - amortised costs for high-volume generation
- **Request multiplexing** - efficient handling of concurrent operations

## Exceptional Value

### **Affordable Growth**
- **$10 per month** or **$100 per year** (2 months free)
- **Less than $0.35 per day** - incredible value for startup-scale capabilities
- **Double the capacity** of Developer plan for only 2x the price
- **No hidden fees** - transparent, predictable pricing

### **Cost Efficiency**
- **600,000+ monthly operations** - extensive capacity for growing applications
- **10 series management** - organise complex multi-project architectures
- **Advanced slice capabilities** - coordinate without consuming quota
- **Business-grade support** - faster response times and technical guidance

### **ROI Benefits**
- **Reduced development time** - no need to build custom slug systems
- **Enhanced user experience** - memorable, branded identifiers
- **Operational efficiency** - reliable identifier generation at scale
- **Future-proof architecture** - seamless scaling as you grow

## Migration & Scaling

### **Seamless Upgrades**
- **From Developer**: Keep all existing series, instantly access doubled capacity
- **To Business**: Upgrade when you need 5x capacity and unlimited slice windows  
- **No downtime** - instant access to increased quotas
- **Same API** - no code changes required

### **When to Upgrade to Business ($20/month)**
- **100,000+ daily operations** - when you need 5x the generation capacity
- **20+ series** - for complex multi-product architectures  
- **Unlimited slice windows** - when you need comprehensive sequence access
- **Enterprise-grade SLAs** - for mission-critical applications

---

**Ready to fuel your startup's growth?** Get double the generation capacity, 10 series, and advanced features for just $10/month. Perfect for scaling startups who need reliable, high-performance identifier generation.


---

# Python SDK Advanced Usage
Source: https://dev.slugkit.dev/docs/sdk-python-advanced

# Python SDK Advanced Usage

This guide covers advanced features of the SlugKit Python SDK including async/await patterns, error handling, streaming, custom configurations, and production best practices.

## Asynchronous Client

The async client is ideal for high-performance applications, web frameworks (FastAPI, Quart), and concurrent operations.

### Basic Async Usage

```python
import asyncio
from slugkit import AsyncClient

async def main():
    client = AsyncClient(
        base_url="https://dev.slugkit.dev/api/v1",
        api_key="your-api-key"
    )
    
    # All operations are async
    slugs = await client.series.mint(count=10)
    info = await client.series.info()
    limits = await client.limits()
    
    print(slugs)

asyncio.run(main())
```

### Concurrent Generation

Generate from multiple series concurrently:

```python
import asyncio
from slugkit import AsyncClient

async def generate_from_multiple_series():
    client = AsyncClient()
    
    # Generate concurrently from different series
    results = await asyncio.gather(
        client.series["user-handles"].mint(count=100),
        client.series["api-endpoints"].mint(count=50),
        client.series["resource-ids"].mint(count=200)
    )
    
    user_handles, api_endpoints, resource_ids = results
    return {
        "users": user_handles,
        "endpoints": api_endpoints,
        "resources": resource_ids
    }

# Run
data = asyncio.run(generate_from_multiple_series())
```

### FastAPI Integration

Integrate with FastAPI web framework:

```python
from fastapi import FastAPI, HTTPException
from slugkit import AsyncClient
from slugkit.base import SlugKitError

app = FastAPI()

# Initialize client at startup
@app.on_event("startup")
async def startup():
    app.state.slugkit = AsyncClient()

@app.post("/users")
async def create_user(name: str):
    try:
        # Generate unique user ID
        user_id = (await app.state.slugkit.series["users"].mint(count=1))[0]
        
        return {
            "id": user_id,
            "name": name,
            "url": f"/users/{user_id}"
        }
    except SlugKitError as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/generate/{pattern}")
async def test_pattern(pattern: str, count: int = 5):
    """Test a custom pattern."""
    try:
        slugs = await app.state.slugkit.forge(pattern, count=count)
        return {"pattern": pattern, "samples": slugs}
    except SlugKitError as e:
        raise HTTPException(status_code=400, detail=str(e))
```

### Async Streaming

Stream large batches asynchronously:

```python
from slugkit import AsyncClient

async def stream_slugs():
    client = AsyncClient()
    
    # Configure streaming generator
    generator = client.series.mint.with_limit(10000).with_batch_size(1000)
    
    # Stream asynchronously
    async for slug in generator:
        await process_slug(slug)  # Your async processing
        
async def process_slug(slug: str):
    # Simulate async processing
    await asyncio.sleep(0.01)
    print(slug)
```

## Comprehensive Error Handling

### Error Hierarchy

```python
from slugkit.base import (
    SlugKitError,              # Base exception
    SlugKitConnectionError,    # Network issues
    SlugKitAuthenticationError,# Auth failures
    SlugKitValidationError,    # Invalid input
    SlugKitRateLimitError,     # Rate limiting
    SlugKitQuotaError,         # Quota exceeded
    SlugKitServerError,        # Server errors
    SlugKitTimeoutError,       # Request timeout
)
```

### Handling Rate Limits

Rate limit errors include detailed information:

```python
from slugkit import SyncClient
from slugkit.base import SlugKitRateLimitError
import time

client = SyncClient()

try:
    slugs = client.series.mint(count=1000)
except SlugKitRateLimitError as e:
    # Access rate limit details
    print(f"Rate limit reason: {e.rate_limit_reason}")
    print(f"Retry after: {e.retry_after} seconds")
    print(f"RPM remaining: {e.rpm_remaining}")
    print(f"Daily remaining: {e.daily_remaining}")
    print(f"Monthly remaining: {e.monthly_remaining}")
    
    # Intelligent retry
    if e.rate_limit_reason in ["rate-limit-exceeded", "daily-limit-exceeded"]:
        # These have accurate retry-after values
        if e.retry_after:
            time.sleep(e.retry_after)
            slugs = client.series.mint(count=1000)
    else:
        # Monthly/lifetime limits - don't retry
        print("Quota exhausted - upgrade required")
```

### Rate Limit Reasons

Different reasons require different handling:

```python
def handle_rate_limit(error: SlugKitRateLimitError):
    """Handle rate limits based on reason."""
    reason = error.rate_limit_reason
    
    if reason == "rate-limit-exceeded":
        # RPM limit - short retry-after
        print(f"Rate limit hit - retry in {error.retry_after}s")
        return "retry"
    
    elif reason == "daily-limit-exceeded":
        # Daily limit - longer retry-after
        hours = error.retry_after / 3600
        print(f"Daily limit hit - retry in {hours:.1f} hours")
        return "retry"
    
    elif reason == "monthly-limit-exceeded":
        # Monthly limit - wait until next month
        print("Monthly quota exceeded - wait for reset")
        return "wait_monthly"
    
    elif reason == "lifetime-limit-exceeded":
        # Lifetime limit - upgrade required
        print("Lifetime quota exceeded - upgrade required")
        return "upgrade"
    
    elif reason == "not-available":
        # Feature not available to user
        print("Feature not available on your plan")
        return "upgrade"
    
    elif reason == "request-size-exceeded":
        # Request too large
        print("Request size too large - reduce batch size")
        return "reduce_size"
    
    else:
        # Unknown reason
        print(f"Rate limited: {reason}")
        return "unknown"
```

### Retry with Exponential Backoff

Implement custom retry logic:

```python
import time
import random
from slugkit import SyncClient
from slugkit.base import SlugKitRateLimitError, SlugKitServerError

def generate_with_retry(client: SyncClient, count: int, max_retries: int = 3):
    """Generate slugs with exponential backoff retry."""
    for attempt in range(max_retries):
        try:
            return client.series.mint(count=count)
        
        except SlugKitRateLimitError as e:
            if e.retry_after:
                # Use server-provided retry-after
                delay = e.retry_after
            else:
                # Exponential backoff: 2^attempt seconds + jitter
                delay = (2 ** attempt) + random.uniform(0, 1)
            
            if attempt < max_retries - 1:
                print(f"Rate limited. Retrying in {delay:.1f}s...")
                time.sleep(delay)
            else:
                raise
        
        except SlugKitServerError as e:
            # Retry server errors
            if attempt < max_retries - 1:
                delay = (2 ** attempt) + random.uniform(0, 1)
                print(f"Server error. Retrying in {delay:.1f}s...")
                time.sleep(delay)
            else:
                raise
    
    raise Exception("Max retries exceeded")
```

### Error Context

All errors include context for debugging:

```python
from slugkit.base import SlugKitError

try:
    slugs = client.series.mint(count=10)
except SlugKitError as e:
    # Access error context
    if e.context:
        print(f"Operation: {e.context.operation}")
        print(f"Endpoint: {e.context.endpoint}")
        print(f"Base URL: {e.context.base_url}")
        print(f"Additional info: {e.context.additional_info}")
    
    # Get recovery suggestions
    print(f"Suggestions: {e.get_recovery_suggestions()}")
```

## Streaming Large Batches

### Synchronous Streaming

Stream slugs efficiently:

```python
from slugkit import SyncClient

client = SyncClient()

# Configure streaming
generator = (
    client.series.mint
    .with_limit(100000)      # Total slugs to generate
    .with_batch_size(10000)  # Slugs per batch
)

# Stream and process
count = 0
for slug in generator:
    # Process each slug as it's generated
    save_to_database(slug)
    count += 1
    
    if count % 10000 == 0:
        print(f"Processed {count} slugs...")

print(f"Total: {count} slugs")
```

### Async Streaming with Progress

```python
from slugkit import AsyncClient
from tqdm.asyncio import tqdm

async def stream_with_progress(total: int):
    client = AsyncClient()
    
    generator = client.series.mint.with_limit(total).with_batch_size(5000)
    
    progress = tqdm(total=total, desc="Generating slugs")
    
    async for slug in generator:
        await process_async(slug)
        progress.update(1)
    
    progress.close()

asyncio.run(stream_with_progress(100000))
```

### Memory-Efficient Processing

Process large batches without loading all into memory:

```python
def process_large_batch(count: int):
    """Process slugs without loading all into memory."""
    client = SyncClient()
    
    # Stream in batches
    batch_size = 1000
    generator = client.series.mint.with_limit(count).with_batch_size(batch_size)
    
    batch = []
    for slug in generator:
        batch.append(slug)
        
        if len(batch) >= batch_size:
            # Process batch
            process_batch(batch)
            batch = []
    
    # Process remaining
    if batch:
        process_batch(batch)

def process_batch(slugs: list[str]):
    """Process a batch of slugs."""
    # Bulk insert to database, write to file, etc.
    print(f"Processing batch of {len(slugs)} slugs")
```

## Generator Configuration

### Fluent Configuration API

Chain configuration methods:

```python
# Configure generator with fluent API
generator = (
    client.series.mint
    .with_limit(1000)          # Total slugs to generate
    .with_batch_size(100)      # Batch size for streaming
    .starting_from(5000)       # Start from sequence 5000
)

# Generate
slugs = list(generator)
```

### Dry Run Mode

Preview without consuming sequence numbers:

```python
# Preview what will be generated
preview = client.series.slice.with_limit(20)
slugs = list(preview)

# Verify the pattern looks good
print("Preview:", slugs[:5])

# Now generate for real
actual = client.series.mint.with_limit(20)
actual_slugs = list(actual)
```

### Series-Specific Configuration

```python
# Access specific series
user_series = client.series["user-handles"]

# Generate with configuration
users = (
    user_series.mint
    .with_limit(100)
    .with_batch_size(10)
)

for user_id in users:
    create_user(user_id)
```

## Pattern Analysis

### Validate Patterns

Check pattern validity and capacity:

```python
# Validate pattern before using
pattern = "{adjective}-{noun}-{number:4d}"

info = client.forge.pattern_info(pattern)
print(f"Pattern: {info.pattern}")
print(f"Capacity: {info.capacity}")
print(f"Max length: {info.max_slug_length}")
print(f"Complexity: {info.complexity}")
print(f"Components: {info.components}")

# Only proceed if capacity is sufficient
if int(info.capacity) < 1000000:
    print("Warning: Low capacity pattern")
```

### Dictionary Information

Explore available dictionaries:

```python
# Get all dictionaries
dicts = client.forge.dictionary_info()
for d in dicts:
    print(f"{d.kind}: {d.count} words")

# Get tags for a dictionary
tags = client.forge.dictionary_tags("adjective", limit=10)
for tag in tags.items:
    print(f"Tag: {tag.tag}, Words: {tag.word_count}")
```

## Custom HTTP Client

### Advanced HTTP Configuration

```python
import httpx
from slugkit import SyncClient

def create_custom_client():
    """Create HTTP client with custom settings."""
    return httpx.Client(
        timeout=30.0,
        limits=httpx.Limits(
            max_connections=100,
            max_keepalive_connections=20
        ),
        transport=httpx.HTTPTransport(
            retries=3,
            verify=True  # SSL verification
        ),
        follow_redirects=True
    )

# Use custom client
client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="your-api-key",
    httpx_client_factory=create_custom_client
)
```

### Proxy Configuration

```python
import httpx
from slugkit import SyncClient

def create_proxy_client():
    """Create client with proxy support."""
    return httpx.Client(
        proxies={
            "http://": "http://proxy.example.com:8080",
            "https://": "http://proxy.example.com:8080"
        },
        timeout=30.0
    )

client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="your-api-key",
    httpx_client_factory=create_proxy_client
)
```

## Production Best Practices

### Connection Pooling

Reuse clients for better performance:

```python
# ✅ Good - reuse client
class SlugGenerator:
    def __init__(self):
        self.client = SyncClient()
    
    def generate(self, count: int):
        return self.client.series.mint(count=count)

# Create once, use many times
generator = SlugGenerator()
slugs1 = generator.generate(10)
slugs2 = generator.generate(20)

# ❌ Bad - creates new client each time
def generate_slugs(count: int):
    client = SyncClient()  # New connection every time
    return client.series.mint(count=count)
```

### Environment-Based Configuration

```python
import os
from slugkit import SyncClient

def create_client():
    """Create client based on environment."""
    env = os.getenv("ENVIRONMENT", "development")
    
    if env == "production":
        return SyncClient(
            base_url="https://api.slugkit.com/v1",
            api_key=os.getenv("SLUGKIT_PROD_API_KEY"),
            timeout=30.0
        )
    else:
        return SyncClient(
            base_url="https://dev.slugkit.dev/api/v1",
            api_key=os.getenv("SLUGKIT_DEV_API_KEY"),
            timeout=10.0
        )

client = create_client()
```

### Logging and Monitoring

```python
import logging
from slugkit import SyncClient
from slugkit.base import SlugKitError

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)

def generate_with_logging(count: int):
    """Generate slugs with comprehensive logging."""
    client = SyncClient()
    
    try:
        logger.info(f"Generating {count} slugs...")
        slugs = client.series.mint(count=count)
        logger.info(f"Successfully generated {len(slugs)} slugs")
        return slugs
    
    except SlugKitError as e:
        logger.error(f"Failed to generate slugs: {e}")
        logger.debug(f"Error context: {e.context}")
        raise
```

### Graceful Degradation

Fallback when SlugKit is unavailable:

```python
import uuid
from slugkit import SyncClient
from slugkit.base import SlugKitConnectionError

def generate_id(use_slugkit: bool = True):
    """Generate ID with fallback to UUID."""
    if use_slugkit:
        try:
            client = SyncClient()
            return client.series.mint(count=1)[0]
        except SlugKitConnectionError:
            logger.warning("SlugKit unavailable, falling back to UUID")
            return str(uuid.uuid4())
    else:
        return str(uuid.uuid4())
```

### Rate Limit Monitoring

Track and log rate limit usage:

```python
from slugkit import SyncClient

def monitor_limits():
    """Monitor subscription limits and usage."""
    client = SyncClient()
    
    # Get current limits
    limits = client.limits()
    stats = client.series.stats()
    
    # Calculate usage
    total_minted = sum(s.total_count for s in stats if s.event_type == "mint")
    
    # Check thresholds
    if limits.max_mint_per_day:
        usage_pct = (total_minted / limits.max_mint_per_day) * 100
        if usage_pct > 80:
            logger.warning(f"High daily usage: {usage_pct:.1f}%")
    
    return {
        "limits": limits,
        "usage": total_minted,
        "stats": stats
    }
```

## Testing

### Mocking for Tests

Mock the SlugKit client in unit tests:

```python
from unittest.mock import Mock, patch
import pytest

def test_user_creation():
    """Test user creation with mocked SlugKit."""
    mock_client = Mock()
    mock_client.series.mint.return_value = ["test-user-001"]
    
    with patch('myapp.slugkit_client', mock_client):
        user = create_user("Alice")
        assert user["id"] == "test-user-001"

def test_rate_limit_handling():
    """Test rate limit error handling."""
    from slugkit.base import SlugKitRateLimitError
    
    mock_client = Mock()
    mock_client.series.mint.side_effect = SlugKitRateLimitError(
        "Rate limited",
        retry_after=60
    )
    
    with patch('myapp.slugkit_client', mock_client):
        with pytest.raises(SlugKitRateLimitError):
            generate_slugs(10)
```

### Integration Tests

Test against real API:

```python
import pytest
from slugkit import SyncClient

@pytest.fixture
def client():
    """Create test client."""
    return SyncClient(
        base_url="https://dev.slugkit.dev/api/v1",
        api_key=pytest.config.getoption("--api-key")
    )

def test_mint_integration(client):
    """Test actual slug generation."""
    slugs = client.series.mint(count=5)
    assert len(slugs) == 5
    assert all(isinstance(s, str) for s in slugs)

def test_forge_integration(client):
    """Test pattern generation."""
    slugs = client.forge("{adjective}-{noun}", count=3)
    assert len(slugs) == 3
    assert all("-" in s for s in slugs)
```

## See Also

- [Python SDK Quickstart](sdk-python-quickstart) - Basic usage
- [API Reference](sdk-python-api-reference) - Complete API documentation
- [Error Handling](api-error-handling) - Error codes and recovery
- [Rate Limits](api-rate-limits) - Understanding quotas and limits


---

# Python SDK API Reference
Source: https://dev.slugkit.dev/docs/sdk-python-api-reference

# Python SDK API Reference

Complete API reference for the SlugKit Python SDK.

## Installation

```bash
pip install slugkit-py-sdk
```

## Client Classes

### SyncClient

Synchronous client for SlugKit API operations.

```python
from slugkit import SyncClient

client = SyncClient(
    base_url: str,
    api_key: str | None = None,
    *,
    httpx_client_factory: Callable = httpx.Client,
    timeout: float = 10.0
)
```

**Parameters:**
- `base_url` (str): API base URL
- `api_key` (str | None): API key (uses `SLUGKIT_API_KEY` if not provided)
- `httpx_client_factory` (Callable): HTTP client factory
- `timeout` (float): Request timeout in seconds

**Properties:**
- `series` → SeriesClient - Series operations
- `forge` → RandomGenerator - Pattern-based generation

**Methods:**
- `ping()` → None - Check API connectivity
- `key_info()` → KeyInfo - Get API key information
- `limits()` → SubscriptionFeatures - Get subscription limits

**Example:**
```python
client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="your-key"
)

# Check connectivity
client.ping()

# Get limits
limits = client.limits()
print(f"Max series: {limits.max_series}")
```

### AsyncClient

Asynchronous client with identical interface to SyncClient.

```python
from slugkit import AsyncClient

async def main():
    client = AsyncClient(
        base_url="https://dev.slugkit.dev/api/v1",
        api_key="your-key"
    )
    slugs = await client.series.mint(count=10)
```

All methods are async: `await client.ping()`, `await client.limits()`, etc.

---

## Series Operations

### SeriesClient

```python
client.series[series_slug]  # Access specific series
client.series.mint          # Generate slugs
client.series.slice         # Preview slugs (dry-run)
```

**Methods:**

#### mint
```python
client.series.mint(count: int = 1) -> list[str]
```

Generate unique slugs from series.

```python
# Generate 10 slugs
slugs = client.series.mint(count=10)

# Configure and stream
gen = client.series.mint.with_limit(100).with_batch_size(50)
for slug in gen:
    print(slug)
```

#### slice
```python
client.series.slice(count: int = 1) -> list[str]
```

Preview slugs without consuming quota.

```python
preview = client.series.slice(count=10)
```

#### stats()
```python
client.series.stats() -> list[StatsItem]
```

Get generation statistics.

```python
stats = client.series.stats()
for item in stats:
    print(f"{item.event_type}: {item.total_count}")
```

#### info()
```python
client.series.info() -> SeriesInfo
```

Get series information.

```python
info = client.series.info()
print(f"Pattern: {info.pattern}")
print(f"Capacity: {info.capacity}")
```

#### list()
```python
client.series.list() -> dict[str, str]
```

List all series (slug → name mapping).

```python
series_map = client.series.list()
```

#### create()
```python
client.series.create(name: str, pattern: str) -> SeriesInfo
```

Create a new series.

```python
info = client.series.create(
    name="User IDs",
    pattern="{adjective}-{noun}-{number:4d}"
)
```

#### update()
```python
series.update(name: str, pattern: str) -> SeriesInfo
```

Update series name or pattern.

```python
series = client.series["my-series"]
info = series.update(name="New Name", pattern="{verb}-{noun}")
```

#### delete()
```python
series.delete() -> None
```

Delete a series.

#### reset()
```python
series.reset() -> None
```

Reset series generator state.

---

## Pattern-Based Generation

### RandomGenerator

```python
client.forge  # Access forge operations
```

**Methods:**

#### forge()
```python
client.forge(
    pattern: str,
    *,
    seed: str | None = None,
    sequence: int | None = None,
    count: int = 1
) -> list[str]
```

Generate slugs from custom pattern.

```python
# Basic
slugs = client.forge(pattern="{adjective}-{noun}", count=5)

# Reproducible
slugs = client.forge(
    pattern="{color}-{animal}",
    seed="my-seed",
    sequence=0,
    count=3
)

# Number formatting
slugs = client.forge(
    pattern="{noun}-{number:4,hex}",
    count=10
)
```

#### pattern_info()
```python
client.forge.pattern_info(pattern: str) -> PatternInfo
```

Analyse pattern characteristics.

```python
info = client.forge.pattern_info("{adjective}-{noun}-{number:3d}")
print(f"Capacity: {info.capacity}")
print(f"Max length: {info.max_slug_length}")
print(f"Complexity: {info.complexity}")
```

#### dictionary_info()
```python
client.forge.dictionary_info() -> list[DictionaryInfo]
```

Get available word dictionaries.

```python
dicts = client.forge.dictionary_info()
for d in dicts:
    print(f"{d.kind}: {d.count} words")
```

#### dictionary_tags()
```python
client.forge.dictionary_tags(
    kind: str,
    *,
    limit: int = 100,
    offset: int = 0
) -> PaginatedTags
```

Get dictionary tags for filtering.

```python
tags = client.forge.dictionary_tags("adjective", limit=50)
for tag in tags.data:
    print(f"{tag.tag}: {tag.word_count} words")
```

---

## Generator Configuration

### SyncSlugGenerator

Chainable configuration for series generators.

```python
generator = client.series.mint
    .with_limit(100)
    .with_batch_size(50)
    .starting_from(1000)
```

**Methods:**

- `with_limit(limit: int)` - Set maximum slugs to generate
- `with_batch_size(size: int)` - Set streaming batch size
- `with_dry_run()` - Enable preview mode
- `starting_from(sequence: int)` - Set starting sequence
- `__call__(count: int)` - Generate list of slugs
- `stream()` - Return generator for streaming
- `__iter__()` - Make generator iterable

**Examples:**

```python
# Generate exactly 100 slugs
gen = client.series.mint.with_limit(100)
slugs = list(gen)

# Stream with batching
gen = client.series.mint.with_limit(1000).with_batch_size(50)
for slug in gen:
    process(slug)

# Preview from specific sequence
preview = client.series.slice.starting_from(1000)
slugs = preview(count=10)
```

---

## Data Models

### KeyInfo
```python
@dataclass
class KeyInfo:
    type: str                    # "api-key" or "sdk-config"
    key_scope: KeyScope          # KeyScope.ORG or KeyScope.SERIES
    slug: str                    # Key identifier
    org_slug: str                # Organisation slug
    series_slug: str | None      # Series slug (if series-scoped)
    scopes: list[str]            # Permitted operations
    enabled: bool                # Whether key is active
```

### StatsItem
```python
@dataclass
class StatsItem:
    event_type: str              # "mint", "forge", "slice", "reset"
    date_part: str               # "hour", "day", "week", "month", "year", "total"
    total_count: int             # Total operations
    request_count: int           # Number of requests
    total_duration_us: int       # Total duration (microseconds)
    avg_duration_us: float       # Average duration per operation
```

### SeriesInfo
```python
@dataclass
class SeriesInfo:
    slug: str                    # Series identifier
    org_slug: str                # Organisation slug
    name: str                    # Human-readable name
    pattern: str                 # Pattern string
    max_slug_length: int         # Maximum slug length
    capacity: str                # Total capacity (large number as string)
    generated_count: str         # Number generated
    mtime: str                   # Last modified (ISO 8601)
```

### PatternInfo
```python
@dataclass
class PatternInfo:
    pattern: str                 # Pattern string
    capacity: str                # Unique combinations possible
    max_slug_length: int         # Maximum slug length
    complexity: int              # Complexity score
    components: int              # Number of pattern components
```

### DictionaryInfo
```python
@dataclass
class DictionaryInfo:
    kind: str                    # Dictionary type (e.g., "adjective", "noun")
    count: int                   # Number of words
```

### DictionaryTag
```python
@dataclass
class DictionaryTag:
    kind: str                    # Dictionary type
    tag: str                     # Tag name
    description: str | None      # Tag description
    opt_in: bool | None          # Requires opt-in
    word_count: int              # Words with this tag
```

### PaginatedTags
```python
@dataclass
class PaginatedTags:
    data: list[DictionaryTag]    # List of tags
    pagination: Pagination       # Pagination metadata
```

### Pagination
```python
@dataclass
class Pagination:
    limit: int                   # Items per page
    offset: int                  # Current offset
    total: int                   # Total items
    has_more: bool               # More pages available
```

### SubscriptionFeatures
```python
@dataclass
class SubscriptionFeatures:
    # All fields are optional (None if unavailable)
    custom_features: bool | None
    max_series: int | None
    req_per_minute: int | None
    burst_req_per_minute: int | None
    forge_enabled: bool | None
    max_forge_per_day: int | None
    max_forge_per_month: int | None
    max_forge_per_request: int | None
    mint_enabled: bool | None
    max_mint_per_day: int | None
    max_mint_per_month: int | None
    max_mint_per_request: int | None
    slice_enabled: bool | None
    slice_window_back: int | None
    slice_window_forward: int | None
    max_nodes: int | None
    api_key_access: bool | None
    api_key_scopes: list[str] | None
    sdk_access: bool | None
    sdk_scopes: list[str] | None
```

---

## Error Handling

### Exception Hierarchy

```
SlugKitError (base)
├── SlugKitConnectionError      # Network/connectivity errors
├── SlugKitAuthenticationError  # Auth/permission errors
├── SlugKitClientError          # Client-side errors
├── SlugKitServerError          # Server-side errors
├── SlugKitRateLimitError       # Rate limiting errors
├── SlugKitValidationError      # Validation errors
├── SlugKitTimeoutError         # Timeout errors
├── SlugKitQuotaError           # Quota exceeded errors
└── SlugKitConfigurationError   # Configuration errors
```

### SlugKitError (Base)

```python
class SlugKitError(Exception):
    message: str                 # Error message
    context: ErrorContext        # Structured context
    cause: Exception | None      # Original exception
    timestamp: float             # Error timestamp
    
    def add_context(**kwargs)    # Add context info
    def get_context_info()       # Get formatted context
```

**Example:**
```python
try:
    slugs = client.series.mint(count=10)
except SlugKitError as e:
    print(f"Error: {e.message}")
    print(f"Context: {e.get_context_info()}")
```

### SlugKitRateLimitError

Rate limiting error with detailed quota information.

```python
class SlugKitRateLimitError(SlugKitError):
    retry_after: int | None          # Seconds until retry allowed
    rate_limit_reason: str | None    # Reason code
    rpm_remaining: int | None        # Remaining RPM quota
    daily_remaining: int | None      # Remaining daily quota
    monthly_remaining: int | None    # Remaining monthly quota
    lifetime_remaining: int | None   # Remaining lifetime quota
```

**Rate Limit Reasons:**
- `rate-limit-exceeded` - RPM limit reached (retryable)
- `daily-limit-exceeded` - Daily limit reached (retryable)
- `monthly-limit-exceeded` - Monthly quota exhausted (non-retryable)
- `lifetime-limit-exceeded` - Lifetime quota exhausted (non-retryable)
- `request-size-exceeded` - Request too large (non-retryable)
- `not-available` - Feature unavailable (non-retryable)
- `redis-error` - Server error (non-retryable)

**Example:**
```python
from slugkit.base import SlugKitRateLimitError
import time

try:
    slugs = client.series.mint(count=1000)
except SlugKitRateLimitError as e:
    print(f"Reason: {e.rate_limit_reason}")
    
    if e.retry_after:
        print(f"Retry in {e.retry_after}s")
    
    # Check remaining quotas
    if e.rpm_remaining is not None:
        print(f"RPM remaining: {e.rpm_remaining}")
    if e.daily_remaining is not None:
        print(f"Daily remaining: {e.daily_remaining}")
    
    # Handle retryable errors
    if e.rate_limit_reason in ["rate-limit-exceeded", "daily-limit-exceeded"]:
        if e.retry_after:
            time.sleep(e.retry_after)
            slugs = client.series.mint(count=1000)
```

### ErrorContext

Structured error context for debugging.

```python
class ErrorContext:
    operation: str               # Operation being performed
    endpoint: str | None         # API endpoint
    base_url: str | None         # API base URL
    user_id: str | None          # User identifier
    timestamp: float             # Context creation time
    additional_data: dict        # Additional context
```

### Utility Functions

```python
from slugkit.base import (
    get_error_recovery_suggestions,
    categorize_error
)

# Get recovery suggestions
suggestions = get_error_recovery_suggestions(error)
for s in suggestions:
    print(f"- {s}")

# Categorise error
category = categorize_error(error)
print(f"Severity: {category['severity']}")
print(f"Retryable: {category['retryable']}")
```

---

## Retry Behaviour

The SDK implements automatic retry with exponential backoff.

### Retryable Errors
- Connection errors
- Timeout errors
- Server errors (5xx)
- Rate limit errors with accurate `retry_after`

### Configuration
- `max_attempts`: 3
- `base_delay`: 1.0 second
- `max_delay`: 60.0 seconds
- Uses server's `retry_after` for rate limits

### Rate Limit Retry Logic

**Retryable (accurate retry-after):**
- `rate-limit-exceeded` (RPM limit)
- `daily-limit-exceeded` (daily limit)

**Non-retryable:**
- `monthly-limit-exceeded` (no accurate retry time)
- `lifetime-limit-exceeded` (permanent limit)
- `request-size-exceeded` (won't succeed on retry)
- `not-available` (feature unavailable)
- `redis-error` (server issue)

---

## Enums

```python
from slugkit.base import EventType, DatePart, KeyScope, ErrorSeverity

class EventType(Enum):
    FORGE = "forge"
    MINT = "mint"
    SLICE = "slice"
    RESET = "reset"

class DatePart(Enum):
    HOUR = "hour"
    DAY = "day"
    WEEK = "week"
    MONTH = "month"
    YEAR = "year"
    TOTAL = "total"

class KeyScope(Enum):
    ORG = "org"
    SERIES = "series"

class ErrorSeverity(Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"
```

---

## Environment Variables

```bash
export SLUGKIT_BASE_URL="https://dev.slugkit.dev/api/v1"
export SLUGKIT_API_KEY="your-api-key"
```

```python
from slugkit import SyncClient

# Uses environment variables
client = SyncClient()
```

---

## Logging

The SDK uses Python's standard `logging` module.

```python
import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("slugkit")
logger.setLevel(logging.DEBUG)

# SDK operations now log debug info
client = SyncClient(base_url="...", api_key="...")
```

**Logger names:**
- `slugkit.sync_client`
- `slugkit.async_client`
- `slugkit.base`
- `slugkit.errors`

---

## Thread Safety

### SyncClient
**Not thread-safe.** Create one client per thread.

```python
import threading

def worker():
    client = SyncClient(base_url="...", api_key="...")
    slugs = client.series.mint(count=10)

threads = [threading.Thread(target=worker) for _ in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()
```

### AsyncClient
**Async-safe.** Share client across concurrent tasks.

```python
import asyncio

async def worker(client):
    return await client.series.mint(count=10)

async def main():
    client = AsyncClient(base_url="...", api_key="...")
    tasks = [worker(client) for _ in range(5)]
    results = await asyncio.gather(*tasks)

asyncio.run(main())
```

---

## Advanced Configuration

### Custom HTTP Client

```python
import httpx
from slugkit import SyncClient

def custom_client():
    return httpx.Client(
        timeout=30.0,
        limits=httpx.Limits(max_connections=100),
        transport=httpx.HTTPTransport(retries=1)
    )

client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="key",
    httpx_client_factory=custom_client
)
```

### Custom Timeout

```python
client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="key",
    timeout=60.0  # 60 seconds
)
```

---

## Type Hints

The SDK uses comprehensive type hints.

```python
from slugkit import SyncClient
from slugkit.base import SeriesInfo, StatsItem
from typing import Generator, AsyncGenerator

client: SyncClient = SyncClient(base_url="...", api_key="...")
slugs: list[str] = client.series.mint(count=10)
info: SeriesInfo = client.series.info()
stats: list[StatsItem] = client.series.stats()

# Generator types
sync_gen: Generator[str, Any, int] = client.series.mint.stream()
async_gen: AsyncGenerator[str, None] = client.series.mint.stream()
```


---

# Python SDK Installation & Setup
Source: https://dev.slugkit.dev/docs/sdk-python-installation

# Python SDK Installation & Setup

This guide walks you through installing and configuring the SlugKit Python SDK.

## Requirements

- Python 3.9 or higher
- pip or uv package manager

## Installation

### Using pip (Recommended)

Install the SlugKit Python SDK from PyPI:

```bash
pip install slugkit-py-sdk
```

### Using uv

If you use [uv](https://github.com/astral-sh/uv) for faster package management:

```bash
uv pip install slugkit-py-sdk
```

### Verify Installation

After installation, verify that both the SDK and CLI are available:

```bash
# Check SDK import
python -c "import slugkit; print(slugkit.__version__)"

# Check CLI
slugkit --help
```

## Configuration

The SlugKit SDK requires two configuration values:

1. **Base URL** - The SlugKit API endpoint
2. **API Key** - Your authentication credentials

### Environment Variables (Recommended)

Set these environment variables for automatic configuration:

```bash
export SLUGKIT_BASE_URL="https://dev.slugkit.dev/api/v1"
export SLUGKIT_API_KEY="your-api-key-here"
```

To make these permanent, add them to your shell configuration:

**Bash/Zsh (~/.bashrc or ~/.zshrc):**

```bash
echo 'export SLUGKIT_BASE_URL="https://dev.slugkit.dev/api/v1"' >> ~/.bashrc
echo 'export SLUGKIT_API_KEY="your-api-key-here"' >> ~/.bashrc
source ~/.bashrc
```

**Fish (~/.config/fish/config.fish):**

```fish
set -Ux SLUGKIT_BASE_URL "https://dev.slugkit.dev/api/v1"
set -Ux SLUGKIT_API_KEY "your-api-key-here"
```

### Programmatic Configuration

You can also configure the SDK programmatically when creating a client:

```python
from slugkit import SyncClient

client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="your-api-key-here"
)
```

### Configuration File (Optional)

For projects with multiple developers, consider using a `.env` file:

**.env:**

```env
SLUGKIT_BASE_URL=https://dev.slugkit.dev/api/v1
SLUGKIT_API_KEY=your-api-key-here
```

Load it using [python-dotenv](https://pypi.org/project/python-dotenv/):

```bash
pip install python-dotenv
```

```python
from dotenv import load_dotenv
from slugkit import SyncClient

load_dotenv()  # Loads .env file
client = SyncClient()  # Uses environment variables
```

**Important:** Add `.env` to your `.gitignore` to avoid committing secrets:

```bash
echo ".env" >> .gitignore
```

## Getting Your API Key

To obtain an API key:

1. Sign up at [SlugKit.dev](/)
2. Create an organization
3. Navigate to Settings → API Keys
4. Generate a new API key

API keys come in two types:

- **Internal Keys (`ik-...`)** - Full access, for server-side use only
- **SDK Keys (`sk-...`)** - Limited scope, can be used in client-side code

**Security Best Practice:** Never commit API keys to version control. Use environment variables or secure secret management.

## Verify Configuration

Test your configuration with a simple ping:

```bash
# Using CLI
slugkit limits

# Using Python
python -c "from slugkit import SyncClient; client = SyncClient(); print(client.limits())"
```

If successful, you should see your subscription limits displayed.

## Client Types

The SDK provides two client types:

### Synchronous Client

For traditional synchronous Python code:

```python
from slugkit import SyncClient

client = SyncClient()
ids = client.series.mint(count=5)
print(ids)
```

### Asynchronous Client

For async/await code (ideal for web frameworks like FastAPI):

```python
import asyncio
from slugkit import AsyncClient

async def main():
    client = AsyncClient()
    ids = await client.series.mint(count=5)
    print(ids)

asyncio.run(main())
```

## Advanced Configuration

### Custom Timeout

Configure request timeout (default: 10 seconds):

```python
from slugkit import SyncClient

client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="your-api-key",
    timeout=30.0  # 30 second timeout
)
```

### Custom HTTP Client

For advanced use cases, provide a custom httpx client factory:

```python
import httpx
from slugkit import SyncClient

def custom_client_factory():
    return httpx.Client(
        timeout=30.0,
        limits=httpx.Limits(max_connections=100),
        transport=httpx.HTTPTransport(retries=3)
    )

client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="your-api-key",
    httpx_client_factory=custom_client_factory
)
```

### Logging

Enable debug logging to troubleshoot issues:

```python
import logging

# Configure logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# The SDK will now output detailed logs
from slugkit import SyncClient
client = SyncClient()
ids = client.series.mint(count=5)
```

## Installation for Development

If you're contributing to the SDK or need the latest development version:

```bash
# Clone the repository
git clone https://github.com/slugkit/slugkit-py-sdk.git
cd slugkit-py-sdk

# Install in development mode with test dependencies
pip install -e ".[test]"

# Run tests
pytest
```

## Troubleshooting

### ImportError: No module named 'slugkit'

The package is not installed or not in your Python path:

```bash
# Verify installation
pip list | grep slugkit

# Reinstall if needed
pip install --force-reinstall slugkit-py-sdk
```

### Command 'slugkit' not found

The CLI script is not in your PATH:

```bash
# Check installation location
python -m pip show slugkit-py-sdk

# On Linux/macOS, ensure ~/.local/bin is in PATH
export PATH="$HOME/.local/bin:$PATH"

# On Windows, ensure Scripts directory is in PATH
# Usually: C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXX\Scripts
```

### Connection Errors

If you get connection errors:

```bash
# Test the API endpoint directly
curl -I https://dev.slugkit.dev/api/v1/ping

# Check your base URL
echo $SLUGKIT_BASE_URL
```

### Authentication Errors

If you get 401 Unauthorized errors:

```bash
# Verify API key is set
echo $SLUGKIT_API_KEY

# Verify API key format (should start with 'ik-' or 'sk-')
# Check key hasn't expired in the SlugKit dashboard
```

## Docker Usage

Run the SDK in a Docker container:

**Dockerfile:**

```dockerfile
FROM python:3.11-slim

WORKDIR /app

# Install SDK
RUN pip install slugkit-py-sdk

# Set environment variables
ENV SLUGKIT_BASE_URL="https://dev.slugkit.dev/api/v1"
ENV SLUGKIT_API_KEY="your-api-key-here"

# Copy your application
COPY . .

CMD ["python", "main.py"]
```

**docker-compose.yml:**

```yaml
version: '3.8'

services:
  app:
    build: .
    environment:
      SLUGKIT_BASE_URL: "https://dev.slugkit.dev/api/v1"
      SLUGKIT_API_KEY: "${SLUGKIT_API_KEY}"
    volumes:
      - ./app:/app
```

Run with:

```bash
export SLUGKIT_API_KEY="your-api-key"
docker-compose up
```

## Next Steps

Now that you have the SDK installed and configured:

- **[Python SDK Quickstart](sdk-python-quickstart)** - Generate your first slugs
- **[CLI Reference](rest-api-curl-examples)** - Learn command-line usage
- **[Pattern Syntax Basics](pattern-syntax-basics)** - Master pattern creation
- **[Core Concepts](developer-core-concepts)** - Understand forge vs mint vs slice

## See Also

- [Python SDK API Reference](sdk-python-api-reference) - Complete API documentation
- [Advanced Usage Guide](sdk-python-advanced) - Async, error handling, streaming
- [Rate Limits & Quotas](api-rate-limits) - Understanding subscription limits
- [Troubleshooting](troubleshooting-common-errors) - Common issues and solutions


---

# Python SDK Quickstart
Source: https://dev.slugkit.dev/docs/sdk-python-quickstart

# Python SDK Quickstart

Get started with the SlugKit Python SDK in 5 minutes. This guide will walk you through generating your first unique slugs.

## Prerequisites

- Python 3.9 or higher
- SlugKit API key ([get one here](/))

## Installation

Install the SDK using pip:

```bash
pip install slugkit-py-sdk
```

## Configuration

Set your API credentials as environment variables:

```bash
export SLUGKIT_BASE_URL="https://dev.slugkit.dev/api/v1"
export SLUGKIT_API_KEY="your-api-key-here"
```

## Your First Slugs

### Using the CLI

The quickest way to generate slugs:

```bash
# Generate a single slug
slugkit mint

# Output: happy-dolphin-0001
```

### Using Python - Synchronous

Create a simple Python script:

```python
from slugkit import SyncClient

# Create client (uses environment variables)
client = SyncClient()

# Generate a single slug
slug = client.series.mint(count=1)[0]
print(f"Generated slug: {slug}")
# Output: Generated slug: happy-dolphin-0001

# Generate multiple slugs
slugs = client.series.mint(count=5)
for slug in slugs:
    print(slug)
# Output:
# happy-dolphin-0002
# bright-falcon-0003
# clever-panda-0004
# gentle-tiger-0005
# swift-eagle-0006
```

### Using Python - Asynchronous

For async/await applications:

```python
import asyncio
from slugkit import AsyncClient

async def main():
    # Create async client
    client = AsyncClient()
    
    # Generate slugs
    slugs = await client.series.mint(count=5)
    for slug in slugs:
        print(slug)

# Run the async function
asyncio.run(main())
```

## Key Concepts

### Generation Methods

SlugKit offers three generation methods:

#### 1. Mint - Unique, Sequential IDs

Generate unique slugs from a series with guaranteed uniqueness:

```python
# Generate from default series
slugs = client.series.mint(count=10)

# Generate from specific series
slugs = client.series["my-series-slug"].mint(count=10)
```

**When to use:** Production IDs that must be unique across your entire system.

#### 2. Forge - Test Custom Patterns

Test patterns without creating a series:

```python
# Test a pattern
slugs = client.forge(
    pattern="{adjective}-{noun}-{number:3d}",
    count=5
)
```

**When to use:** Experimenting with patterns, one-off generation, prototyping.

#### 3. Slice - Preview Without Consuming

Preview what would be generated without consuming sequence numbers:

```python
# Preview next 10 slugs
preview = client.series.slice(count=10)
```

**When to use:** Testing, debugging, previewing patterns.

## Common Use Cases

### Generate User Handles

```python
from slugkit import SyncClient

client = SyncClient()

# Create a user handle pattern
user_handle = client.forge(
    pattern="{adjective}-{animal}",
    count=1
)[0]

print(f"Welcome, {user_handle}!")
# Output: Welcome, happy-dolphin!
```

### Generate API Endpoint IDs

```python
# Generate unique endpoint identifiers
endpoint_ids = client.series.mint(count=5)

# Use in your API
endpoints = {
    f"/api/{slug}": handler
    for slug, handler in zip(endpoint_ids, handlers)
}
```

### Generate Test Data

```python
# Generate test user IDs
test_users = client.forge(
    pattern="test-user-{number:4d}",
    sequence=1,
    count=100
)
```

### Generate Content Slugs

```python
# Generate URL slugs for blog posts
def create_blog_post(title, content):
    slug = client.series["blog-posts"].mint(count=1)[0]
    return {
        "id": slug,
        "title": title,
        "url": f"/blog/{slug}",
        "content": content
    }
```

## Pattern Basics

Patterns define the structure of your slugs using tokens:

### Word Tokens

```python
# Adjectives
client.forge("{adjective}")  # → "happy"

# Nouns
client.forge("{noun}")  # → "dolphin"

# Verbs
client.forge("{verb}")  # → "running"

# Adverbs
client.forge("{adverb}")  # → "quickly"

# Colors
client.forge("{color}")  # → "blue"

# Animals
client.forge("{animal}")  # → "dolphin"
```

### Number Tokens

```python
# Decimal numbers
client.forge("{number:3d}")  # → "001"
client.forge("{number:5d}")  # → "00001"

# Hexadecimal
client.forge("{number:4,hex}")  # → "a3f9"

# Roman numerals (lowercase)
client.forge("{number:3r}")  # → "xiv"

# Roman numerals (uppercase)
client.forge("{number:3R}")  # → "XIV"
```

### Combining Tokens

```python
# Simple combination
client.forge("{adjective}-{noun}")
# → "happy-dolphin"

# With numbers
client.forge("{adjective}-{noun}-{number:3d}")
# → "happy-dolphin-001"

# Complex patterns
client.forge("{color}-{animal}-{verb}-{number:4,hex}")
# → "blue-dolphin-running-a3f9"
```

## Working with Series

Series provide guaranteed unique, sequential ID generation.

### List Available Series

```python
# Get all series
series_list = client.series.list()
print(series_list)
# Output: {'my-series': 'My Series Name', 'another-series': 'Another Series'}
```

### Get Series Information

```python
# Get detailed series info
info = client.series["my-series"].info()
print(f"Pattern: {info.pattern}")
print(f"Capacity: {info.capacity}")
print(f"Generated: {info.generated_count}")
```

### Generate from Specific Series

```python
# Access series by slug
series = client.series["user-handles"]
slugs = series.mint(count=10)

# Or use dict-style access
slugs = client.series["user-handles"].mint(count=10)
```

## Error Handling

Handle common errors gracefully:

```python
from slugkit import SyncClient
from slugkit.base import (
    SlugKitRateLimitError,
    SlugKitAuthenticationError,
    SlugKitValidationError,
)

client = SyncClient()

try:
    slugs = client.series.mint(count=10)
except SlugKitRateLimitError as e:
    print(f"Rate limited: {e.rate_limit_reason}")
    print(f"Retry after: {e.retry_after} seconds")
except SlugKitAuthenticationError:
    print("Invalid API key - check your credentials")
except SlugKitValidationError as e:
    print(f"Invalid request: {e}")
```

## Streaming Large Batches

For generating large numbers of slugs efficiently:

```python
# Stream slugs in batches
generator = client.series.mint.with_limit(10000).with_batch_size(1000)

for slug in generator:
    print(slug)
    # Process each slug as it's generated
```

## Check Your Limits

Monitor your subscription limits:

```python
# Get subscription limits
limits = client.limits()

print(f"Max mint per day: {limits.max_mint_per_day}")
print(f"Requests per minute: {limits.req_per_minute}")
print(f"Max series: {limits.max_series}")
```

## Configuration Options

### Custom Timeout

```python
# Set custom timeout (default: 10 seconds)
client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="your-api-key",
    timeout=30.0
)
```

### Explicit Configuration

```python
# Configure without environment variables
from slugkit import SyncClient

client = SyncClient(
    base_url="https://dev.slugkit.dev/api/v1",
    api_key="your-api-key-here"
)
```

## CLI Quick Reference

Quickly generate slugs from the command line:

```bash
# Generate slugs
slugkit mint 5

# Test patterns
slugkit forge "{adjective}-{noun}-{number:3d}" --count 5

# Preview slugs
slugkit slice 10

# Check limits
slugkit limits

# Get statistics
slugkit stats

# Validate patterns
slugkit validate "{adjective}-{noun}-{number:3d}"
```

## Best Practices

### 1. Use Environment Variables

Keep credentials secure:

```python
# ✅ Good - uses environment variables
client = SyncClient()

# ❌ Bad - credentials in code
client = SyncClient(api_key="ik-12345...")
```

### 2. Choose the Right Method

- **Mint** - Production IDs that must be unique
- **Forge** - Testing, prototyping, one-off generation
- **Slice** - Preview without consuming

### 3. Handle Rate Limits

Rate limit errors include retry-after information:

```python
from slugkit.base import SlugKitRateLimitError
import time

try:
    slugs = client.series.mint(count=1000)
except SlugKitRateLimitError as e:
    if e.retry_after:
        time.sleep(e.retry_after)
        slugs = client.series.mint(count=1000)
```

### 4. Validate Patterns First

Test patterns before creating series:

```bash
# Validate pattern
slugkit validate "{adjective}-{noun}-{number:3d}"

# Test generation
slugkit forge "{adjective}-{noun}-{number:3d}" --count 10
```

## Common Patterns

### User Handles

```python
client.forge("{adjective}-{animal}")
# → happy-dolphin
```

### API Endpoints

```python
client.forge("{verb}-{noun}-{number:4,hex}")
# → create-user-a3f9
```

### Resource IDs

```python
client.forge("{noun}-{adjective}-{noun}-{number:3d}")
# → server-fast-dolphin-001
```

### Short Codes

```python
client.forge("{number:6,hex}")
# → a3f921
```

## Next Steps

Now that you know the basics:

- **[Advanced Usage Guide](sdk-python-advanced)** - Async clients, error handling, streaming
- **[Pattern Syntax Reference](pattern-syntax-basics)** - Master the pattern language
- **[CLI Reference](rest-api-curl-examples)** - Complete CLI documentation
- **[API Reference](sdk-python-api-reference)** - Full Python API documentation

## Troubleshooting

### Import Error

```bash
pip install --upgrade slugkit-py-sdk
```

### Authentication Failed

Check your API key:

```bash
echo $SLUGKIT_API_KEY
# Verify it starts with 'ik-' or 'sk-'
```

### Connection Error

Verify the base URL:

```bash
curl -I https://dev.slugkit.dev/api/v1/ping
```

### Rate Limited

Check your limits and current usage:

```bash
slugkit limits
slugkit stats
```

## Complete Example

Putting it all together:

```python
from slugkit import SyncClient
from slugkit.base import SlugKitRateLimitError
import time

def generate_user_ids(count: int) -> list[str]:
    """Generate unique user IDs with error handling."""
    client = SyncClient()
    
    try:
        # Generate IDs from user-handles series
        ids = client.series["user-handles"].mint(count=count)
        return ids
    
    except SlugKitRateLimitError as e:
        print(f"Rate limited: {e.rate_limit_reason}")
        if e.retry_after:
            print(f"Retrying after {e.retry_after} seconds...")
            time.sleep(e.retry_after)
            return generate_user_ids(count)
        raise
    
    except Exception as e:
        print(f"Error generating IDs: {e}")
        raise

if __name__ == "__main__":
    # Generate 10 user IDs
    user_ids = generate_user_ids(10)
    
    print(f"Generated {len(user_ids)} user IDs:")
    for user_id in user_ids:
        print(f"  - {user_id}")
```

## See Also

- [Installation Guide](sdk-python-installation) - Detailed setup instructions
- [Core Concepts](developer-core-concepts) - Understanding SlugKit fundamentals
- [Pattern Cookbook](pattern-cookbook) - Real-world pattern examples
- [Error Handling](api-error-handling) - Complete error reference


---

# TypeScript SDK: Browser Usage
Source: https://dev.slugkit.dev/docs/sdk-typescript-browser

# TypeScript SDK: Browser Usage

Use SlugKit's TypeScript SDK securely in browser-based applications. This guide covers SDK key authentication, CORS configuration, security best practices, and common patterns for frontend frameworks.

## Overview

The TypeScript SDK works seamlessly in modern browsers with native Web Crypto API support. SDK keys enable secure authentication without exposing credentials in client-side code.

**Perfect for:**
- Single-page applications (React, Vue, Angular, Svelte)
- Progressive web applications (PWAs)
- Static site generators with dynamic features
- Browser extensions and WebAssembly applications

**Key features for browsers:**
- ✅ **Signature-based authentication** - no exposed secrets
- ✅ **Automatic key rotation** - handles expiration transparently
- ✅ **CORS-ready** - works with SlugKit's CORS configuration
- ✅ **Rate limit tracking** - respects quota limits
- ✅ **Zero dependencies** - uses native browser APIs

## Prerequisites

Before integrating the SDK in your browser application:

1. **Install the SDK** - See [Installation & Setup](sdk-typescript-installation)
2. **Create an SDK configuration** - Dashboard → Organization → SDK Configuration
3. **Note your SDK slug** - You'll need this for initialization
4. **Ensure modern browser support** - ES2020, Web Crypto API, Fetch API

**⚠️ CRITICAL:** Never use API keys in browser applications. They're designed for server-side use and will expose your credentials if embedded in client code.

## SDK Keys vs API Keys

| Feature | SDK Keys (Browser) | API Keys (Server) |
|---------|-------------------|-------------------|
| **Security** | ✅ Signature-based, no exposed secrets | ❌ Secret token, must stay server-side |
| **Client-side use** | ✅ Designed for browsers | ❌ Never expose in browsers |
| **Authentication** | Cryptographic signatures | X-API-Key header |
| **Key rotation** | ✅ Automatic | Manual revocation and replacement |
| **CORS** | ✅ Fully supported | Not applicable |
| **Availability** | Paid tiers | Free tier and above |

## Basic Browser Setup

### Vanilla JavaScript/TypeScript

```typescript
import { SlugKit } from '@slugkit/sdk';

// Initialize with SDK slug (fetches keys automatically)
const slugkit = await SlugKit.fromBackend(
  'https://api.slugkit.com',
  'web-app-prod'  // Your SDK configuration slug
);

// Generate slugs
const slugs = await slugkit.forgeSlugs('{adjective}-{noun}', 5);
console.log(slugs);
// ['brilliant-keyboard', 'clever-telescope', 'swift-compass', ...]
```

### With Build-Time Embedded Keys

For environments where automatic key fetching isn't suitable (e.g., strict CSP policies):

```typescript
import { SlugKit } from '@slugkit/sdk';

// Embed JWK at build time (from environment variable)
const jwk: JsonWebKey = JSON.parse(process.env.VITE_SLUGKIT_JWK!);

const slugkit = await SlugKit.fromJwk(
  'https://api.slugkit.com',
  'web-app-prod',
  jwk
);
```

**Note:** Even with embedded keys, private keys remain in your built application code - they're never transmitted to the client after the initial download. This is safe because:
1. Keys are rotated automatically
2. Each request is signed uniquely with timestamps
3. Replay attacks are prevented server-side

## Framework Integration

### React

Create a context provider for application-wide access:

```typescript
// contexts/SlugKitContext.tsx
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { SlugKit } from '@slugkit/sdk';

interface SlugKitContextType {
  slugkit: SlugKit | null;
  loading: boolean;
  error: Error | null;
}

const SlugKitContext = createContext<SlugKitContextType>({
  slugkit: null,
  loading: true,
  error: null
});

export function SlugKitProvider({ children }: { children: ReactNode }) {
  const [slugkit, setSlugkit] = useState<SlugKit | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    async function initSlugKit() {
      try {
        const client = await SlugKit.fromBackend(
          'https://api.slugkit.com',
          'web-app-prod'
        );
        setSlugkit(client);
      } catch (err) {
        setError(err as Error);
      } finally {
        setLoading(false);
      }
    }

    initSlugKit();
  }, []);

  return (
    <SlugKitContext.Provider value={{ slugkit, loading, error }}>
      {children}
    </SlugKitContext.Provider>
  );
}

export function useSlugKit() {
  const context = useContext(SlugKitContext);
  if (!context.slugkit && !context.loading) {
    throw new Error('SlugKit not initialized');
  }
  return context;
}
```

**Usage in components:**

```typescript
import { useSlugKit } from './contexts/SlugKitContext';

function UserHandleGenerator() {
  const { slugkit, loading } = useSlugKit();
  const [handles, setHandles] = useState<string[]>([]);

  async function generateHandles() {
    if (!slugkit) return;
    
    const result = await slugkit.forgeSlugs('{adjective}-{noun}', 10);
    setHandles(result);
  }

  if (loading) return <div>Initializing SlugKit...</div>;

  return (
    <div>
      <button onClick={generateHandles}>Generate Handles</button>
      <ul>
        {handles.map((handle, i) => <li key={i}>{handle}</li>)}
      </ul>
    </div>
  );
}
```

See [React Integration](sdk-typescript-react) for more advanced patterns.

### Vue 3

Create a composable for Vue applications:

```typescript
// composables/useSlugKit.ts
import { ref, onMounted } from 'vue';
import { SlugKit } from '@slugkit/sdk';

const slugkit = ref<SlugKit | null>(null);
const loading = ref(true);
const error = ref<Error | null>(null);

export function useSlugKit() {
  onMounted(async () => {
    if (slugkit.value) return; // Already initialized

    try {
      slugkit.value = await SlugKit.fromBackend(
        'https://api.slugkit.com',
        'web-app-prod'
      );
    } catch (err) {
      error.value = err as Error;
    } finally {
      loading.value = false;
    }
  });

  return { slugkit, loading, error };
}
```

**Usage in components:**

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { useSlugKit } from '@/composables/useSlugKit';

const { slugkit, loading } = useSlugKit();
const handles = ref<string[]>([]);

async function generateHandles() {
  if (!slugkit.value) return;
  handles.value = await slugkit.value.forgeSlugs('{adjective}-{noun}', 10);
}
</script>

<template>
  <div>
    <button @click="generateHandles" :disabled="loading">
      Generate Handles
    </button>
    <ul>
      <li v-for="(handle, i) in handles" :key="i">{{ handle }}</li>
    </ul>
  </div>
</template>
```

### Angular

Create an injectable service:

```typescript
// services/slugkit.service.ts
import { Injectable } from '@angular/core';
import { SlugKit } from '@slugkit/sdk';

@Injectable({
  providedIn: 'root'
})
export class SlugKitService {
  private slugkit: SlugKit | null = null;
  private initPromise: Promise<void> | null = null;

  constructor() {
    this.initPromise = this.initialize();
  }

  private async initialize() {
    this.slugkit = await SlugKit.fromBackend(
      'https://api.slugkit.com',
      'web-app-prod'
    );
  }

  async forgeSlugs(pattern: string, count: number): Promise<string[]> {
    await this.initPromise;
    if (!this.slugkit) throw new Error('SlugKit not initialized');
    return this.slugkit.forgeSlugs(pattern, count);
  }

  async mintSlugs(seriesSlug: string, count: number): Promise<string[]> {
    await this.initPromise;
    if (!this.slugkit) throw new Error('SlugKit not initialized');
    return this.slugkit.mintSlugs(seriesSlug, count);
  }
}
```

**Usage in components:**

```typescript
import { Component } from '@angular/core';
import { SlugKitService } from './services/slugkit.service';

@Component({
  selector: 'app-handle-generator',
  template: `
    <button (click)="generateHandles()">Generate Handles</button>
    <ul>
      <li *ngFor="let handle of handles">{{ handle }}</li>
    </ul>
  `
})
export class HandleGeneratorComponent {
  handles: string[] = [];

  constructor(private slugkitService: SlugKitService) {}

  async generateHandles() {
    this.handles = await this.slugkitService.forgeSlugs(
      '{adjective}-{noun}',
      10
    );
  }
}
```

## Common Use Cases

### Real-Time Slug Preview

Generate preview slugs as users type patterns:

```typescript
import { SlugKit, PatternParser } from '@slugkit/sdk';

async function previewPattern(pattern: string): Promise<string[]> {
  // Validate pattern first
  const isValid = PatternParser.validate(pattern);
  if (!isValid) {
    return ['Invalid pattern syntax'];
  }

  try {
    // Generate preview slugs
    const slugs = await slugkit.forgeSlugs(pattern, 5);
    return slugs;
  } catch (error) {
    console.error('Preview failed:', error);
    return ['Error generating preview'];
  }
}

// Debounced input handler
let debounceTimer: NodeJS.Timeout;
inputElement.addEventListener('input', (e) => {
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(async () => {
    const pattern = (e.target as HTMLInputElement).value;
    const preview = await previewPattern(pattern);
    updatePreviewUI(preview);
  }, 500);
});
```

### User Handle Generation

Generate available handles for user registration:

```typescript
async function generateAvailableHandles(count: number): Promise<string[]> {
  try {
    // Mint unique handles from series
    const handles = await slugkit.mintSlugs('user-handles', count);
    
    // Check availability against your database
    const available = await checkHandleAvailability(handles);
    
    return available;
  } catch (error) {
    if (error.retryAfter) {
      console.log(`Rate limited. Retry after ${error.retryAfter}s`);
    }
    throw error;
  }
}
```

### URL Slug Generation for Content

Generate SEO-friendly URL slugs:

```typescript
async function generateContentSlug(title: string): Promise<string> {
  // Create pattern based on title keywords
  const keywords = extractKeywords(title);
  const pattern = `{adjective}-${keywords[0]}-{number:2x}`;
  
  // Generate slug
  const slugs = await slugkit.forgeSlugs(pattern, 1);
  return slugs[0];
}
```

### Batch Generation with Progress

Generate large batches with progress tracking:

```typescript
async function generateWithProgress(
  totalCount: number,
  onProgress: (current: number, total: number) => void
): Promise<string[]> {
  const batchSize = 100;
  const results: string[] = [];
  
  for (let i = 0; i < totalCount; i += batchSize) {
    const count = Math.min(batchSize, totalCount - i);
    const batch = await slugkit.forgeSlugs('{adjective}-{noun}', count);
    results.push(...batch);
    onProgress(i + count, totalCount);
  }
  
  return results;
}

// Usage
await generateWithProgress(1000, (current, total) => {
  console.log(`Progress: ${current}/${total}`);
  updateProgressBar(current / total);
});
```

## Security Best Practices

### Content Security Policy (CSP)

If you use CSP headers, ensure they allow:

```
Content-Security-Policy: 
  connect-src 'self' https://api.slugkit.com;
  script-src 'self';
```

For automatic key fetching, allow connections to SlugKit's API.

### Avoid Exposing Keys in DevTools

While SDK keys are designed for client-side use, avoid logging them:

```typescript
// ❌ Bad: Logs sensitive data
console.log('SlugKit instance:', slugkit);

// ✅ Good: Log only necessary information
console.log('SlugKit initialized successfully');
```

### Rate Limit Awareness

Implement client-side rate limiting to avoid hitting quotas:

```typescript
class RateLimitedSlugKit {
  private requestCount = 0;
  private resetTime = Date.now() + 60000;

  async forgeSlugs(pattern: string, count: number): Promise<string[]> {
    // Reset counter every minute
    if (Date.now() > this.resetTime) {
      this.requestCount = 0;
      this.resetTime = Date.now() + 60000;
    }

    // Check local limit (e.g., 50 requests per minute)
    if (this.requestCount >= 50) {
      throw new Error('Local rate limit exceeded');
    }

    this.requestCount++;
    return await slugkit.forgeSlugs(pattern, count);
  }
}
```

### Secure Storage

Never store SDK configuration slugs or keys in:
- ❌ localStorage or sessionStorage (accessible via XSS)
- ❌ Cookies without HttpOnly flag
- ❌ URL query parameters
- ❌ HTML data attributes

Instead:
- ✅ Use environment variables at build time
- ✅ Fetch keys at runtime in memory only
- ✅ Leverage the SDK's automatic key rotation

## Error Handling

### Network Errors

Handle connectivity issues gracefully:

```typescript
async function generateWithRetry(
  pattern: string,
  count: number,
  maxRetries = 3
): Promise<string[]> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await slugkit.forgeSlugs(pattern, count);
    } catch (error) {
      if (error.message.includes('Network error')) {
        if (attempt < maxRetries - 1) {
          // Exponential backoff
          await new Promise(resolve => 
            setTimeout(resolve, Math.pow(2, attempt) * 1000)
          );
          continue;
        }
      }
      throw error;
    }
  }
  throw new Error('Max retries exceeded');
}
```

### CORS Errors

If you encounter CORS errors:

1. **Verify API endpoint** - Ensure you're using the correct base URL
2. **Check SDK key configuration** - Confirm your SDK slug is correct
3. **Test with cURL** - Rule out network issues:

```bash
curl -X POST https://api.slugkit.com/api/v1/gen/forge \
  -H "Content-Type: application/json" \
  -H "X-SDK-Slug: web-app-prod" \
  -H "X-Timestamp: 2025-01-15T10:30:00Z" \
  -H "X-Signature: <signature>" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

4. **Contact support** - If CORS issues persist, reach out with your SDK slug

### Rate Limiting

Handle quota limits transparently:

```typescript
async function generateWithRateLimit(
  pattern: string,
  count: number
): Promise<string[]> {
  try {
    return await slugkit.forgeSlugs(pattern, count);
  } catch (error) {
    if (error.retryAfter) {
      // Show user-friendly message
      showNotification(
        `Rate limit reached. Please wait ${error.retryAfter} seconds.`
      );
      
      // Automatically retry after delay
      await new Promise(resolve => 
        setTimeout(resolve, error.retryAfter * 1000)
      );
      
      return await slugkit.forgeSlugs(pattern, count);
    }
    throw error;
  }
}
```

## Performance Optimization

### Lazy Initialization

Defer SDK initialization until needed:

```typescript
let slugkitPromise: Promise<SlugKit> | null = null;

function getSlugKit(): Promise<SlugKit> {
  if (!slugkitPromise) {
    slugkitPromise = SlugKit.fromBackend(
      'https://api.slugkit.com',
      'web-app-prod'
    );
  }
  return slugkitPromise;
}

// Usage: SDK only initializes on first use
const slugkit = await getSlugKit();
```

### Caching Generated Slugs

Cache results client-side to reduce API calls:

```typescript
const slugCache = new Map<string, string[]>();

async function getCachedSlugs(
  pattern: string,
  count: number
): Promise<string[]> {
  const cacheKey = `${pattern}:${count}`;
  
  if (slugCache.has(cacheKey)) {
    return slugCache.get(cacheKey)!;
  }
  
  const slugs = await slugkit.forgeSlugs(pattern, count);
  slugCache.set(cacheKey, slugs);
  
  // Cache for 5 minutes
  setTimeout(() => slugCache.delete(cacheKey), 5 * 60 * 1000);
  
  return slugs;
}
```

### Debouncing Pattern Validation

Avoid excessive validation calls:

```typescript
import { debounce } from 'lodash-es'; // or your own implementation

const validatePattern = debounce(async (pattern: string) => {
  const isValid = PatternParser.validate(pattern);
  updateValidationUI(isValid);
}, 300);

// Usage: Only validates after user stops typing for 300ms
inputElement.addEventListener('input', (e) => {
  validatePattern((e.target as HTMLInputElement).value);
});
```

## Testing

### Mock SlugKit for Unit Tests

```typescript
// __mocks__/@slugkit/sdk.ts
export class SlugKit {
  static async fromBackend() {
    return new SlugKit();
  }

  async forgeSlugs(pattern: string, count: number): Promise<string[]> {
    return Array.from({ length: count }, (_, i) => `mock-slug-${i}`);
  }

  async mintSlugs(series: string, count: number): Promise<string[]> {
    return Array.from({ length: count }, (_, i) => `${series}-${i}`);
  }
}
```

**Usage in Jest:**

```typescript
jest.mock('@slugkit/sdk');

test('generates handles', async () => {
  const slugkit = await SlugKit.fromBackend('', '');
  const handles = await slugkit.forgeSlugs('{noun}', 5);
  expect(handles).toHaveLength(5);
});
```

### Integration Testing

For E2E tests with real API calls:

```typescript
// Use test SDK configuration
const testSlugkit = await SlugKit.fromBackend(
  'https://api.slugkit.com',
  'test-sdk-slug'  // Separate SDK config for testing
);
```

## Browser Compatibility

The SDK requires:
- **ES2020** support (Chrome 80+, Firefox 74+, Safari 13.1+, Edge 80+)
- **Web Crypto API** (all modern browsers)
- **Fetch API** (all modern browsers)
- **Promise support** (all modern browsers)

For older browsers, consider polyfills:
- `core-js` for ES2020 features
- `whatwg-fetch` for Fetch API
- `webcrypto-shim` for Web Crypto API

## Troubleshooting

### "SlugKit not initialized" Error

Ensure you await initialization:

```typescript
// ❌ Wrong: Not awaiting
const slugkit = SlugKit.fromBackend('https://api.slugkit.com', 'slug');
await slugkit.forgeSlugs('{noun}', 5); // Error!

// ✅ Correct: Await initialization
const slugkit = await SlugKit.fromBackend('https://api.slugkit.com', 'slug');
await slugkit.forgeSlugs('{noun}', 5);
```

### CORS Errors in Development

If developing locally, ensure your dev server forwards requests correctly or use the production API URL directly.

### Signature Verification Failed

If you see authentication errors:
1. Check your SDK slug is correct
2. Verify your SDK configuration is active in the dashboard
3. Ensure system clock is synchronized (signatures use timestamps)

## Next Steps

**Framework-Specific Guides:**
- [React Integration](sdk-typescript-react) - Hooks, context, and advanced patterns
- [Node.js Usage](sdk-typescript-nodejs) - Server-side integration

**Core Concepts:**
- [Authentication Guide](api-authentication) - Deep dive into SDK keys and security
- [Pattern Syntax Basics](pattern-syntax-basics) - Master pattern creation
- [Rate Limits & Quotas](api-rate-limits) - Understanding tier limits

**Guides:**
- [Web Development Guide](guide-web-development) - Best practices for web applications
- [User Handles Guide](guide-user-handles) - Social and gaming identifiers


---

# TypeScript SDK: Installation & Setup
Source: https://dev.slugkit.dev/docs/sdk-typescript-installation

# TypeScript SDK: Installation & Setup

Get started with SlugKit's TypeScript SDK in minutes. This SDK provides a type-safe, modern interface for generating human-readable identifiers in both browser and Node.js environments.

## Overview

The `@slugkit/sdk` package is SlugKit's official TypeScript SDK, providing:

- **Full TypeScript support** with comprehensive type definitions
- **Pattern parsing and validation** for SlugKit's EBNF grammar
- **Automatic authentication** with API keys or SDK signature-based auth
- **Dictionary management** with automatic caching
- **Rate limit tracking** with detailed error handling
- **Universal compatibility** for browsers and Node.js

**Perfect for:**
- React, Vue, Angular, and other frontend frameworks
- Node.js backend services and APIs
- Electron and desktop applications
- Mobile apps with React Native or similar frameworks
- CLI tools and scripts

## Requirements

- **Node.js 16+** or a modern browser with ES2020 support
- **npm**, **yarn**, or **pnpm** package manager
- **TypeScript 4.5+** (optional but recommended)

The SDK uses native Web Crypto APIs available in all modern environments - no polyfills required.

## Installation

### npm

```bash
npm install @slugkit/sdk
```

### yarn

```bash
yarn add @slugkit/sdk
```

### pnpm

```bash
pnpm add @slugkit/sdk
```

## Authentication Setup

The SDK supports two authentication methods optimised for different environments. Choose the method that fits your use case.

### API Keys (Server-Side)

API keys are traditional secret tokens used for server-side applications. They're simple to set up but **must never be exposed in client-side code**.

**Use API keys for:**
- Node.js backend services and APIs
- Server-side scripts and automation
- CLI tools and development workflows
- Any environment where secrets can be securely stored

**Getting an API key:**

1. Log in to your SlugKit dashboard at https://slugkit.com/dashboard
2. Navigate to **Dashboard → Organization** (for org-scoped keys) or **Dashboard → Organization → [Series]** (for series-scoped keys)
3. Click **"Create API Key"** or **"New API Key"**
4. Configure permissions (forge, mint, slice, reset as needed)
5. Copy your key immediately - it's only shown once
6. Store securely in environment variables

**Setup with API key:**

```typescript
import { SlugKit } from '@slugkit/sdk';

// Create a SlugKit instance with your API key
const slugkit = SlugKit.fromApiKey(
  'https://api.slugkit.com',  // Backend URL
  process.env.SLUGKIT_API_KEY!  // Your API key from environment variable
);

// Ready to use
const slugs = await slugkit.forgeSlugs('{adjective}-{noun}', 5);
console.log(slugs);
// ['brilliant-keyboard', 'clever-telescope', 'swift-compass', ...]
```

**Environment variables:**

```bash
# .env file (never commit this)
SLUGKIT_API_KEY=sk_live_abc123...
```

**⚠️ SECURITY WARNING:** Never embed API keys in client-side code, mobile apps, or public repositories. For browsers and mobile applications, use SDK keys instead (see below).

### SDK Keys (Client-Side Signature-Based)

SDK keys use cryptographic signatures to authenticate requests without exposing secret credentials in client-side code. The SDK handles all complexity automatically.

**Use SDK keys for:**
- Browser-based single-page applications
- Mobile applications (iOS, Android, React Native)
- Desktop applications with embedded browsers
- Any client-side environment

**Availability:** SDK keys are available on paid tiers - see the [feature matrix](/products/feature-matrix) for details.

**Getting an SDK key:**

1. Log in to your SlugKit dashboard
2. Navigate to **Dashboard → Organization → SDK Configuration**
3. Create an SDK configuration with a unique slug (e.g., "web-app-prod")
4. The SDK will automatically fetch signing keys using this slug

**Setup with SDK key (automatic key fetching):**

```typescript
import { SlugKit } from '@slugkit/sdk';

// Create a SlugKit instance with automatic key fetching
const slugkit = await SlugKit.fromBackend(
  'https://api.slugkit.com',  // Backend URL
  'web-app-prod'  // Your SDK slug from dashboard
);

// Ready to use - the SDK signs all requests automatically
const slugs = await slugkit.forgeSlugs('{adjective}-{noun}', 5);
```

**Setup with SDK key (manual JWK):**

For advanced use cases or environments where automatic fetching isn't suitable:

```typescript
import { SlugKit } from '@slugkit/sdk';

// Manually provide the JWK (JSON Web Key)
const jwk: JsonWebKey = {
  kty: 'EC',
  crv: 'P-256',
  x: 'base64url-encoded-x-coordinate',
  y: 'base64url-encoded-y-coordinate',
  d: 'base64url-encoded-private-key'
};

const slugkit = await SlugKit.fromJwk(
  'https://api.slugkit.com',
  'web-app-prod',
  jwk
);
```

**How SDK keys work:**

1. The SDK fetches your public/private key pair during initialization
2. Each request is cryptographically signed with headers:
   - `X-Signature`: Request signature
   - `X-Timestamp`: Request timestamp
   - `X-SDK-Slug`: Your SDK configuration identifier
3. SlugKit's API verifies signatures using your public key
4. Private keys stay in your application - never transmitted

**Key rotation:**

The SDK automatically handles key rotation:
- Fetches new keys 2 minutes before expiration
- Falls back to provided keys if fetching fails
- Schedules refreshes with jitter to avoid thundering herd

## Basic Usage

Once authenticated, the SDK provides a clean, promise-based API for generating slugs.

### Generate Custom Slugs (Forge)

Use **forge** to generate custom slugs with explicit pattern control:

```typescript
// Generate 5 slugs with a simple pattern
const slugs = await slugkit.forgeSlugs('{adjective}-{noun}', 5);
console.log(slugs);
// ['brilliant-keyboard', 'clever-telescope', 'swift-compass', 'elegant-framework', 'cosmic-symphony']

// Generate with seed for reproducible results
const seededSlugs = await slugkit.forgeSlugs(
  '{adjective}-{noun}',
  3,
  'campaign-2025'  // Seed
);
console.log(seededSlugs);
// Always produces the same slugs with this seed

// Generate with sequence offset
const offsetSlugs = await slugkit.forgeSlugs(
  '{adjective}-{noun}',
  2,
  undefined,  // No seed
  100  // Start at sequence 100
);
```

### Generate Unique Slugs from Series (Mint)

Use **mint** to generate guaranteed unique slugs from a configured series:

```typescript
// Mint 10 unique slugs from a series
const uniqueSlugs = await slugkit.mintSlugs('user-handles', 10);
console.log(uniqueSlugs);
// ['clever-wolf-01', 'swift-eagle-02', 'brave-tiger-03', ...]

// Mint with custom batch size for performance
const bulkSlugs = await slugkit.mintSlugs(
  'user-handles',
  500,
  2000  // Batch size (default: 1000)
);
```

**Note:** For organization-scoped API keys, you must specify the series slug. Series-scoped keys automatically target their associated series:

```typescript
// With series-scoped key (no series slug needed)
const slugs = await slugkit.mintSlugs(undefined, 10);

// With organization-scoped key (series slug required)
const slugs = await slugkit.mintSlugs('user-handles', 10);
```

### Preview Slugs (Slice)

Use **slice** to preview slugs from a series without consuming them:

```typescript
// Preview 50 slugs starting from sequence 1000
const preview = await slugkit.sliceSlugs(
  'user-handles',
  50,  // Count
  1000,  // Batch size
  1000  // Sequence offset
);
console.log(preview);
// Shows what the next 50 slugs will be without advancing the counter
```

### Validate Patterns

Before generating, validate your patterns:

```typescript
import { PatternParser } from '@slugkit/sdk';

// Validate a pattern (returns boolean)
const isValid = PatternParser.validate('{adjective}-{noun}');
console.log(isValid);  // true

// Parse a pattern (throws on invalid syntax)
try {
  const parsed = PatternParser.parse('{adjective@en:+formal-nsfw>3}');
  console.log(parsed.elements);  // Array of pattern elements
} catch (error) {
  console.error('Invalid pattern:', error.message);
}
```

### Get Pattern Information

Analyze patterns to understand capacity and characteristics:

```typescript
const info = await slugkit.getPatternInfo('{adjective}-{noun}');
console.log(info);
// {
//   pattern: '{adjective}-{noun}',
//   capacity: '12500000',  // ~12.5M possible combinations
//   max_slug_length: 30,  // Maximum generated length
//   complexity: 2,  // Number of variable components
//   components: 3  // Total components (including literals)
// }
```

## Working with Dictionaries

The SDK provides access to SlugKit's curated word dictionaries with automatic caching.

### Get Dictionary Statistics

```typescript
// Fetch dictionary stats (cached after first call)
const stats = await slugkit.getDictionaries();
console.log(stats);
// [
//   { kind: 'noun', lang: 'en', word_count: 15234, tag_count: 42 },
//   { kind: 'adjective', lang: 'en', word_count: 8456, tag_count: 38 },
//   { kind: 'verb', lang: 'en', word_count: 12789, tag_count: 35 },
//   ...
// ]

// Force fresh data (bypass cache)
const freshStats = await slugkit.fetchDictionaries();
```

### Get Dictionary Tags

```typescript
// Fetch dictionary tags (cached after first call)
const tags = await slugkit.getDictionaryTags();
console.log(tags);
// [
//   {
//     kind: 'noun',
//     tag: 'formal',
//     description: 'Formal, professional language',
//     opt_in: true,
//     word_count: 1234
//   },
//   {
//     kind: 'adjective',
//     tag: 'nsfw',
//     description: 'Not safe for work',
//     opt_in: true,
//     word_count: 89
//   },
//   ...
// ]

// Force fresh data (bypass cache)
const freshTags = await slugkit.fetchDictionaryTags();
```

**Caching behaviour:**

- `getDictionaries()` and `getDictionaryTags()` cache results in memory
- Cache persists for the lifetime of the SlugKit instance
- Use `fetch*` methods to bypass cache when needed
- No automatic cache invalidation (dictionaries are stable)

## Rate Limiting

The SDK automatically tracks rate limiting information from API responses and provides enhanced error handling.

### Check Current Rate Limits

```typescript
// After any API call, check current limits
const rateLimits = slugkit.getRateLimitInfo();
if (rateLimits) {
  console.log('RPM remaining:', rateLimits.rpmRemaining);  // -1 = unlimited
  console.log('Daily remaining:', rateLimits.dailyRemaining);
  console.log('Monthly remaining:', rateLimits.monthlyRemaining);
  console.log('Lifetime remaining:', rateLimits.lifetimeRemaining);
}
```

### Handle Rate Limit Errors

```typescript
try {
  const slugs = await slugkit.forgeSlugs('{noun}', 1000);
} catch (error) {
  if (error.retryAfter) {
    console.log(`Rate limited! Retry after ${error.retryAfter} seconds`);
    console.log('Reason:', error.rateLimitReason);

    // Access current limits even in error case
    if (error.rateLimitInfo) {
      console.log('Current RPM remaining:', error.rateLimitInfo.rpmRemaining);
    }

    // Implement exponential backoff
    await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000));
    // Retry the request...
  }
}
```

**Rate limit headers:**

The SDK extracts these headers from all API responses:
- `x-slug-rpm-remaining` - Requests per minute remaining
- `x-slug-daily-remaining` - Daily requests remaining
- `x-slug-monthly-remaining` - Monthly requests remaining
- `x-slug-lifetime-remaining` - Lifetime requests remaining
- `x-slug-rate-limit-reason` - Reason for rate limiting (errors only)
- `x-slug-retry-after` - Seconds to wait before retry (errors only)

See [Rate Limits & Quotas](api-rate-limits) for tier-specific limits.

## Error Handling

The SDK provides structured error handling with context-rich error messages.

```typescript
try {
  const result = await slugkit.forgeSlugs('{invalid-pattern}', 5);
} catch (error) {
  if (error.message.includes('Authentication failed')) {
    // Handle authentication errors
    // SDK automatically attempts key refresh for JWT mode
    console.error('Auth error:', error.message);
  } else if (error.message.includes('Network error')) {
    // Handle network/CORS errors
    console.error('Network error:', error.message);
  } else if (error.retryAfter) {
    // Handle rate limiting
    console.log(`Rate limited! Retry after ${error.retryAfter}s`);
  } else if (error.message.includes('Pattern validation failed')) {
    // Handle pattern syntax errors
    console.error('Invalid pattern:', error.message);
  } else {
    // Handle other errors
    console.error('Unexpected error:', error.message);
  }
}
```

**Common error scenarios:**

- **Authentication failures:** Invalid or expired API key, or signature verification failed (SDK auto-retries in JWT mode)
- **Network errors:** CORS issues, server unavailable, connection timeouts
- **Rate limiting:** Quota exceeded (includes retry-after and reason)
- **Pattern validation:** Invalid pattern syntax or unsupported features
- **Resource not found:** Series doesn't exist or not accessible

## TypeScript Support

The SDK is written in TypeScript and provides comprehensive type definitions out of the box.

### Core Types

```typescript
import { 
  SlugKit,
  PatternParser,
  DictionaryStats,
  DictionaryTag,
  PatternInfo,
  RateLimitInfo,
  RateLimitError
} from '@slugkit/sdk';

// Dictionary statistics type
interface DictionaryStats {
  kind: string;
  lang: string;
  word_count: number;
  tag_count: number;
}

// Dictionary tag type
interface DictionaryTag {
  kind: string;
  tag: string;
  description: string;
  opt_in: boolean;
  word_count: number;
}

// Pattern analysis type
interface PatternInfo {
  pattern: string;
  capacity: string;
  max_slug_length: number;
  complexity: number;
  components: number;
}

// Rate limiting information
interface RateLimitInfo {
  rpmRemaining: number;      // -1 = unlimited
  dailyRemaining: number;    // -1 = unlimited
  monthlyRemaining: number;  // -1 = unlimited
  lifetimeRemaining: number; // -1 = unlimited
}

// Enhanced rate limit error
interface RateLimitError extends Error {
  rateLimitReason?: string;
  retryAfter?: number;
  rateLimitInfo?: RateLimitInfo;
}
```

### Type-Safe Patterns

```typescript
// Pattern parser returns typed structures
import { PatternParser, ParsedPattern } from '@slugkit/sdk';

const parsed: ParsedPattern = PatternParser.parse('{adjective}-{noun}');

// Access typed elements
parsed.elements.forEach(element => {
  if (element.type === 'selector') {
    console.log('Selector:', element.kind);
  } else if (element.type === 'literal') {
    console.log('Literal:', element.value);
  }
});
```

## Next Steps

Now that you've installed and configured the SDK, explore environment-specific guides:

**Environment-Specific Guides:**
- [Browser Usage](sdk-typescript-browser) - Using SlugKit in browser applications with proper CORS and security
- [Node.js Usage](sdk-typescript-nodejs) - Server-side integration patterns and best practices
- [React Integration](sdk-typescript-react) - React hooks, context, and component patterns

**Core Concepts:**
- [Authentication Guide](api-authentication) - Deep dive into API keys, SDK keys, and security
- [Choosing Generation Methods](choosing-generation-method) - Forge vs Mint vs Slice decision guide
- [Pattern Syntax Basics](pattern-syntax-basics) - Master SlugKit's pattern language

**API Reference:**
- [Forge Endpoint](api-reference) - Custom slug generation with pattern control
- [Mint Endpoint](api-reference) - Unique series-based generation
- [Slice Endpoint](api-reference) - Preview slugs without consuming

**Advanced Topics:**
- [Rate Limits & Quotas](api-rate-limits) - Understanding tier-specific limits
- [Pattern Performance Optimization](pattern-performance-optimization) - Capacity planning and efficiency
- [Dictionary Reference](pattern-dictionary-reference) - Complete word dictionary documentation


---

# TypeScript SDK: Node.js Usage
Source: https://dev.slugkit.dev/docs/sdk-typescript-nodejs

# TypeScript SDK: Node.js Usage

Integrate SlugKit into your Node.js backend services, APIs, and automation scripts. This guide covers server-side patterns, performance optimization, error handling, and production deployment strategies.

## Overview

The TypeScript SDK provides a clean, promise-based API for Node.js applications with full TypeScript support and automatic authentication management.

**Perfect for:**
- RESTful APIs and GraphQL backends
- Microservices and serverless functions
- Background jobs and batch processing
- CLI tools and automation scripts
- Express, Fastify, NestJS, and other frameworks

**Key features for Node.js:**
- ✅ **API key authentication** - secure X-API-Key header authentication
- ✅ **Connection pooling** - efficient HTTP client with keep-alive
- ✅ **Rate limit tracking** - automatic quota monitoring
- ✅ **Error recovery** - automatic retries and fallback strategies
- ✅ **TypeScript-first** - comprehensive type definitions

## Prerequisites

Before integrating the SDK in your Node.js application:

1. **Install the SDK** - See [Installation & Setup](sdk-typescript-installation)
2. **Get an API key** - Dashboard → Organization → API Keys
3. **Configure environment variables** - Store keys securely
4. **Node.js 16+** - Ensure native fetch and Web Crypto support

## Basic Setup

### Initialize with API Key

```typescript
import { SlugKit } from '@slugkit/sdk';

// Initialize with API key (recommended for server-side)
const slugkit = SlugKit.fromApiKey(
  process.env.SLUGKIT_BACKEND_URL || 'https://api.slugkit.com',
  process.env.SLUGKIT_API_KEY!
);

// Ready to use
const slugs = await slugkit.forgeSlugs('{adjective}-{noun}', 5);
console.log(slugs);
// ['brilliant-keyboard', 'clever-telescope', 'swift-compass', ...]
```

### Environment Configuration

```bash
# .env file (never commit this)
SLUGKIT_API_KEY=sk_live_abc123...
SLUGKIT_BACKEND_URL=https://api.slugkit.com
```

**Load with dotenv:**

```typescript
import 'dotenv/config';
import { SlugKit } from '@slugkit/sdk';

const slugkit = SlugKit.fromApiKey(
  process.env.SLUGKIT_BACKEND_URL!,
  process.env.SLUGKIT_API_KEY!
);
```

### Singleton Pattern

Create a single SDK instance for your entire application:

```typescript
// lib/slugkit.ts
import { SlugKit } from '@slugkit/sdk';

let slugkitInstance: SlugKit | null = null;

export function getSlugKit(): SlugKit {
  if (!slugkitInstance) {
    slugkitInstance = SlugKit.fromApiKey(
      process.env.SLUGKIT_BACKEND_URL!,
      process.env.SLUGKIT_API_KEY!
    );
  }
  return slugkitInstance;
}
```

**Usage across your application:**

```typescript
import { getSlugKit } from './lib/slugkit';

const slugkit = getSlugKit();
const slugs = await slugkit.forgeSlugs('{adjective}-{noun}', 10);
```

## Framework Integration

### Express.js

Integrate SlugKit into Express routes:

```typescript
import express from 'express';
import { SlugKit } from '@slugkit/sdk';

const app = express();
const slugkit = SlugKit.fromApiKey(
  process.env.SLUGKIT_BACKEND_URL!,
  process.env.SLUGKIT_API_KEY!
);

app.use(express.json());

// Generate user handles endpoint
app.post('/api/handles/generate', async (req, res) => {
  try {
    const { count = 10 } = req.body;
    const handles = await slugkit.mintSlugs('user-handles', count);
    res.json({ handles });
  } catch (error) {
    console.error('Failed to generate handles:', error);
    
    if (error.retryAfter) {
      res.status(429).json({
        error: 'Rate limit exceeded',
        retryAfter: error.retryAfter
      });
    } else {
      res.status(500).json({ error: 'Failed to generate handles' });
    }
  }
});

// Custom slug generation endpoint
app.post('/api/slugs/forge', async (req, res) => {
  try {
    const { pattern, count = 5, seed } = req.body;
    const slugs = await slugkit.forgeSlugs(pattern, count, seed);
    res.json({ slugs });
  } catch (error) {
    console.error('Failed to forge slugs:', error);
    res.status(500).json({ error: 'Failed to forge slugs' });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
```

### Fastify

Use Fastify decorators for dependency injection:

```typescript
import Fastify from 'fastify';
import { SlugKit } from '@slugkit/sdk';

const fastify = Fastify({ logger: true });

// Decorate with SlugKit instance
const slugkit = SlugKit.fromApiKey(
  process.env.SLUGKIT_BACKEND_URL!,
  process.env.SLUGKIT_API_KEY!
);

fastify.decorate('slugkit', slugkit);

// Use in routes
fastify.post('/api/handles/generate', async (request, reply) => {
  const { count = 10 } = request.body as { count?: number };
  
  try {
    const handles = await fastify.slugkit.mintSlugs('user-handles', count);
    return { handles };
  } catch (error) {
    if (error.retryAfter) {
      reply.status(429);
      return { error: 'Rate limit exceeded', retryAfter: error.retryAfter };
    }
    throw error;
  }
});

fastify.listen({ port: 3000 });
```

### NestJS

Create an injectable service:

```typescript
// slugkit/slugkit.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SlugKit } from '@slugkit/sdk';

@Injectable()
export class SlugKitService implements OnModuleInit {
  private slugkit: SlugKit;

  constructor(private configService: ConfigService) {}

  onModuleInit() {
    this.slugkit = SlugKit.fromApiKey(
      this.configService.get<string>('SLUGKIT_BACKEND_URL')!,
      this.configService.get<string>('SLUGKIT_API_KEY')!
    );
  }

  async forgeSlugs(
    pattern: string,
    count: number,
    seed?: string
  ): Promise<string[]> {
    return this.slugkit.forgeSlugs(pattern, count, seed);
  }

  async mintSlugs(seriesSlug: string, count: number): Promise<string[]> {
    return this.slugkit.mintSlugs(seriesSlug, count);
  }

  async sliceSlugs(
    seriesSlug: string,
    count: number,
    batchSize?: number,
    sequence?: number
  ): Promise<string[]> {
    return this.slugkit.sliceSlugs(seriesSlug, count, batchSize, sequence);
  }

  getRateLimitInfo() {
    return this.slugkit.getRateLimitInfo();
  }
}
```

**Module configuration:**

```typescript
// slugkit/slugkit.module.ts
import { Module } from '@nestjs/common';
import { SlugKitService } from './slugkit.service';

@Module({
  providers: [SlugKitService],
  exports: [SlugKitService]
})
export class SlugKitModule {}
```

**Usage in controllers:**

```typescript
import { Controller, Post, Body } from '@nestjs/common';
import { SlugKitService } from './slugkit/slugkit.service';

@Controller('handles')
export class HandlesController {
  constructor(private slugkitService: SlugKitService) {}

  @Post('generate')
  async generate(@Body() body: { count: number }) {
    const handles = await this.slugkitService.mintSlugs(
      'user-handles',
      body.count
    );
    return { handles };
  }
}
```

## Common Use Cases

### User Registration with Unique Handles

Generate guaranteed unique handles during user signup:

```typescript
async function createUser(
  email: string,
  displayName: string
): Promise<User> {
  // Generate unique handle
  const handles = await slugkit.mintSlugs('user-handles', 1);
  const handle = handles[0];

  // Create user in database
  const user = await db.users.create({
    email,
    displayName,
    handle,
    createdAt: new Date()
  });

  return user;
}
```

### Batch Processing with Progress

Process large batches with progress tracking:

```typescript
async function generateProductSKUs(count: number): Promise<string[]> {
  const batchSize = 500;
  const skus: string[] = [];

  for (let i = 0; i < count; i += batchSize) {
    const currentBatch = Math.min(batchSize, count - i);
    
    try {
      const batch = await slugkit.mintSlugs('product-skus', currentBatch);
      skus.push(...batch);
      
      console.log(`Generated ${skus.length}/${count} SKUs`);
      
      // Check rate limits
      const rateLimits = slugkit.getRateLimitInfo();
      if (rateLimits && rateLimits.rpmRemaining < 10 && rateLimits.rpmRemaining !== -1) {
        console.warn('Approaching rate limit, slowing down...');
        await new Promise(resolve => setTimeout(resolve, 2000));
      }
    } catch (error) {
      if (error.retryAfter) {
        console.log(`Rate limited. Waiting ${error.retryAfter}s...`);
        await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000));
        i -= batchSize; // Retry this batch
      } else {
        throw error;
      }
    }
  }

  return skus;
}
```

### Background Job Processing

Generate identifiers in background workers:

```typescript
import { Queue, Worker } from 'bullmq';
import { getSlugKit } from './lib/slugkit';

const slugQueue = new Queue('slug-generation');

// Producer: Add jobs to queue
async function queueSlugGeneration(userId: string, count: number) {
  await slugQueue.add('generate-slugs', { userId, count });
}

// Consumer: Process jobs
const worker = new Worker('slug-generation', async (job) => {
  const { userId, count } = job.data;
  const slugkit = getSlugKit();

  try {
    const slugs = await slugkit.forgeSlugs('{adjective}-{noun}', count);
    
    // Store results
    await db.userSlugs.create({
      userId,
      slugs,
      generatedAt: new Date()
    });

    return { success: true, count: slugs.length };
  } catch (error) {
    console.error('Job failed:', error);
    throw error;
  }
});
```

### API Gateway / Proxy Pattern

Create a proxy service for frontend applications:

```typescript
import express from 'express';
import cors from 'cors';
import { SlugKit } from '@slugkit/sdk';

const app = express();
app.use(cors());
app.use(express.json());

const slugkit = SlugKit.fromApiKey(
  process.env.SLUGKIT_BACKEND_URL!,
  process.env.SLUGKIT_API_KEY!
);

// Proxy forge requests
app.post('/api/proxy/forge', async (req, res) => {
  try {
    const { pattern, count, seed } = req.body;
    
    // Validate pattern server-side
    const isValid = PatternParser.validate(pattern);
    if (!isValid) {
      return res.status(400).json({ error: 'Invalid pattern' });
    }

    const slugs = await slugkit.forgeSlugs(pattern, count, seed);
    res.json({ slugs });
  } catch (error) {
    console.error('Proxy error:', error);
    res.status(500).json({ error: 'Failed to generate slugs' });
  }
});

// Return rate limit info
app.get('/api/proxy/rate-limits', (req, res) => {
  const rateLimits = slugkit.getRateLimitInfo();
  res.json(rateLimits || { message: 'No rate limit data available' });
});

app.listen(3001, () => {
  console.log('SlugKit proxy running on port 3001');
});
```

### CLI Tool

Build command-line tools with SlugKit:

```typescript
#!/usr/bin/env node
import { Command } from 'commander';
import { SlugKit, PatternParser } from '@slugkit/sdk';

const program = new Command();
const slugkit = SlugKit.fromApiKey(
  process.env.SLUGKIT_BACKEND_URL!,
  process.env.SLUGKIT_API_KEY!
);

program
  .name('slugkit-cli')
  .description('Generate human-readable slugs from the command line')
  .version('1.0.0');

program
  .command('forge <pattern>')
  .description('Generate slugs with a custom pattern')
  .option('-c, --count <number>', 'Number of slugs to generate', '10')
  .option('-s, --seed <string>', 'Seed for reproducible generation')
  .action(async (pattern, options) => {
    try {
      const count = parseInt(options.count, 10);
      const slugs = await slugkit.forgeSlugs(pattern, count, options.seed);
      
      console.log(slugs.join('\n'));
    } catch (error) {
      console.error('Error:', error.message);
      process.exit(1);
    }
  });

program
  .command('mint <series>')
  .description('Generate unique slugs from a series')
  .option('-c, --count <number>', 'Number of slugs to mint', '10')
  .action(async (series, options) => {
    try {
      const count = parseInt(options.count, 10);
      const slugs = await slugkit.mintSlugs(series, count);
      
      console.log(slugs.join('\n'));
    } catch (error) {
      console.error('Error:', error.message);
      process.exit(1);
    }
  });

program
  .command('validate <pattern>')
  .description('Validate a pattern')
  .action((pattern) => {
    const isValid = PatternParser.validate(pattern);
    console.log(isValid ? '✓ Valid pattern' : '✗ Invalid pattern');
    process.exit(isValid ? 0 : 1);
  });

program.parse();
```

## Performance Optimization

### Connection Reuse

The SDK automatically reuses HTTP connections with keep-alive. Ensure you use a single SDK instance:

```typescript
// ✅ Good: Single instance (connection pooling)
const slugkit = SlugKit.fromApiKey(url, key);

// Use this instance throughout your app
export { slugkit };

// ❌ Bad: Creating new instances (no connection reuse)
function generateSlugs() {
  const slugkit = SlugKit.fromApiKey(url, key); // New instance!
  return slugkit.forgeSlugs('{noun}', 10);
}
```

### Caching Dictionary Data

Dictionary data is automatically cached, but you can prefetch it at startup:

```typescript
import { getSlugKit } from './lib/slugkit';

async function warmupCache() {
  const slugkit = getSlugKit();
  
  // Prefetch dictionary data
  await Promise.all([
    slugkit.getDictionaries(),
    slugkit.getDictionaryTags()
  ]);
  
  console.log('SlugKit cache warmed up');
}

// Call during application startup
warmupCache();
```

### Batch Processing

Generate slugs in batches for better performance:

```typescript
async function generateInBatches(
  totalCount: number,
  batchSize: number = 500
): Promise<string[]> {
  const results: string[] = [];
  
  for (let i = 0; i < totalCount; i += batchSize) {
    const count = Math.min(batchSize, totalCount - i);
    const batch = await slugkit.forgeSlugs('{adjective}-{noun}', count);
    results.push(...batch);
  }
  
  return results;
}
```

### Parallel Requests

For independent operations, parallelize requests:

```typescript
async function generateMultipleSeries(): Promise<Record<string, string[]>> {
  const [userHandles, productSKUs, sessionIDs] = await Promise.all([
    slugkit.mintSlugs('user-handles', 100),
    slugkit.mintSlugs('product-skus', 100),
    slugkit.forgeSlugs('{hex:8}', 100)
  ]);

  return { userHandles, productSKUs, sessionIDs };
}
```

## Error Handling

### Comprehensive Error Handler

```typescript
import { RateLimitError } from '@slugkit/sdk';

async function generateWithErrorHandling(
  pattern: string,
  count: number
): Promise<string[]> {
  try {
    return await slugkit.forgeSlugs(pattern, count);
  } catch (error) {
    // Type guard for rate limit errors
    if ('retryAfter' in error) {
      const rateLimitError = error as RateLimitError;
      console.error(
        `Rate limited: ${rateLimitError.rateLimitReason}. ` +
        `Retry after ${rateLimitError.retryAfter}s`
      );
      
      // Implement exponential backoff
      await new Promise(resolve => 
        setTimeout(resolve, rateLimitError.retryAfter! * 1000)
      );
      
      // Retry once
      return await slugkit.forgeSlugs(pattern, count);
    }
    
    // Authentication errors
    if (error.message.includes('Authentication failed')) {
      console.error('API key is invalid or expired');
      throw new Error('SlugKit authentication failed');
    }
    
    // Network errors
    if (error.message.includes('Network error')) {
      console.error('Network connectivity issue');
      throw new Error('SlugKit service unavailable');
    }
    
    // Pattern validation errors
    if (error.message.includes('Pattern validation failed')) {
      console.error('Invalid pattern syntax');
      throw new Error('Invalid SlugKit pattern');
    }
    
    // Unknown errors
    console.error('Unexpected error:', error);
    throw error;
  }
}
```

### Retry Logic with Exponential Backoff

```typescript
async function generateWithRetry(
  pattern: string,
  count: number,
  maxRetries: number = 3
): Promise<string[]> {
  let lastError: Error;
  
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await slugkit.forgeSlugs(pattern, count);
    } catch (error) {
      lastError = error as Error;
      
      // Don't retry on client errors (4xx)
      if (error.message.includes('Authentication failed') ||
          error.message.includes('Pattern validation failed')) {
        throw error;
      }
      
      // For rate limiting, use server-provided retry-after
      if ('retryAfter' in error) {
        const delay = (error as RateLimitError).retryAfter! * 1000;
        console.log(`Rate limited. Waiting ${delay}ms before retry ${attempt + 1}/${maxRetries}`);
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      
      // Exponential backoff for other errors
      if (attempt < maxRetries - 1) {
        const delay = Math.pow(2, attempt) * 1000;
        console.log(`Attempt ${attempt + 1} failed. Retrying in ${delay}ms...`);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  }
  
  throw lastError!;
}
```

### Circuit Breaker Pattern

Prevent cascading failures with a circuit breaker:

```typescript
class SlugKitCircuitBreaker {
  private failures = 0;
  private lastFailureTime = 0;
  private readonly threshold = 5;
  private readonly timeout = 60000; // 1 minute

  async execute<T>(fn: () => Promise<T>): Promise<T> {
    // Check if circuit is open
    if (this.failures >= this.threshold) {
      const timeSinceLastFailure = Date.now() - this.lastFailureTime;
      
      if (timeSinceLastFailure < this.timeout) {
        throw new Error('Circuit breaker is OPEN. Service temporarily unavailable.');
      }
      
      // Try to close circuit after timeout
      this.failures = 0;
    }

    try {
      const result = await fn();
      this.failures = 0; // Reset on success
      return result;
    } catch (error) {
      this.failures++;
      this.lastFailureTime = Date.now();
      throw error;
    }
  }
}

const circuitBreaker = new SlugKitCircuitBreaker();

// Usage
const slugs = await circuitBreaker.execute(() =>
  slugkit.forgeSlugs('{adjective}-{noun}', 10)
);
```

## Monitoring & Observability

### Rate Limit Monitoring

Track rate limit usage across your application:

```typescript
function logRateLimits() {
  const rateLimits = slugkit.getRateLimitInfo();
  
  if (!rateLimits) {
    console.log('No rate limit data available');
    return;
  }

  console.log('SlugKit Rate Limits:', {
    rpm: rateLimits.rpmRemaining === -1 ? 'unlimited' : rateLimits.rpmRemaining,
    daily: rateLimits.dailyRemaining === -1 ? 'unlimited' : rateLimits.dailyRemaining,
    monthly: rateLimits.monthlyRemaining === -1 ? 'unlimited' : rateLimits.monthlyRemaining,
    lifetime: rateLimits.lifetimeRemaining === -1 ? 'unlimited' : rateLimits.lifetimeRemaining
  });

  // Alert when approaching limits
  if (rateLimits.rpmRemaining !== -1 && rateLimits.rpmRemaining < 10) {
    console.warn('⚠️  Approaching RPM limit!');
  }
}

// Log after each request
await slugkit.forgeSlugs('{noun}', 10);
logRateLimits();
```

### Metrics Collection

Integrate with your monitoring system:

```typescript
import { performance } from 'perf_hooks';

async function generateWithMetrics(
  pattern: string,
  count: number
): Promise<string[]> {
  const startTime = performance.now();
  
  try {
    const slugs = await slugkit.forgeSlugs(pattern, count);
    const duration = performance.now() - startTime;
    
    // Send metrics to monitoring system (Prometheus, DataDog, etc.)
    metrics.histogram('slugkit.forge.duration', duration);
    metrics.increment('slugkit.forge.success', { pattern });
    
    return slugs;
  } catch (error) {
    const duration = performance.now() - startTime;
    
    metrics.histogram('slugkit.forge.duration', duration);
    metrics.increment('slugkit.forge.error', { 
      pattern, 
      error: error.constructor.name 
    });
    
    throw error;
  }
}
```

### Structured Logging

Use structured logging for better observability:

```typescript
import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [new winston.transports.Console()]
});

async function generateWithLogging(
  pattern: string,
  count: number
): Promise<string[]> {
  logger.info('Generating slugs', { pattern, count });
  
  try {
    const slugs = await slugkit.forgeSlugs(pattern, count);
    
    logger.info('Slugs generated successfully', {
      pattern,
      count: slugs.length,
      rateLimits: slugkit.getRateLimitInfo()
    });
    
    return slugs;
  } catch (error) {
    logger.error('Failed to generate slugs', {
      pattern,
      count,
      error: error.message,
      stack: error.stack
    });
    
    throw error;
  }
}
```

## Testing

### Unit Testing with Mocks

```typescript
// __tests__/user-service.test.ts
import { SlugKit } from '@slugkit/sdk';

jest.mock('@slugkit/sdk');

describe('UserService', () => {
  let mockSlugKit: jest.Mocked<SlugKit>;

  beforeEach(() => {
    mockSlugKit = {
      mintSlugs: jest.fn().mockResolvedValue(['test-user-01', 'test-user-02']),
      forgeSlugs: jest.fn().mockResolvedValue(['test-slug']),
      getRateLimitInfo: jest.fn().mockReturnValue(null)
    } as any;

    (SlugKit.fromApiKey as jest.Mock).mockReturnValue(mockSlugKit);
  });

  test('creates user with generated handle', async () => {
    const user = await createUser('test@example.com', 'Test User');
    
    expect(mockSlugKit.mintSlugs).toHaveBeenCalledWith('user-handles', 1);
    expect(user.handle).toBe('test-user-01');
  });
});
```

### Integration Testing

```typescript
// __tests__/integration/slugkit.test.ts
import { SlugKit } from '@slugkit/sdk';

describe('SlugKit Integration', () => {
  let slugkit: SlugKit;

  beforeAll(() => {
    slugkit = SlugKit.fromApiKey(
      process.env.SLUGKIT_TEST_BACKEND_URL!,
      process.env.SLUGKIT_TEST_API_KEY!
    );
  });

  test('generates slugs with forge', async () => {
    const slugs = await slugkit.forgeSlugs('{adjective}-{noun}', 5);
    
    expect(slugs).toHaveLength(5);
    expect(slugs[0]).toMatch(/^[a-z]+-[a-z]+$/);
  });

  test('handles rate limiting gracefully', async () => {
    try {
      // Try to exceed rate limit
      await Promise.all(
        Array.from({ length: 100 }, () => 
          slugkit.forgeSlugs('{noun}', 100)
        )
      );
    } catch (error) {
      expect(error).toHaveProperty('retryAfter');
      expect(error).toHaveProperty('rateLimitReason');
    }
  });
});
```

## Security Best Practices

### Environment Variable Management

Use a secrets manager in production:

```typescript
// AWS Secrets Manager example
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';

async function getSlugKitKey(): Promise<string> {
  const client = new SecretsManagerClient({ region: 'us-east-1' });
  const response = await client.send(
    new GetSecretValueCommand({ SecretId: 'slugkit-api-key' })
  );
  return JSON.parse(response.SecretString!).apiKey;
}

const apiKey = await getSlugKitKey();
const slugkit = SlugKit.fromApiKey('https://api.slugkit.com', apiKey);
```

### Key Rotation

Implement graceful key rotation:

```typescript
class SlugKitManager {
  private slugkit: SlugKit;
  private currentKey: string;

  constructor(initialKey: string) {
    this.currentKey = initialKey;
    this.slugkit = SlugKit.fromApiKey('https://api.slugkit.com', initialKey);
  }

  async rotateKey(newKey: string) {
    console.log('Rotating SlugKit API key...');
    
    // Create new instance with new key
    const newSlugKit = SlugKit.fromApiKey('https://api.slugkit.com', newKey);
    
    // Test new key
    await newSlugKit.forgeSlugs('{noun}', 1);
    
    // Switch to new instance
    this.slugkit = newSlugKit;
    this.currentKey = newKey;
    
    console.log('Key rotation successful');
  }

  getClient(): SlugKit {
    return this.slugkit;
  }
}
```

### Request Validation

Validate all inputs before sending to SlugKit:

```typescript
import { PatternParser } from '@slugkit/sdk';

function validateSlugRequest(pattern: string, count: number): void {
  // Validate count
  if (count < 1 || count > 10000) {
    throw new Error('Count must be between 1 and 10000');
  }

  // Validate pattern
  if (!PatternParser.validate(pattern)) {
    throw new Error('Invalid pattern syntax');
  }

  // Additional validation (e.g., prevent abuse)
  if (pattern.length > 500) {
    throw new Error('Pattern too long');
  }
}

// Usage
app.post('/api/forge', async (req, res) => {
  try {
    validateSlugRequest(req.body.pattern, req.body.count);
    const slugs = await slugkit.forgeSlugs(req.body.pattern, req.body.count);
    res.json({ slugs });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});
```

## Deployment Considerations

### Environment-Specific Configuration

```typescript
const config = {
  development: {
    backendUrl: 'http://localhost:8088',
    apiKey: process.env.SLUGKIT_DEV_API_KEY!
  },
  staging: {
    backendUrl: 'https://staging-api.slugkit.com',
    apiKey: process.env.SLUGKIT_STAGING_API_KEY!
  },
  production: {
    backendUrl: 'https://api.slugkit.com',
    apiKey: process.env.SLUGKIT_PROD_API_KEY!
  }
};

const env = process.env.NODE_ENV || 'development';
const { backendUrl, apiKey } = config[env];

const slugkit = SlugKit.fromApiKey(backendUrl, apiKey);
```

### Graceful Shutdown

Ensure clean shutdown:

```typescript
let isShuttingDown = false;

process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully...');
  isShuttingDown = true;
  
  // Close server, wait for pending requests
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
  
  // Force shutdown after 30 seconds
  setTimeout(() => {
    console.error('Forced shutdown');
    process.exit(1);
  }, 30000);
});

// Reject new requests during shutdown
app.use((req, res, next) => {
  if (isShuttingDown) {
    res.status(503).json({ error: 'Service shutting down' });
  } else {
    next();
  }
});
```

## Next Steps

**Related Guides:**
- [Browser Usage](sdk-typescript-browser) - Client-side integration with SDK keys
- [React Integration](sdk-typescript-react) - React hooks and patterns
- [Authentication Guide](api-authentication) - Deep dive into API keys and security

**Core Concepts:**
- [Choosing Generation Methods](choosing-generation-method) - Forge vs Mint vs Slice
- [Pattern Syntax Basics](pattern-syntax-basics) - Master pattern creation
- [Rate Limits & Quotas](api-rate-limits) - Understanding tier limits

**Advanced Topics:**
- [Pattern Performance Optimization](pattern-performance-optimization) - Capacity planning
- [Enterprise Integration Guide](guide-enterprise-integration) - SSO, monitoring, compliance


---

# TypeScript SDK: React Integration
Source: https://dev.slugkit.dev/docs/sdk-typescript-react

# TypeScript SDK: React Integration

Build React applications with SlugKit using hooks, context providers, and modern patterns. This guide covers everything from basic setup to advanced production patterns with TypeScript.

## Overview

The TypeScript SDK integrates seamlessly with React through custom hooks and context providers. This guide demonstrates idiomatic React patterns for slug generation in your applications.

**Perfect for:**
- Single-page applications with Create React App or Vite
- Next.js applications (both pages and app router)
- React Native mobile applications
- Static site generators like Gatsby

**Key patterns covered:**
- ✅ **Context providers** - application-wide SlugKit access
- ✅ **Custom hooks** - reusable slug generation logic
- ✅ **TypeScript integration** - full type safety
- ✅ **Error boundaries** - graceful error handling
- ✅ **Suspense support** - async initialization patterns

## Prerequisites

1. **Install the SDK** - See [Installation & Setup](sdk-typescript-installation)
2. **Create an SDK configuration** - Dashboard → Organization → SDK Configuration  
3. **Set up React 16.8+** - Hooks support required
4. **Configure TypeScript** - Optional but highly recommended

## Basic Setup

### Context Provider Pattern

Create a context provider for application-wide access:

```typescript
// contexts/SlugKitContext.tsx
import { 
  createContext, 
  useContext, 
  useState, 
  useEffect, 
  ReactNode 
} from 'react';
import { SlugKit } from '@slugkit/sdk';

interface SlugKitContextType {
  slugkit: SlugKit | null;
  loading: boolean;
  error: Error | null;
}

const SlugKitContext = createContext<SlugKitContextType | undefined>(undefined);

interface SlugKitProviderProps {
  children: ReactNode;
  backendUrl?: string;
  sdkSlug: string;
}

export function SlugKitProvider({ 
  children, 
  backendUrl = 'https://api.slugkit.com',
  sdkSlug 
}: SlugKitProviderProps) {
  const [slugkit, setSlugkit] = useState<SlugKit | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    async function initSlugKit() {
      try {
        const client = await SlugKit.fromBackend(backendUrl, sdkSlug);
        setSlugkit(client);
      } catch (err) {
        setError(err as Error);
        console.error('Failed to initialize SlugKit:', err);
      } finally {
        setLoading(false);
      }
    }

    initSlugKit();
  }, [backendUrl, sdkSlug]);

  return (
    <SlugKitContext.Provider value={{ slugkit, loading, error }}>
      {children}
    </SlugKitContext.Provider>
  );
}

export function useSlugKit() {
  const context = useContext(SlugKitContext);
  
  if (context === undefined) {
    throw new Error('useSlugKit must be used within SlugKitProvider');
  }
  
  return context;
}
```

### Application Setup

Wrap your application with the provider:

```typescript
// App.tsx
import { SlugKitProvider } from './contexts/SlugKitContext';
import { HandleGenerator } from './components/HandleGenerator';

function App() {
  return (
    <SlugKitProvider sdkSlug="web-app-prod">
      <HandleGenerator />
    </SlugKitProvider>
  );
}

export default App;
```

## Custom Hooks

### useForge Hook

Generate custom slugs with patterns:

```typescript
// hooks/useForge.ts
import { useState, useCallback } from 'react';
import { useSlugKit } from '../contexts/SlugKitContext';

export function useForge() {
  const { slugkit, loading: clientLoading } = useSlugKit();
  const [slugs, setSlugs] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const forge = useCallback(
    async (pattern: string, count: number, seed?: string) => {
      if (!slugkit) {
        setError(new Error('SlugKit not initialized'));
        return;
      }

      setLoading(true);
      setError(null);

      try {
        const result = await slugkit.forgeSlugs(pattern, count, seed);
        setSlugs(result);
        return result;
      } catch (err) {
        setError(err as Error);
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [slugkit]
  );

  return {
    slugs,
    forge,
    loading: clientLoading || loading,
    error
  };
}
```

**Usage:**

```typescript
import { useForge } from '../hooks/useForge';

function SlugGenerator() {
  const { slugs, forge, loading, error } = useForge();
  const [pattern, setPattern] = useState('{adjective}-{noun}');

  async function handleGenerate() {
    await forge(pattern, 10);
  }

  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <input 
        value={pattern} 
        onChange={(e) => setPattern(e.target.value)}
        placeholder="Enter pattern"
      />
      <button onClick={handleGenerate} disabled={loading}>
        {loading ? 'Generating...' : 'Generate Slugs'}
      </button>
      <ul>
        {slugs.map((slug, i) => <li key={i}>{slug}</li>)}
      </ul>
    </div>
  );
}
```

### useMint Hook

Generate unique slugs from series:

```typescript
// hooks/useMint.ts
import { useState, useCallback } from 'react';
import { useSlugKit } from '../contexts/SlugKitContext';

export function useMint(seriesSlug?: string) {
  const { slugkit, loading: clientLoading } = useSlugKit();
  const [slugs, setSlugs] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const mint = useCallback(
    async (count: number, customSeriesSlug?: string) => {
      if (!slugkit) {
        setError(new Error('SlugKit not initialized'));
        return;
      }

      setLoading(true);
      setError(null);

      try {
        const targetSeries = customSeriesSlug || seriesSlug;
        const result = await slugkit.mintSlugs(targetSeries, count);
        setSlugs(result);
        return result;
      } catch (err) {
        setError(err as Error);
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [slugkit, seriesSlug]
  );

  return {
    slugs,
    mint,
    loading: clientLoading || loading,
    error
  };
}
```

**Usage:**

```typescript
import { useMint } from '../hooks/useMint';

function UserHandleGenerator() {
  const { slugs, mint, loading, error } = useMint('user-handles');

  async function handleGenerate() {
    await mint(10);
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <button onClick={handleGenerate} disabled={loading}>
        {loading ? 'Generating...' : 'Generate Handles'}
      </button>
      <ul>
        {slugs.map((slug, i) => <li key={i}>{slug}</li>)}
      </ul>
    </div>
  );
}
```

### usePatternValidation Hook

Validate patterns in real-time:

```typescript
// hooks/usePatternValidation.ts
import { useState, useEffect } from 'react';
import { PatternParser } from '@slugkit/sdk';

export function usePatternValidation(pattern: string, debounceMs: number = 300) {
  const [isValid, setIsValid] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const timer = setTimeout(() => {
      if (!pattern) {
        setIsValid(false);
        setError(null);
        return;
      }

      try {
        const valid = PatternParser.validate(pattern);
        setIsValid(valid);
        setError(valid ? null : 'Invalid pattern syntax');
      } catch (err) {
        setIsValid(false);
        setError((err as Error).message);
      }
    }, debounceMs);

    return () => clearTimeout(timer);
  }, [pattern, debounceMs]);

  return { isValid, error };
}
```

**Usage:**

```typescript
import { usePatternValidation } from '../hooks/usePatternValidation';

function PatternInput() {
  const [pattern, setPattern] = useState('');
  const { isValid, error } = usePatternValidation(pattern);

  return (
    <div>
      <input 
        value={pattern}
        onChange={(e) => setPattern(e.target.value)}
        className={isValid ? 'valid' : 'invalid'}
      />
      {error && <span className="error">{error}</span>}
      {isValid && <span className="success">✓ Valid pattern</span>}
    </div>
  );
}
```

## Component Examples

### Interactive Slug Preview

Real-time preview as users type:

```typescript
import { useState, useEffect } from 'react';
import { useForge } from '../hooks/useForge';
import { usePatternValidation } from '../hooks/usePatternValidation';

export function SlugPreview() {
  const [pattern, setPattern] = useState('{adjective}-{noun}');
  const { isValid } = usePatternValidation(pattern);
  const { forge, slugs, loading } = useForge();

  useEffect(() => {
    if (isValid && pattern) {
      forge(pattern, 5);
    }
  }, [pattern, isValid, forge]);

  return (
    <div className="slug-preview">
      <h2>Pattern Preview</h2>
      
      <input
        type="text"
        value={pattern}
        onChange={(e) => setPattern(e.target.value)}
        placeholder="Enter a pattern"
        className={isValid ? 'valid' : 'invalid'}
      />

      {loading ? (
        <div>Generating preview...</div>
      ) : (
        <div className="preview-results">
          <h3>Preview Results:</h3>
          <ul>
            {slugs.map((slug, i) => (
              <li key={i} className="slug-item">{slug}</li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
```

### User Handle Selection

Let users choose from generated handles:

```typescript
import { useState } from 'react';
import { useMint } from '../hooks/useMint';

interface HandleSelectorProps {
  onSelect: (handle: string) => void;
}

export function HandleSelector({ onSelect }: HandleSelectorProps) {
  const { slugs, mint, loading } = useMint('user-handles');
  const [selected, setSelected] = useState<string | null>(null);

  async function handleRefresh() {
    await mint(10);
    setSelected(null);
  }

  function handleSelect(handle: string) {
    setSelected(handle);
    onSelect(handle);
  }

  return (
    <div className="handle-selector">
      <h2>Choose Your Handle</h2>
      
      <button onClick={handleRefresh} disabled={loading}>
        {loading ? 'Loading...' : 'Show More Options'}
      </button>

      <div className="handle-grid">
        {slugs.map((slug) => (
          <button
            key={slug}
            onClick={() => handleSelect(slug)}
            className={selected === slug ? 'selected' : ''}
          >
            @{slug}
          </button>
        ))}
      </div>

      {selected && (
        <div className="selection-preview">
          Selected: <strong>@{selected}</strong>
        </div>
      )}
    </div>
  );
}
```

### Batch Generation with Progress

Generate large batches with progress tracking:

```typescript
import { useState } from 'react';
import { useSlugKit } from '../contexts/SlugKitContext';

export function BatchGenerator() {
  const { slugkit } = useSlugKit();
  const [progress, setProgress] = useState(0);
  const [total, setTotal] = useState(0);
  const [results, setResults] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  async function generateBatch(totalCount: number) {
    if (!slugkit) return;

    setLoading(true);
    setTotal(totalCount);
    setProgress(0);
    setResults([]);

    const batchSize = 100;
    const allSlugs: string[] = [];

    try {
      for (let i = 0; i < totalCount; i += batchSize) {
        const count = Math.min(batchSize, totalCount - i);
        const batch = await slugkit.forgeSlugs('{adjective}-{noun}', count);
        
        allSlugs.push(...batch);
        setProgress(allSlugs.length);
        setResults([...allSlugs]);
      }
    } finally {
      setLoading(false);
    }
  }

  const progressPercent = total > 0 ? (progress / total) * 100 : 0;

  return (
    <div className="batch-generator">
      <button 
        onClick={() => generateBatch(1000)} 
        disabled={loading}
      >
        Generate 1000 Slugs
      </button>

      {loading && (
        <div className="progress">
          <div className="progress-bar" style={{ width: `${progressPercent}%` }} />
          <span>{progress} / {total}</span>
        </div>
      )}

      {results.length > 0 && (
        <div>
          <h3>Generated {results.length} slugs</h3>
          <textarea 
            readOnly 
            value={results.join('\n')}
            rows={10}
          />
        </div>
      )}
    </div>
  );
}
```

## Advanced Patterns

### Error Boundary

Catch and handle errors gracefully:

```typescript
import { Component, ReactNode } from 'react';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  hasError: boolean;
  error: Error | null;
}

export class SlugKitErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: any) {
    console.error('SlugKit error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        <div className="error-boundary">
          <h2>Something went wrong</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false, error: null })}>
            Try Again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}
```

**Usage:**

```typescript
import { SlugKitErrorBoundary } from './components/SlugKitErrorBoundary';

function App() {
  return (
    <SlugKitProvider sdkSlug="web-app-prod">
      <SlugKitErrorBoundary>
        <HandleGenerator />
      </SlugKitErrorBoundary>
    </SlugKitProvider>
  );
}
```

### Suspense Integration

Use React Suspense for async loading:

```typescript
import { Suspense } from 'react';

// Lazy load components that use SlugKit
const HandleGenerator = lazy(() => import('./components/HandleGenerator'));

function App() {
  return (
    <SlugKitProvider sdkSlug="web-app-prod">
      <Suspense fallback={<div>Loading SlugKit...</div>}>
        <HandleGenerator />
      </Suspense>
    </SlugKitProvider>
  );
}
```

### Rate Limit Monitoring

Display rate limit status to users:

```typescript
import { useSlugKit } from '../contexts/SlugKitContext';

export function RateLimitStatus() {
  const { slugkit } = useSlugKit();
  const rateLimits = slugkit?.getRateLimitInfo();

  if (!rateLimits) return null;

  const { rpmRemaining, dailyRemaining, monthlyRemaining } = rateLimits;

  return (
    <div className="rate-limit-status">
      <h4>Rate Limits</h4>
      <ul>
        <li>
          RPM: {rpmRemaining === -1 ? 'Unlimited' : rpmRemaining}
        </li>
        <li>
          Daily: {dailyRemaining === -1 ? 'Unlimited' : dailyRemaining}
        </li>
        <li>
          Monthly: {monthlyRemaining === -1 ? 'Unlimited' : monthlyRemaining}
        </li>
      </ul>
      
      {rpmRemaining !== -1 && rpmRemaining < 10 && (
        <div className="warning">⚠️ Approaching rate limit</div>
      )}
    </div>
  );
}
```

### Optimistic Updates

Update UI immediately while generating in background:

```typescript
import { useState } from 'react';
import { useMint } from '../hooks/useMint';

export function OptimisticHandleGenerator() {
  const { mint } = useMint('user-handles');
  const [handles, setHandles] = useState<string[]>([]);
  const [pending, setPending] = useState(false);

  async function generateHandle() {
    // Optimistically add placeholder
    const placeholderId = `generating-${Date.now()}`;
    setHandles(prev => [...prev, placeholderId]);
    setPending(true);

    try {
      const [newHandle] = await mint(1);
      
      // Replace placeholder with actual handle
      setHandles(prev => 
        prev.map(h => h === placeholderId ? newHandle : h)
      );
    } catch (error) {
      // Remove placeholder on error
      setHandles(prev => prev.filter(h => h !== placeholderId));
      console.error('Failed to generate handle:', error);
    } finally {
      setPending(false);
    }
  }

  return (
    <div>
      <button onClick={generateHandle} disabled={pending}>
        Generate Handle
      </button>
      
      <ul>
        {handles.map((handle, i) => (
          <li key={i} className={handle.startsWith('generating-') ? 'pending' : ''}>
            {handle.startsWith('generating-') ? 'Generating...' : handle}
          </li>
        ))}
      </ul>
    </div>
  );
}
```

## Next.js Integration

### App Router (Next.js 13+)

```typescript
// app/providers.tsx
'use client';

import { SlugKitProvider } from '@/contexts/SlugKitContext';
import { ReactNode } from 'react';

export function Providers({ children }: { children: ReactNode }) {
  return (
    <SlugKitProvider sdkSlug={process.env.NEXT_PUBLIC_SLUGKIT_SDK_SLUG!}>
      {children}
    </SlugKitProvider>
  );
}
```

```typescript
// app/layout.tsx
import { Providers } from './providers';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html>
      <body>
        <Providers>
          {children}
        </Providers>
      </body>
    </html>
  );
}
```

### Pages Router (Next.js 12 and earlier)

```typescript
// pages/_app.tsx
import type { AppProps } from 'next/app';
import { SlugKitProvider } from '@/contexts/SlugKitContext';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <SlugKitProvider sdkSlug={process.env.NEXT_PUBLIC_SLUGKIT_SDK_SLUG!}>
      <Component {...pageProps} />
    </SlugKitProvider>
  );
}
```

### Server-Side Generation

For server-side slug generation in Next.js:

```typescript
// pages/api/generate-handle.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { SlugKit } from '@slugkit/sdk';

const slugkit = SlugKit.fromApiKey(
  process.env.SLUGKIT_BACKEND_URL!,
  process.env.SLUGKIT_API_KEY!
);

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const handles = await slugkit.mintSlugs('user-handles', 1);
    res.status(200).json({ handle: handles[0] });
  } catch (error) {
    console.error('Failed to generate handle:', error);
    res.status(500).json({ error: 'Failed to generate handle' });
  }
}
```

## TypeScript Best Practices

### Type-Safe Hook Returns

```typescript
interface UseForgeReturn {
  slugs: string[];
  forge: (pattern: string, count: number, seed?: string) => Promise<string[] | undefined>;
  loading: boolean;
  error: Error | null;
}

export function useForge(): UseForgeReturn {
  // Implementation...
}
```

### Generic Hooks

Create reusable hooks with generics:

```typescript
import { useState, useCallback } from 'react';
import { useSlugKit } from '../contexts/SlugKitContext';

export function useSlugGeneration<T extends string>(
  generator: (slugkit: SlugKit) => Promise<string[]>,
  transformer?: (slugs: string[]) => T[]
) {
  const { slugkit } = useSlugKit();
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const generate = useCallback(async () => {
    if (!slugkit) return;

    setLoading(true);
    setError(null);

    try {
      const slugs = await generator(slugkit);
      const result = transformer ? transformer(slugs) : (slugs as any);
      setData(result);
      return result;
    } catch (err) {
      setError(err as Error);
      throw err;
    } finally {
      setLoading(false);
    }
  }, [slugkit, generator, transformer]);

  return { data, generate, loading, error };
}
```

## Testing

### Mock Provider for Tests

```typescript
// test-utils/MockSlugKitProvider.tsx
import { ReactNode } from 'react';
import { SlugKitContext } from '../contexts/SlugKitContext';
import { SlugKit } from '@slugkit/sdk';

const mockSlugKit = {
  forgeSlugs: jest.fn().mockResolvedValue(['test-slug-1', 'test-slug-2']),
  mintSlugs: jest.fn().mockResolvedValue(['user-handle-1', 'user-handle-2']),
  getRateLimitInfo: jest.fn().mockReturnValue(null)
} as unknown as SlugKit;

export function MockSlugKitProvider({ children }: { children: ReactNode }) {
  return (
    <SlugKitContext.Provider 
      value={{ 
        slugkit: mockSlugKit, 
        loading: false, 
        error: null 
      }}
    >
      {children}
    </SlugKitContext.Provider>
  );
}
```

### Component Tests with React Testing Library

```typescript
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MockSlugKitProvider } from '../test-utils/MockSlugKitProvider';
import { HandleGenerator } from './HandleGenerator';

describe('HandleGenerator', () => {
  test('generates handles on button click', async () => {
    render(
      <MockSlugKitProvider>
        <HandleGenerator />
      </MockSlugKitProvider>
    );

    const button = screen.getByText('Generate Handles');
    fireEvent.click(button);

    await waitFor(() => {
      expect(screen.getByText('user-handle-1')).toBeInTheDocument();
      expect(screen.getByText('user-handle-2')).toBeInTheDocument();
    });
  });
});
```

## Performance Optimization

### Memoization

Prevent unnecessary re-renders:

```typescript
import { memo, useMemo } from 'react';

interface SlugListProps {
  slugs: string[];
}

export const SlugList = memo(function SlugList({ slugs }: SlugListProps) {
  const sortedSlugs = useMemo(() => 
    [...slugs].sort(), 
    [slugs]
  );

  return (
    <ul>
      {sortedSlugs.map((slug, i) => (
        <li key={i}>{slug}</li>
      ))}
    </ul>
  );
});
```

### Lazy Loading

Load slug generation components on demand:

```typescript
import { lazy, Suspense } from 'react';

const HandleGenerator = lazy(() => import('./components/HandleGenerator'));
const SlugPreview = lazy(() => import('./components/SlugPreview'));

function App() {
  return (
    <SlugKitProvider sdkSlug="web-app-prod">
      <Suspense fallback={<div>Loading...</div>}>
        <HandleGenerator />
        <SlugPreview />
      </Suspense>
    </SlugKitProvider>
  );
}
```

## Troubleshooting

### "useSlugKit must be used within SlugKitProvider"

Ensure components using `useSlugKit` are wrapped in the provider:

```typescript
// ❌ Wrong: Component outside provider
function App() {
  return <HandleGenerator />;
}

// ✅ Correct: Component inside provider
function App() {
  return (
    <SlugKitProvider sdkSlug="web-app-prod">
      <HandleGenerator />
    </SlugKitProvider>
  );
}
```

### Infinite Re-render Loop

Avoid creating new functions in render:

```typescript
// ❌ Wrong: New function on every render
function Component() {
  const { forge } = useForge();
  
  useEffect(() => {
    forge('{noun}', 5);
  }, [forge]); // forge is a new function every render!
}

// ✅ Correct: Memoized callback
function Component() {
  const { forge } = useForge();
  
  useEffect(() => {
    forge('{noun}', 5);
  }, []); // Empty dependency array, runs once
}
```

### Stale Closure

Use functional updates to avoid stale state:

```typescript
// ❌ Wrong: Captures stale slugs
const [slugs, setSlugs] = useState<string[]>([]);

async function addSlug() {
  const [newSlug] = await mint(1);
  setSlugs([...slugs, newSlug]); // slugs might be stale
}

// ✅ Correct: Functional update
async function addSlug() {
  const [newSlug] = await mint(1);
  setSlugs(prev => [...prev, newSlug]);
}
```

## Next Steps

**Related Guides:**
- [Browser Usage](sdk-typescript-browser) - General browser patterns and security
- [Node.js Usage](sdk-typescript-nodejs) - Server-side integration
- [Installation & Setup](sdk-typescript-installation) - Basic SDK setup

**Core Concepts:**
- [Pattern Syntax Basics](pattern-syntax-basics) - Master pattern creation
- [Authentication Guide](api-authentication) - SDK keys and security
- [Rate Limits & Quotas](api-rate-limits) - Understanding tier limits

**Advanced Topics:**
- [Web Development Guide](guide-web-development) - Best practices for web applications
- [User Handles Guide](guide-user-handles) - Social and gaming identifiers


---

# SlugKit CLI Reference
Source: https://dev.slugkit.dev/docs/slugkit-cli-reference

# SlugKit CLI Reference

The SlugKit Python SDK includes a comprehensive command-line interface (CLI) for generating slugs, testing patterns, managing series, and inspecting your subscription limits.

## Installation

The CLI is installed automatically when you install the Python SDK:

```bash
pip install slugkit-py-sdk
```

After installation, the `slugkit` command will be available in your PATH.

## Configuration

The CLI can be configured using environment variables or command-line options.

### Environment Variables

```bash
# Set the base URL (required)
export SLUGKIT_BASE_URL="https://dev.slugkit.dev/api/v1"

# Set your API key (required for most operations)
export SLUGKIT_API_KEY="your-api-key-here"
```

### Command-Line Options

You can also pass configuration directly to commands:

```bash
slugkit --base-url "https://dev.slugkit.dev/api/v1" --api-key "your-api-key" mint 5
```

## Global Options

All commands support these global options:

- `--base-url TEXT` - SlugKit API base URL
- `--api-key TEXT` - Your API key
- `--output-format [text|json]` - Output format (default: text)
- `--help` - Show help message

## Commands

### mint - Generate Unique IDs from Series

Generate unique slugs from a series using the Mint endpoint.

**Usage:**

```bash
slugkit mint [COUNT] [OPTIONS]
```

**Arguments:**

- `COUNT` - Number of slugs to generate (default: 1)

**Options:**

- `--series TEXT` - Series slug to use (uses default if not specified)
- `--batch-size INTEGER` - Batch size for streaming (default: 100000)
- `--stream` - Stream slugs instead of batch generation

**Examples:**

```bash
# Generate a single slug
slugkit mint

# Generate 10 slugs
slugkit mint 10

# Generate from a specific series
slugkit mint 5 --series my-series-slug

# Stream slugs with custom batch size
slugkit mint 1000 --stream --batch-size 100
```

**Output (text format):**

```
happy-dolphin-0001
bright-falcon-0002
clever-panda-0003
```

**Output (JSON format):**

```bash
slugkit mint 3 --output-format json
```

```json
[
  "happy-dolphin-0001",
  "bright-falcon-0002",
  "clever-panda-0003"
]
```

### forge - Test Custom Patterns

Generate slugs from a custom pattern without creating a series.

**Usage:**

```bash
slugkit forge PATTERN [OPTIONS]
```

**Arguments:**

- `PATTERN` - The pattern to use (required)

**Options:**

- `--count INTEGER` - Number of slugs to generate (default: 1)
- `--seed TEXT` - Seed for reproducible generation
- `--sequence INTEGER` - Starting sequence number

**Examples:**

```bash
# Test a simple pattern
slugkit forge "{adjective}-{noun}"

# Generate multiple test slugs
slugkit forge "{color}-{animal}-{number:3d}" --count 5

# Use a seed for reproducible results
slugkit forge "{adjective}-{noun}" --seed test-seed --count 3

# Start from a specific sequence
slugkit forge "{noun}-{number:4d}" --sequence 1000 --count 5
```

**Output:**

```
happy-dolphin
bright-falcon
clever-panda
gentle-tiger
swift-eagle
```

### slice - Preview Slugs Without Consuming

Preview what slugs would be generated without actually consuming them from the series.

**Usage:**

```bash
slugkit slice [COUNT] [OPTIONS]
```

**Arguments:**

- `COUNT` - Number of slugs to preview (default: 10)

**Options:**

- `--series TEXT` - Series slug to preview
- `--sequence INTEGER` - Starting sequence number (default: 0)
- `--batch-size INTEGER` - Batch size for streaming (default: 100000)

**Examples:**

```bash
# Preview next 10 slugs
slugkit slice

# Preview next 50 slugs from a specific series
slugkit slice 50 --series my-series-slug

# Preview slugs starting from sequence 1000
slugkit slice 20 --sequence 1000
```

**Output:**

```
Previewing slugs (dry-run mode):
happy-dolphin-1000
bright-falcon-1001
clever-panda-1002
...
```

### stats - View Generation Statistics

Get statistics about slug generation for your organization or a specific series.

**Usage:**

```bash
slugkit stats [OPTIONS]
```

**Options:**

- `--series TEXT` - Get stats for a specific series (omit for organization-wide stats)

**Examples:**

```bash
# Get organization-wide statistics
slugkit stats

# Get statistics for a specific series
slugkit stats --series my-series-slug
```

**Output (text format):**

```
=== Generation Statistics ===

Event Type: mint
Date: total
Total Count: 104517
Request Count: 118
Total Duration: 1092348 μs
Avg Duration: 10.45 μs

Event Type: forge
Date: total
Total Count: 15
Request Count: 5
Total Duration: 500 μs
Avg Duration: 50.00 μs
```

**Output (JSON format):**

```bash
slugkit stats --output-format json
```

```json
[
  {
    "event_type": "mint",
    "date_part": "total",
    "total_count": 104517,
    "request_count": 118,
    "total_duration_us": 1092348,
    "avg_duration_us": 10.45
  },
  {
    "event_type": "forge",
    "date_part": "total",
    "total_count": 15,
    "request_count": 5,
    "total_duration_us": 500,
    "avg_duration_us": 50.0
  }
]
```

### limits - View Subscription Limits

Get your organization's subscription limits and features.

**Usage:**

```bash
slugkit limits
```

**Examples:**

```bash
# View limits in text format
slugkit limits

# View limits in JSON format
slugkit limits --output-format json
```

**Output (text format):**

```
=== Series Limits ===
Max Series                    : 5

=== Rate Limits ===
Requests Per Minute           : 100
Burst Requests Per Minute     : 1000

=== Forge Limits ===
Forge Enabled                 : True
Max Forge Per Day             : 10000
Max Forge Per Month           : 300000
Max Forge Per Request         : 500

=== Mint Limits ===
Mint Enabled                  : True
Max Mint Per Day              : 100000
Max Mint Per Month            : 3000000
Max Mint Per Request          : 10000

=== Slice Limits ===
Slice Enabled                 : True
Slice Window Back             : 1000
Slice Window Forward          : 10000

=== Access Control ===
API Key Access                : True
API Key Scopes                : read, write, admin
SDK Access                    : True
SDK Scopes                    : read, write

=== Other ===
Max Nodes                     : 100
Custom Features               : False
```

**Output (JSON format):**

```json
{
  "custom_features": false,
  "max_series": 5,
  "req_per_minute": 100,
  "burst_req_per_minute": 1000,
  "forge_enabled": true,
  "max_forge_per_day": 10000,
  "max_forge_per_month": 300000,
  "max_forge_per_request": 500,
  "mint_enabled": true,
  "max_mint_per_day": 100000,
  "max_mint_per_month": 3000000,
  "max_mint_per_request": 10000,
  "slice_enabled": true,
  "slice_window_back": 1000,
  "slice_window_forward": 10000,
  "max_nodes": 100,
  "api_key_access": true,
  "api_key_scopes": ["read", "write", "admin"],
  "sdk_access": true,
  "sdk_scopes": ["read", "write"]
}
```

### series-list - List Available Series

Get a list of all series available to your organization.

**Usage:**

```bash
slugkit series-list
```

**Output (text format):**

```
Available Series:
- my-first-series (My First Series)
- user-handles (User Handle Generator)
- api-endpoints (API Endpoint IDs)
```

**Output (JSON format):**

```bash
slugkit series-list --output-format json
```

```json
{
  "my-first-series": "My First Series",
  "user-handles": "User Handle Generator",
  "api-endpoints": "API Endpoint IDs"
}
```

### series-info - Get Series Information

Get detailed information about a specific series.

**Usage:**

```bash
slugkit series-info [OPTIONS]
```

**Options:**

- `--series TEXT` - Series slug (uses default if not specified)

**Examples:**

```bash
# Get info for default series
slugkit series-info

# Get info for specific series
slugkit series-info --series my-series-slug
```

**Output (text format):**

```
=== Series Information ===

Slug: my-series-slug
Organisation: my-org-slug
Pattern: {adjective}-{noun}-{number:4d}
Max Pattern Length: 80
Capacity: 1281739952493000
Generated Count: 105
Last Modified: 2025-08-29T00:54:35.128902+00:00
```

**Output (JSON format):**

```json
{
  "slug": "my-series-slug",
  "org_slug": "my-org-slug",
  "pattern": "{adjective}-{noun}-{number:4d}",
  "max_pattern_length": 80,
  "capacity": "1281739952493000",
  "generated_count": "105",
  "mtime": "2025-08-29T00:54:35.128902+00:00"
}
```

### validate - Validate a Pattern

Validate a pattern and get detailed information about its capacity and structure.

**Usage:**

```bash
slugkit validate PATTERN
```

**Arguments:**

- `PATTERN` - The pattern to validate (required)

**Examples:**

```bash
# Validate a simple pattern
slugkit validate "{adjective}-{noun}"

# Validate a complex pattern
slugkit validate "{adverb}-{adjective}-{noun}-{number:4,hex}"
```

**Output (text format):**

```
=== Pattern Information ===

Pattern: {adjective}-{noun}-{number:4d}
Capacity: 12817399524930000
Max Slug Length: 35
Complexity: 3
Components: 3
Node Count: 5
```

**Output (JSON format):**

```json
{
  "pattern": "{adjective}-{noun}-{number:4d}",
  "capacity": "12817399524930000",
  "max_slug_length": 35,
  "complexity": 3,
  "components": 3,
  "node_count": 5
}
```

### reset - Reset Series Generator

Reset a series generator back to its initial state (useful for development and testing).

**Usage:**

```bash
slugkit reset [OPTIONS]
```

**Options:**

- `--series TEXT` - Series slug to reset (resets default if not specified)

**Examples:**

```bash
# Reset default series
slugkit reset

# Reset specific series
slugkit reset --series my-series-slug
```

**Output:**

```
Series reset successfully
```

**Warning:** This operation cannot be undone. Use with caution in production environments.

## Output Formats

The CLI supports two output formats controlled by the `--output-format` option:

### Text Format (Default)

Human-readable output with formatted tables and sections. Best for interactive use.

```bash
slugkit stats
```

### JSON Format

Machine-readable JSON output. Best for scripting and automation.

```bash
slugkit stats --output-format json
```

## Error Handling

The CLI provides detailed error messages with context-specific suggestions:

### Authentication Errors

```
Error: Authentication failed
Suggestion: Check your API key is correct and has not expired
```

### Rate Limiting

```
Error: Rate limit exceeded
Reason: rate-limit-exceeded
Retry after: 60 seconds (1.0 minutes)
Remaining quotas: RPM: 0, Daily: 9500, Monthly: 250000
Suggestion: Wait 60 seconds before retrying
```

### Pattern Validation Errors

```
Error: Invalid pattern
Details: Unknown token type 'invalid' at position 10
Suggestion: Check pattern syntax in the documentation
```

## Exit Codes

The CLI uses standard exit codes:

- `0` - Success
- `1` - Error occurred

Use exit codes for scripting:

```bash
if slugkit mint 10; then
    echo "Success!"
else
    echo "Failed with exit code $?"
fi
```

## Examples and Common Workflows

### Generate IDs for a New Feature

```bash
# First, validate your pattern
slugkit validate "{feature}-{adjective}-{noun}-{number:3d}"

# Test the pattern to see sample output
slugkit forge "{feature}-{adjective}-{noun}-{number:3d}" --count 5

# Generate production IDs from your series
slugkit mint 100 --series feature-ids
```

### Monitor Usage and Limits

```bash
# Check current limits
slugkit limits --output-format json | jq '.max_mint_per_day'

# Check usage statistics
slugkit stats --output-format json | jq '.[] | select(.event_type=="mint") | .total_count'
```

### Automate ID Generation in Scripts

```bash
#!/bin/bash

# Generate IDs and save to file
slugkit mint 1000 --series user-handles --output-format json > user_handles.json

# Check if generation succeeded
if [ $? -eq 0 ]; then
    echo "Generated $(jq 'length' user_handles.json) IDs"
else
    echo "Generation failed"
    exit 1
fi
```

### Preview Before Generating

```bash
# Preview what will be generated
slugkit slice 10 --series production-ids

# If satisfied, generate for real
slugkit mint 10 --series production-ids
```

## Troubleshooting

### Command Not Found

If `slugkit` command is not found after installation:

```bash
# Reinstall with pipx for isolated environment
pipx install slugkit-py-sdk

# Or ensure pip install location is in PATH
python -m pip show slugkit-py-sdk
```

### Connection Errors

```bash
# Verify base URL is accessible
curl -I https://dev.slugkit.dev/api/v1/ping

# Test with explicit base URL
slugkit --base-url "https://dev.slugkit.dev/api/v1" mint
```

### API Key Issues

```bash
# Verify API key format (should start with 'ik-' or 'sk-')
echo $SLUGKIT_API_KEY

# Test authentication
slugkit limits
```

## See Also

- [Python SDK Installation](sdk-python-installation) - Install the full Python SDK
- [Pattern Syntax Basics](pattern-syntax-basics) - Learn pattern syntax
- [API Reference](api-reference) - Complete API documentation
- [Rate Limits & Quotas](api-rate-limits) - Understanding limits

---

# How It Works: The Slug Science of SlugKit
Source: https://dev.slugkit.dev/docs/slug-science-fiction

### There are UUIDs. There are incrementing integers. And then… there are slugs.

![Generating](/random-shit-card.png)

Readable, delightful, pattern-matching IDs like *fuzzy-pineapple-8008* or *epic-ceramic-sasquatch-42*. These aren’t just cute — they’re powerful identifiers that developers actually enjoy working with. SlugKit makes them possible. And behind every quirky slug is a careful blend of pseudo-randomness, math wizardry, and just enough chaos to keep things interesting.

Let’s dive into the slug nebula.

⸻

## 🎯 Deterministically Random

SlugKit doesn’t do “random” the way most people think of it. We use a deterministic engine — specifically, a pseudo-random number generator (PRNG) seeded per project.

Each project gets a private seed (internally derived from something obscured but stable, like an UUID). From this seed, we generate a reproducible sequence of pseudo-random numbers using a reliable algorithm. It’s like everyone gets their own personalised random universe — where randomness is guaranteed, but not universal.

* Repeatable: Same inputs, same slug. Great for tests, previews, and analytics.
* Unique per project: Dev and prod don’t cross streams.
* No coordination needed: Distributed systems can generate slugs independently and still behave like grownups.


In the [playground](/playground)? You get the same treatment, but your seed is generated in the browser, so you can share a link and recreate the slug — chaos for one, chaos for all.

⸻

## 🧮 Prime-Aligned Permutations

Here’s where we let our math flag fly.

To make the most of pseudo-randomness, we don’t just select words from a list at random. We shuffle each dictionary into a pseudo-random permutation — and then walk through it cyclically.

But here’s the twist: we align dictionary sizes to the nearest prime number. Why? Because primes are cycle-maximizing beasts. They help ensure the slug sequence has a ridiculously long period before repeating, especially when combining multiple dictionaries. The result is higher entropy across your slugs, fewer patterns, and a whole lot of mathematical smugness.

You don’t need to know this to use SlugKit — but if you’re the kind of person who smiled reading this paragraph, we see you.

⸻

## ✨ Pattern-Powered Slugs

SlugKit isn’t just a generator — it’s a slug language.

We support a powerful pattern syntax that lets you define exactly how your slugs should look. Want to keep things short? Go with `{noun}-{number:3}`. Feeling flamboyant? Try [`{adverb}-{Adjective:+pos}-{noun}-{number:4x}`](/playground?slug=doubly-cuneal-nutmeg-c23).

Here’s what a pattern can include:

* Placeholders for dictionary types: noun, adjective, verb, etc.
* Tag filters: Include only +pos or exclude -nsfw
* Length constraints for controlling word size
* Language specifiers (multi-language support will be growing sometime, current dictionaries contain only English words)
* Case control through the placeholder’s casing (e.g., {Adjective} = Title Case)

Want to add suffixes or glue text in between? You can. Anything outside {} is treated as literal. Even escaping is supported (\{ if you’re into that sort of thing).

You can also tack on global settings with square brackets — like language filters or default tags — so you don’t have to repeat yourself.

[`{Adverb}{Adjective}-{Noun}[+pos-nsfw]`](/playground?slug=square-garish-vibist-e69&highlight=2)

Result? Something like: *ManipulativelyWinsome-Demon*.

⸻

## 🏷️ Tags, Glorious Tags

Every dictionary entry can be tagged. These aren’t just keywords — they describe semantic qualities like emotion, domain, or safety level.

Examples:

| Tag | Meaning |
|---|---|
| +animal	 | Animals only |
| +pos | Positive tone |
| +device | Tools, gadgets, tech objects |
| -urlunsafe | Exclude words containing characters that are not safe for URLs |

⸻

## ☠️ Boring Slugs? Not On Our Watch

Random doesn’t always mean interesting. In fact, true randomness often leads to unfortunate streaks: dry-lion, dry-lion, dry-lion — great for a debugging session, less so for anything human-facing.

SlugKit watches for these. If the same word starts showing up in the same position too often, it’ll reroll behind the scenes (within the same seed space) to ensure your slugs stay lively. It’s not full entropy — it’s curated chaos.

We don’t just want slugs that work. We want slugs with personality.

⸻

## 🌐 Distributed, But Sane

SlugKit is built to work across machines, clusters, galaxies, etc.

Each project stores a persistent sequence counter in the service’s database. This counter drives the PRNG, advancing one step per slug. Multiple API keys per project? No problem — the scope is shared, and output remains consistent no matter which key you use.

In distributed setups, each slug request can be stateless, but the output is deterministic and scoped. You can cache results, parallelize calls, or generate slugs on the edge — and still maintain uniqueness and order.

Playground mode? It’s all ephemeral — seeds, counters, state — but the rules still apply.

⸻

## ⚗️ Example Slugs, Crafted with Patterns

Here are a few real-world patterns you can try:

1. Friendly slug for sharing links:

[`{adjective}-{noun}-{number:4}`](/playground?slug=dumbly-humped-easter-07d&highlight=3)
→ *aboveboard-teaser-1718*

2. Branded tech handle:

[`{Adjective:+pos}-{noun:+device}-{number:4x}`](/playground?slug=withal-astral-salter-e37&highlight=4)
→ *Playful-Waveguide-8345*

3. Future centuries royalty name:

[`{Adjective:+pos} {Noun:+person} {number:3R}`](/playground?slug=nimbly-hourly-holder-385&highlight=4)
→ *Conventional Hack LVI*

4. Slugs of exactly same length? We got you:

[`{adverb}-{adjective}-{noun}-{number:4x}[==4]`](/playground?slug=cosily-citric-sphinx-642&highlight=4)
→ *easy-rust-muck-e592*

5. Though it's somewhat dull, but we can generate passwords for you:

[`{aDverb}{special}{adJective}{special}{noUn}{special}{number:4x}[==4]`](/playground?pattern=%7BaDverb%7D%7Bspecial%7D%7BadJective%7D%7Bspecial%7D%7BnoUn%7D%7Bspecial%7D%7Bnumber%3A4x%7D%5B%3D%3D4%5D)

⸻

## Final Thoughts: What Makes a Great Slug?

A great slug should be:

* Readable — humans first, robots second.
* Diverse — no two in a row should feel the same.
* Contextual — match your product’s tone or domain.
* Memorable — for users, support teams, and marketing.

SlugKit is your slug forge. We do the math. You get the magic.


---

# SlugKit Generator Benchmark - Aug 28 2025 / add dictionary cache
Source: https://dev.slugkit.dev/docs/smitten-mileage-mdx

## A HUGE Drop In Timings

The most important metric - the slug generation

### Slug Generation

| Benchmark | 20250827 | Add Indexes | Δ | Add Cache | Δ | Details |
| --- | --- |--- | --- | --- | --- | --- |
| GenerateSlugs/0 | 73.533 µs | 28.222 µs | 🔽 -61.62% -45.311 µs | 903.000 ns | 🔽 -96.80% -27.319 µs | {verb}-{adverb}  |
| GenerateSlugs/1 | 303.032 µs | 138.858 µs | 🔽 -54.18% -164.174 µs | 1.326 µs | 🔽 -99.05% -137.532 µs | {adverb}-{noun}-{verb}  |
| GenerateSlugs/2 | 301.868 µs | 140.090 µs | 🔽 -53.59% -161.778 µs | 1.466 µs | 🔽 -98.95% -138.624 µs | {adverb}-{noun}-{verb}-{number:4x}  |
| GenerateSlugs/3 | 613.231 µs | 283.689 µs | 🔽 -53.74% -329.542 µs | 2.633 µs | 🔽 -99.07% -281.056 µs | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}  |
| GenerateSlugs/4 | 916.800 µs | 423.584 µs | 🔽 -53.80% -493.216 µs | 3.904 µs | 🔽 -99.08% -419.680 µs | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}  |

<details>

<summary>More intimate metrics that also were affected by introducing the cache</summary>

### Dictionary Filtering

| Benchmark | 20250827 |20250828 | Δ | 20250828(2) | Δ | Details |
| --- | --- |--- | --- | --- | --- | --- |
| FilterDictionary/0 | 202.000 µs | 91.931 µs | 🔽 -54.49% -110.069 µs | 68.000 ns | 🔽 -99.93% -91.863 µs | word  |
| FilterDictionary/1 | 150.000 µs | 84.200 ns | 🔽 -99.94% -149.916 µs | 70.100 ns | 🔽 -16.75% -14.100 ns | word:==5  |
| FilterDictionary/2 | 200.000 µs | 821.580 µs | 🔼 310.79% 621.580 µs | 71.300 ns | 🔽 -99.99% -821.509 µs | word:==10  |
| FilterDictionary/3 | 150.000 µs | 208.000 ns | 🔽 -99.86% -149.792 µs | 70.000 ns | 🔽 -66.35% -138.000 ns | word:==15  |
| FilterDictionary/4 | 150.000 µs | 209.000 ns | 🔽 -99.86% -149.791 µs | 74.800 ns | 🔽 -64.21% -134.200 ns | word:==20  |
| FilterDictionary/5 | 183.000 µs | 83.391 µs | 🔽 -54.43% -99.609 µs | 74.500 ns | 🔽 -99.91% -83.317 µs | word:<10  |
| FilterDictionary/6 | 153.000 µs | 306.000 ns | 🔽 -99.80% -152.694 µs | 70.800 ns | 🔽 -76.86% -235.200 ns | word:>10  |
| FilterDictionary/7 | 152.000 µs | 6.011 µs | 🔽 -96.05% -145.989 µs | 69.900 ns | 🔽 -98.84% -5.941 µs | word:<=8  |
| FilterDictionary/8 | 174.000 µs | 304.000 ns | 🔽 -99.83% -173.696 µs | 70.000 ns | 🔽 -76.97% -234.000 ns | word:>=12  |
| FilterDictionary/9 | 156.000 µs | 83.341 µs | 🔽 -46.58% -72.659 µs | 70.100 ns | 🔽 -99.92% -83.271 µs | word:!=10  |
| FilterDictionary/10 | 204.000 µs | 889.553 µs | 🔼 336.06% 685.553 µs | 70.500 ns | 🔽 -99.99% -889.482 µs | word:!=15  |
| FilterDictionary/11 | 695.000 µs | 91.481 µs | 🔽 -86.84% -603.519 µs | 71.400 ns | 🔽 -99.92% -91.410 µs | word:+tag1  |
| FilterDictionary/12 | 629.000 µs | 45.762 µs | 🔽 -92.72% -583.238 µs | 71.200 ns | 🔽 -99.84% -45.691 µs | word:+tag2  |
| FilterDictionary/13 | 598.000 µs | 22.684 µs | 🔽 -96.21% -575.316 µs | 71.100 ns | 🔽 -99.69% -22.613 µs | word:+tag3  |
| FilterDictionary/14 | 601.000 µs | 8.802 µs | 🔽 -98.54% -592.198 µs | 71.400 ns | 🔽 -99.19% -8.731 µs | word:+tag4  |
| FilterDictionary/15 | 692.000 µs | 62.215 µs | 🔽 -91.01% -629.785 µs | 71.800 ns | 🔽 -99.88% -62.143 µs | word:-tag1  |
| FilterDictionary/16 | 706.000 µs | 126.590 µs | 🔽 -82.07% -579.410 µs | 71.400 ns | 🔽 -99.94% -126.519 µs | word:-tag2  |
| FilterDictionary/17 | 752.000 µs | 173.317 µs | 🔽 -76.95% -578.683 µs | 78.000 ns | 🔽 -99.95% -173.239 µs | word:-tag3  |
| FilterDictionary/18 | 766.000 µs | 193.085 µs | 🔽 -74.79% -572.915 µs | 71.600 ns | 🔽 -99.96% -193.013 µs | word:-tag4  |
| FilterDictionary/19 | 1.140 ms | 127.259 µs | 🔽 -88.84% -1.013 ms | 79.100 ns | 🔽 -99.94% -127.180 µs | word:+tag1-tag2  |
| FilterDictionary/20 | 1.001 ms | 134.685 µs | 🔽 -86.54% -866.315 µs | 79.600 ns | 🔽 -99.94% -134.605 µs | word:+tag1+tag2  |
| FilterDictionary/21 | 1.011 ms | 142.409 µs | 🔽 -85.91% -868.591 µs | 83.500 ns | 🔽 -99.94% -142.326 µs | word:+tag1+tag2+tag3  |
| FilterDictionary/22 | 900.000 µs | 126.262 µs | 🔽 -85.97% -773.738 µs | 88.400 ns | 🔽 -99.93% -126.174 µs | word:+tag1+tag2+tag4-tag3  |
| FilterDictionary/23 | 648.000 µs | 93.300 ns | 🔽 -99.99% -647.907 µs | 79.000 ns | 🔽 -15.33% -14.300 ns | word:+tag1==5  |
| FilterDictionary/24 | 1.006 ms | 158.384 µs | 🔽 -84.26% -847.616 µs | 83.000 ns | 🔽 -99.95% -158.301 µs | word:+tag1+tag2==10  |
| FilterDictionary/25 | 966.000 µs | 148.810 µs | 🔽 -84.60% -817.190 µs | 83.200 ns | 🔽 -99.94% -148.727 µs | word:+tag1+tag2!=10  |
| FilterDictionary/26 | 1.002 ms | 241.000 ns | 🔽 -99.98% -1.002 ms | 90.200 ns | 🔽 -62.57% -150.800 ns | word:+tag1+tag2+tag3==15  |
| FilterDictionary/27 | 890.000 µs | 246.000 ns | 🔽 -99.97% -889.754 µs | 94.900 ns | 🔽 -61.42% -151.100 ns | word:+tag1+tag2+tag4-tag3==20  |
| FilterDictionary/28 | 709.000 µs | 135.213 µs | 🔽 -80.93% -573.787 µs | 79.600 ns | 🔽 -99.94% -135.133 µs | word:+tag1<8  |
| FilterDictionary/29 | -- | 150.981 µs | 🔼 0.00% 150.981 µs | 79.600 ns | 🔽 -99.95% -150.901 µs | word:+tag1>=8 |

### Pattern Calculation

| Benchmark | 20250827 |20250828 | Δ | 20250828(2) | Δ | Details |
| --- | --- |--- | --- | --- | --- | --- |
| CalculateSettings/0 | 73.940 µs | 27.460 µs | 🔽 -62.86% -46.480 µs | 614.000 ns | 🔽 -97.76% -26.846 µs | {verb}-{adverb}  |
| CalculateSettings/1 | 301.710 µs | 139.169 µs | 🔽 -53.87% -162.541 µs | 933.000 ns | 🔽 -99.33% -138.236 µs | {adverb}-{noun}-{verb}  |
| CalculateSettings/2 | 301.914 µs | 140.671 µs | 🔽 -53.41% -161.243 µs | 1.027 µs | 🔽 -99.27% -139.644 µs | {adverb}-{noun}-{verb}-{number:4x}  |
| CalculateSettings/3 | 301.136 µs | 139.909 µs | 🔽 -53.54% -161.227 µs | 1.490 µs | 🔽 -98.94% -138.419 µs | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}  |
| CalculateSettings/4 | 302.194 µs | 140.210 µs | 🔽 -53.60% -161.984 µs | 2.042 µs | 🔽 -98.54% -138.168 µs | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}  |

</details>

## Full Report

### Seed Hash Calculation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FNV1aHash/1 | 0.734 ns | 0.734 ns | 942461081 | 1 chars |
| FNV1aHash/2 | 0.984 ns | 0.984 ns | 710460342 | 2 chars |
| FNV1aHash/4 | 1.470 ns | 1.470 ns | 474536864 | 4 chars |
| FNV1aHash/8 | 2.460 ns | 2.460 ns | 285124690 | 8 chars |
| FNV1aHash/16 | 5.150 ns | 5.150 ns | 134404839 | 16 chars |
| FNV1aHash/32 | 11.000 ns | 11.000 ns | 62939028 | 32 chars |
| FNV1aHash/64 | 28.700 ns | 28.700 ns | 24319661 | 64 chars |
| FNV1aHash/128 | 79.700 ns | 79.700 ns | 8843986 | 128 chars |


</details>


### Permutation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| PermutePowerOf2/1 | 3.510 ns | 3.510 ns | 200107630 | 2^1 |
| PermutePowerOf2/2 | 3.530 ns | 3.530 ns | 200269220 | 2^2 |
| PermutePowerOf2/4 | 3.500 ns | 3.500 ns | 200073600 | 2^4 |
| PermutePowerOf2/8 | 3.500 ns | 3.500 ns | 200052301 | 2^8 |
| PermutePowerOf2/16 | 3.490 ns | 3.490 ns | 199387927 | 2^16 |
| PermutePowerOf2/18 | 3.510 ns | 3.510 ns | 200307353 | 2^18 |
| Permute/1 | 1.750 ns | 1.750 ns | 398323250 | 10^1 |
| Permute/2 | 2.100 ns | 2.090 ns | 334867814 | 10^2 |
| Permute/4 | 3.070 ns | 3.070 ns | 226989054 | 10^4 |
| Permute/8 | 8.240 ns | 8.240 ns | 83716370 | 10^8 |
| Permute/16 | 16.300 ns | 16.300 ns | 42903856 | 10^16 |
| Permute/18 | 21.300 ns | 21.300 ns | 30233320 | 10^18 |


</details>


### Pattern Parsing


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| ParsePattern/0 | 48.300 ns | 48.300 ns | 14437182 | {number:8d} |
| ParsePattern/1 | 48.200 ns | 48.200 ns | 14567954 | {special:8} |
| ParsePattern/2 | 63.400 ns | 63.400 ns | 10688696 | {special:8-12} |
| ParsePattern/3 | 54.100 ns | 54.100 ns | 12531450 | {noun} |
| ParsePattern/4 | 53.600 ns | 53.600 ns | 12896005 | {Noun} |
| ParsePattern/5 | 53.500 ns | 53.500 ns | 13209541 | {NOUN} |
| ParsePattern/6 | 53.400 ns | 53.400 ns | 13161193 | {nOun} |
| ParsePattern/7 | 58.700 ns | 58.700 ns | 12090941 | {adjective} |
| ParsePattern/8 | 58.300 ns | 58.300 ns | 11625115 | {ADJECTIVE} |
| ParsePattern/9 | 58.700 ns | 58.700 ns | 11642605 | {Adjective} |
| ParsePattern/10 | 59.500 ns | 59.500 ns | 11686550 | {aDjective} |
| ParsePattern/11 | 101.000 ns | 101.000 ns | 6891522 | {adjective:+tag} |
| ParsePattern/12 | 147.000 ns | 147.000 ns | 4833358 | {adjective:+tag1-tag2} |
| ParsePattern/13 | 83.300 ns | 82.800 ns | 8399693 | {adjective:==10} |
| ParsePattern/14 | 171.000 ns | 171.000 ns | 4085682 | {adjective:+tag1-tag2==10} |
| ParsePattern/15 | 115.000 ns | 115.000 ns | 5997687 | {adjective}-{noun} |
| ParsePattern/16 | 174.000 ns | 174.000 ns | 4006437 | {adjective}-{noun}-{verb} |
| ParsePattern/17 | 215.000 ns | 215.000 ns | 3245073 | {adverb}-{adjective}-{noun}-{number:4x} |


</details>


### Pattern Formatting


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FormatPattern/1 | 17.700 ns | 17.700 ns | 39338578 | 1 components |
| FormatPattern/2 | 24.600 ns | 24.600 ns | 28343552 | 2 components |
| FormatPattern/3 | 33.600 ns | 33.600 ns | 20732734 | 3 components |
| FormatPattern/4 | 40.000 ns | 40.000 ns | 17380016 | 4 components |
| FormatPattern/5 | 48.000 ns | 48.000 ns | 14619510 | 5 components |
| FormatPattern/6 | 54.400 ns | 54.400 ns | 12744884 | 6 components |
| FormatPattern/7 | 61.100 ns | 61.100 ns | 11236443 | 7 components |
| FormatPattern/8 | 70.100 ns | 70.100 ns | 9922346 | 8 components |
| FormatPattern/9 | 74.800 ns | 74.800 ns | 9350018 | 9 components |
| FormatPattern/10 | 81.200 ns | 81.200 ns | 8582853 | 10 components |


</details>


### Value Generation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| GenerateHexNumbers/1 | 22.300 ns | 22.300 ns | 31390586 | number:1x |
| GenerateHexNumbers/2 | 24.100 ns | 24.100 ns | 29132775 | number:2x |
| GenerateHexNumbers/4 | 25.000 ns | 25.000 ns | 27934419 | number:4x |
| GenerateHexNumbers/8 | 26.300 ns | 26.200 ns | 27181642 | number:8x |
| GenerateHexNumbers/16 | 33.100 ns | 33.100 ns | 22210071 | number:16x |
| GenerateHexNumbersUppercase/1 | 22.400 ns | 22.400 ns | 31205102 | number:1X |
| GenerateHexNumbersUppercase/2 | 24.200 ns | 24.200 ns | 28960774 | number:2X |
| GenerateHexNumbersUppercase/4 | 25.400 ns | 25.400 ns | 27930518 | number:4X |
| GenerateHexNumbersUppercase/8 | 26.200 ns | 26.200 ns | 26612875 | number:8X |
| GenerateHexNumbersUppercase/16 | 31.800 ns | 31.800 ns | 22549921 | number:16X |
| GenerateDecNumbers/1 | 52.300 ns | 52.300 ns | 13481653 | number:1d |
| GenerateDecNumbers/2 | 61.400 ns | 61.400 ns | 11199134 | number:2d |
| GenerateDecNumbers/4 | 60.900 ns | 60.900 ns | 11430290 | number:4d |
| GenerateDecNumbers/8 | 57.200 ns | 57.200 ns | 12070336 | number:8d |
| GenerateDecNumbers/16 | 82.200 ns | 82.200 ns | 8386732 | number:16d |
| GenerateDecNumbers/18 | 99.700 ns | 99.700 ns | 6932375 | number:18d |
| GenerateRomanNumbersUppercase/1 | 18.600 ns | 18.600 ns | 37945787 | number:1R |
| GenerateRomanNumbersUppercase/2 | 14.700 ns | 14.700 ns | 47283759 | number:2R |
| GenerateRomanNumbersUppercase/4 | 12.000 ns | 12.000 ns | 57973195 | number:4R |
| GenerateRomanNumbersUppercase/8 | 32.500 ns | 32.500 ns | 21706125 | number:8R |
| GenerateRomanNumbersUppercase/15 | 25.700 ns | 25.700 ns | 27203156 | number:15R |
| GenerateRomanNumbersLowercase/1 | 65.000 ns | 65.000 ns | 10792435 | number:1r |
| GenerateRomanNumbersLowercase/2 | 61.000 ns | 61.000 ns | 11546574 | number:2r |
| GenerateRomanNumbersLowercase/4 | 67.000 ns | 67.000 ns | 10542182 | number:4r |
| GenerateRomanNumbersLowercase/8 | 112.000 ns | 112.000 ns | 6260383 | number:8r |
| GenerateRomanNumbersLowercase/15 | 96.800 ns | 96.800 ns | 7239825 | number:15r |
| GenerateFromDictionary/1000 | 191.000 ns | 191.000 ns | 3664408 | 1000 words |
| GenerateFromDictionary/10000 | 198.000 ns | 198.000 ns | 3457465 | 10000 words |
| GenerateFromDictionary/100000 | 203.000 ns | 203.000 ns | 3355206 | 100000 words |
| GenerateFromDictionary/1000000 | 344.000 ns | 344.000 ns | 2022219 | 1000000 words |
| GenerateFromDictionaryUppercase/1000 | 335.000 ns | 335.000 ns | 2109923 | 1000 words |
| GenerateFromDictionaryUppercase/10000 | 346.000 ns | 346.000 ns | 2027660 | 10000 words |
| GenerateFromDictionaryUppercase/100000 | 358.000 ns | 358.000 ns | 2030131 | 100000 words |
| GenerateFromDictionaryUppercase/1000000 | 524.000 ns | 524.000 ns | 1353708 | 1000000 words |
| GenerateFromDictionaryTitleCase/1000 | 6.857 µs | 6.789 µs | 103983 | 1000 words |
| GenerateFromDictionaryTitleCase/10000 | 6.547 µs | 6.547 µs | 105734 | 10000 words |
| GenerateFromDictionaryTitleCase/100000 | 6.604 µs | 6.604 µs | 106430 | 100000 words |
| GenerateFromDictionaryTitleCase/1000000 | 6.708 µs | 6.708 µs | 105606 | 1000000 words |
| GenerateFromDictionaryMixedCase/1000 | 359.000 ns | 359.000 ns | 1942223 | 1000 words |
| GenerateFromDictionaryMixedCase/10000 | 408.000 ns | 408.000 ns | 1746028 | 10000 words |
| GenerateFromDictionaryMixedCase/100000 | 456.000 ns | 456.000 ns | 1554178 | 100000 words |
| GenerateFromDictionaryMixedCase/1000000 | 664.000 ns | 664.000 ns | 1047295 | 1000000 words |


</details>


### Dictionary Building


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| BuildLengthIndex | 10.589 ms | 10.589 ms | 65 |  |
| BuildTagIndex | 1.863 ms | 1.863 ms | 365 |  |
| BuildCombinedIndex | 14.003 ms | 14.003 ms | 51 |  |
| BuildDictionaryNoCache | 18.024 ms | 18.024 ms | 39 |  |
| BuildDictionaryWithCache | 17.949 ms | 17.949 ms | 39 |  |


</details>


### IndexQuery


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| QueryLengthIndex/0 | 7.410 ns | 7.410 ns | 98320016 | word:==5 |
| QueryLengthIndex/1 | 135.000 ns | 135.000 ns | 5013121 | word:==10 |
| QueryLengthIndex/2 | 43.300 ns | 43.300 ns | 15961125 | word:==15 |
| QueryLengthIndex/3 | 41.100 ns | 41.100 ns | 16844444 | word:==20 |
| QueryLengthIndex/4 | 19.100 ns | 19.000 ns | 37500871 | word:<10 |
| QueryLengthIndex/5 | 98.100 ns | 98.100 ns | 7292531 | word:>10 |
| QueryLengthIndex/6 | 17.800 ns | 17.800 ns | 39685971 | word:<=8 |
| QueryLengthIndex/7 | 98.200 ns | 98.200 ns | 7022325 | word:>=12 |
| QueryLengthIndex/8 | 153.000 ns | 153.000 ns | 4507638 | word:!=10 |
| QueryLengthIndex/9 | 205.000 ns | 205.000 ns | 3454416 | word:!=15 |
| QueryTagIndex/0 | 13.258 µs | 13.258 µs | 54566 | word:+tag1 |
| QueryTagIndex/1 | 6.756 µs | 6.756 µs | 103869 | word:+tag2 |
| QueryTagIndex/2 | 3.461 µs | 3.461 µs | 200184 | word:+tag3 |
| QueryTagIndex/3 | 989.000 ns | 989.000 ns | 750719 | word:+tag4 |
| QueryTagIndex/4 | 62.886 µs | 62.883 µs | 11254 | word:-tag1 |
| QueryTagIndex/5 | 85.003 µs | 85.002 µs | 8241 | word:-tag2 |
| QueryTagIndex/6 | 109.303 µs | 109.302 µs | 6331 | word:-tag3 |
| QueryTagIndex/7 | 120.112 µs | 120.111 µs | 5871 | word:-tag4 |
| QueryTagIndex/8 | 84.740 µs | 84.735 µs | 8241 | word:+tag1-tag2 |
| QueryTagIndex/9 | 90.433 µs | 90.433 µs | 7924 | word:+tag1+tag2 |
| QueryTagIndex/10 | 121.819 µs | 121.818 µs | 5297 | word:+tag1+tag2+tag3 |
| QueryTagIndex/11 | 126.684 µs | 125.578 µs | 5913 | word:+tag1+tag2+tag4-tag3 |
| QueryCombinedIndex/0 | 94.185 µs | 94.179 µs | 7439 | word |
| QueryCombinedIndex/1 | 9.660 ns | 9.660 ns | 62617851 | word:==5 |
| QueryCombinedIndex/2 | 832.807 µs | 832.801 µs | 840 | word:==10 |
| QueryCombinedIndex/3 | 41.600 ns | 41.600 ns | 16562554 | word:==15 |
| QueryCombinedIndex/4 | 42.500 ns | 42.500 ns | 16649820 | word:==20 |
| QueryCombinedIndex/5 | 85.051 µs | 85.050 µs | 8203 | word:<10 |
| QueryCombinedIndex/6 | 96.400 ns | 96.400 ns | 7032790 | word:>10 |
| QueryCombinedIndex/7 | 6.139 µs | 6.139 µs | 112145 | word:<=8 |
| QueryCombinedIndex/8 | 95.400 ns | 95.400 ns | 6819258 | word:>=12 |
| QueryCombinedIndex/9 | 87.018 µs | 87.017 µs | 8125 | word:!=10 |
| QueryCombinedIndex/10 | 903.350 µs | 903.343 µs | 763 | word:!=15 |
| QueryCombinedIndex/11 | 94.690 µs | 94.674 µs | 7356 | word:+tag1 |
| QueryCombinedIndex/12 | 47.877 µs | 47.877 µs | 14502 | word:+tag2 |
| QueryCombinedIndex/13 | 23.301 µs | 23.295 µs | 29757 | word:+tag3 |
| QueryCombinedIndex/14 | 8.690 µs | 8.690 µs | 81355 | word:+tag4 |
| QueryCombinedIndex/15 | 63.014 µs | 63.014 µs | 11071 | word:-tag1 |
| QueryCombinedIndex/16 | 129.167 µs | 129.153 µs | 5411 | word:-tag2 |
| QueryCombinedIndex/17 | 177.582 µs | 177.581 µs | 3984 | word:-tag3 |
| QueryCombinedIndex/18 | 195.113 µs | 195.112 µs | 3490 | word:-tag4 |
| QueryCombinedIndex/19 | 130.458 µs | 130.457 µs | 5387 | word:+tag1-tag2 |
| QueryCombinedIndex/20 | 137.901 µs | 137.900 µs | 5027 | word:+tag1+tag2 |
| QueryCombinedIndex/21 | 143.320 µs | 142.067 µs | 5017 | word:+tag1+tag2+tag3 |
| QueryCombinedIndex/22 | 127.099 µs | 127.099 µs | 5988 | word:+tag1+tag2+tag4-tag3 |
| QueryCombinedIndex/23 | 8.360 ns | 8.360 ns | 90283022 | word:+tag1==5 |
| QueryCombinedIndex/24 | 131.534 µs | 131.533 µs | 5321 | word:+tag1==10 |
| QueryCombinedIndex/25 | 154.679 µs | 154.678 µs | 4304 | word:+tag1+tag2==10 |
| QueryCombinedIndex/26 | 146.370 µs | 146.369 µs | 4860 | word:+tag1+tag2!=10 |
| QueryCombinedIndex/27 | 46.700 ns | 46.700 ns | 15224589 | word:+tag1+tag2+tag3==15 |
| QueryCombinedIndex/28 | 45.500 ns | 45.500 ns | 14940383 | word:+tag1+tag2+tag4-tag3==20 |
| QueryCombinedIndex/29 | 137.280 µs | 137.278 µs | 5213 | word:+tag1<8 |
| QueryCombinedIndex/30 | 152.472 µs | 152.471 µs | 4595 | word:+tag1>=8 |


</details>


### Index Estimation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| EstimateTagIndexWordCount/0 | 15.500 ns | 15.500 ns | 43860302 | word:+tag1 |
| EstimateTagIndexWordCount/1 | 14.800 ns | 14.800 ns | 47620857 | word:+tag2 |
| EstimateTagIndexWordCount/2 | 13.000 ns | 13.000 ns | 51877407 | word:+tag3 |
| EstimateTagIndexWordCount/3 | 12.800 ns | 12.800 ns | 52371134 | word:+tag4 |
| EstimateTagIndexWordCount/4 | 15.900 ns | 15.900 ns | 45367726 | word:-tag1 |
| EstimateTagIndexWordCount/5 | 14.800 ns | 14.800 ns | 49459916 | word:-tag2 |
| EstimateTagIndexWordCount/6 | 13.100 ns | 13.100 ns | 56067674 | word:-tag3 |
| EstimateTagIndexWordCount/7 | 12.900 ns | 12.900 ns | 55297501 | word:-tag4 |
| EstimateTagIndexWordCount/8 | 28.400 ns | 28.400 ns | 24564068 | word:+tag1-tag2 |
| EstimateTagIndexWordCount/9 | 29.700 ns | 29.700 ns | 23477594 | word:+tag1+tag2 |
| EstimateTagIndexWordCount/10 | 44.700 ns | 44.700 ns | 16232755 | word:+tag1+tag2+tag3 |
| EstimateTagIndexWordCount/11 | 56.600 ns | 56.600 ns | 12493567 | word:+tag1+tag2+tag4-tag3 |


</details>


### Dictionary Filtering


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| FilterDictionaryNoCache/0 | 93.948 µs | 93.947 µs | 7127 | word |
| FilterDictionaryNoCache/1 | 84.200 ns | 84.200 ns | 8209198 | word:==5 |
| FilterDictionaryNoCache/2 | 851.543 µs | 851.516 µs | 822 | word:==10 |
| FilterDictionaryNoCache/3 | 209.000 ns | 209.000 ns | 3268024 | word:==15 |
| FilterDictionaryNoCache/4 | 219.000 ns | 219.000 ns | 3317291 | word:==20 |
| FilterDictionaryNoCache/5 | 87.405 µs | 87.403 µs | 7881 | word:<10 |
| FilterDictionaryNoCache/6 | 309.000 ns | 309.000 ns | 2270938 | word:>10 |
| FilterDictionaryNoCache/7 | 6.291 µs | 6.291 µs | 107808 | word:<=8 |
| FilterDictionaryNoCache/8 | 312.000 ns | 312.000 ns | 2202647 | word:>=12 |
| FilterDictionaryNoCache/9 | 87.098 µs | 87.097 µs | 8122 | word:!=10 |
| FilterDictionaryNoCache/10 | 921.978 µs | 921.968 µs | 753 | word:!=15 |
| FilterDictionaryNoCache/11 | 95.412 µs | 95.411 µs | 7337 | word:+tag1 |
| FilterDictionaryNoCache/12 | 48.301 µs | 48.301 µs | 13939 | word:+tag2 |
| FilterDictionaryNoCache/13 | 23.466 µs | 23.466 µs | 29775 | word:+tag3 |
| FilterDictionaryNoCache/14 | 8.875 µs | 8.875 µs | 76326 | word:+tag4 |
| FilterDictionaryNoCache/15 | 63.161 µs | 63.160 µs | 10826 | word:-tag1 |
| FilterDictionaryNoCache/16 | 130.494 µs | 130.493 µs | 5322 | word:-tag2 |
| FilterDictionaryNoCache/17 | 176.112 µs | 176.110 µs | 3931 | word:-tag3 |
| FilterDictionaryNoCache/18 | 197.873 µs | 197.871 µs | 3504 | word:-tag4 |
| FilterDictionaryNoCache/19 | 130.220 µs | 130.219 µs | 5328 | word:+tag1-tag2 |
| FilterDictionaryNoCache/20 | 139.141 µs | 139.140 µs | 5099 | word:+tag1+tag2 |
| FilterDictionaryNoCache/21 | 151.652 µs | 151.651 µs | 4798 | word:+tag1+tag2+tag3 |
| FilterDictionaryNoCache/22 | 129.366 µs | 129.082 µs | 5678 | word:+tag1+tag2+tag4-tag3 |
| FilterDictionaryNoCache/23 | 92.500 ns | 92.500 ns | 7446353 | word:+tag1==5 |
| FilterDictionaryNoCache/24 | 157.327 µs | 157.326 µs | 4324 | word:+tag1+tag2==10 |
| FilterDictionaryNoCache/25 | 150.610 µs | 150.609 µs | 4752 | word:+tag1+tag2!=10 |
| FilterDictionaryNoCache/26 | 231.000 ns | 231.000 ns | 3013861 | word:+tag1+tag2+tag3==15 |
| FilterDictionaryNoCache/27 | 241.000 ns | 241.000 ns | 2854070 | word:+tag1+tag2+tag4-tag3==20 |
| FilterDictionaryNoCache/28 | 138.472 µs | 138.470 µs | 4967 | word:+tag1<8 |
| FilterDictionaryNoCache/29 | 153.186 µs | 153.172 µs | 4543 | word:+tag1>=8 |
| FilterDictionary/0 | 68.000 ns | 68.000 ns | 10333057 | word |
| FilterDictionary/1 | 70.100 ns | 70.100 ns | 10061230 | word:==5 |
| FilterDictionary/2 | 71.300 ns | 71.300 ns | 9725802 | word:==10 |
| FilterDictionary/3 | 70.000 ns | 70.000 ns | 9857981 | word:==15 |
| FilterDictionary/4 | 74.800 ns | 74.800 ns | 9272767 | word:==20 |
| FilterDictionary/5 | 74.500 ns | 74.500 ns | 8876016 | word:<10 |
| FilterDictionary/6 | 70.800 ns | 70.800 ns | 9812287 | word:>10 |
| FilterDictionary/7 | 69.900 ns | 69.900 ns | 9892467 | word:<=8 |
| FilterDictionary/8 | 70.000 ns | 70.100 ns | 9970587 | word:>=12 |
| FilterDictionary/9 | 70.100 ns | 70.100 ns | 9889491 | word:!=10 |
| FilterDictionary/10 | 70.500 ns | 70.500 ns | 9856639 | word:!=15 |
| FilterDictionary/11 | 71.400 ns | 71.400 ns | 9733025 | word:+tag1 |
| FilterDictionary/12 | 71.200 ns | 71.200 ns | 9773334 | word:+tag2 |
| FilterDictionary/13 | 71.100 ns | 71.100 ns | 9841349 | word:+tag3 |
| FilterDictionary/14 | 71.400 ns | 71.400 ns | 9649804 | word:+tag4 |
| FilterDictionary/15 | 71.800 ns | 71.800 ns | 9720523 | word:-tag1 |
| FilterDictionary/16 | 71.400 ns | 71.400 ns | 9706511 | word:-tag2 |
| FilterDictionary/17 | 78.000 ns | 77.700 ns | 9015294 | word:-tag3 |
| FilterDictionary/18 | 71.600 ns | 71.600 ns | 9778949 | word:-tag4 |
| FilterDictionary/19 | 79.100 ns | 79.100 ns | 8785141 | word:+tag1-tag2 |
| FilterDictionary/20 | 79.600 ns | 79.600 ns | 8792732 | word:+tag1+tag2 |
| FilterDictionary/21 | 83.500 ns | 83.500 ns | 8380779 | word:+tag1+tag2+tag3 |
| FilterDictionary/22 | 88.400 ns | 88.400 ns | 7822631 | word:+tag1+tag2+tag4-tag3 |
| FilterDictionary/23 | 79.000 ns | 79.000 ns | 8862428 | word:+tag1==5 |
| FilterDictionary/24 | 83.000 ns | 83.000 ns | 8381903 | word:+tag1+tag2==10 |
| FilterDictionary/25 | 83.200 ns | 83.200 ns | 8379683 | word:+tag1+tag2!=10 |
| FilterDictionary/26 | 90.200 ns | 90.200 ns | 7811661 | word:+tag1+tag2+tag3==15 |
| FilterDictionary/27 | 94.900 ns | 94.900 ns | 7423328 | word:+tag1+tag2+tag4-tag3==20 |
| FilterDictionary/28 | 79.600 ns | 79.600 ns | 8827725 | word:+tag1<8 |
| FilterDictionary/29 | 79.600 ns | 79.600 ns | 8816491 | word:+tag1>=8 |


</details>


### Pattern Calculation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| CalculateSettings/0 | 614.000 ns | 612.000 ns | 1145981 | {verb}-{adverb} |
| CalculateSettings/1 | 933.000 ns | 933.000 ns | 736818 | {adverb}-{noun}-{verb} |
| CalculateSettings/2 | 1.027 µs | 1.027 µs | 693716 | {adverb}-{noun}-{verb}-{number:4x} |
| CalculateSettings/3 | 1.490 µs | 1.490 µs | 471462 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| CalculateSettings/4 | 2.042 µs | 2.042 µs | 344180 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |


</details>


### Slug Generation


<details>
<summary>Benchmark results</summary>


| Benchmark                                     | Time  |           CPU | Iterations |     |
| ----                                          | ---   | ---           | ---        | --- |
| GenerateSlugInternal/0 | 478.000 ns | 478.000 ns | 1514546 | {verb}-{adverb} |
| GenerateSlugInternal/1 | 687.000 ns | 687.000 ns | 1001231 | {adverb}-{noun}-{verb} |
| GenerateSlugInternal/2 | 755.000 ns | 755.000 ns | 913890 | {adverb}-{noun}-{verb}-{number:4x} |
| GenerateSlugInternal/3 | 1.378 µs | 1.378 µs | 513645 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| GenerateSlugInternal/4 | 2.079 µs | 2.079 µs | 339484 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| GenerateSlugs/0 | 903.000 ns | 903.000 ns | 772544 | {verb}-{adverb} |
| GenerateSlugs/1 | 1.326 µs | 1.326 µs | 485322 | {adverb}-{noun}-{verb} |
| GenerateSlugs/2 | 1.466 µs | 1.466 µs | 470516 | {adverb}-{noun}-{verb}-{number:4x} |
| GenerateSlugs/3 | 2.633 µs | 2.633 µs | 264889 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |
| GenerateSlugs/4 | 3.904 µs | 3.903 µs | 179066 | {adverb}-{noun}-{verb}-{adverb}-{noun}-{verb}-{adverb}-{noun}-{verb} |


</details>



---

# Technical Highlights
Source: https://dev.slugkit.dev/docs/technical-highlights

## Built for Production Scale

SlugKit's architecture combines cutting-edge performance with mathematical precision, delivering enterprise-grade reliability whilst maintaining the flexibility developers love.

## Open Source Foundation

**SlugKit Engine** - Our core generation algorithms are open source, built with modern C++ for maximum performance and transparency.

[**View on GitHub →**](https://github.com/slugkit/slugkit-generator)

- **Zero dependencies** - Pure C++ implementation with no external runtime requirements
- **Memory efficient** - Optimised data structures for minimal memory footprint  
- **Cross-platform** - Runs on Linux, macOS, Windows, and embedded systems
- **Embeddable** - Use the engine directly in your applications

---

## High-Performance Backend

### C++ with userver Framework

Built on [userver](https://userver.tech), Yandex's production-proven microservices framework that powers some of the world's largest web services.

**Performance characteristics:**
- **Sub-millisecond latency** - 3-20μs per slug generation
- **High throughput** - Handle thousands of concurrent requests
- **Memory stability** - Zero memory leaks with RAII and smart pointers
- **Async I/O** - Non-blocking operations for maximum concurrency

### Modern C++ Design

**C++20 standard** with contemporary best practices:
- **Concepts and constraints** for compile-time safety
- **Structured bindings** for cleaner code
- **std::span and ranges** for memory-safe operations
- **Coroutines** for async processing (where supported)

```cpp
// Example: Type-safe pattern compilation
auto pattern = compile_pattern("{adjective}-{noun}");
auto slugs = generate_batch(pattern, 1000);
```

---

## Enterprise Data Storage

### PostgreSQL v16

**Production deployments** use PostgreSQL v16 for maximum reliability and performance.

**Key features:**
- **ACID compliance** - Guaranteed data consistency
- **Concurrent safety** - Atomic counter operations across distributed instances  
- **Backup and recovery** - Point-in-time recovery and streaming replication
- **Performance tuning** - Optimised queries with proper indexing strategies

**SQL implementation:**
```sql
-- Lowercase keywords as per preference
select series_slug, pattern, generated_count 
from series 
where org_slug = $1 
order by mtime desc;
```

### SQLite for Lite Edition

**Embedded deployments** use SQLite for zero-configuration operation.

- **Single file database** - No server setup required
- **Read-only dictionaries** - Embedded word collections
- **Docker-ready** - Packaged with container images
- **Development friendly** - Perfect for local testing

---

## Mathematical Precision

### Uniqueness Guarantees

**Series domains** provide mathematical certainty about uniqueness within defined scopes.

**Capacity calculation algorithm:**
1. **Component analysis** - Calculate individual capacities for each pattern element
2. **Prime optimisation** - Reduce dictionary sizes to nearest beneficial primes
3. **LCM computation** - Use least common multiple for maximum diversity
4. **Constraint application** - Apply global filters and length restrictions

```cpp
// Simplified capacity calculation
auto adjective_capacity = filter_dictionary("adjective", tags, constraints);
auto noun_capacity = filter_dictionary("noun", tags, constraints);  
auto number_capacity = std::pow(base, length);
auto total_capacity = lcm(adjective_capacity, noun_capacity, number_capacity);
```

### Deterministic Generation

**Reproducible results** using cryptographic-quality pseudo-random number generators.

- **Seed-based generation** - Same seed always produces same sequence
- **Mersenne Twister** - High-quality randomness for word selection
- **Sequence integrity** - Counter-based advancement ensures no gaps or duplicates

---

## Pattern Language Implementation

### Formal Grammar Parser

**EBNF-based parser** with full syntax validation and error reporting.

```ebnf
pattern := ARBITRARY, { placeholder, ARBITRARY }, [ global_settings ];
placeholder := '{', (selector | number_gen | special_char_gen), '}';
selector := kind ['@' lang], [':', [tags], [length_constraint], [options]];
```

### Advanced Text Processing

**Arbitrary text placement** - Insert any Unicode text between placeholders:
- **Separators** - `-`, `_`, `.`, `/`, `@`, `://`, `=`
- **Special characters** - `#`, `!`, `?`, `*`, `%`, emoji
- **Complex structures** - URLs, file paths, command syntax

**Mathematical case transformations** - Deterministic capitalisation patterns:
```cpp
// Pattern: {AdJeCtIvE} → "brilliant" becomes "BrIlLiAnT"
std::string apply_case_pattern(const std::string& word, const std::string& pattern);
```

---

## Distributed Architecture

### Multi-Instance Safety

**Atomic operations** ensure consistency across distributed deployments.

```sql
-- Atomic counter increment with PostgreSQL
update series 
set generated_count = generated_count + $2 
where slug = $1 
returning generated_count;
```

### Caching Strategy

**Multi-level caching** for optimal performance:
- **Pattern compilation cache** - Compiled patterns stored in memory
- **Dictionary cache** - Word lists cached per process
- **Capacity cache** - Pre-calculated capacities with 30-60 second TTL
- **Connection pooling** - Efficient database connection management

---

## Quality Assurance

### Comprehensive Testing

**Production-grade testing** across all components:
- **Unit tests** - 95%+ code coverage with Google Test framework
- **Integration tests** - End-to-end API testing with real database scenarios
- **Performance benchmarks** - Continuous performance regression testing
- **Fuzzing** - Pattern parser stress testing with invalid inputs

### Memory Safety

**Modern C++ safety practices:**
- **RAII everywhere** - Automatic resource management
- **Smart pointers** - No manual memory management
- **Bounds checking** - Safe array and string operations
- **Sanitiser testing** - Address, thread, and undefined behaviour sanitisers

---

## Observability

### Metrics and Monitoring

**Production observability** with detailed metrics:
- **Request latency** - P50, P95, P99 percentiles
- **Throughput metrics** - Requests per second by endpoint
- **Error rates** - 4xx/5xx response categorisation
- **Resource usage** - CPU, memory, database connection utilisation

### Structured Logging

**JSON-structured logs** for modern observability stacks:
```json
{
  "timestamp": "2025-09-08T10:30:00Z",
  "level": "INFO", 
  "component": "pattern_engine",
  "operation": "forge",
  "pattern": "{adjective}-{noun}",
  "count": 100,
  "duration_us": 1547,
  "capacity": 708339294
}
```

---

## Security

### API Security

**Enterprise-grade security** throughout the stack:
- **API key authentication** - Secure token-based access control
- **Rate limiting** - Configurable per-key quotas and burst limits
- **Input validation** - Comprehensive pattern and parameter sanitisation
- **TLS encryption** - All communication secured with modern TLS

### Data Protection

**Privacy by design:**
- **No user data storage** - Generated slugs are not retained
- **Audit logging** - Optional request logging for compliance
- **GDPR compliance** - Minimal data collection with clear retention policies

---

This technical foundation ensures SlugKit delivers on its promise of fast, reliable, and scalable slug generation whilst maintaining the mathematical guarantees and aesthetic appeal that make it unique in the market.


---

# Terms of Service (TOS) - 2025-08
Source: https://dev.slugkit.dev/docs/tos-2025-08

# Terms of Service

**Effective Date:** August 1, 2025
**Version:** 2025-08

These Terms of Service ("Terms") govern your access to and use of the SlugKit service ("Service"), operated by **Sergei Fedorov pr Računarsko programiranje cpp Beograd** ("Provider", "we", "us").

By using the Service, you agree to be bound by these Terms.

## 1. Overview of Service

SlugKit is a hosted platform that generates unique, human-readable identifiers ("Slugs") based on user-defined or system-provided patterns. The Service is offered as a Software-as-a-Service (SaaS) product with free and paid tiers.

Use of the Service is also governed by our [EULA](/legal/eula-2025-06) and [Privacy Policy](/legal/privacy-policy-2025-06).

## 2. Account Registration

To access the Service, you must create an account and provide a valid email address. You are responsible for maintaining the security of your account and credentials.

You must be at least 18 years old to use the Service.

## 3. Subscription and Payment

Paid subscriptions are managed and billed via our merchant-of-record, [Paddle.com Market Limited](https://paddle.com/), which handles payment processing, invoicing, taxes, and compliance.

By subscribing to a paid plan:
- You agree to Paddle's [Buyer Terms](https://www.paddle.com/legal-buyers)
- You authorize Paddle to charge your selected payment method on a recurring basis (monthly or annually)

Plan limits, pricing, and billing frequencies are described on our website or pricing page. All prices are listed in USD unless stated otherwise.

## 4. Refunds and Cancellations

You may cancel your subscription at any time. Cancellation will take effect at the end of your current billing period.

Refunds are handled in accordance with Paddle's refund policy. To request a refund, contact us or Paddle directly at [https://paddle.net](https://paddle.net).

## 5. Usage Limits

Each subscription tier includes specific usage limits (e.g., number of Slugs per month). You agree not to circumvent rate limits or access restrictions.

Excessive or abusive use of the Service may result in temporary suspension or termination of your account.

## 6. Service Level and Availability

We aim to maintain high availability and performance of the Service. Paid tiers may include guaranteed service levels (SLA), as specified in your subscription plan. Free tiers are provided without any performance guarantee.

## 7. Acceptable Use

You agree not to:
- Use the Service for unlawful, harmful, or abusive purposes
- Reverse-engineer, scrape, or attempt to bypass access controls
- Interfere with the normal functioning of the Service or its infrastructure

## 8. Intellectual Property

All intellectual property related to the Service, including the slug generation engine, dictionaries, and associated software, is owned by the Provider. Users may define and use custom Slug patterns but do not gain ownership over the underlying generation tools.

## 9. Termination

We may suspend or terminate your access to the Service at any time, especially in case of violations of these Terms or abuse of the system. Upon termination, your access and data may be deleted.

## 10. Disclaimers

The Service is provided "as is", without warranties of any kind. For paid users, specific uptime guarantees may apply. We are not responsible for damages resulting from use or inability to use the Service.

## 11. Limitation of Liability

To the fullest extent permitted by law, the Provider shall not be liable for indirect, incidental, or consequential damages arising from your use of the Service.

## 12. Changes

We may update these Terms from time to time. If material changes are made, we will notify users. Continued use of the Service after updates constitutes acceptance of the new Terms.

## 13. Governing Law

These Terms shall be governed by and construed in accordance with the laws of the Republic of Serbia, without regard to its conflict of law provisions.

## 14. On-Premises Installations

The Provider may offer downloadable or on-premises versions of the Service ("On-Prem Versions") under separate license terms.

These On-Prem Versions are not governed by this Terms of Service.  
Instead, they are subject to the applicable **End-User License Agreement** or **Subscription Agreement** provided at the time of installation or purchase.

If you are using an On-Prem Version, please refer to the accompanying license file or documentation for applicable terms.

## 15. Contact

If you have any questions or concerns, contact us at:

**Sergei Fedorov pr Računarsko programiranje cpp Beograd**  
Email: [sergei@slugkit.dev]  


---

# SlugKit Preview and Development Environments – Terms of Service
Source: https://dev.slugkit.dev/docs/tos-dev-2025-07

# SlugKit Preview and Development Environments – Terms of Service

**Effective Date:** July 5, 2025  
**Version:** dev-2025-07

These Terms of Service ("Terms") govern your use of **non-production environments** of the SlugKit service, including but not limited to development, beta, staging, or preview deployments ("Development Environments"), operated by **Sergei Fedorov pr Računarsko programiranje Beograd** ("Provider").

By using a Development Environment, you agree to be bound by these Terms.

## 1. Scope and Purpose

Development Environments are provided for **testing, development, and evaluation purposes only**. They are not intended for production use and may differ in functionality, stability, and availability from the Provider’s production systems.

## 2. No Service-Level Agreement (SLA)

Development Environments are offered **without any guarantee** of:
- Uptime or availability
- Performance or latency
- Data persistence or integrity
- Feature completeness

The Provider may add, remove, or modify features or behavior at any time **without notice**.

## 3. Payment Prohibited

You must **not attempt to make any payments, purchases, or financial transactions** in or through any Development Environment.

Any payment submitted in a Development Environment is considered invalid and **non-refundable**.

## 4. No Support or Warranty

Development Environments are provided **"as is"**, with **no warranties**, express or implied. The Provider disclaims any liability for damages resulting from the use or misuse of these environments.

## 5. Data Loss and Instability

You acknowledge that:
- Your data in Development Environments may be modified or deleted at any time.
- The system may be reset or redeployed with or without notice.
- Generated Slugs may not be unique, stable, or persistent.

## 6. Acceptable Use

You agree not to:
- Rely on the output or behavior of Development Environments for business-critical use
- Circumvent rate limits, quota checks, or sandbox restrictions
- Attempt to reverse-engineer, scrape, or exploit Development Environments in any way

## 7. Changes

These Terms may be updated at any time. Continued use of a Development Environment after changes are posted constitutes your acceptance of the updated Terms.

## 8. Governing Law

These Terms shall be governed by the laws of the Republic of Serbia, without regard to its conflict of law principles.

---

**By using a Development Environment, you acknowledge that you have read, understood, and agreed to these Terms.**

---

# P####R0: `string_markup` - Move-Safe String Component References
Source: https://dev.slugkit.dev/docs/trained-molle-cdi

> This is a mock proposal. Or is it? [Jump to code](#proof-of-concept)

<script src="https://gist.github.com/zmij/415056de7d4b25125fb64470499a239c.js"></script>

# P####R0: `string_markup` - Move-Safe String Component References

**Document number:** P####R0  
**Date:** 2025-10-16  
**Project:** Programming Language C++  
**Audience:** LEWG, LWG  
**Reply-to:** Sergei Fedorov <sergei@slugkit.dev>

## I. Abstract

We propose `std::string_markup`, a lightweight vocabulary type for referring to substrings within owned strings while maintaining value semantics and move safety. This solves a common antipattern where `std::string_view` members create dangling references after move operations.

## II. Motivation

### The Problem

Consider a common pattern when parsing structured strings:

```cpp
class LanguageCode {
    std::string code_;           // "en-US"
    std::string_view language_;  // Points to "en"
    std::string_view region_;    // Points to "US"
};
```

**This code has undefined behavior on move:**

```cpp
LanguageCode lang1("en-US");
LanguageCode lang2 = std::move(lang1);  // 💥 DANGLING!
// lang2.language_ still points to lang1.code_'s old buffer
```

### Current Workarounds

**Option 1: Manual reconstruction (error-prone)**

```cpp
LanguageCode(LanguageCode&& other) noexcept {
    auto lang_offset = other.language_.data() - other.code_.data();
    auto lang_size = other.language_.size();
    
    code_ = std::move(other.code_);
    language_ = std::string_view(code_.data() + lang_offset, lang_size);
    // Repeat for all components... (~90 lines)
}
```

**Option 2: Store offsets manually (verbose)**

```cpp
std::string code_;
size_t language_offset_;
size_t language_size_;
// Reconstruct view each time
```

**Option 3: Store strings (wasteful)**

```cpp
std::string code_;        // "en-US"
std::string language_;    // "en" (duplicate!)
std::string region_;      // "US" (duplicate!)
```

## III. Proposed Solution

### Design

`string_markup` stores substring position as `(start, size)` offsets, reconstructing `string_view` on demand:

```cpp
template <typename CharT, typename Traits = std::char_traits<CharT>>
class basic_string_markup {
    size_type start_;
    size_type size_;
    
public:
    constexpr basic_string_markup(size_type start, size_type size);
    constexpr basic_string_markup(string_view_type str, string_view_type substr);
    
    [[nodiscard]] constexpr auto value(string_view_type str) const 
        -> string_view_type;
};

using string_markup = basic_string_markup<char>;
```

### Usage

```cpp
class LanguageCode {
    std::string code_;              // Owns data
    string_markup language_;        // (offset, size)
    string_markup region_;          // (offset, size)
    
public:
    LanguageCode(std::string code) : code_(std::move(code)) {
        // Parse and store components
        language_ = string_markup(code_, parse_language());
        region_ = string_markup(code_, parse_region());
    }
    
    // Compiler-generated: perfect! ✅
    LanguageCode(const LanguageCode&) = default;
    LanguageCode(LanguageCode&&) noexcept = default;
    
    auto language() const -> std::string_view {
        return language_.value(code_);  // Reconstruct on demand
    }
};
```

## IV. Design Decisions

### 1. Store Offsets, Not Pointers

**Why:** Enables trivial copy/move semantics. No need to fix up pointers.

```cpp
sizeof(string_markup) = 2 * sizeof(size_t) = 16 bytes
// vs
sizeof(string_view) = sizeof(const char*) + sizeof(size_t) = 16 bytes
```

**Same size, but move-safe!**

### 2. Lazy Reconstruction

**Why:** Most operations don't need the actual `string_view`.

```cpp
auto code = LanguageCode("en-US");
auto code2 = std::move(code);  // No reconstruction needed!

// Only when accessing:
auto lang = code2.language();  // Reconstruct now
```

### 3. Bounds Checking

```cpp
auto value(string_view_type str) const -> string_view_type {
    if (start_ >= str.size()) {
        throw std::out_of_range("string_markup: out of range");
    }
    if (start_ + size_ > str.size()) {
        throw std::out_of_range("string_markup: out of range");
    }
    return {str.data() + start_, size_};
}
```

**Catches misuse:**

```cpp
LanguageCode lang1("en-US");
LanguageCode lang2("fr");
auto view = lang1.language_.value(lang2.code_);  // THROWS! ✅
```

### 4. Constexpr Support

All operations are `constexpr`, enabling compile-time string parsing:

```cpp
constexpr auto parse_language_code() {
    constexpr auto code = std::string_view("en-US");
    constexpr string_markup lang(0, 2);
    return lang.value(code);  // "en"
}
```

## V. Prior Art

### Similar Concepts

1. **Rope data structures** - Store tree of string fragments with offsets
2. **Gapped buffers** - Store positions, reconstruct views
3. **SSO (Small String Optimization)** - Similar technique of storing offsets into owned buffer

### Related Proposals

- **P0009R18 `mdspan`** - Uses `extents` (similar to offsets) for multidimensional indexing
- **P1206R7 `ranges::subrange`** - Iterator pair with similar "reconstruct on demand" semantics

## VI. Technical Specification

```cpp
namespace std {
    template <typename CharT, typename Traits = char_traits<CharT>>
    class basic_string_markup {
    public:
        using string_view_type = basic_string_view<CharT, Traits>;
        using size_type = typename string_view_type::size_type;
        
        // Construction
        constexpr basic_string_markup() noexcept = default;
        constexpr basic_string_markup(size_type start, size_type size);
        constexpr basic_string_markup(string_view_type sv);
        constexpr basic_string_markup(
            string_view_type str, 
            string_view_type substr
        );
        
        // Observers
        [[nodiscard]] constexpr auto start() const noexcept -> size_type;
        [[nodiscard]] constexpr auto size() const noexcept -> size_type;
        [[nodiscard]] constexpr auto empty() const noexcept -> bool;
        
        // Reconstruction
        [[nodiscard]] constexpr auto value(string_view_type str) const 
            -> string_view_type;
        
        // Comparison
        [[nodiscard]] friend constexpr auto operator==(
            const basic_string_markup&,
            const basic_string_markup&
        ) noexcept -> bool = default;
    };
    
    using string_markup = basic_string_markup<char>;
    using wstring_markup = basic_string_markup<wchar_t>;
    using u8string_markup = basic_string_markup<char8_t>;
    using u16string_markup = basic_string_markup<char16_t>;
    using u32string_markup = basic_string_markup<char32_t>;
}
```

## VII. Performance Characteristics

### Space Complexity

```cpp
struct LanguageCode_Before {
    std::string code_;        // 32 bytes (typical)
    std::string_view lang_;   // 16 bytes
    std::string_view region_; // 16 bytes
};  // Total: 64 bytes

struct LanguageCode_After {
    std::string code_;          // 32 bytes
    string_markup lang_;        // 16 bytes
    string_markup region_;      // 16 bytes
};  // Total: 64 bytes ✅ Same!
```

### Time Complexity

| Operation | Before | After |
|-----------|--------|-------|
| Construction | O(n) | O(n) |
| Copy | O(n) + fixup | O(n) ✅ |
| Move | O(1) + fixup | O(1) ✅ |
| Access | O(1) | O(1) + offset ⚠️ |

**Trade-off:** Slightly slower access (pointer arithmetic) for much simpler copy/move.

### Real-World Benchmarks

```cpp
// Benchmark: Parse 1M language codes, move to vector
Before (manual fixup):  1.2s
After (string_markup):  0.8s  ✅ 33% faster!

// Why? Compiler generates optimal code for = default
```

## VIII. Real-World Impact

### Use Cases

1. **URL parsing** - Store path components without allocation
2. **Protocol parsers** - HTTP headers, language codes, MIME types
3. **Lexers/tokenizers** - Store token positions in source
4. **Configuration parsing** - INI sections, YAML keys
5. **Any structured string parsing**

### Production Experience

This design is used in production at SlugKit for:

- BCP 47 language code parsing (`en-US`, `sr-Latn-RS`)
- URL path matching and routing
- Pattern parsing for slug generation

**Results:**

- Eliminated 90+ lines of error-prone copy/move code
- Fixed production segfault on AMD64 (ARM64 was "lucky")
- 100% test coverage with move semantics
- Zero overhead vs manual approach

## IX. Alternative Designs Considered

### A. `string_view` with "parent pointer"

```cpp
class anchored_string_view {
    const std::string* parent_;  // Weak reference
    size_t start_, size_;
};
```

**Rejected:** Dangling pointer risk, not constexpr-friendly, 24 bytes vs 16.

### B. `std::span<char>` with custom deleter

**Rejected:** `span` doesn't own memory, same dangling issues.

### C. `boost::string_ref` with offset

**Rejected:** Boost already has this problem with `string_ref`.

### D. Store `string_view` + validate on access

```cpp
auto value() const -> string_view {
    assert(is_valid(stored_view_));  // How?
    return stored_view_;
}
```

**Rejected:** No way to validate without parent pointer.

## X. Implementation Experience

### Proof of Concept

Full implementation available at: [Gist](https://gist.github.com/zmij/415056de7d4b25125fb64470499a239c)

**Compiler support tested:**

- GCC 13+ ✅
- Clang 16+ ✅
- ARM64 ✅
- AMD64 ✅

**Key findings:**

- Compilers optimize `value()` perfectly (inline + CSE)
- Codegen identical to manual offset calculation
- `constexpr` works in all tested compilers

## XI. Wording

*(Full standard wording omitted for brevity - would be added in final revision)*

## XII. Questions for LEWG

1. **Should this be in `<string_view>` or new header `<string_markup>`?**

2. **Should `value()` be `constexpr` (requires throwing in constexpr)?**

3. **Should we provide `unchecked_value()` for performance-critical code?**

4. **Should there be a `rebind(new_string)` operation?**
   ```cpp
   string_markup m(0, 2);
   auto v1 = m.value("hello");  // "he"
   auto v2 = m.value("world");  // "wo"
   ```

5. **Should we support negative offsets (from end)?**
   ```cpp
   string_markup m(-2, 2);  // Last 2 chars
   ```

## XIII. Acknowledgments

Thanks to the Belgrade C++ User Group for rubber-duck debugging sessions, and to Claude (Anthropic) for late-night architecture discussions that led to this design being conceived at 03:45 AM and implemented over morning coffee.

Special thanks to the C++ community for 40+ years of struggling with string lifetime issues - this proposal wouldn't exist without that shared pain.

## XIV. References

1. **CppReference `string_view`:** https://en.cppreference.com/w/cpp/string/basic_string_view
2. **P0009R18 `mdspan`:** https://wg21.link/p0009r18
3. **BCP 47 Language Tags:** https://www.rfc-editor.org/rfc/rfc5646
4. **Production implementation:** https://github.com/slugkit/slugkit/common/utils/string_markup.hpp

## Appendix A: Before/After Comparison

### Before: Manual Copy/Move (~90 lines)

```cpp
LanguageCode::LanguageCode(LanguageCode&& other) noexcept {
    auto lang_offset = other.language_.data() - other.code_.data();
    auto lang_size = other.language_.size();
    auto region_offset = other.region_.data() - other.code_.data();
    auto region_size = other.region_.size();
    auto script_offset = other.script_.data() - other.code_.data();
    auto script_size = other.script_.size();
    auto variant_offset = other.variant_.data() - other.code_.data();
    auto variant_size = other.variant_.size();
    
    code_ = std::move(other.code_);
    
    language_ = string_view(code_.data() + lang_offset, lang_size);
    region_ = string_view(code_.data() + region_offset, region_size);
    script_ = string_view(code_.data() + script_offset, script_size);
    variant_ = string_view(code_.data() + variant_offset, variant_size);
}

// + Similar for copy constructor
// + Similar for copy assignment  
// + Similar for move assignment
```

### After: With `string_markup`

```cpp
LanguageCode(const LanguageCode&) noexcept = default;
LanguageCode(LanguageCode&&) noexcept = default;
auto operator=(const LanguageCode&) noexcept -> LanguageCode& = default;
auto operator=(LanguageCode&&) noexcept -> LanguageCode& = default;
```

**Code reduction: 90 lines → 4 lines**

## Appendix B: Constexpr Example

```cpp
constexpr auto parse_at_compile_time() {
    constexpr auto code = std::string_view("en-Latn-US");
    constexpr string_markup language(0, 2);
    constexpr string_markup script(3, 4);
    constexpr string_markup region(8, 2);
    
    static_assert(language.value(code) == "en");
    static_assert(script.value(code) == "Latn");
    static_assert(region.value(code) == "US");
    
    return true;
}

static_assert(parse_at_compile_time());
```

---

**END OF PROPOSAL**

---

# API Debugging Guide
Source: https://dev.slugkit.dev/docs/troubleshooting-api-debugging

# API Debugging Guide

Debug SlugKit API calls effectively with request inspection, response analysis, and systematic troubleshooting techniques.

## API Debugging Toolkit

### Essential Tools

1. **curl** - Command-line HTTP client
2. **jq** - JSON processor for parsing responses
3. **httpie** - User-friendly HTTP client
4. **Postman** - GUI API testing tool

### Basic Request Template

```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}' \
  -v  # Verbose output for debugging
```

## Inspecting Requests

### Verbose Output

```bash
# Add -v flag for full request/response details
curl -v -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 3}'
```

**Output includes:**
```
> POST /api/forge HTTP/2
> Host: api.slugkit.dev
> User-Agent: curl/7.81.0
> Accept: */*
> x-api-key: sk_api_***
> Content-Type: application/json
> Content-Length: 52
>
< HTTP/2 200
< content-type: application/json
< content-length: 123
< x-request-id: req_abc123xyz
< x-ratelimit-remaining: 99
<
{"slugs": ["accurate-head", "lunatic-corer", "marauding-obliviousness"]}
```

### Custom Headers

```bash
# Add request ID for tracking
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -H "X-Request-ID: debug-session-001" \
  -d '{"series": "test", "count": 5}'
```

### Timing Information

```bash
# Measure request timing
curl -w "\nTime: %{time_total}s\n" \
  -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 10}'
```

**Detailed timing breakdown:**
```bash
# Create timing format file
cat > curl-timing.txt << 'EOF'
    time_namelookup:  %{time_namelookup}s\n
       time_connect:  %{time_connect}s\n
    time_appconnect:  %{time_appconnect}s\n
   time_pretransfer:  %{time_pretransfer}s\n
      time_redirect:  %{time_redirect}s\n
 time_starttransfer:  %{time_starttransfer}s\n
                    ----------\n
         time_total:  %{time_total}s\n
EOF

# Use timing format
curl -w "@curl-timing.txt" -o /dev/null -s \
  -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 100}'
```

## Response Analysis

### Status Code Inspection

```bash
# Get HTTP status code only
curl -s -o /dev/null -w "%{http_code}" \
  -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'

# Output: 200
```

### Response Headers

```bash
# View headers only
curl -I -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

**Important headers:**
```
HTTP/2 200
content-type: application/json
x-request-id: req_abc123xyz
x-ratelimit-limit: 100
x-ratelimit-remaining: 95
x-ratelimit-reset: 1696348800
```

### JSON Response Parsing

```bash
# Pretty print JSON with jq
curl -s -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 3}' | jq '.'

# Extract specific fields
curl -s -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 3}' | jq '.slugs[]'

# Output:
# "accurate-head"
# "lunatic-corer"
# "marauding-obliviousness"
```

## Common Debugging Scenarios

### Scenario 1: "Request works in curl, fails in code"

**Problem:** API call succeeds with curl but fails in application code.

**Debug Steps:**

1. **Compare headers exactly:**
```bash
# Capture exact curl headers
curl -v -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 3}' 2>&1 | grep ">"
```

2. **Check application request:**
```python
import requests
import logging

# Enable request logging
logging.basicConfig(level=logging.DEBUG)

response = requests.post(
    'https://api.slugkit.dev/api/v1/gen/forge',
    headers={
        'x-api-key': 'sk_api_your_key',
        'Content-Type': 'application/json'
    },
    json={'pattern': '{adjective}-{noun}', 'count': 3}
)
```

3. **Common differences:**
   - Missing `Content-Type: application/json` header
   - Wrong x-api-key header format
   - JSON serialization differences
   - Character encoding issues

### Scenario 2: "API returns unexpected results"

**Problem:** Generated slugs don't match expectations.

**Debug Steps:**

1. **Validate pattern first:**
```bash
# Test pattern validation
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{your-pattern}"}' | jq '.'
```

2. **Generate multiple samples:**
```bash
# Generate several batches to check consistency
for i in {1..5}; do
  echo "Batch $i:"
  curl -s -X POST https://api.slugkit.dev/api/v1/gen/forge \
    -H "x-api-key: sk_api_your_key" \
    -H "Content-Type: application/json" \
    -d '{"pattern": "{adjective:+pos}-{noun}", "count": 3}' | jq '.slugs'
done
```

3. **Check pattern components:**
```bash
# Validate pattern structure
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective:+pos}-{noun}"}' | jq '.selectors'

# Output shows applied filters:
# [
#   {"original_size": 17082, "selected_size": 710},  # +pos filtered adjectives
#   {"original_size": 41469, "selected_size": 41469}  # all nouns
# ]
```

### Scenario 3: "Intermittent failures"

**Problem:** API calls succeed sometimes, fail other times.

**Debug Steps:**

1. **Check rate limiting:**
```bash
# Monitor rate limit headers
curl -i -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}' | grep -i ratelimit

# Look for:
# x-ratelimit-remaining: 0  # ← Hitting limit
```

2. **Test with retry logic:**
```python
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# Configure retry with backoff
session = requests.Session()
retry = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[429, 500, 502, 503, 504]
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('https://', adapter)

# This will auto-retry on failures
response = session.post(
    'https://api.slugkit.dev/api/v1/gen/forge',
    headers={'x-api-key': 'sk_api_your_key'},
    json={'pattern': '{adjective}-{noun}', 'count': 5}
)
```

3. **Log request IDs:**
```bash
# Extract request ID from responses
curl -i -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}' | grep x-request-id

# Save request IDs for support investigation
```

### Scenario 4: "Series operations fail"

**Problem:** Mint or slice operations return 404 or unexpected results.

**Debug Steps:**

1. **Verify series exists:**
```bash
# List all series
curl -s https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: sk_api_your_key" | jq '.series[].slug'
```

2. **Check series configuration:**
```bash
# Get specific series details
curl -s https://api.slugkit.dev/api/v1/gen/series/your-series-slug \
  -H "x-api-key: sk_api_your_key" | jq '.'

# Verify:
# - Pattern is what you expect
# - Series is active
# - Counter position
```

3. **Test series operations in order:**
```bash
# 1. Create series
curl -X POST https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "slug": "debug-series",
    "pattern": "{adjective}-{noun}",
    "description": "Debug test series"
  }'

# 2. Slice (preview, doesn't increment counter)
curl -X POST https://api.slugkit.dev/api/v1/gen/slice \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"series": "debug-series", "start": 0, "count": 5}'

# 3. Mint (increments counter)
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"series": "debug-series", "count": 5}'

# 4. Check updated counter
curl -s https://api.slugkit.dev/api/v1/gen/series/debug-series \
  -H "x-api-key: sk_api_your_key" | jq '.counter'
```

## API Authentication Debugging

### Verify API Key Format

```bash
# API key should start with sk_api_ or sk_sdk_
echo "sk_api_abc123xyz..." | grep -E '^sk_(api|sdk)_'
```

### Test API Key Validity

```bash
# Simple auth test
curl -s -o /dev/null -w "%{http_code}" \
  https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: sk_api_your_key"

# 200 = Valid
# 401 = Invalid/expired key
```

### Check API Key Scopes

```bash
# Get key information
curl -s https://api.slugkit.dev/api/keys/current \
  -H "x-api-key: sk_api_your_key" | jq '.scopes'

# Example output:
# [
#   "forge:write",
#   "mint:write",
#   "slice:read",
#   "series:write",
#   "series:read"
# ]
```

### Test Specific Scope

```bash
# Try operation that requires specific scope
curl -s -o /dev/null -w "%{http_code}" \
  -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 1}'

# 200 = Has forge:write scope
# 403 = Missing required scope
```

## Request/Response Logging

### Full Request/Response Capture

```bash
# Save complete interaction to file
curl -v -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 3}' \
  > response.json 2> request.log

# request.log contains headers and timing
# response.json contains response body
```

### Python Request Logging

```python
import requests
import logging
from http.client import HTTPConnection

# Enable debug logging
HTTPConnection.debuglevel = 1

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

# Make request - will log everything
response = requests.post(
    'https://api.slugkit.dev/api/v1/gen/forge',
    headers={
        'x-api-key': 'sk_api_your_key',
        'Content-Type': 'application/json'
    },
    json={'pattern': '{adjective}-{noun}', 'count': 3}
)
```

### Node.js Request Logging

```javascript
const axios = require('axios');

// Configure request interceptor
axios.interceptors.request.use(request => {
  console.log('Starting Request:', {
    method: request.method,
    url: request.url,
    headers: request.headers,
    data: request.data
  });
  return request;
});

// Configure response interceptor
axios.interceptors.response.use(response => {
  console.log('Response:', {
    status: response.status,
    headers: response.headers,
    data: response.data
  });
  return response;
});

// Make request
axios.post('https://api.slugkit.dev/api/v1/gen/forge', {
  pattern: '{adjective}-{noun}',
  count: 3
}, {
  headers: {
    'x-api-key': 'sk_api_your_key',
    'Content-Type': 'application/json'
  }
});
```

## Testing Different Endpoints

### Validate Endpoint

```bash
# Test pattern validation
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective:+pos}-{noun:<10}"}' | jq '.'

# Response:
# {
#   "pattern": "{adjective:+pos}-{noun:<10}",
#   "capacity": "6203790",
#   "max_slug_length": 19,
#   "complexity": 14,
#   "components": 2,
#   "selectors": [...]
# }
```

### Forge Endpoint

```bash
# Test slug generation
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective:+pos}-{noun}",
    "count": 5,
    "seed": "test-seed"
  }' | jq '.'

# Response:
# {
#   "slugs": ["engaging-...", "pivotal-...", ...]
# }
```

### Mint Endpoint

```bash
# Test series-based generation
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "series": "test-series",
    "count": 5
  }' | jq '.'
```

### Slice Endpoint

```bash
# Test series preview
curl -X POST https://api.slugkit.dev/api/v1/gen/slice \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "series": "test-series",
    "start": 0,
    "count": 10
  }' | jq '.'
```

### Series Management Endpoints

```bash
# List series
curl https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: sk_api_your_key" | jq '.'

# Get specific series
curl https://api.slugkit.dev/api/v1/gen/series/my-series \
  -H "x-api-key: sk_api_your_key" | jq '.'

# Create series
curl -X POST https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "slug": "new-series",
    "pattern": "{adjective}-{noun}",
    "description": "Test series"
  }' | jq '.'

# Update series
curl -X PATCH https://api.slugkit.dev/api/v1/gen/series/my-series \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"description": "Updated description"}' | jq '.'

# Delete series
curl -X DELETE https://api.slugkit.dev/api/v1/gen/series/test-series \
  -H "x-api-key: sk_api_your_key"
```

## Debugging Checklist

Before contacting support, verify:

- [ ] API key is valid and not expired
- [ ] API key has required scopes for operation
- [ ] x-api-key header is correct: `sk_api_...`
- [ ] Content-Type header is set: `application/json`
- [ ] Request JSON is valid (test with `jq`)
- [ ] Pattern syntax is valid (test with `/validate`)
- [ ] Series exists (for mint/slice operations)
- [ ] Rate limits not exceeded (check `x-ratelimit-remaining`)
- [ ] Request times out > 5 seconds (network/timeout issue)
- [ ] Error is reproducible with curl
- [ ] Request ID captured for support

## Debugging Tools Reference

### curl Useful Flags

```bash
-v              # Verbose output (headers + timing)
-i              # Include response headers in output
-I              # Headers only (no body)
-s              # Silent (no progress bar)
-o <file>       # Save response body to file
-w <format>     # Custom output format
-H <header>     # Add request header
-d <data>       # Request body
-X <method>     # HTTP method
--compressed    # Request compressed response
```

### jq Useful Filters

```bash
jq '.'              # Pretty print JSON
jq '.slugs'         # Extract slugs array
jq '.slugs[]'       # Extract each slug
jq '.slugs | length'  # Count slugs
jq '.selectors[0].selected_size'  # Specific field
jq -r '.slugs[]'    # Raw output (no quotes)
```

### HTTPie Alternative

```bash
# More user-friendly than curl
http POST https://api.slugkit.dev/api/v1/gen/forge \
  x-api-key:sk_api_your_key \
  pattern="{adjective}-{noun}" \
  count:=5
```

## Support Information

When reporting API issues, include:

1. **Complete curl command** (with key redacted)
2. **Full response** (including headers)
3. **Request ID** (from `x-request-id` header)
4. **Timestamp** of failure
5. **Subscription tier**
6. **Frequency** of issue (one-time, intermittent, consistent)

**Contact:** support@slugkit.dev

---

# Common Errors and Solutions
Source: https://dev.slugkit.dev/docs/troubleshooting-common-errors

# Common Errors and Solutions

Solve frequent SlugKit pattern and API issues quickly with practical solutions and working examples.

## Pattern Parse Errors

### Error: "Expected `}` at column X"

**Symptom:**
```
Pattern validation failed: Pattern parse error: expected `}` at column 10, got `<`
```

**Cause:** Invalid constraint syntax. Length constraints must use `:` prefix, not direct comparison operators.

**❌ Invalid Syntax:**
```
{adjective<8}-{noun>5}
```

**✅ Correct Syntax:**
```
{adjective:<8}-{noun:>5}
```

**Example Output:**
```
burred-abettal
faddy-abfarad
joint-ability
```

**Common Variations:**
- `{word<10}` → `{word:<10}` (less than)
- `{word>5}` → `{word:>5}` (greater than)
- `{word==7}` → `{word:==7}` (exactly)

### Error: "No matching words found"

**Symptom:**
```
Pattern validation failed: No matching words found for: adjective:+tech
```

**Cause:** Referenced tag doesn't exist for the dictionary type.

**Debug Steps:**

1. **Check tag availability:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: sk_api_your_key" \
  -d '{"pattern": "{adjective:+tech}-{noun}"}'
```

2. **List available tags:**
```bash
# Check what tags exist for adjectives
curl https://api.slugkit.dev/api/v1/gen/dictionary-tags?kind=adjective \
  -H "x-api-key: sk_api_your_key"
```

**Available adjective tags:**
- `+pos` - Positive words (710 words)
- `+neg` - Negative words (1,395 words)
- `+emo` - Emotional words (2,944 words)
- `+neut` - Neutral words (6,595 words)
- `+obj` - Objective words (8,382 words)
- `+det` - Detached words (14,138 words)

**❌ Non-existent tag:**
```
{adjective:+tech}-{noun}
```

**✅ Use valid tags:**
```
{adjective:+pos}-{noun}
```

**Example Output:**
```
engaging-spermatozoon
pivotal-plugboard
animating-lotusland
```

**Capacity:** ~29.4 million unique combinations

### Error: "Contradictory tag combination"

**Symptom:**
```
Pattern validation failed: No matching words found for: adjective:+pos+neg
```

**Cause:** Mutually exclusive tags combined (word can't be both positive AND negative).

**❌ Contradictory tags:**
```
{adjective:+pos+neg}-{noun}        # Can't be positive AND negative
{adjective:+emo+det}-{noun}        # Can't be emotional AND detached
```

**✅ Compatible tags:**
```
{adjective:+pos+emo}-{noun}        # Positive emotional words
{adjective:+neg-nsfw}-{noun}       # Negative, excluding NSFW
{adjective:+obj+det}-{noun}        # Objective detached words
```

### Error: "Pattern too complex"

**Symptom:**
```
Pattern validation failed: Pattern exceeds maximum complexity
```

**Cause:** Pattern has too many placeholders or nested global modifiers.

**Maximum Limits:**
- 20 placeholders per pattern
- 1 global modifier block
- 100 characters per placeholder

**❌ Too complex:**
```
{adj}-{noun}-{verb}-{adv}-{adj}-{noun}-{verb}-{adv}-{adj}-{noun}-{verb}-{adv}-{adj}-{noun}-{verb}-{adv}-{adj}-{noun}-{verb}-{adv}-{adj}
```

**✅ Simplified:**
```
{adjective}-{noun}-{number:3x}
```

**Solution:** Break complex patterns into multiple generation calls or simplify pattern structure.

## API Errors

### 401 Unauthorized

**Symptom:**
```json
{
  "error": "Unauthorized",
  "message": "Invalid or missing API key"
}
```

**Common Causes:**

1. **Missing Authorization header:**
```bash
# ❌ Missing header
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

```bash
# ✅ Include Authorization
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key_here" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

2. **Wrong header format:**
```bash
# ❌ Incorrect formats
-H "Authorization: sk_api_your_key"           # Missing x-api-key header
-H "x-api-key=sk_api_your_key"              # Wrong separator (use : not =)
-H "X-API-Key: sk_api_your_key"              # Wrong header name
```

3. **Expired or revoked key:**
- Check key status in dashboard
- Generate new API key if necessary
- Ensure key has required scopes

### 403 Forbidden - Insufficient Permissions

**Symptom:**
```json
{
  "error": "Forbidden",
  "message": "missing required scope forge"
}
```

**Cause:** API key doesn't have permission for the requested operation.

**Required Scopes:**
- `forge` - Generate slugs with forge method
- `mint` - Generate slugs with mint method
- `slice` - Preview slugs with slice method
- `series:create`, `series:update`, `series:delete` - Manage series
- `series:read` - List and view series

**Solution:**
1. Go to SlugKit dashboard
2. Navigate to API Keys
3. Edit key or create new key with required scopes
4. Update your application with new key

### 400 Bad Request - Invalid Pattern

**Symptom:**
```json
{
  "error": "Bad Request",
  "message": "Pattern validation failed",
  "details": "Invalid pattern syntax"
}
```

**Debug Checklist:**

1. **Validate pattern syntax locally:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{your-pattern}"}'
```

2. **Check for common syntax errors:**
- Mismatched braces: `{adjective-{noun}}`
- Invalid characters: `{adjective}-{noun!}`
- Wrong constraint syntax: `{noun<5}` instead of `{noun:<5}`
- Non-existent tags: `{adjective:+tech}`

3. **Verify JSON formatting:**
```bash
# ❌ Invalid JSON
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -d '{pattern: "{adjective}-{noun}"}'

# ✅ Valid JSON
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

### 429 Too Many Requests

**Symptom:**
```json
{
  "error": "Too Many Requests",
  "message": "Rate limit exceeded",
  "retry_after": 30
}
```

**Cause:** Exceeded API rate limits for your subscription tier.

**Rate Limits by Plan:**
- **Free:** 10 req/min sustained, 100 req/min burst
- **Developer:** 100 req/min sustained, 1,000 req/min burst
- **Startup:** 200 req/min sustained, 2,000 req/min burst
- **Business:** 500 req/min sustained, 5,000 req/min burst

**Solutions:**

1. **Implement exponential backoff:**
```python
import time
import requests

def generate_slugs_with_retry(pattern, count, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(
            'https://api.slugkit.dev/api/v1/gen/forge',
            headers={'x-api-key': 'sk_api_your_key'},
            json={'pattern': pattern, 'count': count}
        )

        if response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 60))
            time.sleep(retry_after)
            continue

        return response.json()

    raise Exception("Max retries exceeded")
```

2. **Batch requests efficiently:**
```bash
# ❌ Many small requests
for i in {1..100}; do
  curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
    -H "x-api-key: sk_api_your_key" \
    -d '{"series": "user-handles", "count": 1}'
done

# ✅ Single batched request
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -H "x-api-key: sk_api_your_key" \
  -d '{"series": "user-handles", "count": 100}'
```

3. **Use slice for previews:**
```bash
# Don't waste mint quota on testing
curl -X POST https://api.slugkit.dev/api/v1/gen/slice \
  -H "x-api-key: sk_api_your_key" \
  -d '{"series": "user-handles", "start": 0, "count": 100}'
```

### 404 Not Found - Series Does Not Exist

**Symptom:**
```json
{
  "error": "Not Found",
  "message": "Series 'my-series' does not exist"
}
```

**Cause:** Referenced series hasn't been created yet.

**Solution:**

1. **Create series first:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "slug": "my-series",
    "pattern": "{adjective}-{noun}",
    "description": "User handle generation"
  }'
```

2. **Then use in mint/slice operations:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -H "x-api-key: sk_api_your_key" \
  -d '{"series": "my-series", "count": 10}'
```

3. **List existing series:**
```bash
curl https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: sk_api_your_key"
```

## Pattern Issues

### Pattern Generates Undesirable Output

**Symptom:** Generated slugs don't match expectations or include inappropriate words.

**Solutions:**

1. **Use tag filtering:**
```bash
# Basic pattern (may include negative words)
{adjective}-{noun}

# Filtered for positive sentiment
{adjective:+pos}-{noun}

# Exclude NSFW content (opt-in tag, excluded by default)
{adjective-nsfw}-{noun}

# Combine filters
{adjective:+pos+emo-neg}-{noun}
```

2. **Apply length constraints:**
```bash
# May generate very long slugs
{adjective}-{noun}

# Constrain for URLs
{adjective:<8}-{noun:<10}
```

3. **Control case for branding:**
```bash
# Mixed case for readability
{Adjective}-{Noun}

# All caps for product codes
{ADJECTIVE}-{NOUN}-{number:3X}

# Mathematical case pattern
{AdJeCtIvE}-{NoUn}
```

### Pattern Has Too Little Capacity

**Symptom:**
```
Warning: Pattern capacity (1,250) may be insufficient for production use
```

**Cause:** Overly restrictive constraints reduce available combinations.

**Debug:**
```bash
# Check pattern capacity
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: sk_api_your_key" \
  -d '{"pattern": "{adjective:+pos<5}-{noun:<5}"}'

# Response shows capacity: ~3,500 combinations
```

**Solutions:**

1. **Relax length constraints:**
```bash
# Too restrictive (~3,500 combinations)
{adjective:+pos<5}-{noun:<5}

# Better capacity (~2.4 million combinations)
{adjective:+pos<8}-{noun:<8}
```

2. **Add more components:**
```bash
# Low capacity
{adjective:+pos<6}-{noun:<6}

# Higher capacity with number suffix
{adjective:+pos<6}-{noun:<6}-{number:2x}
# Multiplies capacity by 256
```

3. **Use fewer tag filters:**
```bash
# Very restrictive
{adjective:+pos+emo<6}-{noun:+person<6}

# More permissive
{adjective:+pos}-{noun}
```

### Pattern Generates Invalid Identifiers

**Symptom:** Slugs contain characters invalid for your use case (URLs, filenames, etc.).

**Solution: Use global modifiers for transformation:**

```bash
# Generate pattern with global settings
{adjective}-{noun}[@en:case=lower]

# Available global modifiers:
# case=lower    - Force lowercase
# case=upper    - Force uppercase
# case=title    - Title Case
# lang=en       - English only (default)
```

**For URL-safe slugs:** SlugKit generates URL-safe slugs by default (no spaces, special chars).

## Common Mistakes

### Using Wrong Generation Method

**Mistake:** Using forge when you need guaranteed uniqueness.

**❌ Not guaranteed unique:**
```bash
# Multiple calls may generate duplicates
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -d '{"pattern": "{adjective}-{noun}", "count": 100}'

curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -d '{"pattern": "{adjective}-{noun}", "count": 100}'
# May have overlapping slugs
```

**✅ Guaranteed unique with mint:**
```bash
# Create series once
curl -X POST https://api.slugkit.dev/api/v1/gen/series \
  -d '{"slug": "user-ids", "pattern": "{adjective}-{noun}"}'

# Mint always unique within series
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -d '{"series": "user-ids", "count": 100}'
```

**When to use each:**
- **Forge:** Themed campaigns, reproducible generation, testing
- **Mint:** User IDs, database keys, production identifiers
- **Slice:** Previews, coordination, testing

### Forgetting Content-Type Header

**Symptom:** API returns HTML error page instead of JSON.

**❌ Missing Content-Type:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -d '{"pattern": "{adjective}-{noun}"}'
```

**✅ Include Content-Type:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective}-{noun}", "count": 5}'
```

### Not Validating Patterns Before Production

**Mistake:** Deploying patterns without testing capacity and output.

**✅ Pre-deployment checklist:**

1. **Validate syntax:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: sk_api_your_key" \
  -d '{"pattern": "{your-pattern}"}'
```

2. **Generate samples:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -d '{"pattern": "{your-pattern}", "count": 20}'
```

3. **Check capacity:**
```bash
# Ensure capacity > 10x expected usage
# For 1M users, need > 10M capacity
```

4. **Test edge cases:**
```bash
# Generate multiple batches to check variety
for i in {1..5}; do
  curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
    -d '{"pattern": "{your-pattern}", "count": 10}'
done
```

## Quick Reference: Error Code Guide

| Status | Error | Common Cause | Quick Fix |
|--------|-------|--------------|-----------|
| 400 | Bad Request | Invalid pattern syntax | Validate pattern with `/pattern-info` |
| 401 | Unauthorized | Missing/invalid API key | Check x-api-key header |
| 403 | Forbidden | Insufficient scopes | Update API key permissions |
| 404 | Not Found | Series doesn't exist | Create series first |
| 429 | Too Many Requests | Rate limit exceeded | Implement backoff, batch requests |
| 500 | Internal Server Error | Server issue | Retry with exponential backoff |

## Getting More Help

If these solutions don't resolve your issue:

1. **Check API status:** https://status.slugkit.dev
2. **Review documentation:** https://docs.slugkit.dev
3. **Contact support:** support@slugkit.dev (include pattern and error message)
4. **Community forums:** https://community.slugkit.dev

**Include in support requests:**
- Exact pattern that's failing
- Complete error message
- API endpoint being used
- Subscription tier
- Timestamp of error


---

# Performance Troubleshooting
Source: https://dev.slugkit.dev/docs/troubleshooting-performance

# Performance Troubleshooting

Diagnose and resolve SlugKit performance issues, optimize pattern efficiency, and scale slug generation for high-traffic applications.

## Understanding SlugKit Performance

### Baseline Performance Characteristics

**Server-Side Generation Speed:**
- **Core generation:** ~2-3 microseconds per slug (measured at 1M batch size)
- **Pattern independent:** Mint and Forge have similar server-side performance (~2-3µs/slug)
- **Small batches (< 1K):** Network overhead dominates, use JSON API
- **Large batches (> 1K):** Use streaming API for progressive processing

**API Types:**

**JSON API** (batches ≤ 1,000 slugs):
- Returns complete array after full generation + serialization
- Best for small-medium batches
- Time to first result: Proportional to batch size
- Subscription limits: max ~1,000 slugs per request

**Streaming API** (batches > 1,000 slugs):
- Streams slugs as newline-delimited text as they're generated
- Eliminates JSON serialization wait
- Time to first result: **~180ms regardless of batch size**
- Progressive processing: Start consuming slugs immediately
- Memory efficient: Process line-by-line
- Recommended for all batches > 1K

**Total Request Time Includes:**
1. DNS lookup (~10-15ms)
2. TLS handshake (~40-100ms)
3. Network round-trip
4. JSON serialization (JSON API only)
5. Actual slug generation (~2-3µs per slug)

**Key Insight - Streaming Advantage:**
- **JSON API:** Must wait for all slugs to generate + serialize before receiving first result
- **Streaming API:** First slug arrives in ~180ms, then continuous stream
- For 1M slugs: JSON takes 1.2s before first byte, streaming takes 0.18s

**Factors Affecting Performance:**
1. **API choice** - Streaming for batches > 1K (6x faster time-to-first-byte)
2. **Batch size** - Larger batches amortize network overhead
3. **Network latency** - Geographic proximity to API
4. **TLS handshake** - First request in connection
5. **Pattern complexity** - Minimal impact on modern hardware
6. **Connection reuse** - Persistent connections avoid handshake

### Expected Response Times (Real Benchmarks)

Based on actual measurements against `https://dev.slugkit.dev`:

**Small-Medium Batches - JSON API (≤ 1,000 slugs):**

| Operation | Batch Size | Total Time | Time to First Byte | Per-Slug | Throughput |
|-----------|------------|------------|--------------------|----------|------------|
| Mint | 1 slug | ~180-340ms | ~180ms | 225ms | 4.4 slugs/s |
| Mint | 10 slugs | ~187-383ms | ~200ms | 25ms | 39.5 slugs/s |
| Mint | 100 slugs | ~180-195ms | ~180ms | 1.9ms | 535 slugs/s |
| Mint | 1,000 slugs | ~229-455ms | ~250ms | 0.3ms | 3,582 slugs/s |
| Forge | 1 slug | ~167-663ms | ~180ms | 278ms | 3.6 slugs/s |
| Forge | 100 slugs | ~169-209ms | ~180ms | 1.9ms | 540 slugs/s |
| Forge | 1,000 slugs | ~210-376ms | ~230ms | 0.3ms | 3,815 slugs/s |

**Large Batches - Streaming API (> 1,000 slugs):**

| Operation | Batch Size | Total Time | Time to First Slug | Per-Slug | Throughput |
|-----------|------------|------------|--------------------|----------|------------|
| Mint | 10,000 | 0.33s | **0.18s** | 33µs | 30,500 slugs/s |
| Mint | 100,000 | 0.81s | **0.18s** | 8.1µs | 124,000 slugs/s |
| Mint | 500,000 | 1.81s | **0.18s** | 3.6µs | 277,000 slugs/s |
| Mint | 1,000,000 | 2.27s | **0.18s** | 2.3µs | 441,000 slugs/s |
| Forge | 10,000 | 0.34s | **0.18s** | 34µs | 29,400 slugs/s |
| Forge | 100,000 | 0.49s | **0.18s** | 4.9µs | 205,000 slugs/s |
| Forge | 500,000 | 1.87s | **0.18s** | 3.7µs | 268,000 slugs/s |
| Forge | 1,000,000 | 3.28s | **0.18s** | 3.3µs | 305,000 slugs/s |

**Comparison: JSON vs Streaming (1M slugs):**

| Metric | Mint JSON | Mint Stream | Forge JSON | Forge Stream |
|--------|-----------|-------------|------------|--------------|
| Time to first byte | 1.21s | **0.18s** | 1.33s | **0.18s** |
| Total time | 2.21s | 2.27s | 2.37s | 3.28s |
| **Advantage** | - | **6.7x faster start** | - | **7.4x faster start** |

**Timing Breakdown (100 slugs):**
- DNS lookup: 11ms
- TCP connect: 52ms
- TLS handshake: 47ms
- Server processing: 85ms (includes generation + serialization)
- Total: 185ms

**Key Takeaways:**
- **Network overhead:** ~160-170ms per request (DNS + TLS + TCP)
- **True server performance:** 2-3µs per slug (visible at 1M batch size)
- **Streaming advantage:** First slug in 180ms vs 1200ms (6-7x faster)
- **Use JSON API for:** Batches ≤ 1,000 slugs (subscription limit)
- **Use Streaming API for:** Batches > 1,000 slugs (progressive processing)
- **Large batch throughput:** 300-440K slugs/s with streaming
- **Practical recommendations:**
  - Small batches (< 1K): JSON API
  - Medium batches (1-10K): Streaming API with line-by-line processing
  - Large batches (> 10K): Streaming API, process as you receive

## Slow Pattern Generation

### Symptom: Requests Slower Than Expected

**Cause:** Network overhead dominating due to small batch sizes or inefficient request patterns.

**Important:** Pattern complexity has minimal impact on generation speed. Server-side generation takes 1-100µs per slug regardless of pattern complexity. Slow performance is almost always due to network overhead or small batch sizes.

**Diagnosis:**

```bash
# Time the pattern with curl timing breakdown
time curl -w "@curl-format.txt" -o /dev/null -s \
  -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "pattern": "{adjective:+pos+emo<6}-{noun:+person<7}",
    "count": 100
  }'

# curl-format.txt should contain:
#     time_namelookup:  %{time_namelookup}\n
#        time_connect:  %{time_connect}\n
#     time_appconnect:  %{time_appconnect}\n
#  time_starttransfer:  %{time_starttransfer}\n
#          time_total:  %{time_total}\n
```

**Expected Timing for 100 Slugs:**
- DNS lookup: 10-15ms
- TCP connect: 40-60ms
- TLS handshake: 40-100ms
- Server processing: 80-100ms
- Total: 170-270ms

**Optimization Strategies:**

1. **Increase batch size (most important):**
```bash
# ❌ Inefficient: 1 slug per request
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -d '{"pattern": "{adjective}-{noun}", "count": 1}'
# Result: 225ms per slug (4.4 slugs/s)

# ✅ Efficient: 500 slugs per request
curl -X POST https://api.slugkit.dev/api/v1/gen/forge \
  -d '{"pattern": "{adjective}-{noun}", "count": 500}'
# Result: 0.4ms per slug (2,694 slugs/s) - 600x faster per slug!
```

2. **Use connection pooling:**
```python
import requests
from requests.adapters import HTTPAdapter

session = requests.Session()
adapter = HTTPAdapter(pool_connections=10, pool_maxsize=20)
session.mount('https://', adapter)

# Reuse connection - saves 90-150ms TLS handshake per request
```

3. **Pattern complexity doesn't matter much:**
```bash
# Simple pattern: {adjective}-{noun}
# Complex pattern: {adjective:+pos+emo<6}-{noun:+person+activity<7}
# Server-side difference: <10µs (negligible)

# Network overhead is 1,000-10,000x larger than pattern complexity
# Focus on batching, not on simplifying patterns
```

### Symptom: Bulk Generation Times Out

**Cause:** Network timeout settings too aggressive, or trying to generate extreme quantities in single request.

**Real-World Batch Performance:**
- **10,000 slugs:** ~500ms (well within typical 30s timeout)
- **5,000 slugs:** ~300-370ms
- **1,000 slugs:** ~230-280ms
- **500 slugs:** ~180-230ms (recommended batch size)

**Recommended Batch Sizes:**
- **Typical usage:** 100-500 slugs per request (185-200ms)
- **Bulk operations:** 1,000-5,000 slugs per request (250-400ms)
- **Maximum tested:** 10,000 slugs (507ms - still fast!)

**Note:** The API can handle very large batches efficiently. If you experience timeouts, it's likely a client-side timeout setting rather than server performance.

**Example: Generate 10 Million Slugs with Streaming API:**
```python
import requests

def generate_slugs_streaming(series, total_count, batch_size=1_000_000):
    """Generate large number of slugs using streaming API

    Streaming API advantages:
    - First slug arrives in ~180ms (vs 1.2s for JSON)
    - Progressive processing (no memory accumulation)
    - Memory efficient (line-by-line)
    - Throughput: ~440K slugs/s for 1M batches

    Use streaming for batches > 1,000 slugs
    """
    slugs_processed = 0
    batches = (total_count + batch_size - 1) // batch_size

    for batch_num in range(batches):
        count = min(batch_size, total_count - slugs_processed)

        # Use streaming endpoint
        response = requests.post(
            'https://api.slugkit.dev/api/v1/gen/mint/stream',
            headers={'x-api-key': 'sk_api_your_key'},
            json={'series': series, 'count': count},
            stream=True  # Enable streaming
        )

        # Process slugs as they arrive (line-by-line)
        for line in response.iter_lines(decode_unicode=True):
            if line:  # Skip empty lines
                slug = line.strip()
                # Process immediately - no memory accumulation
                process_slug(slug)  # Your processing logic
                slugs_processed += 1

                if slugs_processed % 10000 == 0:
                    print(f"Processed {slugs_processed:,} / {total_count:,}")

# Generate 10,000,000 slugs in batches of 1,000,000
# Expected time: ~23 seconds (10 batches × 2.3s)
# First results in 180ms, continuous stream after
generate_slugs_streaming('user-ids', 10_000_000, batch_size=1_000_000)
```

**Alternative: Accumulate slugs if needed (memory-constrained batches):**
```python
def generate_and_collect_streaming(series, count):
    """Use streaming but collect results

    Note: For very large counts, use smaller batches
    to avoid memory issues
    """
    slugs = []

    response = requests.post(
        f'https://api.slugkit.dev/api/v1/gen/mint/stream',
        headers={'x-api-key': 'sk_api_your_key'},
        json={'series': series, 'count': count},
        stream=True
    )

    for line in response.iter_lines(decode_unicode=True):
        if line:
            slugs.append(line.strip())

    return slugs

# For batches up to 100K, collecting is reasonable
slugs = generate_and_collect_streaming('user-ids', 100_000)
# Time: 0.81s, first slug in 0.18s
```

**Comparison: JSON API (for small batches ≤ 1K):**
```python
# JSON API - use for batches ≤ 1,000 slugs
response = requests.post(
    'https://api.slugkit.dev/api/v1/gen/mint',
    headers={'x-api-key': 'sk_api_your_key'},
    json={'series': 'user-ids', 'count': 500}
)
slugs = response.json()['slugs']  # Get array of slugs
# Total time: ~200ms, all slugs arrive at once
```

## High Latency Issues

### Symptom: Requests Take > 500ms

**Note:** Requests taking > 500ms are unusual for batch sizes under 10,000 slugs. Based on real benchmarks:
- 100 slugs: 180-210ms expected
- 500 slugs: 180-230ms expected
- 1,000 slugs: 230-280ms expected
- 5,000 slugs: 300-370ms expected
- 10,000 slugs: ~500ms expected

If seeing > 500ms for smaller batches, investigate:

**Common Causes:**

1. **Network latency** (geographic distance from API)
2. **TLS handshake on each request** (not reusing connections)
3. **DNS lookup delays**
4. **Small batch sizes** (network overhead dominates)

**Diagnosis:**

```bash
# Measure with curl timing
curl -w "@curl-format.txt" -o /dev/null -s \
  -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -H "x-api-key: sk_api_your_key" \
  -d '{"series": "test", "count": 100}'

# curl-format.txt:
#     time_namelookup:  %{time_namelookup}\n
#        time_connect:  %{time_connect}\n
#     time_appconnect:  %{time_appconnect}\n
#    time_pretransfer:  %{time_pretransfer}\n
#  time_starttransfer:  %{time_starttransfer}\n
#                     ----------\n
#          time_total:  %{time_total}\n
```

**Expected Breakdown (100 slugs):**
```
time_namelookup:  0.011s   (DNS lookup)
time_connect:     0.052s   (TCP connection)
time_appconnect:  0.099s   (TLS handshake)
time_starttransfer: 0.184s (Server processing + first byte)
time_total:       0.185s   (Complete)
```

**Diagnosis:**
- DNS > 50ms: DNS resolver issues
- connect - namelookup > 100ms: Network routing issues
- appconnect - connect > 150ms: TLS handshake slow
- starttransfer - pretransfer > 200ms: Server overload (unlikely) or large response serialization
- total > 500ms for <5000 slugs: Network issues

**Solutions:**

1. **Use connection pooling (most important):**
```python
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# Configure session with connection pooling
session = requests.Session()
adapter = HTTPAdapter(
    pool_connections=10,
    pool_maxsize=20,
    max_retries=Retry(total=3, backoff_factor=0.3)
)
session.mount('https://', adapter)

# Reuse session for all requests - saves 90-150ms TLS handshake
response = session.post(
    'https://api.slugkit.dev/api/v1/gen/mint',
    headers={'x-api-key': 'sk_api_your_key'},
    json={'series': 'user-ids', 'count': 500}
)
```

**Performance Impact:**
- First request: 185ms (includes TLS handshake)
- Subsequent requests on same connection: 95ms (reuses connection)
- Savings: ~90ms per request after first

2. **Batch requests efficiently:**
```bash
# ❌ Many small requests (network overhead dominates)
for i in {1..100}; do
  curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
    -d '{"series": "test", "count": 1}'
done
# Result: 100 requests × 225ms = 22.5 seconds for 100 slugs

# ✅ Single batched request (amortizes overhead)
curl -X POST https://api.slugkit.dev/api/v1/gen/mint \
  -d '{"series": "test", "count": 100}'
# Result: 1 request × 187ms = 0.187 seconds for 100 slugs (120x faster!)
```

3. **Use HTTP/2 or HTTP/3 if available:**
```python
# Use httpx for HTTP/2 support
import httpx

client = httpx.Client(http2=True)
# HTTP/2 multiplexing can improve concurrent request performance
```

4. **Pre-generate slugs in background:**
```python
import threading
import queue

slug_queue = queue.Queue(maxsize=10000)

def slug_producer():
    """Background thread that keeps queue filled"""
    while True:
        if slug_queue.qsize() < 5000:
            response = requests.post(
                'https://api.slugkit.dev/api/v1/gen/mint',
                headers={'x-api-key': 'sk_api_your_key'},
                json={'series': 'user-ids', 'count': 5000}
            )
            for slug in response.json()['slugs']:
                slug_queue.put(slug)

# Start background producer
threading.Thread(target=slug_producer, daemon=True).start()

# Use slugs from queue (no API latency)
slug = slug_queue.get()  # Instant
```

## Capacity Planning Issues

### Symptom: Pattern Exhaustion

**Cause:** Pattern capacity too low for expected usage.

**Example:**
```bash
# Pattern with 10,000 capacity
{adjective:+pos<5}-{noun:<5}

# But need to generate 100,000 user IDs
# Will start seeing duplicates after 10,000
```

**Check Pattern Capacity:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: sk_api_your_key" \
  -H "Content-Type: application/json" \
  -d '{"pattern": "{adjective:+pos<5}-{noun:<5}"}'

# Response includes capacity: "10823"
```

**Capacity Guidelines:**
- **Development:** 10x expected usage minimum
- **Production:** 100x expected usage recommended
- **Critical systems:** 1,000x+ buffer

**Increase Capacity:**

1. **Relax constraints:**
```bash
# Low capacity (~10,000)
{adjective:+pos<5}-{noun:<5}

# Higher capacity (~2.4M)
{adjective:+pos<8}-{noun:<8}

# Very high capacity (~29.4M)
{adjective:+pos}-{noun}
```

2. **Add numeric component:**
```bash
# Base capacity: 29M
{adjective:+pos}-{noun}

# Add 3-digit hex: 29M × 4,096 = ~118B
{adjective:+pos}-{noun}-{number:3x}

# Add 4-digit hex: 29M × 65,536 = ~1.9T
{adjective:+pos}-{noun}-{number:4x}
```

3. **Use fewer filters:**
```bash
# Highly filtered: 710 adjectives
{adjective:+pos}

# All adjectives: 17,082 adjectives
{adjective}
```

### Symptom: Running Out of Quota

**Cause:** Subscription quota exceeded.

**Daily Quotas by Plan:**
- **Free:** 1,000 mint/day
- **Developer:** 10,000 forge/day, 10,000 mint/day
- **Startup:** 20,000 forge/day, 20,000 mint/day
- **Business:** 50,000 forge/day, 100,000 mint/day

**Check Current Usage:**
```bash
curl https://api.slugkit.dev/api/usage \
  -H "x-api-key: sk_api_your_key"

# Response:
# {
#   "forge": {"used": 8234, "limit": 10000, "remaining": 1766},
#   "mint": {"used": 5621, "limit": 10000, "remaining": 4379}
# }
```

**Optimization Strategies:**

1. **Use slice for testing:**
```bash
# Don't waste mint quota on development/testing
# Slice doesn't consume generation quota

# Testing pattern output
curl -X POST https://api.slugkit.dev/api/v1/gen/slice \
  -H "x-api-key: sk_api_your_key" \
  -d '{"series": "user-ids", "start": 0, "count": 100}'
```

2. **Cache generated slugs:**
```python
import redis

cache = redis.Redis(host='localhost', port=6379)

def get_or_generate_slug(series, cache_key):
    """Check cache before generating"""
    cached = cache.get(cache_key)
    if cached:
        return cached.decode('utf-8')

    # Generate new slug
    response = requests.post(
        'https://api.slugkit.dev/api/v1/gen/mint',
        headers={'x-api-key': 'sk_api_your_key'},
        json={'series': series, 'count': 1}
    )

    slug = response.json()['slugs'][0]
    cache.set(cache_key, slug, ex=3600)  # Cache 1 hour
    return slug
```

3. **Batch generation efficiently:**
```python
# ❌ Inefficient: Generate on-demand one at a time
def create_user(username):
    slug = generate_single_slug()  # API call per user
    return create_user_with_slug(username, slug)

# ✅ Efficient: Pre-generate batch, use from pool
slug_pool = []

def refill_pool():
    global slug_pool
    response = requests.post(
        'https://api.slugkit.dev/api/v1/gen/mint',
        headers={'x-api-key': 'sk_api_your_key'},
        json={'series': 'user-ids', 'count': 500}
    )
    slug_pool = response.json()['slugs']

def create_user(username):
    if len(slug_pool) < 10:
        refill_pool()
    slug = slug_pool.pop()
    return create_user_with_slug(username, slug)
```

4. **Consider plan upgrade:**
```bash
# If consistently hitting limits, upgrade tier
# Developer → Startup: 2x capacity
# Startup → Business: 5x mint, 2.5x forge
```

## Rate Limiting Issues

### Symptom: 429 Too Many Requests

**Cause:** Exceeded requests per minute limit.

**Rate Limits:**
- **Free:** 10 req/min sustained, 100 req/min burst
- **Developer:** 100 req/min sustained, 1,000 req/min burst
- **Startup:** 200 req/min sustained, 2,000 req/min burst
- **Business:** 500 req/min sustained, 5,000 req/min burst

**Solution: Implement Rate Limiting Client-Side**

```python
import time
from collections import deque

class RateLimiter:
    """Client-side rate limiter"""

    def __init__(self, requests_per_minute):
        self.rate = requests_per_minute
        self.window = 60  # seconds
        self.requests = deque()

    def wait_if_needed(self):
        """Block if rate limit would be exceeded"""
        now = time.time()

        # Remove requests older than window
        while self.requests and self.requests[0] < now - self.window:
            self.requests.popleft()

        # Check if at limit
        if len(self.requests) >= self.rate:
            sleep_time = self.requests[0] + self.window - now
            if sleep_time > 0:
                time.sleep(sleep_time)
                return self.wait_if_needed()

        self.requests.append(now)

# Usage
limiter = RateLimiter(requests_per_minute=90)  # Leave buffer

def generate_slugs(series, count):
    limiter.wait_if_needed()
    return requests.post(
        'https://api.slugkit.dev/api/v1/gen/mint',
        headers={'x-api-key': 'sk_api_your_key'},
        json={'series': series, 'count': count}
    )
```

**Batch to Reduce Request Count:**
```python
# ❌ 100 requests/minute
for i in range(100):
    generate_slug(series='test', count=1)

# ✅ 1 request/minute
generate_slug(series='test', count=100)
```

## Memory and Resource Issues

### Symptom: Client Memory Exhaustion

**Cause:** Generating and holding too many slugs in memory.

**❌ Memory-intensive:**
```python
# Generate 1 million slugs and hold in memory
all_slugs = []
for i in range(2000):
    response = requests.post(url, json={'series': 'test', 'count': 500})
    all_slugs.extend(response.json()['slugs'])

# Now holding ~20MB of strings in memory
```

**✅ Stream and process:**
```python
# Generate and immediately write to database
def stream_slugs_to_db(series, total_count, batch_size=500):
    batches = (total_count + batch_size - 1) // batch_size

    for i in range(batches):
        count = min(batch_size, total_count - i * batch_size)
        response = requests.post(
            'https://api.slugkit.dev/api/v1/gen/mint',
            headers={'x-api-key': 'sk_api_your_key'},
            json={'series': series, 'count': count}
        )

        # Process immediately, don't accumulate
        slugs = response.json()['slugs']
        db.bulk_insert(slugs)  # Write to DB
        # slugs goes out of scope, memory freed

stream_slugs_to_db('user-ids', 1000000)
```

**✅ Use generator pattern:**
```python
def slug_generator(series, total_count, batch_size=500):
    """Yield slugs without holding all in memory"""
    generated = 0

    while generated < total_count:
        count = min(batch_size, total_count - generated)
        response = requests.post(
            'https://api.slugkit.dev/api/v1/gen/mint',
            headers={'x-api-key': 'sk_api_your_key'},
            json={'series': series, 'count': count}
        )

        for slug in response.json()['slugs']:
            yield slug
            generated += 1

# Process one at a time
for slug in slug_generator('user-ids', 1000000):
    process_slug(slug)  # Memory efficient
```

## Monitoring and Diagnostics

### Key Metrics to Track

1. **Response time percentiles:**
   - p50 (median)
   - p95 (slow requests)
   - p99 (very slow requests)

2. **Error rate:**
   - 4xx errors (client issues)
   - 5xx errors (server issues)
   - Timeout rate

3. **Quota consumption:**
   - Daily forge usage
   - Daily mint usage
   - Rate limit hits

4. **Pattern performance:**
   - Time per pattern type
   - Capacity warnings
   - Validation failures

### Example Monitoring Setup

```python
import time
import statsd

metrics = statsd.StatsClient('localhost', 8125, prefix='slugkit')

def monitored_generate(series, count):
    """Generate slugs with monitoring"""
    start = time.time()

    try:
        response = requests.post(
            'https://api.slugkit.dev/api/v1/gen/mint',
            headers={'x-api-key': 'sk_api_your_key'},
            json={'series': series, 'count': count},
            timeout=5
        )

        duration = (time.time() - start) * 1000  # ms
        metrics.timing('generate.duration', duration)
        metrics.incr('generate.success')

        if duration > 1000:
            metrics.incr('generate.slow')

        return response.json()['slugs']

    except requests.exceptions.Timeout:
        metrics.incr('generate.timeout')
        raise
    except requests.exceptions.HTTPError as e:
        metrics.incr(f'generate.error.{e.response.status_code}')
        raise
```

## Performance Optimization Checklist

- [ ] Patterns validated with capacity check
- [ ] Length constraints relaxed where possible
- [ ] Tag filters minimized
- [ ] Batch sizes optimized (100-500 per request)
- [ ] Connection pooling implemented
- [ ] Rate limiting handled client-side
- [ ] Quota tracking implemented
- [ ] Error handling with exponential backoff
- [ ] Monitoring and alerting configured
- [ ] Caching strategy for generated slugs
- [ ] Memory-efficient processing (generators/streaming)

## When to Contact Support

Contact support if you experience:

- **Response times > 1 second for batches < 10,000 slugs**
  - Expected: 180-500ms for 100-10,000 slugs
  - If seeing consistent > 1s, investigate network first

- **Unexplained capacity issues**
  - Pattern validation showing incorrect capacity
  - Running out of unique slugs earlier than expected

- **Rate limiting despite being under documented limits**
  - Check response headers for actual limits
  - Verify your subscription tier

- **Server errors (5xx) persisting > 5 minutes**
  - Occasional 5xx may be transient
  - Persistent errors indicate infrastructure issue

- **Performance degradation without code changes**
  - Established patterns suddenly slow
  - Previously working batch sizes timing out

**Include in report:**
- Pattern(s) experiencing issues
- Batch sizes being used
- Response time measurements:
  - curl timing breakdown (DNS, connect, TLS, transfer, total)
  - p50, p95, p99 percentiles over time
- Error rates and status codes
- Subscription tier
- Region/location and network path
- Request rate (requests per minute)
- Connection reuse strategy
- Example requests showing issue:
  ```bash
  # Include actual curl commands with timing
  time curl -w "@curl-format.txt" -X POST ...
  ```

---

# Troubleshooting and Support
Source: https://dev.slugkit.dev/docs/troubleshooting-support

# Getting Support

Find help, report issues, and get assistance with SlugKit. Learn what information to provide for faster resolution.

## Support Channels

### Documentation (Self-Service)

**Start here for fastest resolution:**

- **Developer Portal:** https://slugkit.dev/docs
  - API reference and endpoint documentation
  - Pattern language syntax and examples
  - SDK guides for Python and TypeScript
  - Integration recipes and use cases

- **Pattern Playground:** https://slugkit.dev/playground
  - Test patterns interactively
  - See generated examples in real-time
  - Validate pattern syntax
  - Check capacity estimates

- **System Status:** https://status.slugkit.dev

### Email Support

**For account, billing, and technical issues:**

- **General Support:** support@slugkit.dev
- **Sales Inquiries:** sales@slugkit.dev

**Best practices:**
- Use descriptive subject line
- Include all relevant details (see checklist below)
- One issue per email thread
- Reply to keep conversation threaded

### GitHub Issues

**For bug reports and feature requests:**

- **Repository:** https://github.com/slugkit/slugkit-issues
- **Use for:**
  - SDK bugs
  - Documentation issues
  - Feature requests
  - Public API feedback

**Not for:** Account issues, billing questions, security vulnerabilities

### Security Issues

**For security vulnerabilities:**

- **Email:** support@slugkit.dev with "SECURITY" in subject line
- **Do NOT:** Post security issues publicly on GitHub
- **Include:** Detailed vulnerability description, reproduction steps, impact assessment

## What Information to Provide

### For Pattern Issues

Include in your report:

```
Pattern: {adjective:+pos}-{noun:<10}

Error message: "Pattern validation failed: ..."

Expected behavior: Generate positive adjectives with short nouns

Actual behavior: Getting error or unexpected output

Attempts to resolve:
- Tried removing length constraint
- Validated tags exist
- Tested in playground

API endpoint: POST /api/forge
Timestamp: 2025-10-02 14:30:00 UTC
Request ID: req_abc123xyz (if available)
```

**Validation test result:**
```bash
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: ik-***" \
  -d '{"pattern": "{adjective:+pos}-{noun:<10}"}' | jq '.'

# Include the response
```

### For API Issues

Include in your report:

```
Endpoint: POST https://api.slugkit.dev/api/v1/gen/mint
Method: POST
Status code: 429
Error message: "Too Many Requests"

Request headers:
x-api-key: ik-*** (redacted)
Content-Type: application/json

Request body:
{
  "series": "user-handles",
  "count": 100
}

Response headers:
x-request-id: req_abc123xyz
x-ratelimit-remaining: 0
x-ratelimit-reset: 1696348800

Response body:
{
  "error": "Too Many Requests",
  "message": "Rate limit exceeded",
  "retry_after": 30
}

Timestamp: 2025-10-02 14:30:00 UTC
Frequency: Happening every request for past 10 minutes
Subscription tier: Developer
```

### For SDK Issues

Include in your report:

```
Issue: SDK authentication failure

SDK: Python SDK v1.2.3
Authentication method: JWK signing
Key slug: my-api-key-slug
SDK config: [relevant configuration]

Error message: "Authentication failed: invalid signature"

Code snippet:
from slugkit import SyncClient

client = SyncClient(
    base_url="https://api.slugkit.dev",
    api_key="ik-***"
)

# Operation that fails
result = client.forge(pattern="{adjective}-{noun}", count=10)

Expected: Successful authentication and slug generation
Actual: Authentication error

Timestamp: 2025-10-02 14:30:00 UTC
```

### For Performance Issues

Include in your report:

```
Issue: Slow API response times

Pattern: {adjective:+pos+emo<6}-{noun:+person<7}
Endpoint: POST /api/forge
Batch size: 100 slugs

Performance metrics:
- Average response time: 2.5 seconds
- p95 response time: 4.2 seconds
- p99 response time: 6.1 seconds

Expected: < 200ms for 100 slugs
Actual: > 2 seconds consistently

Pattern validation:
Capacity: 125,830
Complexity: 18
Components: 2

Timing breakdown (from curl):
time_namelookup: 0.010s
time_connect: 0.045s
time_starttransfer: 2.300s
time_total: 2.450s

Region: US East
Network: AWS VPC
Timestamp: 2025-10-02 14:00-15:00 UTC
```

**Include timing test:**
```bash
for i in {1..10}; do
  time curl -s -X POST https://api.slugkit.dev/api/v1/gen/forge \
    -H "x-api-key: ik-***" \
    -H "Content-Type: application/json" \
    -d '{"pattern": "{adjective:+pos}-{noun}", "count": 100}' \
    > /dev/null
done
```

### For Series Issues

Include in your report:

```
Issue: Mint operation returns 404

Series slug: user-handles
Operation: mint
Count: 10

Error response:
{
  "error": "Not Found",
  "message": "Series 'user-handles' does not exist"
}

Series list:
[checked via GET /api/series]
- Result: Series not found in list

Series creation attempt:
[details of POST /api/series request]
- Status: 201 Created (or error details)

Timestamp: 2025-10-02 14:30:00 UTC
Request ID: req_abc123xyz
```

### For Billing/Account Issues

Include in your report:

```
Issue: Upgrade not reflecting in quota

Account email: user@example.com
Organization: Example Corp
Current plan: Developer (expected: Startup)
Upgrade date: 2025-10-01
Payment status: Completed
Transaction ID: txn_abc123

Current quotas observed:
forge: 10,000/day (expected: 20,000/day)
mint: 10,000/day (expected: 20,000/day)
series: 5 (expected: 10)

Dashboard screenshot: [attach if helpful]
```

## Information Checklist

Before submitting support request:

### Required Information
- [ ] Detailed description of issue
- [ ] Expected behavior vs actual behavior
- [ ] Exact error message (if applicable)
- [ ] Timestamp (including timezone)
- [ ] Subscription tier
- [ ] Your account email

### API Issues
- [ ] Complete API endpoint URL
- [ ] HTTP method
- [ ] Request headers (API key redacted as ik-***)
- [ ] Request body
- [ ] Response status code
- [ ] Response headers
- [ ] Response body
- [ ] Request ID (x-request-id header)

### SDK Issues
- [ ] SDK version and language
- [ ] Authentication method (JWK signing)
- [ ] Key slug or SDK config
- [ ] Code snippet demonstrating issue
- [ ] Complete error message

### Pattern Issues
- [ ] Complete pattern string
- [ ] Pattern validation result
- [ ] Sample generated output
- [ ] Expected vs actual results
- [ ] Tags used and their intended meaning

### Performance Issues
- [ ] Response time measurements
- [ ] Batch sizes
- [ ] Request frequency
- [ ] Network information (region, provider)
- [ ] Time period affected
- [ ] curl timing breakdown

### Series Issues
- [ ] Series slug
- [ ] Series pattern
- [ ] Current counter position
- [ ] Operation attempted
- [ ] Series list output

## Common Issues and Self-Service Solutions

### Before Contacting Support

Try these quick fixes:

#### Authentication Error (401)
```bash
# Verify API key format (should start with ik-)
echo $SLUGKIT_API_KEY | grep -E '^ik-'

# Test key validity
curl -s https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: $SLUGKIT_API_KEY"
```

**Solution:** Generate new API key if invalid

#### Pattern Validation Error
```bash
# Test pattern in playground: https://slugkit.dev/playground
# Or validate via API:
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: ik-your-key" \
  -d '{"pattern": "{your-pattern}"}'
```

**Solution:** See [Common Errors documentation](troubleshooting-common-errors)

#### Rate Limiting (429)
```bash
# Check rate limit headers
curl -i https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: ik-your-key" | grep ratelimit
```

**Solution:** Implement exponential backoff, reduce request frequency, or upgrade tier

#### Series Not Found (404)
```bash
# List all series
curl https://api.slugkit.dev/api/v1/gen/series \
  -H "x-api-key: ik-your-key" | jq '.series[].slug'
```

**Solution:** Create series before using in mint/slice operations

#### Quota Exceeded
```bash
# Check current usage
curl https://api.slugkit.dev/api/usage \
  -H "x-api-key: ik-your-key" | jq '.'
```

**Solution:** Wait for daily reset, optimize usage, or upgrade tier

## Feature Requests

### How to Submit

1. **Search existing requests:** https://github.com/slugkit/slugkit-issues/issues
2. **If not found, create new issue:**
   - Title: Clear, concise description
   - Description: Use case, expected behavior, alternatives considered
   - Impact: How many users/use cases affected
   - Workaround: Current solution (if any)

### Feature Request Template

```markdown
## Feature Description
[Clear description of feature]

## Use Case
[Why you need this feature]

## Proposed Solution
[How you envision it working]

## Alternatives Considered
[Other approaches you've tried]

## Impact
[How this affects your usage]
- [ ] Blocking production deployment
- [ ] Nice to have enhancement
- [ ] Critical for future plans
```

### Feature Request Process

1. **Submit** via GitHub Issues
2. **Triage** by SlugKit team
3. **Discussion** with community and requestor
4. **Roadmap consideration** if accepted
5. **Implementation** priority based on impact
6. **Announcement** when available

## Bug Reports

### How to Report

1. **Verify it's a bug:**
   - Reproducible steps
   - Unexpected behavior
   - Not documented limitation

2. **Submit via GitHub Issues:** https://github.com/slugkit/slugkit-issues/issues

### Bug Report Template

```markdown
## Bug Description
[What's wrong]

## Steps to Reproduce
1. [Step 1]
2. [Step 2]
3. [Error occurs]

## Expected Behavior
[What should happen]

## Actual Behavior
[What actually happens]

## Environment
- Subscription tier:
- SDK version (if applicable):
- Language/Framework:
- Region:

## Additional Context
[Error messages, screenshots, logs]
```

## Contributing

### Open Source Components

SlugKit has several open source components:

- **Generator Library:** https://github.com/slugkit/slugkit-generator
  - Core pattern parsing and slug generation engine
  - Pull requests welcome

- **Python SDK:** https://github.com/slugkit/slugkit-py-sdk
  - Official Python client library
  - Pull requests welcome

- **TypeScript SDK:** https://github.com/slugkit/slugkit-ts-sdk
  - Official TypeScript/JavaScript client library
  - Pull requests welcome

**Documentation:** Fixes and improvements can be suggested via support@slugkit.dev

## Support Best Practices

### For Fastest Resolution

1. **Check documentation first** - Most questions are answered there
2. **Search existing issues** - Your question may already be answered
3. **Test in playground** - Verify patterns before reporting issues
4. **Provide complete information** - Follow checklists above
5. **One issue per ticket** - Don't combine multiple problems
6. **Stay on thread** - Reply to keep conversation together
7. **Update when resolved** - Help others with similar issues

### What Makes a Good Support Request

✅ **Good Example:**
```
Subject: Pattern validation fails for {adjective:+pos<8}

I'm trying to use the pattern {adjective:+pos<8}-{noun} but
getting a validation error.

Pattern: {adjective:+pos<8}-{noun}
Error: "Pattern parse error: expected '}' at column 21"

I've tested in the playground and get the same error.

Expected: Pattern validates successfully
Actual: Parse error

Validation attempt:
curl -X POST https://api.slugkit.dev/api/v1/gen/pattern-info \
  -H "x-api-key: ik-***" \
  -d '{"pattern": "{adjective:+pos<8}-{noun}"}'

Response: [paste response]

Account: user@example.com
Tier: Developer
Timestamp: 2025-10-02 14:30 UTC
```

❌ **Poor Example:**
```
Subject: Not working

My patterns don't work. Can you help?
```

## Contact Information Summary

| Purpose | Contact |
|---------|---------|
| General Support | support@slugkit.dev |
| Sales Inquiries | sales@slugkit.dev |
| Bug Reports | https://github.com/slugkit/slugkit-issues |
| Feature Requests | https://github.com/slugkit/slugkit-issues |
| Generator Issues | https://github.com/slugkit/slugkit-generator |
| Python SDK Issues | https://github.com/slugkit/slugkit-py-sdk |
| TypeScript SDK Issues | https://github.com/slugkit/slugkit-ts-sdk |

**Resources:**
- **Main Website:** https://slugkit.dev
- **Documentation:** https://slugkit.dev/docs
- **Playground:** https://slugkit.dev/playground
- **LinkedIn:** https://www.linkedin.com/company/slugkit/ (general questions, not for support)

**Note:** Response times and SLA details are available on the [feature matrix page](/products/feature-matrix) for each subscription tier.


---

# SlugKit MCP Server
Source: https://dev.slugkit.dev/docs/untangled-ecdysiast-lxi

# SlugKit MCP Server Guide

## The Problem: AI Cannot Generate Unique Strings

**AI assistants like Claude, ChatGPT, and others cannot generate truly unique strings.** This is a fundamental limitation of how language models work:

- **No persistence**: Each conversation is isolated, so AI can't remember what it generated before
- **No coordination**: Multiple AI instances can't coordinate to avoid duplicates
- **Probabilistic nature**: AI generates text based on patterns, not true randomness
- **Sequence awareness**: AI has no concept of sequential uniqueness across sessions

### Real-World Impact

This limitation becomes critical when you need:
- **Unique identifiers** for database records, user accounts, or API resources
- **Sequential IDs** that increment properly across multiple requests
- **Non-colliding slugs** for URLs, file names, or resource identifiers
- **Guaranteed uniqueness** in production systems where duplicates cause failures

**SlugKit MCP solves this by connecting AI assistants to a real uniqueness-guaranteed ID generation service.**

## What is MCP?

Model Context Protocol (MCP) is an open standard that allows AI assistants to securely connect to external data sources and tools. The SlugKit MCP server provides AI assistants like Claude Desktop, Cursor, and Warp with direct access to SlugKit's guaranteed-unique ID generation capabilities.

## The Uniqueness Guarantee

### How SlugKit Ensures Uniqueness

1. **Server-Side State**: SlugKit maintains state across all requests and sessions
2. **Atomic Operations**: Each ID generation is an atomic operation with database backing
3. **Sequential Tracking**: Series maintain counters that never repeat
4. **Collision Detection**: Mathematical guarantees prevent duplicate generation within patterns
5. **Global Coordination**: All clients coordinate through the central service

### Comparison: AI vs SlugKit

| Aspect | AI Assistant Alone | With SlugKit MCP |
|--------|-------------------|------------------|
| **Uniqueness** | ❌ Cannot guarantee | ✅ Mathematically guaranteed |
| **Sequences** | ❌ No sequence awareness | ✅ Proper sequential generation |
| **Persistence** | ❌ Forgets between sessions | ✅ Persistent state across all sessions |
| **Collision Prevention** | ❌ High collision probability | ✅ Zero collision guarantee |
| **Production Ready** | ❌ Not suitable for production | ✅ Battle-tested for production use |
| **Scale** | ❌ Breaks down with volume | ✅ Handles millions of IDs |

## Why Use the SlugKit MCP Server?

### Core Benefits

1. **True Uniqueness**: Unlike AI-generated strings, SlugKit guarantees every ID is unique within its series
2. **Sequential Consistency**: IDs increment properly across all requests and sessions
3. **Production Ready**: Built for high-volume, mission-critical applications
4. **Pattern Flexibility**: Generate IDs matching your specific format requirements
5. **Collision-Free**: Mathematical guarantees prevent duplicate generation

### What Your AI Assistant Can Do

- **Generate guaranteed-unique IDs** directly in conversations
- **Analyze and validate patterns** before deploying them
- **Compare different pattern designs** to optimize for your use case
- **Get comprehensive statistics** about ID generation performance
- **Access SlugKit documentation** and pattern syntax help
- **Test patterns** without affecting production series
- **Preview ID sequences** without consuming them (dry-run mode)

This creates a seamless workflow where you can discuss ID generation strategies with your AI assistant and have it immediately generate, test, and validate truly unique identifiers for you.

## Available Tools

The MCP server provides these tools to AI assistants:

### Core Generation
- **`forge`** - Generate unique IDs from custom patterns (one-off generation)
- **`mint`** - Generate sequential unique IDs from predefined series (production use)
- **`slice`** - Preview what IDs would be generated without consuming them (dry-run)

### Pattern Analysis & Validation
- **`validate_pattern`** - Validate pattern syntax and get detailed information
- **`analyze_pattern`** - Analyze pattern complexity, capacity, and performance characteristics
- **`compare_patterns`** - Compare multiple patterns side-by-side with sample outputs

### Information & Discovery
- **`dictionary_info`** - Get available word categories (adjectives, nouns, etc.) and counts
- **`dictionary_tags`** - Get word filtering options and content ratings
- **`series_list`** - List available series in your organization
- **`series_info`** - Get detailed information about a specific series
- **`key_info`** - Get your API key capabilities and permissions

### Management & Monitoring
- **`stats`** - Get comprehensive usage and performance statistics
- **`reset`** - Reset a series (development/testing only)
- **`ping`** - Test connectivity to SlugKit API

### Documentation
- **`list_help_topics`** - List available documentation topics
- **`get_help_topic`** - Retrieve specific documentation (pattern syntax, examples, etc.)

## Setup Instructions

### Option 1: Cloud Instance (Recommended)

Use our hosted MCP server for the easiest setup:

> [!NOTE]
> Most MCP clients don't support remote servers directly, so we use `mcp-remote` to bridge the connection.

**For Claude Desktop:**
```json
{
    "mcpServers": {
        "SlugKit": {
            "command": "npx",
            "args": [
                "-y",
                "mcp-remote",
                "https://dev.slugkit.dev/api/v1/mcp",
                "--header",
                "x-api-key:YOUR_API_KEY_HERE"
            ]
        }
    }
}
```

**For Cursor:**
```json
{
    "mcpServers": {
        "SlugKit": {
            "command": "npx",
            "args": [
                "-y",
                "mcp-remote",
                "https://dev.slugkit.dev/api/v1/mcp",
                "--header",
                "x-api-key:YOUR_API_KEY_HERE"
            ]
        }
    }
}
```

**For Warp:**
Add to your Warp MCP configuration:
```json
{
    "mcpServers": {
        "SlugKit": {
            "command": "npx",
            "args": [
                "-y",
                "mcp-remote",
                "https://dev.slugkit.dev/api/v1/mcp",
                "--header",
                "x-api-key:YOUR_API_KEY_HERE"
            ]
        }
    }
}
```

### Option 2: Local Installation

Install and run the MCP server locally:

```bash
# Install the SlugKit Python SDK
pip install slugkit-py-sdk
```

Then add to your MCP client configuration:

```json
{
    "mcpServers": {
        "SlugKit": {
            "command": "slugkit-mcp",
            "env": {
                "SLUGKIT_API_KEY": "YOUR_API_KEY_HERE",
                "SLUGKIT_BASE_URL": "https://dev.slugkit.dev/api/v1"
            }
        }
    }
}
```

### Option 3: Development Setup

For development or if you want to run from the source code:

```json
{
    "mcpServers": {
        "SlugKit": {
            "command": "uv",
            "args": [
                "--directory",
                "/path/to/slugkit-py-sdk",
                "run",
                "slugkit-mcp"
            ],
            "env": {
                "SLUGKIT_API_KEY": "YOUR_API_KEY_HERE",
                "SLUGKIT_BASE_URL": "https://dev.slugkit.dev/api/v1"
            }
        }
    }
}
```

## Configuration Files

MCP client configuration files are typically located at:

- **Claude Desktop (macOS):** `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Claude Desktop (Windows):** `%APPDATA%/Claude/claude_desktop_config.json`
- **Cursor:** Follow Cursor's MCP setup documentation
- **Warp:** Follow Warp's MCP setup documentation

## Getting Your API Key

1. Visit [SlugKit.dev](https://dev.slugkit.dev)
2. Sign up or log in to your account
3. Create a new organization or select an existing one
4. Generate an API key with appropriate permissions
5. Replace `YOUR_API_KEY_HERE` in the configuration above

## Usage Examples

Once configured, you can ask your AI assistant to:

### Generate Unique IDs (The Core Benefit)
```
"I need 10 unique identifiers for user accounts using the pattern user-{adjective}-{noun}-{number:4d}"
```
*Response: Generates 10 guaranteed-unique IDs like "user-happy-dolphin-0001", "user-bright-falcon-0002", etc.*

### Analyze Pattern Capacity
```
"Analyze this pattern: {color}-{animal}-{number:4,hex} and tell me how many unique IDs it can generate"
```
*Response: Shows total capacity (e.g., "2.1M unique combinations"), complexity analysis, and recommendations*

### Compare Pattern Options
```
"Compare these patterns and recommend the best one for a URL slug system:
- {adjective}-{noun}
- {verb}-{noun}-{number:2d}
- {adverb}-{adjective}-{animal}"
```
*Response: Generates samples from each pattern, analyzes capacity and performance, recommends best option*

### Validate Before Production
```
"Is this pattern valid and production-ready: {adjective:+positive}-{noun:+animals}-{special:3-5}?"
```
*Response: Validates syntax, shows capacity, identifies any issues, suggests improvements*

### Sequential ID Generation
```
"Generate the next 5 IDs in sequence from my main series"
```
*Response: Returns the next 5 sequential, unique IDs from your production series*

### Preview Without Consuming
```
"Show me what the next 10 IDs would look like without actually generating them"
```
*Response: Uses slice/dry-run mode to preview upcoming IDs without incrementing counters*

## Troubleshooting

### Connection Issues

**Problem:** "Connection failed" or timeout errors

**Solutions:**
1. Verify your API key is correct and has not expired
2. Check that `SLUGKIT_BASE_URL` is set to `https://dev.slugkit.dev/api/v1`
3. Test connectivity: Ask the assistant to run the `ping` tool
4. For cloud instance: Ensure `mcp-remote` is working with `npx -y mcp-remote --version`

### Authentication Issues

**Problem:** "Unauthorized" or API key errors

**Solutions:**
1. Verify your API key is valid at [SlugKit.dev](https://dev.slugkit.dev)
2. Check that the API key has the necessary scopes (forge, mint, slice, stats)
3. Ensure the API key is properly set in the environment variables
4. Use the `key_info` tool to verify your key's permissions

### Installation Issues

**Problem:** Command not found or package errors

**Solutions:**
1. **For cloud instance:** Run `npm install -g mcp-remote` if npx fails
2. **For local installation:** Ensure `pip install slugkit-py-sdk` completed successfully
3. **For development:** Make sure `uv` is installed and the path is correct
4. Restart your MCP client after configuration changes

### Pattern Issues

**Problem:** Pattern validation or generation errors

**Solutions:**
1. Use the `validate_pattern` tool to check syntax
2. Check the pattern syntax documentation with `get_help_topic`
3. Start with simple patterns like `{adjective}-{noun}` and build complexity
4. Use `analyze_pattern` to understand pattern limitations

## Advanced Configuration

### Custom Base URL

If you're using a different SlugKit instance:

```json
{
    "mcpServers": {
        "SlugKit": {
            "command": "slugkit-mcp",
            "env": {
                "SLUGKIT_API_KEY": "YOUR_API_KEY_HERE",
                "SLUGKIT_BASE_URL": "https://your-instance.com/api/v1"
            }
        }
    }
}
```

### Logging and Debug

For troubleshooting, you can enable debug logging:

```json
{
    "mcpServers": {
        "SlugKit": {
            "command": "slugkit-mcp",
            "args": ["--log-level", "DEBUG"],
            "env": {
                "SLUGKIT_API_KEY": "YOUR_API_KEY_HERE"
            }
        }
    }
}
```

### HTTP Transport

For advanced setups, you can run the MCP server with HTTP transport:

```bash
slugkit-mcp --transport http --host 127.0.0.1 --port 3000 --path /mcp
```

Then configure your MCP client to connect to `http://127.0.0.1:3000/mcp`.

## Best Practices

1. **Start Simple:** Begin with basic patterns like `{adjective}-{noun}` and gradually add complexity
2. **Validate First:** Always use `validate_pattern` before deploying patterns to production
3. **Use Dry-Run:** Use `slice` to preview IDs before `mint`ing them in production
4. **Monitor Usage:** Regularly check `stats` to understand your usage patterns and performance
5. **Test Patterns:** Use `forge` for testing and experimentation, `mint` for production series
6. **Check Capacity:** Use `analyze_pattern` to ensure patterns have sufficient capacity for your needs
7. **Plan for Scale:** Consider future growth when choosing patterns - start with higher capacity than you need

## Getting Help

- **Documentation:** Use the `get_help_topic` tool for pattern syntax and examples
- **API Reference:** Visit [SlugKit.dev documentation](https://dev.slugkit.dev/docs)
- **Support:** Contact support through the SlugKit.dev website
- **Issues:** Report bugs or request features on the GitHub repository
- **Community:** Join discussions about unique identifier generation and best practices


---

# What is Series in SlugKit?
Source: https://dev.slugkit.dev/docs/what-is-series

# Series Entity - Comprehensive Description

A **series** in SlugKit is a stateful configuration that defines a unique sequence of slugs within an organisational scope. It combines pattern templates, deterministic seeding, and auto-managed counters to provide guaranteed uniqueness and high-performance slug generation.

## Core Components

### Pattern Template
The series stores a pattern definition that specifies the structure and content of generated slugs. This includes:
- Dictionary selectors with optional language, tag filtering, and length constraints
- Number generators with format specifications (decimal, hexadecimal, Roman numerals)
- Special character generators
- Global modifiers applied across all pattern elements

### Seed Configuration
Each series maintains a seed value that ensures deterministic generation across the pattern. The seed influences:
- Dictionary word selection from available vocabularies
- Random number generation for numeric components
- Special character selection
- Overall pattern determinism

### Counter Management
The series tracks generation state through auto-managed counters:
- **Current position**: The next slug to be minted
- **Sequence integrity**: Ensures no gaps or duplicates in the mint operation
- **Distributed safety**: Counter operations are atomic across multiple nodes

## Series Domain
The **series domain** represents the theoretical set of all possible unique slugs that can be generated from the series configuration. This domain is bounded by:
- Pattern complexity and available dictionary entries
- Numeric generator ranges and formats
- Special character availability
- Mathematical combinations of all pattern elements

The domain provides the uniqueness guarantee - within a series, no two slugs will be identical regardless of generation method.

## Series Capacity
The **series capacity** is the total number of unique slugs available within the series domain, calculated as the least common multiple (LCM) of all pattern component capacities. This approach ensures that all pattern elements advance together, creating varied and unpredictable slug sequences rather than monotonous patterns.

### Capacity Calculation Process
1. **Component analysis**: Each pattern element contributes its individual capacity:
   - Dictionary selectors: Available word count (after language, tag, and length filtering)
   - Number generators: Base^length (e.g., 4-digit hex = 16⁴ = 65,536)
   - Special character generators: Cumulative capacity across all possible lengths
   - Roman numerals: Filtered count based on maximum length constraints

2. **Prime optimisation**: Dictionary capacities are reduced to the nearest lower prime when beneficial, maximising the overall LCM whilst maintaining good distribution properties.

3. **LCM calculation**: The final capacity is the least common multiple of all component capacities, ensuring complete pattern element cycling without premature repetition.

For example, a pattern `{adjective}-{noun}-{number:2x}` with 17,082 adjectives and 41,469 nouns would use primes 17,077 and 41,467 respectively, yielding capacity LCM(17,077, 41,467, 256) = 30,397,861,888 rather than the naive product of 29,465,697,792.

This mathematical approach guarantees that slug sequences remain visually diverse and unpredictable whilst maximising the total number of unique combinations available within the series domain.

The capacity determines the maximum number of slugs that can be minted from a series before exhaustion. After reaching the capacity, series will rotate. Series with higher capacity can support longer-running applications and larger user bases without uniqueness concerns.

## Operations

### Mint Operation
Advances the series counter and returns the next unique slug(s) in sequence:
- **State modification**: Increments the internal counter
- **Uniqueness guarantee**: Each minted slug is unique within the series domain
- **Performance**: 3-20μs per slug with automatic counter management
- **Use case**: Production applications requiring continuous unique slug streams

### Slice Operation  
Extracts specific ranges from the series without advancing counters:
- **State preservation**: Counter remains unchanged after operation
- **Deterministic access**: Same range parameters always return identical results
- **Window constraints**: Configurable backward/forward limits from current position
- **Performance**: 3-20μs per slug with direct sequence access
- **Use case**: Distributed coordination, testing, preview generation

## Organisational Scoping
Series exist within organisational boundaries:
- **Namespace isolation**: Series names are unique per organisation
- **Access control**: Users can only access series within their organisation
- **Resource quotas**: Generation limits apply per organisation
- **Multi-tenancy**: Complete isolation between different organisations

## Technical Implementation
- **Storage**: PostgreSQL (SaaS/enterprise) or SQLite (Lite) with atomic counter operations
- **Threading**: Distributed-safe counter management across multiple service instances  
- **Streaming**: Both mint and slice support streaming responses for bulk operations
- **Caching**: Pattern compilation and dictionary loading optimised for repeated access

## Lifecycle Management
- **Creation**: Series created with initial pattern, seed, and counter at position 0
- **Modification**: Pattern and seed updates reset the counter (breaking uniqueness chain)
- **Deletion**: Removes all series state and counter history
- **Migration**: Series can be exported/imported with full state preservation

This entity design enables SlugKit's core promise: fast, unique, aesthetically pleasing slug generation with mathematical guarantees about uniqueness within defined domains.
