Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 38207eb618 | |||
| 1352e69895 | |||
| 1b05af09fb | |||
| 32c61fff42 | |||
| df517b6078 | |||
| 1e54ee57a1 | |||
| b6f8da512c | |||
| 9cf86f4be1 | |||
| 2240c93db5 | |||
| 3e9052c4a7 |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.27.12",
|
||||
"version": "0.28.0",
|
||||
"description": "Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -19,6 +19,7 @@ export * from './path-events';
|
||||
export * from './promise-progress';
|
||||
export * from './search';
|
||||
export * from './string';
|
||||
export * from './template';
|
||||
export * from './time';
|
||||
export * from './types';
|
||||
export * from 'var-persist';
|
||||
|
||||
@@ -40,6 +40,7 @@ export function PE(str: TemplateStringsArray, ...args: any[]) {
|
||||
* @param {TemplateStringsArray} str
|
||||
* @param {string} args
|
||||
* @return {string}
|
||||
* @constructor
|
||||
*/
|
||||
export function PES(str: TemplateStringsArray, ...args: any[]) {
|
||||
let combined = [];
|
||||
@@ -108,35 +109,21 @@ export class PathEvent {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check cache first
|
||||
if(PathEvent.pathEventCache.has(e)) {
|
||||
Object.assign(this, PathEvent.pathEventCache.get(e)!);
|
||||
return;
|
||||
}
|
||||
|
||||
let [p, method] = e.replaceAll(/\/{2,}/g, '/').split(':');
|
||||
let [p, method] = e.replaceAll(/(^|\/)\*+\/?$/g, '').split(':');
|
||||
if(!method) method = '*';
|
||||
|
||||
// Handle special cases
|
||||
if(p === '' || p === undefined) {
|
||||
// Empty string matches nothing
|
||||
this.module = '';
|
||||
this.path = '';
|
||||
this.fullPath = '';
|
||||
this.name = '';
|
||||
this.methods = new ASet<Method>(['n']);
|
||||
this.hasGlob = false;
|
||||
PathEvent.pathEventCache.set(e, this);
|
||||
return;
|
||||
}
|
||||
|
||||
if(p === '*') {
|
||||
// Wildcard means any path any event
|
||||
if(p === '' || p === undefined || p === '*') {
|
||||
this.module = '';
|
||||
this.path = '';
|
||||
this.fullPath = '**';
|
||||
this.name = '';
|
||||
this.methods = new ASet<Method>(['*']);
|
||||
this.methods = new ASet<Method>(p === '*' ? ['*'] : <any>method.split(''));
|
||||
this.hasGlob = true;
|
||||
PathEvent.pathEventCache.set(e, this);
|
||||
return;
|
||||
@@ -147,17 +134,74 @@ export class PathEvent {
|
||||
this.path = temp.join('/');
|
||||
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
|
||||
this.name = temp.pop() || '';
|
||||
|
||||
// Don't trim /** - it's needed for glob matching to work properly
|
||||
// Only trim if there's something after it which won't happen with our parsing
|
||||
|
||||
this.hasGlob = this.fullPath.includes('*');
|
||||
this.methods = new ASet(<any>method.split(''));
|
||||
|
||||
// Store in cache
|
||||
PathEvent.pathEventCache.set(e, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a filter pattern matches a target path
|
||||
* @private
|
||||
*/
|
||||
private static matches(pattern: PathEvent, target: PathEvent): boolean {
|
||||
const methodsMatch = pattern.all || target.all || pattern.methods.intersection(target.methods).length > 0;
|
||||
if(!methodsMatch) return false;
|
||||
if(!pattern.hasGlob && !target.hasGlob) {
|
||||
const last = pattern.fullPath[target.fullPath.length];
|
||||
return pattern.fullPath.startsWith(target.fullPath) && (last == null || last == '/');
|
||||
}
|
||||
if(pattern.hasGlob) return this.pathMatchesGlob(target.fullPath, pattern.fullPath);
|
||||
return this.pathMatchesGlob(pattern.fullPath, target.fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path matches a glob pattern
|
||||
* @private
|
||||
*/
|
||||
private static pathMatchesGlob(path: string, pattern: string): boolean {
|
||||
if(pattern === path) return true;
|
||||
const pathParts = path.split('/').filter(p => !!p);
|
||||
const patternParts = pattern.split('/').filter(p => !!p);
|
||||
|
||||
let pathIdx = 0;
|
||||
let patternIdx = 0;
|
||||
while (patternIdx < patternParts.length && pathIdx < pathParts.length) {
|
||||
const patternPart = patternParts[patternIdx];
|
||||
if(patternPart === '**') {
|
||||
if(patternIdx === patternParts.length - 1) return true;
|
||||
while (pathIdx < pathParts.length) {
|
||||
if(PathEvent.pathMatchesGlob(pathParts.slice(pathIdx).join('/'), patternParts.slice(patternIdx + 1).join('/'))) return true;
|
||||
pathIdx++;
|
||||
}
|
||||
return false;
|
||||
} else if(patternPart === '*') {
|
||||
pathIdx++;
|
||||
patternIdx++;
|
||||
} else {
|
||||
if(patternPart !== pathParts[pathIdx]) return false;
|
||||
pathIdx++;
|
||||
patternIdx++;
|
||||
}
|
||||
}
|
||||
if(patternIdx < patternParts.length) return patternParts.slice(patternIdx).every(p => p === '**');
|
||||
return pathIdx === pathParts.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Score a path for specificity ranking (lower = more specific = higher priority)
|
||||
* @private
|
||||
*/
|
||||
private static scoreSpecificity(path: string): number {
|
||||
if(path === '**' || path === '') return Number.MAX_SAFE_INTEGER;
|
||||
const segments = path.split('/').filter(p => !!p);
|
||||
let score = -segments.length;
|
||||
segments.forEach(seg => {
|
||||
if(seg === '**') score += 0.5;
|
||||
else if(seg === '*') score += 0.25;
|
||||
});
|
||||
return score;
|
||||
}
|
||||
|
||||
/** Clear the cache of all PathEvents */
|
||||
static clearCache(): void {
|
||||
PathEvent.pathEventCache.clear();
|
||||
@@ -168,82 +212,6 @@ export class PathEvent {
|
||||
PathEvent.permissionCache.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Score a path for specificity ranking (lower = more specific = higher priority)
|
||||
* @private
|
||||
*/
|
||||
private static scoreSpecificity(path: string): number {
|
||||
if (path === '**' || path === '') return Number.MAX_SAFE_INTEGER; // Least specific
|
||||
|
||||
const segments = path.split('/').filter(p => !!p);
|
||||
// Base score: number of segments (more segments = more specific = lower score)
|
||||
let score = -segments.length;
|
||||
|
||||
// Penalty for wildcards (makes them less specific than exact matches)
|
||||
// ADD to score to make it HIGHER/WORSE
|
||||
segments.forEach(seg => {
|
||||
if (seg === '**') score += 0.5;
|
||||
else if (seg === '*') score += 0.25;
|
||||
});
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path matches a glob pattern
|
||||
* @private
|
||||
*/
|
||||
private static pathMatchesGlob(path: string, pattern: string): boolean {
|
||||
// Handle exact match
|
||||
if (pattern === path) return true;
|
||||
|
||||
const pathParts = path.split('/').filter(p => !!p);
|
||||
const patternParts = pattern.split('/').filter(p => !!p);
|
||||
|
||||
let pathIdx = 0;
|
||||
let patternIdx = 0;
|
||||
|
||||
while (patternIdx < patternParts.length && pathIdx < pathParts.length) {
|
||||
const patternPart = patternParts[patternIdx];
|
||||
|
||||
if (patternPart === '**') {
|
||||
// ** matches zero or more path segments
|
||||
if (patternIdx === patternParts.length - 1) {
|
||||
// ** at the end matches everything
|
||||
return true;
|
||||
}
|
||||
// Try matching from next pattern part onwards
|
||||
const nextPattern = patternParts[patternIdx + 1];
|
||||
while (pathIdx < pathParts.length) {
|
||||
if (PathEvent.pathMatchesGlob(pathParts.slice(pathIdx).join('/'), patternParts.slice(patternIdx + 1).join('/'))) {
|
||||
return true;
|
||||
}
|
||||
pathIdx++;
|
||||
}
|
||||
return false;
|
||||
} else if (patternPart === '*') {
|
||||
// * matches exactly one segment
|
||||
pathIdx++;
|
||||
patternIdx++;
|
||||
} else {
|
||||
// Exact match required
|
||||
if (patternPart !== pathParts[pathIdx]) {
|
||||
return false;
|
||||
}
|
||||
pathIdx++;
|
||||
patternIdx++;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we've consumed all pattern parts
|
||||
if (patternIdx < patternParts.length) {
|
||||
// Remaining pattern parts must all be ** to match
|
||||
return patternParts.slice(patternIdx).every(p => p === '**');
|
||||
}
|
||||
|
||||
return pathIdx === pathParts.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
|
||||
* combined until a "none" is reached
|
||||
@@ -253,32 +221,22 @@ export class PathEvent {
|
||||
*/
|
||||
static combine(...paths: (string | PathEvent)[]): PathEvent {
|
||||
const parsed = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p));
|
||||
|
||||
// Sort by specificity: lower score = more specific = higher priority
|
||||
const sorted = parsed.toSorted((p1, p2) => {
|
||||
const score1 = PathEvent.scoreSpecificity(p1.fullPath);
|
||||
const score2 = PathEvent.scoreSpecificity(p2.fullPath);
|
||||
return score1 - score2;
|
||||
});
|
||||
|
||||
let result: PathEvent | null = null;
|
||||
|
||||
for (const p of sorted) {
|
||||
if(!result) {
|
||||
result = p;
|
||||
} else {
|
||||
// Only combine if current result's path starts with or matches the new permission's path
|
||||
if(result.fullPath.startsWith(p.fullPath)) {
|
||||
// If we hit a none at a parent level, stop here
|
||||
if (p.none) {
|
||||
break;
|
||||
}
|
||||
// Combine methods for permissions in the same hierarchy
|
||||
if(p.none) break;
|
||||
result.methods = new ASet([...result.methods, ...p.methods]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result || new PathEvent('');
|
||||
}
|
||||
|
||||
@@ -292,39 +250,7 @@ export class PathEvent {
|
||||
static filter(target: string | PathEvent | (string | PathEvent)[], ...filter: (string | PathEvent)[]): PathEvent[] {
|
||||
const parsedTarget = makeArray(target).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
|
||||
const parsedFilter = makeArray(filter).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
|
||||
|
||||
return parsedTarget.filter(t => {
|
||||
const combined = PathEvent.combine(t);
|
||||
return !!parsedFilter.find(r => PathEvent.matches(r, combined));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a filter pattern matches a target path
|
||||
* @private
|
||||
*/
|
||||
private static matches(pattern: PathEvent, target: PathEvent): boolean {
|
||||
// Handle special cases
|
||||
if (pattern.fullPath === '' || target.fullPath === '') return false;
|
||||
if (pattern.fullPath === '*' || target.fullPath === '*') return pattern.methods.has('*') || target.methods.has('*') || pattern.methods.intersection(target.methods).length > 0;
|
||||
|
||||
// Check methods
|
||||
const methodsMatch = pattern.all || target.all || pattern.methods.intersection(target.methods).length > 0;
|
||||
if (!methodsMatch) return false;
|
||||
|
||||
// Check paths
|
||||
if (!pattern.hasGlob && !target.hasGlob) {
|
||||
// Fast path: no globs, use string comparison
|
||||
return pattern.fullPath === target.fullPath;
|
||||
}
|
||||
|
||||
if (pattern.hasGlob) {
|
||||
// Pattern has glob, match target against it
|
||||
return this.pathMatchesGlob(target.fullPath, pattern.fullPath);
|
||||
}
|
||||
|
||||
// Target has glob but pattern doesn't - pattern must match within target's glob range
|
||||
return this.pathMatchesGlob(pattern.fullPath, target.fullPath);
|
||||
return parsedTarget.filter(t => !!parsedFilter.find(r => PathEvent.matches(r, t)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -337,11 +263,7 @@ export class PathEvent {
|
||||
static has(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean {
|
||||
const parsedTarget = makeArray(target).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
|
||||
const parsedRequired = makeArray(has).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
|
||||
|
||||
// If target is a single item, check directly; if multiple, combine first
|
||||
const effectiveTarget = parsedTarget.length === 1 ? parsedTarget[0] : PathEvent.combine(...parsedTarget);
|
||||
|
||||
return !!parsedRequired.find(r => PathEvent.matches(r, effectiveTarget));
|
||||
return !!parsedRequired.find(r => !!parsedTarget.find(t => PathEvent.matches(r, t)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
116
src/template.ts
Normal file
116
src/template.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import {BadRequestError} from './errors.ts';
|
||||
import {dotNotation} from './objects.ts';
|
||||
import {matchAll} from './string.ts';
|
||||
import {formatDate} from './time.ts';
|
||||
|
||||
export class TemplateError extends BadRequestError { }
|
||||
|
||||
export function findTemplateVars(html: string): Record<string, any> {
|
||||
const variables = new Set<string>();
|
||||
const regex = /\{\{\s*([^<>\*\?!/}\s][^}]*?)\s*}}/g;
|
||||
let match;
|
||||
|
||||
while ((match = regex.exec(html)) !== null) {
|
||||
const code = match[1].trim();
|
||||
const varMatch = code.match(/^([a-zA-Z_$][a-zA-Z0-9_$.]*)/);
|
||||
if (varMatch) variables.add(varMatch[1]);
|
||||
}
|
||||
|
||||
const result: Record<string, any> = {};
|
||||
for (const path of variables) {
|
||||
const parts = path.split('.');
|
||||
let current = result;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
if (i === parts.length - 1) {
|
||||
current[part] = '';
|
||||
} else {
|
||||
current[part] = current[part] || {};
|
||||
current = current[part];
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function renderTemplate(template: string, data: any, fetch?: (file: string) => Promise<string>) {
|
||||
let content = template, found: any;
|
||||
const now = new Date(), d = {
|
||||
date: {
|
||||
day: now.getDate(),
|
||||
month: now.toLocaleString('default', { month: 'long' }),
|
||||
year: now.getFullYear(),
|
||||
time: now.toLocaleTimeString(),
|
||||
format: formatDate
|
||||
},
|
||||
...(data || {}),
|
||||
};
|
||||
if(!fetch) fetch = (file) => { throw new TemplateError(`Unable to fetch template: ${file}`); }
|
||||
const evaluate = (code: string, data: object, fatal = true) => {
|
||||
try {
|
||||
return Function('data', `with(data) { return ${code}; }`)(data);
|
||||
} catch {
|
||||
if(fatal) throw new TemplateError(`Failed to evaluate: ${code}`);
|
||||
else return false;
|
||||
}
|
||||
}
|
||||
|
||||
// If Statements - Optimize what we render: `{{ ? javascript }} IF TRUE CONTENT {{ !? javascript }} ELSE-IF CONTENT {{ !? }} ELSE FALSE CONTENT {{ /? }}`
|
||||
while(!!(found = /\{\{\s*?\?\s*?(.+?)\s*?}}([\s\S]*?)\{\{\s*?\/\?\s*?}}/g.exec(content))) {
|
||||
const nested = matchAll(found[0], /\{\{\s*?\?.+?}}/g).slice(-1)?.[0]?.index;
|
||||
if(nested != 0) found = /\{\{\s*?\?\s*?(.+?)\s*?}}([\s\S]*?)\{\{\s*?\/\?\s*?}}/g.exec(content.slice(found.index + nested))
|
||||
const parts = found[2].split(/\{\{\s*?!\?\s*?/);
|
||||
let result = evaluate(found[1], d, false) ? parts[0] : '';
|
||||
if (!result) {
|
||||
for (let i = 1; i < parts.length; i++) {
|
||||
const [cond, body] = parts[i].split(/}}/);
|
||||
if (!cond.trim()) {
|
||||
result = body || '';
|
||||
break;
|
||||
}
|
||||
if (evaluate(cond, d, false)) {
|
||||
result = body || '';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
content = content.replace(found[0], result);
|
||||
}
|
||||
|
||||
// Imports - We render bottom up: `{{ < file.html }}`
|
||||
while(!!(found = /\{\{\s*?<\s*?(.+?)\s*?}}/g.exec(content))) {
|
||||
const t = await fetch(found[1].trim());
|
||||
if(!t) throw new TemplateError(`Unknown imported template: ${found[1].trim()}`);
|
||||
content = content.replace(found[0], await renderTemplate(t, d, fetch));
|
||||
}
|
||||
|
||||
// For Loops: `{{ * (row, index) in invoice }} CONTENT {{ /* }}`
|
||||
while(!!(found = /\{\{\s*?\*\s*?(.+?)\s+in\s+(.+?)\s*?}}([\s\S]*?)\{\{\s*?\/\*\s*?}}/g.exec(content))) {
|
||||
const split = found[1].replaceAll(/[()\s]/g, '').split(',');
|
||||
const element = split[0];
|
||||
const index = split[1] || 'index';
|
||||
const array: any[] = <any>dotNotation(d, found[2]);
|
||||
if(!array || typeof array != 'object') throw new TemplateError(`Cannot iterate: ${found[2]}`);
|
||||
let compiled = [];
|
||||
for(let i = 0; i < array.length; i++)
|
||||
compiled.push(await renderTemplate(found[3], {...d, [element]: array[i], [index]: i}, fetch));
|
||||
content = content.replace(found[0], compiled.join('\n'));
|
||||
}
|
||||
|
||||
// Evaluate whatever is left - Should come last: `{{ javascript }}`
|
||||
while(!!(found = /\{\{\s*([^<>\*\?!/}\s][^}]*?)\s*}}/g.exec(content))) {
|
||||
content = content.replace(found[0], evaluate(found[1].trim(), d) ?? '');
|
||||
}
|
||||
|
||||
// Extends: `{{ > file.html:property }} CONTENT {{ /> }}`
|
||||
while(!!(found = /\{\{\s*?>\s*?(.+?):(.+?)\s*?}}([\s\S]*?)\{\{\s*?\/>\s*?}}/g.exec(content))) {
|
||||
const t = await fetch(found[1].trim());
|
||||
if(!t) throw new TemplateError(`Unknown extended templated: ${found[1].trim()}`);
|
||||
content = content.replace(found[0], await renderTemplate(t, {
|
||||
...d,
|
||||
[found[2].trim()]: found[3],
|
||||
}, fetch));
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
@@ -48,10 +48,9 @@ describe('Path Events', () => {
|
||||
expect(pe.hasAll('module:c', 'some/path:ud')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('parses empty string as none', () => {
|
||||
it('parses empty string as wildcard', () => {
|
||||
const pe = new PathEvent('');
|
||||
expect(pe.none).toBe(true);
|
||||
expect(pe.fullPath).toBe('');
|
||||
expect(pe.has('any/path:c')).toBe(true);
|
||||
});
|
||||
|
||||
it('parses none method', () => {
|
||||
@@ -61,6 +60,10 @@ describe('Path Events', () => {
|
||||
expect(pe.none).toBe(false);
|
||||
});
|
||||
|
||||
it('Test several wild card perms', () => {
|
||||
expect(PathEvent.has(['actions:*', 'groups:*', 'users:*'], 'groups/AUTH:r')).toBe(true);
|
||||
});
|
||||
|
||||
it('setters for methods', () => {
|
||||
const pe = new PathEvent('users/system:r');
|
||||
pe.create = true;
|
||||
@@ -81,6 +84,7 @@ describe('Path Events', () => {
|
||||
expect(c.methods.has('c')).toBe(true);
|
||||
expect(c.methods.has('r')).toBe(true);
|
||||
expect(c.methods.has('u')).toBe(true);
|
||||
expect(c.delete).toBe(false);
|
||||
});
|
||||
|
||||
it('combine stops at none', () => {
|
||||
@@ -95,6 +99,17 @@ describe('Path Events', () => {
|
||||
expect(d.none).toBe(false);
|
||||
});
|
||||
|
||||
it('combine works with wildcards', () => {
|
||||
expect(PathEvent.has([
|
||||
'payments/anonymous:d',
|
||||
'payments/anonymous:c',
|
||||
'payments/system:cr',
|
||||
'logs/Momentum:c',
|
||||
'products:r',
|
||||
'*'
|
||||
], 'actions/692a92d18afa11e6722e9f2e:r')).toBe(true);
|
||||
});
|
||||
|
||||
it('filter finds overlap by path and methods', () => {
|
||||
const events = [
|
||||
new PathEvent('users/sys:cr'),
|
||||
|
||||
132
tests/templates.spec.ts
Normal file
132
tests/templates.spec.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { renderTemplate, TemplateError } from '../src';
|
||||
|
||||
describe('renderTemplate', () => {
|
||||
test('basic variable interpolation', async () => {
|
||||
const result = await renderTemplate('Hello {{ name }}!', { name: 'World' });
|
||||
expect(result).toBe('Hello World!');
|
||||
});
|
||||
|
||||
test('nested object access', async () => {
|
||||
const result = await renderTemplate('{{ user.name }} is {{ user.age }}', {
|
||||
user: { name: 'Alice', age: 25 }
|
||||
});
|
||||
expect(result).toBe('Alice is 25');
|
||||
});
|
||||
|
||||
test('method calls', async () => {
|
||||
const result = await renderTemplate('{{ price.toFixed(2) }}', { price: 9.5 });
|
||||
expect(result).toBe('9.50');
|
||||
});
|
||||
|
||||
test('if statement true', async () => {
|
||||
const result = await renderTemplate('{{ ? active }}YES{{ /? }}', { active: true });
|
||||
expect(result).toBe('YES');
|
||||
});
|
||||
|
||||
test('if statement false', async () => {
|
||||
const result = await renderTemplate('{{ ? active }}YES{{ /? }}', { active: false });
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
test('if-else', async () => {
|
||||
const result = await renderTemplate('{{ ? active }}YES{{ !? }}NO{{ /? }}', { active: false });
|
||||
expect(result).toBe('NO');
|
||||
});
|
||||
|
||||
test('if-elseif-else', async () => {
|
||||
const tpl = '{{ ? status == "paid" }}PAID{{ !? status == "pending" }}PENDING{{ !? }}OTHER{{ /? }}';
|
||||
expect(await renderTemplate(tpl, { status: 'paid' })).toBe('PAID');
|
||||
expect(await renderTemplate(tpl, { status: 'pending' })).toBe('PENDING');
|
||||
expect(await renderTemplate(tpl, { status: 'failed' })).toBe('OTHER');
|
||||
});
|
||||
|
||||
test('nested if statements', async () => {
|
||||
const tpl = '{{ ? a }}A{{ ? b }}B{{ /? }}{{ /? }}';
|
||||
expect(await renderTemplate(tpl, { a: true, b: true })).toBe('AB');
|
||||
expect(await renderTemplate(tpl, { a: true, b: false })).toBe('A');
|
||||
expect(await renderTemplate(tpl, { a: false, b: true })).toBe('');
|
||||
});
|
||||
|
||||
test('for loop', async () => {
|
||||
const tpl = '{{ * item in items }}{{ item }}{{ /* }}';
|
||||
const result = await renderTemplate(tpl, { items: ['a', 'b', 'c'] });
|
||||
expect(result).toBe('a\nb\nc');
|
||||
});
|
||||
|
||||
test('for loop with index', async () => {
|
||||
const tpl = '{{ * (item, i) in items }}{{ i }}:{{ item }}{{ /* }}';
|
||||
const result = await renderTemplate(tpl, { items: ['a', 'b'] });
|
||||
expect(result).toBe('0:a\n1:b');
|
||||
});
|
||||
|
||||
test('for loop with objects', async () => {
|
||||
const tpl = '{{ * user in users }}{{ user.name }}{{ /* }}';
|
||||
const result = await renderTemplate(tpl, {
|
||||
users: [{ name: 'Alice' }, { name: 'Bob' }]
|
||||
});
|
||||
expect(result).toBe('Alice\nBob');
|
||||
});
|
||||
|
||||
test('for loop error on non-array', async () => {
|
||||
await expect(
|
||||
renderTemplate('{{ * x in notArray }}{{ x }}{{ /* }}', { notArray: 'string' })
|
||||
).rejects.toThrow(TemplateError);
|
||||
});
|
||||
|
||||
test('import template', async () => {
|
||||
const fetch = async (file: string) => {
|
||||
if (file === 'header.html') return 'HEADER: {{ title }}';
|
||||
throw new Error('Not found');
|
||||
};
|
||||
const result = await renderTemplate('{{ < header.html }}', { title: 'Test' }, fetch);
|
||||
expect(result).toBe('HEADER: Test');
|
||||
});
|
||||
|
||||
test('import template error', async () => {
|
||||
await expect(
|
||||
renderTemplate('{{ < missing.html }}', {})
|
||||
).rejects.toThrow(TemplateError);
|
||||
});
|
||||
|
||||
test('extend template', async () => {
|
||||
const fetch = async (file: string) => {
|
||||
if (file === 'layout.html') return '<div>{{ content }}</div>';
|
||||
throw new Error('Not found');
|
||||
};
|
||||
const result = await renderTemplate('{{ > layout.html:content }}Hello{{ /> }}', {}, fetch);
|
||||
expect(result).toBe('<div>Hello</div>');
|
||||
});
|
||||
|
||||
test('date object', async () => {
|
||||
const result = await renderTemplate('{{ date.year }}', {});
|
||||
expect(result).toBe(new Date().getFullYear().toString());
|
||||
});
|
||||
|
||||
test('evaluation error', async () => {
|
||||
await expect(
|
||||
renderTemplate('{{ undefined.property }}', {})
|
||||
).rejects.toThrow(TemplateError);
|
||||
});
|
||||
|
||||
test('complex nested example', async () => {
|
||||
const tpl = `
|
||||
{{ ? items.length > 0 }}
|
||||
{{ * (item, i) in items }}
|
||||
{{ i + 1 }}. {{ item.name }}: \${{ item.price.toFixed(2) }}
|
||||
{{ /* }}
|
||||
Total: \${{ total.toFixed(2) }}
|
||||
{{ !? }}
|
||||
No items
|
||||
{{ /? }}`;
|
||||
const result = await renderTemplate(tpl, {
|
||||
items: [
|
||||
{ name: 'A', price: 10 },
|
||||
{ name: 'B', price: 20 }
|
||||
],
|
||||
total: 30
|
||||
});
|
||||
expect(result.trim()).toContain('1. A: $10.00');
|
||||
expect(result.trim()).toContain('2. B: $20.00');
|
||||
expect(result.trim()).toContain('Total: $30.00');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user