@grkndev/snowflakeid
Version:
A simple Snowflake ID generator for JavaScript and TypeScript
68 lines (67 loc) • 2.82 kB
TypeScript
/**
* Options for customizing Snowflake ID generation.
*/
interface SnowflakeOptions {
/** Custom epoch timestamp (in milliseconds since Unix epoch) */
epoch?: number;
/** Node ID (0-1023) for distributed systems */
nodeId?: number;
/** Initial sequence number (0-4095) */
sequence?: number;
}
interface RandomIdOptions {
useChars?: boolean;
useNumbers?: boolean;
}
/**
* Generates a Snowflake ID.
*
* @param {SnowflakeOptions} options - Custom options for ID generation
* @param {number} [options.epoch=DEFAULT_EPOCH] - Custom epoch timestamp
* @param {number} [options.nodeId=1] - Node ID for distributed systems
* @param {number} [options.sequence] - Initial sequence number
* @returns {string} The generated Snowflake ID as a string
* @throws {Error} If nodeId is invalid or if the clock moves backwards
*/
declare function generateSnowflakeId(options?: SnowflakeOptions): string;
/**
* Parses a Snowflake ID into its component parts.
*
* @param {string} id - The Snowflake ID to parse
* @param {number} [epoch=DEFAULT_EPOCH] - The epoch used in ID generation
* @returns {{timestamp: Date, nodeId: number, sequence: number}} Parsed components of the Snowflake ID
*/
declare function parseSnowflakeId(id: string, epoch?: number): {
timestamp: Date;
nodeId: number;
sequence: number;
};
/**
* Generates a random ID with a specified length.
* @param {number} [length=6] - The length of the random ID (must be >= 1)
* @param {RandomIdOptions} [options] - Custom options for ID generation
* @param {boolean} [options.useChars=false] - Use characters in the ID
* @param {boolean} [options.useNumbers=true] - Use numbers in the ID
* @returns {string} The generated random ID (example: "aBc123")
* @throws {Error} If length is less than 1 or if neither useChars nor useNumbers is true
*/
declare function randomId(length?: number, options?: RandomIdOptions): string;
/**
* Generates a pseudo-UUID string using random alphanumeric characters.
* Note: This is NOT a standard UUID (RFC 4122). It generates a random
* alphanumeric string split into segments for readability.
* For cryptographically secure UUIDs, use crypto.randomUUID() instead.
* @param {number} [split=4] - The number of 8-character segments to generate (must be >= 1)
* @returns {string} The generated pseudo-UUID (example: "aBcD1234-EfGh5678-iJkL9012-MnOp3456")
* @throws {Error} If split is less than 1
*/
declare function uuid(split?: number): string;
export { generateSnowflakeId, parseSnowflakeId, randomId, uuid };
export type { SnowflakeOptions, RandomIdOptions };
declare const _default: {
generateSnowflakeId: typeof generateSnowflakeId;
parseSnowflakeId: typeof parseSnowflakeId;
randomId: typeof randomId;
uuid: typeof uuid;
};
export default _default;