Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@handy-common-utils/misc-utils

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@handy-common-utils/misc-utils

Miscellaneous utilities

  • 1.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
91
decreased by-20.87%
Maintainers
1
Weekly downloads
 
Created
Source

@handy-common-utils/misc-utils

Miscellaneous utilities

Version Downloads/week CI codecov

How to use

First add it as a dependency:

npm install @handy-common-utils/misc-utils

Then you can use it in the code:

import { shortBase64UrlFromUInt32 } from '@handy-common-utils/misc-utils';

const urlSafeBase64 = shortBase64UrlFromUInt32(12345);
 // use chalk (chalk is not a dependency of this package, you need to add chalk as a dependency separately)
 import chalk from 'chalk';
 import { LineLogger } from '@handy-common-utils/misc-utils';

 // this.flags is an object with properties "debug" and "quiet"
 this.output = LineLogger.consoleWithColour(this.flags, chalk);
 this.output.warn('Configuration file not found, default configuration would be used.');  // it would be printed out in yellow

API

@handy-common-utils/misc-utils

Modules

Classes

Class: LineLogger<DEBUG_FUNC, INFO_FUNC, WARN_FUNC, ERROR_FUNC>

line-logger.LineLogger

A LineLogger logs/prints one entire line of text before advancing to another line. This class is useful for encapsulating console.log/info/warn/error functions. By having an abstraction layer, your code can switching to a different output with nearly no change.

Please note that although the name contains "Logger", this class is not intended to be used as a generic logger. It is intended for "logging for humans to read" scenario.

LineLogger.console() and LineLogger.consoleWithColour() are ready to use convenient functions. Or you can use the constructor to build your own wrappers.

example



// Just a wrapper of console.log/info/warn/error
const consoleLogger = LineLogger.console();

// Wrapper of console.log/info/warn/error but it mutes console.log
const lessVerboseConsoleLogger = LineLogger.console({debug: false});

// Wrapper of console.log/info/warn/error but it mutes console.log and console.info
const lessVerboseConsoleLogger = LineLogger.console({quiet: true});

// use chalk (chalk is not a dependency of this package, you need to add chalk as a dependency separately)
import chalk from 'chalk';
// this.flags is an object with properties "debug" and "quiet"
this.output = LineLogger.consoleWithColour(this.flags, chalk);
this.output.warn('Configuration file not found, default configuration would be used.');  // it would be printed out in yellow

Type parameters
NameType
DEBUG_FUNCextends Function
INFO_FUNCextends Function
WARN_FUNCextends Function
ERROR_FUNCextends Function
Constructors
constructor

new LineLogger<DEBUG_FUNC, INFO_FUNC, WARN_FUNC, ERROR_FUNC>(debugFunction, infoFunction, warnFunction, errorFunction, isDebug?, isQuiet?)

Constructor

Type parameters
NameType
DEBUG_FUNCextends Function
INFO_FUNCextends Function
WARN_FUNCextends Function
ERROR_FUNCextends Function
Parameters
NameTypeDefault valueDescription
debugFunctionDEBUG_FUNCundefinedfunction for outputting debug information
infoFunctionINFO_FUNCundefinedfunction for outputting info information
warnFunctionWARN_FUNCundefinedfunction for outputting warn information
errorFunctionERROR_FUNCundefinedfunction for outputting error information
isDebugbooleanfalseis debug output enabled or not, it could be overriden by isQuiet
isQuietbooleanfalseis quiet mode enabled or not. When quiet mode is enabled, both debug and info output would be discarded.
Properties
PropertyDescription
debug: DEBUG_FUNC
error: ERROR_FUNC
info: INFO_FUNC
isDebug: boolean = false
isQuiet: boolean = false
warn: WARN_FUNC
Static Protected NO_OP_FUNC: () => voidType declaration:
▸ (): void

Returns:
void
Methods
console

Static console<FLAGS>(flags?, debugFlagName?, quietFlagName?): LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

Build an instance with console.log/info/warn/error.

Type parameters
NameType
FLAGSextends Record<string, any>
Parameters
NameTypeDefault valueDescription
flagsFLAGSundefinedThe flag object that contains fields for knowning whether debug is enabled and whether quiet mode is enabled. Values of those fields are evaluated only once within this function. They are not evaluated when debug/info/warn/error functions are called.
debugFlagNamekeyof FLAGS'debug'Name of the debug field in the flags object
quietFlagNamekeyof FLAGS'quiet'Name of the quiet field in the flags object
Returns

LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

An instance that uses console.log/info/warn/error.


consoleLike

Static consoleLike(log): LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

Build an instance from 'log' (https://github.com/medikoo/log). info of the LineLogger is mapped to notice of the medikoo log.

Parameters
NameTypeDescription
logMedikooLoggerinstance of the logger
Returns

LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

instance of LineLogger that is actually ConsoleLineLogger type


consoleWithColour

Static consoleWithColour<FLAGS, COLOURER>(flags, colourer, debugColourFuncName?, infoColourFuncName?, warnColourFuncName?, errorColourFuncName?, debugFlagName?, quietFlagName?): LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

Build an instance with console.log/info/warn/error and chalk/colors/cli-color. This package does not depend on chalk or colors or cli-color, you need to add them as dependencies separately.

Type parameters
NameType
FLAGSextends Record<string, any>
COLOURERextends Record<string, any>
Parameters
NameTypeDefault valueDescription
flagsFLAGSundefinedThe flag object that contains fields for knowning whether debug is enabled and whether quiet mode is enabled. Values of those fields are evaluated only once within this function. They are not evaluated when debug/info/warn/error functions are called.
colourerCOLOURERundefinedSupplier of the colouring function, such as chalk or colors or cli-color
debugColourFuncNamekeyof COLOURER'grey'Name of the function within colourer that will be used to add colour to debug messages, or null if colouring is not desired.
infoColourFuncName?keyof COLOURERundefinedName of the function within colourer that will be used to add colour to info messages, or null if colouring is not desired.
warnColourFuncNamekeyof COLOURER'yellow'Name of the function within colourer that will be used to add colour to warn messages, or null if colouring is not desired.
errorColourFuncNamekeyof COLOURER'red'Name of the function within colourer that will be used to add colour to error messages, or null if colouring is not desired.
debugFlagNamekeyof FLAGS'debug'Name of the debug field in the flags object
quietFlagNamekeyof FLAGS'quiet'Name of the quiet field in the flags object
Returns

LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

An instance that uses console.log/info/warn/error and also adds colour to the messages using chalk/colors/cli-color.

Modules

Module: index

References
ConsoleLineLogger

Re-exports ConsoleLineLogger


LineLogger

Re-exports LineLogger


PathAwareReplacer

Re-exports PathAwareReplacer


consoleLike

Re-exports consoleLike


consoleWithColour

Re-exports consoleWithColour


consoleWithoutColour

Re-exports consoleWithoutColour


mask

Re-exports mask


maskAll

Re-exports maskAll


maskEmail

Re-exports maskEmail


maskFullName

Re-exports maskFullName


pathAwareReplacer

Re-exports pathAwareReplacer


pathBasedReplacer

Re-exports pathBasedReplacer

Functions
base64FromUInt32

base64FromUInt32<T>(ui32): Exclude<T, number> | string

Encode an unsigned 32-bit integer into BASE64 string.

Type parameters
NameType
Textends undefined | null | number
Parameters
NameTypeDescription
ui32TA 32-bit integer number which could also be null or undefined. It must be a valid unsigned 32-bit integer. Behavior is undefined when valueis anything other than an unsigned 32-bit integer. If you don't care about loosing precision, you can convert a number by doing n >>> 0 (See https://stackoverflow.com/questions/22335853/hack-to-convert-javascript-number-to-uint32)
Returns

Exclude<T, number> | string

BASE64 string representing the integer input, or the original input if it is null or undefined.


base64UrlFromUInt32

base64UrlFromUInt32<T>(ui32, replacements?): Exclude<T, number> | string

Encode an unsigned 32-bit integer into URL/path safe BASE64 string.

Type parameters
NameType
Textends undefined | null | number
Parameters
NameTypeDefault valueDescription
ui32TundefinedA 32-bit integer number which could also be null or undefined. It must be a valid unsigned 32-bit integer. Behavior is undefined when valueis anything other than an unsigned 32-bit integer. If you don't care about loosing precision, you can convert a number by doing n >>> 0 (See https://stackoverflow.com/questions/22335853/hack-to-convert-javascript-number-to-uint32)
replacementsstring'_-='A string containing replacement characters for "/", "+", and "=". If omitted, default value of '_-=' would be used.
Returns

Exclude<T, number> | string

URL/path safe BASE64 string representing the integer input, or the original input if it is null or undefined.


shortBase64FromUInt32

shortBase64FromUInt32<T>(ui32): Exclude<T, number> | string

Encode an unsigned 32-bit integer into BASE64 string without trailing '='.

Type parameters
NameType
Textends undefined | null | number
Parameters
NameTypeDescription
ui32TA 32-bit integer number which could also be null or undefined. It must be a valid unsigned 32-bit integer. Behavior is undefined when valueis anything other than an unsigned 32-bit integer. If you don't care about loosing precision, you can convert a number by doing n >>> 0 (See https://stackoverflow.com/questions/22335853/hack-to-convert-javascript-number-to-uint32)
Returns

Exclude<T, number> | string

BASE64 string without trailing '=' representing the integer input, or the original input if it is null or undefined.


shortBase64UrlFromUInt32

shortBase64UrlFromUInt32<T>(ui32, replacements?): Exclude<T, number> | string

Encode an unsigned 32-bit integer into URL/path safe BASE64 string without trailling '='.

Type parameters
NameType
Textends undefined | null | number
Parameters
NameTypeDefault valueDescription
ui32TundefinedA 32-bit integer number which could also be null or undefined. It must be a valid unsigned 32-bit integer. Behavior is undefined when valueis anything other than an unsigned 32-bit integer. If you don't care about loosing precision, you can convert a number by doing n >>> 0 (See https://stackoverflow.com/questions/22335853/hack-to-convert-javascript-number-to-uint32)
replacementsstring'_-'A string containing replacement characters for "/" and "+". If omitted, default value of '_-' would be used.
Returns

Exclude<T, number> | string

URL/path safe BASE64 string without trailing '=' representing the integer input, or the original input if it is null or undefined.


urlSafe

urlSafe<T>(base64Input, replacements?): T

Make a "normal" (BASE64) string URL/path safe.

Type parameters
NameType
Textends undefined | null | string
Parameters
NameTypeDefault valueDescription
base64InputTundefinedA (BASE64) string which could be null or undefined.
replacementsstring'_-='A string containing replacement characters for "/", "+", and "=". If omitted, default value of '_-=' would be used.
Returns

T

URL/path safe version of the (BASE64) input string, or the original input if it is null or undefined.

Module: line-logger

Classes
Type aliases
ConsoleLineLogger

Ƭ ConsoleLineLogger: ReturnType<typeof console>

Type of the object returned by LineLogger.console() or LineLogger.consoleWithColour(). It has the same function signatures as console.log/info/warn/error.

Functions
consoleLike

consoleLike(log): LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

Build an instance from 'log' (https://github.com/medikoo/log). info of the LineLogger is mapped to notice of the medikoo log.

Parameters
NameTypeDescription
logMedikooLoggerinstance of the logger
Returns

LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

instance of LineLogger that is actually ConsoleLineLogger type


consoleWithColour

consoleWithColour<FLAGS, COLOURER>(flags, colourer, debugColourFuncName?, infoColourFuncName?, warnColourFuncName?, errorColourFuncName?, debugFlagName?, quietFlagName?): LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

Build an encapsulation of console output functions with console.log/info/warn/error and chalk/colors/cli-color.

Type parameters
NameType
FLAGSextends Record<string, any>
COLOURERextends Record<string, any>
Parameters
NameTypeDefault valueDescription
flagsFLAGSundefinedThe flag object that contains fields for knowning whether debug is enabled and whether quiet mode is enabled. Values of those fields are evaluated only once within this function. They are not evaluated when debug/info/warn/error functions are called.
colourerCOLOURERundefinedSupplier of the colouring function, such as chalk or colors or cli-color
debugColourFuncNamekeyof COLOURER'grey'Name of the function within colourer that will be used to add colour to debug messages, or null if colouring is not desired.
infoColourFuncName?keyof COLOURERundefinedName of the function within colourer that will be used to add colour to info messages, or null if colouring is not desired.
warnColourFuncNamekeyof COLOURER'yellow'Name of the function within colourer that will be used to add colour to warn messages, or null if colouring is not desired.
errorColourFuncNamekeyof COLOURER'red'Name of the function within colourer that will be used to add colour to error messages, or null if colouring is not desired.
debugFlagNamekeyof FLAGS'debug'Name of the debug field in the flags object
quietFlagNamekeyof FLAGS'quiet'Name of the quiet field in the flags object. Quiet flag can override debug flag.
Returns

LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

An LineLogger instance that uses console.log/info/warn/error and also adds colour to the messages using chalk/colors/cli-color.


consoleWithoutColour

consoleWithoutColour<FLAGS>(flags?, debugFlagName?, quietFlagName?): LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

Build an encapsulation of console output functions with console.log/info/warn/error.

Type parameters
NameType
FLAGSextends Record<string, any>
Parameters
NameTypeDefault valueDescription
flagsFLAGSundefinedThe flag object that contains fields for knowning whether debug is enabled and whether quiet mode is enabled. Values of those fields are evaluated only once within this function. They are not evaluated when debug/info/warn/error functions are called.
debugFlagNamekeyof FLAGS'debug'Name of the debug field in the flags object
quietFlagNamekeyof FLAGS'quiet'Name of the quiet field in the flags object. Quiet flag can override debug flag.
Returns

LineLogger<(message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void, (message?: any, ...optionalParams: any[]) => void>

An LineLogger instance that uses console.log/info/warn/error.

Module: mask

Functions
mask

mask<T>(input, keepLeft?, keepRight?, minLength?, maskLengthOrMaskString?, maskPattern?): T

Mask the content of a string

Type parameters
NameType
Textends undefined | null | string
Parameters
NameTypeDefault valueDescription
inputTundefinedThe input which could also be null or undefined
keepLeftnumber1Number of characters on the left to be kept in the output without masking. Default value is 1.
keepRightnumber0Number of characters on the right to be kept in the output without masking. Default value is 0.
minLengthnumber3Minimal length of the string for keepLeft and keepRight to be effective. If the input string is shorter than this length, the whole string would be masked. Default value is 3.
maskLengthOrMaskStringundefined | null | string | numbernullThe string to be used for replacing the part in the input that needs to be masked, or the length of the mask string if a fixed length is desired, or null/undefined if the mask string should have the same length as the part to be masked. Default value is null.
maskPatternstring'*'The pattern to be repeated as the mask. Default value is '*'.
Returns

T

String with masked content


maskAll

maskAll<T>(input): T

Replace each character of the input with '*'

Type parameters
NameType
Textends undefined | null | string
Parameters
NameTypeDescription
inputTa string or null or undefined
Returns

T

masked string or null or undefined


maskEmail

maskEmail<T>(email): T

Mask sensitive information in an email address while keeping some information for troubleshooting

Type parameters
NameType
Textends undefined | null | string
Parameters
NameTypeDescription
emailTthe email address which could also be null or undefined
Returns

T

masked email address


maskFullName

maskFullName<T>(name): T

Mask sensitive information in the full name while keeping useful information for troubleshooting

Type parameters
NameType
Textends undefined | null | string
Parameters
NameTypeDescription
nameTthe full name which could also be null or undefined
Returns

T

masked full name

Module: stringify-replacer

Type aliases
PathAwareReplacer

Ƭ PathAwareReplacer: (key: string, value: any, path: string, parent: Parent, pathArray: string[], ancestors: Parent[]) => any

Type declaration

▸ (key, value, path, parent, pathArray, ancestors): any

The replacer that can potentially utilise the full path of the property in the object.

####### Parameters

NameTypeDescription
keystringName of the property, or the index in the parent array.
valueanyValue of the property or the object in the parent array.
pathstringThe full path of the property in the object, such like "access.visitor.location" or "request.x-forwarded-for.0". Please note that the special characters (including ".") in property names are not escaped, for example, "order.billing address.first line".
parentParentThe object that the property or the element belongs to. It could be { '': <the original object> } when this replacer function is called the first time.
pathArraystring[]The full path as an array. It is more useful than path in case special characters exist in property names. When this replacer function is called the first time, pathArray array would have a zero length.
ancestorsParent[]All the ancestor objects/arrays of the property. When this replacer function is called the first time, ancestors array would have a zero length.

####### Returns

any

Functions
pathAwareReplacer

pathAwareReplacer(replacer, options?): JsonStringifyReplacer

Build a replacer function that can be passed to JSON.stringify(...).

Parameters
NameTypeDescription
replacerPathAwareReplacerThe actual replacer function which could utilise additional information.
options?ObjectOptions to control whether the pathArray and ancestors parameters would have values populated. By default all information available would be populated. There is no need to specify options unless you are extremely concerned about performance, for example if you need to frequently stringify 500MB objects.
options.ancestors?boolean-
options.pathArray?boolean-
Returns

JsonStringifyReplacer

The replacer function that can be passed to JSON.stringify(...).


pathBasedReplacer

pathBasedReplacer(rules): JsonStringifyReplacer

Create a replacer function for JSON.stringify(...) from an array of path based rules. This function is useful for creating masking replacers which can apply masking based on the path of the property.

example


import { mask, maskAll, maskEmail, maskFullName, pathBasedReplacer } from '@handy-common-utils/misc-utils';
console.log(JSON.stringify(obj, pathBasedReplacer([
 [/.*\.x-api-key$/, maskAll],
 [/.*customer\.name$/, maskFullName],
 [/.*customer\..*[eE]mail$/, maskEmail],
 [/.*\.zip$/, (value: string) => value.slice(0, 3) + 'XX'],
 [/.*\.cc$/, () => undefined],
 [/.*\.ssn$/, mask],
])));

Parameters
NameTypeDescription
rules[RegExp, (input: any) => any][]Array of rules: if the regular expression tests true with the property path, the replacer function will be applied on the value
Returns

JsonStringifyReplacer

the replacer function built from those path based rules

Keywords

FAQs

Package last updated on 26 Mar 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc