parser package

An AST parser for ICU MessageFormat strings

Example

import { parse } from '@messageformat/parser

parse('So {wow}.')
[ { type: 'content', value: 'So ' },
  { type: 'argument', arg: 'wow' },
  { type: 'content', value: '.' } ]


parse('Such { thing }. { count, selectordinal, one {First} two {Second}' +
      '                  few {Third} other {#th} } word.')
[ { type: 'content', value: 'Such ' },
  { type: 'argument', arg: 'thing' },
  { type: 'content', value: '. ' },
  { type: 'selectordinal',
    arg: 'count',
    cases: [
      { key: 'one', tokens: [ { type: 'content', value: 'First' } ] },
      { key: 'two', tokens: [ { type: 'content', value: 'Second' } ] },
      { key: 'few', tokens: [ { type: 'content', value: 'Third' } ] },
      { key: 'other',
        tokens: [ { type: 'octothorpe' }, { type: 'content', value: 'th' } ] }
    ] },
  { type: 'content', value: ' word.' } ]


parse('Many{type,select,plural{ numbers}selectordinal{ counting}' +
                         'select{ choices}other{ some {type}}}.')
[ { type: 'content', value: 'Many' },
  { type: 'select',
    arg: 'type',
    cases: [
      { key: 'plural', tokens: [ { type: 'content', value: 'numbers' } ] },
      { key: 'selectordinal', tokens: [ { type: 'content', value: 'counting' } ] },
      { key: 'select', tokens: [ { type: 'content', value: 'choices' } ] },
      { key: 'other',
        tokens: [ { type: 'content', value: 'some ' }, { type: 'argument', arg: 'type' } ] }
    ] },
  { type: 'content', value: '.' } ]


parse('{Such compliance')
// ParseError: invalid syntax at line 1 col 7:
//
//  {Such compliance
//        ^


const msg = '{words, plural, zero{No words} one{One word} other{# words}}'
parse(msg)
[ { type: 'plural',
    arg: 'words',
    cases: [
      { key: 'zero', tokens: [ { type: 'content', value: 'No words' } ] },
      { key: 'one', tokens: [ { type: 'content', value: 'One word' } ] },
      { key: 'other',
        tokens: [ { type: 'octothorpe' }, { type: 'content', value: ' words' } ] }
    ] } ]


parse(msg, { cardinal: [ 'one', 'other' ], ordinal: [ 'one', 'two', 'few', 'other' ] })
// ParseError: The plural case zero is not valid in this locale at line 1 col 17:
//
//   {words, plural, zero{
//                   ^

Classes

Class Description
ParseError Thrown by parse() on error

Functions

Function Description
parse(src, options) Parse an input string into an array of tokens

Interfaces

Interface Description
Content Text content of the message
Context The parsing context for a token
FunctionArg A placeholder for a mapped argument
Octothorpe Represents the # character
ParseOptions Options for the parser
PlainArg A simple placeholder
Select A selector between multiple variants
SelectCase A case within a Select

Type Aliases

Type Alias Description
PluralCategory One of the valid Unicode CLDR plural category keys