@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.
- package/LICENSE +54 -31
- package/README.md +373 -324
- package/dist/alphabet.d.ts +5 -17
- package/dist/alphabet.d.ts.map +1 -1
- package/dist/alphabet.js +146 -112
- package/dist/alphabet.js.map +1 -1
- package/dist/base64url-name.d.ts +7 -0
- package/dist/base64url-name.d.ts.map +1 -0
- package/dist/base64url-name.js +8 -0
- package/dist/base64url-name.js.map +1 -0
- package/dist/errors.d.ts +50 -9
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +145 -63
- package/dist/errors.js.map +1 -1
- package/dist/feistel.js +29 -95
- package/dist/feistel.js.map +1 -1
- package/dist/generation-options.js +20 -0
- package/dist/generation-options.js.map +1 -0
- package/dist/index.d.ts +22 -10
- package/dist/index.js +21 -9
- package/dist/instant.js +83 -0
- package/dist/instant.js.map +1 -0
- package/dist/mask-handle.d.ts +16 -0
- package/dist/mask-handle.d.ts.map +1 -0
- package/dist/mask-handle.js +60 -0
- package/dist/mask-handle.js.map +1 -0
- package/dist/mask.d.ts +27 -0
- package/dist/mask.d.ts.map +1 -0
- package/dist/mask.js +151 -95
- package/dist/mask.js.map +1 -1
- package/dist/masking-codec-protocol.js +23 -0
- package/dist/masking-codec-protocol.js.map +1 -0
- package/dist/masking-codec-types.d.ts +245 -0
- package/dist/masking-codec-types.d.ts.map +1 -0
- package/dist/masking-codec.d.ts +19 -0
- package/dist/masking-codec.d.ts.map +1 -0
- package/dist/masking-codec.js +391 -0
- package/dist/masking-codec.js.map +1 -0
- package/dist/migration.js +114 -51
- package/dist/migration.js.map +1 -1
- package/dist/node/runtime.js +39 -0
- package/dist/node/runtime.js.map +1 -0
- package/dist/payload.d.ts +7 -0
- package/dist/payload.d.ts.map +1 -0
- package/dist/payload.js +118 -0
- package/dist/payload.js.map +1 -0
- package/dist/runtime/pool.js +21 -46
- package/dist/runtime/pool.js.map +1 -1
- package/dist/runtime/portable.js +27 -0
- package/dist/runtime/portable.js.map +1 -0
- package/dist/sentinel.js +10 -0
- package/dist/sentinel.js.map +1 -0
- package/dist/siphash.js +20 -99
- package/dist/siphash.js.map +1 -1
- package/dist/slug.d.ts +169 -0
- package/dist/slug.d.ts.map +1 -0
- package/dist/slug.js +268 -0
- package/dist/slug.js.map +1 -0
- package/dist/timestamp.d.ts +19 -0
- package/dist/timestamp.d.ts.map +1 -0
- package/dist/timestamp.js +44 -0
- package/dist/timestamp.js.map +1 -0
- package/dist/types.d.ts +480 -200
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +8 -0
- package/dist/types.js.map +1 -0
- package/dist/uuid-value-protocol.js +46 -0
- package/dist/uuid-value-protocol.js.map +1 -0
- package/dist/uuid-value.d.ts +17 -0
- package/dist/uuid-value.d.ts.map +1 -0
- package/dist/uuid-value.js +127 -0
- package/dist/uuid-value.js.map +1 -0
- package/dist/uuid.d.ts +51 -64
- package/dist/uuid.d.ts.map +1 -1
- package/dist/uuid.js +203 -199
- package/dist/uuid.js.map +1 -1
- package/dist/v4-slug.d.ts +16 -0
- package/dist/v4-slug.d.ts.map +1 -0
- package/dist/v4-slug.js +16 -0
- package/dist/v4-slug.js.map +1 -0
- package/dist/v4.d.ts +42 -0
- package/dist/v4.d.ts.map +1 -0
- package/dist/v4.js +85 -0
- package/dist/v4.js.map +1 -0
- package/dist/v7-bounds.d.ts +36 -0
- package/dist/v7-bounds.d.ts.map +1 -0
- package/dist/v7-bounds.js +49 -0
- package/dist/v7-bounds.js.map +1 -0
- package/dist/v7-generator-input.js +75 -0
- package/dist/v7-generator-input.js.map +1 -0
- package/dist/v7-generator.d.ts +43 -0
- package/dist/v7-generator.d.ts.map +1 -0
- package/dist/v7-generator.js +105 -0
- package/dist/v7-generator.js.map +1 -0
- package/dist/v7-keyless.d.ts +46 -0
- package/dist/v7-keyless.d.ts.map +1 -0
- package/dist/v7-keyless.js +106 -0
- package/dist/v7-keyless.js.map +1 -0
- package/dist/v7-payload.js +54 -0
- package/dist/v7-payload.js.map +1 -0
- package/dist/v7-slug.d.ts +46 -0
- package/dist/v7-slug.d.ts.map +1 -0
- package/dist/v7-slug.js +127 -0
- package/dist/v7-slug.js.map +1 -0
- package/dist/v7-timestamp.js +9 -0
- package/dist/v7-timestamp.js.map +1 -0
- package/dist/v7-value-options.js +28 -0
- package/dist/v7-value-options.js.map +1 -0
- package/dist/v7-value.d.ts +23 -0
- package/dist/v7-value.d.ts.map +1 -0
- package/dist/v7-value.js +31 -0
- package/dist/v7-value.js.map +1 -0
- package/dist/v7.js +127 -171
- package/dist/v7.js.map +1 -1
- package/package.json +15 -8
- package/src/alphabet.ts +456 -27
- package/src/base64url-name.ts +5 -0
- package/src/errors.ts +373 -37
- package/src/feistel.ts +69 -56
- package/src/generation-options.ts +48 -0
- package/src/index.ts +134 -80
- package/src/instant.ts +196 -0
- package/src/keyless.ts +7 -134
- package/src/mask-handle.ts +141 -0
- package/src/mask.ts +354 -129
- package/src/masking-codec-protocol.ts +29 -0
- package/src/masking-codec-types.ts +380 -0
- package/src/masking-codec.ts +923 -0
- package/src/migration.ts +195 -42
- package/src/payload.ts +321 -0
- package/src/runtime/bun.ts +30 -49
- package/src/runtime/node.ts +43 -24
- package/src/runtime/pool.ts +49 -21
- package/src/runtime/portable.ts +68 -0
- package/src/runtime/types.ts +23 -35
- package/src/sentinel.ts +13 -0
- package/src/siphash.ts +5 -4
- package/src/slug.ts +884 -0
- package/src/timestamp.ts +122 -0
- package/src/types.ts +759 -205
- package/src/uuid-value-protocol.ts +77 -0
- package/src/uuid-value.ts +341 -0
- package/src/uuid.ts +514 -234
- package/src/v4-slug.ts +27 -0
- package/src/v4.ts +234 -0
- package/src/v7-bounds.ts +171 -0
- package/src/v7-generator-input.ts +169 -0
- package/src/v7-generator.ts +245 -0
- package/src/v7-keyless.ts +354 -0
- package/src/v7-payload.ts +121 -0
- package/src/v7-slug.ts +293 -0
- package/src/v7-timestamp.ts +21 -0
- package/src/v7-value-options.ts +62 -0
- package/src/v7-value.ts +54 -0
- package/src/v7.ts +377 -200
- package/dist/base64url.d.ts +0 -20
- package/dist/base64url.d.ts.map +0 -1
- package/dist/base64url.js +0 -33
- package/dist/base64url.js.map +0 -1
- package/dist/codec.d.ts +0 -17
- package/dist/codec.d.ts.map +0 -1
- package/dist/codec.js +0 -192
- package/dist/codec.js.map +0 -1
- package/dist/keyless.d.ts +0 -31
- package/dist/keyless.d.ts.map +0 -1
- package/dist/keyless.js +0 -93
- package/dist/keyless.js.map +0 -1
- package/dist/legacy-mask.js +0 -55
- package/dist/legacy-mask.js.map +0 -1
- package/dist/node/alphabet.js +0 -130
- package/dist/node/base64url.js +0 -31
- package/dist/node/codec.js +0 -190
- package/dist/node/errors.js +0 -78
- package/dist/node/feistel.js +0 -103
- package/dist/node/index.js +0 -10
- package/dist/node/keyless.js +0 -91
- package/dist/node/legacy-mask.js +0 -53
- package/dist/node/mask.js +0 -106
- package/dist/node/migration.js +0 -64
- package/dist/node/runtime/node.js +0 -33
- package/dist/node/runtime/pool.js +0 -53
- package/dist/node/schema.js +0 -214
- package/dist/node/siphash.js +0 -106
- package/dist/node/uuid.js +0 -226
- package/dist/node/v7.js +0 -185
- package/dist/node/yield.js +0 -20
- package/dist/runtime/web.js +0 -39
- package/dist/runtime/web.js.map +0 -1
- package/dist/schema.d.ts +0 -20
- package/dist/schema.d.ts.map +0 -1
- package/dist/schema.js +0 -216
- package/dist/schema.js.map +0 -1
- package/dist/v7.d.ts +0 -12
- package/dist/v7.d.ts.map +0 -1
- package/dist/yield.js +0 -22
- package/dist/yield.js.map +0 -1
- package/src/base64url.ts +0 -41
- package/src/codec.ts +0 -320
- package/src/legacy-mask.ts +0 -25
- package/src/runtime/web.ts +0 -48
- package/src/schema.ts +0 -300
- package/src/yield.ts +0 -22
package/README.md
CHANGED
|
@@ -1,418 +1,467 @@
|
|
|
1
1
|
# @anizoptera/uuid-slug
|
|
2
2
|
|
|
3
|
-
|
|
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
|
[](https://www.npmjs.com/package/@anizoptera/uuid-slug)
|
|
6
6
|
[](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml)
|
|
7
|
-
[](package.json)
|
|
8
7
|
[](package.json)
|
|
8
|
+
[](package.json)
|
|
9
|
+
[](#runtime)
|
|
10
|
+
[](#runtime)
|
|
11
|
+
[](#runtime)
|
|
9
12
|
[](LICENSE)
|
|
10
13
|
|
|
11
|
-
|
|
12
|
-
|
|
14
|
+
[](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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
|
|
25
|
-
|
|
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
|
-
|
|
29
|
-
|
|
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 {
|
|
70
|
+
import { generateUuidV7WithPlainSlug } from "@anizoptera/uuid-slug";
|
|
71
|
+
import type { GeneratedUuidV7, PlainUuidV7Slug } from "@anizoptera/uuid-slug";
|
|
35
72
|
|
|
36
|
-
const
|
|
37
|
-
|
|
73
|
+
const { uuid, slug }: GeneratedUuidV7<PlainUuidV7Slug> = generateUuidV7WithPlainSlug();
|
|
74
|
+
```
|
|
38
75
|
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
60
|
-
|
|
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
|
-
|
|
110
|
-
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
-
|
|
114
|
+
// Alternative to the typeof check: the helper recognizes returned error values.
|
|
115
|
+
if (!isUuidSlugError(slug)) console.log(slug);
|
|
122
116
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
126
|
+
All examples encode the same UUIDv7; sizes are characters except for bytes.
|
|
139
127
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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
|
-
|
|
145
|
-
|
|
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
|
-
|
|
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
|
-
|
|
151
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
150
|
+
_Examples: `AZirzRI0eryd7wEjRWeJqw` (base64url), `06canj8i6htbp7ff04hkaps9lc` (base32hex)_
|
|
169
151
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
-
|
|
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
|
-
|
|
237
|
-
|
|
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
|
-
|
|
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
|
-
`
|
|
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
|
-
|
|
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
|
-
|
|
251
|
-
|
|
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
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
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
|
-
|
|
260
|
-
|
|
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
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
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
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
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
|
-
###
|
|
218
|
+
### Sentinels
|
|
281
219
|
|
|
282
|
-
|
|
283
|
-
|
|
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
|
-
|
|
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
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
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
|
-
|
|
295
|
-
|
|
296
|
-
|
|
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
|
-
|
|
243
|
+
## Parse once for repeated work
|
|
299
244
|
|
|
300
|
-
|
|
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
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
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
|
-
|
|
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
|
-
|
|
316
|
-
|
|
317
|
-
|
|
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
|
-
|
|
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
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
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
|
-
|
|
330
|
-
|
|
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
|
-
|
|
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
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
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
|
-
`
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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
|
-
|
|
352
|
-
|
|
353
|
-
|
|
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
|
-
|
|
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 {
|
|
368
|
+
import { isUuidSlugError, uuidStringToBytes } from "@anizoptera/uuid-slug";
|
|
369
|
+
import type { UuidBytes, UuidSlugError } from "@anizoptera/uuid-slug";
|
|
361
370
|
|
|
362
|
-
const
|
|
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
|
-
|
|
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
|
-
`
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
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
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
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
|
-
|
|
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
|
|