API Reference
Complete TypeScript and JavaScript API reference for UrduMagic core functions, static transliteration engine, instance methods, and React hooks.
Package Subpath Exports
UrduMagic provides tree-shakeable modular subpath exports:
| Import Path | Type | Description |
| :--- | :--- | :--- |
| urdumagic | Core Engine | Core client library, static engine, transliteration, and dictionary utilities. |
| urdumagic/react | React Hooks | Native useUrduMagic hook, UrduMagicProvider, and context consumer. |
| urdumagic/server | SSR / Node.js | Server-side HTML translation (renderToString) for Server Components & pre-rendering. |
| urdumagic/next | Next.js Helpers | Static param generators (generateUrduParams) and routing middleware helpers. |
Static Engine & Methods
These core methods can be called directly without creating or managing an instance.
UrduMagic.init
Initializes the UrduMagic engine in browser DOM, attaches live mutation observers, injects font styles, and optionally renders the floating switcher UI button.
import { UrduMagic } from 'urdumagic';
const app = UrduMagic.init({
defaultLang: 'en',
modes: ['en', 'ur', 'roman'],
showSwitcher: true
});UrduMagic.fromEnglish
Synchronously looks up English words in the built-in 10,000+ offline dictionary with O(1) instant memory lookup.
const res = UrduMagic.fromEnglish('welcome');
console.log(res.urdu); // → 'خوش آمدید'
console.log(res.roman); // → 'khush amdeed'UrduMagic.toUrdu
Converts phonetic Roman Urdu text directly into Nastaliq Urdu script offline using the built-in rules engine.
const script = UrduMagic.toUrdu('aap kaise hain');
console.log(script); // → 'آپ کیسے ہیں'UrduMagic.toRoman
Transliterates Urdu script back into readable Roman Urdu Latin characters offline.
const roman = UrduMagic.toRoman('شکریہ');
console.log(roman); // → 'shukriya'UrduMagic.detectScript
Analyzes character codepoints and linguistic patterns to detect the script family and language.
const type = UrduMagic.detectScript('سلام');
console.log(type); // → 'arabic'UrduMagic.renderToString
Server-Side Rendering utility. Translates raw HTML strings on Node.js/SSR, preserves tags and attributes, translates text nodes, and injects dir='rtl' for Urdu.
import { renderToString } from 'urdumagic/server';
const output = await renderToString('<p>Welcome to our store</p>', 'ur');
// Output: '<p dir="rtl">ہمارے اسٹور میں خوش آمدید</p>'extendDictionary
Injects custom domain terminology, company brand names, or slang into the offline dictionary. Automatically updates cache and alerts active listeners.
import { extendDictionary } from 'urdumagic';
extendDictionary({
'urdumagic': 'اردو میجک',
'fintech': 'فن ٹیک',
});Instance Methods
These methods are available on the instance object returned by UrduMagic.init() or UrduMagic.getInstance().
app.switchLang
Switches the entire active website language, scans and mutates visible text nodes, applies dir='rtl'/'ltr', and updates localStorage.
app.switchLang('ur'); // Translates entire website to Urduapp.getCurrentLang
Returns the currently active language mode of the application.
const current = app.getCurrentLang(); // → 'en'
app.translate
Translates a phrase or sentence using the full multi-tier offline pipeline.
const translated = await app.translate('Contact Us', 'ur');
console.log(translated); // → 'ہم سے رابطہ کریں'app.getMissingWords
Returns all unknown or untranslated words tracked during user browsing sessions.
const missing = app.getMissingWords(); console.log(missing);
app.destroy
Unmounts the floating switcher UI, detaches DOM mutation observers, and frees memory listeners.
app.destroy();
Configuration Options (UrduMagicConfig)
Configuration object accepted by UrduMagic.init(config) and <UrduMagicProvider config={...}>:
| Option | Type | Default | Required | Description |
| :--- | :--- | :--- | :--- | :--- |
| defaultLang | 'en' \| 'ur' \| 'roman' | 'en' | Yes | Initial active language mode on first page load. |
| modes | ('en' \| 'ur' \| 'roman')[] | ['en', 'ur', 'roman'] | Yes | Supported language options displayed in the UI switcher. |
| showSwitcher | boolean | true | No | Automatically renders the floating language switcher button. |
| strategy | 'offline' | 'offline' | No | Translation execution strategy (offline-first). |
| performance | PerformanceConfig | { debounceMs: 300 } | No | Controls DOM mutation debounce timing and LRU cache sizes. |
| security | SecurityConfig | { sanitizeHtml: true } | No | XSS sanitization and prototype pollution protection. |
| onLangSwitch | (lang: LangMode) => void | undefined | No | Callback invoked whenever the user switches languages. |
React Integration (urdumagic/react)
UrduMagic provides idiomatic React hooks and Context Providers:
import { useUrduMagic, UrduMagicProvider, useUrduMagicContext } from 'urdumagic/react';Hook Return Value (useUrduMagic & useUrduMagicContext)
| Property | Type | Description |
| :--- | :--- | :--- |
| currentLanguage | 'en' \| 'ur' \| 'roman' | Active language code. |
| switchLang | (lang: LangMode) => void | Function to switch the website language. |
| translate | (text: string, target: LangMode) => Promise<string> | Translation helper function. |
| toUrdu | (text: string) => string | Roman Urdu to Urdu script transliteration. |
| toRoman | (text: string) => string | Urdu script to Roman Urdu transliteration. |
| isTranslating | boolean | true while DOM translation mutations are processing. |
| isReady | boolean | true once dictionary and fonts are loaded in memory. |
| error | string \| null | Error message if initialization encountered an issue. |
| instance | UrduMagicInstance \| null | Direct reference to the underlying core instance. |