Compare commits

...

38 Commits

Author SHA1 Message Date
cf122ef9e8 * Fixed cache expiry
All checks were successful
Build / Build NPM Project (push) Successful in 46s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 34s
2025-05-13 11:13:48 -04:00
76b570b3fe * Fixed cache expire checks on uncached
All checks were successful
Build / Build NPM Project (push) Successful in 39s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 35s
2025-05-13 11:10:23 -04:00
4fecf10d11 * Fixed cache value type
All checks were successful
Build / Build NPM Project (push) Successful in 1m16s
Build / Tag Version (push) Successful in 14s
Build / Publish Documentation (push) Successful in 54s
2025-05-13 10:53:17 -04:00
028b9c0f4c + Caching manually expire
All checks were successful
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 36s
2025-05-12 20:29:29 -04:00
d938996a66 + Caching expiry strategies
Some checks failed
Build / Build NPM Project (push) Failing after 34s
Build / Publish Documentation (push) Has been skipped
Build / Tag Version (push) Has been skipped
+ Prefix PathEvents
2025-05-12 19:46:23 -04:00
cdcaeda67c + Added writable
All checks were successful
Build / Build NPM Project (push) Successful in 40s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 35s
2025-05-12 18:00:12 -04:00
482c90b53b + Added writable
All checks were successful
Build / Build NPM Project (push) Successful in 1m13s
Build / Tag Version (push) Successful in 15s
Build / Publish Documentation (push) Successful in 49s
2025-05-12 16:28:10 -04:00
7500ba502f + Added clear function to ASet
All checks were successful
Build / Build NPM Project (push) Successful in 44s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 37s
* fixed pathedEvent fullPath casing
2025-05-11 14:13:01 -04:00
edc059d17d Added var-persist
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 35s
2025-05-11 11:55:40 -04:00
48cfbee46e Removed test
All checks were successful
Build / Build NPM Project (push) Successful in 1m8s
Build / Tag Version (push) Successful in 14s
Build / Publish Documentation (push) Successful in 53s
2025-05-11 11:50:08 -04:00
26cc18ffb3 Fixed path event, renamed testCondition to logicTest & fixed some tests
Some checks failed
Build / Build NPM Project (push) Failing after 44s
Build / Publish Documentation (push) Has been skipped
Build / Tag Version (push) Has been skipped
2025-05-11 11:46:03 -04:00
3fd5c5ed57 Added sync function runner
All checks were successful
Build / Build NPM Project (push) Successful in 42s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 41s
2025-05-06 19:52:32 -04:00
2e4559d805 Added async function runner
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 34s
2025-05-06 16:09:24 -04:00
95f8d5762c Fixed import error
All checks were successful
Build / Build NPM Project (push) Successful in 57s
Build / Tag Version (push) Successful in 13s
Build / Publish Documentation (push) Successful in 48s
2025-05-06 16:01:57 -04:00
3bc82fab45 - Fixed cache.addAll()
Some checks failed
Build / Build NPM Project (push) Failing after 34s
Build / Publish Documentation (push) Has been skipped
Build / Tag Version (push) Has been skipped
- Renamed jwtDecode to decodeJWT to match conventions
- Added testCondition to search
2025-05-06 15:59:08 -04:00
6b15848896 Fixed defaulting date in date formatter
All checks were successful
Build / Build NPM Project (push) Successful in 1m15s
Build / Tag Version (push) Successful in 16s
Build / Publish Documentation (push) Successful in 49s
2025-04-30 11:58:03 -04:00
9a0f32323e Fix HTTP empty responses
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 34s
2025-04-13 10:16:50 -04:00
f952abc95a More zelous path fixing in the http client
All checks were successful
Build / Build NPM Project (push) Successful in 1m13s
Build / Tag Version (push) Successful in 14s
Build / Publish Documentation (push) Successful in 51s
2025-04-13 09:50:19 -04:00
21fc1378b8 Added more naming convention utilities
All checks were successful
Build / Build NPM Project (push) Successful in 42s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 38s
2025-04-08 19:02:42 -04:00
a03567eba3 toCSV comma fix
All checks were successful
Build / Build NPM Project (push) Successful in 1m15s
Build / Tag Version (push) Successful in 13s
Build / Publish Documentation (push) Successful in 50s
2025-04-06 21:37:01 -04:00
f9fc4fb7ff Better CSV handling
All checks were successful
Build / Build NPM Project (push) Successful in 38s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 35s
2025-03-24 23:01:57 -04:00
ff16f3bf9b Better CSV handling
All checks were successful
Build / Build NPM Project (push) Successful in 38s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 36s
2025-03-24 21:40:03 -04:00
e0085ecb6f Better CSV handling
All checks were successful
Build / Build NPM Project (push) Successful in 1m15s
Build / Tag Version (push) Successful in 16s
Build / Publish Documentation (push) Successful in 53s
2025-03-24 21:28:51 -04:00
1c2c18b65d Added camelCase function
All checks were successful
Build / Build NPM Project (push) Successful in 1m12s
Build / Tag Version (push) Successful in 12s
Build / Publish Documentation (push) Successful in 50s
2025-03-10 09:50:16 -04:00
cd5741d6ab Simplified timestampedFilename to use formatDate
All checks were successful
Build / Build NPM Project (push) Successful in 43s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 45s
2025-03-02 21:37:48 -05:00
5b9e0714ce Cache returns deep copies to prevent deletion mid-use
All checks were successful
Build / Build NPM Project (push) Successful in 1m13s
Build / Tag Version (push) Successful in 17s
Build / Publish Documentation (push) Successful in 54s
2025-02-27 08:36:30 -05:00
a3b34ef03f Fixed http no decode
All checks were successful
Build / Build NPM Project (push) Successful in 43s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 40s
2025-02-18 16:04:18 -05:00
f755d8f5b8 Fixed PathEvents filter
All checks were successful
Build / Build NPM Project (push) Successful in 38s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 35s
2025-02-04 22:17:31 -05:00
35c471eef4 Fixed PathEvents filter
All checks were successful
Build / Build NPM Project (push) Successful in 1m12s
Build / Tag Version (push) Successful in 12s
Build / Publish Documentation (push) Successful in 47s
2025-02-04 21:35:31 -05:00
fe9fdb9384 Fixed blackorwhite invalid argument crash
All checks were successful
Build / Build NPM Project (push) Successful in 38s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 40s
2025-02-03 14:20:18 -05:00
a5d7a35fdc Fixed formatDate
All checks were successful
Build / Build NPM Project (push) Successful in 42s
Build / Tag Version (push) Successful in 9s
Build / Publish Documentation (push) Successful in 38s
2025-01-08 14:21:14 -05:00
cb117273a7 Fixed path-event filter
All checks were successful
Build / Build NPM Project (push) Successful in 39s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 36s
2024-12-27 22:20:27 -05:00
3bda688b1e added blackOrWhite color contrast function
All checks were successful
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 36s
2024-12-26 10:40:39 -05:00
446b1aa9db Updated arg-parser help output
All checks were successful
Build / Build NPM Project (push) Successful in 1m2s
Build / Tag Version (push) Successful in 16s
Build / Publish Documentation (push) Successful in 57s
2024-11-29 18:26:09 -05:00
30be1c5a91 bump 0.23.4
All checks were successful
Build / Build NPM Project (push) Successful in 1m2s
Build / Tag Version (push) Successful in 14s
Build / Publish Documentation (push) Successful in 56s
2024-11-29 17:41:20 -05:00
6b328e64ba Added default help argument to arg-parser
Some checks failed
Build / Tag Version (push) Blocked by required conditions
Build / Publish Documentation (push) Blocked by required conditions
Build / Build NPM Project (push) Has been cancelled
2024-11-29 17:41:00 -05:00
435be31347 Added arg-parser
All checks were successful
Build / Build NPM Project (push) Successful in 1m46s
Build / Tag Version (push) Successful in 19s
Build / Publish Documentation (push) Successful in 1m10s
2024-11-29 17:26:07 -05:00
2522635815 Added JSONSerialize
All checks were successful
Build / Build NPM Project (push) Successful in 1m12s
Build / Tag Version (push) Successful in 12s
Build / Publish Documentation (push) Successful in 48s
2024-11-24 11:08:17 -05:00
22 changed files with 596 additions and 240 deletions

View File

@ -1,16 +0,0 @@
<!Doctype html>
<html>
<head>
<title>@ztimson/utils sandbox</title>
</head>
<body>
<script type="module">
import {formatDate} from './dist/index.mjs';
console.log(formatDate(new Date(), 'HH:mm:ss z', 5));
console.log(formatDate(new Date(), 'HH:mm:ss z', 0));
console.log(formatDate(new Date(), 'HH:mm:ss z', -5));
</script>
</body>
</html>

View File

@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.23.1", "version": "0.24.12",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",
@ -14,9 +14,9 @@
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"exports": { "exports": {
".": { ".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs", "import": "./dist/index.mjs",
"require": "./dist/index.cjs", "require": "./dist/index.cjs"
"types": "./dist/index.d.ts"
} }
}, },
"scripts": { "scripts": {
@ -26,6 +26,9 @@
"test:coverage": "npx jest --coverage", "test:coverage": "npx jest --coverage",
"watch": "npx vite build --watch" "watch": "npx vite build --watch"
}, },
"dependencies": {
"var-persist": "^1.0.1"
},
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.12", "@types/jest": "^29.5.12",
"jest": "^29.7.0", "jest": "^29.7.0",
@ -34,7 +37,7 @@
"typedoc": "^0.26.7", "typedoc": "^0.26.7",
"typescript": "^5.3.3", "typescript": "^5.3.3",
"vite": "^5.0.12", "vite": "^5.0.12",
"vite-plugin-dts": "^3.7.2" "vite-plugin-dts": "^4.5.3"
}, },
"files": [ "files": [
"dist" "dist"

141
src/arg-parser.ts Normal file
View File

@ -0,0 +1,141 @@
export type Arg<T = any> = {
/** Argument/property name */
name: string;
/** Argument description for help page */
desc: string;
/** Available shorthands */
flags?: string[];
/** Argument is not required */
optional?: boolean;
/** Default value if argument is not used */
default?: T;
/** Collects any unmatched arguments */
extras?: boolean;
}
export class ArgParser {
commands: ArgParser[] = [];
args: Arg[] = [];
flags: Arg[] = [];
defaults!: {[key: string]: any};
/**
* Create a unix-like argument parser to extract flags from the argument list. Can also create help messages.
*
* @param {string} name Script name
* @param {string} desc Help description
* @param {(ArgParser | Arg[]} argList Array of CLI arguments
* @param {string[]} examples Additional examples to display
*/
constructor(public readonly name: string,
public readonly desc: string,
public readonly argList: (ArgParser | Arg)[] = [],
public readonly examples: string[] = []
) {
// Arguments
this.commands = argList.filter(arg => arg instanceof ArgParser);
this.args = <Arg[]>argList.filter(arg => !(arg instanceof ArgParser) && !arg.flags?.length);
this.flags = <Arg[]>[...argList.filter(arg => !(arg instanceof ArgParser) && arg.flags && arg.flags.length),
{name: 'help', desc: 'Display command\'s help message', flags: ['-h', '--help'], default: false}];
this.defaults = argList.reduce((acc, arg: any) => ({...acc, [arg.name]: arg['extras'] ? [] : (arg.default ?? null)}), {});
// Examples
this.examples = <string[]>[
...examples,
`[OPTIONS] ${this.args.map(arg => (arg.optional ? `[${arg.name.toUpperCase()}]` : arg.name.toUpperCase()) + (arg.extras ? '...' : '')).join(' ')}`,
this.commands.length ? `[OPTIONS] COMMAND` : null,
`--help ${this.commands.length ? '[COMMAND]' : ''}`
].filter(e => !!e);
}
/**
* Parse an array into an arguments dictionary using the configuration.
*
* @param {string[]} args Array of arguments to be parsed
* @returns {object} Dictionary of arguments with defaults applied
*/
parse(args: string[]) {
// Parse arguments
let extras = [], parsed: any = {...this.defaults, '_error': []}, queue = [...args];
while(queue.length) {
let arg = queue.splice(0, 1)[0];
if(arg[0] == '-') { // Flags
// Check for combined shorthand
if(arg[1] != '-' && arg.length > 2) {
queue = [...arg.substring(2).split('').map(a => `-${a}`), ...queue];
arg = `-${arg[1]}`;
}
// Find & add flag
const combined = arg.split('=');
const argDef = this.flags.find(flag => flag.flags?.includes(combined[0] || arg));
if(argDef == null) { // Not found, add to extras
extras.push(arg);
continue;
}
const value = argDef.default === false ? true :
argDef.default === true ? false :
queue.splice(queue.findIndex(q => q[0] != '-'), 1)[0] ||
argDef.default;
if(value == null) parsed['_error'].push(`Option missing value: ${argDef.name || combined[0]}`);
parsed[argDef.name] = value;
} else { // Command
const c = this.commands.find(command => command.name == arg);
if(!!c) {
const parsedCommand = c.parse(queue.splice(0, queue.length));
Object.keys(parsedCommand).forEach(key => {
if(parsed[key] != parsedCommand[key] && parsedCommand[key] == c.defaults[key])
delete parsedCommand[key];
});
parsed = {
...parsed,
...parsedCommand,
_command: c.name
};
} else extras.push(arg); // Not found, add to extras
}
}
// Arguments
this.args.filter(arg => !arg.extras).forEach(arg => {
if(!arg.optional && !extras.length) parsed['_error'].push(`Argument missing: ${arg.name.toUpperCase()}`);
if(extras.length) parsed[arg.name] = extras.splice(0, 1)[0];
});
// Extras
const extraKey = this.args.find(arg => arg.extras)?.name || '_extra';
parsed[extraKey] = extras;
return parsed;
}
/**
* Create help message from the provided description & argument list.
*
* @returns {string} Help message
* @param opts Help options: command - display a commands help, message - override help description
*/
help(opts: {command?: string, message?: string} = {}): string {
const spacer = (text: string) => Array(24 - text.length || 1).fill(' ').join('');
// Help with specific command
if(opts.command) {
const argParser = this.commands.find(parser => parser.name == opts.command);
if(!argParser) throw new Error(`${opts.command.toUpperCase()} is not a command`)
return argParser.help({...opts, command: undefined});
}
// Description
let msg = `\n\n${opts.message || this.desc}`;
// Examples
msg += '\n\nUsage:\t' + this.examples.map(ex => `${this.name} ${ex}`).join('\n\t');
// Arguments
if(this.args.length) msg += '\n\n\t' + this.args.map(arg =>
`${arg.name.toUpperCase()}${spacer(arg.name)}${arg.desc}`).join('\n\t');
// Flags
msg += '\n\nOptions:\n\t' + this.flags.map(flag => {
const flags = flag.flags?.join(', ') || '';
return `${flags}${spacer(flags)}${flag.desc}`;
}).join('\n\t');
// Commands
if(this.commands.length) msg += '\n\nCommands:\n\t' + this.commands.map(command =>
`${command.name}${spacer(command.name)}${command.desc}`).join('\n\t');
return `${msg}\n\n`;
}
}

View File

@ -29,6 +29,14 @@ export class ASet<T> extends Array {
return this; return this;
} }
/**
* Remove all elements
*/
clear() {
this.splice(0, this.length);
return this;
}
/** /**
* Delete elements from set * Delete elements from set
* @param items Elements that will be deleted * @param items Elements that will be deleted

View File

@ -1,3 +1,5 @@
import {deepCopy} from './objects.ts';
export type CacheOptions = { export type CacheOptions = {
/** Delete keys automatically after x amount of seconds */ /** Delete keys automatically after x amount of seconds */
ttl?: number; ttl?: number;
@ -5,22 +7,25 @@ export type CacheOptions = {
storage?: Storage; storage?: Storage;
/** Key cache will be stored under */ /** Key cache will be stored under */
storageKey?: string; storageKey?: string;
/** Keep or delete cached items once expired, defaults to delete */
expiryPolicy?: 'delete' | 'keep';
} }
export type CachedValue<T> = T & {_expired?: boolean};
/** /**
* Map of data which tracks whether it is a complete collection & offers optional expiry of cached values * Map of data which tracks whether it is a complete collection & offers optional expiry of cached values
*/ */
export class Cache<K extends string | number | symbol, T> { export class Cache<K extends string | number | symbol, T> {
private store = <Record<K, T>>{}; private store: Record<K, T> = <any>{};
/** Support index lookups */ /** Support index lookups */
[key: string | number | symbol]: T | any; [key: string | number | symbol]: CachedValue<T> | any;
/** Whether cache is complete */ /** Whether cache is complete */
complete = false; complete = false;
/** /**
* Create new cache * Create new cache
*
* @param {keyof T} key Default property to use as primary key * @param {keyof T} key Default property to use as primary key
* @param options * @param options
*/ */
@ -37,11 +42,11 @@ export class Cache<K extends string | number | symbol, T> {
return new Proxy(this, { return new Proxy(this, {
get: (target: this, prop: string | symbol) => { get: (target: this, prop: string | symbol) => {
if(prop in target) return (target as any)[prop]; if(prop in target) return (target as any)[prop];
return target.store[prop as K]; return this.get(prop as K, true);
}, },
set: (target: this, prop: string | symbol, value: any) => { set: (target: this, prop: string | symbol, value: any) => {
if(prop in target) (target as any)[prop] = value; if(prop in target) (target as any)[prop] = value;
else target.store[prop as K] = value; else this.set(prop as K, value);
return true; return true;
} }
}); });
@ -52,18 +57,22 @@ export class Cache<K extends string | number | symbol, T> {
return <K>value[this.key]; return <K>value[this.key];
} }
private save() {
if(this.options.storageKey && this.options.storage)
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
}
/** /**
* Get all cached items * Get all cached items
*
* @return {T[]} Array of items * @return {T[]} Array of items
*/ */
all(): T[] { all(expired?: boolean): CachedValue<T>[] {
return Object.values(this.store); return deepCopy<any>(Object.values(this.store)
.filter((v: any) => expired || !v._expired));
} }
/** /**
* 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 {T} value Item to add to cache
* @param {number | undefined} ttl Override default expiry * @param {number | undefined} ttl Override default expiry
* @return {this} * @return {this}
@ -76,12 +85,12 @@ 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 {T[]} rows Several items that will be cached using the default key
* @param complete Mark cache as complete & reliable, defaults to true * @param complete Mark cache as complete & reliable, defaults to true
* @return {this} * @return {this}
*/ */
addAll(rows: T[], complete = true): this { addAll(rows: T[], complete = true): this {
this.clear();
rows.forEach(r => this.add(r)); rows.forEach(r => this.add(r));
this.complete = complete; this.complete = complete;
return this; return this;
@ -91,26 +100,36 @@ export class Cache<K extends string | number | symbol, T> {
* Remove all keys from cache * Remove all keys from cache
*/ */
clear() { clear() {
this.store = <Record<K, T>>{}; this.complete = false;
this.store = <any>{};
} }
/** /**
* Delete an item from the cache * Delete an item from the cache
*
* @param {K} key Item's primary key * @param {K} key Item's primary key
*/ */
delete(key: K) { delete(key: K) {
delete this.store[key]; delete this.store[key];
if(this.options.storageKey && this.options.storage) this.save();
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
} }
/** /**
* Return cache as an array of key-value pairs * Return cache as an array of key-value pairs
* @return {[K, T][]} Key-value pairs array * @return {[K, T][]} Key-value pairs array
*/ */
entries(): [K, T][] { entries(expired?: boolean): [K, CachedValue<T>][] {
return <[K, T][]>Object.entries(this.store); return deepCopy<any>(Object.entries(this.store)
.filter((v: any) => expired || !v?._expired));
}
/**
* Manually expire a cached item
* @param {K} key Key to expire
*/
expire(key: K) {
this.complete = false;
if(this.options.expiryPolicy == 'keep') (<any>this.store[key])._expired = true;
else this.delete(key);
} }
/** /**
@ -118,50 +137,53 @@ export class Cache<K extends string | number | symbol, T> {
* @param {K} key Key to lookup * @param {K} key Key to lookup
* @return {T} Cached item * @return {T} Cached item
*/ */
get(key: K): T { get(key: K, expired?: boolean): T | null {
return this.store[key]; const cached = deepCopy<any>(this.store[key] ?? null);
if(expired || !cached?._expired) return cached;
return null;
} }
/** /**
* Get a list of cached keys * Get a list of cached keys
*
* @return {K[]} Array of keys * @return {K[]} Array of keys
*/ */
keys(): K[] { keys(expired?: boolean): K[] {
return <K[]>Object.keys(this.store); return <K[]>Object.keys(this.store)
.filter(k => expired || !(<any>this.store)[k]._expired);
} }
/** /**
* Get map of cached items * Get map of cached items
*
* @return {Record<K, T>} * @return {Record<K, T>}
*/ */
map(): Record<K, T> { map(expired?: boolean): Record<K, CachedValue<T>> {
return structuredClone(this.store); const copy: any = deepCopy(this.store);
if(!expired) Object.keys(copy).forEach(k => {
if(copy[k]._expired) delete copy[k]
});
return copy;
} }
/** /**
* Add an item to the cache manually specifying the key * Add an item to the cache manually specifying the key
*
* @param {K} key Key item will be cached under * @param {K} key Key item will be cached under
* @param {T} value Item to cache * @param {T} value Item to cache
* @param {number | undefined} ttl Override default expiry in seconds * @param {number | undefined} ttl Override default expiry in seconds
* @return {this} * @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;
this.store[key] = value; this.store[key] = value;
if(this.options.storageKey && this.options.storage) this.save();
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
if(ttl) setTimeout(() => { if(ttl) setTimeout(() => {
this.complete = false; this.expire(key);
this.delete(key); this.save();
}, ttl * 1000); }, ttl * 1000);
return this; return this;
} }
/** /**
* Get all cached items * Get all cached items
*
* @return {T[]} Array of items * @return {T[]} Array of items
*/ */
values = this.all(); values = this.all();

12
src/color.ts Normal file
View File

@ -0,0 +1,12 @@
/**
* Determine if either black or white provides more contrast to the provided color
* @param {string} background Color to compare against
* @return {"white" | "black"} Color with the most contrast
*/
export function blackOrWhite(background: string): 'white' | 'black' {
const exploded = background?.match(background.length >= 6 ? /\w\w/g : /\w/g);
if(!exploded) return 'black';
const [r, g, b] = exploded.map(hex => parseInt(hex, 16));
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
return luminance > 0.5 ? 'black' : 'white';
}

View File

@ -1,29 +1,56 @@
import {makeArray} from './array.ts';
import {ASet} from './aset.ts'; import {ASet} from './aset.ts';
import {dotNotation, flattenObj, JSONSanitize} from './objects.ts'; import {dotNotation, flattenObj, JSONSanitize} from './objects.ts';
import {LETTER_LIST} from './string.ts'; import {LETTER_LIST} from './string.ts';
/**
* Parse a CSV string into an array of objects
*
* @param csv String with CSV
* @param hasHeaders First line of CSV contains headers
* @return {T[]} Array of parsed objects
*/
export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] { export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] {
const row = csv.split('\n');
let headers: any = hasHeaders ? row.splice(0, 1)[0] : null;
if(headers) headers = headers.match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g);
return <T[]>row.map(r => {
function parseLine(line: string): (string | null)[] { function parseLine(line: string): (string | null)[] {
const parts = line.split(','), columns: string[] = []; const columns: string[] = [];
let quoted = false; let current = '', inQuotes = false;
for(const p of parts) { for (let i = 0; i < line.length; i++) {
if(quoted) columns[columns.length - 1] = columns.at(-1) + ',' + p; const char = line[i];
else columns.push(p); const nextChar = line[i + 1];
if(/[^"]"$/g.test(p)) { if (char === '"') {
quoted = false; if (inQuotes && nextChar === '"') {
} else if(/^"[^"]/g.test(p)) { current += '"'; // Handle escaped quotes
quoted = true; i++;
} else inQuotes = !inQuotes;
} else if (char === ',' && !inQuotes) {
columns.push(current.trim()); // Trim column values
current = '';
} else current += char;
} }
} columns.push(current.trim()); // Trim last column value
return columns; return columns.map(col => col.replace(/^"|"$/g, '').replace(/""/g, '"'));
} }
// Normalize line endings and split rows
const rows = [];
let currentRow = '', inQuotes = false;
for (const char of csv.replace(/\r\n/g, '\n')) { // Normalize \r\n to \n
if (char === '"') inQuotes = !inQuotes;
if (char === '\n' && !inQuotes) {
rows.push(currentRow.trim()); // Trim row
currentRow = '';
} else currentRow += char;
}
if (currentRow) rows.push(currentRow.trim()); // Trim last row
// Extract headers
let headers: any = hasHeaders ? rows.splice(0, 1)[0] : null;
if (headers) headers = headers.match(/(?:[^,"']+|"(?:[^"]|"")*"|'(?:[^']|'')*')+/g)?.map((h: any) => h.trim());
// Parse rows
return <T[]>rows.map(r => {
const props = parseLine(r); const props = parseLine(r);
const h = headers || (Array(props.length).fill(null).map((r, i) => { const h = headers || (Array(props.length).fill(null).map((_, i) => {
let letter = ''; let letter = '';
const first = i / 26; const first = i / 26;
if (first > 1) letter += LETTER_LIST[Math.floor(first - 1)]; if (first > 1) letter += LETTER_LIST[Math.floor(first - 1)];
@ -34,23 +61,28 @@ export function fromCsv<T = any>(csv: string, hasHeaders=true): T[] {
dotNotation(acc, h, props[i]); dotNotation(acc, h, props[i]);
return acc; return acc;
}, {}); }, {});
}) });
} }
/** /**
* Convert an object to a CSV string * Convert an array of objects to a CSV string
* *
* @param {any[]} target Array of objects to create CSV from * @param {any[]} target Array of objects to create CSV from
* @param {boolean} flatten Should nested object be flattened or treated as values * @param {boolean} flatten Should nested object be flattened or treated as values
* @return {string} CSV string * @return {string} CSV string
*/ */
export function toCsv(target: any[], flatten=true) { export function toCsv(target: any, flatten=true) {
const headers = new ASet(target.reduce((acc, row) => [...acc, ...Object.keys(flatten ? flattenObj(row) : row)], [])); const t = makeArray(target);
const headers = new ASet(t.reduce((acc, row) => [...acc, ...Object.keys(flatten ? flattenObj(row) : row)], []));
return [ return [
headers.join(','), headers.join(','),
...target.map(row => headers.map((h: string) => { ...t.map(row => headers.map((h: string) => {
const value = dotNotation<any>(row, h); const value = dotNotation<any>(row, h);
return (typeof value == 'object' && value != null) ? '"' + JSONSanitize(value).replaceAll('"', '""') + '"' : value; if(value == null) return '';
if(typeof value == 'object') return `"${JSONSanitize(value).replaceAll('"', '""')}"`;
if(typeof value == 'string' && /[\n",]/g.test(value)) return `"${value.replaceAll('"', '""')}"`;
return value;
}).join(',')) }).join(','))
].join('\n'); ].join('\n');
} }

View File

@ -1,6 +1,7 @@
import {makeArray} from './array.ts'; import {makeArray} from './array.ts';
import {JSONAttemptParse} from './objects.ts'; import {JSONAttemptParse} from './objects.ts';
import {PromiseProgress} from './promise-progress'; import {PromiseProgress} from './promise-progress';
import {formatDate} from './time.ts';
/** /**
* Download blob as a file * Download blob as a file
@ -76,7 +77,7 @@ export function fileText(file: any): Promise<string | null> {
*/ */
export function timestampFilename(name?: string, date: Date | number | string = new Date()) { export function timestampFilename(name?: string, date: Date | number | string = new Date()) {
if(typeof date == 'number' || typeof date == 'string') date = new Date(date); if(typeof date == 'number' || typeof date == 'string') date = new Date(date);
const timestamp = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}_${date.getHours().toString().padStart(2, '0')}-${date.getMinutes().toString().padStart(2, '0')}-${date.getSeconds().toString().padStart(2, '0')}`; const timestamp = formatDate('YYYY-MM-DD_HH:mm:ss', date);
return name ? name.replace('{{TIMESTAMP}}', timestamp) : timestamp; return name ? name.replace('{{TIMESTAMP}}', timestamp) : timestamp;
} }

View File

@ -22,6 +22,28 @@ export type HttpDefaults = {
url?: string; url?: string;
} }
class HttpResponse<T = any> extends Response {
data?: T
ok!: boolean;
redirected!: boolean;
type!: ResponseType;
url!: string;
constructor(resp: Response, stream: ReadableStream) {
const body = [204, 205, 304].includes(resp.status) ? null : stream;
super(body, {
headers: resp.headers,
status: resp.status,
statusText: resp.statusText,
});
this.ok = resp.ok;
this.redirected = resp.redirected;
this.type = resp.type;
this.url = resp.url;
}
}
export class Http { export class Http {
private static interceptors: {[key: string]: HttpInterceptor} = {}; private static interceptors: {[key: string]: HttpInterceptor} = {};
@ -54,8 +76,9 @@ export class Http {
request<T>(opts: HttpRequestOptions = {}): PromiseProgress<DecodedResponse<T>> { request<T>(opts: HttpRequestOptions = {}): PromiseProgress<DecodedResponse<T>> {
if(!this.url && !opts.url) throw new Error('URL needs to be set'); if(!this.url && !opts.url) throw new Error('URL needs to be set');
let url = (opts.url?.startsWith('http') ? opts.url : (this.url || '') + (opts.url || '')).replace(/([^:]\/)\/+/g, '$1'); let url = opts.url?.startsWith('http') ? opts.url : (this.url || '') + (opts.url || '');
if(opts.fragment) url.includes('#') ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += '#' + opts.fragment; url = url.replaceAll(/([^:]\/)\/+/g, '$1');
if(opts.fragment) url.includes('#') ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : `${url}#${opts.fragment}`;
if(opts.query) { if(opts.query) {
const q = Array.isArray(opts.query) ? opts.query : const q = Array.isArray(opts.query) ? opts.query :
Object.keys(opts.query).map(k => ({key: k, value: (<any>opts.query)[k]})) Object.keys(opts.query).map(k => ({key: k, value: (<any>opts.query)[k]}))
@ -101,18 +124,17 @@ export class Http {
push(); push();
}).catch((error: any) => controller.error(error)); }).catch((error: any) => controller.error(error));
} }
push(); push();
} }
}); });
resp.data = new Response(stream); resp = new HttpResponse<T>(resp, stream);
if(opts.decode == null || opts.decode) { if(opts.decode !== false) {
const content = resp.headers.get('Content-Type')?.toLowerCase(); const content = resp.headers.get('Content-Type')?.toLowerCase();
if(content?.includes('form')) resp.data = <T>await resp.data.formData(); if(content?.includes('form')) resp.data = <T>await resp.formData();
else if(content?.includes('json')) resp.data = <T>await resp.data.json(); else if(content?.includes('json')) resp.data = <T>await resp.json();
else if(content?.includes('text')) resp.data = <T>await resp.data.text(); else if(content?.includes('text')) resp.data = <T>await resp.text();
else if(content?.includes('application')) resp.data = <T>await resp.data.blob(); else if(content?.includes('application')) resp.data = <T>await resp.blob();
} }
if(resp.ok) res(resp); if(resp.ok) res(resp);

View File

@ -1,6 +1,8 @@
export * from './arg-parser';
export * from './array'; export * from './array';
export * from './aset'; export * from './aset';
export * from './cache'; export * from './cache';
export * from './color';
export * from './csv'; export * from './csv';
export * from './files'; export * from './files';
export * from './emitter'; export * from './emitter';
@ -17,3 +19,4 @@ export * from './search';
export * from './string'; export * from './string';
export * from './time'; export * from './time';
export * from './types'; export * from './types';
export * from 'var-persist';

View File

@ -6,7 +6,7 @@ import {JSONAttemptParse} from './objects.ts';
* @param {string} token JWT to decode * @param {string} token JWT to decode
* @return {unknown} JWT payload * @return {unknown} JWT payload
*/ */
export function jwtDecode<T>(token: string): T { export function decodeJwt<T>(token: string): T {
const base64 = token.split('.')[1] const base64 = token.split('.')[1]
.replace(/-/g, '+').replace(/_/g, '/'); .replace(/-/g, '+').replace(/_/g, '/');
return <T>JSONAttemptParse(decodeURIComponent(atob(base64).split('').map(function(c) { return <T>JSONAttemptParse(decodeURIComponent(atob(base64).split('').map(function(c) {

View File

@ -1,6 +1,18 @@
import {PathEvent} from './path-events.ts'; import {PathEvent} from './path-events.ts';
import {md5} from './string'; import {md5} from './string';
/**
* Run a stringified function with arguments asynchronously
* @param {object} args Map of key/value arguments
* @param {string} fn Function as string
* @param {boolean} async Run with async (returns a promise)
* @return {T | Promise<T>} Function return result
*/
export function fn<T>(args: object, fn: string, async: boolean = false): T {
const keys = Object.keys(args);
return new Function(...keys, `return (${async ? 'async ' : ''}(${keys.join(',')}) => { ${fn} })(${keys.join(',')})`)(...keys.map(k => (<any>args)[k]));
}
/** /**
* Get profile image from Gravatar * Get profile image from Gravatar
* *

View File

@ -109,7 +109,6 @@ export function encodeQuery(data: any): string {
).join('&'); ).join('&');
} }
/** /**
* Recursively flatten a nested object, while maintaining key structure * Recursively flatten a nested object, while maintaining key structure
* *
@ -224,6 +223,17 @@ export function JSONAttemptParse<T1, T2>(json: T2): T1 | T2 {
catch { return 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. * Convert an object to a JSON string avoiding any circular references.
* *

View File

@ -31,7 +31,7 @@ export function PE(str: TemplateStringsArray, ...args: any[]) {
if(str[i]) combined.push(str[i]); if(str[i]) combined.push(str[i]);
if(args[i]) combined.push(args[i]); if(args[i]) combined.push(args[i]);
} }
return new PathEvent(combined.join('')); return new PathEvent(combined.join('/'));
} }
/** /**
@ -79,20 +79,20 @@ export class PathEvent {
set none(v: boolean) { v ? this.methods = new ASet<Method>(['n']) : this.methods.delete('n'); } set none(v: boolean) { v ? this.methods = new ASet<Method>(['n']) : this.methods.delete('n'); }
/** 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').add('c') : this.methods.delete('c'); } set create(v: boolean) { v ? this.methods.delete('n').delete('*').add('c') : this.methods.delete('c'); }
/** 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').add('r') : this.methods.delete('r'); } set read(v: boolean) { v ? this.methods.delete('n').delete('*').add('r') : this.methods.delete('r'); }
/** Update method specified */ /** Update method specified */
get update(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('u')) } get update(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('u')) }
set update(v: boolean) { v ? this.methods.delete('n').add('u') : this.methods.delete('u'); } set update(v: boolean) { v ? this.methods.delete('n').delete('*').add('u') : this.methods.delete('u'); }
/** Delete method specified */ /** Delete method specified */
get delete(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('d')) } get delete(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('d')) }
set delete(v: boolean) { v ? this.methods.delete('n').add('d') : this.methods.delete('d'); } set delete(v: boolean) { v ? this.methods.delete('n').delete('*').add('d') : this.methods.delete('d'); }
constructor(Event: string | PathEvent) { constructor(e: string | PathEvent) {
if(typeof Event == 'object') return Object.assign(this, Event); if(typeof e == 'object') return Object.assign(this, e);
let [p, scope, method] = Event.replaceAll(/\/{2,}/g, '/').split(':'); let [p, scope, method] = e.replaceAll(/\/{2,}/g, '/').split(':');
if(!method) method = scope || '*'; if(!method) method = scope || '*';
if(p == '*' || !p && method == '*') { if(p == '*' || !p && method == '*') {
p = ''; p = '';
@ -100,8 +100,8 @@ export class PathEvent {
} }
let temp = p.split('/').filter(p => !!p); let temp = p.split('/').filter(p => !!p);
this.module = temp.splice(0, 1)[0]?.toLowerCase() || ''; this.module = temp.splice(0, 1)[0]?.toLowerCase() || '';
this.fullPath = p;
this.path = temp.join('/'); this.path = temp.join('/');
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
this.name = temp.pop() || ''; this.name = temp.pop() || '';
this.methods = new ASet(<any>method.split('')); this.methods = new ASet(<any>method.split(''));
} }
@ -142,8 +142,9 @@ export class PathEvent {
const parsedFind = makeArray(filter).map(pe => new PathEvent(pe)); const parsedFind = makeArray(filter).map(pe => new PathEvent(pe));
return parsedTarget.filter(t => { return parsedTarget.filter(t => {
if(!t.fullPath && t.all) return true; if(!t.fullPath && t.all) return true;
return !!parsedFind.find(f => t.fullPath.startsWith(f.fullPath) return !!parsedFind.find(f =>
&& (f.all || t.all || t.methods.intersection(f.methods).length)); (t.fullPath.startsWith(f.fullPath) || f.fullPath.startsWith(t.fullPath)) &&
(f.all || t.all || t.methods.intersection(f.methods).length));
}); });
} }
@ -205,7 +206,7 @@ export class PathEvent {
* @return {string} String representation of Event * @return {string} String representation of Event
*/ */
static toString(path: string | string[], methods: Method | Method[]): string { static toString(path: string | string[], methods: Method | Method[]): string {
let p = makeArray(path).filter(p => p != null).join('/'); let p = makeArray(path).filter(p => !!p).join('/');
p = p?.trim().replaceAll(/\/{2,}/g, '/').replaceAll(/(^\/|\/$)/g, ''); p = p?.trim().replaceAll(/\/{2,}/g, '/').replaceAll(/(^\/|\/$)/g, '');
if(methods?.length) p += `:${makeArray(methods).map(m => m.toLowerCase()).join('')}`; if(methods?.length) p += `:${makeArray(methods).map(m => m.toLowerCase()).join('')}`;
return p; return p;
@ -234,11 +235,12 @@ export class PathEvent {
export type PathListener = (event: PathEvent, ...args: any[]) => any; export type PathListener = (event: PathEvent, ...args: any[]) => any;
export type PathUnsubscribe = () => void; export type PathUnsubscribe = () => void;
export type Event = string | PathEvent;
export interface IPathEventEmitter { export interface IPathEventEmitter {
emit(event: string, ...args: any[]): void; emit(event: Event, ...args: any[]): void;
off(listener: PathListener): void; off(listener: PathListener): void;
on(event: string, listener: PathListener): PathUnsubscribe; on(event: Event | Event[], listener: PathListener): PathUnsubscribe;
once(event: string, listener?: PathListener): Promise<any>; once(event: Event | Event[], listener?: PathListener): Promise<any>;
relayEvents(emitter: PathEventEmitter): void; relayEvents(emitter: PathEventEmitter): void;
} }
@ -248,8 +250,10 @@ export interface IPathEventEmitter {
export class PathEventEmitter implements IPathEventEmitter{ export class PathEventEmitter implements IPathEventEmitter{
private listeners: [PathEvent, PathListener][] = []; private listeners: [PathEvent, PathListener][] = [];
emit(event: string | PathEvent, ...args: any[]) { constructor(public readonly prefix: string = '') { }
const parsed = new PathEvent(event);
emit(event: Event, ...args: any[]) {
const parsed = new PathEvent(`${this.prefix}/${typeof event == 'string' ? event : event.toString()}`);
this.listeners.filter(l => PathEvent.has(l[0], event)) this.listeners.filter(l => PathEvent.has(l[0], event))
.forEach(async l => l[1](parsed, ...args)); .forEach(async l => l[1](parsed, ...args));
}; };
@ -258,12 +262,15 @@ export class PathEventEmitter implements IPathEventEmitter{
this.listeners = this.listeners.filter(l => l[1] != listener); this.listeners = this.listeners.filter(l => l[1] != listener);
} }
on(event: string | string[], listener: PathListener): PathUnsubscribe { on(event: Event | Event[], listener: PathListener): PathUnsubscribe {
makeArray(event).forEach(e => this.listeners.push([new PathEvent(e), listener])); makeArray(event).forEach(e => this.listeners.push([
new PathEvent(`${this.prefix}/${typeof e == 'string' ? event : event.toString()}`),
listener
]));
return () => this.off(listener); return () => this.off(listener);
} }
once(event: string | string[], listener?: PathListener): Promise<any> { once(event: Event | Event[], listener?: PathListener): Promise<any> {
return new Promise(res => { return new Promise(res => {
const unsubscribe = this.on(event, (event: PathEvent, ...args: any[]) => { const unsubscribe = this.on(event, (event: PathEvent, ...args: any[]) => {
res(args.length < 2 ? args[0] : args); res(args.length < 2 ? args[0] : args);

View File

@ -1,4 +1,4 @@
import {dotNotation, JSONAttemptParse} from './objects'; import {dotNotation, JSONAttemptParse, JSONSerialize} from './objects.ts';
export function search(rows: any[], search: string, regex?: boolean, transform: Function = (r: any) => r) { export function search(rows: any[], search: string, regex?: boolean, transform: Function = (r: any) => r) {
if(!rows) return []; if(!rows) return [];
@ -12,27 +12,48 @@ export function search(rows: any[], search: string, regex?: boolean, transform:
try { return RegExp(search, 'gm').test(v.toString()); } try { return RegExp(search, 'gm').test(v.toString()); }
catch { return false; } catch { return false; }
}).length }).length
} else {
return logicTest(r, search);
} }
// Make sure at least one OR passes });
const or = search.split('||').map(p => p.trim()).filter(p => !!p); }
/**
* Test an object against a logic condition. By default values are checked
* @param {string} condition
* @param {object} target
* @return {boolean}
*/
export function logicTest(target: object, condition: string): boolean {
const evalBoolean = (a: any, op: string, b: any): boolean => {
switch(op) {
case '=':
case '==': return a == b;
case '!=': return a != b;
case '>': return a > b;
case '>=': return a >= b;
case '<': return a < b;
case '<=': return a <= b;
default: return false;
}
}
const or = condition.split('||').map(p => p.trim()).filter(p => !!p);
return -1 != or.findIndex(p => { return -1 != or.findIndex(p => {
// Make sure all ANDs pass // Make sure all ANDs pass
const and = p.split('&&').map(p => p.trim()).filter(p => !!p); const and = p.split('&&').map(p => p.trim()).filter(p => !!p);
return and.filter(p => { return and.filter(p => {
// Boolean operator // Boolean operator
const prop = /(\w+)\s*(==?|!=|>=|>|<=|<)\s*(\w+)/g.exec(p); const prop = /(\S+)\s*(==?|!=|>=|>|<=|<)\s*(\S+)/g.exec(p);
if(prop) { if(prop) {
const a = JSON.stringify(JSONAttemptParse(dotNotation<any>(value, prop[1]))); const key = Object.keys(target).find(k => k.toLowerCase() == prop[1].toLowerCase());
const operator = prop[2] == '=' ? '==' : prop[2]; return evalBoolean(dotNotation<any>(target, key || prop[1]), prop[2], JSONAttemptParse(prop[3]));
const b = JSON.stringify(JSONAttemptParse(prop[3]));
return eval(`${a} ${operator} ${b}`);
} }
// Case-sensitive // Case-sensitive
const v = Object.values(value).join(''); const v = Object.values(target).map(JSONSerialize).join('');
if(/[A-Z]/g.test(search)) return v.includes(p); if(/[A-Z]/g.test(condition)) return v.includes(p);
// Case-insensitive // Case-insensitive
return v.toLowerCase().includes(p); return v.toLowerCase().includes(p);
}).length == and.length; }).length == and.length;
})
}); });
} }

View File

@ -18,6 +18,14 @@ export const SYMBOL_LIST = '~`!@#$%^&*()_-+={[}]|\\:;"\'<,>.?/';
*/ */
export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST + SYMBOL_LIST; export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST + SYMBOL_LIST;
/**
* Converts text to camelCase
*/
export function camelCase(str?: string) {
const text = pascalCase(str);
return text[0].toLowerCase() + text.slice(1);
}
/** /**
* Convert number of bytes into a human-readable size * Convert number of bytes into a human-readable size
* *
@ -64,6 +72,17 @@ export function insertAt(target: string, str: string, index: number): String {
return `${target.slice(0, index)}${str}${target.slice(index + 1)}`; return `${target.slice(0, index)}${str}${target.slice(index + 1)}`;
} }
/**
* Converts text to kebab-case
*/
export function kebabCase(str: string) {
if(!str) return '';
return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '')
.replaceAll(/([A-Z]|[0-9]+)/g, (...args) => `-${args[0].toLowerCase()}`)
.replaceAll(/([0-9])([a-z])/g, (...args) => `${args[1]}-${args[2]}`)
.replaceAll(/[^a-z0-9]+(\w?)/g, (...args) => `-${args[1] ?? ''}`).toLowerCase();
}
/** /**
* Add padding to string * Add padding to string
* *
@ -86,6 +105,18 @@ export function pad(text: any, length: number, char: string = ' ', start = true)
return text.toString().padEnd(length, char); return text.toString().padEnd(length, char);
} }
/**
* Convert text to PascalCase
* @param {string} str
* @return {string}
*/
export function pascalCase(str?: string) {
if(!str) return '';
const text = str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '')
.replaceAll(/[^a-zA-Z0-9]+(\w?)/g, (...args) => args[1]?.toUpperCase() || '');
return text[0].toUpperCase() + text.slice(1);
}
/** /**
* Generate a random hexadecimal value * Generate a random hexadecimal value
* *
@ -149,6 +180,17 @@ export function randomStringBuilder(length: number, letters = false, numbers = f
}).join(''); }).join('');
} }
/**
* Converts text to snake_case
*/
export function snakeCase(str?: string) {
if(!str) return '';
return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '')
.replaceAll(/([A-Z]|[0-9]+)/g, (...args) => `_${args[0].toLowerCase()}`)
.replaceAll(/([0-9])([a-z])/g, (...args) => `${args[1]}_${args[2]}`)
.replaceAll(/[^a-z0-9]+(\w?)/g, (...args) => `_${args[1] ?? ''}`).toLowerCase();
}
/** /**
* Splice a string together (Similar to Array.splice) * Splice a string together (Similar to Array.splice)
* *

View File

@ -23,12 +23,12 @@ export function adjustedInterval(cb: Function, ms: number) {
/** /**
* Format date * Format date
* *
* @param {Date | number | string} date Date or timestamp to convert to string
* @param {string} format How date string will be formatted, default: `YYYY-MM-DD H:mm A` * @param {string} format How date string will be formatted, default: `YYYY-MM-DD H:mm A`
* @param tz Override timezone, can be either string or number * @param {Date | number | string} date Date or timestamp, defaults to now
* @param tz Set timezone offset
* @return {string} Formated date * @return {string} Formated date
*/ */
export function formatDate(date: Date | number | string, format = 'YYYY-MM-DD H:mm', tz?: string | number): string { export function formatDate(format = 'YYYY-MM-DD H:mm', date: Date | number | string = new Date(), tz?: string | number): string {
const timezones = [ const timezones = [
['IDLW', -12], ['IDLW', -12],
['SST', -11], ['SST', -11],
@ -67,16 +67,7 @@ export function formatDate(date: Date | number | string, format = 'YYYY-MM-DD H:
} }
function day(num: number): string { function day(num: number): string {
switch(num) { return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][num] || 'Unknown';
case(0): return 'Sunday';
case(1): return 'Monday';
case(2): return 'Tuesday';
case(3): return 'Wednesday';
case(4): return 'Thursday';
case(5): return 'Friday';
case(6): return 'Saturday';
default: return 'Unknown';
}
} }
function doy(date: Date) { function doy(date: Date) {
@ -85,30 +76,16 @@ export function formatDate(date: Date | number | string, format = 'YYYY-MM-DD H:
} }
function month(num: number): string { function month(num: number): string {
switch(num) { return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][num] || 'Unknown';
case(0): return 'January';
case(1): return 'February';
case(2): return 'March';
case(3): return 'April';
case(4): return 'May';
case(5): return 'June';
case(6): return 'July';
case(7): return 'August';
case(8): return 'September';
case(9): return 'October';
case(10): return 'November';
case(11): return 'December';
default: return 'Unknown';
}
} }
function suffix(num: number) { function suffix(num: number) {
let n = num.toString(); if (num % 100 >= 11 && num % 100 <= 13) return `${num}th`;
switch(n.at(-1)) { switch (num % 10) {
case('1'): return num + 'st'; case 1: return `${num}st`;
case('2'): return num + 'nd'; case 2: return `${num}nd`;
case('3'): return num + 'rd'; case 3: return `${num}rd`;
default: return num + 'th'; default: return `${num}th`;
} }
} }
@ -118,7 +95,7 @@ export function formatDate(date: Date | number | string, format = 'YYYY-MM-DD H:
return (offset > 0 ? '-' : '') + `${hours}:${minutes.toString().padStart(2, '0')}`; return (offset > 0 ? '-' : '') + `${hours}:${minutes.toString().padStart(2, '0')}`;
} }
if(typeof date == 'number' || typeof date == 'string') date = new Date(date); if(typeof date == 'number' || typeof date == 'string' || date == null) date = new Date(date);
// Handle timezones // Handle timezones
let t!: [string, number]; let t!: [string, number];
@ -127,46 +104,36 @@ export function formatDate(date: Date | number | string, format = 'YYYY-MM-DD H:
if(!t) throw new Error(`Unknown timezone: ${tz}`); if(!t) throw new Error(`Unknown timezone: ${tz}`);
date = adjustTz(date, t[1]); date = adjustTz(date, t[1]);
return format // Token mapping
// Year const tokens: Record<string, string> = {
.replaceAll('YYYY', date.getFullYear().toString()) 'YYYY': date.getFullYear().toString(),
.replaceAll('YY', date.getFullYear().toString().slice(2)) 'YY': date.getFullYear().toString().slice(2),
// Month 'MMMM': month(date.getMonth()),
.replaceAll('MMMM', month(date.getMonth())) 'MMM': month(date.getMonth()).slice(0, 3),
.replaceAll('MMM', month(date.getMonth()).slice(0, 3)) 'MM': (date.getMonth() + 1).toString().padStart(2, '0'),
.replaceAll('MM', (date.getMonth() + 1).toString().padStart(2, '0')) 'M': (date.getMonth() + 1).toString(),
.replaceAll('M', (date.getMonth() + 1).toString()) 'DDD': doy(date).toString(),
// Day 'DD': date.getDate().toString().padStart(2, '0'),
.replaceAll('DDD', doy(date).toString()) 'Do': suffix(date.getDate()),
.replaceAll('DD', date.getDate().toString().padStart(2, '0')) 'D': date.getDate().toString(),
.replaceAll('Do', suffix(date.getDate())) 'dddd': day(date.getDay()),
.replaceAll('D', date.getDate().toString()) 'ddd': day(date.getDay()).slice(0, 3),
.replaceAll('dddd', day(date.getDay())) 'HH': date.getHours().toString().padStart(2, '0'),
.replaceAll('ddd', day(date.getDay()).slice(0, 2)) 'H': date.getHours().toString(),
.replaceAll('dd', date.getDate().toString().padStart(2, '0')) 'hh': (date.getHours() % 12 || 12).toString().padStart(2, '0'),
.replaceAll('d', date.getDay().toString()) 'h': (date.getHours() % 12 || 12).toString(),
// Hour 'mm': date.getMinutes().toString().padStart(2, '0'),
.replaceAll('HH', date.getHours().toString().padStart(2, '0')) 'm': date.getMinutes().toString(),
.replaceAll('H', date.getHours().toString()) 'ss': date.getSeconds().toString().padStart(2, '0'),
.replaceAll('hh', (date.getHours() > 12 ? date.getHours() - 12 : date.getHours()).toString().padStart(2, '0')) 's': date.getSeconds().toString(),
.replaceAll('h', (date.getHours() > 12 ? date.getHours() - 12 : date.getHours()).toString()) 'SSS': date.getMilliseconds().toString().padStart(3, '0'),
// Minute 'A': date.getHours() >= 12 ? 'PM' : 'AM',
.replaceAll('mm', date.getMinutes().toString().padStart(2, '0')) 'a': date.getHours() >= 12 ? 'pm' : 'am',
.replaceAll('m', date.getMinutes().toString()) 'ZZ': tzOffset(t[1] * 60).replace(':', ''),
// Second 'Z': tzOffset(t[1] * 60),
.replaceAll('ss', date.getSeconds().toString().padStart(2, '0')) 'z': typeof tz == 'string' ? tz : (<any>t)[0]
.replaceAll('s', date.getSeconds().toString()) };
// Millisecond return format.replace(/YYYY|YY|MMMM|MMM|MM|M|DDD|DD|Do|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|SSS|A|a|ZZ|Z|z/g, token => tokens[token]);
.replaceAll('SSS', date.getMilliseconds().toString().padEnd(3, '0'))
.replaceAll('SS', date.getMilliseconds().toString().slice(0, 1).padEnd(2, '0'))
.replaceAll('S', date.getMilliseconds().toString()[0])
// Period/Meridian (AM/PM)
.replaceAll('A', date.getHours() >= 12 ? 'PM' : 'AM')
.replaceAll('a', date.getHours() >= 12 ? 'pm' : 'am')
// Timezone
.replaceAll('ZZ', tzOffset(t[1] * 60).replace(':', ''))
.replaceAll('Z', tzOffset(t[1] * 60))
.replaceAll('z', typeof tz == 'string' ? tz : (<any>t)[0]);
} }
/** /**

View File

@ -18,3 +18,10 @@
export function typeKeys<T extends object>() { export function typeKeys<T extends object>() {
return Object.keys(<T>{}) as Array<keyof T>; return Object.keys(<T>{}) as Array<keyof T>;
} }
/**
* Mark all properties as writable
*/
export type Writable<T> = {
-readonly [P in keyof T]: T[P]
};

View File

@ -1,36 +1,18 @@
import {sleep, parseUrl} from '../src'; import {fn} from '../src';
describe('Miscellanies Utilities', () => { describe('Miscellanies Utilities', () => {
describe('sleep', () => { describe('fn', () => {
test('wait until', async () => { test('async', async () => {
const wait = ~~(Math.random() * 500); const test = {a: Math.random()};
const time = new Date().getTime(); const resp = fn(test, 'return a;', true);
await sleep(wait); expect(resp instanceof Promise).toBeTruthy();
expect(new Date().getTime()).toBeGreaterThanOrEqual(time + wait); expect(await resp).toEqual(test['a']);
});
}); });
describe('urlParser', () => { test('sync', async () => {
test('localhost w/ port', () => { const test = {a: Math.random()};
const parsed = parseUrl('http://localhost:4200/some/path?q1=test1&q2=test2#frag'); const resp = fn(test, 'return a;3');
expect(parsed.protocol).toStrictEqual('http'); expect(resp).toEqual(test['a']);
expect(parsed.host).toStrictEqual('localhost:4200');
expect(parsed.domain).toStrictEqual('localhost');
expect(parsed.port).toStrictEqual(4200);
expect(parsed.path).toStrictEqual('/some/path');
expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
expect(parsed.fragment).toStrictEqual('frag');
});
test('advanced URL', () => {
const parsed = parseUrl('https://sub.domain.example.com/some/path?q1=test1&q2=test2#frag');
expect(parsed.protocol).toStrictEqual('https');
expect(parsed.host).toStrictEqual('sub.domain.example.com');
expect(parsed.domain).toStrictEqual('example.com');
expect(parsed.subdomain).toStrictEqual('sub.domain');
expect(parsed.path).toStrictEqual('/some/path');
expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
expect(parsed.fragment).toStrictEqual('frag');
}); });
}); });
}); });

43
tests/path-events.spec.ts Normal file
View File

@ -0,0 +1,43 @@
import {PathEvent} from '../src';
describe('Path Events', () => {
describe('malformed', () => {
test('starting slash', async () =>
expect(new PathEvent('/module').toString()).toEqual('module:*'));
test('trailing slash', async () =>
expect(new PathEvent('module/').toString()).toEqual('module:*'));
test('double slash', async () =>
expect(new PathEvent('module////path').toString()).toEqual('module/path:*'));
});
describe('methods', () => {
test('custom', async () => {
expect(new PathEvent('module:t').methods.includes('t')).toBeTruthy();
expect(new PathEvent('module:t').methods.includes('z')).toBeFalsy();
});
test('create', async () =>
expect(new PathEvent('module:crud').create).toBeTruthy());
test('read', async () =>
expect(new PathEvent('module:crud').read).toBeTruthy());
test('update', async () =>
expect(new PathEvent('module:crud').update).toBeTruthy());
test('delete', async () =>
expect(new PathEvent('module:crud').delete).toBeTruthy());
test('none', async () => {
const event = new PathEvent('module:n');
expect(event.none).toBeTruthy();
expect(event.create).toBeFalsy();
expect(event.read).toBeFalsy();
expect(event.update).toBeFalsy();
expect(event.delete).toBeFalsy()
});
test('wildcard', async () => {
const event = new PathEvent('module:*');
expect(event.none).toBeFalsy();
expect(event.create).toBeTruthy();
expect(event.read).toBeTruthy();
expect(event.update).toBeTruthy();
expect(event.delete).toBeTruthy()
});
});
});

View File

@ -1,4 +1,5 @@
import {matchAll, randomString, randomStringBuilder} from "../src"; import {matchAll, parseUrl, randomString, randomStringBuilder} from "../src";
describe('String Utilities', () => { describe('String Utilities', () => {
describe('randomString', () => { describe('randomString', () => {
@ -47,4 +48,28 @@ describe('String Utilities', () => {
test('using regex', () => expect(matchAll('fooBar fooBar FooBar', /fooBar/g).length).toBe(2)); test('using regex', () => expect(matchAll('fooBar fooBar FooBar', /fooBar/g).length).toBe(2));
test('using malformed regex', () => expect(() => matchAll('fooBar fooBar FooBar', /fooBar/)).toThrow()); test('using malformed regex', () => expect(() => matchAll('fooBar fooBar FooBar', /fooBar/)).toThrow());
}); });
describe('urlParser', () => {
test('localhost', () => {
const parsed = parseUrl('http://localhost:4200/some/path?q1=test1&q2=test2#frag');
expect(parsed.protocol).toStrictEqual('http');
expect(parsed.host).toStrictEqual('localhost:4200');
expect(parsed.domain).toStrictEqual('localhost');
expect(parsed.port).toStrictEqual(4200);
expect(parsed.path).toStrictEqual('/some/path');
expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
expect(parsed.fragment).toStrictEqual('frag');
});
test('subdomains', () => {
const parsed = parseUrl('https://sub.domain.example.com/some/path?q1=test1&q2=test2#frag');
expect(parsed.protocol).toStrictEqual('https');
expect(parsed.host).toStrictEqual('sub.domain.example.com');
expect(parsed.domain).toStrictEqual('example.com');
expect(parsed.subdomain).toStrictEqual('sub.domain');
expect(parsed.path).toStrictEqual('/some/path');
expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
expect(parsed.fragment).toStrictEqual('frag');
});
});
}); });

12
tests/time.spec.ts Normal file
View File

@ -0,0 +1,12 @@
import {sleep} from '../src';
describe('Time Utilities', () => {
describe('sleep', () => {
test('wait until', async () => {
const wait = ~~(Math.random() * 500);
const time = new Date().getTime();
await sleep(wait);
expect(new Date().getTime()).toBeGreaterThanOrEqual(time + wait);
});
});
});