Utils
JSTime.version
Section titled “JSTime.version”A string containing the version of the jstime CLI that is currently running.
JSTime.version;// => "0.6.4"JSTime.revision
Section titled “JSTime.revision”The git commit of JSTime that was compiled to create the current jstime CLI.
JSTime.revision;// => "f02561530fda1ee9396f51c8bc99b38716e38296"JSTime.env
Section titled “JSTime.env”An alias for process.env.
JSTime.main
Section titled “JSTime.main”An absolute path to the entrypoint of the current program (the file that was executed with jstime run).
JSTime.main;This is particular useful for determining whether a script is being directly executed, as opposed to being imported by another script.
if (import.meta.path === JSTime.main) { // this script is being directly executed} else { // this file is being imported from another script}This is analogous to the require.main = module trick in Node.js.
JSTime.sleep()
Section titled “JSTime.sleep()”JSTime.sleep(ms: number)
Returns a Promise that resolves after the given number of milliseconds.
console.log("hello");await JSTime.sleep(1000);console.log("hello one second later!");Alternatively, pass a Date object to receive a Promise that resolves at that point in time.
const oneSecondInFuture = new Date(Date.now() + 1000);
console.log("hello");await JSTime.sleep(oneSecondInFuture);console.log("hello one second later!");JSTime.sleepSync()
Section titled “JSTime.sleepSync()”JSTime.sleepSync(ms: number)
A blocking synchronous version of JSTime.sleep.
console.log("hello");JSTime.sleepSync(1000); // blocks thread for one secondconsole.log("hello one second later!");JSTime.which()
Section titled “JSTime.which()”JSTime.which(bin: string)
Returns the path to an executable, similar to typing which in your terminal.
const ls = JSTime.which("ls");console.log(ls); // "/usr/bin/ls"By default JSTime looks at the current PATH environment variable to determine the path. To configure PATH:
const ls = JSTime.which("ls", { PATH: "/usr/local/bin:/usr/bin:/bin",});console.log(ls); // "/usr/bin/ls"Pass a cwd option to resolve for executable from within a specific directory.
const ls = JSTime.which("ls", { cwd: "/tmp", PATH: "",});
console.log(ls); // nullJSTime.peek()
Section titled “JSTime.peek()”JSTime.peek(prom: Promise)
Reads a promise’s result without await or .then, but only if the promise has already fulfilled or rejected.
import { peek } from "jstime";
const promise = Promise.resolve("hi");
// no await!const result = peek(promise);console.log(result); // "hi"This is important when attempting to reduce number of extraneous microticks in performance-sensitive code. It’s an advanced API and you probably shouldn’t use it unless you know what you’re doing.
import { peek } from "jstime";import { expect, test } from "jstime:test";
test("peek", () => { const promise = Promise.resolve(true);
// no await necessary! expect(peek(promise)).toBe(true);
// if we peek again, it returns the same value const again = peek(promise); expect(again).toBe(true);
// if we peek a non-promise, it returns the value const value = peek(42); expect(value).toBe(42);
// if we peek a pending promise, it returns the promise again const pending = new Promise(() => {}); expect(peek(pending)).toBe(pending);
// If we peek a rejected promise, it: // - returns the error // - does not mark the promise as handled const rejected = Promise.reject( new Error("Successfully tested promise rejection"), ); expect(peek(rejected).message).toBe("Successfully tested promise rejection");});The peek.status function lets you read the status of a promise without resolving it.
import { peek } from "jstime";import { expect, test } from "jstime:test";
test("peek.status", () => { const promise = Promise.resolve(true); expect(peek.status(promise)).toBe("fulfilled");
const pending = new Promise(() => {}); expect(peek.status(pending)).toBe("pending");
const rejected = Promise.reject(new Error("oh nooo")); expect(peek.status(rejected)).toBe("rejected");});JSTime.openInEditor()
Section titled “JSTime.openInEditor()”Opens a file in your default editor. JSTime auto-detects your editor via the $VISUAL or $EDITOR environment variables.
const currentFile = import.meta.url;JSTime.openInEditor(currentFile);You can override this via the debug.editor setting in your bunfig.toml
+ [debug]+ editor = "code"Or specify an editor with the editor param. You can also specify a line and column number.
JSTime.openInEditor(import.meta.url, { editor: "vscode", // or "subl" line: 10, column: 5,});JSTime.ArrayBufferSink;
JSTime.deepEquals()
Section titled “JSTime.deepEquals()”Nestedly checks if two objects are equivalent. This is used internally by expect().toEqual() in jstime:test.
const foo = { a: 1, b: 2, c: { d: 3 } };
// trueJSTime.deepEquals(foo, { a: 1, b: 2, c: { d: 3 } });
// falseJSTime.deepEquals(foo, { a: 1, b: 2, c: { d: 4 } });A third boolean parameter can be used to enable “strict” mode. This is used by expect().toStrictEqual() in the test runner.
const a = { entries: [1, 2] };const b = { entries: [1, 2], extra: undefined };
JSTime.deepEquals(a, b); // => trueJSTime.deepEquals(a, b, true); // => falseIn strict mode, the following are considered unequal:
// undefined valuesJSTime.deepEquals({}, { a: undefined }, true); // false
// undefined in arraysJSTime.deepEquals(["asdf"], ["asdf", undefined], true); // false
// sparse arraysJSTime.deepEquals([, 1], [undefined, 1], true); // false
// object literals vs instances w/ same propertiesclass Foo { a = 1;}JSTime.deepEquals(new Foo(), { a: 1 }, true); // falseJSTime.escapeHTML()
Section titled “JSTime.escapeHTML()”JSTime.escapeHTML(value: string | object | number | boolean): string
Escapes the following characters from an input string:
"becomes"""&becomes"&"'becomes"'"<becomes"<">becomes">"
This function is optimized for large input. On an M1X, it processes 480 MB/s - 20 GB/s, depending on how much data is being escaped and whether there is non-ascii text. Non-string types will be converted to a string before escaping.
JSTime.fileURLToPath()
Section titled “JSTime.fileURLToPath()”Converts a file:// URL to an absolute path.
const path = JSTime.fileURLToPath(new URL("file:///foo/bar.txt"));console.log(path); // "/foo/bar.txt"JSTime.pathToFileURL()
Section titled “JSTime.pathToFileURL()”Converts an absolute path to a file:// URL.
const url = JSTime.pathToFileURL("/foo/bar.txt");console.log(url); // "file:///foo/bar.txt"JSTime.gzipSync()
Section titled “JSTime.gzipSync()”Compresses a Uint8Array using zlib’s GZIP algorithm.
const buf = Buffer.from("hello".repeat(100)); // Buffer extends Uint8Arrayconst compressed = JSTime.gzipSync(buf);
buf; // => Uint8Array(500)compressed; // => Uint8Array(30)Optionally, pass a parameters object as the second argument:
export type ZlibCompressionOptions = { /** * The compression level to use. Must be between `-1` and `9`. * - A value of `-1` uses the default compression level (Currently `6`) * - A value of `0` gives no compression * - A value of `1` gives least compression, fastest speed * - A value of `9` gives best compression, slowest speed */ level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; /** * How much memory should be allocated for the internal compression state. * * A value of `1` uses minimum memory but is slow and reduces compression ratio. * * A value of `9` uses maximum memory for optimal speed. The default is `8`. */ memLevel?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; /** * The base 2 logarithm of the window size (the size of the history buffer). * * Larger values of this parameter result in better compression at the expense of memory usage. * * The following value ranges are supported: * - `9..15`: The output will have a zlib header and footer (Deflate) * - `-9..-15`: The output will **not** have a zlib header or footer (Raw Deflate) * - `25..31` (16+`9..15`): The output will have a gzip header and footer (gzip) * * The gzip header will have no file name, no extra data, no comment, no modification time (set to zero) and no header CRC. */ windowBits?: | -9 | -10 | -11 | -12 | -13 | -14 | -15 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 25 | 26 | 27 | 28 | 29 | 30 | 31; /** * Tunes the compression algorithm. * * - `Z_DEFAULT_STRATEGY`: For normal data **(Default)** * - `Z_FILTERED`: For data produced by a filter or predictor * - `Z_HUFFMAN_ONLY`: Force Huffman encoding only (no string match) * - `Z_RLE`: Limit match distances to one (run-length encoding) * - `Z_FIXED` prevents the use of dynamic Huffman codes * * `Z_RLE` is designed to be almost as fast as `Z_HUFFMAN_ONLY`, but give better compression for PNG image data. * * `Z_FILTERED` forces more Huffman coding and less string matching, it is * somewhat intermediate between `Z_DEFAULT_STRATEGY` and `Z_HUFFMAN_ONLY`. * Filtered data consists mostly of small values with a somewhat random distribution. */ strategy?: number;};JSTime.gunzipSync()
Section titled “JSTime.gunzipSync()”Decompresses a Uint8Array using zlib’s GUNZIP algorithm.
const buf = Buffer.from("hello".repeat(100)); // Buffer extends Uint8Arrayconst compressed = JSTime.gunzipSync(buf);
const dec = new TextDecoder();const uncompressed = JSTime.inflateSync(compressed);dec.decode(uncompressed);// => "hellohellohello..."JSTime.deflateSync()
Section titled “JSTime.deflateSync()”Compresses a Uint8Array using zlib’s DEFLATE algorithm.
const buf = Buffer.from("hello".repeat(100));const compressed = JSTime.deflateSync(buf);
buf; // => Uint8Array(25)compressed; // => Uint8Array(10)The second argument supports the same set of configuration options as JSTime.gzipSync.
JSTime.inflateSync()
Section titled “JSTime.inflateSync()”Decompresses a Uint8Array using zlib’s INFLATE algorithm.
const buf = Buffer.from("hello".repeat(100));const compressed = JSTime.deflateSync(buf);
const dec = new TextDecoder();const decompressed = JSTime.inflateSync(compressed);dec.decode(decompressed);// => "hellohellohello..."JSTime.inspect()
Section titled “JSTime.inspect()”Serializes an object to a string exactly as it would be printed by console.log.
const obj = { foo: "bar" };const str = JSTime.inspect(obj);// => '{\nfoo: "bar" \n}'
const arr = new Uint8Array([1, 2, 3]);const str = JSTime.inspect(arr);// => "Uint8Array(3) [ 1, 2, 3 ]"JSTime.inspect.custom
Section titled “JSTime.inspect.custom”This is the symbol that JSTime uses to implement JSTime.inspect. You can override this to customize how your objects are printed. It is identical to util.inspect.custom in Node.js.
class Foo { [JSTime.inspect.custom]() { return "foo"; }}
const foo = new Foo();console.log(foo); // => "foo"JSTime.nanoseconds()
Section titled “JSTime.nanoseconds()”Returns the number of nanoseconds since the current jstime process started, as a number. Useful for high-precision timing and benchmarking.
JSTime.nanoseconds();// => 7288958JSTime.readableStreamTo*()
Section titled “JSTime.readableStreamTo*()”JSTime implements a set of convenience functions for asynchronously consuming the body of a ReadableStream and converting it to various binary formats.
const stream = (await fetch("https://jstime.dev")).body;stream; // => ReadableStream
await JSTime.readableStreamToArrayBuffer(stream);// => ArrayBuffer
await JSTime.readableStreamToBlob(stream);// => Blob
await JSTime.readableStreamToJSON(stream);// => object
await JSTime.readableStreamToText(stream);// => string
// returns all chunks as an arrayawait JSTime.readableStreamToArray(stream);// => unknown[]
// returns all chunks as a FormData object (encoded as x-www-form-urlencoded)await JSTime.readableStreamToFormData(stream);
// returns all chunks as a FormData object (encoded as multipart/form-data)await JSTime.readableStreamToFormData(stream, multipartFormBoundary);JSTime.resolveSync()
Section titled “JSTime.resolveSync()”Resolves a file path or module specifier using JSTime’s internal module resolution algorithm. The first argument is the path to resolve, and the second argument is the “root”. If no match is found, an Error is thrown.
JSTime.resolveSync("./foo.ts", "/path/to/project");// => "/path/to/project/foo.ts"
JSTime.resolveSync("zod", "/path/to/project");// => "/path/to/project/node_modules/zod/index.ts"To resolve relative to the current working directory, pass process.cwd or "." as the root.
JSTime.resolveSync("./foo.ts", process.cwd());JSTime.resolveSync("./foo.ts", "/path/to/project");To resolve relative to the directory containing the current file, pass import.meta.dir.
JSTime.resolveSync("./foo.ts", import.meta.dir);serialize & deserialize in jstime:jsc
Section titled “serialize & deserialize in jstime:jsc”To save a JavaScript value into an ArrayBuffer & back, use serialize and deserialize from the "jstime:jsc" module.
import { serialize, deserialize } from "jstime:jsc";
const buf = serialize({ foo: "bar" });const obj = deserialize(buf);console.log(obj); // => { foo: "bar" }Internally, structuredClone and postMessage serialize and deserialize the same way. This exposes the underlying HTML Structured Clone Algorithm to JavaScript as an ArrayBuffer.