### Install @nds-stack/bun-id Source: https://context7.com/nds-stack/bun-id/llms.txt Install the library using Bun's package manager. ```bash bun add @nds-stack/bun-id ``` -------------------------------- ### Run Benchmarks and Tests Source: https://context7.com/nds-stack/bun-id/llms.txt Execute the test suite using `bun test` and run benchmarks to compare the performance of different ID generators. Benchmark output shows operations per second. ```bash # Run the test suite bun test # Run benchmarks (outputs ops/s for each generator) bun run bench # Expected benchmark output (Bun 1.3.x, 10,000 iterations × 3 samples): # --- bun-id Benchmark --- # Operation | Throughput # ------------|------------- # ulid() | 1.0M ops/s # nanoid() | 2.7M ops/s # shortid() | 3.2M ops/s # uuid() | 3.9M ops/s ``` -------------------------------- ### Import and Use ID Generators in Bun Source: https://github.com/nds-stack/bun-id/blob/main/README.md Import various ID generation functions from the library and demonstrate their basic usage. Each function produces a different type of ID with specific characteristics. ```typescript import { ulid, nanoid, shortid, uuid } from "@nds-stack/bun-id"; ulid(); // → "0DH9X7BV4BAJ5G7KVM2P" (20 chars, sortable) nanoid(); // → "V1StGXR8_Z5jdHi6B-myT" (21 chars, URL-safe) shortid(); // → "a3b8c9d1" (8 chars, compact) uuid(); // → "550e8400e29b41d4a716446655440000" (32 chars, no dashes) ``` -------------------------------- ### Bun ID Generation Benchmarks Source: https://github.com/nds-stack/bun-id/blob/main/README.md Performance comparison of different ID generation functions within the @nds-stack/bun-id library. Shows throughput in operations per second for ulid, nanoid, shortid, and uuid. ```text Bun 1.3.13, 10000 iterations x 3 samples Operation | Throughput ------------|------------- ulid() | 1.0M ops/s nanoid() | 2.7M ops/s shortid() | 3.2M ops/s uuid() | 3.9M ops/s ``` -------------------------------- ### nanoid(size?) Source: https://github.com/nds-stack/bun-id/blob/main/README.md Generates a URL-safe ID using a base64-like alphabet (A-Za-z0-9_-). The default size is 21 characters, providing approximately 126 bits of entropy, which results in a virtually zero collision probability. ```APIDOC ## nanoid(size?) ### Description Generates a URL-safe ID using a base64-like alphabet (A-Za-z0-9_-). The default size is 21 characters, providing approximately 126 bits of entropy, which results in a virtually zero collision probability. ### Function Signature ```typescript nanoid(size?: number): string // default: 21 ``` ``` -------------------------------- ### shortid() Source: https://github.com/nds-stack/bun-id/blob/main/README.md Generates a compact 8-character hexadecimal ID using 4 random bytes (32 bits of entropy). This is suitable for log correlation or display IDs where approximately 4 billion unique values are sufficient. ```APIDOC ## shortid() ### Description Generates a compact 8-character hexadecimal ID using 4 random bytes (32 bits of entropy). This is suitable for log correlation or display IDs where approximately 4 billion unique values are sufficient. ### Function Signature ```typescript shortid(): string // 8 hex chars = 32 bits ``` ``` -------------------------------- ### Choose the Right ID Generator Source: https://context7.com/nds-stack/bun-id/llms.txt Select the appropriate ID generator based on requirements like sortability, length, entropy, and intended use case. Imports are tree-shakeable. ```typescript import { ulid, nanoid, shortid, uuid } from "@nds-stack/bun-id"; // Primary key / event sourcing → ulid() (sortable, 20 chars) const eventId = ulid(); // URL token / API key / session → nanoid() (URL-safe, configurable) const apiKey = nanoid(32); // Log correlation / display ref → shortid() (compact, 8 chars) const correlId = shortid(); // Legacy UUID compatibility → uuid() (32-char hex, no dashes) const legacyId = uuid(); ``` -------------------------------- ### Generate NanoID with @nds-stack/bun-id Source: https://github.com/nds-stack/bun-id/blob/main/README.md Generates a URL-safe ID using the A-Za-z0-9_- alphabet. The default size is 21 characters, providing approximately 126 bits of entropy for a very low collision probability. ```typescript nanoid(size?: number): string // default: 21 ``` -------------------------------- ### Generate Compact UUIDs with `uuid()` Source: https://context7.com/nds-stack/bun-id/llms.txt Wraps `crypto.randomUUID()` to produce a 32-character lowercase hex string without dashes. Ideal for systems that accept UUIDs without formatting or for storage efficiency. Re-format to standard UUID string if needed. ```typescript import { uuid } from "@nds-stack/bun-id"; // Basic usage const id = uuid(); console.log(id); console.log(id.length); console.log(/^[0-9a-f]+$/.test(id)); // Compare with native crypto.randomUUID() const native = crypto.randomUUID(); const compact = uuid(); // Re-format to standard UUID string if needed function toUUIDFormat(compactId: string): string { return `${compactId.slice(0,8)}-${compactId.slice(8,12)}-${compactId.slice(12,16)}-${compactId.slice(16,20)}-${compactId.slice(20)}`; } console.log(toUUIDFormat(compact)); // Database row with compact UUID const row = { id: uuid(), payload: "data" }; console.log(row); ``` -------------------------------- ### uuid() Source: https://github.com/nds-stack/bun-id/blob/main/README.md Wraps Bun's built-in `crypto.randomUUID()` function and removes the dashes, resulting in a compact 32-character hexadecimal string. This is useful for legacy compatibility. ```APIDOC ## uuid() ### Description Wraps Bun's built-in `crypto.randomUUID()` function and removes the dashes, resulting in a compact 32-character hexadecimal string. This is useful for legacy compatibility. ### Function Signature ```typescript uuid(): string // 32 hex chars ``` ``` -------------------------------- ### Generate ShortID with @nds-stack/bun-id Source: https://github.com/nds-stack/bun-id/blob/main/README.md Generates a compact 8-character hexadecimal ID using 4 random bytes. This provides 32 bits of entropy, suitable for log correlation or display IDs where approximately 4 billion unique values are sufficient. ```typescript shortid(): string // 8 hex chars = 32 bits ``` -------------------------------- ### ulid() Source: https://github.com/nds-stack/bun-id/blob/main/README.md Generates a ULID (Universally Unique Lexicographically Sortable Identifier). It includes a 48-bit timestamp prefix and 80-bit random data, encoded into 26 Crockford base32 characters. The IDs are sortable by timestamp and URL-safe. ```APIDOC ## ulid() ### Description Generates a ULID (Universally Unique Lexicographically Sortable Identifier). It includes a 48-bit timestamp prefix and 80-bit random data, encoded into 26 Crockford base32 characters. The IDs are sortable by timestamp and URL-safe. **Properties:** - **Sortable**: IDs generated close together sort lexicographically (timestamp prefix) - **Case-insensitive**: Crockford base32 avoids ambiguous characters (I, L, O, U) - **Time-safe**: Timestamp uses `Date.now()` — about 1ms precision ### Function Signature ```typescript ulid(): string ``` ``` -------------------------------- ### Generate ShortID with @nds-stack/bun-id Source: https://context7.com/nds-stack/bun-id/llms.txt Generates a compact 8-character lowercase hex ID from 4 random bytes. Suitable for log correlation IDs or display references where brevity is key. ```typescript import { shortid } from "@nds-stack/bun-id"; // Basic usage const id = shortid(); console.log(id); // "a3b8c9d1" console.log(id.length); // 8 console.log(/^[0-9a-f]+$/.test(id)); // true — lowercase hex // Log correlation function logRequest(method: string, path: string) { const reqId = shortid(); console.log(`[${reqId}] ${method} ${path}`); return reqId; } const reqId = logRequest("GET", "/api/users"); // [a3b8c9d1] GET /api/users console.log(`[${reqId}] Response: 200 OK`); // [a3b8c9d1] Response: 200 OK // Display-friendly reference numbers const order = { ref: shortid().toUpperCase(), total: 49.99 }; console.log(`Order #${order.ref} confirmed — $${order.total}`); // Order #A3B8C9D1 confirmed — $49.99 ``` -------------------------------- ### Generate ULID with @nds-stack/bun-id Source: https://context7.com/nds-stack/bun-id/llms.txt Generates a 20-character ULID suitable for database primary keys and event streams. IDs generated later will lexicographically sort after earlier ones. ```typescript import { ulid } from "@nds-stack/bun-id"; // Basic usage const id = ulid(); console.log(id); // "0DH9X7BV4BAJ5G7KVM2P" — 20 chars, uppercase alphanumeric console.log(id.length); // 20 console.log(/^[0-9A-Z]+$/.test(id)); // true // Sortability: IDs generated later will be >= earlier ones const ids = Array.from({ length: 5 }, () => ulid()); const sorted = [...ids].sort(); console.log(ids); // already in ascending order (within same ms, random suffix) console.log(sorted.every((v, i) => v === ids[i])); // true (already sorted) // Use as a database primary key const record = { id: ulid(), // "0DH9XABCDE0123456789" createdAt: new Date().toISOString(), name: "Example", }; console.log(record); // { id: '0DH9XABCDE0123456789', createdAt: '2025-01-15T10:30:00.000Z', name: 'Example' } ``` -------------------------------- ### Generate UUID with @nds-stack/bun-id Source: https://github.com/nds-stack/bun-id/blob/main/README.md Generates a UUID (Universally Unique Identifier) by wrapping Bun's crypto.randomUUID() and removing the dashes. This results in a compact 32-character hexadecimal string for legacy compatibility. ```typescript uuid(): string // 32 hex chars ``` -------------------------------- ### ulid() Source: https://context7.com/nds-stack/bun-id/llms.txt Generates a 20-character Universally Unique Lexicographically Sortable Identifier. Ideal for database primary keys and event IDs due to its sortability. ```APIDOC ## ulid() ### Description Generates a 20-character Universally Unique Lexicographically Sortable Identifier. The first 10 characters encode a 48-bit millisecond timestamp using Crockford base32; the remaining 10 characters are 80 bits of cryptographic randomness. IDs generated later will sort lexicographically after earlier ones, making them ideal for database primary keys and event IDs. ### Usage ```typescript import { ulid } from "@nds-stack/bun-id"; // Basic usage const id = ulid(); console.log(id); // "0DH9X7BV4BAJ5G7KVM2P" console.log(id.length); // 20 // Sortability example const ids = Array.from({ length: 5 }, () => ulid()); console.log(ids); // already in ascending order (within same ms, random suffix) // Use as a database primary key const record = { id: ulid(), createdAt: new Date().toISOString(), name: "Example", }; console.log(record); // { id: '0DH9XABCDE0123456789', createdAt: '2025-01-15T10:30:00.000Z', name: 'Example' } ``` ``` -------------------------------- ### Generate ULID with @nds-stack/bun-id Source: https://github.com/nds-stack/bun-id/blob/main/README.md Generates a ULID (Universally Unique Lexicographically Sortable Identifier) using Crockford base32 encoding. It includes a timestamp prefix for sortability and is case-insensitive. ```typescript ulid(): string ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.