docs/SDK.md

TypeScript SDK & Browser Runtime Reference

Version 0.6.0 programmatic SDK signatures, two-tier error handling, createSession() SSE lifecycle, and sandboxed DOMPatchApplier integration.

This reference covers the TypeScript exports from leveonas, leveonas/sdk, leveonas/runtime, and the standalone CDN bundles (/leveonas-runtime.js and /leveonas.js).

For HTTP REST endpoints (/api/v1/chat/completions, /api/generate, /api/compile, /api/patch, /api/models), see the Public REST API Reference.


Package Entry Points (leveonas@0.6.0)

Import / Script URLEnvironmentExports
import { ... } from "leveonas"Node.js / Bundlerscompile (async), parse, lower, inspect, format, diagnose, types
import { createSession } from "leveonas/sdk"Node.js / BrowsercreateSession, LeveonasSession, StreamingEvent, LeveonasError
import { DOMPatchApplier } from "leveonas/runtime"Bundlers (Vite, Next.js)DOMPatchApplier, CSSPatchApplier, JSPatchApplier, validatePatches
https://leveonas.ainot.site/leveonas-runtime.jsStandalone <iframe sandbox="allow-scripts">window.LeveonasRuntime (DOMPatchApplier, validatePatches, PatchSerializer)
https://leveonas.ainot.site/leveonas.jsStandalone HTML host pagewindow.Leveonas.Engine + window.LeveonasRuntime

1. Compiler SDK (leveonas)

typescript
import {
  compile,
  parse,
  lower,
  inspect,
  format,
  diagnose,
  VERSION,
  type LMFramework,
  type CompileOptions,
  type CompileResult,
  type ParseOptions,
  type ParsedAST,
  type UIIRProgramNode,
  type DocumentInspection,
  type LSPDiagnostic,
} from 'leveonas';

Synchronous Offline vs. Asynchronous Server Functions

FunctionExecutionNetwork / Key RequiredReturns
compile(source, options?)Async (Promise)Yes (POST /api/compile + lv_live_...)Promise<CompileResult> (code, html, document, sections, ast, uiIR)
parse(source, options?)Sync (Offline)NoParsedAST (`RootNode \ReactProgramNode \VueProgramNode \SvelteProgramNode \AngularProgramNode`)
lower(astOrSource, framework?)Sync (Offline)NoUIIRProgramNode (framework-neutral Common UI IR)
inspect(source)Sync (Offline)NoDocumentInspection (AST, UI IR, Runtime IR, Reactivity Graph, patchOperations)
format(source, options?)Sync (Offline)NoCanonical formatted LM string (tag(attr(value) child))
diagnose(source, options?)Sync (Offline)NoLSPDiagnostic[]

CompileOptions, ParseOptions & Error Handling

typescript
export type LMFramework =
  | 'html'
  | 'react'
  | 'nextjs'
  | 'tailwind'
  | 'vue'
  | 'svelte'
  | 'angular'
  | 'auto'
  | (string & {});

export interface ParseOptions {
  framework?: LMFramework;
}

export interface CompileOptions {
  apiKey?: string;
  serverUrl?: string;
  /** Target language/framework dialect override */
  framework?: LMFramework;
  /** Representation hint (`'all' | 'ui-ir' | 'dom' | 'patches'`) */
  target?: 'all' | 'ui-ir' | 'dom' | 'patches';
  allowIncomplete?: boolean;
  documentMode?: boolean;
}

compile() has two distinct failure modes depending on where the failure happens:

  1. HTTP / Auth / Network failures (401 LM-AUTH-001, 413 oversized body, missing API key, offline timeout): Rejects the Promise with an Error.
  2. LM Syntax / Compiler Diagnostics (malformed LM such as legacy Lisp (di cs:"x") -> LM-DIALECT-001, unclosed parens): Resolves with result.success === false, populated result.diagnostics, and result.error.

Always handle both:

typescript
import { compile } from 'leveonas';

try {
  const result = await compile('<REACT>component(Card)(di(h2(Pro)))</REACT>', {
    apiKey: process.env.LEVEONAS_API_KEY,
    serverUrl: 'https://leveonas.ainot.site',
    framework: 'react',
    documentMode: true,
  });

  if (!result.success) {
    console.error('LM diagnostics:', result.diagnostics);
    throw new Error(result.error ?? 'Compilation failed');
  }

  console.log(result.detectedTarget); // "react"
  console.log(result.code);           // React TSX source
} catch (error) {
  console.error('Leveonas request failed:', error);
}

Offline parse(), lower(), inspect(), format(), diagnose()

typescript
const lm = '<SVELTE>component(Counter)(state(count, 0) bo(oc(count++) {count}))</SVELTE>';

const formatted = format(lm);
const diagnostics = diagnose(formatted, { streaming: false });
const ast = parse(formatted, { framework: 'svelte' });
const uiIR = lower(ast, 'svelte');
const report = inspect(formatted);

console.log(report.reactivityGraph.nodes);
console.log(report.patchOperations);

2. Streaming Session SDK (leveonas/sdk)

createSession() connects to POST /api/generate and translates raw SSE frames (session, patch, text, error, telemetry, [DONE]) into a typed StreamingEvent async iterable.

Complete TypeScript Interfaces

typescript
export type StreamingEvent =
  | { type: 'generation:start'; timestamp: number }
  | { type: 'generation:chunk'; text: string; delta: string; timestamp: number }
  | { type: 'generation:patch'; patch: PatchOperation[]; timestamp: number }
  | { type: 'generation:diagnostic'; diagnostic: LSPDiagnostic | unknown; timestamp: number }
  | { type: 'generation:error'; error: Error; code?: string; timestamp: number }
  | { type: 'generation:complete'; metrics: GenerationMetrics; timestamp: number };
SSE Wire Event (/api/generate)createSession() EventWhen Emitted
Stream openedgeneration:startImmediately when session.generate() starts
data: {"text":"..."}generation:chunkWhen emitDebugText: true is passed; delta has incremental text, text has full buffer
data: {"patch":[...]}generation:patchWhenever LM tokens reconcile into a PatchOperation[] batch
data: {"error":"..."}generation:errorEmitted on error before throwing LeveonasError (non-abort failures)
data: [DONE]generation:completeTranslated into generation:complete carrying metrics: GenerationMetrics

PatchOperation Schema

Every event.patch emitted in generation:patch is a PatchOperation[] array ready for validatePatches() and DOMPatchApplier.apply():

typescript
export interface PatchOperation {
  operation: PatchOperationType; // e.g. 'CREATE_NODE' | 'INSERT_CHILD' | 'UPDATE_TEXT' | 'SET_ATTRIBUTE' | ...
  nodeId: string;
  parentId?: string;
  index?: number;
  payload?: any;
  timestamp?: number;
}

3. End-to-End Tutorial: Progressive React Pricing Card

This verified bridge connects createSession() (leveonas/sdk) on your server/API route (or proxy) directly to DOMPatchApplier (window.LeveonasRuntime) inside a sandboxed <iframe sandbox="allow-scripts"> — streaming a React pricing card generated by Gemini into the browser without exposing keys.

Step A — Server Route (app/api/stream-ui/route.ts)

Forward the authenticated /api/generate SSE stream from your backend so LEVEONAS_API_KEY and GEMINI_API_KEY stay strictly on the server:

typescript
import { NextRequest } from 'next/server';

export async function POST(req: NextRequest) {
  const { prompt } = await req.json();

  const upstream = await fetch('https://leveonas.ainot.site/api/generate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Leveonas-Key': process.env.LEVEONAS_API_KEY!,
      'x-gemini-key': process.env.GEMINI_API_KEY!,
    },
    body: JSON.stringify({
      provider: 'gemini',
      model: 'gemini-4-carbon',
      prompt,
      maxTokens: 4096,
      telemetry: true,
    }),
    signal: req.signal,
  });

  return new Response(upstream.body, {
    status: upstream.status,
    headers: { 'Content-Type': 'text/event-stream' },
  });
}

Step B — Client Stream + Sandboxed DOMPatchApplier Bridge

Because event.patch from createSession() already matches PatchOperation[] expected by DOMPatchApplier.apply(), you can stream straight into the sandboxed iframe:

tsx
'use client';

import React, { useRef, useState } from 'react';
import { createSession } from 'leveonas/sdk';

const SANDBOX_HTML = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="https://leveonas.ainot.site/leveonas-runtime.js"></script>
</head>
<body style="margin:0;padding:16px;font-family:system-ui,sans-serif;">
  <div id="leveonas-root" data-ast-id="leveonas-root"></div>
  <script>
    var root = document.getElementById('leveonas-root');
    var applier = null;
    window.addEventListener('message', function (event) {
      if (event.source !== window.parent) return;
      if (!event.data || event.data.type !== 'leveonas:patch') return;
      var rt = window.LeveonasRuntime;
      if (!rt) return;
      if (!applier) {
        applier = new rt.DOMPatchApplier(root, document);
        applier.registerNode('leveonas-root', root);
      }
      var validPatches = rt.validatePatches(event.data.patches);
      applier.apply(validPatches);
    });
  </script>
</body>
</html>`;

export function PricingCardGenerator() {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [error, setError] = useState<string | null>(null);

  async function runGeneration() {
    setError(null);
    const session = createSession({
      endpoint: '/api/stream-ui', // Calls your own backend route — no keys in browser!
      provider: 'gemini',
      model: 'gemini-4-carbon',
    });

    try {
      for await (const event of session.generate('Build a React pricing card with Pro tier at $29/mo')) {
        if (event.type === 'generation:patch') {
          iframeRef.current?.contentWindow?.postMessage(
            { type: 'leveonas:patch', patches: event.patch },
            '*'
          );
        } else if (event.type === 'generation:error') {
          setError(event.error.message);
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Generation failed');
    } finally {
      session.destroy();
    }
  }

  return (
    <div>
      <button onClick={runGeneration}>Generate React Pricing Card</button>
      {error && <p role="alert">{error}</p>}
      <iframe
        ref={iframeRef}
        title="Progressive Preview"
        sandbox="allow-scripts"
        srcDoc={SANDBOX_HTML}
        style={{ width: '100%', minHeight: 420, border: '1px solid #DADCE0' }}
      />
    </div>
  );
}

4. Browser Runtime Distributions & Security Architecture

Three Browser Runtime Distributions

DistributionIntended UseMain API
leveonas/runtimeTypeScript / bundler apps applying patches directly in controlled containersDOMPatchApplier, CSSPatchApplier, JSPatchApplier, validatePatches, isPatchBatchValid
/leveonas-runtime.jsStandalone CDN bundle loaded inside <iframe sandbox="allow-scripts">window.LeveonasRuntime (identical exports as leveonas/runtime)
/leveonas.jsFull zero-build client engine that handles SSE fetch, validatePatches, and iframe creation automaticallynew window.Leveonas.Engine({ apiUrl, apiKey })

Browser Security Guarantees & Boundaries

  1. Opaque Origin Isolation: <iframe sandbox="allow-scripts"> omits allow-same-origin, giving the iframe origin: "null". Untrusted generated scripts cannot read host document.cookie, localStorage, sessionStorage, or DOM.
  2. Directional postMessage Validation: Because an opaque iframe has origin "null", message authenticity relies on event.source === window.parent inside the iframe and event.source === iframe.contentWindow in the host window. Unknown message type values and __proto__/constructor/prototype keys are dropped immediately.
  3. Patch & Attribute Hardening (validatePatches): Rejects unknown operation names, batches > 500 ops, node IDs > 256 chars or with control characters, any on* inline HTML event attributes (onclick, onerror, etc.), dangerous URL schemes (javascript:, vbscript:, file:, about:), and CSS expression() / -moz-binding. Invalid schemas throw PatchValidationError before touching the DOM.
  4. Known Limitation: Dynamic event handlers bound via ATTACH_EVENT_HANDLER execute inside the iframe's sandboxed JS realm (JSPatchApplier); do not pass secrets into srcDoc or post sensitive user data via postMessage into the preview iframe.