API / @aihu/compiler

@aihu/compiler

Compiler & tooling

Single File Component (.aihu) compiler — Rust binary + JS glue.

version
1.0.0
exports
40
values
30
types
10
01

_buildDeferredHydration

function
function _buildDeferredHydration(compiledCode: string, elementTag: string): string

Rewrite an interactive-island module so its `connectedCallback` waits for the element to scroll into view before mounting.

02

_buildStaticIsland

function
function _buildStaticIsland(compiledCode: string, elementTag: string): string

Build a static-island shim for a compiled module.

03

_clearTransformMemo

function
function _clearTransformMemo(): void

Test/diagnostic hook — wipe the memo and its counters.

04

_compileViaBackend

function
function _compileViaBackend( source: string, legacyArgs: string[], options: CompileEnvelopeOptions, ): EnvelopeReply

Run one compile through the active backend.

05

_foldCssEngineStyles

function
function _foldCssEngineStyles(compiledCode: string, css: string): string

Fold css-engine-produced scoped CSS into a compiled `.aihu` module.

06

_foldCssEngineStylesGlobal

function
function _foldCssEngineStylesGlobal( compiledCode: string, css: string, id: string, ): { code: string; virtualId: string } | null

Bug 6 — `shadowMode === 'light'` branch.

07

_formatExtractCensus

function
function _formatExtractCensus( census: ReadonlyMap<string, { read: string; call: string }>, ): string[]

GX Phase 1 (#437-GX) — format the per-value extract census (the DA-e census pattern from #437: every build PRINTS the posture distribution, so the default-vs-declared migration story stays visible rather than silent).

08

_getCompilerNativeStateKind

function
function _getCompilerNativeStateKind(): CompilerNativeState['kind']

Returns the cached state kind (resolving if needed).

09

_globalizeAuthoredStyle

function
function _globalizeAuthoredStyle(code: string): string

Light-DOM (`shadowMode:'light'`) recipes: redirect the authored `@style` block's per-instance `host.adoptedStyleSheets = [__style__]` assignment to `document.adoptedStyleSheets` so the recipe's class-scoped CSS reaches the global cascade (a light-DOM host has no shadow root, making the original setter a silent no-op).

10

_hashIdForUtilityCss

function
function _hashIdForUtilityCss(id: string): string

Stable short hash for keying the virtual-CSS module per source-SFC id.

11

_injectAutoWiring

function
function _injectAutoWiring(code: string): string

Inject `_setMount(mount)` + `_setSignal(signal)` auto-wiring into a compiled `.aihu` module.

12

_injectShadowMode

function
function _injectShadowMode(code: string, mode: 'light' | 'shadow'): string

Inject `{ shadowMode: '...' }` as the third argument to the emitted `defineElement('tag', defineComponent(...))` call.

13

_isLayoutFile

function
function _isLayoutFile(rawId: string, layoutsDir: string): boolean

Is `rawId` a layout SFC (a `.aihu` file under the configured layouts dir)?

14

_layoutTag

function
function _layoutTag(stem: string): string

Layout custom-element tag for a filename stem.

15

_parseExtractMarker

function
function _parseExtractMarker(code: string): { read: string; call: string } | null

GX Phase 1 (#437-GX) — parse the `//

16

_parseIslandMarker

function
function _parseIslandMarker(compiledCode: string): 'static' | 'interactive'

Read the compiler's AUTHORITATIVE island classification from the `//

17

_passivizeOutlet

function
function _passivizeOutlet(code: string): string

Collapse the reactive `<outlet>` boundary the Rust codegen emits into a passive `data-aihu-outlet` marker.

18

_resetCompileBackend

function
function _resetCompileBackend(): void

Reset the cached backend (tests).

19

_resetCompilerNative

function
function _resetCompilerNative(): void

Reset the cached state.

20

_resolveCompileBackend

function
function _resolveCompileBackend(): CompileBackend

Resolve (once) which backend serves compiles for this process.

21

_transformMemoStats

function
function _transformMemoStats(): { size: number hits: number misses: number seeds: number }

Test/diagnostic hook — current memo size + hit/miss/seed counters.

22

aihuCompilerPlugin

function
function aihuCompilerPlugin(options?: AihuCompilerPluginOptions): VitePlugin
23

compileRouteMeta

function
function compileRouteMeta(source: string, id?: string): RouteMeta | null
24

compileSidecar

functionagent
function compileSidecar( source: string, id?: string, options?: { /** * #486 step 4 — emit the attribute/component-prop type layer * (`--strict-templates`). Default off: the surface stays byte-identical * to the pre-#486 sidecar. */ strictTemplates?: boolean }, ): string

Compile an SFC to its TYPE-CHECK SURFACE and return it as a string — the `.aihu.ts` sidecar's content, without writing a file.

25

compileToAst

function
function compileToAst(source: string, id?: string): SfcAst
26

kebabComponentTag

function
function kebabComponentTag(raw: string): string

O1a (tag naming) — JS mirror of the Rust compiler's `tags::kebab_component_tag` (packages/compiler/src/tags.rs).

27

loadCompilerNative

function
function loadCompilerNative(): CompilerNativeState

Resolve (and cache) the native compiler addon.

28

transform

function
function transform( source: string, id: string, options?: { sidecarOut?: string target?: 'client' | 'server' | 'universal' /** Override the registered custom-element tag (default: file stem). Used for layouts. */ tag?: string /** * #486 step 4 — emit the sidecar's attribute/component-prop type layer * (`--strict-templates`). Affects only the type-check surface written to * `sidecarOut`; the compiled JS is identical either way. Default off. */ strictTemplates?: boolean }, ): { code: string; map: null }

Compile a .aihu source string to TypeScript.

29

_MEMO_MAX_ENTRIES

const
const _MEMO_MAX_ENTRIES

FIFO size bound.

30

VIRTUAL_UTILITY_PREFIX

const
const VIRTUAL_UTILITY_PREFIX

Virtual-module prefix used by the `shadowMode === 'light'` branch to route per-SFC utility CSS through Vite's built-in CSS pipeline.

31

AihuCompilerPluginOptions

interface
interface AihuCompilerPluginOptions {
  /**
   * When `true` (default), components the compiler classified as `'static'`
   * (read from the `// @aihu:island` marker via `_parseIslandMarker()`) are
   * emitted with a minimal HTML-only registration shim that ships **zero**
   * `@aihu/runtime` and `@aihu/signals` JS to the browser. Components
   * classified as `'interactive'` retain the full runtime path.
   *
   * Setting `islands: false` opts every component back into the unified
   * runtime path (Plan 3.2 baseline behaviour).
   */
  islands?: boolean

  /**
   * Project-wide rendering mode applied to every `.aihu` SFC compiled
   * by this plugin instance. When set, the plugin post-processes the
   * compiled JS to inject `, { shadowMode: '<mode>' }` as the third arg
   * to the emitted `defineElement(tag, defineComponent(...))` call.
   *
   * BINARY vocabulary (DA4 #437):
   * - `'shadow'` — shadow DOM (`attachShadow({ mode: 'open' })` internally;
   *               open is the only browser mode aihu's composition/hydration
   *               can use). `this.shadowRoot` is the non-null root.
   * - `'light'`  — **no shadow root.** The component mounts into its own
   *               element (`this.shadowRoot === null`). Required for global
   *               utility-class CSS frameworks like Tailwind, UnoCSS, Pico
   *               that rely on the cascade.
   *
   * Per-file override: the `$shadow: 'light' | 'shadow'` macro outranks this
   * config. Unset, pages/layouts default to `'light'` and leaves to
   * `'shadow'`.
   */
  shadowMode?: 'light' | 'shadow'

  /**
   * Build target threaded to the compiler binary (`--target`). Defaults to the
   * compiler's `universal` target (current behaviour). Set to `'client'` for a
   * browser bundle that must NOT ship the server `__agentBinding` (policy) and
   * instead gets the policy-free `@agent` opaque-ID dispatcher + the per-instance
   * `_registerAgentDispatcher` wiring the capability bridge reads after mount.
   * See `examples/agent-driven-demo`.
   */
  target?: 'client' | 'server' | 'universal'

  /**
   * Directory (relative to the project root) holding layout SFCs. Default:
   * `'src/layouts'`. Files under this directory are compiled in **layout mode**:
   * their custom element is registered under the namespaced tag
   * `aihu-layout-<stem>` (a layout stem like `app` is not a valid custom-element
   * name on its own), and their `<outlet>` lowers to a **passive**
   * `data-aihu-outlet` marker rather than the reactive route-driven boundary —
   * because `@aihu/app`'s client renderer fills the marker imperatively and the
   * reactive boundary would otherwise clear it on mount.
   *
   * Kept in sync with `@aihu/router`'s `layoutTagFor()` (`virtual:aihu-layouts`).
   */
  layoutsDir?: string
}

Options for `aihuCompilerPlugin()` (Plan 3.3 — Islands).

32

CompileEnvelope

interface
interface CompileEnvelope {
  envelope: number
  targets: Record<string, { js?: string; manifest?: string }>
  astJson?: string
  routeJson?: string
  diagnostics: unknown[]
}

The wire shape of a compile envelope (Rust `Envelope`, camelCase).

33

CompileEnvelopeOptions

interface
interface CompileEnvelopeOptions {
  tag?: string
  path?: string
  targets?: string[]
  emits?: Array<'js' | 'ast' | 'route' | 'manifest'>
  strictTemplates?: boolean
  exprParser?: string
}

Options forwarded to the Rust envelope API (Rust `EnvelopeOptions`).

34

RouteMeta

interface
interface RouteMeta {
  pattern?: string
  name?: string
  layout?: string
  middleware?: string[]
  ssr?: boolean
  params?: string[]
  head?: unknown
  /**
   * GX Phase 1 fan-out (#437-GX): the resolved `extract` policy — always
   * present in the binary's route-json output since 0.1.12 (the default is
   * recorded, never implied by absence). Typed loose here: consumers
   * normalize fail-closed (`deriveReadPolicy` in `@aihu/server`).
   */
  extract?: { read?: unknown; call?: unknown }
  /**
   * GX Phase 4 fan-out (#466): the `data:` governed-resource declaration
   * (70-governed-data-access §2.1) — present only when the route declares one
   * (0.1.14+). `type` keys the server registry's provider; `preview` lists
   * the locked-state fields (omitted when none declared). Consumers: the
   * server runtime's boot validation + generated loader, and the router Vite
   * layer's C486 sibling-loader conflict check (§4.7).
   */
  data?: { type?: string; preview?: string[] }
}

Structured `@route` metadata (the `.route.json` sidecar shape).

35

SfcAst

interface
interface SfcAst {
  /** Resolved custom-element tag name (meta.name → route.name → file stem). */
  tag: string
  /** AST schema version — bumped on any breaking shape change (semver-tied). */
  astVersion: 1
  /** The @style block, if the SFC declared one. */
  style: SfcStyleBlock | null
  /** Parsed template tree. null when the SFC has no @template block. */
  template: SfcNode[] | null
  /** SFC-level metadata. */
  meta: SfcMeta
}

Top-level AST export — one per .aihu SFC.

36

SfcMeta

interface
interface SfcMeta {
  /** From @meta { name } / @route { name } / file stem — never null after resolution. */
  name: string
}
37

SfcStyleBlock

interface
interface SfcStyleBlock {
  /** Verbatim CSS body of the @style block (braces stripped, $global token removed). */
  content: string
  /** 'scoped' (default) or 'global' (@style { $global ... }). */
  scope: 'scoped' | 'global'
}
38

SfcAttr

type
type SfcAttr =
  | { kind: 'static'; name: string; value: string } // Form A
  | { kind: 'binding'; name: string; expr: string } // Form B
  | { kind: 'macro'; name: string; value: SfcMacroValue }

Discriminated union mirroring Rust `Attr` — the three class-forms key on `kind`.

39

SfcMacroValue

type
type SfcMacroValue =
  | { form: 'quoted'; value: string }
  | { form: 'curly'; expr: string }
  | { form: 'boolean' }
40

SfcNode

type
type SfcNode =
  | { kind: 'element'; tag: string; attrs: SfcAttr[]; children: SfcNode[] }
  | { kind: 'macroElement'; name: string; attrs: SfcAttr[]; children: SfcNode[] }
  | { kind: 'text'; value: string }
  | { kind: 'interpolation'; expr: string }
  | { kind: 'ifBlock'; branches: Array<{ cond: string; body: SfcNode[] }> }
  | {
      kind: 'eachBlock'
      list: string
      item: string
      idx: string | null
      key: string | null
      body: SfcNode[]
      emptyBody: SfcNode[] | null
    }
  | { kind: 'htmlBlock'; expr: string }

Discriminated union mirroring Rust `TemplateNode`.