inputx-nihongo-wasm 1.5.0

WASM bindings for inputx-nihongo — Japanese romaji → hiragana/katakana + on-yomi kanji + jukugo, browser/Node ready. Powers the Inputx IME web surface.
Documentation
/* @ts-self-types="./inputx_nihongo_wasm.d.ts" */

/**
 * JP engine wrapping the embedded romaji / jukugo / kanji tables.
 * Cheap to construct (all data is in const tables).
 */
export class JapaneseEngine {
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        JapaneseEngineFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_japaneseengine_free(ptr, 0);
    }
    /**
     * Pop one byte off the buffer. Returns `true` if state changed.
     * @returns {boolean}
     */
    backspace() {
        const ret = wasm.japaneseengine_backspace(this.__wbg_ptr);
        return ret !== 0;
    }
    /**
     * Current candidates as a `js_sys::Array` of `Object`s. Each
     * object carries:
     *
     *   - `word: string`
     *   - `kind: KanaKind` (enum numeric value)
     *   - `freq: number` (0–100, higher = more common)
     *   - `composed: boolean` (`true` for mechanical
     *     `compose_sentence` products — particle/copula glue)
     *   - `proximityMilli: number` (1000 = exact match, < 1000 =
     *     prefix-prediction candidate whose reading the buffer is
     *     only a prefix of, e.g. `shinjuk → 新宿` at 875)
     * @returns {Array<any>}
     */
    candidates() {
        const ret = wasm.japaneseengine_candidates(this.__wbg_ptr);
        return takeObject(ret);
    }
    /**
     * Commit the candidate at `index`. Returns the committed text and
     * clears the buffer. Returns `null` (via empty `JsValue`) if
     * `index` is out of range; state is unchanged on out-of-range.
     * @param {number} index
     * @returns {string | undefined}
     */
    commitIndex(index) {
        try {
            const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
            wasm.japaneseengine_commitIndex(retptr, this.__wbg_ptr, index);
            var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
            var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
            let v1;
            if (r0 !== 0) {
                v1 = getStringFromWasm0(r0, r1).slice();
                wasm.__wbindgen_export2(r0, r1 * 1, 1);
            }
            return v1;
        } finally {
            wasm.__wbindgen_add_to_stack_pointer(16);
        }
    }
    /**
     * Drop the buffer entirely. Returns `true` if state changed.
     * @returns {boolean}
     */
    escape() {
        const ret = wasm.japaneseengine_escape(this.__wbg_ptr);
        return ret !== 0;
    }
    /**
     * Push one ASCII letter byte (`'a'..='z'`, `'A'..='Z'`) into the
     * buffer and re-render candidates. The `-` byte is also accepted
     * (chōonpu `ー`) when the buffer is non-empty.
     *
     * Returns `true` if the byte was accepted; rejected bytes leave
     * state unchanged so the host controller can route the byte
     * elsewhere (locale punct mapping, raw passthrough).
     * @param {number} byte
     * @returns {boolean}
     */
    handleLetter(byte) {
        const ret = wasm.japaneseengine_handleLetter(this.__wbg_ptr, byte);
        return ret !== 0;
    }
    /**
     * @returns {boolean}
     */
    get isComposing() {
        const ret = wasm.japaneseengine_isComposing(this.__wbg_ptr);
        return ret !== 0;
    }
    constructor() {
        const ret = wasm.japaneseengine_new();
        this.__wbg_ptr = ret;
        JapaneseEngineFinalization.register(this, this.__wbg_ptr, this);
        return this;
    }
    /**
     * Current buffer rendered as a string (for the preedit display).
     * @returns {string}
     */
    preedit() {
        let deferred1_0;
        let deferred1_1;
        try {
            const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
            wasm.japaneseengine_preedit(retptr, this.__wbg_ptr);
            var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
            var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
            deferred1_0 = r0;
            deferred1_1 = r1;
            return getStringFromWasm0(r0, r1);
        } finally {
            wasm.__wbindgen_add_to_stack_pointer(16);
            wasm.__wbindgen_export2(deferred1_0, deferred1_1, 1);
        }
    }
}
if (Symbol.dispose) JapaneseEngine.prototype[Symbol.dispose] = JapaneseEngine.prototype.free;

/**
 * Kana kind mirrored for JS. Use as `KanaKind.Kanji` etc. Numeric
 * values match the facade enum's discriminants.
 * @enum {0 | 1 | 2}
 */
export const KanaKind = Object.freeze({
    Hiragana: 0, "0": "Hiragana",
    Katakana: 1, "1": "Katakana",
    Kanji: 2, "2": "Kanji",
});
function __wbg_get_imports() {
    const import0 = {
        __proto__: null,
        __wbg___wbindgen_throw_9c31b086c2b26051: function(arg0, arg1) {
            throw new Error(getStringFromWasm0(arg0, arg1));
        },
        __wbg_new_02d162bc6cf02f60: function() {
            const ret = new Object();
            return addHeapObject(ret);
        },
        __wbg_new_310879b66b6e95e1: function() {
            const ret = new Array();
            return addHeapObject(ret);
        },
        __wbg_push_b77c476b01548d0a: function(arg0, arg1) {
            const ret = getObject(arg0).push(getObject(arg1));
            return ret;
        },
        __wbg_set_a0e911be3da02782: function() { return handleError(function (arg0, arg1, arg2) {
            const ret = Reflect.set(getObject(arg0), getObject(arg1), getObject(arg2));
            return ret;
        }, arguments); },
        __wbindgen_cast_0000000000000001: function(arg0) {
            // Cast intrinsic for `F64 -> Externref`.
            const ret = arg0;
            return addHeapObject(ret);
        },
        __wbindgen_cast_0000000000000002: function(arg0, arg1) {
            // Cast intrinsic for `Ref(String) -> Externref`.
            const ret = getStringFromWasm0(arg0, arg1);
            return addHeapObject(ret);
        },
        __wbindgen_object_drop_ref: function(arg0) {
            takeObject(arg0);
        },
    };
    return {
        __proto__: null,
        "./inputx_nihongo_wasm_bg.js": import0,
    };
}

const JapaneseEngineFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_japaneseengine_free(ptr, 1));

function addHeapObject(obj) {
    if (heap_next === heap.length) heap.push(heap.length + 1);
    const idx = heap_next;
    heap_next = heap[idx];

    heap[idx] = obj;
    return idx;
}

function dropObject(idx) {
    if (idx < 1028) return;
    heap[idx] = heap_next;
    heap_next = idx;
}

let cachedDataViewMemory0 = null;
function getDataViewMemory0() {
    if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
        cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
    }
    return cachedDataViewMemory0;
}

function getStringFromWasm0(ptr, len) {
    return decodeText(ptr >>> 0, len);
}

let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
    if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
        cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
    }
    return cachedUint8ArrayMemory0;
}

function getObject(idx) { return heap[idx]; }

function handleError(f, args) {
    try {
        return f.apply(this, args);
    } catch (e) {
        wasm.__wbindgen_export(addHeapObject(e));
    }
}

let heap = new Array(1024).fill(undefined);
heap.push(undefined, null, true, false);

let heap_next = heap.length;

function takeObject(idx) {
    const ret = getObject(idx);
    dropObject(idx);
    return ret;
}

let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
const MAX_SAFARI_DECODE_BYTES = 2146435072;
let numBytesDecoded = 0;
function decodeText(ptr, len) {
    numBytesDecoded += len;
    if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
        cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
        cachedTextDecoder.decode();
        numBytesDecoded = len;
    }
    return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}

let wasmModule, wasmInstance, wasm;
function __wbg_finalize_init(instance, module) {
    wasmInstance = instance;
    wasm = instance.exports;
    wasmModule = module;
    cachedDataViewMemory0 = null;
    cachedUint8ArrayMemory0 = null;
    return wasm;
}

async function __wbg_load(module, imports) {
    if (typeof Response === 'function' && module instanceof Response) {
        if (typeof WebAssembly.instantiateStreaming === 'function') {
            try {
                return await WebAssembly.instantiateStreaming(module, imports);
            } catch (e) {
                const validResponse = module.ok && expectedResponseType(module.type);

                if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
                    console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);

                } else { throw e; }
            }
        }

        const bytes = await module.arrayBuffer();
        return await WebAssembly.instantiate(bytes, imports);
    } else {
        const instance = await WebAssembly.instantiate(module, imports);

        if (instance instanceof WebAssembly.Instance) {
            return { instance, module };
        } else {
            return instance;
        }
    }

    function expectedResponseType(type) {
        switch (type) {
            case 'basic': case 'cors': case 'default': return true;
        }
        return false;
    }
}

function initSync(module) {
    if (wasm !== undefined) return wasm;


    if (module !== undefined) {
        if (Object.getPrototypeOf(module) === Object.prototype) {
            ({module} = module)
        } else {
            console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
        }
    }

    const imports = __wbg_get_imports();
    if (!(module instanceof WebAssembly.Module)) {
        module = new WebAssembly.Module(module);
    }
    const instance = new WebAssembly.Instance(module, imports);
    return __wbg_finalize_init(instance, module);
}

async function __wbg_init(module_or_path) {
    if (wasm !== undefined) return wasm;


    if (module_or_path !== undefined) {
        if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
            ({module_or_path} = module_or_path)
        } else {
            console.warn('using deprecated parameters for the initialization function; pass a single object instead')
        }
    }

    if (module_or_path === undefined) {
        module_or_path = new URL('inputx_nihongo_wasm_bg.wasm', import.meta.url);
    }
    const imports = __wbg_get_imports();

    if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
        module_or_path = fetch(module_or_path);
    }

    const { instance, module } = await __wbg_load(await module_or_path, imports);

    return __wbg_finalize_init(instance, module);
}

export { initSync, __wbg_init as default };