### Install Dependencies
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Installs all necessary project dependencies using npm.
```bash
npm install
```
--------------------------------
### Install and Generate a ULID
Source: https://github.com/ulid/javascript/blob/master/_autodocs/START_HERE.md
Demonstrates how to install the ULID library using npm and generate a standard ULID string.
```APIDOC
## Install and Generate a ULID
### Description
Installs the ULID library via npm and shows a basic example of generating a ULID.
### Installation
```bash
npm install ulid
```
### Usage
```typescript
import { ulid } from "ulid";
const id = ulid();
console.log(id); // Example Output: "01HNZXD07M5CEN5XA66EMZSRZW"
```
```
--------------------------------
### Generate ULID via CLI (Global Install)
Source: https://github.com/ulid/javascript/blob/master/README.md
Install the ULID CLI globally and run it to generate a ULID from the command line.
```shell
npm install -g ulid
ulid
```
--------------------------------
### Install ULID using NPM
Source: https://github.com/ulid/javascript/blob/master/README.md
Install the ULID library as a project dependency using npm.
```shell
npm install ulid --save
```
--------------------------------
### Browser Global Import and Usage Example
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Include the ULID library via a script tag in HTML and access the ulid function from the global `window.ulidx` object.
```html
```
--------------------------------
### Generate ULID via CLI (npx)
Source: https://github.com/ulid/javascript/blob/master/README.md
Use npx to run the ULID CLI without a global installation.
```shell
npx ulid
```
--------------------------------
### TypeScript Import and Usage Example
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Import various types and functions from the ULID library in TypeScript, including creating a ULID and a monotonic factory.
```typescript
import {
ulid,
monotonicFactory,
ULID,
ULIDFactory,
ULIDError,
ULIDErrorCode
} from "ulid";
const id: ULID = ulid();
const factory: ULIDFactory = monotonicFactory();
```
--------------------------------
### Invoke CLI via npm scripts
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/cli.md
Shows how to execute the ULID CLI when the library is installed as a local dev dependency, either directly with `npm exec` or by defining a script in `package.json`.
```bash
npm exec ulid -- --count 10
```
```json
{
"scripts": {
"generate-ids": "ulid --count 100"
}
}
```
```bash
npm run generate-ids
```
--------------------------------
### Crockford Encode and Decode Example
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/crockford.md
Shows how to encode a Uint8Array to a Crockford-encoded string and then decode it back to the original Uint8Array. Both functions are case-insensitive.
```typescript
import { crockfordEncode, crockfordDecode } from "ulid";
const original = new Uint8Array([1, 174, 89, 214, 68, 65, 83, 86, 52, 82, 255, 246, 169, 71, 95, 170]);
const encoded = crockfordEncode(original);
const decoded = crockfordDecode(encoded);
console.log(original); // Uint8Array(16) [1, 174, 89, 214, ...]
console.log(encoded); // "01ARYZ6S41TSV4RRFFQ69G5FAV"
console.log(decoded); // Uint8Array(16) [1, 174, 89, 214, ...] (identical to original)
```
--------------------------------
### ULID JavaScript Type Usage Example
Source: https://github.com/ulid/javascript/blob/master/_autodocs/types.md
Illustrates generating ULIDs, creating monotonic factories, converting between ULID and UUID formats, defining custom PRNGs, and handling ULID-specific errors with type safety.
```typescript
import {
PRNG,
ULID,
ULIDFactory,
UUID,
ulid,
monotonicFactory,
ulidToUUID,
uuidToULID,
ULIDError,
ULIDErrorCode
} from "ulid";
// Generate a ULID (type is inferred)
const myId: ULID = ulid();
// Create a monotonic factory (explicit type annotation)
const factory: ULIDFactory = monotonicFactory();
// Use the factory
const id = factory();
// Convert to UUID
const uuid: UUID = ulidToUUID(myId);
// Convert back
const recovered: ULID = uuidToULID(uuid);
// Define a custom PRNG
const myPRNG: PRNG = () => Math.random();
// Handle errors with type safety
try {
ulid(999999999999999999); // Invalid timestamp
} catch (error) {
if (error instanceof ULIDError && error.code === ULIDErrorCode.EncodeTimeSizeExceeded) {
console.error("Timestamp too large");
}
}
```
--------------------------------
### ULID Performance Benchmarks
Source: https://github.com/ulid/javascript/blob/master/README.md
Demonstrates the performance of ULID generation with and without timestamps. Run 'npm run bench' to test.
```bash
Simple ulid x 56,782 ops/sec ±2.50% (86 runs sampled)
ulid with timestamp x 58,574 ops/sec ±1.80% (87 runs sampled)
Done!
```
--------------------------------
### Run Benchmarks
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Runs performance benchmarks for the project.
```bash
npm run bench
```
--------------------------------
### Run Tests
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Executes the project's test suite to ensure code quality.
```bash
npm test
```
--------------------------------
### Format Code
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Formats the project's code according to predefined style guidelines.
```bash
npm run format
```
--------------------------------
### Main Project File Structure
Source: https://github.com/ulid/javascript/blob/master/_autodocs/MANIFEST.md
Overview of the main directories and files within the ULID JavaScript project documentation.
```text
output/
├── INDEX.md ← Navigation guide and cross-reference
├── README.md ← Overview, quick start, features
├── configuration.md ← Build, environment, imports
├── constants.md ← All constants and limits
├── errors.md ← Error handling documentation
├── types.md ← Type definitions
└── api-reference/
├── ulid.md ← Core ULID functions (6 functions)
├── uuid.md ← UUID conversion (2 functions)
├── crockford.md ← Base32 utilities (4 functions)
└── cli.md ← CLI tool
```
--------------------------------
### Direct ULID Usage and Factory Creation
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Demonstrates direct usage of the `ulid` function and creating a monotonic factory. No runtime configuration is needed.
```typescript
import { ulid, monotonicFactory } from "ulid";
// Direct use — no configuration needed
const id = ulid();
// Or create a factory
const factory = monotonicFactory();
const id2 = factory();
```
--------------------------------
### Run Main Build Script
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Executes the primary build script which generates all distribution files sequentially. This includes cleaning the output directory, building CommonJS and ES Module formats for Node.js and browsers, and generating CLI executables and TypeScript declarations.
```bash
npm run build
```
--------------------------------
### Package.json Exports Configuration
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Defines entry points for different module systems and environments, including TypeScript declaration files.
```json
{
"exports": {
".": {
"types": {
"require": "./dist/index.d.cts",
"default": "./dist/index.d.ts"
},
"node": {
"require": "./dist/node/index.cjs",
"default": "./dist/node/index.js"
},
"default": {
"require": "./dist/browser/index.cjs",
"default": "./dist/browser/index.js"
}
}
}
}
```
--------------------------------
### Generate Monotonic ULIDs
Source: https://github.com/ulid/javascript/blob/master/_autodocs/START_HERE.md
Shows how to use the `monotonicFactory` to generate ULIDs that are guaranteed to be in increasing order.
```APIDOC
## Generate Monotonic ULIDs
### Description
Utilizes the `monotonicFactory` to create ULIDs sequentially, ensuring they are always increasing.
### Usage
```typescript
import { monotonicFactory } from "ulid";
const factory = monotonicFactory();
console.log(factory()); // Example Output: "01HNZXD07M5CEN5XA66EMZSRZW"
console.log(factory()); // Example Output: "01HNZXD07M5CEN5XA66EMSZSRX"
```
```
--------------------------------
### Generate ULIDs from Terminal (CLI)
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Demonstrates generating ULIDs directly from the command line using npx. Supports generating single or multiple ULIDs.
```bash
# Single ULID
npx ulid
# 01HNZXD07M5CEN5XA66EMZSRZW
# Multiple ULIDs
npx ulid --count 5
# Generates 5 monotonically-ordered ULIDs
```
--------------------------------
### Build CLI Executable
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Generates the CLI executable file at `dist/cli.js` and makes it executable using `chmod +x`. This command uses ES Module format and is intended for CLI environments.
```bash
FMT=esm ENV=cli rollup -c && chmod +x ./dist/cli.js
```
--------------------------------
### Build Browser ES Module
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Generates ES Module output for browsers. It includes a global name `ulidx` and is saved to `dist/browser/index.js`.
```bash
FMT=esm ENV=browser rollup -c --name ulidx
```
--------------------------------
### Generate ULID with Custom PRNG (Testing Only)
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Shows how to use a custom pseudo-random number generator (PRNG) for ULID generation. This is insecure and intended only for testing purposes. Requires importing 'ulid'.
```typescript
import { ulid } from "ulid";
const testPRNG = () => Math.random();
const id = ulid(undefined, testPRNG);
// Uses Math.random for randomness (NOT recommended for production)
```
--------------------------------
### Check Types
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Verifies the type correctness of the package using @arethetypeswrong/cli.
```bash
npx --yes @arethetypeswrong/cli --pack .
```
--------------------------------
### Use Custom PRNG with ULID
Source: https://github.com/ulid/javascript/blob/master/_autodocs/types.md
Demonstrates how to define and use a custom, albeit not cryptographically secure, PRNG with the `ulid` function. Ensure to use secure PRNGs for production environments.
```typescript
import { ulid, PRNG } from "ulid";
// Define a custom PRNG (not recommended for security)
const insecurePRNG: PRNG = () => Math.random();
// Use with ulid
const id = ulid(undefined, insecurePRNG);
```
--------------------------------
### Control Output Format with FMT
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Use the `FMT` environment variable during the build process to specify the desired output module format (CommonJS or ES Module). This affects the generated entry points.
```bash
# Generate CommonJS output
FMT=cjs npm run build:node:cjs
```
```bash
# Generate ES Module output
FMT=esm npm run build:node:esm
```
--------------------------------
### Include ULID in Browser (Global Script)
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Include the ULID library via a script tag for direct use in the browser. The global object is `ulidx`.
```html
```
--------------------------------
### Build Browser CommonJS
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Generates CommonJS output suitable for browsers. It includes a global name `ulidx` and is saved to `dist/browser/index.cjs`.
```bash
FMT=cjs ENV=browser rollup -c --name ulidx
```
--------------------------------
### Build Node.js ES Module
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Generates ES Module output for Node.js environments. The output is placed in `dist/node/index.js`.
```bash
FMT=esm ENV=node rollup -c
```
--------------------------------
### ulid()
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/ulid.md
Generates a single ULID. It can optionally accept a seed timestamp in milliseconds and a custom pseudo-random number generator (PRNG). If no seed time is provided, it defaults to the current system time. If no PRNG is provided, it attempts to detect the best available one.
```APIDOC
## Function: ulid()
### Description
Generate a single ULID with optional seed timestamp and custom PRNG.
### Signature
```typescript
function ulid(seedTime?: number, prng?: PRNG): ULID
```
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Parameters Table
| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| seedTime | number | No | `Date.now()` |
| prng | PRNG | No | Auto-detected |
### Returns
`ULID` — A 26-character ULID string encoded in Crockford's base32.
### Throws
- `ULIDError` with code `PRNGDetectFailure` if no PRNG can be detected when `prng` is not provided.
- `ULIDError` with code `EncodeTimeNegative` if `seedTime` is negative.
- `ULIDError` with code `EncodeTimeSizeExceeded` if `seedTime` exceeds `TIME_MAX` (281474976710655).
- `ULIDError` with code `EncodeTimeValueMalformed` if `seedTime` is not an integer.
### Example
```typescript
import { ulid } from "ulid";
// Generate a ULID with current timestamp
const id = ulid();
console.log(id); // "01HNZXD07M5CEN5XA66EMZSRZW"
// Generate a ULID with a specific timestamp
const specificId = ulid(1469918176385);
console.log(specificId); // "01ARYZ6S41TSV4RRFFQ69G5FAV" (time component only; random varies)
// Generate a ULID with a custom PRNG
const customId = ulid(undefined, () => Math.random());
console.log(customId); // Uses Math.random for randomness (not recommended for security)
```
```
--------------------------------
### detectPRNG()
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/ulid.md
Detects and returns the best available cryptographically-secure pseudo-random number generator (PRNG) for the current environment, prioritizing secure sources like `crypto.getRandomValues()` or `crypto.randomBytes()`.
```APIDOC
## Function: detectPRNG()
### Description
Detects the best available cryptographically-secure PRNG in the current environment. It searches for `crypto.getRandomValues()` (browser, Deno) and `crypto.randomBytes()` (Node.js, electron), falling back to Node.js `crypto` module if necessary.
### Signature
```typescript
function detectPRNG(root?: any): PRNG
```
### Parameters
#### Path Parameters
- **root** (any) - Optional - The global object to search (e.g., `window`, `global`, `self`). If not provided, searches common global locations.
### Returns
`PRNG` — A function that generates random numbers in the range [0, 1).
### Throws
- `ULIDError` with code `PRNGDetectFailure` if no suitable PRNG is available in the environment.
### Example
```typescript
import { detectPRNG, ulid } from "ulid";
// Explicitly detect PRNG (normally done automatically)
const prng = detectPRNG();
// Use it for custom ULID generation
const id = ulid(undefined, prng);
console.log(id); // "01HNZXD07M5CEN5XA66EMZSRZW"
```
```
--------------------------------
### ULID Constants Usage
Source: https://github.com/ulid/javascript/blob/master/_autodocs/constants.md
Demonstrates how to access and use various constants defined for ULID generation and validation, such as length, encoding, time bounds, and regex patterns.
```typescript
import {
ENCODING,
ENCODING_LEN,
TIME_LEN,
RANDOM_LEN,
TIME_MAX,
MIN_ULID,
MAX_ULID,
ULID_REGEX,
UUID_REGEX,
B32_CHARACTERS
} from "ulid";
// ULID structure
console.log(`ULID length: ${TIME_LEN + RANDOM_LEN}`); // 26
// Base32 alphabet
console.log(`Base32 characters: ${ENCODING}`);
console.log(`Alphabet length: ${ENCODING_LEN}`); // 32 (5 bits per char)
// Time bounds
console.log(`Max timestamp: ${TIME_MAX}`);
console.log(`Max date: ${new Date(TIME_MAX)}`); // ~Year 8921
// ULID range
console.log(`Minimum ULID: ${MIN_ULID}`);
console.log(`Maximum ULID: ${MAX_ULID}`);
// Validation
console.log(ULID_REGEX.test("01ARYZ6S41TSV4RRFFQ69G5FAV"));
console.log(UUID_REGEX.test("550e8400-e29b-41d4-a716-446655440000"));
```
--------------------------------
### Generate Multiple ULIDs via CLI
Source: https://github.com/ulid/javascript/blob/master/README.md
Specify the number of ULIDs to generate using the `--count` flag with the CLI.
```shell
ulid --count 15
```
--------------------------------
### Generate a ULID
Source: https://github.com/ulid/javascript/blob/master/_autodocs/START_HERE.md
Generate a standard ULID string. This is the most common use case for the library.
```typescript
import { ulid } from "ulid";
const id = ulid();
console.log(id); // "01HNZXD07M5CEN5XA66EMZSRZW"
```
--------------------------------
### Generate a Single ULID
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/cli.md
Generates a single ULID. This is the default behavior when no options are specified.
```bash
ulid
```
```bash
npx ulid
```
```bash
$ ulid
01HNZXD07M5CEN5XA66EMZSRZW
```
--------------------------------
### Generate and Type ULID
Source: https://github.com/ulid/javascript/blob/master/_autodocs/types.md
Shows how to generate a ULID and explicitly type it using the `ULID` alias. This ensures type safety when assigning generated ULIDs to variables.
```typescript
import { ulid, ULID } from "ulid";
const myId: ULID = ulid();
console.log(myId); // "01HNZXD07M5CEN5XA66EMZSRZW"
```
--------------------------------
### Throw and Catch ULIDError
Source: https://github.com/ulid/javascript/blob/master/_autodocs/errors.md
Demonstrates how to throw a ULIDError with a specific error code and message, and how to catch and inspect it using an instanceof check.
```typescript
import { ULIDError, ULIDErrorCode } from "ulid";
try {
throw new ULIDError(ULIDErrorCode.ULIDInvalid, "Invalid ULID provided");
} catch (error) {
if (error instanceof ULIDError) {
console.log(error.name); // "ULIDError"
console.log(error.code); // "ULID_INVALID"
console.log(error.message); // "Invalid ULID provided (ULID_INVALID)"
}
}
```
--------------------------------
### Build Node.js CommonJS
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Generates CommonJS output specifically for Node.js environments. The output is placed in `dist/node/index.cjs`.
```bash
FMT=cjs ENV=node rollup -c
```
--------------------------------
### monotonicFactory()
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/ulid.md
Creates a ULID factory that generates monotonically increasing ULIDs. Each subsequent call within the same millisecond increments the random portion instead of generating new randomness.
```APIDOC
## Function: monotonicFactory()
### Description
Creates a ULID factory that generates monotonically increasing ULIDs. Each subsequent call within the same millisecond increments the random portion instead of generating new randomness.
### Signature
```typescript
function monotonicFactory(prng?: PRNG): ULIDFactory
```
### Parameters
#### Optional Parameters
- **prng** (PRNG) - No - Auto-detected - Custom PRNG function. If not provided, uses `detectPRNG()`.
### Returns
`ULIDFactory` — A function that accepts an optional `seedTime` and returns a monotonically-increasing ULID string.
### Throws
- `ULIDError` with code `PRNGDetectFailure` if no PRNG can be detected when `prng` is not provided.
### Factory Function Signature
```typescript
function factory(seedTime?: number): ULID
```
### Factory Function Behavior
The returned factory maintains internal state:
- Tracks the last generated ULID's timestamp and random portion
- If `seedTime <= lastTime`, increments the random portion and returns the new ULID
- If `seedTime > lastTime`, generates fresh randomness and updates the internal time
### Example
```typescript
import { monotonicFactory } from "ulid";
const factory = monotonicFactory();
// Multiple calls at the same seed time produce monotonic ordering
const id1 = factory(150000); // "000XAL6S41ACTAV9WEVGEMMVR8"
const id2 = factory(150000); // "000XAL6S41ACTAV9WEVGEMMVR9"
const id3 = factory(150000); // "000XAL6S41ACTAV9WEVGEMMVRA"
// Backward time movement still maintains monotonic order
const id4 = factory(100000); // "000XAL6S41ACTAV9WEVGEMMVRD" (incremented from id3)
// Forward time resets randomness
const id5 = factory(200000); // New random portion generated
```
```
--------------------------------
### Custom PRNG (Insecure - For Testing Only)
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Allows specifying a custom pseudo-random number generator for ULID generation. This is insecure and intended for testing purposes only.
```APIDOC
## ulid(timestamp, prng)
### Description
Allows specifying a custom pseudo-random number generator for ULID generation. This is insecure and intended for testing purposes only.
### Method Signature
```typescript
ulid(timestamp?: number, prng?: () => number): string
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **timestamp** (number) - Optional - The Unix timestamp in milliseconds to encode into the ULID.
- **prng** (function) - Optional - A function that returns a random number between 0 (inclusive) and 1 (exclusive). Defaults to `Math.random` if not provided.
### Request Example
```typescript
import { ulid } from "ulid";
const testPRNG = () => Math.random();
const id = ulid(undefined, testPRNG);
// Uses Math.random for randomness (NOT recommended for production)
```
### Response
#### Success Response
- **id** (string) - A ULID string generated with the specified timestamp and custom PRNG.
### Response Example
```json
{
"id": "01HNZXD07M5CEN5XA66EMZSRZW"
}
```
```
--------------------------------
### CLI: Generate ULIDs from Terminal
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Generates ULIDs directly from the command line interface.
```APIDOC
## CLI Usage
### Description
Generates ULIDs directly from the command line interface.
### Commands
- **`npx ulid`**: Generates a single ULID.
- **`npx ulid --count `**: Generates multiple ULIDs, which will be monotonically ordered.
### Examples
```bash
# Single ULID
npx ulid
# 01HNZXD07M5CEN5XA66EMZSRZW
# Multiple ULIDs
npx ulid --count 5
# Generates 5 monotonically-ordered ULIDs
```
```
--------------------------------
### Build TypeScript Declarations
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Generates TypeScript declaration files (`.d.ts`) for all output formats. It finds all generated `.d.ts` files and renames them to have a `.d.cts` extension, likely for CommonJS compatibility.
```bash
tsc -p tsconfig.dec.json --emitDeclarationOnly && find ./dist -name '*.d.ts' -exec sh -c 'cp {} $(dirname {})/$(basename -s .d.ts {}).d.cts' \;
```
--------------------------------
### Control Target Environment with ENV
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
The `ENV` environment variable selects the target environment (Node.js, browser, or CLI) for the build. This is used in conjunction with `FMT` and influences environment-specific PRNG selection.
```bash
# Generate Node.js ESM build
ENV=node FMT=esm rollup -c
```
```bash
# Generate browser CommonJS build
ENV=browser FMT=cjs rollup -c
```
```bash
# Generate CLI build
ENV=cli FMT=esm rollup -c
```
--------------------------------
### ULID Functions Reference
Source: https://github.com/ulid/javascript/blob/master/_autodocs/START_HERE.md
A reference table listing available ULID functions, their associated files, and their primary use cases.
```APIDOC
## ULID Functions Reference
### Description
Provides a list of all exported functions within the ULID library, detailing their purpose and location within the documentation.
| Function | File | Use For |
|----------|------|---------|
| `ulid()` | api-reference/ulid.md | Generate a ULID |
| `monotonicFactory()` | api-reference/ulid.md | Monotonic ULID generation |
| `encodeTime()` | api-reference/ulid.md | Encode timestamp to base32 |
| `decodeTime()` | api-reference/ulid.md | Extract timestamp from ULID |
| `isValid()` | api-reference/ulid.md | Validate ULID string |
| `detectPRNG()` | api-reference/ulid.md | Detect PRNG in environment |
| `ulidToUUID()` | api-reference/uuid.md | Convert ULID to UUID |
| `uuidToULID()` | api-reference/uuid.md | Convert UUID to ULID |
| `crockfordEncode()` | api-reference/crockford.md | Encode bytes to base32 |
| `crockfordDecode()` | api-reference/crockford.md | Decode base32 to bytes |
| `fixULIDBase32()` | api-reference/crockford.md | Fix encoding errors |
| `incrementBase32()` | api-reference/crockford.md | Increment base32 string |
**Full function index:** [INDEX.md](INDEX.md)
```
--------------------------------
### CLI Error Handling for Count
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/cli.md
Demonstrates how the CLI handles invalid or non-positive values for the --count option. These are treated as NaN and default to generating a single ULID.
```bash
$ ulid --count invalid
# Produces 1 ULID (count is treated as NaN and defaults to 1)
```
```bash
$ ulid --count=-5
# Produces 1 ULID (negative count is treated as NaN and defaults to 1)
```
--------------------------------
### Environment Variables for Rollup
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Detects the target environment and module format using process environment variables.
```javascript
const FMT = process.env.FMT; // "cjs" or "esm"
const ENV = process.env.ENV; // "node", "browser", or "cli"
```
--------------------------------
### Import ULID in Browser (Bundler)
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Use this import statement when using a bundler like Webpack or Rollup for browser environments.
```javascript
import { ulid } from "ulid";
```
--------------------------------
### Create Monotonic ULID Factory
Source: https://github.com/ulid/javascript/blob/master/README.md
Use `monotonicFactory` to create a ULID generator that produces monotonically increasing ULIDs, even for the same timestamp.
```typescript
import { monotonicFactory } from "ulid";
const ulid = monotonicFactory();
// Strict ordering for the same timestamp, by incrementing the least-significant random bit by 1
ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVR8"
ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVR9"
ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVRA"
ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVRB"
ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVRC"
// Even if a lower timestamp is passed (or generated), it will preserve sort order
ulid(100000); // "000XAL6S41ACTAV9WEVGEMMVRD"
```
--------------------------------
### Generate a ULID
Source: https://github.com/ulid/javascript/blob/master/README.md
Import the `ulid` function and call it to generate a new ULID string.
```typescript
import { ulid } from "ulid";
ulid(); // "01ARZ3NDEKTSV4RRFFQ69G5FAV"
```
--------------------------------
### Create a ULIDFactory
Source: https://github.com/ulid/javascript/blob/master/_autodocs/types.md
Use monotonicFactory to create a ULIDFactory. This factory can generate ULIDs using the current time or a provided timestamp. Generated ULIDs are guaranteed to be in strictly increasing order.
```typescript
import { monotonicFactory, ULIDFactory } from "ulid";
const factory: ULIDFactory = monotonicFactory();
// Generate multiple ULIDs
const id1 = factory(); // Uses current time
const id2 = factory(1469918176385); // Uses provided timestamp
const id3 = factory(); // Uses current time
// All are guaranteed to be in strictly increasing order
console.log(id1 < id2); // Comparison works due to lexicographic format
```
--------------------------------
### Exported Functions from ULID Module
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Lists all public exports from the main entry point of the ULID library. Supports Node.js CommonJS, ESM, browser, and CLI environments.
```typescript
export { decodeTime, encodeTime, isValid, monotonicFactory, ulid } from "./ulid.js";
export { ulidToUUID, uuidToULID } from "./uuid.js";
export { fixULIDBase32, incrementBase32 } from "./crockford.js";
export { ULIDError, ULIDErrorCode } from "./error.js";
export { MAX_ULID, MIN_ULID, TIME_LEN, TIME_MAX } from "./constants.js";
export * from "./types.js";
```
--------------------------------
### Import ULID in Node.js (ES Module)
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Use this import statement for Node.js environments that use ES Module syntax.
```javascript
import { ulid, monotonicFactory } from "ulid";
```
--------------------------------
### ULID Functions
Source: https://github.com/ulid/javascript/blob/master/_autodocs/INDEX.md
This section lists the available functions for working with ULIDs and Crockford Base32 encoding.
```APIDOC
## crockfordDecode()
### Description
Decodes a Crockford Base32 encoded string into a Uint8Array.
### Signature
`crockfordDecode(input: string) => Uint8Array`
```
```APIDOC
## crockfordEncode()
### Description
Encodes a Uint8Array into a Crockford Base32 encoded string.
### Signature
`crockfordEncode(input: Uint8Array) => string`
```
```APIDOC
## decodeTime()
### Description
Decodes the timestamp component from a ULID string.
### Signature
`decodeTime(id: ULID) => number`
```
```APIDOC
## detectPRNG()
### Description
Detects and returns a suitable Pseudo-Random Number Generator (PRNG).
### Signature
`detectPRNG(root?: any) => PRNG`
```
```APIDOC
## encodeTime()
### Description
Encodes a timestamp number into a ULID-compatible string segment.
### Signature
`encodeTime(now: number, len?: number) => string`
```
```APIDOC
## fixULIDBase32()
### Description
Corrects potential encoding issues in a ULID Base32 string.
### Signature
`fixULIDBase32(id: string) => string`
```
```APIDOC
## incrementBase32()
### Description
Increments a Crockford Base32 encoded string.
### Signature
`incrementBase32(str: string) => string`
```
```APIDOC
## isValid()
### Description
Checks if a given string is a valid ULID.
### Signature
`isValid(id: string) => boolean`
```
```APIDOC
## monotonicFactory()
### Description
Creates a ULID factory that generates monotonic ULIDs.
### Signature
`monotonicFactory(prng?: PRNG) => ULIDFactory`
```
```APIDOC
## ulid()
### Description
Generates a new ULID.
### Signature
`ulid(seedTime?: number, prng?: PRNG) => ULID`
```
```APIDOC
## ulidToUUID()
### Description
Converts a ULID string to a UUID string.
### Signature
`ulidToUUID(ulid: ULID) => UUID`
```
```APIDOC
## uuidToULID()
### Description
Converts a UUID string to a ULID string.
### Signature
`uuidToULID(uuid: string) => ULID`
```
--------------------------------
### Generate ULID with Seed Time
Source: https://github.com/ulid/javascript/blob/master/README.md
Provide a seed time (in milliseconds) to the `ulid` function to ensure consistent time components for generated ULIDs.
```typescript
ulid(1469918176385) // "01ARYZ6S41TSV4RRFFQ69G5FAV"
```
--------------------------------
### Convert ULID to UUID and Vice Versa
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Provides functions to convert between ULID strings and UUID strings. Requires importing 'ulidToUUID' and 'uuidToULID'.
```typescript
import { ulidToUUID, uuidToULID } from "ulid";
const ulid = "01ARYZ6S41TSV4RRFFQ69G5FAV";
const uuid = ulidToUUID(ulid);
// "015D8E2E-FB3E-8000-803D-CD8EF24AB4A8"
const recovered = uuidToULID(uuid);
// "01ARYZ6S41TSV4RRFFQ69G5FAV" (round-trip)
```
--------------------------------
### Import ULID in Node.js (CommonJS)
Source: https://github.com/ulid/javascript/blob/master/_autodocs/configuration.md
Use this import statement for Node.js environments that use CommonJS module syntax.
```javascript
const { ulid, monotonicFactory } = require("ulid");
```
--------------------------------
### Calculate Total ULID Length
Source: https://github.com/ulid/javascript/blob/master/_autodocs/constants.md
Demonstrates the calculation of the total ULID string length by summing the timestamp and random components.
```typescript
// Calculated as: TIME_LEN + RANDOM_LEN = 10 + 16 = 26
```
--------------------------------
### Handle ULID Generation Errors
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Demonstrates how to catch and log specific ULID errors, such as providing a timestamp that exceeds the maximum allowed value. Ensure you import ULIDError and ULIDErrorCode for proper error handling.
```typescript
import { ulid, ULIDError, ULIDErrorCode } from "ulid";
try {
ulid(999999999999999999); // Timestamp too large
} catch (error) {
if (error instanceof ULIDError) {
console.error(`Error [${error.code}]: ${error.message}`);
// Error [ENC_TIME_SIZE_EXCEED]: Cannot encode a time larger than 281474976710655: 999999999999999999
}
}
```
--------------------------------
### Round-Trip Conversion ULID <-> UUID
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/uuid.md
Demonstrates the symmetrical conversion between ULID and UUID formats. Converting a ULID to UUID and back to ULID results in the original ULID. Both functions handle case-insensitive input and produce uppercase output.
```typescript
import { ulidToUUID, uuidToULID } from "ulid";
const originalULID = "01ARYZ6S41TSV4RRFFQ69G5FAV";
// Convert ULID → UUID → ULID
const uuid = ulidToUUID(originalULID);
const recoveredULID = uuidToULID(uuid);
console.log(originalULID); // "01ARYZ6S41TSV4RRFFQ69G5FAV"
console.log(uuid); // "015D8E2E-FB3E-8000-803D-CD8EF24AB4A8"
console.log(recoveredULID); // "01ARYZ6S41TSV4RRFFQ69G5FAV" (identical to original)
```
--------------------------------
### Use Math.random as PRNG (Insecure)
Source: https://github.com/ulid/javascript/blob/master/README.md
Override the default cryptographically-secure PRNG with `Math.random` by passing it to `monotonicFactory`. This is not recommended for production use.
```typescript
const ulid = monotonicFactory(() => Math.random());
ulid(); // "01BXAVRG61YJ5YSBRM51702F6M"
```
--------------------------------
### Error Codes
Source: https://github.com/ulid/javascript/blob/master/_autodocs/INDEX.md
This section details the error codes that can be thrown by the library functions.
```APIDOC
## Error Code: Base32IncorrectEncoding
### String Value
`"B32_ENC_INVALID"`
### Thrown By
`incrementBase32()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: DecodeTimeInvalidCharacter
### String Value
`"DEC_TIME_CHAR"`
### Thrown By
`decodeTime()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: DecodeTimeValueMalformed
### String Value
`"DEC_TIME_MALFORMED"`
### Thrown By
`decodeTime()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: EncodeTimeNegative
### String Value
`"ENC_TIME_NEG"`
### Thrown By
`encodeTime()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: EncodeTimeSizeExceeded
### String Value
`"ENC_TIME_SIZE_EXCEED"`
### Thrown By
`encodeTime()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: EncodeTimeValueMalformed
### String Value
`"ENC_TIME_MALFORMED"`
### Thrown By
`encodeTime()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: PRNGDetectFailure
### String Value
`"PRNG_DETECT"`
### Thrown By
`detectPRNG()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: ULIDInvalid
### String Value
`"ULID_INVALID"`
### Thrown By
`ulidToUUID()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: Unexpected
### String Value
`"UNEXPECTED"`
### Thrown By
`uuidToULID()`
### Details
Refer to `errors.md` for more information.
```
```APIDOC
## Error Code: UUIDInvalid
### String Value
`"UUID_INVALID"`
### Thrown By
`uuidToULID()`
### Details
Refer to `errors.md` for more information.
```
--------------------------------
### Generate ULID with Current Timestamp
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/ulid.md
Generates a ULID using the current system time. This is the most common usage.
```typescript
import { ulid } from "ulid";
// Generate a ULID with current timestamp
const id = ulid();
console.log(id); // "01HNZXD07M5CEN5XA66EMZSRZW"
```
--------------------------------
### Generate a Single ULID
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Generates a standard ULID using the current timestamp. Ensure the 'ulid' function is imported.
```typescript
import { ulid } from "ulid";
const id = ulid();
// "01HNZXD07M5CEN5XA66EMZSRZW"
```
--------------------------------
### Monotonic ULID Factory
Source: https://github.com/ulid/javascript/blob/master/_autodocs/README.md
Creates a factory function that generates ULIDs guaranteed to be monotonically increasing, even if called within the same millisecond.
```APIDOC
## monotonicFactory()
### Description
Creates a factory function that generates ULIDs guaranteed to be monotonically increasing, even if called within the same millisecond.
### Method Signature
```typescript
monotonicFactory(): () => string
```
### Parameters
None
### Request Example
```typescript
import { monotonicFactory } from "ulid";
const factory = monotonicFactory();
// All subsequent calls are guaranteed monotonic
for (let i = 0; i < 5; i++) {
console.log(factory());
}
// Even if called in the same millisecond, order is maintained
```
### Response
#### Success Response
- **factory** (function) - A function that returns a monotonically increasing ULID string on each call.
### Response Example
```json
{
"factory": "[Function: factory]"
}
```
```
--------------------------------
### Generate Multiple ULIDs
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/cli.md
Generates a specified number of ULIDs using the --count option. ULIDs generated in the same invocation will be monotonically increasing.
```bash
ulid --count 15
```
```bash
npx ulid --count 5
```
```bash
$ ulid --count 5
01HNZXD07M5CEN5XA66EMZSRZW
01HNZXD07M5CEN5XA66EMSZSRX
01HNZXD07M5CEN5XA66EMZSRSY
01HNZXD07M5CEN5XA66EMZSRTZ
01HNZXD07M5CEN5XA66EMZSRU0
```
```bash
$ ulid --count=3
01HNZXD07M5CEN5XA66EMZSRZW
01HNZXD07M5CEN5XA66EMSZSRX
01HNZXD07M5CEN5XA66EMZSRSY
```
--------------------------------
### encodeTime()
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/ulid.md
Encodes a timestamp into the time portion of a ULID, generating a base32 string. It supports custom lengths and throws errors for invalid input.
```APIDOC
## Function: encodeTime()
### Description
Encode a timestamp into the time portion of a ULID (10 base32 characters by default).
### Signature
```typescript
function encodeTime(now: number, len: number = TIME_LEN): string
```
### Parameters
#### Path Parameters
- **now** (number) - Required - Timestamp in milliseconds. Must be a non-negative integer not exceeding `TIME_MAX`.
- **len** (number) - Optional - Number of base32 characters to generate. Defaults to `TIME_LEN` (10).
### Returns
`string` — The encoded time portion as a Crockford's base32 string of the specified length.
### Throws
- `ULIDError` with code `EncodeTimeValueMalformed` if `now` is `NaN` or not an integer.
- `ULIDError` with code `EncodeTimeNegative` if `now` is negative.
- `ULIDError` with code `EncodeTimeSizeExceeded` if `now` exceeds `TIME_MAX` (281474976710655).
### Example
```typescript
import { encodeTime } from "ulid";
// Encode a standard ULID timestamp (10 characters)
const encoded = encodeTime(1469918176385);
console.log(encoded); // "01ARYZ6S41"
// Encode with custom length
const shortEncoding = encodeTime(1469918176385, 5);
console.log(shortEncoding); // "01ARY"
```
```
--------------------------------
### Generate Monotonic ULIDs
Source: https://github.com/ulid/javascript/blob/master/_autodocs/START_HERE.md
Generate ULIDs that are guaranteed to be monotonically increasing. This is useful for scenarios where order is important.
```typescript
import { monotonicFactory } from "ulid";
const factory = monotonicFactory();
console.log(factory()); // "01HNZXD07M5CEN5XA66EMZSRZW"
console.log(factory()); // "01HNZXD07M5CEN5XA66EMSZSRX"
```
--------------------------------
### incrementBase32()
Source: https://github.com/ulid/javascript/blob/master/_autodocs/api-reference/crockford.md
Increments a base32 string by 1, following Crockford's base32 alphabet order. This function is useful for generating sequential ULIDs within the same millisecond.
```APIDOC
## Function: incrementBase32()
Increment a base32 string by 1, following Crockford's base32 alphabet order.
```typescript
function incrementBase32(str: string): string
```
### Parameters
#### Path Parameters
- **str** (string) - Required - A Crockford's base32 string to increment. Characters must all be in the valid alphabet.
### Returns
`string` — The incremented base32 string. Same length as input.
### Throws:
- `ULIDError` with code `Base32IncorrectEncoding` if the string contains characters not in Crockford's base32 alphabet or if the string is all maximum characters and cannot be incremented further.
### Algorithm:
1. Starts from the rightmost character
2. Finds its position in the Crockford base32 alphabet
3. Increments to the next character in the alphabet
4. If the character was already at max (`Z`), replaces it with `0` and carries the increment to the left
5. Continues leftward until a character that can be incremented is found
### Example:
```typescript
import { incrementBase32 } from "ulid";
// Increment a random portion
const incremented1 = incrementBase32("YYYYYYYYYYYYYYYY");
console.log(incremented1); // "YYYYYYYYYYYYYYYZ"
const incremented2 = incrementBase32("YYYYYYYYYYYYYYYZ");
console.log(incremented2); // "YYYYYYYYYYYYYYZ0"
const incremented3 = incrementBase32("YYYYYYYYYYYYYYZ0");
console.log(incremented3); // "YYYYYYYYYYYYYYZ1"
// Used internally by monotonicFactory for same-millisecond ULIDs
```
```