Registry / serialization / icu-messageformat-parser

icu-messageformat-parser

JSON →
library2.0.0jsnpmunverified

icu-messageformat-parser is a JavaScript library that provides a PEG.js-based parser for ICU MessageFormat strings. It transforms a given MessageFormat string into an Abstract Syntax Tree (AST), enabling programmatic manipulation or interpretation of localized messages. The current stable version is 4.0.0. New major versions are released periodically to introduce breaking changes, often related to stricter conformance with the ICU MessageFormat specification, and to expand parsing capabilities. Key differentiators include its robust AST output, configurable strictness options (e.g., for number signs and function parameters), and its role as a fundamental parsing component for internationalization workflows involving MessageFormat, prioritizing accurate parsing according to Unicode CLDR and ICU standards.

npm install icu-messageformat-parser
INSTALL
IMPORT
SIG · ICU-MESSAGEFORMAT-
I
icu-messageformat-parser
serializationjavascriptv2.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

parse
import { parse } from 'icu-messageformat-parser';
const parse = require('icu-messageformat-parser').parse; // or const parse = require('messageformat-parser').parse;
The `parse` function is the primary export. Since v3.0.0, the package is primarily designed for ESM. Attempting `require()` in an ESM context will fail. Older documentation might show `require('messageformat-parser')`, but the correct package name is `icu-messageformat-parser`.
AST Types
import type { Ast } from 'icu-messageformat-parser';
While explicit AST types are not directly shown in the README, if the package provides TypeScript definitions, common AST interfaces (e.g., `Ast`, `Argument`, `Plural` nodes) might be importable as types for enhanced type safety when working with the parsed output.
Default Export (hypothetical)
import parse from 'icu-messageformat-parser';
import { parse } from 'icu-messageformat-parser';
This package uses named exports. Attempting to import `parse` as a default export will result in `undefined` or a runtime error. The correct way is `import { parse } from '...'`. This entry serves as a common mistake pattern.

Demonstrates basic parsing, complex selectordinal statements, nested selects, and usage of options for plural key validation and strict mode for '#' parsing.

import { parse } from 'icu-messageformat-parser'; // Basic argument parsing console.log('Basic argument:', parse('So {wow}.')); // Expected output: [ 'So ', { type: 'argument', arg: 'wow' }, '.' ] // Complex selectordinal with octothorpe const selectOrdinalAst = parse( 'Such { thing }. { count, selectordinal, one {First} two {Second}' + ' few {Third} other {#th} } word.' ); console.log('Selectordinal AST:', selectOrdinalAst); // Nested select statements const nestedSelectAst = parse( 'Many{type,select,plural{ numbers}selectordinal{ counting}' + 'select{ choices}other{ some {type}}}.' ); console.log('Nested Select AST:', nestedSelectAst); // Example with options for plural key validation const msg = '{words, plural, zero{No words} one{One word} other{# words}}'; const englishKeys = { cardinal: [ 'one', 'other' ], ordinal: [ 'one', 'two', 'few', 'other' ] }; console.log('Parsed with default keys (zero is valid):', parse(msg)); try { // This will throw an error because 'zero' is not in englishKeys.cardinal parse(msg, englishKeys); } catch (error: any) { console.error('Error during parsing with strict keys for plurals:', error.message); } // Example demonstrating the `strict` option (replaces `strictNumberSign` in v4+) // In strict mode, '#' is only special inside plural/selectordinal contexts. const strictParse = parse('In plural, # is special. Outside, # is text.', { strict: true }); console.log('Strict parsing of #:', strictParse);
Debug
Known issues
breakingBackslash (`\`) escaping is no longer supported and will be parsed as literal text. This change was introduced to conform with the ICU MessageFormat standard.
fix
Replace backslash escapes with single quotes for literal text, e.g., `\{` should become `'{'`. A codemod was provided with v3.0.0 to assist with this migration.
affects: >=3.0.0
breakingThe `strictNumberSign` option has been replaced by a broader `strict` option.
fix
Replace `{ strictNumberSign: true }` with `{ strict: true }` in your parser options. The `strict` option now encompasses more strict parsing behaviors.
affects: >=4.0.0
breakingFunction parameters can now contain MessageFormat content, which changes how they are parsed and represented in the AST.
fix
Review code that processes function parameters from the AST, as their structure might have changed to accommodate nested MessageFormat elements. If you relied on parameters being simple strings, adjust your logic accordingly.
affects: >=4.0.0
gotchaThe `options` object for `cardinal` and `ordinal` rule keys validates plural and selectordinal keys. If a key used in the MessageFormat string is not present in the provided options (or the default CLDR keys if options are omitted), parsing will fail.
fix
Ensure that the `options` object, specifically `options.cardinal` and `options.ordinal`, contains all plural and selectordinal keys expected for your target locales. To disable this validation, pass an empty array for these options.
affects: >=1.0.0
gotchaThe `strictFunctionParams` option significantly changes how function parameters are parsed. By default, parameters are split by commas and trimmed. With `strictFunctionParams: true`, parameters are treated as a single, untrimmed string.
fix
Be explicit about the `strictFunctionParams` option. If you expect an array of trimmed strings, ensure this option is `false` (default). If you need the raw parameter string, set it to `true` and handle parsing manually.
affects: >=1.1.0
gotchaApostrophe escaping follows `DOUBLE_OPTIONAL` mode. Single apostrophes only quote literal text if preceded by `{}` or `#` (inside `plural`/`selectordinal` and depending on `strict` option). Otherwise, they are literal apostrophes.
fix
Always use double apostrophes (`''`) for a literal apostrophe within quoted text. For literal text that contains curly braces or `#`, enclose it in single quotes, e.g., `'{literal text}'`.
affects: >=2.0.0
Errors
Common errors & fixes
SyntaxError: Expected ",", "}" or [ \t\n\r] but "c" found.
The MessageFormat string contains a syntax error, such as an unclosed curly brace or incorrect argument format.
fix
Review the MessageFormat string for common syntax errors like `{Such compliance` missing a closing brace or incorrect separator characters. Ensure all arguments and elements are correctly formatted according to the ICU MessageFormat specification.
Error: Invalid key
A plural or selectordinal key (e.g., 'zero', 'one', 'few') used in the MessageFormat string is not present in the allowed keys specified in the parser options (or default CLDR keys).
fix
Check the `cardinal` and `ordinal` arrays in the parser `options` object. Ensure they contain all the plural rule keys used in your MessageFormat string for the target locale. If 'zero' is used but not listed in `options.cardinal`, it will cause this error.
ReferenceError: require is not defined
Attempting to use CommonJS `require()` syntax in an ES Module context.
fix
For versions 3.0.0 and above, use ES Module `import` syntax: `import { parse } from 'icu-messageformat-parser';`. If you are in a CommonJS environment, ensure your `package.json` does not have `"type": "module"` or configure your build system to correctly transpile.
TypeError: (0 , icu_messageformat_parser__WEBPACK_IMPORTED_MODULE_0__.parse) is not a function
Attempting to import `parse` as a default export when it is a named export, or module resolution issues in bundlers.
fix
Ensure you are using named import syntax: `import { parse } from 'icu-messageformat-parser';`. If using a bundler like Webpack or Rollup, verify its configuration for ES Module resolution and tree-shaking.
Upgrade
Version history
2.0.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
6
Resources