Compare commits

..

16 Commits

Author SHA1 Message Date
cabfc93773 Better template variable extraction
All checks were successful
Build / Publish Docs (push) Successful in 47s
Build / Build NPM Project (push) Successful in 1m9s
Build / Tag Version (push) Successful in 9s
2025-12-08 10:42:02 -05:00
38207eb618 Fixed missing export
All checks were successful
Build / Publish Docs (push) Successful in 42s
Build / Build NPM Project (push) Successful in 1m1s
Build / Tag Version (push) Successful in 9s
2025-12-08 10:07:20 -05:00
1352e69895 Added templating tests
All checks were successful
Build / Publish Docs (push) Successful in 53s
Build / Build NPM Project (push) Successful in 1m6s
Build / Tag Version (push) Successful in 9s
2025-12-08 10:03:38 -05:00
1b05af09fb Fixed templates
All checks were successful
Build / Publish Docs (push) Successful in 58s
Build / Build NPM Project (push) Successful in 1m15s
Build / Tag Version (push) Successful in 11s
2025-12-06 21:51:47 -05:00
32c61fff42 Fixed templates
All checks were successful
Build / Publish Docs (push) Successful in 1m14s
Build / Build NPM Project (push) Successful in 1m38s
Build / Tag Version (push) Successful in 11s
2025-12-06 21:34:21 -05:00
df517b6078 Fixed templates bleeding into each other between runs
All checks were successful
Build / Publish Docs (push) Successful in 43s
Build / Build NPM Project (push) Successful in 1m49s
Build / Tag Version (push) Successful in 8s
2025-12-06 19:45:38 -05:00
1e54ee57a1 Fixed imports
All checks were successful
Build / Publish Docs (push) Successful in 43s
Build / Build NPM Project (push) Successful in 1m2s
Build / Tag Version (push) Successful in 8s
2025-12-06 15:23:22 -05:00
b6f8da512c Added template helper
Some checks failed
Build / Build NPM Project (push) Failing after 35s
Build / Publish Docs (push) Failing after 33s
Build / Tag Version (push) Has been skipped
2025-12-06 15:20:51 -05:00
9cf86f4be1 Fixed path events
All checks were successful
Build / Publish Docs (push) Successful in 49s
Build / Build NPM Project (push) Successful in 1m4s
Build / Tag Version (push) Successful in 9s
2025-11-29 21:58:04 -05:00
2240c93db5 Fixed path events
All checks were successful
Build / Publish Docs (push) Successful in 48s
Build / Build NPM Project (push) Successful in 1m6s
Build / Tag Version (push) Successful in 9s
2025-11-29 20:03:45 -05:00
3e9052c4a7 Fixed path event has checks
All checks were successful
Build / Publish Docs (push) Successful in 1m1s
Build / Build NPM Project (push) Successful in 1m16s
Build / Tag Version (push) Successful in 8s
2025-11-29 11:27:47 -05:00
326f6fe851 removed docs submodule (not used)
All checks were successful
Build / Publish Docs (push) Successful in 43s
Build / Build NPM Project (push) Successful in 1m1s
Build / Tag Version (push) Successful in 9s
2025-11-29 10:45:59 -05:00
5b57b67542 Updates
Some checks failed
Build / Build NPM Project (push) Failing after 6s
Build / Publish Docs (push) Failing after 6s
Build / Tag Version (push) Has been skipped
2025-11-29 10:14:50 -05:00
bcc76c7561 Glob support and path scoring
All checks were successful
Build / Publish Docs (push) Successful in 43s
Build / Build NPM Project (push) Successful in 1m49s
Build / Tag Version (push) Successful in 8s
2025-11-27 20:48:04 -05:00
67c2e8c434 added execute support ot pathed events 2025-11-27 18:32:15 -05:00
c88d96bcfa Optimized deepCopy & fixed cache object bugs
All checks were successful
Build / Publish Docs (push) Successful in 35s
Build / Build NPM Project (push) Successful in 49s
Build / Tag Version (push) Successful in 8s
2025-11-18 14:03:17 -05:00
12 changed files with 677 additions and 131 deletions

1
.gitignore vendored
View File

@@ -9,6 +9,7 @@ node_modules
uploads uploads
public/momentum*js public/momentum*js
junit.xml junit.xml
/docs/
# Logs # Logs
*.log *.log

5
.gitmodules vendored
View File

@@ -1,5 +0,0 @@
[submodule "docs"]
path = docs
url = ../utils.wiki.git
branch = master
ignore = all

1
docs

Submodule docs deleted from dbf5d8cd07

View File

@@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.27.9", "version": "0.28.1",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",
@@ -30,15 +30,15 @@
"var-persist": "^1.0.1" "var-persist": "^1.0.1"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.12", "@types/jest": "^30.0.0",
"fake-indexeddb": "^6.0.1", "fake-indexeddb": "^6.2.5",
"jest": "^29.7.0", "jest": "^30.2.0",
"jest-junit": "^16.0.0", "jest-junit": "^16.0.0",
"ts-jest": "^29.1.2", "ts-jest": "^29.4.5",
"typedoc": "^0.26.7", "typedoc": "^0.28.15",
"typescript": "^5.3.3", "typescript": "^5.9.3",
"vite": "^5.0.12", "vite": "^7.2.4",
"vite-plugin-dts": "^4.5.3" "vite-plugin-dts": "^4.5.4"
}, },
"files": [ "files": [
"dist" "dist"

View File

@@ -85,6 +85,7 @@ export class Cache<K extends string | number | symbol, T> {
return <K>(value as any)[this.key]; return <K>(value as any)[this.key];
} }
/** Save item to storage */
private save(key?: K) { private save(key?: K) {
const persists: {storage: any, key: string} = <any>this.options.persistentStorage; const persists: {storage: any, key: string} = <any>this.options.persistentStorage;
if(!!persists?.storage) { if(!!persists?.storage) {
@@ -131,16 +132,13 @@ export class Cache<K extends string | number | symbol, T> {
const out: CachedValue<T>[] = []; const out: CachedValue<T>[] = [];
for(const v of this.store.values()) { for(const v of this.store.values()) {
const val: any = v; const val: any = v;
if(expired || !val?._expired) out.push(deepCopy<any>(val)); if(expired || !val?._expired) out.push(deepCopy(val));
} }
return out; return out;
} }
/** /**
* Add a new item to the cache. Like set, but finds key automatically * Add a new item to the cache. Like set, but finds key automatically
* @param {T} value Item to add to cache
* @param {number | undefined} ttl Override default expiry
* @return {this}
*/ */
add(value: T, ttl = this.ttl): this { add(value: T, ttl = this.ttl): this {
const key = this.getKey(value); const key = this.getKey(value);
@@ -150,9 +148,6 @@ export class Cache<K extends string | number | symbol, T> {
/** /**
* Add several rows to the cache * Add several rows to the cache
* @param {T[]} rows Several items that will be cached using the default key
* @param complete Mark cache as complete & reliable, defaults to true
* @return {this}
*/ */
addAll(rows: T[], complete = true): this { addAll(rows: T[], complete = true): this {
this.clear(); this.clear();
@@ -161,9 +156,7 @@ export class Cache<K extends string | number | symbol, T> {
return this; return this;
} }
/** /** Remove all keys */
* Remove all keys from cache
*/
clear(): this { clear(): this {
this.complete = false; this.complete = false;
for (const [k, t] of this.timers) clearTimeout(t); for (const [k, t] of this.timers) clearTimeout(t);
@@ -174,10 +167,7 @@ export class Cache<K extends string | number | symbol, T> {
return this; return this;
} }
/** /** Delete a cached item */
* Delete an item from the cache
* @param {K} key Item's primary key
*/
delete(key: K): this { delete(key: K): this {
this.clearTimer(key); this.clearTimer(key);
const idx = this.lruOrder.indexOf(key); const idx = this.lruOrder.indexOf(key);
@@ -187,23 +177,17 @@ export class Cache<K extends string | number | symbol, T> {
return this; return this;
} }
/** /** Return entries as array */
* Return cache as an array of key-value pairs
* @return {[K, T][]} Key-value pairs array
*/
entries(expired?: boolean): [K, CachedValue<T>][] { entries(expired?: boolean): [K, CachedValue<T>][] {
const out: [K, CachedValue<T>][] = []; const out: [K, CachedValue<T>][] = [];
for(const [k, v] of this.store.entries()) { for(const [k, v] of this.store.entries()) {
const val: any = v; const val: any = v;
if(expired || !val?._expired) out.push([k, deepCopy<any>(val)]); if(expired || !val?._expired) out.push([k, deepCopy(val)]);
} }
return out; return out;
} }
/** /** Manually expire a cached item */
* Manually expire a cached item
* @param {K} key Key to expire
*/
expire(key: K): this { expire(key: K): this {
this.complete = false; this.complete = false;
if(this.options.expiryPolicy == 'keep') { if(this.options.expiryPolicy == 'keep') {
@@ -217,39 +201,26 @@ export class Cache<K extends string | number | symbol, T> {
return this; return this;
} }
/** /** Find first matching item */
* Find the first cached item to match a filter
* @param {Partial<T>} filter Partial item to match
* @param {Boolean} expired Include expired items, defaults to false
* @returns {T | undefined} Cached item or undefined if nothing matched
*/
find(filter: Partial<T>, expired?: boolean): T | undefined { find(filter: Partial<T>, expired?: boolean): T | undefined {
for(const v of this.store.values()) { for(const v of this.store.values()) {
const row: any = v; const row: any = v;
if((expired || !row._expired) && includes(row, filter)) return deepCopy<any>(row); if((expired || !row._expired) && includes(row, filter)) return deepCopy(row);
} }
return undefined; return undefined;
} }
/** /** Get cached item by key */
* Get item from the cache
* @param {K} key Key to lookup
* @param expired Include expired items
* @return {T} Cached item
*/
get(key: K, expired?: boolean): CachedValue<T> | null { get(key: K, expired?: boolean): CachedValue<T> | null {
const raw = this.store.get(key); const raw = this.store.get(key);
if(raw == null) return null; if(raw == null) return null;
const cached: any = deepCopy<any>(raw);
this.touchLRU(key); this.touchLRU(key);
if(expired || !cached?._expired) return cached; const isExpired = (raw as any)?._expired;
if(expired || !isExpired) return deepCopy(raw);
return null; return null;
} }
/** /** Return list of keys */
* Get a list of cached keys
* @return {K[]} Array of keys
*/
keys(expired?: boolean): K[] { keys(expired?: boolean): K[] {
const out: K[] = []; const out: K[] = [];
for(const [k, v] of this.store.entries()) { for(const [k, v] of this.store.entries()) {
@@ -259,26 +230,17 @@ export class Cache<K extends string | number | symbol, T> {
return out; return out;
} }
/** /** Return map of key → item */
* Get map of cached items
* @return {Record<K, T>}
*/
map(expired?: boolean): Record<K, CachedValue<T>> { map(expired?: boolean): Record<K, CachedValue<T>> {
const copy: any = {}; const copy: any = {};
for(const [k, v] of this.store.entries()) { for(const [k, v] of this.store.entries()) {
const val: any = v; const val: any = v;
if(expired || !val?._expired) copy[k as any] = deepCopy<any>(val); if(expired || !val?._expired) copy[k as any] = deepCopy(val);
} }
return copy; return copy;
} }
/** /** Add item manually specifying the key */
* Add an item to the cache manually specifying the key
* @param {K} key Key item will be cached under
* @param {T} value Item to cache
* @param {number | undefined} ttl Override default expiry in seconds
* @return {this}
*/
set(key: K, value: T, ttl = this.options.ttl): this { set(key: K, value: T, ttl = this.options.ttl): this {
if(this.options.expiryPolicy == 'keep') delete (<any>value)._expired; if(this.options.expiryPolicy == 'keep') delete (<any>value)._expired;
this.clearTimer(key); this.clearTimer(key);
@@ -289,15 +251,12 @@ export class Cache<K extends string | number | symbol, T> {
const t = setTimeout(() => { const t = setTimeout(() => {
this.expire(key); this.expire(key);
this.save(key); this.save(key);
}, (ttl || 0) * 1000); }, ttl * 1000);
this.timers.set(key, t); this.timers.set(key, t);
} }
return this; return this;
} }
/** /** Get all cached items */
* Get all cached items values = this.all;
* @return {T[]} Array of items
*/
values = this.all
} }

View File

@@ -19,6 +19,7 @@ export * from './path-events';
export * from './promise-progress'; export * from './promise-progress';
export * from './search'; export * from './search';
export * from './string'; export * from './string';
export * from './template';
export * from './time'; export * from './time';
export * from './types'; export * from './types';
export * from 'var-persist'; export * from 'var-persist';

View File

@@ -82,6 +82,9 @@ export function clean<T>(obj: T, undefinedOnly = false): Partial<T> {
* @returns {T} Type * @returns {T} Type
*/ */
export function deepCopy<T>(value: T): T { export function deepCopy<T>(value: T): T {
if(value == null) return value;
const t = typeof value;
if(t === 'string' || t === 'number' || t === 'boolean' || t === 'function') return value;
try {return structuredClone(value); } try {return structuredClone(value); }
catch { return JSON.parse(JSONSanitize(value)); } catch { return JSON.parse(JSONSanitize(value)); }
} }

View File

@@ -56,8 +56,9 @@ export class PathError extends Error { }
/** /**
* A event broken down into its core components for easy processing * A event broken down into its core components for easy processing
* Event Structure: `module/path/name:property:method` * Event Structure: `module/path/name:method`
* Example: `users/system:crud` or `storage/some/path/file.txt:r` * Example: `users/system:crud` or `storage/some/path/file.txt:r`
* Supports glob patterns: `users/*:r` or `storage/**:rw`
*/ */
export class PathEvent { export class PathEvent {
/** First directory in path */ /** First directory in path */
@@ -66,13 +67,19 @@ export class PathEvent {
fullPath!: string; fullPath!: string;
/** Path including the name, excluding the module */ /** Path including the name, excluding the module */
path!: string; path!: string;
/** Last sagment of path */ /** Last segment of path */
name!: string; name!: string;
/** List of methods */ /** List of methods */
methods!: ASet<Method>; methods!: ASet<Method>;
/** Whether this path contains glob patterns */
hasGlob!: boolean;
/** Internal cache for PathEvent instances to avoid redundant parsing */ /** Internal cache for PathEvent instances to avoid redundant parsing */
private static pathEventCache: Map<string, PathEvent> = new Map(); private static pathEventCache: Map<string, PathEvent> = new Map();
/** Cache for compiled permissions (path + required permissions → result) */
private static permissionCache: Map<string, PathEvent> = new Map();
/** Max size for permission cache before LRU eviction */
private static readonly MAX_PERMISSION_CACHE_SIZE = 1000;
/** All/Wildcard specified */ /** All/Wildcard specified */
get all(): boolean { return this.methods.has('*') } get all(): boolean { return this.methods.has('*') }
@@ -83,6 +90,9 @@ export class PathEvent {
/** Create method specified */ /** Create method specified */
get create(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('c')) } get create(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('c')) }
set create(v: boolean) { v ? this.methods.delete('n').delete('*').add('c') : this.methods.delete('c'); } set create(v: boolean) { v ? this.methods.delete('n').delete('*').add('c') : this.methods.delete('c'); }
/** Execute method specified */
get execute(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('x')) }
set execute(v: boolean) { v ? this.methods.delete('n').delete('*').add('x') : this.methods.delete('x'); }
/** Read method specified */ /** Read method specified */
get read(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('r')) } get read(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('r')) }
set read(v: boolean) { v ? this.methods.delete('n').delete('*').add('r') : this.methods.delete('r'); } set read(v: boolean) { v ? this.methods.delete('n').delete('*').add('r') : this.methods.delete('r'); }
@@ -99,34 +109,109 @@ export class PathEvent {
return; return;
} }
// Check cache first if(PathEvent.pathEventCache.has(e)) {
if (PathEvent.pathEventCache.has(e)) {
Object.assign(this, PathEvent.pathEventCache.get(e)!); Object.assign(this, PathEvent.pathEventCache.get(e)!);
return; return;
} }
let [p, scope, method] = e.replaceAll(/\/{2,}/g, '/').split(':'); let [p, method] = e.replaceAll(/(^|\/)\*+\/?$/g, '').split(':');
if(!method) method = scope || '*'; if(!method) method = '*';
if(p == '*' || (!p && method == '*')) {
p = ''; // Handle special cases
method = '*'; if(p === '' || p === undefined || p === '*') {
this.module = '';
this.path = '';
this.fullPath = '**';
this.name = '';
this.methods = new ASet<Method>(p === '*' ? ['*'] : <any>method.split(''));
this.hasGlob = true;
PathEvent.pathEventCache.set(e, this);
return;
} }
let temp = p.split('/').filter(p => !!p); let temp = p.split('/').filter(p => !!p);
this.module = temp.splice(0, 1)[0] || ''; this.module = temp.splice(0, 1)[0] || '';
this.path = temp.join('/'); this.path = temp.join('/');
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`; this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
this.name = temp.pop() || ''; this.name = temp.pop() || '';
this.hasGlob = this.fullPath.includes('*');
this.methods = new ASet(<any>method.split('')); this.methods = new ASet(<any>method.split(''));
// Store in cache
PathEvent.pathEventCache.set(e, this); 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 */ /** Clear the cache of all PathEvents */
static clearCache(): void { static clearCache(): void {
PathEvent.pathEventCache.clear(); PathEvent.pathEventCache.clear();
} }
/** Clear the permission cache */
static clearPermissionCache(): void {
PathEvent.permissionCache.clear();
}
/** /**
* Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are * Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
* combined until a "none" is reached * combined until a "none" is reached
@@ -135,40 +220,37 @@ export class PathEvent {
* @return {PathEvent} Final combined permission * @return {PathEvent} Final combined permission
*/ */
static combine(...paths: (string | PathEvent)[]): PathEvent { static combine(...paths: (string | PathEvent)[]): PathEvent {
let hitNone = false; const parsed = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p));
const combined = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p)) const sorted = parsed.toSorted((p1, p2) => {
.toSorted((p1, p2) => { const score1 = PathEvent.scoreSpecificity(p1.fullPath);
const l1 = p1.fullPath.length, l2 = p2.fullPath.length; const score2 = PathEvent.scoreSpecificity(p2.fullPath);
return l1 < l2 ? 1 : (l1 > l2 ? -1 : 0); return score1 - score2;
}).reduce((acc, p) => { });
if(acc && !acc.fullPath.startsWith(p.fullPath)) return acc; let result: PathEvent | null = null;
if(p.none) hitNone = true; for (const p of sorted) {
if(!acc) return p; if(!result) {
if(hitNone) return acc; result = p;
acc.methods = new ASet([...acc.methods, ...p.methods]); } else {
return acc; if(result.fullPath.startsWith(p.fullPath)) {
}, <any>null); if(p.none) break;
return combined; result.methods = new ASet([...result.methods, ...p.methods]);
}
}
}
return result || new PathEvent('');
} }
/** /**
* Filter a set of paths based on the target * Filter a set of paths based on the target
* *
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
* @param filter {...PathEvent} Must container one of * @param filter {...PathEvent} Must contain one of
* @return {boolean} Whether there is any overlap * @return {PathEvent[]} Filtered results
*/ */
static filter(target: string | PathEvent | (string | PathEvent)[], ...filter: (string | PathEvent)[]): 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 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)); const parsedFilter = makeArray(filter).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
return parsedTarget.filter(t => !!parsedFilter.find(r => { return parsedTarget.filter(t => !!parsedFilter.find(r => PathEvent.matches(r, t)));
const wildcard = r.fullPath == '*' || t.fullPath == '*';
const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath;
const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath;
const scope = p1.startsWith(p2) || p2.startsWith(p1);
const methods = r.all || t.all || r.methods.intersection(t.methods).length;
return (wildcard || scope) && methods;
}));
} }
/** /**
@@ -181,14 +263,7 @@ export class PathEvent {
static has(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean { 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 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)); const parsedRequired = makeArray(has).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
return !!parsedRequired.find(r => !!parsedTarget.find(t => { return !!parsedRequired.find(r => !!parsedTarget.find(t => PathEvent.matches(r, t)));
const wildcard = r.fullPath == '*' || t.fullPath == '*';
const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath;
const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath;
const scope = p1.startsWith(p2); // Note: Original had || p2.startsWith(p1) here, but has implies target has required.
const methods = r.all || t.all || r.methods.intersection(t.methods).length;
return (wildcard || scope) && methods;
}));
} }
/** /**
@@ -196,7 +271,7 @@ export class PathEvent {
* *
* @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed * @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
* @param has Target must have all these paths * @param has Target must have all these paths
* @return {boolean} Whether there is any overlap * @return {boolean} Whether all are present
*/ */
static hasAll(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean { static hasAll(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean {
return has.filter(h => PathEvent.has(target, h)).length == has.length; return has.filter(h => PathEvent.has(target, h)).length == has.length;
@@ -205,7 +280,7 @@ export class PathEvent {
/** /**
* Same as `has` but raises an error if there is no overlap * Same as `has` but raises an error if there is no overlap
* *
* @param {string | string[]} target Array of Events as strings or pre-parsed * @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
* @param has Target must have at least one of these path * @param has Target must have at least one of these path
*/ */
static hasFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void { static hasFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
@@ -215,7 +290,7 @@ export class PathEvent {
/** /**
* Same as `hasAll` but raises an error if the target is missing any paths * Same as `hasAll` but raises an error if the target is missing any paths
* *
* @param {string | string[]} target Array of Events as strings or pre-parsed * @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
* @param has Target must have all these paths * @param has Target must have all these paths
*/ */
static hasAllFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void { static hasAllFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
@@ -250,7 +325,7 @@ export class PathEvent {
* Squash 2 sets of paths & return true if the target has all paths * Squash 2 sets of paths & return true if the target has all paths
* *
* @param has Target must have all these paths * @param has Target must have all these paths
* @return {boolean} Whether there is any overlap * @return {boolean} Whether all are present
*/ */
hasAll(...has: (string | PathEvent)[]): boolean { hasAll(...has: (string | PathEvent)[]): boolean {
return PathEvent.hasAll(this, ...has); return PathEvent.hasAll(this, ...has);
@@ -278,7 +353,7 @@ export class PathEvent {
* Filter a set of paths based on this event * Filter a set of paths based on this event
* *
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
* @return {boolean} Whether there is any overlap * @return {PathEvent[]} Filtered results
*/ */
filter(target: string | PathEvent | (string | PathEvent)[]): PathEvent[] { filter(target: string | PathEvent | (string | PathEvent)[]): PathEvent[] {
return PathEvent.filter(target, this); return PathEvent.filter(target, this);
@@ -317,7 +392,7 @@ export class PathEventEmitter implements IPathEventEmitter{
emit(event: Event, ...args: any[]) { emit(event: Event, ...args: any[]) {
const parsed = event instanceof PathEvent ? event : new PathEvent(`${this.prefix}/${event}`); const parsed = event instanceof PathEvent ? event : new PathEvent(`${this.prefix}/${event}`);
this.listeners.filter(l => PathEvent.has(l[0], parsed)) this.listeners.filter(l => PathEvent.has(l[0], parsed))
.forEach(async l => l[1](parsed, ...args)); .forEach(l => l[1](parsed, ...args));
}; };
off(listener: PathListener) { off(listener: PathListener) {
@@ -326,9 +401,21 @@ export class PathEventEmitter implements IPathEventEmitter{
on(event: Event | Event[], listener: PathListener): PathUnsubscribe { on(event: Event | Event[], listener: PathListener): PathUnsubscribe {
makeArray(event).forEach(e => { makeArray(event).forEach(e => {
if(typeof e == 'string' && e[0] == '*' && this.prefix) e = e.slice(1); let fullEvent: string;
if(typeof e === 'string') {
// If event starts with ':', it's a scope specifier - prepend prefix
if(e[0] === ':' && this.prefix) {
fullEvent = `${this.prefix}${e}`;
} else if(this.prefix) {
fullEvent = `${this.prefix}/${e}`;
} else {
fullEvent = e;
}
} else {
fullEvent = e instanceof PathEvent ? PathEvent.toString(e.fullPath, e.methods) : (e as string);
}
this.listeners.push([ this.listeners.push([
e instanceof PathEvent ? e : new PathEvent(`${this.prefix}/${e}`), new PathEvent(fullEvent),
listener listener
]) ])
}); });
@@ -346,6 +433,6 @@ export class PathEventEmitter implements IPathEventEmitter{
} }
relayEvents(emitter: IPathEventEmitter) { relayEvents(emitter: IPathEventEmitter) {
emitter.on('*', (event, ...args) => this.emit(event, ...args)); emitter.on('**', (event, ...args) => this.emit(event, ...args));
} }
} }

157
src/template.ts Normal file
View File

@@ -0,0 +1,157 @@
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 excluded = new Set<string>(['true', 'false', 'null', 'undefined']);
// Extract & exclude loop variables
for (const loop of matchAll(html, /\{\{\s*?\*\s*?(.+?)\s+in\s+(.+?)\s*?}}/g)) {
const [element, index = 'index'] = loop[1].replaceAll(/[()\s]/g, '').split(',');
excluded.add(element);
excluded.add(index);
// Add the array reference (but exclude if it's a loop variable)
const arrayRef = loop[2].trim();
const arrayVar = arrayRef.split('.')[0].match(/^[a-zA-Z_$][a-zA-Z0-9_$]*/)?.[0];
if (arrayVar && !excluded.has(arrayVar)) variables.add(arrayVar);
}
// Extract variables from if/else-if conditions
for (const ifStmt of matchAll(html, /\{\{\s*?[!]?\?\s*?([^}]+?)\s*?}}/g)) {
const code = ifStmt[1].replace(/["'`][^"'`]*["'`]/g, ''); // Remove string literals
const vars = code.match(/[a-zA-Z_$][a-zA-Z0-9_$.]+/g) || [];
for (const v of vars) {
const root = v.split('.')[0];
if (!excluded.has(root)) variables.add(root);
}
}
// Extract variables from content within if blocks
for (const ifBlock of matchAll(html, /\{\{\s*?\?\s*?.+?\s*?}}([\s\S]*?)\{\{\s*?\/\?\s*?}}/g)) {
const content = ifBlock[1];
const regex = /\{\{\s*([^<>\*\?!/}\s][^}]*?)\s*}}/g;
let match;
while ((match = regex.exec(content)) !== null) {
const code = match[1].trim().replace(/["'`][^"'`]*["'`]/g, '');
const vars = code.match(/[a-zA-Z_$][a-zA-Z0-9_$.]+/g) || [];
for (const v of vars) {
const root = v.split('.')[0];
if (!excluded.has(root)) variables.add(v);
}
}
}
// Extract variables from regular interpolations
const regex = /\{\{\s*([^<>\*\?!/}\s][^}]*?)\s*}}/g;
let match;
while ((match = regex.exec(html)) !== null) {
const code = match[1].trim().replace(/["'`][^"'`]*["'`]/g, '');
const vars = code.match(/[a-zA-Z_$][a-zA-Z0-9_$.]+/g) || [];
for (const v of vars) {
const root = v.split('.')[0];
if (!excluded.has(root)) variables.add(v);
}
}
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;
}

View File

@@ -3,6 +3,7 @@ import {PathError, PathEvent, PathEventEmitter, PE, PES} from '../src';
describe('Path Events', () => { describe('Path Events', () => {
beforeEach(() => { beforeEach(() => {
PathEvent.clearCache(); PathEvent.clearCache();
PathEvent.clearPermissionCache();
}); });
describe('PE', () => { describe('PE', () => {
@@ -42,8 +43,14 @@ describe('Path Events', () => {
it('parses wildcard', () => { it('parses wildcard', () => {
const pe = new PathEvent('*'); const pe = new PathEvent('*');
expect(pe.all).toBe(true); expect(pe.all).toBe(true);
expect(pe.fullPath).toBe(''); expect(pe.fullPath).toBe('**');
expect(pe.methods.has('*')).toBe(true); expect(pe.methods.has('*')).toBe(true);
expect(pe.hasAll('module:c', 'some/path:ud')).toBeTruthy();
});
it('parses empty string as wildcard', () => {
const pe = new PathEvent('');
expect(pe.has('any/path:c')).toBe(true);
}); });
it('parses none method', () => { it('parses none method', () => {
@@ -53,6 +60,10 @@ describe('Path Events', () => {
expect(pe.none).toBe(false); 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', () => { it('setters for methods', () => {
const pe = new PathEvent('users/system:r'); const pe = new PathEvent('users/system:r');
pe.create = true; pe.create = true;
@@ -73,6 +84,7 @@ describe('Path Events', () => {
expect(c.methods.has('c')).toBe(true); expect(c.methods.has('c')).toBe(true);
expect(c.methods.has('r')).toBe(true); expect(c.methods.has('r')).toBe(true);
expect(c.methods.has('u')).toBe(true); expect(c.methods.has('u')).toBe(true);
expect(c.delete).toBe(false);
}); });
it('combine stops at none', () => { it('combine stops at none', () => {
@@ -87,6 +99,17 @@ describe('Path Events', () => {
expect(d.none).toBe(false); 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', () => { it('filter finds overlap by path and methods', () => {
const events = [ const events = [
new PathEvent('users/sys:cr'), new PathEvent('users/sys:cr'),
@@ -143,6 +166,82 @@ describe('Path Events', () => {
const filtered = pe.filter(arr); const filtered = pe.filter(arr);
expect(filtered[0].fullPath).toBe('users/sys'); expect(filtered[0].fullPath).toBe('users/sys');
}); });
it('caches PathEvent instances', () => {
const pe1 = new PathEvent('users/sys:cr');
const pe2 = new PathEvent('users/sys:cr');
expect(pe1.fullPath).toBe(pe2.fullPath);
});
it('clearCache removes all cached instances', () => {
new PathEvent('users/sys:cr');
PathEvent.clearCache();
const pe = new PathEvent('users/sys:cr');
expect(pe.fullPath).toBe('users/sys');
});
});
describe('Glob Patterns', () => {
it('** matches zero or more segments', () => {
const pattern = new PathEvent('storage/**:r');
expect(PathEvent.has(pattern, 'storage:r')).toBe(true);
expect(PathEvent.has(pattern, 'storage/file:r')).toBe(true);
expect(PathEvent.has(pattern, 'storage/dir/file:r')).toBe(true);
});
it('** in middle matches multiple segments', () => {
const pattern = new PathEvent('data/**/archive:r');
expect(PathEvent.has(pattern, 'data/archive:r')).toBe(true);
expect(PathEvent.has(pattern, 'data/old/archive:r')).toBe(true);
});
it('filters by glob and methods', () => {
const events = [
new PathEvent('users/123/profile:cr'),
new PathEvent('users/456/profile:r'),
new PathEvent('users/789/settings:r')
];
const filtered = PathEvent.filter(events, 'users/*/profile:r');
expect(filtered.length).toBe(2);
});
it('wildcard method matches all methods', () => {
const pattern = new PathEvent('users/**:*');
expect(PathEvent.has(pattern, 'users/123:c')).toBe(true);
expect(PathEvent.has(pattern, 'users/456:r')).toBe(true);
});
});
describe('Specificity and None Permissions', () => {
it('more specific path wins when sorted by specificity', () => {
const perms = [new PathEvent('users/**:*'), new PathEvent('users/admin:r')];
const combined = PathEvent.combine(...perms);
expect(combined.fullPath).toBe('users/admin');
});
it('none at parent stops combining', () => {
const a = new PathEvent('data/public:cr');
const b = new PathEvent('data:n');
const combined = PathEvent.combine(a, b);
expect(combined.fullPath).toBe('data/public');
expect(combined.read).toBe(true);
});
it('instance methods work correctly', () => {
const pe = new PathEvent('users/sys:r');
expect(pe.has('users/sys:r')).toBe(true);
expect(pe.hasAll('users/sys:r')).toBe(true);
expect(pe.filter(['users/sys:r', 'users/other:r']).length).toBe(1);
});
it('combines methods from hierarchy', () => {
const a = new PathEvent('users/admin:c');
const b = new PathEvent('users/admin:r');
const combined = PathEvent.combine(a, b);
expect(combined.fullPath).toBe('users/admin');
expect(combined.create).toBe(true);
expect(combined.read).toBe(true);
});
}); });
describe('PathEventEmitter', () => { describe('PathEventEmitter', () => {
@@ -157,7 +256,7 @@ describe('Path Events', () => {
it('scoped', done => { it('scoped', done => {
const emitter = new PathEventEmitter('users'); const emitter = new PathEventEmitter('users');
emitter.on(':cud', (event) => { emitter.on('*:cud', (event) => {
expect(event.fullPath).toBe('users/system'); expect(event.fullPath).toBe('users/system');
done(); done();
}); });
@@ -198,5 +297,35 @@ describe('Path Events', () => {
expect(event.fullPath).toBe('foo/bar')); expect(event.fullPath).toBe('foo/bar'));
emitter.emit('bar:r'); emitter.emit('bar:r');
}); });
it('registers multiple listeners', () => {
const emitter = new PathEventEmitter();
const fn1 = jest.fn();
const fn2 = jest.fn();
emitter.on('users/sys:r', fn1);
emitter.on('users/sys:r', fn2);
emitter.emit('users/sys:r');
expect(fn1).toHaveBeenCalled();
expect(fn2).toHaveBeenCalled();
});
it('matches multiple listeners with overlapping globs', () => {
const emitter = new PathEventEmitter();
const fn1 = jest.fn();
const fn2 = jest.fn();
emitter.on('users/**:r', fn1);
emitter.on('users/*/profile:r', fn2);
emitter.emit('users/123/profile:r');
expect(fn1).toHaveBeenCalled();
expect(fn2).toHaveBeenCalled();
});
it('glob patterns in listener registration', () => {
const emitter = new PathEventEmitter();
const fn = jest.fn();
emitter.on('users/sys:r', fn);
emitter.emit('users/sys:r');
expect(fn).toHaveBeenCalled();
});
}); });
}); });

215
tests/templates.spec.ts Normal file
View File

@@ -0,0 +1,215 @@
import {findTemplateVars, renderTemplate, TemplateError} from '../src';
describe('findTemplateVars', () => {
test('extracts simple variables', () => {
const result = findTemplateVars('Hello {{ name }}!');
expect(result).toEqual({ name: '' });
});
test('extracts nested object paths', () => {
const result = findTemplateVars('{{ user.name }} is {{ user.age }}');
expect(result).toEqual({ user: { name: '', age: '' } });
});
test('extracts variables from if statements', () => {
const result = findTemplateVars('{{ ? active }}{{ message }}{{ /? }}');
expect(result).toEqual({ active: '', message: '' });
});
test('extracts variables from else-if conditions', () => {
const result = findTemplateVars('{{ ? status == "paid" }}PAID{{ !? status == "pending" }}{{ value }}{{ /? }}');
expect(result).toEqual({ status: '', value: '' });
});
test('extracts array reference from loops', () => {
const result = findTemplateVars('{{ * item in items }}{{ item }}{{ /* }}');
expect(result).toEqual({ items: '' });
});
test('excludes loop element variable', () => {
const result = findTemplateVars('{{ * item in items }}{{ item.name }}{{ /* }}');
expect(result).toEqual({ items: '' });
expect(result).not.toHaveProperty('item');
});
test('excludes loop index variable', () => {
const result = findTemplateVars('{{ * (item, i) in items }}{{ i }}:{{ item }}{{ /* }}');
expect(result).toEqual({ items: '' });
expect(result).not.toHaveProperty('item');
expect(result).not.toHaveProperty('i');
});
test('extracts external vars used inside loops', () => {
const result = findTemplateVars('{{ * item in items }}{{ item }}-{{ prefix }}{{ /* }}');
expect(result).toEqual({ items: '', prefix: '' });
});
test('handles nested loops', () => {
const result = findTemplateVars('{{ * row in rows }}{{ * col in row.cols }}{{ col }}{{ /* }}{{ /* }}');
expect(result).toEqual({ rows: '' });
expect(result).not.toHaveProperty('row');
expect(result).not.toHaveProperty('col');
});
test('extracts from complex nested template', () => {
const tpl = `
{{ ? items.length > 0 }}
{{ * (item, i) in items }}
{{ i }}. {{ item.name }}: {{ currency }}{{ item.price }}
{{ /* }}
Total: {{ total }}
{{ !? }}
{{ emptyMessage }}
{{ /? }}`;
const result = findTemplateVars(tpl);
expect(result).toEqual({
items: '',
currency: '',
total: '',
emptyMessage: ''
});
expect(result).not.toHaveProperty('item');
expect(result).not.toHaveProperty('i');
});
test('ignores template control syntax', () => {
const result = findTemplateVars('{{ < header.html }}{{ > layout.html:content }}content{{ /> }}');
expect(result).toEqual({});
});
test('handles multiple variables in expressions', () => {
const result = findTemplateVars('{{ firstName + " " + lastName }}');
expect(result).toEqual({ firstName: '', lastName: '' });
});
});
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');
});
});

View File

@@ -35,7 +35,7 @@ describe('Time Utilities', () => {
}); });
it('throws for unknown timezone', () => { it('throws for unknown timezone', () => {
expect(() => formatDate('YYYY', new Date(), '???')).toThrowError(/Invalid timezone/); expect(() => formatDate('YYYY', new Date(), '???')).toThrow(/Invalid timezone/);
}); });
it('handles timezone by offset number', () => { it('handles timezone by offset number', () => {