lakutata
Version:
An IoC-based universal application framework.
56 lines (51 loc) • 1.62 kB
JavaScript
const e = e => e.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">");
function r(r, ...t) {
if (typeof r === "string") {
return e(r);
}
let n = r[0];
for (const [o, i] of t.entries()) {
n = n + e(String(i)) + r[o + 1];
}
return n;
}
class MissingValueError extends Error {
constructor(e) {
super(`Missing a value for ${e ? `the placeholder: ${e}` : "a placeholder"}`);
this.name = "MissingValueError";
this.key = e;
}
}
function t(e, t, {ignoreMissing: n = false, transform: o = ({value: e}) => e} = {}) {
if (typeof e !== "string") {
throw new TypeError(`Expected a \`string\` in the first argument, got \`${typeof e}\``);
}
if (typeof t !== "object") {
throw new TypeError(`Expected an \`object\` or \`Array\` in the second argument, got \`${typeof t}\``);
}
const i = (e, r) => {
let i = t;
for (const e of r.split(".")) {
i = i ? i[e] : undefined;
}
const s = o({
value: i,
key: r
});
if (s === undefined) {
if (n) {
return e;
}
throw new MissingValueError(r);
}
return String(s);
};
const s = e => (...t) => r(e(...t));
const a = /{{(\d+|[a-z$_][\w\-$]*?(?:\.[\w\-$]*?)*?)}}/gi;
if (a.test(e)) {
e = e.replace(a, s(i));
}
const c = /{(\d+|[a-z$_][\w\-$]*?(?:\.[\w\-$]*?)*?)}/gi;
return e.replace(c, i);
}
export { MissingValueError, t as Templating };