# Coralite — Machine-Readable LLM Developer Reference
> **Metadata**: Node.js Floor: `>=22.22.2` (ESM native)
---
## Table of Contents
- [§0. Critical Directives](#0-critical-directives)
- [§1. The Golden Optimal App](#1-the-golden-optimal-app)
- [§2. The Serialization Boundary & Isomorphic Model](#2-the-serialization-boundary-isomorphic-model)
- [§3. File Structure: Pages vs. Components](#3-file-structure-pages-vs-components)
- [§4. System Architecture, Fault Isolation & Asset Integrity](#4-system-architecture-fault-isolation-asset-integrity)
- [§5. Static Components (Declarative SSR-Only)](#5-static-components-declarative-ssr-only)
- [§5.3 Opting Out with `coralite-ignore`](#53-opting-out-with-coralite-ignore)
- [§6. Dynamic Components (Named Exports Reference)](#6-dynamic-components-named-exports-reference)
- [§6.1 Complete Schema & Export Signatures](#61-complete-schema-export-signatures)
- [§6.2 `attributes` (Coercion Pipeline, Validation & ARIA Rules)](#62-attributes-coercion-pipeline-validation-aria-rules)
- [§6.3 `server` (SSR Data Fetching & Context Keys)](#63-server-ssr-data-fetching-context-keys)
- [§6.4 `getters` (Unified Context Mechanics)](#64-getters-unified-context-mechanics)
- [§6.5 `style` (Synchronous Reactive Host Styles & CSS Vars)](#65-style-synchronous-reactive-host-styles-css-vars)
- [§6.6 `client` (Lifecycle, `errors`, `updateComplete`, FACE Hooks)](#66-client-lifecycle-errors-updatecomplete-face-hooks)
- [§6.7 `slots` (Reactive Element Builders)](#67-slots-reactive-element-builders)
- [§6.8 `onError` (SSR Component Error Boundaries)](#68-onerror-ssr-component-error-boundaries)
- [§6.9 W3C Context Protocol (`provide`, `consume`, `createContext`)](#69-w3c-context-protocol-provide-consume-createcontext)
- [§6.10 Form-Associated Custom Elements (`formControl = true`)](#610-form-associated-custom-elements-formcontrol--true)
- [§6.11 CSS Scoping, Specificity Taming (`@layer`, `:where()`), Slot Transparency & `::slotted()`](#611-css-scoping-specificity-taming-layer-where-slot-transparency-slotted)
- [§6.12 Lazy Dependency Stylesheets (`await import('*.css')`)](#612-lazy-dependency-stylesheets-await-importcss)
- [§7. Framework Extensibility (`definePlugin`)](#7-framework-extensibility-defineplugin)
- [§7.1 Plugin Schema & Physical Source Error Mapping (`rootDir`, `filePath`)](#71-plugin-schema-physical-source-error-mapping-rootdir-filepath)
- [§7.2 Context Resolver System (Static vs. Two-Phase Instance Context)](#72-context-resolver-system-static-vs-two-phase-instance-context)
- [§7.3 Server & Client Lifecycle Hooks](#73-server-client-lifecycle-hooks)
- [§7.4 Context Injection Targets & Getter Isomorphism Invariant](#74-context-injection-targets--getter-isomorphism-invariant)
- [§7.5 Imperative Custom Elements & Dependency Tracking](#75-imperative-custom-elements--dependency-tracking)
- [§7.6 Testing Server Plugins](#76-testing-server-plugins)
- [§8. Configuration (`coralite.config.js` / `defineConfig`)](#8-configuration-coraliteconfigjs-defineconfig)
- [§8.1 `defineConfig` Requirements](#81-defineconfig-requirements)
- [§8.2 Complete Options Reference](#82-complete-options-reference)
- [§9. Asset Management & Automated SRI Injection](#9-asset-management-automated-sri-injection)
- [§10. Built-In Plugins](#10-built-in-plugins)
- [§10.1 SPA Router (`coralite/plugins/router`)](#101-spa-router-coralitepluginsrouter)
- [§11. Automated Testing & E2E](#11-automated-testing-e2e)
- [§12. Native Form & Input Interaction Patterns](#12-native-form-input-interaction-patterns)
- [§13. Collections Architecture (`CoraliteCollection`)](#13-collections-architecture-coralitecollection)
- [§14. Error Handling (`CoraliteError` & `CoraliteBuildError`)](#14-error-handling-coraliteerror-coralitebuilderror)
- [§15. Component Validation & AST Auto-Fixer](#15-component-validation-ast-auto-fixer)
- [§16. Plugin Validation & Auto-Fixer](#16-plugin-validation-auto-fixer)
- [§17. Content Security Policy (CSP Level 2/3)](#17-content-security-policy-csp-level-23)
- [§18. Page Auditing & Encapsulation](#18-page-auditing-encapsulation)
- [§19. CLI & Tooling Ecosystem](#19-cli-tooling-ecosystem)
- [§20. Application Performance Architecture & Optimization](#20-application-performance-architecture-optimization)
---
## 0. Critical Directives
When generating code or providing instructions for Coralite applications, you MUST, SHOULD, and MUST NEVER adhere to the following normative rules:
1. **MUST use Named Exports**: Component `
```
### `src/components/custom-input.html`
```html
```
### `src/pages/index.html`
```html
Coralite Optimal App
Coralite Demo
Active Counter (Step 2)
Static Rendered Counter
```
### `coralite.config.js`
```javascript
import { defineConfig } from 'coralite'
export default defineConfig({
output: 'dist',
components: 'src/components',
pages: 'src/pages',
public: 'public',
mode: 'production',
styles: {
input: ['src/css/main.css']
},
csp: {
enabled: true,
hashAlgorithm: 'sha256',
injectMeta: true,
externalScripts: false,
externalStyles: false
}
})
```
---
## 2. The Serialization Boundary & Isomorphic Model
Coralite components operate across a strict boundary between Node.js server evaluation and browser client hydration.
```
+-----------------------------------------------------------------------+
| SERVER BUILD PASS (Node.js >=22.22.2) |
| |
| [attributes] -> [server()] -> [getters] -> SSR Template Compiler |
| | |
| v |
| Merged State Snapshot |
+--------------------------------------------------|--------------------+
|
HTML + JSON Bridge
|
v
+-----------------------------------------------------------------------+
| BROWSER CLIENT HYDRATION (Browser) |
| |
| Unpack Hydration Snapshot -> Hydrate State Proxy |
| | |
| v |
| [client({ state })] |
+-----------------------------------------------------------------------+
```
1. **`server` Execution**: The `server()` block executes during SSR in Node.js. Top-level imports from Node.js standard modules (`node:fs`, `node:path`) or server-only packages are permitted here.
2. **Stripping Phase**: At compile time, esbuild removes the `server` block and outer static imports from the client JavaScript module payload.
3. **Hydration Bridge**: Values returned by `server()` are serialized to JSON and embedded into the HTML payload. In the browser, Coralite hydrates this data directly into the component's reactive state proxy.
4. **Client Isolation**: The `client()` block cannot reference variables from outer module scope unless they are returned by `server()` or imported dynamically (`await import(...)`) inside `client()`.
---
## 3. File Structure: Pages vs. Components
* **Pages (`src/pages/*.html`)**: Pages are standard `.html` files that represent route entry points. Pages contain HTML document structure (``, ``, ``, ``) and declare custom element component tags as consumers (e.g. ` `). Pages must never contain component internal logic or manipulate custom element internals.
* **Page controller scripts**: A page may contain exactly one Coralite page controller `
```
Key properties:
- `{{ type }}` and `{{ disabled }}` render directly from `state` at SSR time — no getter and no `client()` are required.
- Native boolean attributes (`disabled`, `readonly`, `required`, `checked`) reflect automatically (`attr=""` when truthy, omitted when falsy).
- Native button/keyboard/form semantics work out-of-the-box because Coralite renders Light DOM.
### 5.2 Ref Pragmas for Phased Component Scaffolding (`CORALITE-W402`)
When authoring UI design systems incrementally (e.g., Phase 1 scaffolds static markup ``, Phase 2 wires events via `client()`), the validator emits `CORALITE-W402: Element ref 'button' defined in template but never accessed`.
Do NOT delete the `ref` attribute, and do NOT add a dummy `client({ refs }) { refs('button') }` handler (which breaks zero-JS static status). Instead, suppress the warning with a scoped pragma comment `` immediately following ``:
```html
```
### 5.3 Opting Out with `coralite-ignore`
Coralite processes page and component HTML by default. The only opt-out is the `coralite-ignore` attribute. There is no opt-in directive: remove the attribute to restore processing.
| Context | Default | With `coralite-ignore` |
|---|---|---|
| Page token interpolation | Processed | Literal |
| Custom-element compilation | Processed | Not compiled |
| Hydration | Processed | Not hydrated |
| Validator diagnostics | Processed | Skipped |
| Page-controller extraction | Processed | Ignored |
| `
```
The projected template, token, and script are emitted literally; the `code-block` component itself still renders. Unknown page tokens inside non-ignored custom-element slots are preserved rather than wiped.
#### Scripts, styles, and page controllers
`
```
**Required — direct flat token:**
```html
…
```
**Legitimate getter examples:**
- Combining fields: `fullName: ({ state }) => `${state.firstName} ${state.lastName}``
- Fallback chains: `displayValue: ({ state }) => state.value || state.placeholder || '—'`
- Slot presence: `hasIcon: ({ slots }) => slots.has('icon')`
### 6.5 `style` (Synchronous Reactive Host Styles & CSS Vars)
Maps CSS properties and CSS custom properties (`--*`) to static values or synchronous getter functions `(state: TState) => string | number | null | undefined | false`.
**Important**: Style functions receive `(state)` directly as their first argument, NOT a context object.
```javascript
style: {
display: (state) => (state.hidden ? 'none' : 'block'),
'--theme-accent': (state) => state.color,
'--counter-color': (state) => (state.count > 5 ? '#22c55e' : '#3b82f6'),
opacity: (state) => state.opacity // numeric 0 is preserved as valid CSS
}
```
- Returning `null`, `undefined`, `false`, or `''` removes the style property.
- Numeric `0` is strictly preserved as `'0'`.
- Functions MUST be synchronous. Returning a `Promise` throws `CoraliteError`.
### 6.6 `client` (Lifecycle, `errors`, `updateComplete`, FACE Hooks)
Executes in the browser runtime when custom elements connect to the DOM.
#### Verbatim TypeScript Type Signature (`CoraliteClientContext`)
```typescript
type CoraliteClientContext> = {
id: string,
instanceId: string,
root: HTMLElement,
state: TState,
errors: Record,
refs: (refName: string) => HTMLElement | null,
signal: AbortSignal,
observe: (propertyName: string, callback: (newValue: any, oldValue: any) => void) => (() => void),
emit: (eventName: string, detail?: any, options?: CustomEventInit) => boolean,
internals?: ElementInternals | null,
setFormValue?: (value: any, state?: any) => void,
setValidity?: (flags?: ValidityStateFlags, message?: string, anchor?: HTMLElement) => void,
checkValidity?: () => boolean,
reportValidity?: () => boolean,
updateComplete: Promise,
validity?: ValidityState,
validationMessage?: string,
form?: HTMLFormElement | null,
onFormReset?: (callback: () => void) => () => void,
onFormDisabled?: (callback: (disabled: boolean) => void) => () => void,
onFormRestore?: (callback: (state: any, mode: 'restore' | 'autocomplete') => void) => () => void
}
```
- **`updateComplete`**: Resolves when current reactive update cycles settle. Returns `Promise.resolve(true)` immediately when idle.
- **`observe(key, cb)`**: Registers explicit state change listener returning a disposer function. Automatically cleaned up when disconnected. Never mutate observed state inside `observe()`.
- **`emit(name, detail?, options?)`**: Dispatches a bubbling, composed `CustomEvent` from `root`.
- **`signal`**: AbortSignal aborted on element disconnection. Always pass `{ signal }` to `addEventListener`.
### 6.7 `slots` (Reactive Element Builders)
Slot builders intercept and transform Light DOM content projected into component `` elements.
Projected content is token-interpolated and custom elements are compiled by default. Add `coralite-ignore` to a slot to keep projected content literal: no tokens, compilation, hydration, or validation. Fallback content remains normal component content. See §5.3.
#### Verbatim TypeScript Type Signature (`CoraliteSlotBuilderContext`)
```typescript
type CoraliteSlotBuilderContext> = {
name: string,
state: TState,
root: HTMLElement | null,
refs: (id: string) => HTMLElement | null,
signal: AbortSignal,
observe: (key: string, callback: (val: any) => void) => () => void,
instanceId: string,
isServer: boolean,
isClient: boolean,
slots: Record
}
```
```javascript
slots: {
default: (nodes, { state, observe }) => {
// Void / undefined return bypasses client transformation to preserve SSR DOM
if (typeof window !== 'undefined' && state.isStatic) return undefined
return nodes.map((node) => transformNode(node))
}
}
```
### 6.8 `onError` (SSR Component Error Boundaries)
Handles component rendering failures during SSR in production mode.
```javascript
onError({ error, state, element, page, root }) {
return {
template: '',
state: { message: 'Component failed to render.' }
}
}
```
- Returns string HTML or object `{ template, state }`.
- Automatically strips hydration markers (`noHydration: true`).
- In `development` and `testing` modes, errors re-throw to preserve diagnostic visibility.
### 6.9 W3C Context Protocol (`provide`, `consume`, `createContext`)
Aligns with the standard W3C Web ComponentsCG Context Protocol for tree-based dependency injection.
```javascript
// Ancestor Provider Component (provider-card.html)
import { createContext } from 'coralite'
export const themeContext = createContext('theme')
export const provide = {
[themeContext]: ({ state }) => state.theme
}
```
```javascript
// Descendant Consumer Component (consumer-badge.html)
import { themeContext } from './theme.js'
export const consume = {
currentTheme: themeContext
}
export function client ({ state }) {
console.log('Consumed theme:', state.currentTheme)
}
```
### 6.10 Form-Associated Custom Elements (`formControl = true`)
Opt-in integration with native HTML `