Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
@hdsydsvenskan/utils
Advanced tools
Misc utility methods that's useful for our sites
npm install --save @hdsydsvenskan/utils
Follow Semantic Versioning and use np and a version like patch | minor | major | prepatch | preminor | premajor | prerelease | 1.2.3
np patch
resolveValue(value, ...valueArgs)
– value can be a function, a Promise or another value. If a function then it will be called with valueArgs
. Returns a PromiseresolveValueRaw(value, ...valueArgs)
– same as resolveValue()
but without the convenience of always returning the value wrapped in a PromiseresolveValueWithThis(value, thisContext, ...valueArgs)
– value can be a function, a Promise or another value. If a function then it will be called with valueArgs
and have this
as thisContext
. Returns a PromiseresolveNonObjectValue(value, ...valueArgs)
– same as resolveValueRaw()
, but with improved and stricter JSDoc typesresolveNonObjectValueRaw(value, ...valueArgs)
– same as resolveValueWithThis()
, but with improved and stricter JSDoc typesresolveNonObjectValueWithThis(value, thisContext, ...valueArgs)
– same as resolveValue()
, but with improved and stricter JSDoc typesapplyToDefaults(defaults, data)
– applies data
to defaults
. Mimicks the applyToDefaults
from Hoek.escapedJSONStringify(obj)
– returns an escaped stringified JSON object that can safely be printed in HTML.sleep(ms: number, [signal: AbortSignal])
– returns a Promise
that resolves after ms
milliseconds. If the signal
parameter is provided, the promise will resolve the instant the signal is aborted.arrayIntersect(firstArray, secondArray)
– returns true
or false
dependening whether the two arrays intersect or not.arrayZip(firstArray, secondArray)
– zips two arrays of the same length into onebisectLeft(sortedArray, value)
– find the left-most index of a sorted array where a value can be inserted while maintaining sorted orderbisectRight(sortedArray, value)
– Similar to bisectLeft
, but finds the right-most index instead.ensureArray(maybeArray)
– always returns an array, either the array input, the input wrapped as an array, or if the input is undefined
, then an empty arrayinsort(sortedArray, value)
– creates a new sorted array with the value inserted at the correct indexdeepClone(obj)
– recursively clones obj
and all objects and arrays it contains. obj
should be either an object or an array.deepMerge(target, source)
– recursively merges properties from source
into target
. If target
is an object (and a property of target
is an object) then properties will be merged into that object. Else it will be replaced with any new value from source
.deepFreeze(obj)
– recursively freezes obj
and all objects and arrays it contains. obj
can be either an object or an array.losslessMerge(obj1, obj2)
– creates an object with all keys from obj1
and obj2
+ with all values from the two merged into arrays. If a value in either was an array, then the content of that array gets merged into the array rather than the array itself.objectFilter(obj, [callback(value, key, i)])
– like [].filter()
but returns an object. Defaults to filter out undefined
itemsobjectMap(obj, callback(value, key, i))
– DEPRECATED BY objectMapExtended()
– like [].map()
but returns an objectobjectMapExtended(obj, callback(value, key, i))
– like [].map()
but returns an objectomit(obj, keys)
– returns obj
with all keys mentioned in keys
omitted. keys
being an array of stringspick(obj, keys)
– like omit()
, but rather than enforcing a blacklist of keys, it enforces a whitelist – only including keys of the object that have been listed in keys
pickDerived(obj, targets)
– targets
should be an object with keys that refer to keys in obj
and values that are either true
(then the value in obj
will be picked), a function
that will be sent obj
and will return a derived value, an object
which value will be resolved using parseDerived(obj, theTargetValue)
or a value of another type, which will then be returned as is.recursiveObjectFilter(obj, [callback(value, key, i)])
– like objectFilter()
, but better, since this one is recursive 💪zipObject(keys, values)
– returns an object with keys from keys
and key valies from values
catchWrap(promise, message)
– wraps the error message of a possibly rejected promise with this message through VError
objectPromiseAll(obj, [mapMethod(value, key)])
– resolves all Promises in obj
and returns a Promise that resolves to an object with all keys of obj
and their respective resolved value. If mapMethod
is set, then it will be called with value
and key
of each item in obj
and is expected to return a value or Promise to resolve to for each.recursiveObjectPromiseAll(obj)
– like objectPromiseAll
, but recursivecommaSeparatedStringToArray(value)
– value should be a string with values separated by a comma and an array of non-falsy values will be returnedescapeHTML(value)
– currently a re-exported escape-goat.escapeHTML()
, also useable as template tagunescapeHTML(value)
– currently a re-exported escape-goat.unescapeHTML()
, also useable as template taginlineString(value)
– replaces all newlines, including their surrounding whitespace, with a simple single spacetrimNewlines(value)
– replaces all newlines, including their surrounding whitespace, with a simple single newlinewrapIn([prefix], value, [suffix])
– adds a prefix and/or suffix to a string if that string is non-empty, else just returns an empty-stringescapeHTML
– currently a re-exported escape-goat.escapeHTML()
, also useable as a simple standalone functionunescapeHTML
– currently a re-exported escape-goat.unescapeHTML()
, also useable as a simple standalone functioninlineTemplateTag
– same as simpleTemplateTag
, but replaces all newlines, including their surrounding whitespace, with a simple single space + also trims any space in the very beginning and end of the stringsimpleTemplateTag
– noop template literal tag, works as if no template tag has been added. Makes it easy to get syntax highlighting, by aliasing it as eg. html
or js
templateTagWithModifier({ [staticCallback], [valueCallback], [finalCallback] })
– makes it simple to create template tags like inlineTemplateTag
and trimNewlines
;trimNewlines
– same as inlineTemplateTag
, but replaces with a single newline insteadlimitedStore(maxSize)
– returns a limited store that saves items up to a limit of maxSize
and then removes the oldest item. The returned object has three methods: set(key, value)
, get(key)
and remove(key)
memoize(func(args), maxSize, [{ keyGenerator(args), hitrateCallback, maxAge, store }])
– memoizes the result of the func using a limited cache of max size maxSize
with optionally a max age of maxAge
, a custom cache key generated by keyGenerator
, a hitrateCallback
that's called with true
for every hit and false
for every miss and a custom store
with same API as limitedStore
. Returns a wrapped func
with an added resetValue(args)
method that can be used to reset the value of a specific cached invocation (useful when eg. a cached Promise
has been rejected and you want to shorten the wait time).lruMemoize(func(args), maxSize, [{ keyGenerator(args), maxAge, store }])
– like memoize()
but defaults to a LRU cacheextendedCache(maxSize, [{ hitrateCallback, maxAge, store }])
– like memoize()
, but without the memoization function. Returns an object with three methods: set(key, value, expires)
, get(key)
and remove(key)
where expires
should be a timestamp in millisecondsdeprecate(name, [message])
– logs a console.trace()
the very first time it's called with a new name
, thus avoiding spamming the output with deprecation errors. Tracks state globally. Does not output logs in production.findCauseByError(err, FooError)
– like VError.findCauseByName(err, 'FooError')
but when it returns an error it actually is an error of the FooError
typeHdsUtilsFetchError(res, parsed)
– fetch related Error
class, can be used wherever a fetch related error happenslogSlowPromise(inputPromise, name, { logger, [logLevel], [warnEveryMs], [thresholdInMs]})
– logs (by default at warn
level) whenever the wrapped Promise
is slower than the set threshold (by default same as the interval) and repeats it on the set interval (by default 500 ms).trackDeprecation([scope], [log])
– creates a local deprecate()
that only tracks name
:s within itself and not globally. log
defaults to console.trace()
formatFieldsAndFragments({ fields, fragments }, spacing = ' ')
– used in GraphQL fragment extensions to format fields
and fragments
(both being arrays of strings and optional) for direct inclusion into a GraphQL query string. The spacing
can be overridden to better suit the insert position in the GraphQL query.getFieldsAndDependencies({ dependencies, fields, fragments })
– used in extendable GraphQL queries to format and merge the input data (all being arrays of strings and optional) into { dependencies, fields }
where dependencies
are what is to be added to a GraphQL query's dependencies and fields
are what to be inserted into the GraphQL query string.seededRandom(seed)
– returns a function that generates a random number. The returned function requires an integer as its only argument, the random number returned will be an integer between 0
and the sent in integer (not including the sent in integer).createMemoizedSeededListSorter
– makes it possible to sort a list consistently across many places both within and across instances, based on the sent in seed. Check the code in this project as well as the uses in other projects to understand how it works. It's a bit complicatedisEmptyishString(value, [{ treatNonStringsAsNonEmpty = false }])
– checks if the value is a string and if it is "emptyish" – returns true
eg. if its falsy, equal to 'null'
or 'undefined'
or if it just contains whitespace. Else it returns false
isFalsyishString(value)
– like isEmptyishString()
but also checks if the value is equal to 'false'
or '0'
isValidUUID(stringValue)
– checks whether the string value is setup according to a very basic regexp structureprocessFetchResponse(fetchPromise)
– returns parsed JSON on a 2xx success code, else returns an informative errorreadFilesInDir(path)
– returns a promise that resolves to an object with file names as keys and content as valuesrenderTpl(template, vars, [{ [customFilters] }])
– replaces named placeholders, {{name}}
, with variable values and applying optional filters, {{name | filter-name}}
. Supported filters are: escape
, inline
, json
. Inspired by Liquid.FAQs
Misc utility methods that's useful for our sites
We found that @hdsydsvenskan/utils demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 11 open source maintainers collaborating on the project.
Did you know?
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.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.