npm package: @llmprofiles/core
Description: Schema.org profiles with three modes: Strict SEO (default), Split Channels, and Standards Header for optimal Google/Bing compatibility and LLM/developer support
Author: HAMI
Latest version: 2.0.6

# @llmprofiles/core

[![npm version](https://img.shields.io/npm/v/@llmprofiles/core.svg)](https://www.npmjs.com/package/@llmprofiles/core)
[![Downloads](https://img.shields.io/npm/dm/@llmprofiles/core.svg)](https://www.npmjs.com/package/@llmprofiles/core)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](../LICENSE-CODE)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![Schema.org](https://img.shields.io/badge/Schema.org-Compatible-green.svg)](https://schema.org/)

<!-- Optional (works when package is published on bundlephobia) -->

<!-- [![minzip](https://img.shields.io/bundlephobia/minzip/@llmprofiles/core?label=bundle%20size)](https://bundlephobia.com/package/@llmprofiles/core) -->

> **High-impact Schema.org builders for top-tier SEO and AI SEO — validated, sanitized, and production-ready.**

* ✅ **Rich-Results friendly** (Google/Bing aware)
* 🔒 **Built-in XSS/URL sanitization**
* 🤖 **3 output modes** (Strict SEO, Split Channels, Standards Header)
* 🧩 **Typed builders** for 15+ common profiles
* 🧪 **Validation utilities** & examples
* ⚡ **Smart validation** with required field checking
* 🎯 **Field suggestions** with importance indicators
* 💡 **IDE autocomplete** support with metadata

---

## 🔗 Quick Links

* **[Client Quick Start](#-client-centric-quick-start)** • **[SEO/AI SEO Playbooks](#-seoai-seo-playbooks)** • **[Real-world Applications](#-real-world-applications)** • **[Dev Guide](#-dev-centric-guide)**
* [Install](#-install) • [60-sec Demo](#-60-sec-demo) • [Smart Validation](#-smart-validation--autocomplete) • [Why @llmprofilescore](#-why-llmprofilescore) • [Output Modes](#-three-output-modes) • [Security](#-security-features) • [HTML/Next.js](#-html--nextjs-integration)

---

## 📦 Install

```bash
# npm
npm install @llmprofiles/core

# yarn
yarn add @llmprofiles/core

# pnpm
pnpm add @llmprofiles/core
```

---

## ⏱ 60-sec Demo

```ts
import { ProductBuilder, MODES } from '@llmprofiles/core';

const product = new ProductBuilder(MODES.STRICT_SEO)
  .name('Wireless Bluetooth Headphones')
  .description('High-quality wireless headphones with noise cancellation')
  .image('https://example.com/headphones.jpg')
  .brand('AudioTech')
  .sku('AT-WH-001')
  .offers(199.99, 'USD', 'InStock')
  .aggregateRating(4.5, 127)
  .build();

console.log(JSON.stringify(product, null, 2));
```

---

## 👤 Client-centric Quick Start

If you just want to add valid JSON-LD to your site/app in minutes:

1) Install the package

```bash
npm i @llmprofiles/core
```

2) Pick a builder and chain required fields

```ts
import { ProductBuilder } from '@llmprofiles/core';

const product = new ProductBuilder()
  .name('Wireless Headphones')
  .offers(199.99, 'USD', 'InStock')
  .build();
```

3) Render as JSON-LD (HTML example)

```html
<script type="application/ld+json">{ /* JSON.stringify(product) */ }</script>
```

- **Need examples?** See the `examples/` folder in this package.
- **Search performance?** Use [STRICT_SEO](#-three-output-modes) (default). For AI pipelines, try [SPLIT_CHANNELS](#-three-output-modes).
- **Validation tips?** See [Smart Validation](#-smart-validation--autocomplete).

---

## 📈 SEO/AI SEO Playbooks

- **E‑commerce Product Rich Results**
  - Use `ProductBuilder().name().image().offers()` and keep titles human-format; add `aggregateRating` when available.
- **Article + FAQ Combo**
  - Pair `Article` with `FAQPage` on long-form posts to win FAQs and enhance passage ranking.
- **Local SEO for Multi-location**
  - `LocalBusiness` per location page; ensure `address`, `telephone`, `openingHours`, and `geo` where possible.
- **Jobs Indexing Speed**
  - `JobPosting` with `hiringOrganization`, `jobLocation`, `datePosted`, and `employmentType`.
- **Split Channels for RAG/AI**
  - Use `MODES.SPLIT_CHANNELS` to keep SEO pristine while generating an LLM-enriched block for retrieval and summarization.

Use validation helpers to surface missing critical fields and recommended enhancements before shipping.

---

## ⚡ Smart Validation & Autocomplete

**Required Field Validation**

The `build()` method now validates required fields and throws errors when critical fields are missing:

```ts
import { JobPostingBuilder } from '@llmprofiles/core';

try {
  const jobPosting = new JobPostingBuilder()
    .title("Software Engineer")
    // Missing required fields: hiringOrganization, jobLocation
    .build(); // This will throw an error
} catch (error) {
  console.log('Error:', error.message);
  // "Missing required fields: hiringOrganization, jobLocation"
}
```

**Field Suggestions with Importance Indicators**

Get intelligent suggestions for completing your schema:

```ts
const jobPosting = new JobPostingBuilder()
  .title("Software Engineer")
  .description("Join our team");

// Check validation status
console.log('Is valid?', jobPosting.isValid()); // false
console.log('Missing fields:', jobPosting.getMissingRequiredFields());
// ['hiringOrganization', 'jobLocation']

// Get field suggestions organized by priority
const suggestions = jobPosting.getSuggestions();
console.log('Critical fields:', suggestions.critical.map(f => f.name));
console.log('Important fields:', suggestions.important.map(f => f.name));

// Get enhanced suggestions with metadata
const enhanced = jobPosting.getEnhancedSuggestions();
console.log('Summary:', enhanced.summary);
// { totalFields: 15, requiredFields: 2, recommendedFields: 13, ... }
```

**IDE Autocomplete Support**

Get completion hints for better development experience:

```ts
// Get all available fields with metadata
const hints = jobPosting.getCompletionHints();
hints.forEach(hint => {
  console.log(`${hint.label} (${hint.importance}) - ${hint.documentation}`);
  // "title (required) - The title field"
  // "hiringOrganization (required) - The hiringOrganization field"
});

// Get next steps guidance
const nextSteps = jobPosting.getNextSteps();
nextSteps.forEach(step => {
  console.log(`Priority ${step.priority}: ${step.message}`);
  console.log(`  Fields: ${step.fields.join(', ')}`);
});
```

**Multiple Build Options**

```ts
// Build with validation (default)
const result1 = builder.build();

// Build with warnings instead of errors
const result2 = builder.buildWithWarnings();

// Build without validation (unsafe)
const result3 = builder.buildUnsafe();
```

📖 **[Full Validation Guide →](./VALIDATION_AND_AUTOCOMPLETE_GUIDE.md)**

---

## ✨ Why @llmprofiles/core?

**SEO-First**

* Emits Schema.org that is friendly to Google/Bing rich result guidelines.
* Sensible defaults — *zero config* to get valid JSON-LD for common use cases.

**Security Built-In**

* XSS-safe: sanitizes HTML, validates URLs, strips unsafe protocols.
* Configurable sanitization levels when you fully trust inputs.

**AI & LLM Ready**

* **Three output modes** for production SEO, LLM ingestion, or full semantic web compliance.
* Optional profile metadata and training export helpers.

**Dev-Friendly**

* Full **TypeScript** types, ESM & CJS builds, tree-shakeable.
* Clean, chainable builders for 15+ profiles.

---

## 🔧 Three Output Modes

| Mode                        | Best For                       | Output Shape                          | Notes                                                                                                        |
| --------------------------- | ------------------------------ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| **STRICT\_SEO** *(default)* | Production SEO (Google/Bing)   | Single JSON-LD block                  | Adds `additionalType`, `schemaVersion`, and profile metadata in a way that plays nicely with search engines. |
| **SPLIT\_CHANNELS**         | SEO + AI pipelines             | `{ seo, llm }` object                 | Keep your SEO block pristine while shipping a parallel LLM-rich block.                                       |
| **STANDARDS\_HEADER**       | Semantic-web purists, gateways | JSON-LD + HTTP `Link`/`rel="profile"` | Access `getRelProfile()` / `getLinkHeader()` for headers integration.                                        |

**Example (Split Channels):**

```ts
import { ProductBuilder, MODES } from '@llmprofiles/core';

const out = new ProductBuilder(MODES.SPLIT_CHANNELS)
  .name('Product Name')
  .build();

// out.seo -> clean SEO JSON-LD
// out.llm -> LLM-enriched metadata block
```

---

## 🌍 Real-world Applications

- **E-commerce product pages**: Emit `Product` and `Offer` JSON-LD for rich results, price/availability, and LLM ingestion.
- **Job boards**: Use `JobPosting` to improve SERP visibility and feed AI matchers with validated fields.
- **Local SEO**: `LocalBusiness` for NAP, hours, and reviews across location pages at scale.
- **Publishers/blogs**: `Article`, `HowTo`, `FAQPage` to boost discoverability and provide clean AI context.
- **Course marketplaces**: `Course` metadata for catalogs, comparisons, and learning platforms.
- **Recipe and content sites**: `Recipe` with ratings and nutrition for rich cards.
- **Software directories/app stores**: `SoftwareApplication` with rating and operating system fields.
- **Q&A/Support**: `QAPage` and `FAQPage` to power answer boxes and RAG pipelines.
- **Datasets/portals**: `Dataset` for data catalogs and machine-readable discovery.
- **Video platforms**: `VideoObject` for previews, durations, and indexing.

Also useful for: multi-channel metadata (SPLIT_CHANNELS) to keep SEO clean while generating LLM-rich context for retrieval, summarization, and grounding.

---

## 📋 Available Profile Types

See `profiles/` and `web/profiles/` directories for definitions and examples.

---

## 🔒 Security Features

**Automatic input sanitization**

```ts
import { ArticleBuilder } from '@llmprofiles/core';

const article = new ArticleBuilder()
  .headline('<script>alert("xss")</script>Breaking News!') // sanitized
  .author('John <b>Doe</b>') // tags stripped
  .url('javascript:alert("xss")') // blocked
  .build();

// Safe outputs:
console.log(article.headline); // 'alert("xss")Breaking News!'
console.log(article.author);   // 'John Doe'
console.log(article.url);      // null
```

**Trusted content (opt-out)**

```ts
import { MODES, ArticleBuilder } from '@llmprofiles/core';

// Disable sanitization (only if you 100% trust your inputs)
const trusted = new ArticleBuilder(MODES.STRICT_SEO, false)
  .headline('<em>Trusted HTML</em>')
  .build();
```

---

## 🌐 HTML & Next.js Integration

**Basic HTML / Next.js**

```tsx
import Head from 'next/head';
import { ProductBuilder } from '@llmprofiles/core';

export default function Page() {
  const product = new ProductBuilder().name('Widget 3000').build();
  return (
    <>
      <Head>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(product) }}
        />
      </Head>
      <main>…</main>
    </>
  );
}
```

---

## 🛠 Advanced Usage (concise)

```ts
// ESM
import { ProductBuilder, MODES, validateStructuredData } from '@llmprofiles/core';

// CJS
const { ProductBuilder, MODES, validateStructuredData } = require('@llmprofiles/core');
```

```ts
// Individual profile imports
import { productofferProfile } from '@llmprofiles/core/profiles/productoffer';
```

```ts
// Custom validation
const result = validateStructuredData({ name: 'Product Name' }, 'Product');
```

---

## 🧑‍💻 Dev-centric Guide

For integrators working with the package in production.

- **Install & Test**

```bash
npm install
npm test
```

- **Build and test all profiles**

```bash
npm run test   # unit tests
node test/test-all-builders.js | cat
```

- **Types and ESM/CJS**: Public types live in `types/`. Both ESM (`index.mjs`) and CJS (`index.js`) builds are shipped.

- **Releases and publishing**: Publishing is automated via CI; avoid manual `npm publish`.

---

## ⚙️ Performance & Compatibility

* Small, tree-shakeable core
* TypeScript types included
* Node.js **16+**
* ESM and CommonJS builds
* No runtime telemetry

---

## ❓ FAQ (SEO/AI SEO focused)

- **How many JSON-LD blocks per page are OK?** Multiple are fine. Keep one primary block per entity. Avoid conflicting types for the same entity on the same URL.
- **Where should JSON-LD live? Head or body?** Either works; head is preferred for critical entities. Ensure it renders in the final HTML (SSR/SSG recommended for core SEO blocks).
- **Can I ship both SEO and AI blocks?** Yes. Use `MODES.SPLIT_CHANNELS` and render `out.seo` for search engines and `out.llm` for AI pipelines/RAG. Do not interlink them unless needed.
- **Do I need microdata if I use JSON-LD?** No. Prefer JSON-LD alone to avoid duplication conflicts. If both exist, ensure they’re consistent.
- **How strict is validation?** `build()` enforces required fields and throws; `buildWithWarnings()` collects warnings; `buildUnsafe()` skips validation (not recommended for production).
- **How do I bypass sanitization for trusted CMS fields?** Pass `new Builder(MODES.STRICT_SEO, false)` to disable sanitization per builder. Use sparingly and only for trusted sources.
- **International sites: language and locale?** Provide language codes in content where applicable; keep canonical URLs stable and avoid locale-swapping in the same entity.
- **Product variants (size/color/price)?** Use `offers()` for each purchasable option or aggregate via `aggregateOffer` when detailed variants are not required.
- **Can I include ratings/reviews safely?** Provide `aggregateRating` with accurate counts. Avoid fabricated review markup or gating user reviews.
- **How do I validate with Google tools?** Paste rendered HTML/URL into Google’s Rich Results Test. For AI blocks, verify your `llm` output separately and exclude it from SEO tests.

---

## 🤝 Contributing

We welcome PRs and issues!

* Read the [Contributing Guide](../CONTRIBUTING.md)
* Open an [Issue](https://github.com/HaMi-IQ/llmprofiles/issues)
* Star the repo if this helps you ⭐

**Development**

```bash
git clone https://github.com/HaMi-IQ/llmprofiles.git
cd llmprofiles/npm-package
npm install
npm test
```

---

## 📚 Resources

- Docs: `https://llmprofiles.org`
- Examples: `./examples/`
- API Types: `./types/`
- GitHub/Issues: `https://github.com/HaMi-IQ/llmprofiles`

---

## 📄 License

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

---


**Ready to ship safer, richer structured data?**
`npm i @llmprofiles/core` and go.