API Reference
This page documents the JavaScript / WASM binding of Suzume, published to npm as @libraz/suzume. Python, Go, C/C++, and the two command-line interfaces have separate guides.
Suzume Class
The main class for Japanese tokenization.
Suzume.create(options?)
Creates a new Suzume instance.
static async create(options?: SuzumeOptions & RuntimeOptions): Promise<Suzume>RuntimeOptions:
| Option | Type | Default | Description |
|---|---|---|---|
wasmPath | string | undefined | URL or path of suzume.wasm, for bundlers that move it |
freshWasmModule | boolean | false | Instantiate an isolated WASM runtime instead of using the shared cached runtime |
SuzumeOptions:
| Option | Type | Default | Description |
|---|---|---|---|
preserveVu | boolean | true | Keeps the ヴ series as written; false folds it to the バ row (ヴァイオリン → バイオリン) |
preserveCase | boolean | true | Preserve case (don't lowercase ASCII) |
preserveSymbols | boolean | false | Preserve punctuation-like SYMBOL tokens; emoji and content-bearing symbols remain OTHER regardless of this option |
mode | 'normal' | 'search' | 'split' | 'normal' | Analysis mode. Use search or split for search-oriented segmentation |
lemmatize | boolean | true | Replaces source base forms with corrected ones. When false, tokens keep their source base form; POS and conjugation annotations are computed either way (details) |
mergeCompounds | boolean | false | Merge consecutive noun compounds where possible |
skipBundledUserDictionary | boolean | false | Skip automatic loading of the bundled user dictionary |
skipCoreDictionary | boolean | false | Skip automatic loading of the bundled core dictionary (L2) |
reportScorerConfig | boolean | false | Add scorer configuration diagnostics to dictionaryWarnings |
skipEnvConfig | boolean | false | Ignore native scorer configuration environment variables; has no effect in the WASM build |
scorerOptions | string | Record<string, unknown> | null | undefined | Final-priority scorer overrides, supplied as JSON text or an object serialized to JSON; null means none |
Boolean options are validated, not coerced: preserveVu: 'false' throws invalid preserve_vu: "false" (expected a boolean). A null or unrecognized mode is invalid as well. Unknown option keys are ignored at runtime, while TypeScript rejects them at compile time. Every invalid option rejects Suzume.create() with a SuzumeError (see Error Handling).
Currency and unit signs, arrows, mathematical or technical marks, and emoji carry text content, so the default analysis keeps them as OTHER. Set preserveSymbols: true only when punctuation-like tokens such as 。 must also appear in the result.
Returns: Promise<Suzume>
Example:
// Default usage
const defaultSuzume = await Suzume.create()
defaultSuzume.destroy()
// Custom WASM path
const customWasmSuzume = await Suzume.create({ wasmPath: '/path/to/suzume.wasm' })
customWasmSuzume.destroy()
// With options
const customSuzume = await Suzume.create({
preserveSymbols: true,
preserveVu: false,
mode: 'normal',
mergeCompounds: true, // merges noun compounds without search mode
scorerOptions: {
unary: { user_dict_bonus: -3.0 },
},
})
customSuzume.destroy()Analysis modes:
The mode option controls how text is segmented:
| Mode | Segmentation |
|---|---|
normal | Balanced segmentation for general use (default) |
search | Merges runs of consecutive nouns into larger search units, with formal nouns excluded |
split | Skips the join rules and the optional noun-merging step |
In normal mode, mergeCompounds controls noun-compound merging. search enables merging, while split disables it. Choosing a Mode defines each mode.
scorerOptions is validated during construction. Malformed JSON text rejects Suzume.create() with a SuzumeError (Parse, operation create), and an object that cannot be serialized, including one holding NaN, Infinity, -Infinity or undefined at any depth, fails with invalid scorer_options: not serializable as JSON. reportScorerConfig: true records the active configuration in dictionaryWarnings. The WASM build does not read the native scorer environment layer, so skipEnvConfig has no effect in this binding. The WASM binding has no dataDirectory option; the bundled dictionaries are always the ones inside the WASM module (Dictionary Layers compares all bindings).
Scorer options
scorerOptions overrides numbers the scorer adds to the cost of a candidate path. The path with the lowest total cost wins, so a negative value favors what it applies to and a positive value penalizes it. Only the keys you give change. An unknown section or key rejects create() with invalid scorer options: Unknown scorer option: unary.foo. The same JSON is accepted by every binding (scorer_options in Python and C++, ScorerOptions in Go).
| JSON path | Keys (default) | Controls |
|---|---|---|
unary | user_dict_bonus (-2.0), noun_prior (0.0), verb_prior (0.2), adj_prior (0.3), adv_prior (0.2) | user_dict_bonus is added to every candidate from a user dictionary. The priors supply base costs for specific join and split candidates. For example, noun_prior affects some noun joins and dictionary splits, and adj_prior affects adjective candidates formed with a negative prefix, such as 不十分. |
candidates.join | compound_verb_bonus (-0.8), verified_v1_bonus (-0.3), verified_noun_bonus (-0.3) | Bonuses for join rule candidates |
candidates.split | alpha_kanji_bonus (-0.3), alpha_katakana_bonus (-0.3), digit_kanji_1_bonus (-0.2), digit_kanji_2_bonus (-0.2), duration_period_bonus (-0.3), digit_kanji_3_penalty (0.5), dict_split_bonus (-0.5), split_base_cost (1.0), noun_verb_split_bonus (-1.0), verified_verb_bonus (-0.8) | Costs of split candidates: letters beside kanji or katakana, numbers with counters, dictionary words and noun + verb |
bigram | noun_to_suffix, prefix_to_noun, prefix_to_verb, pron_to_aux, verb_to_verb, verb_to_noun, verb_to_aux, adj_to_aux, adj_to_verb, adj_to_adj, part_to_verb, part_to_noun, aux_to_part, aux_to_aux | The connection cost between a POS and the one after it, replacing the built-in table value |
verb_candidates, inflection | 22 and 28 tuning keys | Confidence and cost of verb and conjugation candidates; the field names are listed in scorer_options_loader.cpp in the Suzume source |
The native environment layer maps SUZUME_SCORER_{SECTION}_{KEY} onto the same keys, with JOIN, SPLIT, UNARY, BIGRAM, VERB and INFL as the sections; scorerOptions is applied after it.
For example, a lone 都庁 user-dictionary row does not split 東京都庁前 (When a Row Does Not Win). With scorerOptions: { unary: { user_dict_bonus: -4 } } the row wins and the result is 東京 / 都庁 / 前. The option applies to every user-dictionary entry, so change it only when the entries you load are meant to override the built-in analysis.
Shared WASM runtime
By default, calls with the same wasmPath share one cached WASM runtime. Each Suzume object gets its own analyzer handle and options inside that runtime's linear memory.
Set freshWasmModule: true when an instance must have an isolated runtime. The standalone version() function uses the same cache unless it also receives freshWasmModule: true.
mode
Reads or changes the analysis mode without reloading dictionaries. Mode names are case-sensitive and lowercase; any other value throws a SuzumeError (InvalidInput) such as invalid mode: "fast" (expected one of: normal, search, split).
get mode(): 'normal' | 'search' | 'split'
set mode(value: 'normal' | 'search' | 'split')console.log(suzume.mode) // "normal"
suzume.mode = 'split'analyze(text)
Analyzes Japanese text and returns an array of tokens.
analyze(text: string): readonly Morpheme[]| Parameter | Type | Description |
|---|---|---|
text | string | Japanese text to analyze |
Returns: readonly Morpheme[]
Example:
const result = suzume.analyze('東京に行きました')
// Result:
// [
// { surface: '東京', pos: 'NOUN', posJa: '名詞', ... },
// { surface: 'に', pos: 'PARTICLE', posJa: '助詞', ... },
// { surface: '行き', pos: 'VERB', posJa: '動詞', ... },
// { surface: 'まし', pos: 'AUX', posJa: '助動詞', ... },
// { surface: 'た', pos: 'AUX', posJa: '助動詞', ... }
// ]analyzeWithNormalizedText(text)
Analyzes text and returns both the morphemes and the exact normalized string their offsets refer to.
interface AnalysisResult {
readonly normalizedText: string
readonly morphemes: readonly Morpheme[]
}
analyzeWithNormalizedText(text: string): AnalysisResultUse the UTF-16 offsets when slicing a JavaScript string:
const { normalizedText, morphemes } =
suzume.analyzeWithNormalizedText('🎉𠮷字を読む')
for (const morpheme of morphemes) {
const surface = normalizedText.slice(
morpheme.startUtf16,
morpheme.endUtf16,
)
console.log(surface)
}start and end are Unicode code-point offsets into normalizedText. startUtf16 and endUtf16 are JavaScript UTF-16 code-unit offsets and can be passed directly to String.prototype.slice(). The two sets differ before or across characters outside the Basic Multilingual Plane, including many emoji and rare kanji.
Offsets refer to the normalized text, which may differ from the input; see Offsets for the concept. Content-bearing symbols and emoji stay in the default output as OTHER, so their ranges remain represented even when preserveSymbols is false.
generateTags(text, options?)
Generates tags for search indexing, classification, and content analysis. By default it returns content words (nouns, verbs, adjectives, and adverbs) while filtering out particles, auxiliaries, formal nouns, and low-information words.
generateTags(text: string, options?: TagOptions): readonly Tag[]Tag:
| Property | Type | Description |
|---|---|---|
tag | string | Tag text (surface or base form depending on useBaseForm) |
pos | PosLabel | Part of speech (NOUN, VERB, ADJ, ADV, etc.) |
| Parameter | Type | Description |
|---|---|---|
text | string | Japanese text to extract tags from |
options | TagOptions | Optional tag generation settings |
TagOptions:
| Option | Type | Default | Description |
|---|---|---|---|
posFilter | TagPosLabel | readonly TagPosLabel[] | undefined (all) | POS categories to include, as one name or an array; undefined, null and an empty array include every filterable category |
excludeBasic | boolean | false | Exclude basic verbs/words with hiragana-only base form |
useBaseForm | boolean | true | Use the base form instead of the surface form |
minLength | number | 2 | Minimum tag length in characters; an integer from 0 to 4294967295 |
maxTags | number | 0 | Maximum number of tags (0 = unlimited); an integer from 0 to 4294967295 |
excludeParticles | boolean | true | Exclude particles; applies only when PARTICLE is not named in posFilter |
excludeAuxiliaries | boolean | true | Exclude auxiliaries; applies only when AUX is not named in posFilter |
excludeFormalNouns | boolean | true | Exclude formal nouns such as こと and もの |
excludeLowInfo | boolean | true | Exclude low-information words |
removeDuplicates | boolean | true | Remove duplicate tags |
TagPosLabel is 'NOUN' | 'VERB' | 'ADJ' | 'ADV' | 'PARTICLE' | 'AUX', exported from the package entry (import type { TagPosLabel } from '@libraz/suzume'). Names are exact and case-sensitive, and a NOUN filter also admits PRON. The generator always considers nouns (including pronouns), verbs, adjectives, adverbs, particles, and auxiliaries; conjunctions, symbols, and other POS categories are excluded even when the filter is empty. A non-empty posFilter adds a whitelist over those filterable categories. Pronouns can still be removed by excludeLowInfo. Naming PARTICLE or AUX returns those tags even though excludeParticles and excludeAuxiliaries default to true.
Invalid values fail the whole call with a SuzumeError (InvalidInput) that lists the accepted names, for example invalid pos_filter: "adjective" (expected one of: NOUN, VERB, ADJ, ADV, PARTICLE, AUX). Invalid minLength or maxTags values (fractions, NaN, negatives) throw invalid min_length: 2.5 (expected an integer from 0 to 4294967295).
Returns: readonly Tag[]
Examples:
// Basic usage
const tags = suzume.generateTags('東京スカイツリーに行きました')
// [{ tag: '東京', pos: 'NOUN' },
// { tag: 'スカイツリー', pos: 'NOUN' },
// { tag: '行く', pos: 'VERB' }]
// Nouns only
const nouns = suzume.generateTags('美しい花が静かに咲いている', {
posFilter: ['NOUN'],
minLength: 1,
})
// [{ tag: '花', pos: 'NOUN' }]
// Particles and auxiliaries
const functionWords = suzume.generateTags('花が咲きます', {
posFilter: ['PARTICLE', 'AUX'],
minLength: 1,
})
// [{ tag: 'が', pos: 'PARTICLE' },
// { tag: 'ます', pos: 'AUX' }]
// Exclude basic verbs (hiragana-only base form like する, いる, ある, なる...)
const tags2 = suzume.generateTags('新しいプロジェクトを開始して管理する', {
excludeBasic: false
})
// [{ tag: '新しい', pos: 'ADJ' },
// { tag: 'プロジェクト', pos: 'NOUN' },
// { tag: '開始', pos: 'NOUN' },
// { tag: 'する', pos: 'VERB' },
// { tag: '管理', pos: 'NOUN' }]
const tags3 = suzume.generateTags('新しいプロジェクトを開始して管理する', {
excludeBasic: true
})
// [{ tag: '新しい', pos: 'ADJ' },
// { tag: 'プロジェクト', pos: 'NOUN' },
// { tag: '開始', pos: 'NOUN' },
// { tag: '管理', pos: 'NOUN' }]
// 'する' is excluded (base form is hiragana-only)
// Limit results
const top3 = suzume.generateTags('東京タワーと東京スカイツリーを見学しました', {
maxTags: 3
})
// [{ tag: '東京', pos: 'NOUN' },
// { tag: 'タワー', pos: 'NOUN' },
// { tag: 'スカイツリー', pos: 'NOUN' }]excludeBasic
excludeBasic: true filters out words whose base form is written entirely in hiragana. It removes entries such as する, いる, ある, なる, いく, and くる while keeping kanji-containing entries such as 開始, 管理, and 確認.
Filter pipeline
The tag generator applies these filters in order:
| Step | Filter | Behavior |
|---|---|---|
| 1 | Particles | Excluded when excludeParticles is true (default), unless PARTICLE is named in a non-empty posFilter |
| 2 | Auxiliaries | Excluded when excludeAuxiliaries is true (default), unless AUX is named in a non-empty posFilter |
| 3 | Formal nouns | Excluded when excludeFormalNouns is true (default) |
| 4 | Low-info words | Excluded when excludeLowInfo is true (default) |
| 5 | Conjunctions | Always excluded |
| 6 | Symbols | Always excluded |
| 7 | POS filter | If posFilter is non-empty, only matching categories pass, and a named POS lifts its own particle or auxiliary exclusion; an empty or undefined filter still admits only nouns (including pronouns), verbs, adjectives, adverbs, particles, and auxiliaries |
| 8 | Basic words | If excludeBasic: true, words with hiragana-only base form are excluded |
| 9 | Tag text | The base form or surface is selected according to useBaseForm |
| 10 | Min length | Tags shorter than minLength Unicode characters are excluded |
| 11 | Deduplication | Duplicate tags are removed when removeDuplicates is true |
| 12 | Result limit | Generation stops at maxTags; 0 is unlimited |
loadUserDictionary(data)
Adds source user dictionary entries to the analyzer. Loads are cumulative until clearUserDictionaries() is called, and a failed load leaves earlier dictionaries installed.
loadUserDictionary(data: string | Uint8Array): number| Parameter | Type | Description |
|---|---|---|
data | string | Uint8Array | Dictionary entries in the TSV format, as text or as its UTF-8 bytes |
Returns: number — the count of expanded entries installed, always at least 1. One source row can install multiple entries when Suzume expands conjugated forms, so the count can exceed the number of rows.
Throws: SuzumeError with the native code and text, operation load_user_dictionary, when the source cannot be loaded, including empty or entry-less text. Bytes that are not valid UTF-8 fail with Parse and Dictionary entry is not valid UTF-8 at line N. Any other argument type throws InvalidInput, for example invalid dictionary: 123 (expected a string or binary data). Nonfatal skipped-row and expansion diagnostics are appended to dictionaryWarnings.
Format: surface<TAB>POS[<TAB>conj_type][<TAB>base_form]. The conjugation type is optional; specify it when inflected forms should be expanded. A third field that is not a recognized conjugation type is treated as the base form. A numeric third field is an error; to use a numeric base form, write it in column 4 and leave column 3 empty. Comma-delimited rows and rows in the old four-column layout fail with a Parse error. See User Dictionaries for the complete format.
Example:
// Single entry
suzume.loadUserDictionary('ChatGPT\tNOUN\n') // 1
// Multiple entries
suzume.loadUserDictionary(`
ChatGPT NOUN
スカイツリー NOUN
DeepL NOUN
`) // 3
// Conjugating entry: the count includes the expanded forms
suzume.loadUserDictionary('検査する\tVERB\tSURU\n') // 7
// UTF-8 bytes, for example read from a file
suzume.loadUserDictionary(new TextEncoder().encode('ChatGPT\tNOUN\n')) // 1loadBinaryDictionary(data)
Adds a compiled binary dictionary (.dic) at runtime. Binary and source dictionary loads are cumulative.
loadBinaryDictionary(data: Uint8Array): number| Parameter | Type | Description |
|---|---|---|
data | Uint8Array | Binary dictionary data (.dic format) |
Returns: number — the count of entries installed, always at least 1.
Throws: SuzumeError with code DictionaryLoadFailed and the native text (for example Dictionary file too small) when the bytes cannot be loaded.
Example:
// Load from file (Node.js)
import { readFile } from 'fs/promises'
const dictData = new Uint8Array(await readFile('custom.dic'))
suzume.loadBinaryDictionary(dictData)
// Load from URL (Browser)
const response = await fetch('/dictionaries/custom.dic')
const browserDictData = new Uint8Array(await response.arrayBuffer())
suzume.loadBinaryDictionary(browserDictData)Binary vs source dictionaries
Binary dictionaries (.dic) load faster than source TSV. Use suzume-cli dict compile to compile a TSV dictionary.
clearUserDictionaries()
Removes dictionaries loaded by the caller and clears their runtime warnings. The automatically loaded bundled user dictionary, if present, remains installed. Throws SuzumeError (operation clear_user_dictionaries) after destroy().
clearUserDictionaries(): voidhasCoreDictionary
Reports whether the bundled core dictionary (L2) is loaded.
get hasCoreDictionary(): booleanThis is false when the analyzer was created with skipCoreDictionary: true or when automatic core-dictionary loading failed.
version(options?)
Returns the version without creating an analyzer handle.
import { version } from '@libraz/suzume'
const current = await version()
console.log(current) // semantic-version stringfunction version(options?: RuntimeOptions): Promise<string>The function is asynchronous because it must instantiate or retrieve the WASM runtime. If the module cannot be loaded, it rejects with a SuzumeError (Internal, operation version).
dictionaryWarnings
Returns nonfatal diagnostics recorded for this analyzer, or an empty array when there are none.
get dictionaryWarnings(): readonly string[]The array contains constructor-time dictionary-loading diagnostics, optional scorer-configuration diagnostics, and warnings from successful source dictionary loads, such as skipped records or duplicate expanded entries. clearUserDictionaries() removes warnings from caller-loaded source dictionaries while retaining construction diagnostics. A fatal load failure is always reported as a SuzumeError thrown by the loading method.
wasmMemoryBytes()
Returns the current size of this runtime's WebAssembly linear memory in bytes.
wasmMemoryBytes(): numberInstances on the shared runtime report the same underlying memory size. Throws SuzumeError after destroy().
destroy()
Releases this analyzer handle and its allocations. The shared WASM runtime remains cached for other and future instances.
destroy(): voidAfter destroy(), every member that needs the handle (analyze, analyzeWithNormalizedText, generateTags, the dictionary methods, mode, dictionaryWarnings, hasCoreDictionary, wasmMemoryBytes) throws a SuzumeError with code InvalidInput and the message Suzume instance has been released. destroy() itself is idempotent. Call it explicitly when you are done with an instance. See Memory Management for what happens if you do not.
Example:
const suzume = await Suzume.create()
// ... use suzume ...
suzume.destroy() // Free resources immediatelyMorpheme Interface
Represents a single linguistic token.
interface Morpheme {
readonly surface: string // Surface form (as appears in text)
readonly pos: PosLabel // Part of speech (English)
readonly baseForm: string // Base form
readonly posJa: string // Part of speech (Japanese)
readonly conjType: string | null // Conjugation type; null if none applies
readonly conjForm: string | null // Conjugation form; null if not conjugatable
readonly extendedPos: string // Stable extended POS code (e.g. "VERB_連用")
readonly start: number // Start Unicode code-point offset in normalized text
readonly end: number // End Unicode code-point offset in normalized text
readonly startUtf16: number // Start JavaScript UTF-16 offset
readonly endUtf16: number // End JavaScript UTF-16 offset
readonly isUserDict: boolean
readonly isFormalNoun: boolean
readonly isLowInfo: boolean
readonly isUnknown: boolean
readonly isFromDictionary: boolean
readonly score: number
}Properties
| Property | Type | Description | Example |
|---|---|---|---|
surface | string | Surface form as it appears in text | "食べ" |
pos | PosLabel | Part of speech in English | "VERB" |
baseForm | string | Base form | "食べる" |
posJa | string | Part of speech in Japanese | "動詞" |
conjType | string | null | Conjugation type | "一段" |
conjForm | string | null | Conjugation form | "連用形" |
extendedPos | string | Stable extended POS code | "VERB_連用" |
start | number | Start Unicode code-point offset in normalized text | 0 |
end | number | End Unicode code-point offset in normalized text | 2 |
startUtf16 | number | Start JavaScript UTF-16 offset in normalized text | 0 |
endUtf16 | number | End JavaScript UTF-16 offset in normalized text | 2 |
isUserDict | boolean | True when matched from a user dictionary | false |
isFormalNoun | boolean | True for formal nouns such as こと and もの | false |
isLowInfo | boolean | True when marked as low information for tag generation | false |
isUnknown | boolean | True when generated as an unknown-word candidate | true |
isFromDictionary | boolean | True when matched from any dictionary | false |
score | number | Cost the analyzer assigned to the token; lower is more likely, and values are not comparable across inputs | -0.17 |
conjType and conjForm are null for tokens that do not conjugate (nouns, particles). They can also be null or partly filled for tokens that do: conjForm may be set while conjType is null, as for the adjective 美しかっ (conjForm 連用形) or the auxiliary いる in 見ている (AUX_継続, conjForm 終止形). Treat a null conjType as "no conjugation type available", not as "does not conjugate"; use pos, extendedPos, and conjForm to judge the form.
Part-of-Speech Values
PosLabel is the union of the coarse pos values, and is the type of both Morpheme.pos and Tag.pos. The coarse and extended label tables, shared by every binding, are on Part-of-Speech Labels.
Error Handling
Every error the package throws is a SuzumeError, which extends Error. It carries a stable code, the operation that raised it, and, when it wraps another error, a cause. Native failures keep the library's own message text; the package adds no prefix.
const ErrorCode = {
Success: 0,
InvalidUtf8: 1,
DictionaryLoadFailed: 2,
FileNotFound: 3,
Parse: 4,
OutOfMemory: 5,
InvalidInput: 6,
Internal: 7,
Unknown: 255,
} as const
type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]
class SuzumeError extends Error {
readonly code: ErrorCode
readonly operation?: SuzumeOperation
readonly cause?: unknown
constructor(
message: string,
code: number = ErrorCode.Internal,
options?: { operation?: SuzumeOperation; cause?: unknown },
)
}ErrorCode is a plain object plus a union type, so there is no reverse lookup from number to name; read error.code and compare it with the named constants. Values 0 to 7 mirror the C ABI; Unknown (255) is reserved for the binding, and any other number passed to the constructor becomes Unknown.
operation is one of the snake_case SuzumeOperation tokens shared with the other bindings: create, analyze, generate_tags, load_user_dictionary, load_binary_dictionary, clear_user_dictionaries, mode, version, dictionary_warnings, has_core_dictionary and wasm_memory_bytes. A setter carries its getter's token, so assigning an invalid mode reports mode.
import { ErrorCode, Suzume, SuzumeError } from '@libraz/suzume'
let suzume: Suzume | undefined
try {
suzume = await Suzume.create()
suzume.analyze('\uD800') // unpaired UTF-16 surrogate
} catch (error) {
if (error instanceof SuzumeError && error.code === ErrorCode.InvalidInput) {
console.error(error.operation, error.message)
// analyze invalid text: contains an unpaired surrogate
}
} finally {
suzume?.destroy()
}| Situation | Result |
|---|---|
Invalid option or argument: unknown mode or POS name, a size outside its range, a non-boolean flag, bad scorerOptions, a non-string text, a dictionary that is neither a string nor a Uint8Array, or text with an unpaired UTF-16 surrogate (dictionary text and the keys and string values of scorerOptions included) | Throws SuzumeError with InvalidInput; the message names the option and the accepted values, for example invalid text: 123 (expected a string) |
Native failure in Suzume.create(), analyze(), analyzeWithNormalizedText(), generateTags(), the dictionary methods, mode changes, or clearUserDictionaries() | Throws SuzumeError with the native code and text |
| WASM module fails to load | Suzume.create() or version() rejects with SuzumeError (Internal, operation create or version); the loader error is the cause |
Method that needs a live handle, called after destroy() | Throws SuzumeError with InvalidInput and the message Suzume instance has been released |
instanceof SuzumeError also catches option errors, so check code to tell a caller mistake from a native failure.
When a call has more than one problem, the error reported is the first in this order: a released instance, then the text, then the options in the row order of the SuzumeOptions and TagOptions tables.
WebAssembly out-of-memory behavior
An allocation failure aborts the WASM runtime instead of returning a normal OutOfMemory result. It does not follow the catchable SuzumeError path, and the affected runtime cannot be reused. Because instances share a runtime by default, an abort also invalidates the other handles on that runtime. Process long documents in chunks, and use freshWasmModule: true when failure isolation is required.
Memory Management
Suzume allocates its memory in WebAssembly linear memory, outside the JavaScript heap; the figure under Shared WASM runtime shows which side the GC sees. In Node.js, V8 does not count that memory toward heap usage, so many undestroyed handles can grow memory use while the GC sees no pressure and the FinalizationRegistry cleanup is delayed. destroy() is the contract for releasing a handle; the FinalizationRegistry is only a backstop. Call it explicitly, especially in server-side code.
Every call on an instance is synchronous and runs to completion, so one instance can be shared freely within a JavaScript thread. A worker needs its own instance, since a WebAssembly module belongs to the thread that loaded it.
// Good: Clean up when done
const suzume = await Suzume.create()
try {
const result = suzume.analyze(text)
// process result...
} finally {
suzume.destroy()
}
// For long-running apps: reuse the instance
class MyApp {
private suzume: Suzume | null = null
async init() {
this.suzume = await Suzume.create()
}
analyze(text: string) {
return this.suzume?.analyze(text) ?? []
}
dispose() {
this.suzume?.destroy()
this.suzume = null
}
}