@messageformat/icu-messageformat-1
Version:
Compile ICU MessageFormat 1 sources into MessageFormat 2 formatters
37 lines (36 loc) • 1.48 kB
JavaScript
import { MessageError, visit } from 'messageformat';
import { DefaultFunctions } from 'messageformat/functions';
import { MF1Functions } from "./functions.js";
/**
* Ensure that the `msg` data model does not contain any unsupported MF1 argType or argStyle references,
* calling `onError` on errors.
* If `onError` is not defined, a {@link MessageError} will be thrown on error.
*/
export function mf1Validate(msg, onError = (type, expr) => {
const argTypeAttr = expr.attributes?.get('mf1:argType');
const argType = argTypeAttr && argTypeAttr !== true
? argTypeAttr.value
: expr.functionRef.name.replace('mf1:', '');
if (type === 'unknown-function') {
throw new MessageError(type, `Unsupported MF1 argType: ${argType}`);
}
else {
const opt = expr.functionRef.options.get('mf1:argStyle');
const argStyle = opt?.type === 'literal' ? opt.value : '�';
throw new MessageError(type, `Unsupported MF1 ${argType} argStyle: ${argStyle}`);
}
}) {
visit(msg, {
expression(expr) {
if (expr.functionRef) {
const name = expr.functionRef.name;
if (!(name in DefaultFunctions) && !(name in MF1Functions)) {
onError('unknown-function', expr);
}
if (expr.functionRef.options?.has('mf1:argStyle')) {
onError('unsupported-operation', expr);
}
}
}
});
}