API Reference
For the complete hyperscript command reference (53 commands,
expressions, compilation API), see the
hyperfixi API docs.
This page documents the LokaScript multilingual-specific APIs.
@lokascript/i18n
Per-language vocabulary for hyperscript: keyword dictionaries, locale
detection, and the grammar profiles that describe each language's word order
and role markers.
This package no longer translates. It used to export
translate(),
toLocale(),toEnglish()and aGrammarTransformerclass. That
transformer was retired once every row of the translation corpus was won by
the semantic engine, and those four exports were deleted with it. Use
@lokascript/semantic'stranslate()— it parses to
a semantic node and renders from it, so the output re-parses in the target
language. What follows is what@lokascript/i18nstill provides.
getSupportedLocales()
Returns the list of supported language codes.
import { getSupportedLocales } from '@lokascript/i18n';
getSupportedLocales();
// ['en', 'ja', 'ko', 'zh', 'ar', 'tr', 'es', 'de', 'fr', 'pt',
// 'id', 'ms', 'qu', 'sw', 'bn', 'it', 'ru', 'uk', 'vi', 'hi',
// 'tl', 'th', 'pl', 'he']
getProfile(lang)
Returns a language's grammar profile — word order, adposition type, text
direction, and the role markers used during transformation.
import { getProfile } from '@lokascript/i18n';
const ja = getProfile('ja');
ja.wordOrder; // 'SOV'
ja.adpositionType; // 'postposition'
ja.direction; // 'ltr'
ja.markers; // [{ form: 'を', role: 'patient', ... }, ...]
getProfile('en').wordOrder; // 'SVO'
getProfile('ar').wordOrder; // 'VSO'
@lokascript/semantic
Semantic multilingual parser for hyperscript.
parse(code, language)
Parse hyperscript code into a SemanticNode. The language is a positional
ISO 639-1 code, not an options object. Throws if parsing fails.
import { parse } from '@lokascript/semantic';
const node = parse('on click toggle .active on me', 'en');
node.kind; // 'event-handler'
node.metadata.confidence; // 1
node.metadata.sourceLanguage; // 'en'
node.metadata.patternId; // 'event-en-standard'
Confidence lives on metadata, and the node is not itself a runtime AST —
use buildAST() for that.
canParse(code, language)
Like parse(), but returns false instead of throwing. Use it to test a
candidate language without a try/catch.
import { canParse, getSupportedLanguages } from '@lokascript/semantic';
canParse('クリック で 私 の .active を 切り替え', 'ja'); // true
canParse('クリック で 私 の .active を 切り替え', 'en'); // false
// There is no built-in language detector. When the language is unknown,
// score the candidates you actually support:
const code = 'クリック で 私 の .active を 切り替え';
const detected = getSupportedLanguages().find((lang) => canParse(code, lang));
// → 'ja'
buildAST(node)
Convert a SemanticNode into a runtime-executable AST.
import { parse, buildAST } from '@lokascript/semantic';
const { ast, warnings } = buildAST(parse('toggle .active', 'en'));
if (warnings.length) console.warn(warnings);
translate(code, fromLang, toLang, options?)
Parse in one language and render in another. This round-trips: the output
re-parses in the target language. It is the only translation API in
LokaScript — @lokascript/i18n's transformer, which substituted keywords
without parsing, was retired.
import { translate } from '@lokascript/semantic';
translate('.active を 切り替え', 'ja', 'en'); // → 'toggle .active'
translate('toggle .active', 'en', 'ja'); // → '.active を 切り替え'
A translation that would lose part of the script is refused, not returned
short: translate() throws a LossyTranslationError. Its loss.kind
('truncation', 'core-only', 'read-back' or 'invariant') says which
check failed, loss.lost what would be dropped, and partial what it would
have returned (not the whole script). Pass { lossy: 'allow' } as the
fourth argument to get the partial output instead.
import { translate, LossyTranslationError } from '@lokascript/semantic';
function toLanguage(code, lang) {
try {
return translate(code, 'en', lang);
} catch (e) {
if (!(e instanceof LossyTranslationError)) throw e;
console.warn(`kept the English: ${lang} would drop`, e.loss.lost);
return code;
}
}
getAllTranslations(code, fromLang)
Translate once into every supported language.
import { getAllTranslations } from '@lokascript/semantic';
getAllTranslations('toggle .active', 'en');
// { en: 'toggle .active', ja: '.active を 切り替え',
// es: 'alternar .active', ar: 'بدّل .active', ... }
render(node, language) / renderExplicit(node)
Render a parsed node back to hyperscript, or to the language-agnostic
explicit syntax used for debugging role assignment.
import { parse, render, renderExplicit } from '@lokascript/semantic';
const node = parse('on click add .highlight to #box', 'en');
render(parse('toggle .active', 'en'), 'ja');
// → '.active を 切り替え'
renderExplicit(node);
// → '[on event:click body:[add patient:.highlight destination:#box]]'
DEFAULT_CONFIDENCE_THRESHOLD / HIGH_CONFIDENCE_THRESHOLD
0.5 and 0.8. Compare against node.metadata.confidence when deciding
whether to trust a semantic parse.
@lokascript/hyperscript-adapter
Drop-in multilingual plugin for original _hyperscript.
See the adapter plugin page for
quick start, live demos, and bundle options.
hyperscriptI18n(options?)
Create a plugin for _hyperscript.use(). It registers a source transform (addSourceTransform on hyperfixi's engine, a before-process hook on upstream _hyperscript) that translates non-English _="..." attributes to English before they are parsed.
import { hyperscriptI18n } from '@lokascript/hyperscript-adapter';
// Basic — uses defaults
_hyperscript.use(hyperscriptI18n());
// With options
_hyperscript.use(
hyperscriptI18n({
defaultLanguage: 'es',
confidenceThreshold: { ja: 0.1, '*': 0.5 },
debug: true,
})
);
PluginOptions
| Option | Type | Default | Description |
|---|---|---|---|
defaultLanguage |
string |
— | Fallback language when no data-lang or data-hyperscript-lang is found |
languageAttribute |
string |
"data-lang" |
Custom attribute name for per-element language |
confidenceThreshold |
number | Record<string, number> |
0.5 |
Min confidence (0–1). Per-language map supported — use '*' key for default. |
strategy |
'semantic' | 'i18n' | 'auto' |
'semantic' |
Translation strategy. 'auto' tries semantic first, then i18n fallback. |
debug |
boolean |
false |
Log translations to console as [hyperscript-i18n] lang: "input" → "output" |
validateWithHost |
boolean |
true |
Parse the rendered English with the host runtime before using it; if the host rejects it, keep the original text so parse errors name the author's code. No effect on hosts without parse(). |
onLossy |
function |
— | Called with { partial, lost } when a translation would drop part of a script. The script is left as written either way, and the plugin warns once per language. |
i18nToEnglish |
function |
— | Optional caller-supplied (code, lang) => english fallback translator (used with 'auto' or 'i18n' strategy). Bring your own — @lokascript/i18n no longer exports one. |
preprocess(src, lang, config?)
Standalone preprocessing for programmatic _hyperscript("code") or _hyperscript.evaluate() calls. The plugin only intercepts DOM attributes — use this for code strings.
import { preprocess } from '@lokascript/hyperscript-adapter';
const english = preprocess('alternar .active', 'es');
// → 'toggle .active'
_hyperscript(english);
Parameters:
src(string) — hyperscript code in the source languagelang(string) — ISO 639-1 language code (e.g.'es','ja')config(Partial<PreprocessorConfig>) — optional overrides
Returns string — English hyperscript. Returns the original text if lang is 'en', if translation fails, or if the translation would drop part of the script (pass onLossy to hear about that case; preprocess() itself logs nothing).
preprocessToEnglish(src, lang, config?)
Lower-level preprocessing function. Unlike preprocess(), does not short-circuit for English input. Most users should use preprocess() instead.
PreprocessorConfig
| Option | Type | Default | Description |
|---|---|---|---|
confidenceThreshold |
number | Record<string, number> |
0.5 |
Min confidence for semantic parsing |
strategy |
'semantic' | 'i18n' | 'auto' |
'semantic' |
Translation strategy |
i18nToEnglish |
function |
— | Optional i18n fallback function |
onLossy |
(refusal: { partial, lost }) => void |
— | Called when semantic refuses a translation that would lose part of the script; the result is then the original text |
fallbackToOriginal |
boolean |
— | Deprecated and ignored: a failed translation always returns the original text |
resolveLanguage(elt)
Resolve the language for an element using the cascading strategy:
data-langattribute on the elementdata-hyperscript-langon the element or closest ancestor<html lang="...">on the document- Returns
null(English assumed)
import { resolveLanguage } from '@lokascript/hyperscript-adapter';
// Useful for debugging language detection
const lang = resolveLanguage(document.querySelector('#myButton'));
console.log(lang); // 'es', 'ja', or null
BCP-47 tags are normalized to ISO 639-1 codes (e.g. "ja-JP" → "ja").
Core API
For the engine's API (register, boot, evaluate, parse, and the
window._hyperscript object), see the
hyperfixi API reference.