@anizoptera/uuid-slug 0.3.0 → 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.
Files changed (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +373 -324
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +15 -8
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
package/README.md CHANGED
@@ -1,418 +1,467 @@
1
1
  # @anizoptera/uuid-slug
2
2
 
3
- Use shorter UUIDs in URLs, with optional masking of UUIDv7 timestamps.
3
+ High-performance UUIDv4/v7 generation and handling for TS, Rust, and WASM, short base64/base32 plain slugs and configurable masked UUIDv7 slugs. Zero runtime deps, tree-shakable, and optimised for your runtime. One efficient ID for databases, URLs and files.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@anizoptera/uuid-slug?label=npm)](https://www.npmjs.com/package/@anizoptera/uuid-slug)
6
6
  [![CI](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml/badge.svg?branch=main)](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml)
7
- [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
8
7
  [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json)
8
+ [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
9
+ [![Bun >=1.0](https://img.shields.io/badge/bun-%3E%3D1.0-FBF0DF?logo=bun&logoColor=FBF0DF)](#runtime)
10
+ [![Deno >=1.29](https://img.shields.io/badge/deno-%3E%3D1.29-70FFAF?logo=deno&logoColor=white)](#runtime)
11
+ [![Cloudflare Workers](https://img.shields.io/badge/cloud-workers-F38020?logo=cloudflare&logoColor=white)](#runtime)
9
12
  [![License](https://img.shields.io/github/license/Anizoptera/uuid-slug)](LICENSE)
10
13
 
11
- A UUID in a URL is 36 characters of hex and dashes. The same 16 bytes written as base64url
12
- are 22 characters, and nothing is lost: it is the same identifier in a shorter alphabet.
14
+ [![One UUIDv7 shown as UUID text, 16 bytes, plain base64url and base32hex slugs, and masked base64url and base32hex slugs, with colours tracing timestamp, version, variant and payload bits](docs/assets/uuid-representations.svg)](https://raw.githubusercontent.com/Anizoptera/uuid-slug/main/docs/assets/uuid-representations.svg)
15
+
16
+ <p align="center"><sub><em>Open the <a href="https://raw.githubusercontent.com/Anizoptera/uuid-slug/main/docs/assets/uuid-representations.svg">interactive infographic</a>: hover any field to trace it through every form.</em></sub></p>
17
+
18
+ - **Benchmark-leading UUIDv7 text generation on Node, Bun, Deno and browsers!**
19
+ - 6+ distinct UUID representations are supported!
20
+
21
+ - **[Leading performance](bench/results/competitors.md)**, low memory and resource allocation!
22
+ - Same API across Node, Bun, Deno, browsers and cloud workers. Native fast paths and portable fallbacks are used automatically.
23
+ - _IDs can be generated or decoded [directly into your buffers](#work-with-uuid-bytes); failed validation leaves them unchanged._
24
+
25
+ - **Zero runtime dependencies.** Small [runtime-optimised](#runtime) bundles on Node, Bun, Deno and browsers.
26
+
27
+ - **One UUID for storage, URLs and files, each in its [most compact form](#representations)!**
28
+ - 16-byte binary UUID for storage or transport.
29
+ - **Short 22-character base64url slug for URLs** (39% shorter than a naive UUID text).
30
+ - 26-character base32hex lowercase slug suits case-insensitive (e.g., cross-OS) filenames. Plain UUIDv7 slugs in this alphabet sort by timestamp under ASCII comparison.
31
+ - Optional **[UUIDv7 masked slug](#masked-slugs) form that hides timestamp and UUID structure.** Expose your IDs without revealing their creation time or nature!
32
+ - _Any UUID converts to a lossless plain slug and back. Existing database keys stay unchanged; no mapping table is needed._
33
+ - _Plain slugs decode with any standard base64url or base32hex decoder, without this library. Masked slugs need your key and settings._
34
+
35
+ - **UUIDv4/v7 generation, conversion and inspection, configurable UUIDv7 masking, and plain conversion for any UUID!**
36
+ - **Full control of UUIDv7 time and order:** [recorded times](#generate-at-a-recorded-time) or your own clock, clock-rollback policy, custom payload layout, [timestamp extraction](#use-the-uuid-as-the-timestamp-source) and [time-range queries](#ordering-and-key-distribution).
37
+ - IDs and relationships can be [created offline](#assign-ids-before-saving-or-syncing), before saving or syncing, without a central allocator or worker number.
38
+ - Masking [key rotation and format migration](docs/api.md#changing-an-existing-id-format) keep old IDs readable while new IDs use current settings.
39
+ - [Async key derivation](docs/api.md#masking-codec-options) yields during long work and can be cancelled.
40
+ - [Parse once](#parse-once-for-repeated-work): validate and decode an ID one time into the optimized UUID object, then reuse it for every conversion and inspection.
41
+ - Optional [sentinel IDs](#sentinels): reserved values for tests, debugging and tracing that stay recognizable in logs, even after key rotation.
42
+ - Optimal, **safe and most efficient defaults!**
43
+
44
+ - **Intuitive, ergonomic, agent-friendly manually tailored API.**
45
+ - Strict types, validation, typed errors, safe buffer writes and one-check composition to prevent integration mistakes.
46
+ - Types catch UUID-version and plain/masked mix-ups before execution. Compatible conversions chain with one error check; failures have stable codes.
47
+ - **Named imports let supported bundlers [remove unused features](#guarantees), including masking and key derivation.**
13
48
 
14
- UUIDv7 adds a second problem. It begins with a millisecond timestamp, which is exactly
15
- what you want in a database index and rarely what you want in public. A v7 id tells anyone
16
- who reads it when the record was created, and two of them tell them how fast you are
17
- creating records. Masking removes that directly readable structure from public identifiers,
18
- then recovers the UUID for a lookup. It is obfuscation, not an authorization boundary.
49
+ - TypeScript and Rust implementations that encode and decode the same formats, including masked IDs with matching key settings.
50
+
51
+
52
+ [Install](#install) · [Quick start](#quick-start) · [Contents](#contents) · [API](#api) · [Performance](bench/results/competitors.md)
19
53
 
20
- It defines no new identifier scheme. Everything here is a UUID underneath.
21
54
 
22
55
  ## Install
23
56
 
24
- ```bash
25
- pnpm add @anizoptera/uuid-slug
57
+ Use your favorite TS/JS package manager (npm/bun/pnpm/yarn/..), e.g.:
58
+ ```
59
+ bun install @anizoptera/uuid-slug
26
60
  ```
27
61
 
28
- Requires TypeScript 5.7 or newer for `Uint8Array<ArrayBuffer>` declarations.
29
- Custom `fillRandom` callbacks receive an ordinary `ArrayBuffer` view, which Web Crypto accepts.
62
+ _The [Rust crate](rust/uuid-slug) and WASM builds live in this repo but are not yet published._
63
+
30
64
 
31
65
  ## Quick start
32
66
 
67
+ One call returns the same ID as `uuid` for storage and `slug` for URLs:
68
+
33
69
  ```ts
34
- import { createUuidSlugCodec } from "@anizoptera/uuid-slug";
70
+ import { generateUuidV7WithPlainSlug } from "@anizoptera/uuid-slug";
71
+ import type { GeneratedUuidV7, PlainUuidV7Slug } from "@anizoptera/uuid-slug";
35
72
 
36
- const seed = process.env.ID_MASK_SEED;
37
- if (!seed) throw new Error("Set ID_MASK_SEED to a stable, randomly generated secret.");
73
+ const { uuid, slug }: GeneratedUuidV7<PlainUuidV7Slug> = generateUuidV7WithPlainSlug();
74
+ ```
38
75
 
39
- // Reuse the codec: the seed is expanded once, at construction.
40
- export const ids = createUuidSlugCodec({ mask: { seed } });
76
+ `uuid` has type `UuidV7String`; `slug` has type `PlainUuidV7Slug`.
77
+ These are ordinary strings at runtime; TypeScript retains their UUID version and representation.
78
+ Unchecked external IDs remain `string` inputs; conversion and parsing validate them.
41
79
 
42
- const publicId = ids.uuidV7MaskedSlug();
43
- const uuid = ids.maskedSlugToUuidV7(publicId);
44
- if (uuid instanceof Error) throw uuid;
45
- // Look up uuid in your store and apply the caller's authorization policy.
46
- ```
80
+ Use `generateUuidV4()` for random IDs, `generateUuidV7()` for timestamped IDs, or
81
+ `generatePlainUuidV7Slug()` for just the slug.
82
+ Default generation returns the ID and throws `rng_unavailable` only without secure randomness.
83
+ [Conversions return errors as values](#handling-errors).
47
84
 
48
- **Generate the seed; do not think one up.** For example, run `openssl rand -base64 32` and
49
- store the result outside your source repository. Seeds shorter than 16 bytes are rejected, but
50
- length alone does not make a seed unpredictable: a known UUID/slug pair allows offline guesses.
51
85
 
52
- Keep the seed and `keyIterations` stable for as long as issued slugs must remain readable.
53
- Changing either derives different keys; retain the old settings in `previousMasks` during
54
- rotation. `keyIterations` defaults to `1`; increasing it adds construction and guessing cost,
55
- but does not turn a human-chosen seed into a suitable secret.
86
+ ## Contents
56
87
 
57
- ## Two kinds of slug
88
+ - [Performance](bench/results/competitors.md) · [Install](#install) · [Quick start](#quick-start)
89
+ - [Convert existing IDs](#keep-your-existing-uuids) · [Representations](#representations)
90
+ - [Plain slugs](#plain-slugs) · [Masking](#masked-slugs) · [Sentinels](#sentinels) · [Bytes](#work-with-uuid-bytes)
91
+ - [Parse once](#parse-once-for-repeated-work) · [Offline IDs](#assign-ids-before-saving-or-syncing)
92
+ - [Recorded time](#generate-at-a-recorded-time) · [Extract time](#use-the-uuid-as-the-timestamp-source) · [Ordering](#ordering-and-key-distribution) · [Security limits](#masking-security)
93
+ - [Errors](#handling-errors) · [Types](docs/api.md#types)
94
+ - [API](#api) · [TypeScript API map](#typescript-api-map)
95
+ - [Codec options](docs/api.md#masking-codec-options) · [Migration](docs/api.md#reading-original-slugs-during-migration)
96
+ - [Guarantees](#guarantees)
97
+ - [Runtime](#runtime)
98
+ - [Upgrades and support](#upgrades-and-support)
99
+ - [License](#license)
100
+
101
+ ## Keep your existing UUIDs
58
102
 
59
- **Direct slug.** The 16 UUID bytes as unpadded base64url, 22 characters. Pure re-encoding:
60
- `uuidToSlug` and `slugToUuid` preserve the UUID value, and anyone can convert either way. Use it
61
- when you only want the identifier shorter.
62
-
63
- Pass `"base32hex"` to get 26 characters instead, and gain one thing: **base32hex slugs of UUIDv7s
64
- sort by creation time as plain strings.** A v7 starts with its timestamp, and base32hex writes
65
- its digits in the same order as their values, so comparing two slugs compares two instants. That
66
- makes them usable directly as an ordered database key. base64url cannot do it — its alphabet runs
67
- `A-Za-z0-9-_`, so `0` stands for a larger value than `A` but sorts before it.
68
-
69
- base32hex is also the safer of the two for a **filename**: it is lowercase throughout, so it
70
- survives a case-insensitive filesystem unchanged, and a directory listing comes back in creation
71
- order for free. `uuidV7Slug("base32hex")` generates one directly; the alphabet is an argument on
72
- every keyless entry point that produces a slug, so nothing about choosing it requires a codec.
73
-
74
- You never say which alphabet you are reading. The two lengths are different, 22 and 26, so
75
- `slugToUuid` works out the encoding from the slug itself — which means switching alphabet leaves
76
- every slug you have already handed out working.
77
-
78
- **Masked slug.** A UUIDv7 payload and check passed through a small block cipher keyed by your
79
- seed, then base64url-encoded. Also 22 characters. Use it when the identifier is public and you
80
- would rather not publish creation times. The exact steps are in
81
- [how masking works](https://github.com/Anizoptera/uuid-slug/blob/main/docs/design.md).
82
-
83
- A supported UUIDv7 carries 116 bits that the masked format must preserve — the version and
84
- variant are fixed, and the top six bits of the timestamp stay zero until the year 2109. 22 base64url characters hold 132
85
- bits, so the spare 16 carry a check for incorrect decoding. Two things follow, and both are
86
- part of the contract rather than implementation detail:
87
-
88
- - **A decoded slug is a candidate, not a proof.** Roughly one random 22-character string in
89
- 65,536 passes the check and decodes to a well-formed, possibly unissued UUID. Look the result
90
- up in your own store; a wrong candidate is then a miss rather than a wrong answer. Every extra
91
- distinct schema you try adds another opportunity for false acceptance; the combined rate is
92
- at most the sum of the individual rates. Keep the rotation list short.
93
- - **Masking refuses a timestamp at or past 2^42 ms** — the year 2109 — with `invalid_timestamp`,
94
- because those six bits are spent on the check. Truncating instead would let two UUIDs share one
95
- slug, which nothing could recover from. Direct slugs have no such limit.
96
-
97
- **Sentinels** are reserved UUIDs that skip masking on purpose, so they stay recognisable in
98
- logs and support tickets. The defaults always encode to these fixed slugs:
99
-
100
- | Name | UUID | Slug |
101
- | --------------- | -------------------------------------- | ------------------------ |
102
- | `nil` | `00000000-0000-7000-8000-000000000000` | `AAAAAAAAcACAAAAAAAAAAA` |
103
- | `anonymousUser` | `00000000-0001-7000-8000-000000000000` | `AAAAAAABcACAAAAAAAAAAA` |
104
- | `unknownUser` | `00000000-0002-7000-8000-000000000000` | `AAAAAAACcACAAAAAAAAAAA` |
105
-
106
- Read the names, UUIDs and slugs from `codec.sentinels`. Pass your own list as `sentinels` to replace the defaults:
103
+ Encode stored UUIDs; decode incoming slugs before querying the same keys.
104
+ Plain encoding preserves every bit. Standard encodings let you decode plain slugs without this library; **masked slugs need the matching key and settings**.
107
105
 
108
106
  ```ts
109
- const ids = createUuidSlugCodec({
110
- mask: { seed },
111
- sentinels: [{ name: "unknownUser", uuid: "00000000-0002-7000-8000-000000000000" }],
112
- });
113
- console.table(ids.sentinels);
114
- ```
107
+ import { isUuidSlugError, plainSlugToUuidString, uuidStringToPlainSlug } from "@anizoptera/uuid-slug";
108
+ import type { PlainUuidSlug, UuidSlugError, UuidString } from "@anizoptera/uuid-slug";
115
109
 
116
- Keep sentinel definitions stable while their slugs are in use. Decoding checks sentinels first, so they
117
- are reserved even if a mask could produce the same text. Encoding rejects a non-sentinel UUID
118
- whose masked output collides with a reserved slug, using `invalid_mask_schema`; it never returns
119
- a slug that would decode to the wrong sentinel.
110
+ const slug: PlainUuidSlug | UuidSlugError = uuidStringToPlainSlug("0198abcd-1234-7abc-9def-0123456789ab");
111
+ if (typeof slug === "string") console.log(slug);
112
+ else console.error(slug.message);
120
113
 
121
- ## What masking is not
114
+ // Alternative to the typeof check: the helper recognizes returned error values.
115
+ if (!isUuidSlugError(slug)) console.log(slug);
122
116
 
123
- Masking uses a four-round Feistel network with HalfSipHash-2-4 round functions and a
124
- seed-derived key schedule. It removes a directly readable timestamp; this package does not
125
- establish a confidentiality strength for that construction or resistance to known-pair attacks.
126
- A reference-vector test for the round function does not establish those properties for the
127
- whole construction. See [the mechanism and its limits](docs/design.md).
117
+ const uuid: UuidString | UuidSlugError = plainSlugToUuidString("AZirzRI0eryd7wEjRWeJqw");
118
+ if (typeof uuid === "string") console.log(uuid); // The database key for this incoming URL slug.
119
+ else console.error(uuid.message);
120
+ ```
128
121
 
129
- Masked slugs are not authentication tokens or capabilities. The check detects many incorrect
130
- decodes; it is not a message authentication code. Confirm decoded candidates against your store
131
- and enforce authorization separately. Supplying a custom `mix` still leaves the same short check
132
- and does not turn the API into an authenticated-token system.
122
+ ## Representations
133
123
 
134
- **Supply your own secret seed for real identifiers.** Omitting `mask` uses the published default
135
- seed, so anyone can decode the result. Reserve that default for tests and demos.
136
- Masked operations are codec methods; `defaultCodec` uses the same public seed.
124
+ A masking codec holds the keys and settings to encode and decode UUIDv7 slugs.
137
125
 
138
- ## Handling errors
126
+ All examples encode the same UUIDv7; sizes are characters except for bytes.
139
127
 
140
- Parsing, decoding, formatting, conversion, byte generation, and explicit-timestamp generation
141
- return `UuidSlugError | T`. Check `instanceof Error` before using the value. String-only
142
- generators return a value directly and throw on failure; constructing an invalid codec throws too.
128
+ | Representation | Size | Example | Meaning and use |
129
+ | --- | ---: | --- | --- |
130
+ | UUID text | 36 | `0198abcd-1234-7abc-9def-0123456789ab` | Lowercase hyphenated output; uppercase optional |
131
+ | UUID bytes | 16 | `01 98 ab cd 12 34 7a bc 9d ef 01 23 45 67 89 ab` | Compact storage; writes a new or caller-owned array; encode as text for URLs |
132
+ | Plain base64url slug | 22 | `AZirzRI0eryd7wEjRWeJqw` | 39% shorter than UUID text; lossless for any UUID; case-sensitive; almost time-ordered for UUIDv7 |
133
+ | Plain base32hex slug | 26 | `06canj8i6htbp7ff04hkaps9lc` | 28% shorter than UUID text; keyless, lossless; writes lowercase, accepts mixed case; UUIDv7 sorts by timestamp in ASCII order |
134
+ | Masked base64url UUIDv7 slug | 22 | `ap225Qa_y6wN5LQCJgwH0z` | 39% shorter than UUID text; opaque, case-sensitive, unordered; 16-bit check; requires its codec to decode |
135
+ | Masked base32hex UUIDv7 slug | 27 | `daerdp86nv5qo3f4mg12c307qco` | 25% shorter than UUID text; opaque, unordered; writes lowercase, accepts mixed case; requires its codec to decode |
143
136
 
144
- Use the error's `code` for handling and its `message` for diagnostics. `UuidSlugErrorCode` and
145
- `UUID_SLUG_ERROR_CODES` are the exported type and runtime list of codes. Errors wrapping failed
146
- entropy draws, clock readings, and custom `mix` calls preserve the original exception as `cause`.
137
+ Parsers accept mixed-case canonical or compact hexadecimal text, brace-wrapped canonical text and UUID URNs. See [input examples](docs/api.md#uuid-text-input).
138
+ Masked examples use the public `UUID_V7_TEST_MASK`; use a private seed for your IDs.
147
139
 
148
- ## Types
140
+ Plain and masked base64url slugs can look identical but decode to different UUIDs.
141
+ Read known plain IDs with `plainSlugToUuidString` and known masked IDs with `maskingCodec.maskedSlugToUuidString`. General codec readers try masks first, then plain decoding only if every mask rejects the slug.
149
142
 
150
- Branded types distinguish the values returned by this library. Their marker is optional:
151
- assigning a string does not validate it. Use guards to check format and your store to check issuance.
143
+ Generate bytes once when you need several representations, then convert only those you use.
144
+ Use paired generation when you need UUID text plus one slug.
152
145
 
153
- - Strings: `UuidString`, `UuidV4String`, `UuidV7String`, `Base64UrlString`.
154
- - Slugs: `UuidSlug` (either alphabet), `UuidV4Slug`, `UuidV7Slug`; masked ones are base64url only
155
- — `MaskedUuidSlug`, `MaskedUuidV7Slug`, `SentinelUuidV7Slug`, and `PublicUuidV7Slug` for
156
- "masked or sentinel", which is what a masking call returns. `SlugAlphabet` names the two
157
- alphabets, and `UuidBytes` brands 16 raw bytes — for annotating storage of your own, which is why
158
- it appears in no signature here: a byte writer returns the caller's output array, which can be
159
- longer than the UUID range it writes.
160
- - Shapes: `UuidSlugCodec` and `UuidSlugCodecOptions`, `MaskSchema`, `MaskSchemaOptions` and `AsyncMaskSchemaOptions`,
161
- `UuidV7Sentinel` and `UuidV7SentinelDefinition`, `UuidV7Generator` and
162
- `UuidV7GeneratorOptions`, `FreshValidationOptions`, `UuidSlugErrorCode`.
146
+ ## Two kinds of slug
163
147
 
164
- **Some masked slugs also pass direct-slug guards.** Canonical trailing bits, version, and variant
165
- can all match by chance. A guard answers "is this well formed", never "is this mine". Decode with
166
- the matching API and look up the candidate; a brand or guard cannot establish issuance.
148
+ ### Plain slugs
167
149
 
168
- ## API
150
+ _Examples: `AZirzRI0eryd7wEjRWeJqw` (base64url), `06canj8i6htbp7ff04hkaps9lc` (base32hex)_
169
151
 
170
- The **Where** column tells you whether to import a function or call a codec method.
171
-
172
- - **codec + top level.** Keyless generation is available directly, for example `import { uuidV7 }`.
173
- A codec can use your supplied v7 generator; top-level generation uses the platform adapter.
174
- - **codec only.** Uses your configured keys or sentinels.
175
- - **module only.** Import these functions directly. Codec settings do not affect them.
176
-
177
- | Method | Where | Returns | What it does |
178
- | ------------------------------------------------------- | ----------------- | ----------------------------- | ---------------------------------------- |
179
- | `uuidV4()` / `uuidV7()` | codec + top level | UUID string | Generate. |
180
- | `uuidV4Bytes(out?, offset?)` / `uuidV7Bytes(...)` | codec + top level | `UuidSlugError \| Uint8Array` | Generate into a buffer you own. |
181
- | `uuidV7At(ms)` / `uuidV7BytesAt(ms, out?, offset?)` | codec + top level | `UuidSlugError \| ...` | Generate at an instant you name. |
182
- | `uuidV4Slug(alphabet?)` / `uuidV7Slug(alphabet?)` | top level | direct slug | Generate and encode in one step. |
183
- | `codec.uuidV4Slug()` / `codec.uuidV7Slug()` | codec | direct slug | Same, in the codec's `slugAlphabet`. |
184
- | `uuidV7MaskedSlug()` | codec only | `PublicUuidV7Slug` | Generate a masked or sentinel slug. |
185
- | `uuidV7ToMaskedSlug(uuid)` / `maskedSlugToUuidV7(slug)` | codec only | `UuidSlugError \| ...` | Masked slug, both ways; v7 only. |
186
- | `maskedSlugToUuid(slug)` | codec only | `UuidSlugError \| ...` | Unmask, accepting any UUID version. |
187
- | `validateMaskedSlugFresh(slug, opts?)` | codec only | `UuidSlugError \| ...` | Unmask, then check the freshness window. |
188
- | `sentinels` | codec only | array | The reserved values this codec knows. |
189
- | `migration(options?)` | codec only | migration reader | Read selected old formats without changing new output. |
190
- | `uuidToSlug(uuid, alphabet?)` / `slugToUuid(slug)` | module only | `UuidSlugError \| ...` | Direct slug, both ways. |
191
- | `parseUuid` / `formatUuid` | module only | `UuidSlugError \| ...` | UUID string to bytes and back. |
192
- | `parseUuidSlug` / `formatUuidSlug` | module only | `UuidSlugError \| ...` | Slug to bytes and back. |
193
-
194
- There is no `uuidToMaskedSlug`: masking is defined for UUIDv7 only, because a v7 is the version
195
- that leaks a creation time and 22 characters have no room for a version tag as well as the check.
196
-
197
- The `At` pair supports backfilling with a known timestamp. It takes the instant first and returns
198
- an error unless it is a whole number of Unix milliseconds in 0..2^48-1. Its interaction with
199
- current-time generation is runtime-specific; within-millisecond ordering is not promised.
200
-
201
- Both masking entry points return a raw sentinel slug when the UUID is registered as a sentinel.
202
- Their result type is `PublicUuidV7Slug`, the union of masked and sentinel slugs.
203
-
204
- Also exported, all module-level:
205
-
206
- - Type guards: `isUuidString`, `isUuidV4String`, `isUuidV7String`, `isUuidSlug`, `isUuidV4Slug`,
207
- `isUuidV7Slug`, and `isUuidV7Bytes` for 16 bytes you already hold.
208
- - base64url helpers: `encodeBase64Url`, `decodeBase64Url`, `isBase64Url`. `decodeBase64Url` returns
209
- a view over exactly the bytes it decoded — with or without an `out` buffer — so `.length` is the
210
- decoded length, never the buffer's. Given `out`, that view shares your buffer's memory.
211
- - `extractUuidV7Timestamp` — the instant a v7 was minted at, and an error for anything that is
212
- not a v7, because a v4's first six bytes are random and would otherwise read back as a
213
- plausible date. `hasUuidV7Entropy` answers whether the 74 random bits are anything but
214
- all-zero or all-one. This rejects obvious degeneracy; it does not measure unpredictability.
215
- - `createMaskSchema` builds a schema from a seed; `createMaskSchemaAsync` adds cooperative cancellation; `DEFAULT_MASK_SCHEMA` is the one a codec uses
216
- when you pass no `mask`, exported so `mask: DEFAULT_MASK_SCHEMA` can be a visible choice rather
217
- than an omission. `UUID_V7_SENTINEL_DEFINITIONS` is the default sentinel list.
218
- - `createUuidV7Generator(options)` builds a generator from your own `clock` and `fillRandom`, for
219
- a `generator:` codec option. Its options type is `UuidV7GeneratorOptions`.
220
- - `UuidSlugError` and its subclass `UuidRuntimeError`, which is what the generators throw when the
221
- runtime has no usable randomness. `UuidSlugErrorCode` types the `code` property.
222
-
223
- ### Codec options
152
+ A plain slug is the UUID's 16 bytes in base64url (22 characters) or base32hex (26), with no key.
153
+ Use `uuidStringToPlainSlug` to encode a UUID and `plainSlugToUuidString` to recover it.
154
+ Decoders reject `=` padding and nonzero unused bits in the last character.
155
+ `isPlainUuidSlug` checks canonical spelling and returns a boolean.
224
156
 
225
- ```ts
226
- createUuidSlugCodec({
227
- mask: { seed: "…", keyIterations: 1 }, // or your own { id, mix } schema
228
- sentinels: [{ name: "nil", uuid: "…" }],
229
- previousMasks: [{ seed: "…previous seed…" }],
230
- acceptUnmaskedSlugs: false,
231
- slugAlphabet: "base32hex", // plain slugs only; masked slugs and sentinels stay base64url
232
- generator: myUuidV7Generator,
233
- });
234
- ```
157
+ Pass `BASE32HEX` to a plain-slug writer, for example `generatePlainUuidV7Slug(BASE32HEX)`; see [ordering](#ordering-and-key-distribution).
235
158
 
236
- The current masked format is fixed: 22 base64url characters, including a 16-bit check.
237
- Changing `slugAlphabet` affects plain slugs only.
159
+ `uuidToString` infers the alphabet from the length automatically, 22 or 26, so old slugs survive alphabet changes.
160
+ It returns lowercase UUID text by default.
161
+ Decode before comparing IDs or building cache keys: different spellings can identify the same record.
162
+ Preserve base64url case; lowercasing changes the value.
238
163
 
239
- To supply a different mixing implementation, pass a `MaskSchema`: an `id` and
240
- `mix(input, output, forward)`, where `forward: false` must reverse `forward: true` for every
241
- 16-byte input. Construction runs round-trip smoke tests and throws if they fail. Passing them
242
- is not a proof of invertibility; the caller remains responsible for the complete domain.
164
+ ### Masked slugs
243
165
 
244
- `createMaskSchema({ seed, keyIterations })` returns an error for invalid seed options.
245
- `createUuidSlugCodec` throws for invalid options, including a supplied schema that fails its
246
- smoke tests. Build a seed schema first when you want to inspect its returned error.
166
+ _Examples: `ap225Qa_y6wN5LQCJgwH0z` (base64url), `daerdp86nv5qo3f4mg12c307qco` (base32hex)_
247
167
 
248
- For expensive derivation, await `createMaskSchemaAsync` and pass the completed schema to the codec:
168
+ Hide UUIDv7 timestamps and other standard fields with a reusable masking codec.
169
+ Codecs default to base64url; set `maskedSlugAlphabet: BASE32HEX` for lowercase filenames.
249
170
 
250
- ```ts
251
- import { createMaskSchemaAsync, createUuidSlugCodec } from "@anizoptera/uuid-slug";
171
+ Supply either `maskSeed` or `mask`; neither or both returns `invalid_mask`.
172
+ Use `maskSeed` for a secret; `mask` accepts a derived mask, derivation options or `UUID_V7_TEST_MASK`. **Anyone can decode IDs made with that public test mask! AVOID USING IT IN PRODUCTION!**
252
173
 
253
- const controller = new AbortController();
254
- const schema = await createMaskSchemaAsync({
255
- seed, // the same stored secret used by the synchronous constructor
256
- keyIterations, // preserve the setting used for issued slugs
257
- signal: controller.signal, // optional; call controller.abort(reason) to stop
174
+ ```ts
175
+ import {
176
+ createUuidV7MaskingCodec,
177
+ isUuidSlugError,
178
+ UUID_V7_TEST_MASK,
179
+ } from "@anizoptera/uuid-slug";
180
+ import type { MaskedOrSentinelUuidV7Slug, UuidSlugError, UuidV7MaskingCodec } from "@anizoptera/uuid-slug";
181
+
182
+ const maskingCodec: UuidV7MaskingCodec | UuidSlugError = createUuidV7MaskingCodec({
183
+ mask: UUID_V7_TEST_MASK,
258
184
  });
259
- if (schema instanceof Error) throw schema;
260
- const codec = createUuidSlugCodec({ mask: schema });
185
+
186
+ if (isUuidSlugError(maskingCodec)) {
187
+ console.error(maskingCodec.message);
188
+ } else {
189
+ const storedUuid = "0198abcd-1234-7abc-9def-0123456789ab";
190
+ const slug: MaskedOrSentinelUuidV7Slug | UuidSlugError = maskingCodec.uuidToMaskedSlug(storedUuid);
191
+ if (typeof slug === "string") console.log(slug);
192
+ else console.error(slug.message);
193
+ }
261
194
  ```
262
195
 
263
- The async form derives the same keys and accepts the same seed settings. It splits encoding,
264
- packing and hashing into cooperative work slices, allowing host tasks to run during long
265
- construction. Cancellation stops derivation and returns `UuidSlugError` with code `aborted` and
266
- `signal.reason` as its cause. Invalid options return `invalid_mask_schema`; unexpected construction
267
- failures retain their cause. No partially derived schema is returned.
196
+ Construct and check the codec once; reuse it to avoid per-ID key derivation.
197
+ Its methods need no `bind`. The public test mask makes this example reproducible; production codecs need a private seed.
198
+ Masking accepts UUIDv7s from other generators and preserves all their payload bits.
199
+ For new IDs, `maskingCodec.generateUuidV7WithMaskedSlug()` returns the UUID and slug together;
200
+ `maskingCodec.generateMaskedUuidV7Slug()` returns just the slug. Both can return `UuidSlugError`.
201
+ [Async mask derivation](docs/api.md#masking-codec-options) lets other work run during long setup and supports cancellation.
202
+
203
+ Generate a random seed, for example with `openssl rand -base64 32`, and keep it outside source control.
204
+ Seeds need at least 16 bytes; length alone does not prevent offline guessing from known UUID/slug pairs.
268
205
 
269
- Options are captured when called. Byte seeds are copied before the first suspension, so later
270
- caller mutation cannot change the key; synchronize concurrent writes to shared backing memory.
271
- The initial copy of a very large byte seed, allocation, GC and host scheduling can exceed the
272
- responsiveness target. Small derivations need no host yield. Construct once and reuse the schema;
273
- passing seed options to each new codec would repeat derivation.
206
+ Changing the seed or `keyDerivationIterations` changes keys. Keep old mask settings and range starts
207
+ in `previousMasks` while old slugs must work. Retain each live format's sentinel definitions too.
208
+ New slugs use current keys. Deploy both readers before switching writers; bookmarks still need
209
+ their old decoder. See [migration](docs/api.md#changing-an-existing-id-format).
210
+ `keyDerivationIterations` defaults to `1`. More iterations increase setup and guessing costs;
211
+ they do not make a human-chosen seed suitable.
274
212
 
275
- `previousMasks` is how you rotate a seed. Decoding tries `mask` first, then each entry in the
276
- order you list them, and the first whose check passes wins — so put the newest first, and keep
277
- the list short. Nothing else is ever tried: a codec decodes with the schemas you gave it and no
278
- others.
213
+ Masking covers roughly 139 years from `timestampRangeStartUnixMs`. The default starts at the
214
+ Unix epoch and ends in May 2109. Outside that range, masking returns `invalid_timestamp` rather
215
+ than lose timestamp bits. Plain slugs and sentinels retain the full UUIDv7 range.
216
+ See [exact bounds and range configuration](docs/design.md#representations-and-bit-budget).
279
217
 
280
- ### Changing an existing ID format
218
+ ### Sentinels
281
219
 
282
- Preserve the UUID; change only how it is encoded. Do not generate a replacement UUID when
283
- converting an existing ID: references and stored records must still identify the same object.
220
+ Reserve UUIDv7 values that stay recognizable in logs: codecs write them as plain slugs,
221
+ even after key rotation. Codecs have none by default. Keep their definitions unchanged while
222
+ their slugs remain in use. See [sentinel setup and collision handling](docs/api.md#sentinels).
284
223
 
285
- Deploy readers that accept both formats before any writer issues the new format. Include
286
- background jobs, cached clients and extensions in that rollout. After switching writers, keep
287
- compatible readers available for rollback: an old-only reader cannot read newly issued IDs.
224
+ ## Work with UUID bytes
288
225
 
289
- Updating the database does not update bookmarks, shared links, cookies or client storage.
290
- Remove compatibility only when the old IDs in those places no longer need to work.
291
- No recent legacy traffic does not prove that old links are gone. To keep old URLs after removing
292
- their decoder, retain an application-owned mapping from each supported old slug to its UUID.
226
+ Generation can write an ID into an existing binary record:
227
+
228
+ ```ts
229
+ import { generateUuidV7Bytes, isUuidSlugError } from "@anizoptera/uuid-slug";
230
+ import type { UuidSlugError } from "@anizoptera/uuid-slug";
231
+
232
+ const record: Uint8Array = new Uint8Array(32);
233
+ const result: Uint8Array | UuidSlugError = generateUuidV7Bytes(record, 8);
234
+ if (isUuidSlugError(result)) console.error(result.message);
235
+ else console.log(result); // The same record, with its ID at bytes 8 through 23.
236
+ ```
293
237
 
294
- Keep keys and sentinel definitions stable throughout the rollout. Non-v7 UUIDs and UUIDv7s
295
- timestamped at or beyond 2^42 ms cannot use the current masked format; preserve them as UUIDs
296
- or direct slugs. Never truncate the timestamp or substitute a new identity to make masking pass.
238
+ Write directly into your database or protocol buffer with `uuidStringToBytes`,
239
+ `plainSlugToUuidBytes` or `maskingCodec.maskedSlugToUuidBytes`. Pass the array and offset;
240
+ the call returns your array and leaves other bytes unchanged. Failed validation leaves the buffer unchanged.
241
+ See [buffer examples and accepted byte forms](docs/api.md#work-with-uuid-bytes).
297
242
 
298
- ### Reading original slugs during migration
243
+ ## Parse once for repeated work
299
244
 
300
- Create a migration reader from your codec. Enable only the old formats your application issued:
245
+ `parseUuid` validates and decodes an ID once for repeated conversion and inspection.
246
+ It returns an immutable `Uuid` object, not a string. Changes to its byte outputs leave the retained UUID unchanged.
301
247
 
302
248
  ```ts
303
- const reader = ids.migration({ original: true, plain: true });
304
- const uuid = reader.decode(incomingSlug);
305
- if (uuid instanceof Error) throw uuid;
306
- // Look up uuid and check the caller's access to the record.
249
+ import { isUuidSlugError, parseUuid } from "@anizoptera/uuid-slug";
250
+ import type { PlainUuidSlug, Uuid, UuidBytes, UuidInspection, UuidSlugError } from "@anizoptera/uuid-slug";
251
+
252
+ const input = "0198abcd-1234-7abc-9def-0123456789ab";
253
+ const uuid: Uuid | UuidSlugError = parseUuid(input);
254
+ if (isUuidSlugError(uuid)) {
255
+ console.error(uuid.message);
256
+ } else {
257
+ const bytes: UuidBytes = uuid.toBytes();
258
+ const slug: PlainUuidSlug = uuid.toPlainSlug();
259
+ const details: UuidInspection = uuid.inspect();
260
+ console.log(bytes, slug, details);
261
+ }
307
262
  ```
308
263
 
309
- `original` accepts the original fixed permutation/XOR format with its 4-bit checksum.
310
- It does **not** accept the different masked format from package version 0.2.0.
311
- `plain` accepts direct UUID slugs of any version, including old base64url spellings whose
312
- last four bits were ignored. Ordinary `slugToUuid` remains strict about those trailing bits.
313
- Neither option changes generation, ordinary codec methods, keys or sentinels.
264
+ ## Assign IDs before saving or syncing
314
265
 
315
- `decode` returns one UUID or `UuidSlugError`: sentinels first, then current keys, then enabled
316
- original and plain formats. A successful decode still needs a record lookup. The same slug can
317
- decode to different UUIDs in different formats; the original check has only four bits.
266
+ Create IDs before saving, even offline. Related records can reference them without a database round
267
+ trip and keep them after synchronization. No central allocator or worker number is needed.
268
+ Any generator works, e.g. `generateUuidV7()`, wherever the record is created.
318
269
 
319
- When you know the input format, name it to avoid trying unrelated formats:
270
+ ## Generate at a recorded time
271
+
272
+ Set `at` on UUIDv7 generation calls to encode a record's time instead of now.
273
+ It accepts a `Date`, Unix milliseconds, zoned ISO text, Temporal-style instants and
274
+ `{ seconds, nanoseconds }` timestamps without manual conversion.
275
+ See [accepted time forms and configured fractional precision](docs/api.md#supplied-time).
320
276
 
321
277
  ```ts
322
- const uuid = reader.decode(oldSlug, "original"); // "plain" or "current" also works
323
- if (uuid instanceof Error) throw uuid;
324
- const replacement = ids.uuidV7ToMaskedSlug(uuid);
325
- if (replacement instanceof Error) throw replacement;
326
- // Keep uuid in the database; use replacement in new links.
278
+ import { BASE32HEX, generatePlainUuidV7Slug } from "@anizoptera/uuid-slug";
279
+ import type { PlainUuidV7Slug, UuidSlugError } from "@anizoptera/uuid-slug";
280
+
281
+ const recordedAt = "2026-01-01T12:00:00Z"; // Also accepts Date or Unix milliseconds.
282
+ const slug: PlainUuidV7Slug | UuidSlugError = generatePlainUuidV7Slug({ at: recordedAt, alphabet: BASE32HEX });
283
+ if (typeof slug === "string") console.log(slug);
284
+ else console.error(slug.message);
327
285
  ```
328
286
 
329
- Enable an old format before selecting it. Recognized sentinels always return their reserved UUID,
330
- including old trailing-bit aliases when reading original or plain slugs.
287
+ Use one `createUuidV7Generator` generator across output forms to share a sequence, including `at` calls.
288
+ Module-level calls remain independent.
289
+
290
+ Calls use fresh randomness even at identical timestamps. For retries, retain the first ID or
291
+ use a deduplication key; existing records keep their UUIDs. Masked IDs need a
292
+ [timestamp range](#masked-slugs) covering the recorded time.
293
+
294
+ To keep IDs in order, a generator may encode a time slightly after the one you supplied.
295
+
296
+ ## Use the UUID as the timestamp source
331
297
 
332
- For unknown formats, use `candidates` to find the matching record without guessing:
298
+ Read UUIDv7's millisecond timestamp without a database lookup or UUID-text conversion.
299
+ If it is the time you need, omit a separate field:
333
300
 
334
301
  ```ts
335
- const candidates = reader.candidates(incomingSlug);
336
- if (candidates instanceof Error) throw candidates;
337
- const matches = candidates.length ? await findRecordsByUuids(candidates) : [];
338
- if (matches.length === 0) throw new Error("ID not found");
339
- if (matches.length !== 1) throw new Error("ID matches multiple records; supply its original format");
340
- const record = matches[0];
341
- // Check access to record before returning it.
302
+ import { extractUuidV7UnixMs } from "@anizoptera/uuid-slug";
303
+ import type { UuidSlugError } from "@anizoptera/uuid-slug";
304
+
305
+ const incomingId = "AZirzRI0eryd7wEjRWeJqw";
306
+ const unixMs: number | UuidSlugError = extractUuidV7UnixMs(incomingId);
307
+ if (typeof unixMs === "number") console.log(unixMs);
308
+ else console.error(unixMs.message);
342
309
  ```
343
310
 
344
- `findRecordsByUuids` is your database query. Return distinct records by UUID. `candidates`
345
- returns distinct UUIDs in decoding order, or an empty array if none match. Malformed input and
346
- failed mask callbacks return an error. Callback errors keep their cause; they never produce a
347
- successful but incomplete list.
348
- An old sentinel alias can also be a current masked ID. `candidates` retains both UUIDs;
349
- `decode` keeps sentinel priority.
311
+ `extractUuidV7UnixMs(bytes, offset)` reads from a larger buffer.
312
+ `maskingCodec.extractMaskedUuidV7UnixMs(slug)` recovers a masked timestamp with the codec's keys.
313
+ UUIDv4 has no timestamp and is rejected.
314
+
315
+ For known fraction and counter layouts, use [payload extraction](docs/api.md#uuidv7-payload-fields).
316
+
317
+ Keep separate fields for other dates, finer precision, editable times or queries the UUID index
318
+ cannot serve. Changing the timestamp changes the ID.
319
+
320
+ ## Ordering and key distribution
321
+
322
+ Base64url UUIDv7 slugs are almost time-ordered: nearby timestamps have similar prefixes.
323
+ ASCII sorting can reverse them: `AAAAAAAz` and `AAAAAAA0` encode consecutive milliseconds,
324
+ but the second prefix sorts first.
325
+
326
+ Base32hex preserves UUID byte order: its alphabet, `0-9a-v`, follows numeric order, with the
327
+ most significant bits first. Equal-length slugs sort by timestamp even across field boundaries.
328
+ Clocks can move backwards, and UUIDv7 does not promise creation order within a millisecond.
329
+ Compare one spelling at a time; database collations and natural file sorting can differ from ASCII.
330
+
331
+ `uuidV7StringBounds(startMs, endMs)` builds inclusive bounds for time-range queries on UUID keys.
332
+ The bounds cover every UUIDv7 in the interval, regardless of its payload.
333
+ For one millisecond, use `uuidV7StringBounds(ms)`. Compare in UUID wire-byte order;
334
+ SQL Server's `uniqueidentifier` uses a different order.
335
+
336
+ Decode masked filenames or store dates separately to sort them chronologically.
337
+
338
+ Changing public URLs leaves the UUID index unchanged. For hash partitioning, hash the UUID
339
+ so a spelling change does not move the record.
340
+
341
+ With unchanged settings, built-in masking gives the same UUID the same slug: URLs and filenames
342
+ stay stable, and repeated uses are recognizable. Rotation can change the slug;
343
+ compare decoded UUIDs to identify the same record.
344
+
345
+ ## Masking security
346
+
347
+ Masking hides UUIDv7 fields; the matching key restores them. Its cryptographic strength is not established,
348
+ including against attacks using known UUID/slug pairs. See the [design](docs/design.md)
349
+ and [security limits](docs/security.md).
350
350
 
351
- Keep this reader while old inputs must work. Replace it with `ids.migration({ plain: true })`
352
- to stop trying the original mask, or `ids.migration({ original: true })` to stop plain decoding.
353
- `ids.migration()` tries only current keys and sentinels. Removing the migration reader entirely
354
- leaves ordinary codec decoding unchanged. Neither method can identify the issuing format from
355
- the slug alone, so successful decoding is not a reliable count of legacy traffic.
351
+ An incorrect key can pass the 16-bit check and return the wrong UUID.
352
+ Keep the rotation list short and confirm decoded IDs against your records;
353
+ see the [record lookup example](docs/security.md#masking).
356
354
 
357
- ### Rejecting stale ids
355
+ A browser can use your service's masked IDs without the seed. Keep private masking and decoding
356
+ on the service; client code exposes the seed. Plain generation and conversion need no seed.
357
+
358
+ ## Handling errors
359
+
360
+ Conversions return `T | UuidSlugError` and pass errors through unchanged.
361
+ Async mask construction resolves to the same union.
362
+ Compatible chains need one final check. For string results, `typeof result === "string"`
363
+ keeps the branded string type; the other branch is `UuidSlugError`.
364
+ Use `isUuidSlugError` for object results or unknown input. It recognizes package errors
365
+ across realms and package copies.
358
366
 
359
367
  ```ts
360
- import { validateUuidV7Fresh } from "@anizoptera/uuid-slug";
368
+ import { isUuidSlugError, uuidStringToBytes } from "@anizoptera/uuid-slug";
369
+ import type { UuidBytes, UuidSlugError } from "@anizoptera/uuid-slug";
361
370
 
362
- const ok = validateUuidV7Fresh(uuid, { windowMs: 60_000 });
371
+ const bytes: UuidBytes | UuidSlugError = uuidStringToBytes("0198abcd-1234-7abc-9def-0123456789ab");
372
+ if (isUuidSlugError(bytes)) console.error(bytes.code, bytes.message);
373
+ else console.log(bytes);
363
374
  ```
364
375
 
365
- The timestamp must be inside the inclusive interval `now() - windowMs` through
366
- `now() + windowMs`; the default radius is 24 hours. `windowMs` must be finite and nonnegative;
367
- zero and finite fractions are valid. `now` defaults to `Date.now`, must return finite Unix
368
- milliseconds, and is read once per validation. Invalid settings return an error instead of
369
- disabling the check. Degenerate all-zero or all-one random bits are also rejected.
376
+ Check intermediate results only when you also need their values.
370
377
 
371
- `validateUuidV7SlugFresh` starts from a plain slug; `codec.validateMaskedSlugFresh` starts from
372
- a slug decoded with that codec. This is a symmetric timestamp sanity check, not past-only expiry,
373
- authentication, or replay prevention. Use ordinary decoding for permanent identifiers. For links
374
- with expiration or one-time use, check the stored expiry and consumption state as well.
378
+ Handle errors by `code`, with constants such as `INVALID_BUFFER` and the `UuidSlugErrorCode` type.
379
+ Use `message` for diagnostics; wording can change while codes stay stable.
380
+ Failed entropy draws, clock readings and custom transforms retain their exception as `cause`.
381
+
382
+ ## API
383
+
384
+ Use the [TypeScript reference](docs/api.md) for [types](docs/api.md#types), [call signatures](docs/api.md#api), [codec options](docs/api.md#masking-codec-options), [migration](docs/api.md#reading-original-slugs-during-migration) and [timestamp windows](docs/api.md#validating-timestamp-windows).
385
+ Each export also documents its accepted input, result and failures in JSDoc.
386
+
387
+ ## TypeScript API map
388
+
389
+ | Job | Main TypeScript API |
390
+ | --- | --- |
391
+ | Generate UUIDv4 | `generateUuidV4`, `generateUuidV4Bytes`, `generatePlainUuidV4Slug`, `generateUuidV4WithRandomFill` |
392
+ | Generate UUIDv7 | `generateUuidV7`, `generateUuidV7Bytes`, `generatePlainUuidV7Slug` |
393
+ | Generate one UUIDv7 with its slug | `generateUuidV7WithPlainSlug`, `maskingCodec.generateUuidV7WithMaskedSlug` |
394
+ | Generate an immutable UUIDv7 value | `generateUuidV7Value`, or its generator and masking-codec methods |
395
+ | Control UUIDv7 time, sequence, rollback, or entropy | `createUuidV7Generator`, `createUuidV7GeneratorWithRandomFill` |
396
+ | Convert UUID text, bytes, and plain slugs | `uuidToString`, `uuidToBytes`, `uuidToPlainSlug`, plus source-specific converters |
397
+ | Parse once for repeated work | [`parseUuid`](#parse-once-for-repeated-work) returns an immutable `Uuid` object |
398
+ | Inspect version, variant, timestamp, or payload | `Uuid.inspect`, `extractUuidVersion`, `extractUuidV7UnixMs`, `extractUuidV7Payload` |
399
+ | Narrow untrusted input | `isUuidText`, `isUuidString`, `isUuidBytes`, `isPlainUuidSlug`, their v4/v7 guards, and `isUuidSlugError` |
400
+ | Build UUIDv7 database range keys | `uuidV7StringBounds`, `uuidV7ByteBounds` |
401
+ | Validate a UUIDv7 timestamp window | `validateUuidV7StringUnixMs` and the plain or masked slug equivalents |
402
+ | Derive UUIDv7 masks, with optional async cancellation | `deriveUuidV7Mask`, `deriveUuidV7MaskAsync` |
403
+ | Use an application-defined reversible masking transform | [`createCustomUuidV7Mask`](docs/api.md#masking-codec-options) |
404
+ | Mask, unmask, rotate keys, or reserve sentinels | `createUuidV7MaskingCodec` and its methods |
405
+ | Read explicitly enabled old formats | `maskingCodec.createUuidSlugMigrationDecoder` |
406
+
407
+ Types catch UUID-version and plain/masked mix-ups; results retain text case and buffer ownership.
408
+ Generator, masking-codec and migration methods need no `this` binding.
375
409
 
376
410
  ## Guarantees
377
411
 
378
- These are API contracts. Runtime measurements and their exercised conditions belong in
379
- [`bench/README.md`](bench/README.md); a benchmark pass is not proof of every guarantee.
380
-
381
- - **Conformance.** Generated ids have RFC 9562 version and variant bits. A custom generator is
382
- responsible for honoring its declared contract.
383
- - **Randomness.** Built-in portable generation draws from Web Crypto or `node:crypto`, never
384
- `Math.random`. Native generation delegates to the platform; a caller-supplied `fillRandom`
385
- controls its own entropy. Collisions are possible: enforce uniqueness in storage when required.
386
- - **Time ordering, to the millisecond.** A v7 carries a 48-bit millisecond timestamp in its
387
- leading bits, so UUID strings sort by their encoded timestamps across different milliseconds.
388
- Backfilled timestamps or a clock adjustment need not reflect generation order.
389
- - **NOT ordered within a millisecond.** Two ids created in the same millisecond may sort in
390
- either order. RFC 9562 §6.2 permits different counter and random-bit strategies. Do not use a v7
391
- to recover the order of events inside a millisecond; use a sequence column.
392
- - **Sortable as a slug only in base32hex.** A 26-character base32hex slug compares as a plain
393
- string in creation order, to the same millisecond granularity as the guarantee above: its digits
394
- are in ASCII order and a v7 leads with its timestamp. That is the whole reason the alphabet is
395
- offered.
396
- - **NOT sortable as a base64url slug.** The default 22-character form is the same 16 bytes in a
397
- shorter alphabet, and the value round-trips exactly — but that alphabet runs `A-Za-z0-9-_`, so
398
- its character order and its value order disagree. Sort by the UUID, or by a timestamp column. A
399
- masked slug has no chronological ordering; masking always uses base64url.
400
- - **One type for owned bytes.** Without an output buffer, byte generators return a plain
401
- `Uint8Array`, never a platform-specific subclass. With an output buffer, they return that same
402
- caller-owned array and write only the requested UUID range.
403
- - **You pay for masking only if you mask.** The keyless operations — generating an id, converting
404
- between a UUID and a plain slug — reach no codec, so a bundle that imports only those carries
405
- none of the cipher, key derivation, or sentinel table. Use named imports with a tree-shaking
406
- bundler; loading the complete module namespace does not promise that removal.
412
+ - Generated IDs have RFC 9562 version and variant bits.
413
+ - Built-in generators use cryptographically secure runtime randomness without weaker fallbacks. If it is unavailable, generation with no arguments or only a text-case or alphabet argument throws `UuidSlugError` with code `rng_unavailable`. Calls with explicit time, a generator, caller output or custom entropy return it.
414
+ - UUIDs **can** still collide even with a very low probability. Use a uniqueness constraint where duplicates could overwrite or misidentify critical data. On conflict creating a record, keep the existing record and generate a new ID.
415
+ - Default calls retain the selected native generator's ordering and clock behavior.
416
+ Use a created generator to control ordering and clock rollback. Native failures fall back to
417
+ the package's generator; if both fail, the error retains both causes.
418
+ - UUIDv7 starts with a 48-bit millisecond timestamp, so UUID strings sort by encoded time across
419
+ different milliseconds. Backfills and clock adjustments can differ from generation order.
420
+ - Successful current-time calls on one created generator strictly increase in UUID byte order
421
+ under the default `clockRollback` policy, `"preserve"`; `at` calls share its sequence state. Module-level
422
+ generation and `"reset"` calls beyond their tolerance do not guarantee this order. Independent generators,
423
+ package copies, workers and processes have separate state; use a sequence column for ordering across them.
424
+ - Plain slugs preserve all UUID bits. Base32hex UUIDv7 slugs sort by timestamp across different
425
+ milliseconds under ASCII comparison. Base64url UUIDv7 slugs are almost time-ordered;
426
+ [ASCII sorting can reverse them](#ordering-and-key-distribution). Masked slugs have no chronological order.
427
+ - Byte generators return a new plain `Uint8Array` or your supplied array, writing only the requested range.
428
+ - `uuidStringToBytes` and `plainSlugToUuidBytes` validate the whole identifier before writing.
429
+ Invalid text or destination ranges return an error without changing caller storage.
430
+ - Named root imports let supported bundlers remove the cipher, key derivation, sentinel table,
431
+ and unrelated generation code.
432
+ - A UUIDv7 masking codec requires explicit private mask options or a package-produced mask.
433
+ Use `UUID_V7_TEST_MASK` explicitly for the public test key; omission does not select it.
407
434
 
408
435
  ## Runtime
409
436
 
410
- No runtime dependencies, on any platform.
437
+ The npm package uses ES modules. Native APIs and portable TypeScript are selected automatically for each runtime and output, so the caller code does not need to choose or coordinate the implementations. When the runtime supports it, the implementation is chosen statically through the `package.json` exports.
438
+
439
+ The [Rust crate](rust/uuid-slug) uses the same identifier formats. Cross-language masked reads require matching seeds, iteration counts and timestamp ranges; see [cross-language contracts](docs/cross-language.md).
440
+
441
+ | Runtime | Package code |
442
+ | --- | --- |
443
+ | Node 20 and newer (also works from 16.20) | Uses compiled JavaScript |
444
+ | Bun 1.0.8 and newer | Uses TypeScript source |
445
+ | Deno 1.29 and newer | Compiled JavaScript; no flag or import map needed |
446
+ | Cloudflare Workers, browsers and other compatible runtimes | Compiled JavaScript over Web Crypto |
447
+
448
+ Bun's native UUIDv7 timestamp can advance ahead of the clock during bursts. Create a generator to control ordering, clock policy or payload layout.
449
+
450
+ Conversion and timestamp extraction need no randomness, so read-only tools and static builds can use them. Generation needs secure randomness.
451
+
452
+
453
+ ## Upgrades and support
454
+
455
+ Check the [changelog](CHANGELOG.md) and the [release policy](docs/release.md) before upgrading.
456
+
457
+ Supported identifier formats remain readable across upgrades. Retain the [matching mask settings and migration readers](docs/api.md#changing-an-existing-id-format) for stored masked IDs.
458
+
459
+ Plain slugs recover standard UUIDs without keys or this library. Masked IDs need their keys, range settings and sentinel definitions; custom masks also need their transform implementation.
460
+
461
+ The built-in [wire format](docs/design.md) is documented for independent decoders.
462
+
463
+ Report bugs through [GitHub issues](https://github.com/Anizoptera/uuid-slug/issues).
411
464
 
412
- - **Bun** uses `Bun.randomUUIDv7`.
413
- - **Node** uses native `crypto.randomUUID`, and native `crypto.randomUUIDv7` where the
414
- version provides it, otherwise the bundled v7 generator.
415
- - **Browsers and Deno** use Web Crypto for randomness plus the bundled v7 generator.
416
465
 
417
466
  ## License
418
467