Compare commits

...

8 Commits

Author SHA1 Message Date
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
057528b0c5 Fixed doc build step
All checks were successful
Build / Build NPM Project (push) Successful in 1m17s
Build / Publish Docs (push) Successful in 1m16s
Build / Tag Version (push) Successful in 28s
2025-10-20 16:16:55 -04:00
1595aea529 Fixed imports
Some checks failed
Build / Build NPM Project (push) Successful in 1m22s
Build / Publish Documentation (push) Failing after 19s
Build / Tag Version (push) Successful in 36s
2025-10-20 16:02:27 -04:00
08503de552 Fixed tests
Some checks failed
Build / Build NPM Project (push) Failing after 56s
Build / Publish Documentation (push) Has been skipped
Build / Tag Version (push) Has been skipped
2025-10-20 15:56:19 -04:00
a9a9b04a5a JSONAttemptPrase fallback
Some checks failed
Build / Build NPM Project (push) Failing after 48s
Build / Publish Documentation (push) Has been skipped
Build / Tag Version (push) Has been skipped
2025-10-20 15:51:10 -04:00
a7b19900da Added object map
Some checks failed
Build / Build NPM Project (push) Successful in 1m59s
Build / Publish Documentation (push) Failing after 32s
Build / Tag Version (push) Successful in 43s
2025-10-20 15:17:51 -04:00
18 changed files with 608 additions and 226 deletions

View File

@@ -13,3 +13,7 @@ quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false
[*.{yaml,yml}]
indent_style = space
indent_size = 2

View File

@@ -11,26 +11,26 @@ jobs:
runs-on: ubuntu-latest
container: node:20-alpine
steps:
- name: Clone Repository
uses: ztimson/actions/clone@develop
- name: Clone Repository
uses: ztimson/actions/clone@develop
- name: Install & Build
run: |
npm i
npm run build
- name: Install & Build
run: |
npm i
npm run build
- name: Test
run: npm run test:coverage
- name: Test
run: npm run test:coverage
- name: Upload to Registry
uses: ztimson/actions/npm/publish@develop
- name: Upload to Registry
uses: ztimson/actions/npm/publish@develop
- name: Upload to NPM
uses: ztimson/actions/npm/publish@develop
with:
owner: ztimson
registry: https://registry.npmjs.org/
token: ${{secrets.NPM_TOKEN}}
- name: Upload to NPM
uses: ztimson/actions/npm/publish@develop
with:
owner: ztimson
registry: https://registry.npmjs.org/
token: ${{secrets.NPM_TOKEN}}
tag:
name: Tag Version
needs: build
@@ -38,23 +38,53 @@ jobs:
runs-on: ubuntu-latest
container: node
steps:
- name: Clone Repository
uses: ztimson/actions/clone@develop
- name: Get Version Number
run: echo "VERSION=$(cat package.json | grep version | grep -Eo ':.+' | grep -Eo '[[:alnum:]\.\/\-]+')" >> $GITHUB_ENV
- name: Tag Version
uses: ztimson/actions/tag@develop
with:
tag: ${{env.VERSION}}
- name: Clone Repository
uses: ztimson/actions/clone@develop
- name: Get Version Number
run: echo "VERSION=$(cat package.json | grep version | grep -Eo ':.+' | grep -Eo '[[:alnum:]\.\/\-]+')" >> $GITHUB_ENV
- name: Tag Version
uses: ztimson/actions/tag@develop
with:
tag: ${{env.VERSION}}
docs:
name: Publish Documentation
needs: build
uses: ztimson/actions/.github/workflows/docker.yaml@develop
with:
name: ztimson/utils
repository: ${{github.server_url}}/${{github.repository}}.git
pass: ${{secrets.DEPLOY_TOKEN}}
name: Publish Docs
runs-on: ubuntu-latest
container: docker:dind
steps:
- name: Clone Repository
uses: ztimson/actions/clone@develop
- name: Build Image
run: |
REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
docker build -t "$REGISTRY/${{github.repository}}:${{github.ref_name}}" .
- name: Build Image
run: |
echo "CHECKSUM: ${{env.CHECKSUM}}"
REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
docker build -t "$REGISTRY/${{github.repository}}:${{github.ref_name}}" --build-arg LICENSE_KEY="${{secrets.LICENSE_KEY}}" --build-arg UPDATE_TOKEN="${{secrets.UPDATE_TOKEN}}" .
- name: Publish Branch Tag
run: |
REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
docker login -u ${{github.repository_owner}} -p ${{secrets.DEPLOY_TOKEN}} $REGISTRY
docker push "$REGISTRY/${{github.repository}}:${{github.ref_name}}"
- name: Publish Version Tag
run: |
if [ "${{github.ref_name}}" = "master" ]; then
REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
docker tag "$REGISTRY/${{github.repository}}:${{github.ref_name}}" "$REGISTRY/${{github.repository}}:${{env.VERSION}}"
docker push "$REGISTRY/${{github.repository}}:${{env.VERSION}}"
fi
- name: Publish Latest Tag
run: |
if [ "${{github.ref_name}}" = "master" ]; then
REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
docker tag "$REGISTRY/${{github.repository}}:${{github.ref_name}}" "$REGISTRY/${{github.repository}}:latest"
docker push "$REGISTRY/${{github.repository}}:latest"
fi

View File

@@ -1,11 +1,102 @@
<!DOCTYPE html>
<html>
<head>
<title>Console Styling Playground</title>
</head>
<body>
<script type="module">
import {formatDate} from './dist/index.mjs';
<h1>Open Chrome DevTools Console to see magic! (Ctrl+Shift+J or Cmd+Option+J)</h1>
const dt = new Date('2021-03-03T09:00:00Z');
const result = formatDate('Do MMMM dddd', dt, 0);
console.log(result);
<script>
// Console Styling Playground
class ConsoleStyler {
// Basic badge with customizable colors
badge(text, bgColor = '#007bff', textColor = 'white') {
console.log(
`%c ${text} `,
`background-color: ${bgColor};
color: ${textColor};
border-radius: 12px;
padding: 2px 8px;
font-weight: bold;`
);
}
// Multi-style log with different sections
richLog() {
console.log(
'%cSystem%c Operation %cDetails',
'background-color: #f0f0f0; color: black; padding: 2px 5px; border-radius: 3px;',
'color: blue; font-weight: bold;',
'color: green;'
);
}
// Grouped logs with nested information
groupedLog(title, items) {
console.group(title);
items.forEach(item => {
console.log(item);
});
console.groupEnd();
}
// Table view for structured data
tableLog(data) {
console.table(data);
}
// Performance tracking
timeTrack(label, operation) {
console.time(label);
operation();
console.timeEnd(label);
}
// Demonstration method
demo() {
// Different styled badges
this.badge('NEW', '#28a745'); // Green
this.badge('WARNING', '#ffc107', 'black'); // Yellow
this.badge('ERROR', '#dc3545'); // Red
this.badge('CUSTOM', '#6f42c1'); // Purple
// Rich multi-style log
this.richLog();
// Grouped logs
this.groupedLog('User Details', [
{ name: 'John Doe', age: 30, role: 'Admin' },
{ name: 'Jane Smith', age: 25, role: 'User' }
]);
// Table logging
this.tableLog([
{ name: 'John', age: 30, active: true },
{ name: 'Jane', age: 25, active: false }
]);
// Performance tracking
this.timeTrack('Complex Operation', () => {
let sum = 0;
for(let i = 0; i < 1000000; i++) {
sum += i;
}
console.log('Sum:', sum);
});
// Advanced: Conditional styling
const logLevel = 'warn';
console.log(
`%c[${logLevel.toUpperCase()}]%c Detailed message`,
`color: ${logLevel === 'warn' ? 'orange' : 'red'}; font-weight: bold;`,
'color: black;'
);
}
}
// Create instance and run demo
const styler = new ConsoleStyler();
styler.demo();
</script>
</body>
</html>

View File

@@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.27.7",
"version": "0.27.11",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@@ -1,5 +1,6 @@
import {Database, Table} from './database.ts';
import {deepCopy, includes, JSONSanitize} from './objects.ts';
import {JSONSanitize} from './json.ts';
import {deepCopy, includes} from './objects.ts';
export type CacheOptions = {
/** Delete keys automatically after x amount of seconds */
@@ -84,6 +85,7 @@ export class Cache<K extends string | number | symbol, T> {
return <K>(value as any)[this.key];
}
/** Save item to storage */
private save(key?: K) {
const persists: {storage: any, key: string} = <any>this.options.persistentStorage;
if(!!persists?.storage) {
@@ -130,16 +132,13 @@ export class Cache<K extends string | number | symbol, T> {
const out: CachedValue<T>[] = [];
for(const v of this.store.values()) {
const val: any = v;
if(expired || !val?._expired) out.push(deepCopy<any>(val));
if(expired || !val?._expired) out.push(deepCopy(val));
}
return out;
}
/**
* 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 {
const key = this.getKey(value);
@@ -149,9 +148,6 @@ export class Cache<K extends string | number | symbol, T> {
/**
* 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 {
this.clear();
@@ -160,9 +156,7 @@ export class Cache<K extends string | number | symbol, T> {
return this;
}
/**
* Remove all keys from cache
*/
/** Remove all keys */
clear(): this {
this.complete = false;
for (const [k, t] of this.timers) clearTimeout(t);
@@ -173,10 +167,7 @@ export class Cache<K extends string | number | symbol, T> {
return this;
}
/**
* Delete an item from the cache
* @param {K} key Item's primary key
*/
/** Delete a cached item */
delete(key: K): this {
this.clearTimer(key);
const idx = this.lruOrder.indexOf(key);
@@ -186,23 +177,17 @@ export class Cache<K extends string | number | symbol, T> {
return this;
}
/**
* Return cache as an array of key-value pairs
* @return {[K, T][]} Key-value pairs array
*/
/** Return entries as array */
entries(expired?: boolean): [K, CachedValue<T>][] {
const out: [K, CachedValue<T>][] = [];
for(const [k, v] of this.store.entries()) {
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;
}
/**
* Manually expire a cached item
* @param {K} key Key to expire
*/
/** Manually expire a cached item */
expire(key: K): this {
this.complete = false;
if(this.options.expiryPolicy == 'keep') {
@@ -216,39 +201,26 @@ export class Cache<K extends string | number | symbol, T> {
return this;
}
/**
* 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 first matching item */
find(filter: Partial<T>, expired?: boolean): T | undefined {
for(const v of this.store.values()) {
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;
}
/**
* Get item from the cache
* @param {K} key Key to lookup
* @param expired Include expired items
* @return {T} Cached item
*/
/** Get cached item by key */
get(key: K, expired?: boolean): CachedValue<T> | null {
const raw = this.store.get(key);
if(raw == null) return null;
const cached: any = deepCopy<any>(raw);
this.touchLRU(key);
if(expired || !cached?._expired) return cached;
const isExpired = (raw as any)?._expired;
if(expired || !isExpired) return deepCopy(raw);
return null;
}
/**
* Get a list of cached keys
* @return {K[]} Array of keys
*/
/** Return list of keys */
keys(expired?: boolean): K[] {
const out: K[] = [];
for(const [k, v] of this.store.entries()) {
@@ -258,26 +230,17 @@ export class Cache<K extends string | number | symbol, T> {
return out;
}
/**
* Get map of cached items
* @return {Record<K, T>}
*/
/** Return map of key → item */
map(expired?: boolean): Record<K, CachedValue<T>> {
const copy: any = {};
for(const [k, v] of this.store.entries()) {
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;
}
/**
* 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}
*/
/** Add item manually specifying the key */
set(key: K, value: T, ttl = this.options.ttl): this {
if(this.options.expiryPolicy == 'keep') delete (<any>value)._expired;
this.clearTimer(key);
@@ -288,15 +251,12 @@ export class Cache<K extends string | number | symbol, T> {
const t = setTimeout(() => {
this.expire(key);
this.save(key);
}, (ttl || 0) * 1000);
}, ttl * 1000);
this.timers.set(key, t);
}
return this;
}
/**
* Get all cached items
* @return {T[]} Array of items
*/
values = this.all
/** Get all cached items */
values = this.all;
}

View File

@@ -1,6 +1,7 @@
import {makeArray} from './array.ts';
import {ASet} from './aset.ts';
import {dotNotation, flattenObj, JSONSanitize} from './objects.ts';
import {JSONSanitize} from './json.ts';
import {dotNotation, flattenObj} from './objects.ts';
import {LETTER_LIST} from './string.ts';
/**

View File

@@ -1,5 +1,5 @@
import {makeArray} from './array.ts';
import {JSONAttemptParse} from './objects.ts';
import {JSONAttemptParse} from './json.ts';
import {PromiseProgress} from './promise-progress';
import {formatDate} from './time.ts';

View File

@@ -9,6 +9,7 @@ export * from './files';
export * from './emitter';
export * from './errors';
export * from './http';
export * from './json';
export * from './jwt';
export * from './logger';
export * from './math';

40
src/json.ts Normal file
View File

@@ -0,0 +1,40 @@
/**
* Parse JSON but return the original string if it fails
*
* @param {any} json JSON string to parse
* @param fallback Fallback value if unable to parse, defaults to original string
* @return {string | T} Object if successful, original string otherwise
*/
export function JSONAttemptParse<T1, T2>(json: T2, fallback?: T1): T1 | T2 {
try { return JSON.parse(<any>json); }
catch { return fallback ?? json; }
}
/**
* Stringifies objects & skips primitives
*
* @param {any} obj Object to convert to serializable value
* @return {string | T} Serialized value
*/
export function JSONSerialize<T1>(obj: T1): T1 | string {
if(typeof obj == 'object' && obj != null) return JSONSanitize(obj);
return obj;
}
/**
* Convert an object to a JSON string avoiding any circular references.
*
* @param obj Object to convert to JSON
* @param {number} space Format the JSON with spaces
* @return {string} JSON string
*/
export function JSONSanitize(obj: any, space?: number): string {
const cache: any[] = [];
return JSON.stringify(obj, (key, value) => {
if(typeof value === 'object' && value !== null) {
if(cache.includes(value)) return '[Circular]';
cache.push(value);
}
return value;
}, space);
}

View File

@@ -1,4 +1,4 @@
import {JSONAttemptParse} from './objects.ts';
import {JSONAttemptParse} from './json.ts';
/**
* Creates a JSON Web Token (JWT) using the provided payload.

View File

@@ -1,5 +1,5 @@
import {TypedEmitter, TypedEvents} from './emitter';
import {JSONSanitize} from './objects.ts';
import {JSONSanitize} from './json.ts';
export const CliEffects = {
CLEAR: "\x1b[0m",

View File

@@ -1,5 +1,6 @@
export type Delta = { [key: string]: any | Delta | null };
import {JSONSanitize} from './json.ts';
export type Delta = { [key: string]: any | Delta | null };
/**
* Applies deltas to `target`.
@@ -81,6 +82,9 @@ export function clean<T>(obj: T, undefinedOnly = false): Partial<T> {
* @returns {T} Type
*/
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); }
catch { return JSON.parse(JSONSanitize(value)); }
}
@@ -294,41 +298,12 @@ export function mixin(target: any, constructors: any[]) {
}
/**
* Parse JSON but return the original string if it fails
*
* @param {any} json JSON string to parse
* @return {string | T} Object if successful, original string otherwise
* Run a map function on each property
* @param obj Object that will be iterated
* @param {(key: string, value: any) => any} fn Transformer function - receives key & value
* @returns {{}}
*/
export function JSONAttemptParse<T1, T2>(json: T2): T1 | T2 {
try { return JSON.parse(<any>json); }
catch { return json; }
}
/**
* Stringifies objects & skips primitives
*
* @param {any} obj Object to convert to serializable value
* @return {string | T} Serialized value
*/
export function JSONSerialize<T1>(obj: T1): T1 | string {
if(typeof obj == 'object' && obj != null) return JSONSanitize(obj);
return obj;
}
/**
* Convert an object to a JSON string avoiding any circular references.
*
* @param obj Object to convert to JSON
* @param {number} space Format the JSON with spaces
* @return {string} JSON string
*/
export function JSONSanitize(obj: any, space?: number): string {
const cache: any[] = [];
return JSON.stringify(obj, (key, value) => {
if(typeof value === 'object' && value !== null) {
if(cache.includes(value)) return '[Circular]';
cache.push(value);
}
return value;
}, space);
export function objectMap<T>(obj: any, fn: (key: string, value: any) => any): T {
return <any>Object.entries(obj).map(([key, value]: [string, any]) => [key, fn(key, value)])
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
}

View File

@@ -55,9 +55,10 @@ export function PES(str: TemplateStringsArray, ...args: any[]) {
export class PathError extends Error { }
/**
* A event broken down into its core components for easy processing
* Event Structure: `module/path/name:property:method`
* A event broken down into its core components for easy processing
* Event Structure: `module/path/name:method`
* Example: `users/system:crud` or `storage/some/path/file.txt:r`
* Supports glob patterns: `users/*:r` or `storage/**:rw`
*/
export class PathEvent {
/** First directory in path */
@@ -66,13 +67,19 @@ export class PathEvent {
fullPath!: string;
/** Path including the name, excluding the module */
path!: string;
/** Last sagment of path */
/** Last segment of path */
name!: string;
/** List of methods */
methods!: ASet<Method>;
/** Whether this path contains glob patterns */
hasGlob!: boolean;
/** Internal cache for PathEvent instances to avoid redundant parsing */
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 */
get all(): boolean { return this.methods.has('*') }
@@ -83,6 +90,9 @@ export class PathEvent {
/** Create method specified */
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'); }
/** 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 */
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'); }
@@ -105,17 +115,44 @@ export class PathEvent {
return;
}
let [p, scope, method] = e.replaceAll(/\/{2,}/g, '/').split(':');
if(!method) method = scope || '*';
if(p == '*' || (!p && method == '*')) {
p = '';
method = '*';
let [p, method] = e.replaceAll(/\/{2,}/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
this.module = '';
this.path = '';
this.fullPath = '**';
this.name = '';
this.methods = new ASet<Method>(['*']);
this.hasGlob = true;
PathEvent.pathEventCache.set(e, this);
return;
}
let temp = p.split('/').filter(p => !!p);
this.module = temp.splice(0, 1)[0] || '';
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
@@ -127,6 +164,87 @@ export class PathEvent {
PathEvent.pathEventCache.clear();
}
/** Clear the permission cache */
static clearPermissionCache(): void {
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
@@ -135,40 +253,79 @@ export class PathEvent {
* @return {PathEvent} Final combined permission
*/
static combine(...paths: (string | PathEvent)[]): PathEvent {
let hitNone = false;
const combined = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p))
.toSorted((p1, p2) => {
const l1 = p1.fullPath.length, l2 = p2.fullPath.length;
return l1 < l2 ? 1 : (l1 > l2 ? -1 : 0);
}).reduce((acc, p) => {
if(acc && !acc.fullPath.startsWith(p.fullPath)) return acc;
if(p.none) hitNone = true;
if(!acc) return p;
if(hitNone) return acc;
acc.methods = new ASet([...acc.methods, ...p.methods]);
return acc;
}, <any>null);
return combined;
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
result.methods = new ASet([...result.methods, ...p.methods]);
}
}
}
return result || new PathEvent('');
}
/**
* Filter a set of paths based on the target
*
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
* @param filter {...PathEvent} Must container one of
* @return {boolean} Whether there is any overlap
* @param filter {...PathEvent} Must contain one of
* @return {PathEvent[]} Filtered results
*/
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 => !!parsedFilter.find(r => {
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;
}));
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);
}
/**
@@ -181,14 +338,11 @@ 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));
return !!parsedRequired.find(r => !!parsedTarget.find(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;
}));
// 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));
}
/**
@@ -196,7 +350,7 @@ export class PathEvent {
*
* @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
* @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 {
return has.filter(h => PathEvent.has(target, h)).length == has.length;
@@ -205,7 +359,7 @@ export class PathEvent {
/**
* 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
*/
static hasFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
@@ -215,7 +369,7 @@ export class PathEvent {
/**
* 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
*/
static hasAllFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
@@ -250,7 +404,7 @@ export class PathEvent {
* Squash 2 sets of paths & return true if the target has all 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 {
return PathEvent.hasAll(this, ...has);
@@ -278,7 +432,7 @@ export class PathEvent {
* Filter a set of paths based on this event
*
* @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[] {
return PathEvent.filter(target, this);
@@ -317,7 +471,7 @@ export class PathEventEmitter implements IPathEventEmitter{
emit(event: Event, ...args: any[]) {
const parsed = event instanceof PathEvent ? event : new PathEvent(`${this.prefix}/${event}`);
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) {
@@ -326,9 +480,21 @@ export class PathEventEmitter implements IPathEventEmitter{
on(event: Event | Event[], listener: PathListener): PathUnsubscribe {
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([
e instanceof PathEvent ? e : new PathEvent(`${this.prefix}/${e}`),
new PathEvent(fullEvent),
listener
])
});
@@ -346,6 +512,6 @@ export class PathEventEmitter implements IPathEventEmitter{
}
relayEvents(emitter: IPathEventEmitter) {
emitter.on('*', (event, ...args) => this.emit(event, ...args));
emitter.on('**', (event, ...args) => this.emit(event, ...args));
}
}

View File

@@ -1,4 +1,5 @@
import {dotNotation, JSONAttemptParse, JSONSerialize} from './objects.ts';
import {JSONAttemptParse, JSONSerialize} from './json.ts';
import {dotNotation} from './objects.ts';
/**
* Filters an array of objects based on a search term and optional regex checking.

View File

@@ -1,5 +1,3 @@
import {numSuffix} from './math.ts';
/**
* Like setInterval but will adjust the timeout value to account for runtime
* @param {Function} cb Callback function that will be ran

33
tests/json.spec.ts Normal file
View File

@@ -0,0 +1,33 @@
import {JSONAttemptParse, JSONSanitize, JSONSerialize} from '../src';
describe('JSON Utilities', () => {
describe('JSONAttemptParse', () => {
it('parses valid JSON', () => {
expect(JSONAttemptParse('{"a":1}')).toEqual({ a: 1 });
});
it('returns original string on error', () => {
expect(JSONAttemptParse('not json')).toBe('not json');
});
});
describe('JSONSerialize', () => {
it('serializes objects', () => {
expect(JSONSerialize({ a: 1 })).toBe(JSON.stringify({ a: 1 }));
});
it('leaves primitives as is', () => {
expect(JSONSerialize('test')).toBe('test');
expect(JSONSerialize(123)).toBe(123);
});
});
describe('JSONSanitize', () => {
it('stringifies objects', () => {
expect(JSONSanitize({ a: 1 })).toBe(JSON.stringify({ a: 1 }));
});
it('does not throw on circular refs', () => {
const obj: any = {};
obj.self = obj;
expect(() => JSONSanitize(obj)).not.toThrow();
});
});
});

View File

@@ -1,6 +1,5 @@
import {
clean, deepCopy, deepMerge, dotNotation, encodeQuery, flattenObj, formData, includes, isEqual, mixin,
JSONAttemptParse, JSONSerialize, JSONSanitize
} from '../src';
describe('Object utilities', () => {
@@ -131,34 +130,4 @@ describe('Object utilities', () => {
expect(c.bar()).toBe(2);
});
});
describe('JSONAttemptParse', () => {
it('parses valid JSON', () => {
expect(JSONAttemptParse('{"a":1}')).toEqual({ a: 1 });
});
it('returns original string on error', () => {
expect(JSONAttemptParse('not json')).toBe('not json');
});
});
describe('JSONSerialize', () => {
it('serializes objects', () => {
expect(JSONSerialize({ a: 1 })).toBe(JSON.stringify({ a: 1 }));
});
it('leaves primitives as is', () => {
expect(JSONSerialize('test')).toBe('test');
expect(JSONSerialize(123)).toBe(123);
});
});
describe('JSONSanitize', () => {
it('stringifies objects', () => {
expect(JSONSanitize({ a: 1 })).toBe(JSON.stringify({ a: 1 }));
});
it('does not throw on circular refs', () => {
const obj: any = {};
obj.self = obj;
expect(() => JSONSanitize(obj)).not.toThrow();
});
});
});

View File

@@ -3,6 +3,7 @@ import {PathError, PathEvent, PathEventEmitter, PE, PES} from '../src';
describe('Path Events', () => {
beforeEach(() => {
PathEvent.clearCache();
PathEvent.clearPermissionCache();
});
describe('PE', () => {
@@ -42,10 +43,16 @@ describe('Path Events', () => {
it('parses wildcard', () => {
const pe = new PathEvent('*');
expect(pe.all).toBe(true);
expect(pe.fullPath).toBe('');
expect(pe.fullPath).toBe('**');
expect(pe.methods.has('*')).toBe(true);
});
it('parses empty string as none', () => {
const pe = new PathEvent('');
expect(pe.none).toBe(true);
expect(pe.fullPath).toBe('');
});
it('parses none method', () => {
const pe = new PathEvent('users/system:n');
expect(pe.none).toBe(true);
@@ -143,6 +150,82 @@ describe('Path Events', () => {
const filtered = pe.filter(arr);
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', () => {
@@ -157,7 +240,7 @@ describe('Path Events', () => {
it('scoped', done => {
const emitter = new PathEventEmitter('users');
emitter.on(':cud', (event) => {
emitter.on('*:cud', (event) => {
expect(event.fullPath).toBe('users/system');
done();
});
@@ -198,5 +281,35 @@ describe('Path Events', () => {
expect(event.fullPath).toBe('foo/bar'));
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();
});
});
});