UNPKG

messageformat

Version:

Intl.MessageFormat / Unicode MessageFormat 2 parser, runtime and polyfill

60 lines (59 loc) 2.05 kB
import { MessageFunctionError } from "../errors.js"; import { getValueSource, resolveValue } from "./resolve-value.js"; export class MessageFunctionContext { #ctx; #litKeys; #source; dir; id; constructor(ctx, source, options) { this.#ctx = ctx; this.#source = source; this.dir = undefined; const dirOpt = options && Object.hasOwn(options, 'u:dir') ? options['u:dir'] : undefined; if (dirOpt) { const dir = String(resolveValue(ctx, dirOpt)); if (dir === 'ltr' || dir === 'rtl' || dir === 'auto') { this.dir = dir; } else if (dir !== 'inherit') { const error = new MessageFunctionError('bad-option', 'Unsupported value for u:dir option'); error.source = getValueSource(dirOpt); ctx.onError(error); } } const idOpt = options && Object.hasOwn(options, 'u:id') ? options['u:id'] : undefined; this.id = idOpt ? String(resolveValue(ctx, idOpt)) : undefined; if (options) { this.#litKeys = new Set(); for (const [key, value] of Object.entries(options)) { if (value.type === 'literal') this.#litKeys.add(key); } } } get literalOptionKeys() { return new Set(this.#litKeys); } get localeMatcher() { return this.#ctx.localeMatcher; } get locales() { return this.#ctx.locales.map(String); } onError(error, message) { let mfError; if (error instanceof MessageFunctionError) { mfError = error; } else if (typeof error === 'string' && typeof message === 'string') { mfError = new MessageFunctionError(error, message); } else { mfError = new MessageFunctionError('function-error', String(error)); mfError.cause = error; } mfError.source = this.#source; this.#ctx.onError(mfError); } }