@applicvision/js-toolbox

2.6.1 • Public • Published

Zero-dependency collection of tools aiming to speed up modern JavaScript development.


Version image

install size

> npm install @applicvision/js-toolbox

Toolbox contents



Tests

Write tests with EcmaScript modules syntax, and run them both in browser and in Node, without any build step. Compose your tests in suites using describe, and declare test units with test or it:

// test.js
import {describe, it} from '@applicvision/js-toolbox/test'
import assert from 'node:assert/strict'

describe('My suite', () => {
  it('test', () => {
    assert.equal(1 + 1, 2)
  })
})

A bin called testa (Swedish for 'test' in imperative form) is exported which runs the test. So either put test: testa in your package.json script section, and call:

npm test

Or even shorter, just call with npx:

npx testa

In your package.json you can configure which files will be picked up by the test runner.

"config": {
  "testa": {
    "endsWith": ".test.js"
  }
}

By default, files ending with .test.js will be searched for from the project directory, but you can specify files and folders as argument to limit the search: testa unit integration extra.test.js.

Passing --help will print the usage information:

Options:
  -f, --filter     Specify a regex to only run matching tests and describes.
  -l, --logger     Specify a logger for the test. Available: animated, simple. Default: animated
  -m, --mode       Specify mode, node or browser. Default node.
  -w, --watch      In browser mode, reload on file changes in specified directory.
  -p, --port       In browser mode, select the port to run the server on. Default 3000.
  --timeout        Set general time limit for tests. Default 4s.
  --bail           Exit immediately on first test failure.
  --only           Run only tests marked with only.
  --notify         Show MacOS notification (osascript)
  -h, --help       Show this message and exit.

Browser mode

Going back to the start of the test module example

import { describe, test } from '@applicvision/js-toolbox/test'
import assert from 'node:assert/strict'

one might wonder how this code will run in the browser, without any compiling, transpiling, translation, build steps or anything.

The answer to that is two fairly new features for EcmaScript modules. The first is in the browser, and is called importmaps, which is available in recent versions of the major web browsers. See more at https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap.

The other is on the Node side, and is called import.meta.resolve. More info here: https://nodejs.org/dist/latest-v20.x/docs/api/esm.html#importmetaresolvespecifier.

So the first line in the example above is resolved to the correct file in node_modules, when the browser requests the module.

And the second line, import node:assert/strict, is intercepted and resolves a browser compatible implementation of node:assert/strict.

A separate bin called browser-test is exposed. It simply calls the testrunner with test mode set to browser.

The server for browser testing is run with http by default, but can also be run with https. To set this up, please create a key.pem (private key) and cert.pem (certificate), in any directory, and set the directory location to an environment variable called JS_TOOLBOX_CERT.

Once the server is started, default port is 3000, simply visit the page in the browser to run the tests.

Query parameters can be used to configure the tests. Available query parameters are:

  • only – run only tests marked with only
  • filter=<regex> – Run tests matching filter.
  • expand – Keep the test suites expanded when finished

Two examples:

'https://localhost:3000/?only'
#run only tests marked with .only

'https://localhost:3000/?filter=sum|random&filter=ayay'
#run only tests matching /sum|random/ and /ayay/

Auto reload

Auto reload is a tool to make the browser reload when files are changed. Start it with the exported bin, autoreload. In package json, add a script row:

autoreload: autoreload src

And then call

npm run autoreload

Or with npx:

npx autoreload src

This starts the file watcher and the server. The default port is 3333, but this can be configured with option --port. The server can also be run with https. To set up this, please create a key.pem (private key) and cert.pem (certificate), in any directory, and set the directory location to an environment variable called JS_TOOLBOX_CERT, or pass the directory location with the option --certificate.

Example:

npx autoreload --certificate ~/certificates/localhost

Then in your web application, during development, import the client script, and call start:

<script type="module">
    import { start } from 'https://localhost:3333/autoreload.js'
    start()
</script>

A little indicator will appear in the bottom right corner. If the indicator is green, it means autoreload is active, and file changes will trigger page reload. If it turns red, it means it lost connection to the server. It will automatically try to reconnect if it loses connection, and if connection is reestablished, the indicator color will return to green.

The file watcher can also be used as a standalone bin:

npx filewatcher .

Then it will emit to standard out when files change, and another process could be piped to it to handle file changes. The auto reload functionality is built that way.


Ayay

A subclass of the native Array. The aim is to extend Array with immutable methods. Create instances of Ayay using the constructor, or any of the static factory methods (which are just the same as those of Array):

import Ayay from '@applicvision/js-toolbox/Ayay'

const anArray = new Ayay()
// or
const anArray = Ayay.of(1, 2, 3)
// or
const anotherArray = Ayay.from([1, 2, 3, 4])

There are also two other static methods for constructing instances:

fromPrettyJoined, seedWith

Available prototype methods:

arrayByDroppingLastItem, arrayByInsertingItem, arrayByMoving, arrayByRemovingItemAtIndex, arrayByReplacingItemAtIndex, arrayBySwappingItems, arraySortedBy, asyncFilter, average, chunksOf, compactMap, findLast, findLastIndex, get first, groupBy, indices, isEmpty, isShallowIdenticalWith, iterateWhile, get last, get lastIndex, mapWhile, omitInObject, permutations, pickInObject, get pipe, prettyJoin, randomIndex, randomItem, reduceWhile, reversedArray, sampleOfSize, shuffledArray, sumItems, sumItemsWhile, toVanilla, transpose, uniqueItems, useAsKeyPathIn, get vanilla

Methods have been named in order to hopefully make them self explanatory. But additional documentation and examples are available in the TypeScript definitions, and will show in your editor.

One example:

const numberArray = Ayay.of(1, 2, 3, 4, 5, 6)

numberArray
  .arrayByDroppingLastItem()
  .average() // 3

// original array not modified
numberArray // [1, 2, 3, 4, 5, 6]

IzzaDate

IzzaDate is a small subclass of the native Date class. It enables easier manipulation, and some immutable operations on Date objects, as well as a few methods for date comparison.

Available methods:

add, components, copy, dateByAdding, dateBySetting, dateBySubtracting, daysSince, daysUntil, get, isEarlierInTheDay, isLaterInTheDay, isSameTimeOfDay, set, subtract

Documentation is available in TypeScript definition.

One example:

import IzzaDate, { DAY } from '@applicivions/js-toolbox/izza-date'
const now = new IzzaDate()
const tomorrow = now.dateByAdding(1, DAY)
now.daysUntil(tomorrow) // 1

Terminal Style

Simple utility to get colored output in the terminal.

import style from '@applicvision/js-toolbox/style'

console.log(
  style.cyan('This text is Cyan'),
  style.bold.red('This text is red and bold')
)

Available styles are those defined in util.inspect.colors, please see https://nodejs.org/api/util.html#foreground-colors for reference.

The default export is a function, with the following properties. Each property returns the style function with that text modifier activated.

blue, bold, cyan, dim, gray, green, italic, red, underline

The modifiers are chainable to combine styles:

style.green.bold.italic.underline('Hello')

And can be nested

style.blue(`blue ${style.bold('bold and blue')} blue`)

To pass custom style string, use .custom:

console.log(style.custom('bgRed', 'bold')('Hello Red background'))

Argument Parser

Argument parser is a simple utility to configure a command line tool. Specify which options and flags a program accepts. The parser will parse the arguments sent (by default process.argv.slice(2)).

Given this

// program.js
import {parseArguments} from '@applicvision/js-toolbox/args'
const parsed = parseArguments
  .option('message', { description: 'Specify a message' })
  .flag('flag', { description: 'A boolean option'})
  .option('option', { description: 'Another good option' })
  .help('Welcome to the program')
  .parse()

When invoked like this

node program.js --option=value1 --option value2 --flag -mhello -- arg1 arg2

The argument parser will return this:

{
  options: { option: [ 'value1', 'value2' ], flag: true, message: 'hello' },
  args: [ 'arg1', 'arg2' ]
}

If --help or -h is passed, the parser will return an object with help as the only property. This help can be logged to display a generated message to the user:

Welcome to the program

Options:
  -m, --message     Specify a message
  -f, --flag        A boolean option
  -o, --option      Another good option
  -h, --help        Show this message and exit.

if an unknown option is passed, or if a value is not correctly passed to an option, the parser will throw an error, with a message that can be logged to the user:

node program.js --missing-option=value1
Error Unknown option 'missing-option'

Available options:
  -m, --message     Specify a message
  -f, --flag        A boolean option
  -o, --option      Another good option
  -h, --help        Show this message and exit.


Passionately developed by ApplicVision


ApplicVision logo

Package Sidebar

Install

npm i @applicvision/js-toolbox

Weekly Downloads

3

Version

2.6.1

License

MIT

Unpacked Size

106 kB

Total Files

35

Last publish

Collaborators

  • mansh