@inizioevoke/tsid
v1.1.0
Published
Timestamp-prefixed, lexicographically sortable unique IDs. Similar in spirit to [ULID](https://github.com/ulid/spec), with configurable output length, UUID-compatible output, and a monotonic factory.
Downloads
41
Keywords
Readme
@inizioevoke/tsid
Timestamp-prefixed, lexicographically sortable unique IDs. Similar in spirit to ULID, with configurable output length, UUID-compatible output, and a monotonic factory.
Format
Every ID has the shape:
<10 timestamp chars><random chars>- Timestamp: 48 bits packed into 10 Crockford Base32 chars. Same width and encoding as ULID; the first char is always
0–7(top 2 bits unused). Range:0to281,474,976,710,655ms since epoch (year 10,889). - Random: variable width. Default is 30 bits (6 chars), giving 16-char IDs total.
Crockford Base32 excludes I, L, O, and U to reduce visual ambiguity. Because the alphabet is ASCII-ordered, lexicographic sort matches numeric sort — you can sort IDs as plain strings in a database column and get chronological order.
When format: 'uuid' is used, the ID is instead rendered as a 128-bit hex value in the canonical UUID shape xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. The timestamp still occupies the leading 48 bits (first 12 hex chars), so UUID-formatted IDs remain sortable by generation time.
Install
npm install @inizioevoke/tsidEnvironment support
Uses the standard crypto.getRandomValues API for random generation, available on globalThis.crypto in:
- Node.js ≥ 20 (stable, unflagged).
- All modern browsers over
https://orlocalhost. Not available in insecure (http://) contexts on some browsers. - Deno, Bun, and other runtimes that expose Web Crypto.
One build serves every environment — the Quick start imports work identically in Node and bundlers (Vite, webpack, Rollup, esbuild). BigInt is used internally, so IE is not supported (Chrome 67+, Safari 14+, Firefox 68+).
Quick start
import { tsid, ulid, uuid, TSIDFactory, parseTSID } from '@inizioevoke/tsid';
tsid(); // '01M2GC9Y7C0JTWDS' — 16 chars
tsid({ length: 26 }); // 26-char ID with more random entropy
tsid(1700000000000); // ID with a fixed timestamp
ulid(); // 26-char ULID-shaped ID
uuid(); // '01a1138c-daa4-8444-a1c8-c99a98e51c72'
const factory = new TSIDFactory();
factory.generate(); // strictly increasing across calls
factory.generate();
parseTSID('01M2GC9Y7C0JTWDS'); // { timestamp: 1701213889388, random: 626770154n }tsid(...) — one-shot function
Each call creates a fresh factory and generates a single ID. Not monotonic across calls — if you need strict ordering, use TSIDFactory.
tsid(): string
tsid(timestamp: number | Date): string
tsid(opts: TSIDOptions): string
tsid(timestamp: number | Date, opts: TSIDOptions): string| Arg | Type | Default |
|---|---|---|
| timestamp | number (ms since epoch) or Date | Date.now() |
| opts | TSIDOptions | {} |
ulid() / uuid() — convenience helpers
Thin wrappers over tsid(...) that preset format:
ulid(): string
ulid(timestamp: number | Date): string
uuid(): string
uuid(timestamp: number | Date): stringulid()— 26-char Crockford Base32 output (matches ULID's width).uuid()— 128-bit hex output in canonical UUID shape.
TSIDFactory — monotonic generator
A stateful factory that guarantees every ID it produces is strictly greater than every previous ID from the same instance.
class TSIDFactory {
constructor();
constructor(timestamp: number | Date);
constructor(opts: TSIDOptions);
constructor(timestamp: number | Date, opts: TSIDOptions);
generate(): string;
}Constructor
Takes the same arguments as tsid(...). The timestamp (or Date.now() if omitted) is captured once and used as the anchor for every subsequent generate() call — the factory is decoupled from wall-clock time after construction.
generate()
- First call — anchors on the captured timestamp with a cryptographically random seed.
- Subsequent calls — hold the timestamp steady and advance the random portion by a random step in
[1, 2^stepBits], wherestepBits = min(randomBits / 2, 16). This keeps the sequence strictly monotonic while making the next ID non-trivial to predict. - Random space exhausted — timestamp bumps by 1 ms and the random portion rerolls with full entropy.
- Timestamp overflow — throws
Monotonic overflow: timestamp exceeded maximum(only reachable after generating an astronomically large number of IDs).
Example
const f = new TSIDFactory({ length: 11 });
f.generate(); // '01M2GCVAE0X'
f.generate(); // '01M2GCVAE0Y' — same timestamp, random advanced
f.generate(); // '01M2GCVAE0Z'
f.generate(); // '01M2GCVAE10' — random space exhausted, timestamp bumped
f.generate(); // '01M2GCVAE11'At length: 11 there's only 5 bits of random space, so overflow happens quickly. At the default 16 chars (30 random bits), roughly 65,000 IDs fit per ms before the timestamp bumps.
TSIDOptions
type TSIDFormat = 'tsid' | 'ulid' | 'uuid';
interface TSIDOptions {
length?: number; // total output character count. Default: 16 (tsid), 26 (ulid). Ignored for 'uuid'.
format?: TSIDFormat; // Default: 'tsid'.
}format: 'tsid'(default) — Crockford Base32, length controlled bylength.format: 'ulid'— Crockford Base32 at ULID width (26 chars) by default. Still acceptslengthto override.format: 'uuid'— 128-bit hex in canonical UUID shape (8-4-4-4-12). Length is fixed at 36 chars;lengthis ignored.- Minimum length — random must be at least 1 Crockford char (5 bits), so
length >= 11.
Length ↔ random reference (Base32 formats)
| length | Random chars | Random values |
|---|---|---|
| 11 | 1 | 32 |
| 12 | 2 | 1,024 |
| 16 (default) | 6 | ~1 billion |
| 20 | 10 | ~10²¹ |
| 24 | 14 | ~10²⁴ |
| 26 (ulid) | 16 | ~10²⁴ |
parseTSID(id)
Decodes an ID back to its timestamp and random portions. Auto-detects UUID format by the presence of - characters.
parseTSID(id: string): { timestamp: number; random: bigint }- Returns the timestamp as a
number(ms since epoch) and the random portion as abigint. - Base32 input is case-insensitive.
- Throws if the input is too short, contains invalid characters, or decodes to a timestamp beyond the 48-bit range.
parseTSID('01M2GC9Y7C0JTWDS');
// { timestamp: 1701213889388, random: 626770154n }
parseTSID('01a1138c-daa4-8444-a1c8-c99a98e51c72');
// { timestamp: 1791329517732, random: 723966209650620349025947n }
parseTSID('01m2gc9y7c0jtwds'); // lowercase Base32 OK
parseTSID('OiM2GC9Y7C0JTWDS'); // invalid Base32 — throwsSort ordering
IDs sort correctly as plain strings in any collation that compares by codepoint (SQL ORDER BY, Array.prototype.sort(), etc.):
const ids = [tsid(), tsid(), tsid()];
[...ids].sort(); // chronological orderThis holds because:
- The timestamp is fixed-width (10 Base32 chars or 12 hex chars, zero-padded).
- Both Crockford Base32 and hex are ASCII-ordered.
- The random portion is fixed-width for a given
length/format.
UUID-formatted IDs sort chronologically too — the dashes sit at the same positions in every ID, and the leading 12 hex chars encode the timestamp.
Script tag / IIFE build
For pages that consume the library via a <script> tag (no bundler, no module system), the package ships a self-contained IIFE bundle that installs a callable global named tsid.
Loading
<!-- production (minified) -->
<script src="https://unpkg.com/@inizioevoke/tsid/dist/iife/index.min.js"></script>
<!-- development (unminified, easier to debug) -->
<script src="https://unpkg.com/@inizioevoke/tsid/dist/iife/index.js"></script>
<!-- or served from a local install -->
<script src="./node_modules/@inizioevoke/tsid/dist/iife/index.min.js"></script>API
The IIFE global has a flatter, shorter shape than the module API. tsid itself is the generator function; parse and Factory are attached as properties.
| Module API | IIFE global |
| --------------------------------- | ------------------- |
| tsid(...) | tsid(...) |
| parseTSID(id) | tsid.parse(id) |
| new TSIDFactory(...) | new tsid.Factory(...) |
<script>
// Generator — same signatures as the module `tsid(...)` function
tsid(); // '01M2GC9Y7C0JTWDS'
tsid({ length: 20 }); // 20-char ID
tsid({ format: 'uuid' }); // '01a1138c-daa4-8444-a1c8-c99a98e51c72'
tsid(1700000000000); // ID with a fixed timestamp
// Parse — same as parseTSID
tsid.parse('01M2GC9Y7C0JTWDS'); // { timestamp: 1701213889388, random: ... }
// Monotonic factory — same as TSIDFactory
const f = new tsid.Factory({ length: 16 });
f.generate();
f.generate();
</script>TypeScript
The package publishes ambient type declarations for the tsid global. Pull them in project-wide via tsconfig:
{
"compilerOptions": {
"types": ["@inizioevoke/tsid/iife"]
}
}Or per-file with a triple-slash reference:
/// <reference types="@inizioevoke/tsid/iife" />
tsid();
tsid.parse('01M2GC9Y7C');
new tsid.Factory();The exported TSID type is also available if you need to reference the callable's shape directly:
import type { TSID } from '@inizioevoke/tsid/iife';Comparison to ULID / UUID
| | ULID | UUIDv4 | TSID | |---|---|---|---| | Encoding | Crockford Base32 | Hex (8-4-4-4-12) | Base32 or hex (configurable) | | Timestamp bits | 48 | 0 (random) | 48 | | Total length | 26 chars | 36 chars | Configurable (default 16) | | Random bits | 80 | 122 | Configurable | | Monotonic factory | Yes | No | Yes | | Sortable by time | Yes | No | Yes |
TSID's differentiators: length flexibility (pick 16 chars for URLs, 24+ for higher entropy), a random-step monotonic sequence that isn't linearly enumerable, and a UUID output mode for columns that require the standard UUID shape.
