Compare commits

...

7 Commits

Author SHA1 Message Date
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
7 changed files with 282 additions and 71 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.10", "version": "0.27.15",
"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

@@ -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));
} }
} }

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();
});
}); });
}); });

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', () => {