uniku 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -12
- package/build/cuid2/cuid2.d.mts +1 -1
- package/build/cuid2/cuid2.d.mts.map +1 -1
- package/build/cuid2/cuid2.mjs +1 -1
- package/build/cuid2/cuid2.mjs.map +1 -1
- package/build/errors-Da-8dh4J.d.mts +67 -0
- package/build/errors-Da-8dh4J.d.mts.map +1 -0
- package/build/errors.d.mts +2 -2
- package/build/errors.mjs +1 -1
- package/build/errors.mjs.map +1 -1
- package/build/generators-BfJLt7Qf.d.mts +17 -0
- package/build/generators-BfJLt7Qf.d.mts.map +1 -0
- package/build/generators.d.mts +2 -17
- package/build/ksuid/ksuid.d.mts +10 -4
- package/build/ksuid/ksuid.d.mts.map +1 -1
- package/build/ksuid/ksuid.mjs +1 -1
- package/build/ksuid/ksuid.mjs.map +1 -1
- package/build/nanoid/nanoid.d.mts +13 -7
- package/build/nanoid/nanoid.d.mts.map +1 -1
- package/build/nanoid/nanoid.mjs +1 -1
- package/build/nanoid/nanoid.mjs.map +1 -1
- package/build/objectid/objectid.d.mts +10 -3
- package/build/objectid/objectid.d.mts.map +1 -1
- package/build/objectid/objectid.mjs +1 -1
- package/build/objectid/objectid.mjs.map +1 -1
- package/build/timestamp-ChrSuQCR.mjs +2 -0
- package/build/timestamp-ChrSuQCR.mjs.map +1 -0
- package/build/tsid/tsid.d.mts +1 -1
- package/build/tsid/tsid.d.mts.map +1 -1
- package/build/tsid/tsid.mjs +1 -1
- package/build/tsid/tsid.mjs.map +1 -1
- package/build/typeid/typeid.d.mts +4 -2
- package/build/typeid/typeid.d.mts.map +1 -1
- package/build/typeid/typeid.mjs +1 -1
- package/build/typeid/typeid.mjs.map +1 -1
- package/build/ulid/ulid.d.mts +1 -1
- package/build/ulid/ulid.d.mts.map +1 -1
- package/build/ulid/ulid.mjs +1 -1
- package/build/ulid/ulid.mjs.map +1 -1
- package/build/uuid/v4.d.mts +1 -1
- package/build/uuid/v4.d.mts.map +1 -1
- package/build/uuid/v4.mjs +1 -1
- package/build/uuid/v4.mjs.map +1 -1
- package/build/uuid/v7.d.mts +8 -2
- package/build/uuid/v7.d.mts.map +1 -1
- package/build/uuid/v7.mjs +1 -1
- package/build/uuid/v7.mjs.map +1 -1
- package/build/uuid-BPebYihz.mjs +2 -0
- package/build/uuid-BPebYihz.mjs.map +1 -0
- package/build/xid/xid.d.mts +12 -2
- package/build/xid/xid.d.mts.map +1 -1
- package/build/xid/xid.mjs +1 -1
- package/build/xid/xid.mjs.map +1 -1
- package/package.json +1 -1
- package/src/common/timestamp.ts +70 -0
- package/src/cuid2/cuid2.ts +5 -2
- package/src/errors.ts +75 -10
- package/src/ksuid/base62.ts +7 -7
- package/src/ksuid/ksuid.ts +19 -15
- package/src/nanoid/nanoid.ts +41 -18
- package/src/objectid/hex.ts +6 -4
- package/src/objectid/objectid.ts +24 -11
- package/src/tsid/crockford64.ts +7 -6
- package/src/tsid/tsid.ts +20 -13
- package/src/typeid/typeid.ts +106 -16
- package/src/ulid/crockford.ts +8 -6
- package/src/ulid/ulid.ts +11 -7
- package/src/uuid/common/uuid.ts +12 -4
- package/src/uuid/v4.ts +5 -2
- package/src/uuid/v7.ts +25 -9
- package/src/xid/base32hex.ts +8 -7
- package/src/xid/xid.ts +25 -12
- package/build/errors-Dgoyi-ci.d.mts +0 -38
- package/build/errors-Dgoyi-ci.d.mts.map +0 -1
- package/build/generators.d.mts.map +0 -1
- package/build/uuid-CnQIYoQi.mjs +0 -2
- package/build/uuid-CnQIYoQi.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
[](https://jkomyno.github.io/uniku/)
|
|
7
7
|
[](https://opensource.org/licenses/MIT)
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Ten ID strategies behind one consistent, type-safe API. The fastest implementation of each in our [current CI benchmark](https://jkomyno.github.io/uniku/docs/guides/performance/).
|
|
10
10
|
|
|
11
|
-
> **uniku** */uˈniːku
|
|
11
|
+
> **uniku** */uˈniːku/*: Maltese for "unique"
|
|
12
12
|
|
|
13
13
|
[Documentation](https://jkomyno.github.io/uniku/) · [Getting started](https://jkomyno.github.io/uniku/docs/getting-started/) · [Choosing an ID](https://jkomyno.github.io/uniku/docs/guides/choosing-an-id/) · [API reference](https://jkomyno.github.io/uniku/docs/reference/entry-points/) · [CLI](https://jkomyno.github.io/uniku/docs/cli/)
|
|
14
14
|
|
|
@@ -21,11 +21,12 @@ const id = uuidv7()
|
|
|
21
21
|
|
|
22
22
|
## Why `uniku`?
|
|
23
23
|
|
|
24
|
-
- **
|
|
25
|
-
- **
|
|
26
|
-
- **
|
|
27
|
-
- **
|
|
28
|
-
- **
|
|
24
|
+
- **Fastest across the benchmark suite.** Every strategy beats its dedicated npm alternative in the current isolated-process CI benchmark, from 1.2× for UUID v4 and ObjectID to 116× for ULID.
|
|
25
|
+
- **Ten strategies, one type-safe API.** UUID v4/v7, ULID, TypeID, CUID v2, Nanoid, KSUID, ObjectID, XID, and TSID each expose a callable generator with matching typed helpers.
|
|
26
|
+
- **Portable by default.** Runs on Node.js, Bun, Deno, browsers, edge runtimes, and Cloudflare Workers using `globalThis.crypto`.
|
|
27
|
+
- **Tree-shakeable entry points.** Import only the generator you use; the package root is intentionally not exported.
|
|
28
|
+
- **Useful at system boundaries.** Validate unknown input, convert canonical binary formats to bytes, or write directly into a caller-owned buffer.
|
|
29
|
+
- **Small dependency surface.** CUID v2 is the only generator with a runtime dependency (`@noble/hashes`).
|
|
29
30
|
|
|
30
31
|
## Install
|
|
31
32
|
|
|
@@ -82,11 +83,11 @@ The [choosing guide](https://jkomyno.github.io/uniku/docs/guides/choosing-an-id/
|
|
|
82
83
|
|
|
83
84
|
## Documentation
|
|
84
85
|
|
|
85
|
-
- [Getting started](https://jkomyno.github.io/uniku/docs/getting-started/)
|
|
86
|
-
- [Generator reference](https://jkomyno.github.io/uniku/docs/reference/entry-points/)
|
|
87
|
-
- [Migration guide](https://jkomyno.github.io/uniku/docs/migration/from-other-libraries/)
|
|
88
|
-
- [Performance and bundle size](https://jkomyno.github.io/uniku/docs/guides/performance/)
|
|
89
|
-
- [Stability contract](https://github.com/jkomyno/uniku/blob/main/docs/STABILITY.md)
|
|
86
|
+
- [Getting started](https://jkomyno.github.io/uniku/docs/getting-started/): installation, direct imports, validation, and byte helpers
|
|
87
|
+
- [Generator reference](https://jkomyno.github.io/uniku/docs/reference/entry-points/): generated from the public TypeScript signatures and JSDoc
|
|
88
|
+
- [Migration guide](https://jkomyno.github.io/uniku/docs/migration/from-other-libraries/): move from `uuid`, `nanoid`, `ulid`, CUID2, KSUID, BSON, TSID, or XID libraries
|
|
89
|
+
- [Performance and bundle size](https://jkomyno.github.io/uniku/docs/guides/performance/): benchmark methodology, current measurements, and reproduction commands
|
|
90
|
+
- [Stability contract](https://github.com/jkomyno/uniku/blob/main/docs/STABILITY.md): the entry points and compatibility policy planned for `uniku@1.0.0`
|
|
90
91
|
|
|
91
92
|
## CLI companion
|
|
92
93
|
|
package/build/cuid2/cuid2.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cuid2.d.mts","names":[],"sources":["../../src/cuid2/cuid2.ts"],"mappings":";;;KAIY,YAAA;;;AAAZ;;EAKE,MAAA;EAOS;;;;;AAAA;EAAT,MAAA,GAAS,UAAA;AAAA;AAAA,KAGC,KAAA;EAEC,kCAAV,OAAA,GAAU,YAAA;EAEX,OAAA,CAAQ,EAAA,YAAc,EAAA;AAAA;;;AAAA;
|
|
1
|
+
{"version":3,"file":"cuid2.d.mts","names":[],"sources":["../../src/cuid2/cuid2.ts"],"mappings":";;;KAIY,YAAA;;;AAAZ;;EAKE,MAAA;EAOS;;;;;AAAA;EAAT,MAAA,GAAS,UAAA;AAAA;AAAA,KAGC,KAAA;EAEC,kCAAV,OAAA,GAAU,YAAA;EAEX,OAAA,CAAQ,EAAA,YAAc,EAAA;AAAA;;;AAAA;AAoMxB;;;;AAAoB;;;;;;;;;;;;;;;;;;;;;;;;;cAAP,KAAA,EAAO,KAAA"}
|
package/build/cuid2/cuid2.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../random-Chp-Nkzi.mjs";import{InvalidInputError as t,UniqueIdError as n}from"../errors.mjs";import{sha3_512 as r}from"@noble/hashes/sha3.js";const i=/^[a-z][0-9a-z]+$/,a=`0123456789abcdefghijklmnopqrstuvwxyz`,o=new TextEncoder,s={counter:void 0,fingerprint:void 0};function c(){return e()%476782368}function l(e){let t=0n;for(let n of e)t=t*256n+BigInt(n);return t}function u(e){if(e===0n)return`0`;let t=[];for(;e>0n;)t.push(a[Number(e%36n)]),e/=36n;return t.reverse().join(``)}function d(e){return`abcdefghijklmnopqrstuvwxyz`[Math.floor(e()*26)]}function f(e,t){let n=Array(e);for(let r=0;r<e;r++)n[r]=a[Math.floor(t()*36)];return n.join(``)}function p(e){return r(o.encode(e))}function m(){let e=h;return u(l(p(Object.keys(globalThis).toString()+f(32,e)))).slice(1,33)}function h(){return e()/4294967296}function g(e){if(e){if(e.length===0)throw new t(`
|
|
1
|
+
import{n as e}from"../random-Chp-Nkzi.mjs";import{InvalidInputError as t,UniqueIdError as n}from"../errors.mjs";import{sha3_512 as r}from"@noble/hashes/sha3.js";const i=/^[a-z][0-9a-z]+$/,a=`0123456789abcdefghijklmnopqrstuvwxyz`,o=new TextEncoder,s={counter:void 0,fingerprint:void 0};function c(){return e()%476782368}function l(e){let t=0n;for(let n of e)t=t*256n+BigInt(n);return t}function u(e){if(e===0n)return`0`;let t=[];for(;e>0n;)t.push(a[Number(e%36n)]),e/=36n;return t.reverse().join(``)}function d(e){return`abcdefghijklmnopqrstuvwxyz`[Math.floor(e()*26)]}function f(e,t){let n=Array(e);for(let r=0;r<e;r++)n[r]=a[Math.floor(t()*36)];return n.join(``)}function p(e){return r(o.encode(e))}function m(){let e=h;return u(l(p(Object.keys(globalThis).toString()+f(32,e)))).slice(1,33)}function h(){return e()/4294967296}function g(e){if(e){if(e.length===0)throw new t(`RANDOM_BYTES_TOO_SHORT`,`Random byte array cannot be empty`,{strategy:`cuid`});let n=0;return()=>{let t=e[n%e.length]/256;return n+=1,t}}return h}function _(e){let n=e?.length;if(n!==void 0&&(!Number.isInteger(n)||n<2||n>32))throw new t(`LENGTH_OUT_OF_RANGE`,`CUID2 length must be between 2 and 32. Received: ${n}`,{strategy:`cuid`});let r=n??24,i=g(e?.random);s.counter===void 0&&(s.counter=c()),s.fingerprint===void 0&&(s.fingerprint=m());let a=d(i),o=Date.now().toString(36);s.counter+=1;let h=s.counter.toString(36);return a+u(l(p(o+f(r,i)+h+s.fingerprint))).slice(1,r)}function v(e){return typeof e==`string`&&e.length>=2&&e.length<=32&&i.test(e)}const y=Object.assign(_,{isValid:v});export{t as InvalidInputError,n as UniqueIdError,y as cuid2};
|
|
2
2
|
//# sourceMappingURL=cuid2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cuid2.mjs","names":[],"sources":["../../src/cuid2/cuid2.ts"],"sourcesContent":["import { sha3_512 } from '@noble/hashes/sha3.js'\nimport { randomUint32 } from '../common/random'\nimport { InvalidInputError } from '../errors'\n\nexport type Cuid2Options = {\n /**\n * Length of the generated ID (2-32 characters).\n * Default: 24\n */\n length?: number\n /**\n * Custom random bytes for deterministic testing.\n * Must be at least 1 byte. For adequate entropy, use at least 16 bytes.\n * Note: The fingerprint always uses cryptographically secure random bytes,\n * regardless of this option.\n */\n random?: Uint8Array\n}\n\nexport type Cuid2 = {\n /** Generate a CUID v2 string. */\n (options?: Cuid2Options): string\n /** Return whether a value is a syntactically valid CUID v2 string. */\n isValid(id: unknown): id is string\n}\n\nconst DEFAULT_LENGTH = 24\nconst MAX_LENGTH = 32\nconst MIN_LENGTH = 2\n\n// Maximum initial counter value from cuid2 spec - provides ~29 bits of\n// initial entropy to prevent cross-process collisions at startup\nconst INITIAL_COUNT_MAX = 476782367\n\n// Validation regex: first char must be a-z, rest can be a-z or 0-9\nconst CUID2_REGEX = /^[a-z][0-9a-z]+$/\n\n// Base36 alphabet\nconst ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'\nconst LETTER_ALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n\n// Reusable TextEncoder instance (stateless, safe to share)\nconst textEncoder = new TextEncoder()\n\n/**\n * Module-level state for counter and fingerprint.\n * Counter is initialized lazily on first call to prevent unnecessary crypto operations.\n * Fingerprint is also generated lazily on first call.\n */\nconst state: { counter: number | undefined; fingerprint: string | undefined } = {\n counter: undefined,\n fingerprint: undefined,\n}\n\n/**\n * Initialize counter using crypto for consistency with other entropy sources.\n */\nfunction initializeCounter(): number {\n return randomUint32() % (INITIAL_COUNT_MAX + 1)\n}\n\n// --- Base36 utilities ---\n\nfunction bufToBigInt(buf: Uint8Array): bigint {\n let value = 0n\n for (const byte of buf) {\n value = value * 256n + BigInt(byte)\n }\n return value\n}\n\nfunction bigIntToBase36(value: bigint): string {\n if (value === 0n) return '0'\n const chars: string[] = []\n while (value > 0n) {\n chars.push(ALPHABET[Number(value % 36n)])\n value = value / 36n\n }\n return chars.reverse().join('')\n}\n\nfunction randomLetter(random: () => number): string {\n return LETTER_ALPHABET[Math.floor(random() * 26)]\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n const chars = new Array<string>(length)\n for (let i = 0; i < length; i++) {\n chars[i] = ALPHABET[Math.floor(random() * 36)]\n }\n return chars.join('')\n}\n\n// --- SHA3 hash wrapper ---\n\nfunction hash(input: string): Uint8Array {\n return sha3_512(textEncoder.encode(input))\n}\n\n// --- Fingerprint generation ---\n\nconst BIG_LENGTH = 32\n\nfunction createFingerprint(): string {\n // Always use CSPRNG for fingerprint to ensure security regardless of custom random option\n const random = getCryptoRandom\n const globals = Object.keys(globalThis).toString()\n const sourceString = globals + createEntropy(BIG_LENGTH, random)\n const hashed = hash(sourceString)\n return bigIntToBase36(bufToBigInt(hashed)).slice(1, BIG_LENGTH + 1)\n}\n\n// --- Random function factory ---\n\n/**\n * Get a random number in [0, 1) using CUID2's own random pool.\n */\nfunction getCryptoRandom(): number {\n return randomUint32() / 0x100000000\n}\n\nfunction getRandomFn(random?: Uint8Array): () => number {\n if (random) {\n if (random.length === 0) {\n throw new InvalidInputError('
|
|
1
|
+
{"version":3,"file":"cuid2.mjs","names":[],"sources":["../../src/cuid2/cuid2.ts"],"sourcesContent":["import { sha3_512 } from '@noble/hashes/sha3.js'\nimport { randomUint32 } from '../common/random'\nimport { InvalidInputError } from '../errors'\n\nexport type Cuid2Options = {\n /**\n * Length of the generated ID (2-32 characters).\n * Default: 24\n */\n length?: number\n /**\n * Custom random bytes for deterministic testing.\n * Must be at least 1 byte. For adequate entropy, use at least 16 bytes.\n * Note: The fingerprint always uses cryptographically secure random bytes,\n * regardless of this option.\n */\n random?: Uint8Array\n}\n\nexport type Cuid2 = {\n /** Generate a CUID v2 string. */\n (options?: Cuid2Options): string\n /** Return whether a value is a syntactically valid CUID v2 string. */\n isValid(id: unknown): id is string\n}\n\nconst DEFAULT_LENGTH = 24\nconst MAX_LENGTH = 32\nconst MIN_LENGTH = 2\n\n// Maximum initial counter value from cuid2 spec - provides ~29 bits of\n// initial entropy to prevent cross-process collisions at startup\nconst INITIAL_COUNT_MAX = 476782367\n\n// Validation regex: first char must be a-z, rest can be a-z or 0-9\nconst CUID2_REGEX = /^[a-z][0-9a-z]+$/\n\n// Base36 alphabet\nconst ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'\nconst LETTER_ALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n\n// Reusable TextEncoder instance (stateless, safe to share)\nconst textEncoder = new TextEncoder()\n\n/**\n * Module-level state for counter and fingerprint.\n * Counter is initialized lazily on first call to prevent unnecessary crypto operations.\n * Fingerprint is also generated lazily on first call.\n */\nconst state: { counter: number | undefined; fingerprint: string | undefined } = {\n counter: undefined,\n fingerprint: undefined,\n}\n\n/**\n * Initialize counter using crypto for consistency with other entropy sources.\n */\nfunction initializeCounter(): number {\n return randomUint32() % (INITIAL_COUNT_MAX + 1)\n}\n\n// --- Base36 utilities ---\n\nfunction bufToBigInt(buf: Uint8Array): bigint {\n let value = 0n\n for (const byte of buf) {\n value = value * 256n + BigInt(byte)\n }\n return value\n}\n\nfunction bigIntToBase36(value: bigint): string {\n if (value === 0n) return '0'\n const chars: string[] = []\n while (value > 0n) {\n chars.push(ALPHABET[Number(value % 36n)])\n value = value / 36n\n }\n return chars.reverse().join('')\n}\n\nfunction randomLetter(random: () => number): string {\n return LETTER_ALPHABET[Math.floor(random() * 26)]\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n const chars = new Array<string>(length)\n for (let i = 0; i < length; i++) {\n chars[i] = ALPHABET[Math.floor(random() * 36)]\n }\n return chars.join('')\n}\n\n// --- SHA3 hash wrapper ---\n\nfunction hash(input: string): Uint8Array {\n return sha3_512(textEncoder.encode(input))\n}\n\n// --- Fingerprint generation ---\n\nconst BIG_LENGTH = 32\n\nfunction createFingerprint(): string {\n // Always use CSPRNG for fingerprint to ensure security regardless of custom random option\n const random = getCryptoRandom\n const globals = Object.keys(globalThis).toString()\n const sourceString = globals + createEntropy(BIG_LENGTH, random)\n const hashed = hash(sourceString)\n return bigIntToBase36(bufToBigInt(hashed)).slice(1, BIG_LENGTH + 1)\n}\n\n// --- Random function factory ---\n\n/**\n * Get a random number in [0, 1) using CUID2's own random pool.\n */\nfunction getCryptoRandom(): number {\n return randomUint32() / 0x100000000\n}\n\nfunction getRandomFn(random?: Uint8Array): () => number {\n if (random) {\n if (random.length === 0) {\n throw new InvalidInputError('RANDOM_BYTES_TOO_SHORT', 'Random byte array cannot be empty', {\n strategy: 'cuid',\n })\n }\n let index = 0\n return () => {\n const value = random[index % random.length] / 256\n index += 1\n return value\n }\n }\n return getCryptoRandom\n}\n\n// --- Main generator ---\n\nfunction cuid2Fn(options?: Cuid2Options): string {\n const requestedLength = options?.length\n\n if (\n requestedLength !== undefined &&\n (!Number.isInteger(requestedLength) || requestedLength < MIN_LENGTH || requestedLength > MAX_LENGTH)\n ) {\n throw new InvalidInputError(\n 'LENGTH_OUT_OF_RANGE',\n `CUID2 length must be between ${MIN_LENGTH} and ${MAX_LENGTH}. Received: ${requestedLength}`,\n { strategy: 'cuid' },\n )\n }\n const length = requestedLength ?? DEFAULT_LENGTH\n\n const random = getRandomFn(options?.random)\n\n // Initialize counter lazily on first call\n if (state.counter === undefined) {\n state.counter = initializeCounter()\n }\n\n // Initialize fingerprint lazily on first call (always uses CSPRNG)\n if (state.fingerprint === undefined) {\n state.fingerprint = createFingerprint()\n }\n\n const firstLetter = randomLetter(random)\n const time = Date.now().toString(36)\n state.counter += 1\n const count = state.counter.toString(36)\n const salt = createEntropy(length, random)\n\n const hashInput = time + salt + count + state.fingerprint\n const hashed = hash(hashInput)\n const base36Hash = bigIntToBase36(bufToBigInt(hashed))\n\n // Drop first char of hash to avoid histogram bias, prepend random letter\n return firstLetter + base36Hash.slice(1, length)\n}\n\n// --- Validation (type guard) ---\n\nfunction isValid(id: unknown): id is string {\n return typeof id === 'string' && id.length >= MIN_LENGTH && id.length <= MAX_LENGTH && CUID2_REGEX.test(id)\n}\n\n/**\n * Generate a CUID v2 string.\n *\n * CUID v2 is a secure, collision-resistant identifier that hashes multiple\n * entropy sources using SHA3-512. Unlike time-ordered IDs (ULID, UUID v7),\n * CUID v2 prevents enumeration attacks by making IDs non-predictable.\n *\n * Note: CUID v2 does not provide toBytes/fromBytes because it is a string-native\n * format with no canonical binary representation (unlike UUID's 16-byte format).\n *\n * @example\n * ```ts\n * import { cuid2 } from 'uniku/cuid2'\n *\n * const id = cuid2()\n * // => \"pfh0haxfpzowht3oi213cqos\"\n *\n * // Custom length\n * const shortId = cuid2({ length: 10 })\n * // => \"tz4a98xxat\"\n *\n * // Validation (type guard)\n * const maybeId: unknown = getUserInput()\n * if (cuid2.isValid(maybeId)) {\n * console.log(maybeId.length) // TypeScript knows maybeId is string\n * }\n * ```\n *\n * @deprecated Use `cuidv2` from `uniku/cuid/v2` instead. This entry point keeps\n * working unchanged, but `uniku/cuid/v2` is the canonical versioned subpath\n * (mirroring `uniku/uuid/v4` / `uniku/uuid/v7`).\n */\nexport const cuid2: Cuid2 = Object.assign(cuid2Fn, {\n isValid,\n})\n\nexport { InvalidInputError, UniqueIdError } from '../errors'\n"],"mappings":"iKA0BA,MASM,EAAc,mBAGd,EAAW,uCAIX,EAAc,IAAI,YAOlB,EAA0E,CAC9E,QAAS,IAAA,GACT,YAAa,IAAA,EACf,EAKA,SAAS,GAA4B,CACnC,OAAO,EAAa,EAAK,SAC3B,CAIA,SAAS,EAAY,EAAyB,CAC5C,IAAI,EAAQ,GACZ,IAAK,IAAM,KAAQ,EACjB,EAAQ,EAAQ,KAAO,OAAO,CAAI,EAEpC,OAAO,CACT,CAEA,SAAS,EAAe,EAAuB,CAC7C,GAAI,IAAU,GAAI,MAAO,IACzB,IAAM,EAAkB,CAAC,EACzB,KAAO,EAAQ,IACb,EAAM,KAAK,EAAS,OAAO,EAAQ,GAAG,EAAE,EACxC,GAAgB,IAElB,OAAO,EAAM,QAAQ,CAAC,CAAC,KAAK,EAAE,CAChC,CAEA,SAAS,EAAa,EAA8B,CAClD,MAAO,6BAAgB,KAAK,MAAM,EAAO,EAAI,EAAE,EACjD,CAEA,SAAS,EAAc,EAAgB,EAA8B,CACnE,IAAM,EAAY,MAAc,CAAM,EACtC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAQ,IAC1B,EAAM,GAAK,EAAS,KAAK,MAAM,EAAO,EAAI,EAAE,GAE9C,OAAO,EAAM,KAAK,EAAE,CACtB,CAIA,SAAS,EAAK,EAA2B,CACvC,OAAO,EAAS,EAAY,OAAO,CAAK,CAAC,CAC3C,CAMA,SAAS,GAA4B,CAEnC,IAAM,EAAS,EAIf,OAAO,EAAe,EADP,EAFC,OAAO,KAAK,UAAU,CAAC,CAAC,SACb,EAAI,EAAc,GAAY,CAAM,CAExB,CAAC,CAAC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mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/errors.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The canonical, ordered list of machine-readable error codes emitted by
|
|
6
|
+
* uniku's public API.
|
|
7
|
+
*
|
|
8
|
+
* Codes describe the failure independently of an ID format. Use an error's
|
|
9
|
+
* `strategy` field when the generator that raised it matters.
|
|
10
|
+
*/
|
|
11
|
+
declare const ERROR_CODES: readonly ["TIMESTAMP_OUT_OF_RANGE", "CONFLICTING_OPTIONS", "COUNTER_OUT_OF_RANGE", "NODE_OUT_OF_RANGE", "NODE_BITS_OUT_OF_RANGE", "EPOCH_INVALID", "PROCESS_ID_OUT_OF_RANGE", "MACHINE_ID_BYTES_TOO_SHORT", "RANDOM_BYTES_TOO_SHORT", "RANDOM_OVERFLOW", "LENGTH_OUT_OF_RANGE", "ALPHABET_OUT_OF_RANGE", "ALPHABET_INVALID_CHAR", "ALPHABET_DUPLICATE", "PREFIX_TOO_LONG", "PREFIX_INVALID_CHAR", "PREFIX_INVALID_BOUNDARY", "UUID_NOT_V7", "BYTES_INVALID_LENGTH", "BUFFER_OUT_OF_BOUNDS", "INVALID_CHAR", "INVALID_LENGTH", "INVALID_FORMAT", "NON_CANONICAL", "VALUE_OUT_OF_RANGE"];
|
|
12
|
+
/**
|
|
13
|
+
* A machine-readable error code emitted by uniku, derived from
|
|
14
|
+
* {@link ERROR_CODES}.
|
|
15
|
+
*/
|
|
16
|
+
type ErrorCode = (typeof ERROR_CODES)[number];
|
|
17
|
+
/**
|
|
18
|
+
* Extra context carried by every uniku error.
|
|
19
|
+
*/
|
|
20
|
+
type UniqueIdErrorOptions = {
|
|
21
|
+
/**
|
|
22
|
+
* The ID strategy whose public boundary raised the error.
|
|
23
|
+
* Error codes are strategy-agnostic (e.g. `TIMESTAMP_OUT_OF_RANGE`), so this
|
|
24
|
+
* field attributes the failure to the generator that produced it.
|
|
25
|
+
*/
|
|
26
|
+
readonly strategy?: IdGenerator;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Base error for all uniku errors.
|
|
30
|
+
* Provides `_tag` for discriminated matching (compatible with Effect's `catchTag`),
|
|
31
|
+
* `code` for machine-readable error identification, and `strategy` to attribute
|
|
32
|
+
* unified codes to the ID generator that raised them.
|
|
33
|
+
*/
|
|
34
|
+
declare abstract class UniqueIdError extends Error {
|
|
35
|
+
abstract readonly _tag: string;
|
|
36
|
+
abstract readonly code: ErrorCode;
|
|
37
|
+
/** The ID strategy whose public boundary raised the error. */
|
|
38
|
+
readonly strategy?: IdGenerator;
|
|
39
|
+
constructor(message: string, options?: UniqueIdErrorOptions);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Thrown when generator arguments are invalid (bad size, alphabet, length, timestamp, version).
|
|
43
|
+
*/
|
|
44
|
+
declare class InvalidInputError extends UniqueIdError {
|
|
45
|
+
readonly code: ErrorCode;
|
|
46
|
+
readonly _tag = "InvalidInputError";
|
|
47
|
+
constructor(code: ErrorCode, message: string, options?: UniqueIdErrorOptions);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Thrown when parsing/decoding an ID string that has invalid format or characters.
|
|
51
|
+
*/
|
|
52
|
+
declare class ParseError extends UniqueIdError {
|
|
53
|
+
readonly code: ErrorCode;
|
|
54
|
+
readonly _tag = "ParseError";
|
|
55
|
+
constructor(code: ErrorCode, message: string, options?: UniqueIdErrorOptions);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Thrown when a byte array or buffer is too short or an offset is out of bounds.
|
|
59
|
+
*/
|
|
60
|
+
declare class BufferError extends UniqueIdError {
|
|
61
|
+
readonly code: ErrorCode;
|
|
62
|
+
readonly _tag = "BufferError";
|
|
63
|
+
constructor(code: ErrorCode, message: string, options?: UniqueIdErrorOptions);
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
export { ParseError as a, InvalidInputError as i, ERROR_CODES as n, UniqueIdError as o, ErrorCode as r, UniqueIdErrorOptions as s, BufferError as t };
|
|
67
|
+
//# sourceMappingURL=errors-Da-8dh4J.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-Da-8dh4J.d.mts","names":[],"sources":["../src/errors.ts"],"mappings":";;;;;AAWA;;;;AAyBE;cAzBW,WAAA;;;;AAgCmB;KAApB,SAAA,WAAoB,WAAA;;;;KAKpB,oBAAA;EAeZ;;;;;EAAA,SATW,QAAA,GAAW,WAAA;AAAA;;;;;;;uBASA,aAAA,SAAsB,KAAA;EAAA,kBACxB,IAAA;EAAA,kBACA,IAAA,EAAM,SAAA;;WAGf,QAAA,GAAW,WAAA;EAEpB,WAAA,CAAY,OAAA,UAAiB,OAAA,GAAU,oBAAA;AAAA;AAAA;AAUzC;;AAVyC,cAU5B,iBAAA,SAA0B,aAAA;EAAA,SAInC,IAAA,EAAe,SAAA;EAAA,SAHR,IAAA;EAET,WAAA,CACE,IAAA,EAAe,SAAA,EACf,OAAA,UACA,OAAA,GAAU,oBAAA;AAAA;;;;cASD,UAAA,SAAmB,aAAA;EAAA,SAI5B,IAAA,EAAe,SAAA;EAAA,SAHR,IAAA;EAET,WAAA,CACE,IAAA,EAAe,SAAA,EACf,OAAA,UACA,OAAA,GAAU,oBAAA;AAAA;;;;cASD,WAAA,SAAoB,aAAA;EAAA,SAI7B,IAAA,EAAe,SAAA;EAAA,SAHR,IAAA;EAET,WAAA,CACE,IAAA,EAAe,SAAA,EACf,OAAA,UACA,OAAA,GAAU,oBAAA;AAAA"}
|
package/build/errors.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as
|
|
2
|
-
export { BufferError, InvalidInputError, ParseError, UniqueIdError };
|
|
1
|
+
import { a as ParseError, i as InvalidInputError, n as ERROR_CODES, o as UniqueIdError, r as ErrorCode, s as UniqueIdErrorOptions, t as BufferError } from "./errors-Da-8dh4J.mjs";
|
|
2
|
+
export { BufferError, ERROR_CODES, ErrorCode, InvalidInputError, ParseError, UniqueIdError, UniqueIdErrorOptions };
|
package/build/errors.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
const e=[`TIMESTAMP_OUT_OF_RANGE`,`CONFLICTING_OPTIONS`,`COUNTER_OUT_OF_RANGE`,`NODE_OUT_OF_RANGE`,`NODE_BITS_OUT_OF_RANGE`,`EPOCH_INVALID`,`PROCESS_ID_OUT_OF_RANGE`,`MACHINE_ID_BYTES_TOO_SHORT`,`RANDOM_BYTES_TOO_SHORT`,`RANDOM_OVERFLOW`,`LENGTH_OUT_OF_RANGE`,`ALPHABET_OUT_OF_RANGE`,`ALPHABET_INVALID_CHAR`,`ALPHABET_DUPLICATE`,`PREFIX_TOO_LONG`,`PREFIX_INVALID_CHAR`,`PREFIX_INVALID_BOUNDARY`,`UUID_NOT_V7`,`BYTES_INVALID_LENGTH`,`BUFFER_OUT_OF_BOUNDS`,`INVALID_CHAR`,`INVALID_LENGTH`,`INVALID_FORMAT`,`NON_CANONICAL`,`VALUE_OUT_OF_RANGE`];var t=class extends Error{strategy;constructor(e,t){super(e),this.name=this.constructor.name,this.strategy=t?.strategy}},n=class extends t{code;_tag=`InvalidInputError`;constructor(e,t,n){super(t,n),this.code=e}},r=class extends t{code;_tag=`ParseError`;constructor(e,t,n){super(t,n),this.code=e}},i=class extends t{code;_tag=`BufferError`;constructor(e,t,n){super(t,n),this.code=e}};export{i as BufferError,e as ERROR_CODES,n as InvalidInputError,r as ParseError,t as UniqueIdError};
|
|
2
2
|
//# sourceMappingURL=errors.mjs.map
|
package/build/errors.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base error for all uniku errors.\n * Provides `_tag` for discriminated matching (compatible with Effect's `catchTag`)
|
|
1
|
+
{"version":3,"file":"errors.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import type { IdGenerator } from './generators'\n\n/**\n * The canonical, ordered list of machine-readable error codes emitted by\n * uniku's public API.\n *\n * Codes describe the failure independently of an ID format. Use an error's\n * `strategy` field when the generator that raised it matters.\n */\n// Plain `as const` keeps declaration emit compatible with\n// `isolatedDeclarations`; every member is already a string literal.\nexport const ERROR_CODES = [\n 'TIMESTAMP_OUT_OF_RANGE',\n 'CONFLICTING_OPTIONS',\n 'COUNTER_OUT_OF_RANGE',\n 'NODE_OUT_OF_RANGE',\n 'NODE_BITS_OUT_OF_RANGE',\n 'EPOCH_INVALID',\n 'PROCESS_ID_OUT_OF_RANGE',\n 'MACHINE_ID_BYTES_TOO_SHORT',\n 'RANDOM_BYTES_TOO_SHORT',\n 'RANDOM_OVERFLOW',\n 'LENGTH_OUT_OF_RANGE',\n 'ALPHABET_OUT_OF_RANGE',\n 'ALPHABET_INVALID_CHAR',\n 'ALPHABET_DUPLICATE',\n 'PREFIX_TOO_LONG',\n 'PREFIX_INVALID_CHAR',\n 'PREFIX_INVALID_BOUNDARY',\n 'UUID_NOT_V7',\n 'BYTES_INVALID_LENGTH',\n 'BUFFER_OUT_OF_BOUNDS',\n 'INVALID_CHAR',\n 'INVALID_LENGTH',\n 'INVALID_FORMAT',\n 'NON_CANONICAL',\n 'VALUE_OUT_OF_RANGE',\n] as const\n\n/**\n * A machine-readable error code emitted by uniku, derived from\n * {@link ERROR_CODES}.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[number]\n\n/**\n * Extra context carried by every uniku error.\n */\nexport type UniqueIdErrorOptions = {\n /**\n * The ID strategy whose public boundary raised the error.\n * Error codes are strategy-agnostic (e.g. `TIMESTAMP_OUT_OF_RANGE`), so this\n * field attributes the failure to the generator that produced it.\n */\n readonly strategy?: IdGenerator\n}\n\n/**\n * Base error for all uniku errors.\n * Provides `_tag` for discriminated matching (compatible with Effect's `catchTag`),\n * `code` for machine-readable error identification, and `strategy` to attribute\n * unified codes to the ID generator that raised them.\n */\nexport abstract class UniqueIdError extends Error {\n abstract readonly _tag: string\n abstract readonly code: ErrorCode\n\n /** The ID strategy whose public boundary raised the error. */\n readonly strategy?: IdGenerator\n\n constructor(message: string, options?: UniqueIdErrorOptions) {\n super(message)\n this.name = this.constructor.name\n this.strategy = options?.strategy\n }\n}\n\n/**\n * Thrown when generator arguments are invalid (bad size, alphabet, length, timestamp, version).\n */\nexport class InvalidInputError extends UniqueIdError {\n readonly _tag = 'InvalidInputError' as const\n\n constructor(\n readonly code: ErrorCode,\n message: string,\n options?: UniqueIdErrorOptions,\n ) {\n super(message, options)\n }\n}\n\n/**\n * Thrown when parsing/decoding an ID string that has invalid format or characters.\n */\nexport class ParseError extends UniqueIdError {\n readonly _tag = 'ParseError' as const\n\n constructor(\n readonly code: ErrorCode,\n message: string,\n options?: UniqueIdErrorOptions,\n ) {\n super(message, options)\n }\n}\n\n/**\n * Thrown when a byte array or buffer is too short or an offset is out of bounds.\n */\nexport class BufferError extends UniqueIdError {\n readonly _tag = 'BufferError' as const\n\n constructor(\n readonly code: ErrorCode,\n message: string,\n options?: UniqueIdErrorOptions,\n ) {\n super(message, options)\n }\n}\n"],"mappings":"AAWA,MAAa,EAAc,CACzB,yBACA,sBACA,uBACA,oBACA,yBACA,gBACA,0BACA,6BACA,yBACA,kBACA,sBACA,wBACA,wBACA,qBACA,kBACA,sBACA,0BACA,cACA,uBACA,uBACA,eACA,iBACA,iBACA,gBACA,oBACF,EA0BA,IAAsB,EAAtB,cAA4C,KAAM,CAKhD,SAEA,YAAY,EAAiB,EAAgC,CAC3D,MAAM,CAAO,EACb,KAAK,KAAO,KAAK,YAAY,KAC7B,KAAK,SAAW,GAAS,QAC3B,CACF,EAKa,EAAb,cAAuC,CAAc,CAIxC,KAHX,KAAgB,oBAEhB,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,CAAO,EAJb,KAAA,KAAA,CAKX,CACF,EAKa,EAAb,cAAgC,CAAc,CAIjC,KAHX,KAAgB,aAEhB,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,CAAO,EAJb,KAAA,KAAA,CAKX,CACF,EAKa,EAAb,cAAiC,CAAc,CAIlC,KAHX,KAAgB,cAEhB,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,CAAO,EAJb,KAAA,KAAA,CAKX,CACF"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
//#region src/generators.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The canonical, ordered list of ID generators supported by uniku.
|
|
4
|
+
*
|
|
5
|
+
* This is the single source of truth for the set of supported ID generators.
|
|
6
|
+
* Tools that need to enumerate or validate ID generators (for example,
|
|
7
|
+
* `@uniku/cli`'s `--type` flag) should derive from this array rather than
|
|
8
|
+
* hand-copying the union.
|
|
9
|
+
*/
|
|
10
|
+
declare const ID_GENERATORS: readonly ["uuid", "ulid", "typeid", "nanoid", "cuid", "ksuid", "objectid", "tsid", "xid"];
|
|
11
|
+
/**
|
|
12
|
+
* The union of ID generators supported by uniku, derived from {@link ID_GENERATORS}.
|
|
13
|
+
*/
|
|
14
|
+
type IdGenerator = (typeof ID_GENERATORS)[number];
|
|
15
|
+
//#endregion
|
|
16
|
+
export { IdGenerator as n, ID_GENERATORS as t };
|
|
17
|
+
//# sourceMappingURL=generators-BfJLt7Qf.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generators-BfJLt7Qf.d.mts","names":[],"sources":["../src/generators.ts"],"mappings":";;AAWA;;;;AAAuG;AAKvG;;cALa,aAAA;;AAKqB;;KAAtB,WAAA,WAAsB,aAAA"}
|
package/build/generators.d.mts
CHANGED
|
@@ -1,17 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* The canonical, ordered list of ID generators supported by uniku.
|
|
4
|
-
*
|
|
5
|
-
* This is the single source of truth for the set of supported ID generators.
|
|
6
|
-
* Tools that need to enumerate or validate ID generators (for example,
|
|
7
|
-
* `@uniku/cli`'s `--type` flag) should derive from this array rather than
|
|
8
|
-
* hand-copying the union.
|
|
9
|
-
*/
|
|
10
|
-
declare const ID_GENERATORS: readonly ["uuid", "ulid", "typeid", "nanoid", "cuid", "ksuid", "objectid", "tsid", "xid"];
|
|
11
|
-
/**
|
|
12
|
-
* The union of ID generators supported by uniku, derived from {@link ID_GENERATORS}.
|
|
13
|
-
*/
|
|
14
|
-
type IdGenerator = (typeof ID_GENERATORS)[number];
|
|
15
|
-
//#endregion
|
|
16
|
-
export { ID_GENERATORS, IdGenerator };
|
|
17
|
-
//# sourceMappingURL=generators.d.mts.map
|
|
1
|
+
import { n as IdGenerator, t as ID_GENERATORS } from "./generators-BfJLt7Qf.mjs";
|
|
2
|
+
export { ID_GENERATORS, IdGenerator };
|
package/build/ksuid/ksuid.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as ParseError, i as InvalidInputError, o as UniqueIdError, t as BufferError } from "../errors-Da-8dh4J.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/ksuid/ksuid.d.ts
|
|
4
4
|
type KsuidOptions = {
|
|
@@ -7,9 +7,15 @@ type KsuidOptions = {
|
|
|
7
7
|
*/
|
|
8
8
|
random?: Uint8Array;
|
|
9
9
|
/**
|
|
10
|
-
* Timestamp in
|
|
11
|
-
* Defaults to
|
|
12
|
-
* KSUID
|
|
10
|
+
* Timestamp in milliseconds since the Unix epoch.
|
|
11
|
+
* Defaults to Date.now().
|
|
12
|
+
* KSUID stores whole seconds, so sub-second precision is truncated.
|
|
13
|
+
*/
|
|
14
|
+
msecs?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Timestamp in seconds since the Unix epoch.
|
|
17
|
+
*
|
|
18
|
+
* @deprecated Use `msecs` instead. Will be removed at v1-rc.
|
|
13
19
|
*/
|
|
14
20
|
secs?: number;
|
|
15
21
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ksuid.d.mts","names":[],"sources":["../../src/ksuid/ksuid.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"ksuid.d.mts","names":[],"sources":["../../src/ksuid/ksuid.ts"],"mappings":";;;KAkCY,YAAA;;;AAAZ;EAIE,MAAA,GAAS,UAAA;;;;;;EAMT,KAAA;EAOA;AAAA;AAGF;;;EAHE,IAAA;AAAA;AAAA,KAGU,KAAA;;gBAII,UAAA,GAAa,UAAA,EAAY,OAAA,EAAS,YAAA,cAA0B,GAAA,EAAK,IAAA,EAAM,MAAA,YAAkB,IAAA;GAEtG,OAAA,GAAU,YAAA,EAAc,GAAA,cAAiB,MAAA,oBAIzB;EAFjB,OAAA,CAAQ,EAAA,WAAa,UAAA;EAErB,SAAA,CAAU,KAAA,EAAO,UAAA;EAEjB,SAAA,CAAU,EAAA;EAEV,OAAA,CAAQ,EAAA,YAAc,EAAA;EAEtB,GAAA;EAEA,GAAA;AAAA;;;;;cA8HW,KAAA,EAAO,KAAA"}
|
package/build/ksuid/ksuid.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"../random-Chp-Nkzi.mjs";import{n as t}from"../validation-CTNpXm94.mjs";import{BufferError as n,InvalidInputError as r,ParseError as i,UniqueIdError as a}from"../errors.mjs";import{n as o}from"../bytes-xqWxFYsM.mjs";const
|
|
1
|
+
import{r as e}from"../random-Chp-Nkzi.mjs";import{n as t}from"../validation-CTNpXm94.mjs";import{BufferError as n,InvalidInputError as r,ParseError as i,UniqueIdError as a}from"../errors.mjs";import{n as o}from"../bytes-xqWxFYsM.mjs";import{t as s}from"../timestamp-ChrSuQCR.mjs";const c=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,l=62n,u=(1n<<160n)-1n,d=new Uint8Array(65536);d.fill(255);for(let e=0;e<62;e+=1)d[c.charCodeAt(e)]=e;function f(e){if(e.length<20)throw new n(`BYTES_INVALID_LENGTH`,`KSUID bytes must be at least 20 bytes, got ${e.length}`,{strategy:`ksuid`});let t=0n;for(let n=0;n<20;n+=1)t=t<<8n|BigInt(e[n]);let r=``;for(;t>0n;){let e=t%l;t/=l,r=c[Number(e)]+r}return r.padStart(27,`0`)}function p(e){if(e.length!==27)throw new i(`INVALID_LENGTH`,`KSUID string must be 27 characters, got ${e.length}`,{strategy:`ksuid`});let t=0n;for(let n=0;n<27;n+=1){let r=d[e.charCodeAt(n)];if(r===255)throw new i(`INVALID_CHAR`,`Invalid KSUID character: ${e[n]}`,{strategy:`ksuid`});t=t*l+BigInt(r)}if(t>u)throw new i(`VALUE_OUT_OF_RANGE`,`KSUID string exceeds 160-bit range`,{strategy:`ksuid`});let n=new Uint8Array(20);for(let e=19;e>=0;--e)n[e]=Number(t&255n),t>>=8n;return n}const m=14e8,h=f(new Uint8Array(20).fill(255)),g=/^[0-9A-Za-z]{27}$/;function _(e,t,n,r){o(n,r,e);for(let e=0;e<16;e+=1)n[r+4+e]=t[e]}function v(i,a,o=0){let c=i?.random;if(c&&c.length<16)throw new r(`RANDOM_BYTES_TOO_SHORT`,`Random bytes length must be >= 16 for KSUID`,{strategy:`ksuid`});let l,u=i===void 0?void 0:s(i,m,5694967295,`ksuid`);l=u===void 0?Math.floor(Date.now()/1e3)-m:u-m;let d=c??e();if(a){if(!t(a,o,20))throw new n(`BUFFER_OUT_OF_BOUNDS`,`KSUID byte range ${o}:${o+20-1} is out of buffer bounds`,{strategy:`ksuid`});return _(l,d,a,o),a}let p=new Uint8Array(20);return _(l,d,p,0),f(p)}function y(e){return p(e)}function b(e){if(e.length!==20)throw new n(`BYTES_INVALID_LENGTH`,`KSUID bytes must be exactly 20 bytes, got ${e.length}`,{strategy:`ksuid`});return f(e)}function x(e){let t=p(e);return(((t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0)+m)*1e3}function S(e){return typeof e==`string`&&e.length===27&&g.test(e)&&e<=h}const C=Object.assign(v,{toBytes:y,fromBytes:b,timestamp:x,isValid:S,NIL:`000000000000000000000000000`,MAX:h});export{n as BufferError,r as InvalidInputError,i as ParseError,a as UniqueIdError,C as ksuid};
|
|
2
2
|
//# sourceMappingURL=ksuid.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ksuid.mjs","names":["KSUID_BYTES","KSUID_STRING_LEN"],"sources":["../../src/ksuid/base62.ts","../../src/ksuid/ksuid.ts"],"sourcesContent":["import { BufferError, ParseError } from '../errors'\n\n/**\n * Base62 encoding/decoding for KSUID.\n * Alphabet: 0-9A-Za-z (standard Base62 ordering)\n *\n * KSUID binary format: 20 bytes (160 bits)\n * - 4 bytes: timestamp (seconds since KSUID epoch)\n * - 16 bytes: payload (cryptographically random)\n *\n * String format: 27 characters of Base62\n */\n\n// Base62 alphabet: digits (0-9), uppercase (A-Z), lowercase (a-z)\nconst BASE62_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\nconst BASE = 62n\nconst MAX_KSUID_VALUE = (1n << 160n) - 1n\nconst KSUID_BYTES = 20\nconst KSUID_STRING_LEN = 27\n\n// Pre-computed decode table covering every UTF-16 code unit charCodeAt can\n// return, so lookups never go out of bounds and a single `=== 255` check\n// rejects invalid input (including non-ASCII) without a per-character range\n// check. Costs 64 KiB once at module load; valid inputs only touch the first\n// 128 bytes, so cache behavior is unaffected.\n// Note: Base62 is case-sensitive - 'A' (value 10) and 'a' (value 36) are different\nconst DECODING = new Uint8Array(65536)\nDECODING.fill(255) // 255 = invalid marker\n\nfor (let i = 0; i < BASE62_ALPHABET.length; i += 1) {\n DECODING[BASE62_ALPHABET.charCodeAt(i)] = i\n}\n\n/**\n * Encode a 20-byte KSUID to a 27-character Base62 string.\n *\n * Algorithm: Convert the 160-bit number to base 62 using BigInt.\n * V8 has highly optimized BigInt operations for this size.\n */\nexport function encodeBase62(bytes: Uint8Array): string {\n if (bytes.length < KSUID_BYTES) {\n throw new BufferError(\n 'KSUID_BYTES_TOO_SHORT',\n `KSUID bytes must be at least ${KSUID_BYTES} bytes, got ${bytes.length}`,\n )\n }\n\n // Convert bytes to BigInt (big-endian)\n let num = 0n\n for (let i = 0; i < KSUID_BYTES; i += 1) {\n num = (num << 8n) | BigInt(bytes[i])\n }\n\n // Convert to Base62 string (build from right to left)\n // Direct string concatenation is faster than array + join in V8\n let encoded = ''\n while (num > 0n) {\n const remainder = num % BASE\n num = num / BASE\n encoded = BASE62_ALPHABET[Number(remainder)] + encoded\n }\n\n // Pad the result with the zero-character ('0') to ensure a fixed length\n return encoded.padStart(KSUID_STRING_LEN, '0')\n}\n\n/**\n * Decode a 27-character Base62 string to a 20-byte KSUID.\n *\n * Algorithm: Convert Base62 string to BigInt, then to bytes.\n * V8 has highly optimized BigInt operations.\n */\nexport function decodeBase62(str: string): Uint8Array {\n if (str.length !== KSUID_STRING_LEN) {\n throw new ParseError(\n 'KSUID_INVALID_LENGTH',\n `KSUID string must be ${KSUID_STRING_LEN} characters, got ${str.length}`,\n )\n }\n\n // Convert Base62 string to BigInt\n let num = 0n\n for (let i = 0; i < KSUID_STRING_LEN; i += 1) {\n const value = DECODING[str.charCodeAt(i)]\n if (value === 255) {\n throw new ParseError('KSUID_INVALID_CHAR', `Invalid KSUID character: ${str[i]}`)\n }\n num = num * BASE + BigInt(value)\n }\n\n if (num > MAX_KSUID_VALUE) {\n throw new ParseError('KSUID_OVERFLOW', 'KSUID string exceeds 160-bit range')\n }\n\n // Convert BigInt to bytes (big-endian)\n const bytes = new Uint8Array(KSUID_BYTES)\n for (let i = KSUID_BYTES - 1; i >= 0; i -= 1) {\n bytes[i] = Number(num & 0xffn)\n num = num >> 8n\n }\n\n return bytes\n}\n","import { writeTimestamp32 } from '../common/bytes'\nimport { rng } from '../common/random'\nimport { isWritableRange } from '../common/validation'\nimport { BufferError, InvalidInputError } from '../errors'\nimport { decodeBase62, encodeBase62 } from './base62'\n\n/**\n * KSUID (K-Sortable Unique Identifier)\n *\n * A 160-bit identifier consisting of:\n * - 4 bytes: timestamp (seconds since KSUID epoch: May 13, 2014)\n * - 16 bytes: cryptographically random payload\n *\n * Encoded as a 27-character Base62 string.\n */\n\n// KSUID epoch: May 13, 2014 00:00:00 UTC (Unix timestamp in seconds)\nconst KSUID_EPOCH = 1400000000\n\nconst KSUID_BYTES = 20\nconst KSUID_STRING_LEN = 27\nconst TIMESTAMP_BYTES = 4\nconst PAYLOAD_BYTES = 16\nconst KSUID_MAX_SECS = KSUID_EPOCH + 0xffffffff\n// 2^160 - 1 in Base62 ('aWgEPTl1tmebfsQzFP4bxwgy80V'), derived from the\n// encoder so it cannot drift from the decoder's 160-bit overflow bound.\nconst KSUID_MAX_STRING = encodeBase62(new Uint8Array(KSUID_BYTES).fill(0xff))\n\n// Validation regex: 27 alphanumeric characters\n// Note: Both cases are valid Base62 characters, but they decode to different values\n// (e.g., 'A' = 10, 'a' = 36). The regex validates format, not semantic equivalence.\nconst KSUID_REGEX = /^[0-9A-Za-z]{27}$/\n\nexport type KsuidOptions = {\n /**\n * 16 bytes of random data to use for KSUID payload.\n */\n random?: Uint8Array\n /**\n * Timestamp in seconds since Unix epoch.\n * Defaults to Math.floor(Date.now() / 1000).\n * KSUID natively uses second precision.\n */\n secs?: number\n}\n\nexport type Ksuid = {\n /** Generate a time-ordered KSUID string. */\n (): string\n /** Generate a KSUID with explicit options or write its 20 canonical bytes into a caller-owned buffer. */\n <TBuf extends Uint8Array = Uint8Array>(options: KsuidOptions | undefined, buf: TBuf, offset?: number): TBuf\n /** Generate a KSUID string with optional timestamp or random payload bytes. */\n (options?: KsuidOptions, buf?: undefined, offset?: number): string\n /** Convert a KSUID string to its canonical 20-byte representation. */\n toBytes(id: string): Uint8Array\n /** Convert 20 canonical KSUID bytes to a KSUID string. */\n fromBytes(bytes: Uint8Array): string\n /** Read the embedded Unix timestamp in milliseconds. */\n timestamp(id: string): number\n /** Return whether a value is a syntactically valid KSUID string. */\n isValid(id: unknown): id is string\n /** The nil KSUID (all zeros) */\n NIL: string\n /** The max KSUID (maximum valid value) */\n MAX: string\n}\n\n/**\n * Write already-validated KSUID fields to a buffer.\n */\nfunction writeKsuidBytesUnchecked(timestamp: number, payload: Uint8Array, buf: Uint8Array, offset: number): void {\n // Timestamp (32-bit big-endian seconds since KSUID epoch) -> bytes 0-3\n writeTimestamp32(buf, offset, timestamp)\n\n // Payload (128 bits) -> bytes 4-19\n for (let i = 0; i < PAYLOAD_BYTES; i += 1) {\n buf[offset + TIMESTAMP_BYTES + i] = payload[i]\n }\n}\n\n/*\n * Overload: no buffer => return a KSUID string.\n */\nfunction ksuidFn(options?: KsuidOptions, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with KSUID bytes.\n */\nfunction ksuidFn<TBuf extends Uint8Array = Uint8Array>(\n options: KsuidOptions | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction ksuidFn<TBuf extends Uint8Array = Uint8Array>(options?: KsuidOptions, buf?: TBuf, offset = 0): string | TBuf {\n const random = options?.random\n if (random && random.length < PAYLOAD_BYTES) {\n throw new InvalidInputError('KSUID_RANDOM_BYTES_TOO_SHORT', 'Random bytes length must be >= 16 for KSUID')\n }\n\n let timestamp: number\n const secs = options?.secs\n if (secs !== undefined) {\n if (!Number.isInteger(secs) || secs < KSUID_EPOCH) {\n throw new InvalidInputError('KSUID_TIMESTAMP_TOO_LOW', 'Timestamp must be >= KSUID epoch')\n }\n\n if (secs > KSUID_MAX_SECS) {\n throw new InvalidInputError('KSUID_TIMESTAMP_TOO_HIGH', 'Timestamp must be <= maximum KSUID timestamp')\n }\n\n timestamp = secs - KSUID_EPOCH\n } else {\n /**\n * Note: by default, Cloudflare Workers \"freezes\" time during request handling to prevent\n * side-channel attacks. This means that Date.now() will return the same value for the entire\n * duration of a request.\n * Implications:\n * - all KSUIDs generated within a single request will have the same timestamp.\n */\n timestamp = Math.floor(Date.now() / 1000) - KSUID_EPOCH\n }\n\n const payload = random ?? rng()\n\n if (buf) {\n if (!isWritableRange(buf, offset, KSUID_BYTES)) {\n throw new BufferError(\n 'KSUID_BUFFER_OUT_OF_BOUNDS',\n `KSUID byte range ${offset}:${offset + KSUID_BYTES - 1} is out of buffer bounds`,\n )\n }\n writeKsuidBytesUnchecked(timestamp, payload, buf, offset)\n return buf\n }\n\n const bytes = new Uint8Array(KSUID_BYTES)\n writeKsuidBytesUnchecked(timestamp, payload, bytes, 0)\n\n // String mode: create bytes then encode to Base62\n return encodeBase62(bytes)\n}\n\n/**\n * Convert a KSUID string to 20 bytes.\n *\n * Note: Base62 is case-sensitive. 'A' (value 10) and 'a' (value 36) decode\n * to different byte values. This function accepts both cases as valid input.\n */\nfunction toBytes(id: string): Uint8Array {\n return decodeBase62(id)\n}\n\n/**\n * Convert 20 bytes to a KSUID string.\n */\nfunction fromBytes(bytes: Uint8Array): string {\n if (bytes.length !== KSUID_BYTES) {\n throw new BufferError(\n 'KSUID_BYTES_INVALID_LENGTH',\n `KSUID bytes must be exactly ${KSUID_BYTES} bytes, got ${bytes.length}`,\n )\n }\n return encodeBase62(bytes)\n}\n\n/**\n * Extract the timestamp from a KSUID string.\n * Returns Unix timestamp in milliseconds for API consistency with ulid/uuidv7.\n * Note: KSUID only has second precision, so the returned value will always end in 000.\n */\nfunction timestamp(id: string): number {\n const bytes = decodeBase62(id)\n // First 4 bytes are big-endian timestamp (seconds since KSUID epoch)\n const secs = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0\n // Add KSUID epoch and convert to milliseconds\n return (secs + KSUID_EPOCH) * 1000\n}\n\n/**\n * Validate a KSUID string format and 160-bit numeric range.\n */\nfunction isValid(id: unknown): id is string {\n return (\n typeof id === 'string' &&\n id.length === KSUID_STRING_LEN &&\n KSUID_REGEX.test(id) &&\n // Fixed-length Base62 strings preserve numeric order because the alphabet is ASCII-sorted.\n id <= KSUID_MAX_STRING\n )\n}\n\n/**\n * Generate a KSUID string or write the bytes into a buffer.\n * Also includes helpers to convert to and from byte arrays.\n */\nexport const ksuid: Ksuid = Object.assign(ksuidFn, {\n toBytes,\n fromBytes,\n timestamp,\n isValid,\n NIL: '000000000000000000000000000',\n MAX: KSUID_MAX_STRING,\n})\n\nex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7B,SAFe,EAAM,IAAM,GAAO,EAAM,IAAM,GAAO,EAAM,IAAM,EAAK,EAAM,MAAQ,GAErE,GAAe,GAChC,CAKA,SAAS,EAAQ,EAA2B,CAC1C,OACE,OAAO,GAAO,UACd,EAAG,SAAW,IACd,EAAY,KAAK,CAAE,GAEnB,GAAM,CAEV,CAMA,MAAa,EAAe,OAAO,OAAO,EAAS,CACjD,UACA,YACA,YACA,UACA,IAAK,8BACL,IAAK,CACP,CAAC"}
|
|
1
|
+
{"version":3,"file":"ksuid.mjs","names":["KSUID_BYTES","KSUID_STRING_LEN"],"sources":["../../src/ksuid/base62.ts","../../src/ksuid/ksuid.ts"],"sourcesContent":["import { BufferError, ParseError } from '../errors'\n\n/**\n * Base62 encoding/decoding for KSUID.\n * Alphabet: 0-9A-Za-z (standard Base62 ordering)\n *\n * KSUID binary format: 20 bytes (160 bits)\n * - 4 bytes: timestamp (seconds since KSUID epoch)\n * - 16 bytes: payload (cryptographically random)\n *\n * String format: 27 characters of Base62\n */\n\n// Base62 alphabet: digits (0-9), uppercase (A-Z), lowercase (a-z)\nconst BASE62_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\nconst BASE = 62n\nconst MAX_KSUID_VALUE = (1n << 160n) - 1n\nconst KSUID_BYTES = 20\nconst KSUID_STRING_LEN = 27\n\n// Pre-computed decode table covering every UTF-16 code unit charCodeAt can\n// return, so lookups never go out of bounds and a single `=== 255` check\n// rejects invalid input (including non-ASCII) without a per-character range\n// check. Costs 64 KiB once at module load; valid inputs only touch the first\n// 128 bytes, so cache behavior is unaffected.\n// Note: Base62 is case-sensitive - 'A' (value 10) and 'a' (value 36) are different\nconst DECODING = new Uint8Array(65536)\nDECODING.fill(255) // 255 = invalid marker\n\nfor (let i = 0; i < BASE62_ALPHABET.length; i += 1) {\n DECODING[BASE62_ALPHABET.charCodeAt(i)] = i\n}\n\n/**\n * Encode a 20-byte KSUID to a 27-character Base62 string.\n *\n * Algorithm: Convert the 160-bit number to base 62 using BigInt.\n * V8 has highly optimized BigInt operations for this size.\n */\nexport function encodeBase62(bytes: Uint8Array): string {\n if (bytes.length < KSUID_BYTES) {\n throw new BufferError(\n 'BYTES_INVALID_LENGTH',\n `KSUID bytes must be at least ${KSUID_BYTES} bytes, got ${bytes.length}`,\n { strategy: 'ksuid' },\n )\n }\n\n // Convert bytes to BigInt (big-endian)\n let num = 0n\n for (let i = 0; i < KSUID_BYTES; i += 1) {\n num = (num << 8n) | BigInt(bytes[i])\n }\n\n // Convert to Base62 string (build from right to left)\n // Direct string concatenation is faster than array + join in V8\n let encoded = ''\n while (num > 0n) {\n const remainder = num % BASE\n num = num / BASE\n encoded = BASE62_ALPHABET[Number(remainder)] + encoded\n }\n\n // Pad the result with the zero-character ('0') to ensure a fixed length\n return encoded.padStart(KSUID_STRING_LEN, '0')\n}\n\n/**\n * Decode a 27-character Base62 string to a 20-byte KSUID.\n *\n * Algorithm: Convert Base62 string to BigInt, then to bytes.\n * V8 has highly optimized BigInt operations.\n */\nexport function decodeBase62(str: string): Uint8Array {\n if (str.length !== KSUID_STRING_LEN) {\n throw new ParseError('INVALID_LENGTH', `KSUID string must be ${KSUID_STRING_LEN} characters, got ${str.length}`, {\n strategy: 'ksuid',\n })\n }\n\n // Convert Base62 string to BigInt\n let num = 0n\n for (let i = 0; i < KSUID_STRING_LEN; i += 1) {\n const value = DECODING[str.charCodeAt(i)]\n if (value === 255) {\n throw new ParseError('INVALID_CHAR', `Invalid KSUID character: ${str[i]}`, { strategy: 'ksuid' })\n }\n num = num * BASE + BigInt(value)\n }\n\n if (num > MAX_KSUID_VALUE) {\n throw new ParseError('VALUE_OUT_OF_RANGE', 'KSUID string exceeds 160-bit range', { strategy: 'ksuid' })\n }\n\n // Convert BigInt to bytes (big-endian)\n const bytes = new Uint8Array(KSUID_BYTES)\n for (let i = KSUID_BYTES - 1; i >= 0; i -= 1) {\n bytes[i] = Number(num & 0xffn)\n num = num >> 8n\n }\n\n return bytes\n}\n","import { writeTimestamp32 } from '../common/bytes'\nimport { rng } from '../common/random'\nimport { resolveTimestampSecs } from '../common/timestamp'\nimport { isWritableRange } from '../common/validation'\nimport { BufferError, InvalidInputError } from '../errors'\nimport { decodeBase62, encodeBase62 } from './base62'\n\n/**\n * KSUID (K-Sortable Unique Identifier)\n *\n * A 160-bit identifier consisting of:\n * - 4 bytes: timestamp (seconds since KSUID epoch: May 13, 2014)\n * - 16 bytes: cryptographically random payload\n *\n * Encoded as a 27-character Base62 string.\n */\n\n// KSUID epoch: May 13, 2014 00:00:00 UTC (Unix timestamp in seconds)\nconst KSUID_EPOCH = 1400000000\n\nconst KSUID_BYTES = 20\nconst KSUID_STRING_LEN = 27\nconst TIMESTAMP_BYTES = 4\nconst PAYLOAD_BYTES = 16\nconst KSUID_MAX_SECS = KSUID_EPOCH + 0xffffffff\n// 2^160 - 1 in Base62 ('aWgEPTl1tmebfsQzFP4bxwgy80V'), derived from the\n// encoder so it cannot drift from the decoder's 160-bit overflow bound.\nconst KSUID_MAX_STRING = encodeBase62(new Uint8Array(KSUID_BYTES).fill(0xff))\n\n// Validation regex: 27 alphanumeric characters\n// Note: Both cases are valid Base62 characters, but they decode to different values\n// (e.g., 'A' = 10, 'a' = 36). The regex validates format, not semantic equivalence.\nconst KSUID_REGEX = /^[0-9A-Za-z]{27}$/\n\nexport type KsuidOptions = {\n /**\n * 16 bytes of random data to use for KSUID payload.\n */\n random?: Uint8Array\n /**\n * Timestamp in milliseconds since the Unix epoch.\n * Defaults to Date.now().\n * KSUID stores whole seconds, so sub-second precision is truncated.\n */\n msecs?: number\n /**\n * Timestamp in seconds since the Unix epoch.\n *\n * @deprecated Use `msecs` instead. Will be removed at v1-rc.\n */\n // TODO(v1-rc): remove this alias (tracked in docs/STABILITY.md).\n secs?: number\n}\n\nexport type Ksuid = {\n /** Generate a time-ordered KSUID string. */\n (): string\n /** Generate a KSUID with explicit options or write its 20 canonical bytes into a caller-owned buffer. */\n <TBuf extends Uint8Array = Uint8Array>(options: KsuidOptions | undefined, buf: TBuf, offset?: number): TBuf\n /** Generate a KSUID string with optional timestamp or random payload bytes. */\n (options?: KsuidOptions, buf?: undefined, offset?: number): string\n /** Convert a KSUID string to its canonical 20-byte representation. */\n toBytes(id: string): Uint8Array\n /** Convert 20 canonical KSUID bytes to a KSUID string. */\n fromBytes(bytes: Uint8Array): string\n /** Read the embedded Unix timestamp in milliseconds. */\n timestamp(id: string): number\n /** Return whether a value is a syntactically valid KSUID string. */\n isValid(id: unknown): id is string\n /** The nil KSUID (all zeros) */\n NIL: string\n /** The max KSUID (maximum valid value) */\n MAX: string\n}\n\n/**\n * Write already-validated KSUID fields to a buffer.\n */\nfunction writeKsuidBytesUnchecked(timestamp: number, payload: Uint8Array, buf: Uint8Array, offset: number): void {\n // Timestamp (32-bit big-endian seconds since KSUID epoch) -> bytes 0-3\n writeTimestamp32(buf, offset, timestamp)\n\n // Payload (128 bits) -> bytes 4-19\n for (let i = 0; i < PAYLOAD_BYTES; i += 1) {\n buf[offset + TIMESTAMP_BYTES + i] = payload[i]\n }\n}\n\n/*\n * Overload: no buffer => return a KSUID string.\n */\nfunction ksuidFn(options?: KsuidOptions, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with KSUID bytes.\n */\nfunction ksuidFn<TBuf extends Uint8Array = Uint8Array>(\n options: KsuidOptions | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction ksuidFn<TBuf extends Uint8Array = Uint8Array>(options?: KsuidOptions, buf?: TBuf, offset = 0): string | TBuf {\n const random = options?.random\n if (random && random.length < PAYLOAD_BYTES) {\n throw new InvalidInputError('RANDOM_BYTES_TOO_SHORT', 'Random bytes length must be >= 16 for KSUID', {\n strategy: 'ksuid',\n })\n }\n\n let timestamp: number\n const secs = options === undefined ? undefined : resolveTimestampSecs(options, KSUID_EPOCH, KSUID_MAX_SECS, 'ksuid')\n if (secs !== undefined) {\n timestamp = secs - KSUID_EPOCH\n } else {\n /**\n * Note: by default, Cloudflare Workers \"freezes\" time during request handling to prevent\n * side-channel attacks. This means that Date.now() will return the same value for the entire\n * duration of a request.\n * Implications:\n * - all KSUIDs generated within a single request will have the same timestamp.\n */\n timestamp = Math.floor(Date.now() / 1000) - KSUID_EPOCH\n }\n\n const payload = random ?? rng()\n\n if (buf) {\n if (!isWritableRange(buf, offset, KSUID_BYTES)) {\n throw new BufferError(\n 'BUFFER_OUT_OF_BOUNDS',\n `KSUID byte range ${offset}:${offset + KSUID_BYTES - 1} is out of buffer bounds`,\n { strategy: 'ksuid' },\n )\n }\n writeKsuidBytesUnchecked(timestamp, payload, buf, offset)\n return buf\n }\n\n const bytes = new Uint8Array(KSUID_BYTES)\n writeKsuidBytesUnchecked(timestamp, payload, bytes, 0)\n\n // String mode: create bytes then encode to Base62\n return encodeBase62(bytes)\n}\n\n/**\n * Convert a KSUID string to 20 bytes.\n *\n * Note: Base62 is case-sensitive. 'A' (value 10) and 'a' (value 36) decode\n * to different byte values. This function accepts both cases as valid input.\n */\nfunction toBytes(id: string): Uint8Array {\n return decodeBase62(id)\n}\n\n/**\n * Convert 20 bytes to a KSUID string.\n */\nfunction fromBytes(bytes: Uint8Array): string {\n if (bytes.length !== KSUID_BYTES) {\n throw new BufferError(\n 'BYTES_INVALID_LENGTH',\n `KSUID bytes must be exactly ${KSUID_BYTES} bytes, got ${bytes.length}`,\n { strategy: 'ksuid' },\n )\n }\n return encodeBase62(bytes)\n}\n\n/**\n * Extract the timestamp from a KSUID string.\n * Returns Unix timestamp in milliseconds for API consistency with ulid/uuidv7.\n * Note: KSUID only has second precision, so the returned value will always end in 000.\n */\nfunction timestamp(id: string): number {\n const bytes = decodeBase62(id)\n // First 4 bytes are big-endian timestamp (seconds since KSUID epoch)\n const secs = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0\n // Add KSUID epoch and convert to milliseconds\n return (secs + KSUID_EPOCH) * 1000\n}\n\n/**\n * Validate a KSUID string format and 160-bit numeric range.\n */\nfunction isValid(id: unknown): id is string {\n return (\n typeof id === 'string' &&\n id.length === KSUID_STRING_LEN &&\n KSUID_REGEX.test(id) &&\n // Fixed-length Base62 strings preserve numeric order because the alphabet is ASCII-sorted.\n id <= KSUID_MAX_STRING\n )\n}\n\n/**\n * Generate a KSUID string or write the bytes into a buffer.\n * Also includes helpers to convert to and from byte arrays.\n */\nexport const ksuid: Ksuid = Object.assign(ksuidFn, {\n toBytes,\n fromBytes,\n timestamp,\n isValid,\n NIL: '000000000000000000000000000',\n MAX: KSUID_MAX_STRING,\n})\n\nexport { BufferError, InvalidInputError, ParseError, UniqueIdError } from '../errors'\n"],"mappings":"wRAcA,MAAM,EAAkB,iEAClB,EAAO,IACP,GAAmB,IAAM,MAAQ,GAUjC,EAAW,IAAI,WAAW,KAAK,EACrC,EAAS,KAAK,GAAG,EAEjB,IAAK,IAAI,EAAI,EAAG,EAAI,GAAwB,GAAK,EAC/C,EAAS,EAAgB,WAAW,CAAC,GAAK,EAS5C,SAAgB,EAAa,EAA2B,CACtD,GAAI,EAAM,OAASA,GACjB,MAAM,IAAI,EACR,uBACA,8CAA0D,EAAM,SAChE,CAAE,SAAU,OAAQ,CACtB,EAIF,IAAI,EAAM,GACV,IAAK,IAAI,EAAI,EAAG,EAAIA,GAAa,GAAK,EACpC,EAAO,GAAO,GAAM,OAAO,EAAM,EAAE,EAKrC,IAAI,EAAU,GACd,KAAO,EAAM,IAAI,CACf,IAAM,EAAY,EAAM,EACxB,GAAY,EACZ,EAAU,EAAgB,OAAO,CAAS,GAAK,CACjD,CAGA,OAAO,EAAQ,SAASC,GAAkB,GAAG,CAC/C,CAQA,SAAgB,EAAa,EAAyB,CACpD,GAAI,EAAI,SAAWA,GACjB,MAAM,IAAI,EAAW,iBAAkB,2CAA4D,EAAI,SAAU,CAC/G,SAAU,OACZ,CAAC,EAIH,IAAI,EAAM,GACV,IAAK,IAAI,EAAI,EAAG,EAAIA,GAAkB,GAAK,EAAG,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GF,OADA,EAAyB,EAAW,EAAS,EAAK,CAAM,EACjD,CACT,CAEA,IAAM,EAAQ,IAAI,WAAW,EAAW,EAIxC,OAHA,EAAyB,EAAW,EAAS,EAAO,CAAC,EAG9C,EAAa,CAAK,CAC3B,CAQA,SAAS,EAAQ,EAAwB,CACvC,OAAO,EAAa,CAAE,CACxB,CAKA,SAAS,EAAU,EAA2B,CAC5C,GAAI,EAAM,SAAW,GACnB,MAAM,IAAI,EACR,uBACA,6CAAyD,EAAM,SAC/D,CAAE,SAAU,OAAQ,CACtB,EAEF,OAAO,EAAa,CAAK,CAC3B,CAOA,SAAS,EAAU,EAAoB,CACrC,IAAM,EAAQ,EAAa,CAAE,EAI7B,SAFe,EAAM,IAAM,GAAO,EAAM,IAAM,GAAO,EAAM,IAAM,EAAK,EAAM,MAAQ,GAErE,GAAe,GAChC,CAKA,SAAS,EAAQ,EAA2B,CAC1C,OACE,OAAO,GAAO,UACd,EAAG,SAAW,IACd,EAAY,KAAK,CAAE,GAEnB,GAAM,CAEV,CAMA,MAAa,EAAe,OAAO,OAAO,EAAS,CACjD,UACA,YACA,YACA,UACA,IAAK,8BACL,IAAK,CACP,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as
|
|
1
|
+
import { i as InvalidInputError, o as UniqueIdError } from "../errors-Da-8dh4J.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/nanoid/nanoid.d.ts
|
|
4
4
|
/** Default URL-safe alphabet (64 characters): A-Z, a-z, 0-9, underscore, hyphen */
|
|
@@ -6,8 +6,8 @@ declare const URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx
|
|
|
6
6
|
type NanoidOptions = {
|
|
7
7
|
/**
|
|
8
8
|
* Random bytes for deterministic output (testing).
|
|
9
|
-
* For power-of-2 alphabets (2, 4, 8, 16, 32, 64, 128, 256): exactly `
|
|
10
|
-
* For other alphabets: ~
|
|
9
|
+
* For power-of-2 alphabets (2, 4, 8, 16, 32, 64, 128, 256): exactly `length` bytes needed.
|
|
10
|
+
* For other alphabets: ~length * 2 bytes needed (rejection sampling).
|
|
11
11
|
*/
|
|
12
12
|
random?: Uint8Array;
|
|
13
13
|
/**
|
|
@@ -18,6 +18,12 @@ type NanoidOptions = {
|
|
|
18
18
|
/**
|
|
19
19
|
* Length of generated ID. Default: 21. Maximum: 2048.
|
|
20
20
|
*/
|
|
21
|
+
length?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Length of generated ID.
|
|
24
|
+
*
|
|
25
|
+
* @deprecated Use `length` instead. Will be removed at v1-rc.
|
|
26
|
+
*/
|
|
21
27
|
size?: number;
|
|
22
28
|
};
|
|
23
29
|
type Nanoid = {
|
|
@@ -51,7 +57,7 @@ type Nanoid = {
|
|
|
51
57
|
* // => "V1StGXR8_Z5jdHi6B-myT"
|
|
52
58
|
* ```
|
|
53
59
|
*
|
|
54
|
-
* @example Custom
|
|
60
|
+
* @example Custom length
|
|
55
61
|
* ```ts
|
|
56
62
|
* const shortId = nanoid(10)
|
|
57
63
|
* // => "IRFa-VaY2b"
|
|
@@ -59,7 +65,7 @@ type Nanoid = {
|
|
|
59
65
|
*
|
|
60
66
|
* @example Custom alphabet (hex)
|
|
61
67
|
* ```ts
|
|
62
|
-
* const hexId = nanoid({ alphabet: '0123456789abcdef',
|
|
68
|
+
* const hexId = nanoid({ alphabet: '0123456789abcdef', length: 12 })
|
|
63
69
|
* // => "4f90d13a42bc"
|
|
64
70
|
* ```
|
|
65
71
|
*
|
|
@@ -72,9 +78,9 @@ type Nanoid = {
|
|
|
72
78
|
* }
|
|
73
79
|
* ```
|
|
74
80
|
*
|
|
75
|
-
* @throws {InvalidInputError}
|
|
81
|
+
* @throws {InvalidInputError} Length must be between 0 and 2048
|
|
76
82
|
* @throws {InvalidInputError} Alphabet must contain 2-256 unique printable ASCII characters
|
|
77
|
-
* @throws {InvalidInputError} Insufficient random bytes for requested
|
|
83
|
+
* @throws {InvalidInputError} Insufficient random bytes for requested length
|
|
78
84
|
*/
|
|
79
85
|
declare const nanoid: Nanoid;
|
|
80
86
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nanoid.d.mts","names":[],"sources":["../../src/nanoid/nanoid.ts"],"mappings":";;;;cAGa,YAAA;AAAA,KAqCD,aAAA;EArCZ;;;;AAAa;EA2CX,MAAA,GAAS,UAAA;EANC;;;;EAWV,QAAA;;;;EAIA,IAAA;AAAA;AAAA,KAGU,MAAA;;GAIT,IAAA;
|
|
1
|
+
{"version":3,"file":"nanoid.d.mts","names":[],"sources":["../../src/nanoid/nanoid.ts"],"mappings":";;;;cAGa,YAAA;AAAA,KAqCD,aAAA;EArCZ;;;;AAAa;EA2CX,MAAA,GAAS,UAAA;EANC;;;;EAWV,QAAA;;;;EAIA,MAAA;EAOA;AAGF;;;;EAHE,IAAA;AAAA;AAAA,KAGU,MAAA;;GAIT,IAAA,mBAOqB;EAAA,CALrB,OAAA,EAAS,aAAA;EA8MS;;;AAAA;EAzMnB,OAAA,CAAQ,EAAA,YAAc,EAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAyMX,MAAA,EAAQ,MAAA"}
|
package/build/nanoid/nanoid.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{InvalidInputError as e,UniqueIdError as t}from"../errors.mjs";const n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-`,r=2048,i=/^[A-Za-z0-9_-]+$/,a=new TextDecoder;let o,s=``,c=0;function l(e){let t=Math.min(e*128,65536);if((!o||o.length<t)&&(o=new Uint8Array(t)),c+e>s.length){crypto.getRandomValues(o);for(let e=0;e<o.length;e++)o[e]=n.charCodeAt(o[e]&63);s=a.decode(o),c=0}}function u(e){l(e);let t=s.substring(c,c+e);return c+=e,t}function d(t){if(t.length<2)throw new e(`
|
|
1
|
+
import{InvalidInputError as e,UniqueIdError as t}from"../errors.mjs";const n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-`,r=2048,i=/^[A-Za-z0-9_-]+$/,a=new TextDecoder;let o,s=``,c=0;function l(e){let t=Math.min(e*128,65536);if((!o||o.length<t)&&(o=new Uint8Array(t)),c+e>s.length){crypto.getRandomValues(o);for(let e=0;e<o.length;e++)o[e]=n.charCodeAt(o[e]&63);s=a.decode(o),c=0}}function u(e){l(e);let t=s.substring(c,c+e);return c+=e,t}function d(t){if(t.length<2)throw new e(`ALPHABET_OUT_OF_RANGE`,`Alphabet must contain at least 2 characters`,{strategy:`nanoid`});if(t.length>256)throw new e(`ALPHABET_OUT_OF_RANGE`,`Alphabet must not exceed 256 characters`,{strategy:`nanoid`});let n=new Set;for(let r of t){let t=r.charCodeAt(0);if(t<32||t>126)throw new e(`ALPHABET_INVALID_CHAR`,`Alphabet must contain only printable ASCII characters (32-126)`,{strategy:`nanoid`});if(n.has(r))throw new e(`ALPHABET_DUPLICATE`,`Duplicate character in alphabet: "${r}"`,{strategy:`nanoid`});n.add(r)}}function f(t){if(!Number.isInteger(t)||t<0)throw new e(`LENGTH_OUT_OF_RANGE`,`Length must be a non-negative integer`,{strategy:`nanoid`});if(t>r)throw new e(`LENGTH_OUT_OF_RANGE`,`Length must not exceed ${r}`,{strategy:`nanoid`})}function p(t){if(t===void 0)return u(21);let r=21,i=n,a;if(typeof t==`number`)r=t;else{if(t.length!==void 0&&t.size!==void 0)throw new e(`CONFLICTING_OPTIONS`,"Pass only one of `length` or `size`, not both",{strategy:`nanoid`});r=t.length??t.size??21,i=t.alphabet??`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-`,a=t.random,t.alphabet!==void 0&&d(i)}if(f(r),r===0)return``;if(i===`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-`&&a===void 0)return u(r);let o=i.length;if(!(o&o-1)){let t=o-1;if(a&&a.length<r)throw new e(`RANDOM_BYTES_TOO_SHORT`,`Insufficient random bytes: need ${r}, have ${a.length}`,{strategy:`nanoid`});let n=a?.subarray(0,r)??globalThis.crypto.getRandomValues(new Uint8Array(r)),s=``;for(let e=0;e<r;e++)s+=i[n[e]&t];return s}let s=(2<<31-Math.clz32(o-1|1))-1,c=Math.ceil(1.6*s*r/o),l=``,p=0;for(;l.length<r;){let t;if(a){if(a.length-p<c)throw new e(`RANDOM_BYTES_TOO_SHORT`,`Insufficient random bytes: need at least ${c} more, have ${a.length-p}`,{strategy:`nanoid`});t=a.subarray(p,p+c),p+=c}else t=globalThis.crypto.getRandomValues(new Uint8Array(c));for(let e=0;e<t.length&&l.length<r;e++){let n=t[e]&s;n<o&&(l+=i[n])}}return l}function m(e){return typeof e==`string`&&e.length>0&&i.test(e)}const h=Object.assign(p,{isValid:m});export{e as InvalidInputError,n as URL_ALPHABET,t as UniqueIdError,h as nanoid};
|
|
2
2
|
//# sourceMappingURL=nanoid.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nanoid.mjs","names":[],"sources":["../../src/nanoid/nanoid.ts"],"sourcesContent":["import { InvalidInputError } from '../errors'\n\n/** Default URL-safe alphabet (64 characters): A-Z, a-z, 0-9, underscore, hyphen */\nexport const URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'\n\nconst DEFAULT_SIZE = 21\nconst MAX_SIZE = 2048\nconst NANOID_REGEX = /^[A-Za-z0-9_-]+$/\n\n// Keep Nanoid's private pool for its default hot path. Translate random bytes\n// into URL-safe ASCII once per refill, then serve IDs as sequential substrings.\nconst POOL_SIZE_MULTIPLIER = 128\nconst MAX_POOL_SIZE = 65_536\nconst ASCII_DECODER = new TextDecoder()\nlet poolBytes: Uint8Array | undefined\nlet characterPool = ''\nlet poolOffset = 0\n\nfunction fillPool(bytes: number): void {\n const size = Math.min(bytes * POOL_SIZE_MULTIPLIER, MAX_POOL_SIZE)\n if (!poolBytes || poolBytes.length < size) {\n poolBytes = new Uint8Array(size)\n }\n if (poolOffset + bytes > characterPool.length) {\n crypto.getRandomValues(poolBytes)\n for (let i = 0; i < poolBytes.length; i++) {\n poolBytes[i] = URL_ALPHABET.charCodeAt(poolBytes[i] & 63)\n }\n characterPool = ASCII_DECODER.decode(poolBytes)\n poolOffset = 0\n }\n}\n\nfunction defaultAlphabetFromPool(size: number): string {\n fillPool(size)\n const id = characterPool.substring(poolOffset, poolOffset + size)\n poolOffset += size\n return id\n}\n\nexport type NanoidOptions = {\n /**\n * Random bytes for deterministic output (testing).\n * For power-of-2 alphabets (2, 4, 8, 16, 32, 64, 128, 256): exactly `size` bytes needed.\n * For other alphabets: ~size * 2 bytes needed (rejection sampling).\n */\n random?: Uint8Array\n /**\n * Custom alphabet to use. Default: URL-safe A-Za-z0-9_-\n * Must be 2-256 printable ASCII characters (32-126) with no duplicates.\n */\n alphabet?: string\n /**\n * Length of generated ID. Default: 21. Maximum: 2048.\n */\n size?: number\n}\n\nexport type Nanoid = {\n /** Generate a Nanoid with the default URL-safe alphabet and 21-character length. */\n (): string\n /** Generate a Nanoid with the default alphabet and a custom length. */\n (size: number): string\n /** Generate a Nanoid with a custom alphabet, length, or deterministic random bytes. */\n (options: NanoidOptions): string\n /**\n * Validate a nanoid string against the default URL-safe alphabet.\n * Note: Does not validate IDs generated with custom alphabets.\n */\n isValid(id: unknown): id is string\n}\n\n/**\n * Validate alphabet: 2-256 printable ASCII chars, no duplicates\n */\nfunction validateAlphabet(alphabet: string): void {\n if (alphabet.length < 2) {\n throw new InvalidInputError('NANOID_ALPHABET_TOO_SHORT', 'Alphabet must contain at least 2 characters')\n }\n if (alphabet.length > 256) {\n throw new InvalidInputError('NANOID_ALPHABET_TOO_LONG', 'Alphabet must not exceed 256 characters')\n }\n const seen = new Set<string>()\n for (const char of alphabet) {\n const code = char.charCodeAt(0)\n if (code < 32 || code > 126) {\n throw new InvalidInputError(\n 'NANOID_ALPHABET_INVALID_CHAR',\n 'Alphabet must contain only printable ASCII characters (32-126)',\n )\n }\n if (seen.has(char)) {\n throw new InvalidInputError('NANOID_ALPHABET_DUPLICATE', `Duplicate character in alphabet: \"${char}\"`)\n }\n seen.add(char)\n }\n}\n\n/**\n * Validate size parameter\n */\nfunction validateSize(size: number): void {\n if (!Number.isInteger(size) || size < 0) {\n throw new InvalidInputError('NANOID_SIZE_INVALID', 'Size must be a non-negative integer')\n }\n if (size > MAX_SIZE) {\n throw new InvalidInputError('NANOID_SIZE_TOO_LARGE', `Size must not exceed ${MAX_SIZE}`)\n }\n}\n\n// Overloads\nfunction nanoidFn(): string\nfunction nanoidFn(size: number): string\nfunction nanoidFn(options: NanoidOptions): string\nfunction nanoidFn(sizeOrOptions?: number | NanoidOptions): string {\n // ULTRA-FAST PATH: No arguments = default nanoid\n // Uses simple pooled random bytes (npm nanoid style) for best performance\n if (sizeOrOptions === undefined) {\n return defaultAlphabetFromPool(DEFAULT_SIZE)\n }\n\n let size = DEFAULT_SIZE\n let alphabet = URL_ALPHABET\n let randomBytes: Uint8Array | undefined\n\n if (typeof sizeOrOptions === 'number') {\n size = sizeOrOptions\n } else {\n size = sizeOrOptions.size ?? DEFAULT_SIZE\n alphabet = sizeOrOptions.alphabet ?? URL_ALPHABET\n randomBytes = sizeOrOptions.random\n if (sizeOrOptions.alphabet !== undefined) {\n validateAlphabet(alphabet)\n }\n }\n\n validateSize(size)\n\n if (size === 0) return ''\n\n if (alphabet === URL_ALPHABET && randomBytes === undefined) {\n return defaultAlphabetFromPool(size)\n }\n\n const alphabetLen = alphabet.length\n\n // FAST PATH: Power-of-2 alphabet (includes default 64-char)\n // No rejection needed - each byte maps directly to a character\n if ((alphabetLen & (alphabetLen - 1)) === 0) {\n const mask = alphabetLen - 1\n if (randomBytes && randomBytes.length < size) {\n throw new InvalidInputError(\n 'NANOID_RANDOM_BYTES_INSUFFICIENT',\n `Insufficient random bytes: need ${size}, have ${randomBytes.length}`,\n )\n }\n const bytes = randomBytes?.subarray(0, size) ?? globalThis.crypto.getRandomValues(new Uint8Array(size))\n let id = ''\n for (let i = 0; i < size; i++) {\n id += alphabet[bytes[i] & mask]\n }\n return id\n }\n\n // SLOW PATH: Rejection sampling for non-power-of-2 alphabets\n // Calculate mask: smallest power-of-2 minus 1 that covers alphabet size\n const mask = (2 << (31 - Math.clz32((alphabetLen - 1) | 1))) - 1\n // Calculate step: random bytes per batch (1.6x accounts for rejection)\n const step = Math.ceil((1.6 * mask * size) / alphabetLen)\n\n let id = ''\n let randomOffset = 0\n\n while (id.length < size) {\n let bytes: Uint8Array\n if (randomBytes) {\n if (randomBytes.length - randomOffset < step) {\n throw new InvalidInputError(\n 'NANOID_RANDOM_BYTES_INSUFFICIENT',\n `Insufficient random bytes: need at least ${step} more, have ${randomBytes.length - randomOffset}`,\n )\n }\n bytes = randomBytes.subarray(randomOffset, randomOffset + step)\n randomOffset += step\n } else {\n bytes = globalThis.crypto.getRandomValues(new Uint8Array(step))\n }\n\n for (let i = 0; i < bytes.length && id.length < size; i++) {\n const index = bytes[i] & mask\n if (index < alphabetLen) {\n id += alphabet[index]\n }\n // Otherwise reject and continue (no modulo bias)\n }\n }\n\n return id\n}\n\n/**\n * Validate a nanoid string against the default URL-safe alphabet.\n * Note: Does not validate IDs generated with custom alphabets.\n */\nfunction isValid(id: unknown): id is string {\n return typeof id === 'string' && id.length > 0 && NANOID_REGEX.test(id)\n}\n\n/**\n * Generate a URL-friendly unique string ID.\n *\n * Nanoid is a tiny, secure, URL-friendly unique string ID generator.\n * It uses a URL-safe alphabet (A-Za-z0-9_-) and generates 21-character\n * IDs by default with 126 bits of entropy.\n *\n * Unlike UUID v7 or ULID, nanoid is NOT time-ordered. Use it for:\n * - URL shorteners\n * - Session tokens\n * - Invite codes\n * - Any case where you need short, random IDs\n *\n * @example Basic usage\n * ```ts\n * import { nanoid } from 'uniku/nanoid'\n *\n * const id = nanoid()\n * // => \"V1StGXR8_Z5jdHi6B-myT\"\n * ```\n *\n * @example Custom size\n * ```ts\n * const shortId = nanoid(10)\n * // => \"IRFa-VaY2b\"\n * ```\n *\n * @example Custom alphabet (hex)\n * ```ts\n * const hexId = nanoid({ alphabet: '0123456789abcdef', size: 12 })\n * // => \"4f90d13a42bc\"\n * ```\n *\n * @example Validation\n * ```ts\n * const maybeId: unknown = getUserInput()\n * if (nanoid.isValid(maybeId)) {\n * // TypeScript knows maybeId is string\n * console.log(maybeId.length)\n * }\n * ```\n *\n * @throws {InvalidInputError} Size must be between 0 and 2048\n * @throws {InvalidInputError} Alphabet must contain 2-256 unique printable ASCII characters\n * @throws {InvalidInputError} Insufficient random bytes for requested size\n */\nexport const nanoid: Nanoid = Object.assign(nanoidFn, {\n isValid,\n})\n\nexport { InvalidInputError, UniqueIdError } from '../errors'\n"],"mappings":"qEAGA,MAAa,EAAe,mEAGtB,EAAW,KACX,EAAe,mBAMf,EAAgB,IAAI,YAC1B,IAAI,EACA,EAAgB,GAChB,EAAa,EAEjB,SAAS,EAAS,EAAqB,CACrC,IAAM,EAAO,KAAK,IAAI,EAAQ,IAAsB,KAAa,EAIjE,IAHI,CAAC,GAAa,EAAU,OAAS,KACnC,EAAY,IAAI,WAAW,CAAI,GAE7B,EAAa,EAAQ,EAAc,OAAQ,CAC7C,OAAO,gBAAgB,CAAS,EAChC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAU,OAAQ,IACpC,EAAU,GAAK,EAAa,WAAW,EAAU,GAAK,EAAE,EAE1D,EAAgB,EAAc,OAAO,CAAS,EAC9C,EAAa,CACf,CACF,CAEA,SAAS,EAAwB,EAAsB,CACrD,EAAS,CAAI,EACb,IAAM,EAAK,EAAc,UAAU,EAAY,EAAa,CAAI,EAEhE,MADA,IAAc,EACP,CACT,CAqCA,SAAS,EAAiB,EAAwB,CAChD,GAAI,EAAS,OAAS,EACpB,MAAM,IAAI,EAAkB,4BAA6B,6CAA6C,EAExG,GAAI,EAAS,OAAS,IACpB,MAAM,I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GAE5B,OAAO,CACT,CAIA,IAAM,GAAQ,GAAM,GAAK,KAAK,MAAO,EAAc,EAAK,CAAC,GAAM,EAEzD,EAAO,KAAK,KAAM,IAAM,EAAO,EAAQ,CAAW,EAEpD,EAAK,GACL,EAAe,EAEnB,KAAO,EAAG,OAAS,GAAM,CACvB,IAAI,EACJ,GAAI,EAAa,CACf,GAAI,EAAY,OAAS,EAAe,EACtC,MAAM,IAAI,EACR,mCACA,4CAA4C,EAAK,cAAc,EAAY,OAAS,GACtF,EAEF,EAAQ,EAAY,SAAS,EAAc,EAAe,CAAI,EAC9D,GAAgB,CAClB,KACE,GAAQ,WAAW,OAAO,gBAAgB,IAAI,WAAW,CAAI,CAAC,EAGhE,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,QAAU,EAAG,OAAS,EAAM,IAAK,CACzD,IAAM,EAAQ,EAAM,GAAK,EACrB,EAAQ,IACV,GAAM,EAAS,GAGnB,CACF,CAEA,OAAO,CACT,CAMA,SAAS,EAAQ,EAA2B,CAC1C,OAAO,OAAO,GAAO,UAAY,EAAG,OAAS,GAAK,EAAa,KAAK,CAAE,CACxE,CAgDA,MAAa,EAAiB,OAAO,OAAO,EAAU,CACpD,SACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"nanoid.mjs","names":[],"sources":["../../src/nanoid/nanoid.ts"],"sourcesContent":["import { InvalidInputError } from '../errors'\n\n/** Default URL-safe alphabet (64 characters): A-Z, a-z, 0-9, underscore, hyphen */\nexport const URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'\n\nconst DEFAULT_SIZE = 21\nconst MAX_SIZE = 2048\nconst NANOID_REGEX = /^[A-Za-z0-9_-]+$/\n\n// Keep Nanoid's private pool for its default hot path. Translate random bytes\n// into URL-safe ASCII once per refill, then serve IDs as sequential substrings.\nconst POOL_SIZE_MULTIPLIER = 128\nconst MAX_POOL_SIZE = 65_536\nconst ASCII_DECODER = new TextDecoder()\nlet poolBytes: Uint8Array | undefined\nlet characterPool = ''\nlet poolOffset = 0\n\nfunction fillPool(bytes: number): void {\n const size = Math.min(bytes * POOL_SIZE_MULTIPLIER, MAX_POOL_SIZE)\n if (!poolBytes || poolBytes.length < size) {\n poolBytes = new Uint8Array(size)\n }\n if (poolOffset + bytes > characterPool.length) {\n crypto.getRandomValues(poolBytes)\n for (let i = 0; i < poolBytes.length; i++) {\n poolBytes[i] = URL_ALPHABET.charCodeAt(poolBytes[i] & 63)\n }\n characterPool = ASCII_DECODER.decode(poolBytes)\n poolOffset = 0\n }\n}\n\nfunction defaultAlphabetFromPool(size: number): string {\n fillPool(size)\n const id = characterPool.substring(poolOffset, poolOffset + size)\n poolOffset += size\n return id\n}\n\nexport type NanoidOptions = {\n /**\n * Random bytes for deterministic output (testing).\n * For power-of-2 alphabets (2, 4, 8, 16, 32, 64, 128, 256): exactly `length` bytes needed.\n * For other alphabets: ~length * 2 bytes needed (rejection sampling).\n */\n random?: Uint8Array\n /**\n * Custom alphabet to use. Default: URL-safe A-Za-z0-9_-\n * Must be 2-256 printable ASCII characters (32-126) with no duplicates.\n */\n alphabet?: string\n /**\n * Length of generated ID. Default: 21. Maximum: 2048.\n */\n length?: number\n /**\n * Length of generated ID.\n *\n * @deprecated Use `length` instead. Will be removed at v1-rc.\n */\n // TODO(v1-rc): remove this alias (tracked in docs/STABILITY.md).\n size?: number\n}\n\nexport type Nanoid = {\n /** Generate a Nanoid with the default URL-safe alphabet and 21-character length. */\n (): string\n /** Generate a Nanoid with the default alphabet and a custom length. */\n (size: number): string\n /** Generate a Nanoid with a custom alphabet, length, or deterministic random bytes. */\n (options: NanoidOptions): string\n /**\n * Validate a nanoid string against the default URL-safe alphabet.\n * Note: Does not validate IDs generated with custom alphabets.\n */\n isValid(id: unknown): id is string\n}\n\n/**\n * Validate alphabet: 2-256 printable ASCII chars, no duplicates\n */\nfunction validateAlphabet(alphabet: string): void {\n if (alphabet.length < 2) {\n throw new InvalidInputError('ALPHABET_OUT_OF_RANGE', 'Alphabet must contain at least 2 characters', {\n strategy: 'nanoid',\n })\n }\n if (alphabet.length > 256) {\n throw new InvalidInputError('ALPHABET_OUT_OF_RANGE', 'Alphabet must not exceed 256 characters', {\n strategy: 'nanoid',\n })\n }\n const seen = new Set<string>()\n for (const char of alphabet) {\n const code = char.charCodeAt(0)\n if (code < 32 || code > 126) {\n throw new InvalidInputError(\n 'ALPHABET_INVALID_CHAR',\n 'Alphabet must contain only printable ASCII characters (32-126)',\n {\n strategy: 'nanoid',\n },\n )\n }\n if (seen.has(char)) {\n throw new InvalidInputError('ALPHABET_DUPLICATE', `Duplicate character in alphabet: \"${char}\"`, {\n strategy: 'nanoid',\n })\n }\n seen.add(char)\n }\n}\n\n/**\n * Validate length parameter\n */\nfunction validateLength(size: number): void {\n if (!Number.isInteger(size) || size < 0) {\n throw new InvalidInputError('LENGTH_OUT_OF_RANGE', 'Length must be a non-negative integer', { strategy: 'nanoid' })\n }\n if (size > MAX_SIZE) {\n throw new InvalidInputError('LENGTH_OUT_OF_RANGE', `Length must not exceed ${MAX_SIZE}`, { strategy: 'nanoid' })\n }\n}\n\n// Overloads\nfunction nanoidFn(): string\nfunction nanoidFn(size: number): string\nfunction nanoidFn(options: NanoidOptions): string\nfunction nanoidFn(sizeOrOptions?: number | NanoidOptions): string {\n // ULTRA-FAST PATH: No arguments = default nanoid\n // Uses simple pooled random bytes (npm nanoid style) for best performance\n if (sizeOrOptions === undefined) {\n return defaultAlphabetFromPool(DEFAULT_SIZE)\n }\n\n let size = DEFAULT_SIZE\n let alphabet = URL_ALPHABET\n let randomBytes: Uint8Array | undefined\n\n if (typeof sizeOrOptions === 'number') {\n size = sizeOrOptions\n } else {\n if (sizeOrOptions.length !== undefined && sizeOrOptions.size !== undefined) {\n throw new InvalidInputError('CONFLICTING_OPTIONS', 'Pass only one of `length` or `size`, not both', {\n strategy: 'nanoid',\n })\n }\n size = sizeOrOptions.length ?? sizeOrOptions.size ?? DEFAULT_SIZE\n alphabet = sizeOrOptions.alphabet ?? URL_ALPHABET\n randomBytes = sizeOrOptions.random\n if (sizeOrOptions.alphabet !== undefined) {\n validateAlphabet(alphabet)\n }\n }\n\n validateLength(size)\n\n if (size === 0) return ''\n\n if (alphabet === URL_ALPHABET && randomBytes === undefined) {\n return defaultAlphabetFromPool(size)\n }\n\n const alphabetLen = alphabet.length\n\n // FAST PATH: Power-of-2 alphabet (includes default 64-char)\n // No rejection needed - each byte maps directly to a character\n if ((alphabetLen & (alphabetLen - 1)) === 0) {\n const mask = alphabetLen - 1\n if (randomBytes && randomBytes.length < size) {\n throw new InvalidInputError(\n 'RANDOM_BYTES_TOO_SHORT',\n `Insufficient random bytes: need ${size}, have ${randomBytes.length}`,\n { strategy: 'nanoid' },\n )\n }\n const bytes = randomBytes?.subarray(0, size) ?? globalThis.crypto.getRandomValues(new Uint8Array(size))\n let id = ''\n for (let i = 0; i < size; i++) {\n id += alphabet[bytes[i] & mask]\n }\n return id\n }\n\n // SLOW PATH: Rejection sampling for non-power-of-2 alphabets\n // Calculate mask: smallest power-of-2 minus 1 that covers alphabet size\n const mask = (2 << (31 - Math.clz32((alphabetLen - 1) | 1))) - 1\n // Calculate step: random bytes per batch (1.6x accounts for rejection)\n const step = Math.ceil((1.6 * mask * size) / alphabetLen)\n\n let id = ''\n let randomOffset = 0\n\n while (id.length < size) {\n let bytes: Uint8Array\n if (randomBytes) {\n if (randomBytes.length - randomOffset < step) {\n throw new InvalidInputError(\n 'RANDOM_BYTES_TOO_SHORT',\n `Insufficient random bytes: need at least ${step} more, have ${randomBytes.length - randomOffset}`,\n { strategy: 'nanoid' },\n )\n }\n bytes = randomBytes.subarray(randomOffset, randomOffset + step)\n randomOffset += step\n } else {\n bytes = globalThis.crypto.getRandomValues(new Uint8Array(step))\n }\n\n for (let i = 0; i < bytes.length && id.length < size; i++) {\n const index = bytes[i] & mask\n if (index < alphabetLen) {\n id += alphabet[index]\n }\n // Otherwise reject and continue (no modulo bias)\n }\n }\n\n return id\n}\n\n/**\n * Validate a nanoid string against the default URL-safe alphabet.\n * Note: Does not validate IDs generated with custom alphabets.\n */\nfunction isValid(id: unknown): id is string {\n return typeof id === 'string' && id.length > 0 && NANOID_REGEX.test(id)\n}\n\n/**\n * Generate a URL-friendly unique string ID.\n *\n * Nanoid is a tiny, secure, URL-friendly unique string ID generator.\n * It uses a URL-safe alphabet (A-Za-z0-9_-) and generates 21-character\n * IDs by default with 126 bits of entropy.\n *\n * Unlike UUID v7 or ULID, nanoid is NOT time-ordered. Use it for:\n * - URL shorteners\n * - Session tokens\n * - Invite codes\n * - Any case where you need short, random IDs\n *\n * @example Basic usage\n * ```ts\n * import { nanoid } from 'uniku/nanoid'\n *\n * const id = nanoid()\n * // => \"V1StGXR8_Z5jdHi6B-myT\"\n * ```\n *\n * @example Custom length\n * ```ts\n * const shortId = nanoid(10)\n * // => \"IRFa-VaY2b\"\n * ```\n *\n * @example Custom alphabet (hex)\n * ```ts\n * const hexId = nanoid({ alphabet: '0123456789abcdef', length: 12 })\n * // => \"4f90d13a42bc\"\n * ```\n *\n * @example Validation\n * ```ts\n * const maybeId: unknown = getUserInput()\n * if (nanoid.isValid(maybeId)) {\n * // TypeScript knows maybeId is string\n * console.log(maybeId.length)\n * }\n * ```\n *\n * @throws {InvalidInputError} Length must be between 0 and 2048\n * @throws {InvalidInputError} Alphabet must contain 2-256 unique printable ASCII characters\n * @throws {InvalidInputError} Insufficient random bytes for requested length\n */\nexport const nanoid: Nanoid = Object.assign(nanoidFn, {\n isValid,\n})\n\nexport { InvalidInputError, UniqueIdError } from '../errors'\n"],"mappings":"qEAGA,MAAa,EAAe,mEAGtB,EAAW,KACX,EAAe,mBAMf,EAAgB,IAAI,YAC1B,IAAI,EACA,EAAgB,GAChB,EAAa,EAEjB,SAAS,EAAS,EAAqB,CACrC,IAAM,EAAO,KAAK,IAAI,EAAQ,IAAsB,KAAa,EAIjE,IAHI,CAAC,GAAa,EAAU,OAAS,KACnC,EAAY,IAAI,WA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,WAAW,CAAI,CAAC,EAGhE,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,QAAU,EAAG,OAAS,EAAM,IAAK,CACzD,IAAM,EAAQ,EAAM,GAAK,EACrB,EAAQ,IACV,GAAM,EAAS,GAGnB,CACF,CAEA,OAAO,CACT,CAMA,SAAS,EAAQ,EAA2B,CAC1C,OAAO,OAAO,GAAO,UAAY,EAAG,OAAS,GAAK,EAAa,KAAK,CAAE,CACxE,CAgDA,MAAa,EAAiB,OAAO,OAAO,EAAU,CACpD,SACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as ParseError, i as InvalidInputError, o as UniqueIdError, t as BufferError } from "../errors-Da-8dh4J.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/objectid/objectid.d.ts
|
|
4
4
|
type ObjectIdOptions = {
|
|
@@ -7,8 +7,15 @@ type ObjectIdOptions = {
|
|
|
7
7
|
*/
|
|
8
8
|
random?: Uint8Array;
|
|
9
9
|
/**
|
|
10
|
-
* Timestamp in
|
|
11
|
-
* Defaults to
|
|
10
|
+
* Timestamp in milliseconds since the Unix epoch.
|
|
11
|
+
* Defaults to Date.now().
|
|
12
|
+
* ObjectID stores whole seconds, so sub-second precision is truncated.
|
|
13
|
+
*/
|
|
14
|
+
msecs?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Timestamp in seconds since the Unix epoch.
|
|
17
|
+
*
|
|
18
|
+
* @deprecated Use `msecs` instead. Will be removed at v1-rc.
|
|
12
19
|
*/
|
|
13
20
|
secs?: number;
|
|
14
21
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"objectid.d.mts","names":[],"sources":["../../src/objectid/objectid.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"objectid.d.mts","names":[],"sources":["../../src/objectid/objectid.ts"],"mappings":";;;KA4BY,eAAA;;;AAAZ;EAIE,MAAA,GAAS,UAAA;;;;;;EAMT,KAAA;;;AAWA;AAGF;;EAPE,IAAA;;;;EAIA,OAAA;AAAA;AAAA,KAGU,QAAA;mEAUO;EAAA,cANH,UAAA,GAAa,UAAA,EAAY,OAAA,EAAS,eAAA,cAA6B,GAAA,EAAK,IAAA,EAAM,MAAA,YAAkB,IAAA;GAEzG,OAAA,GAAU,eAAA,EAAiB,GAAA,cAAiB,MAAA;EAE7C,OAAA,CAAQ,EAAA,WAAa,UAAA;EAErB,SAAA,CAAU,KAAA,EAAO,UAAA;EAEjB,SAAA,CAAU,EAAA;EAEV,OAAA,CAAQ,EAAA,YAAc,EAAA;EAEtB,GAAA;EAEA,GAAA;AAAA;;;;;;;;;;;;;AAAA;AAsNF;;;;AAAuB;;;;;;;;;;cAAV,QAAA,EAAU,QAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"../random-Chp-Nkzi.mjs";import{n,t as r}from"../validation-CTNpXm94.mjs";import{BufferError as i,InvalidInputError as a,ParseError as o,UniqueIdError as s}from"../errors.mjs";import{n as c}from"../bytes-xqWxFYsM.mjs";const
|
|
1
|
+
import{n as e,t}from"../random-Chp-Nkzi.mjs";import{n,t as r}from"../validation-CTNpXm94.mjs";import{BufferError as i,InvalidInputError as a,ParseError as o,UniqueIdError as s}from"../errors.mjs";import{n as c}from"../bytes-xqWxFYsM.mjs";import{t as l}from"../timestamp-ChrSuQCR.mjs";const u=`0123456789abcdef`,d=Array.from({length:256},(e,t)=>u[t>>4&15]+u[t&15]),f=new Uint8Array(65536);f.fill(255);for(let e=0;e<=9;e+=1)f[48+e]=e;for(let e=0;e<6;e+=1)f[97+e]=10+e,f[65+e]=10+e;function p(e){if(e.length<12)throw new i(`BYTES_INVALID_LENGTH`,`ObjectID bytes must be at least 12 bytes, got ${e.length}`,{strategy:`objectid`});let t=``;for(let n=0;n<12;n+=1)t+=d[e[n]];return t}function m(e){if(e.length!==24)throw new o(`INVALID_LENGTH`,`ObjectID string must be 24 characters, got ${e.length}`,{strategy:`objectid`});let t=new Uint8Array(12);for(let n=0;n<12;n+=1){let r=n*2,i=r+1,a=f[e.charCodeAt(r)],s=f[e.charCodeAt(i)];if(a===255)throw new o(`INVALID_CHAR`,`Invalid ObjectID character: ${e[r]}`,{strategy:`objectid`});if(s===255)throw new o(`INVALID_CHAR`,`Invalid ObjectID character: ${e[i]}`,{strategy:`objectid`});t[n]=a<<4|s}return t}const h=16777215,g=/^[0-9a-f]{24}$/i,_={random:void 0,counter:void 0};function v(){let e=new Uint8Array(5);return e.set(t(5)),e}function y(e,t,n,r,i){c(r,i,e);for(let e=0;e<5;e+=1)r[i+4+e]=t[e];r[i+4+5]=n>>>16&255,r[i+4+5+1]=n>>>8&255,r[i+4+5+3-1]=n&255}function b(t,o,s=0){let c,u,d;if(t){let n=t.random;if(n&&n.length<5)throw new a(`RANDOM_BYTES_TOO_SHORT`,`Random bytes length must be >= 5 for ObjectID`,{strategy:`objectid`});let i=l(t,0,4294967295,`objectid`),o=t.counter;if(o!==void 0&&!r(o,0,h))throw new a(`COUNTER_OUT_OF_RANGE`,`Counter must be between 0 and ${h}`,{strategy:`objectid`});c=i??Math.floor(Date.now()/1e3),u=n??v(),d=o??e()&h}else _.random===void 0&&(_.random=v()),_.counter===void 0&&(_.counter=e()&h),c=Math.floor(Date.now()/1e3),u=_.random,_.counter=_.counter+1&h,d=_.counter;if(o){if(!n(o,s,12))throw new i(`BUFFER_OUT_OF_BOUNDS`,`ObjectID byte range ${s}:${s+12-1} is out of buffer bounds`,{strategy:`objectid`});return y(c,u,d,o,s),o}let f=new Uint8Array(12);return y(c,u,d,f,0),p(f)}function x(e){return m(e)}function S(e){if(e.length!==12)throw new i(`BYTES_INVALID_LENGTH`,`ObjectID bytes must be exactly 12 bytes, got ${e.length}`,{strategy:`objectid`});return p(e)}function C(e){let t=m(e);return((t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0)*1e3}function w(e){return typeof e==`string`&&g.test(e)}const T=Object.assign(b,{toBytes:x,fromBytes:S,timestamp:C,isValid:w,NIL:`0`.repeat(24),MAX:`f`.repeat(24)});export{i as BufferError,a as InvalidInputError,o as ParseError,s as UniqueIdError,T as objectid};
|
|
2
2
|
//# sourceMappingURL=objectid.mjs.map
|