@anizoptera/uuid-slug 0.2.0 → 0.3.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 (95) hide show
  1. package/README.md +381 -27
  2. package/dist/alphabet.d.ts +21 -0
  3. package/dist/alphabet.d.ts.map +1 -0
  4. package/dist/alphabet.js +132 -0
  5. package/dist/alphabet.js.map +1 -0
  6. package/dist/base64url.d.ts +20 -0
  7. package/dist/base64url.d.ts.map +1 -0
  8. package/dist/base64url.js +33 -0
  9. package/dist/base64url.js.map +1 -0
  10. package/dist/codec.d.ts +17 -0
  11. package/dist/codec.d.ts.map +1 -0
  12. package/dist/codec.js +192 -0
  13. package/dist/codec.js.map +1 -0
  14. package/dist/errors.d.ts +16 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +80 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/feistel.js +105 -0
  19. package/dist/feistel.js.map +1 -0
  20. package/dist/index.d.ts +11 -168
  21. package/dist/index.js +10 -649
  22. package/dist/keyless.d.ts +31 -0
  23. package/dist/keyless.d.ts.map +1 -0
  24. package/dist/keyless.js +93 -0
  25. package/dist/keyless.js.map +1 -0
  26. package/dist/legacy-mask.js +55 -0
  27. package/dist/legacy-mask.js.map +1 -0
  28. package/dist/mask.js +108 -0
  29. package/dist/mask.js.map +1 -0
  30. package/dist/migration.js +66 -0
  31. package/dist/migration.js.map +1 -0
  32. package/dist/node/alphabet.js +130 -0
  33. package/dist/node/base64url.js +31 -0
  34. package/dist/node/codec.js +190 -0
  35. package/dist/node/errors.js +78 -0
  36. package/dist/node/feistel.js +103 -0
  37. package/dist/node/index.js +10 -647
  38. package/dist/node/keyless.js +91 -0
  39. package/dist/node/legacy-mask.js +53 -0
  40. package/dist/node/mask.js +106 -0
  41. package/dist/node/migration.js +64 -0
  42. package/dist/node/runtime/node.js +33 -0
  43. package/dist/node/runtime/pool.js +53 -0
  44. package/dist/node/schema.js +214 -0
  45. package/dist/node/siphash.js +106 -0
  46. package/dist/node/uuid.js +226 -0
  47. package/dist/node/v7.js +185 -0
  48. package/dist/node/yield.js +20 -0
  49. package/dist/runtime/pool.js +55 -0
  50. package/dist/runtime/pool.js.map +1 -0
  51. package/dist/runtime/web.js +39 -0
  52. package/dist/runtime/web.js.map +1 -0
  53. package/dist/schema.d.ts +20 -0
  54. package/dist/schema.d.ts.map +1 -0
  55. package/dist/schema.js +216 -0
  56. package/dist/schema.js.map +1 -0
  57. package/dist/siphash.js +108 -0
  58. package/dist/siphash.js.map +1 -0
  59. package/dist/types.d.ts +255 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/uuid.d.ts +78 -0
  62. package/dist/uuid.d.ts.map +1 -0
  63. package/dist/uuid.js +228 -0
  64. package/dist/uuid.js.map +1 -0
  65. package/dist/v7.d.ts +12 -0
  66. package/dist/v7.d.ts.map +1 -0
  67. package/dist/v7.js +187 -0
  68. package/dist/v7.js.map +1 -0
  69. package/dist/yield.js +22 -0
  70. package/dist/yield.js.map +1 -0
  71. package/package.json +8 -12
  72. package/src/alphabet.ts +187 -0
  73. package/src/base64url.ts +28 -63
  74. package/src/codec.ts +227 -125
  75. package/src/errors.ts +83 -9
  76. package/src/feistel.ts +128 -0
  77. package/src/index.ts +52 -26
  78. package/src/keyless.ts +136 -0
  79. package/src/legacy-mask.ts +25 -0
  80. package/src/mask.ts +129 -67
  81. package/src/migration.ts +104 -0
  82. package/src/runtime/bun.ts +49 -24
  83. package/src/runtime/node.ts +33 -15
  84. package/src/runtime/pool.ts +62 -0
  85. package/src/runtime/types.ts +42 -5
  86. package/src/runtime/web.ts +37 -9
  87. package/src/schema.ts +274 -97
  88. package/src/siphash.ts +127 -0
  89. package/src/types.ts +221 -37
  90. package/src/uuid.ts +189 -50
  91. package/src/v7.ts +217 -45
  92. package/src/yield.ts +22 -0
  93. package/dist/index.d.ts.map +0 -1
  94. package/dist/index.js.map +0 -1
  95. package/dist/web/index.js +0 -648
package/README.md CHANGED
@@ -1,15 +1,23 @@
1
1
  # @anizoptera/uuid-slug
2
2
 
3
+ Use shorter UUIDs in URLs, with optional masking of UUIDv7 timestamps.
4
+
3
5
  [![npm version](https://img.shields.io/npm/v/@anizoptera/uuid-slug?label=npm)](https://www.npmjs.com/package/@anizoptera/uuid-slug)
4
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)
5
7
  [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
6
- [![Bun checked](https://img.shields.io/badge/Bun-checked-000000?logo=bun&logoColor=white)](https://bun.sh/docs/cli/test)
7
8
  [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json)
8
9
  [![License](https://img.shields.io/github/license/Anizoptera/uuid-slug)](LICENSE)
9
10
 
10
- Zero-dependency UUID v4/v7 generation, canonical parsing, 22-character base64url direct slugs, and configurable masked UUIDv7 slugs.
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.
13
+
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.
11
19
 
12
- This package does not define a new identifier scheme. Direct slugs are the same 16 UUID bytes encoded as unpadded base64url. Masked slugs are reversible obfuscation for textual transmission; they are not encryption, authentication, bearer tokens, or secret material.
20
+ It defines no new identifier scheme. Everything here is a UUID underneath.
13
21
 
14
22
  ## Install
15
23
 
@@ -17,49 +25,395 @@ This package does not define a new identifier scheme. Direct slugs are the same
17
25
  pnpm add @anizoptera/uuid-slug
18
26
  ```
19
27
 
20
- ## Usage
28
+ Requires TypeScript 5.7 or newer for `Uint8Array<ArrayBuffer>` declarations.
29
+ Custom `fillRandom` callbacks receive an ordinary `ArrayBuffer` view, which Web Crypto accepts.
30
+
31
+ ## Quick start
21
32
 
22
33
  ```ts
23
34
  import { createUuidSlugCodec } from "@anizoptera/uuid-slug";
24
35
 
25
- export const ids = createUuidSlugCodec({
26
- mask: { seed: "project-stable-obfuscation-seed" },
27
- });
36
+ const seed = process.env.ID_MASK_SEED;
37
+ if (!seed) throw new Error("Set ID_MASK_SEED to a stable, randomly generated secret.");
38
+
39
+ // Reuse the codec: the seed is expanded once, at construction.
40
+ export const ids = createUuidSlugCodec({ mask: { seed } });
28
41
 
29
42
  const publicId = ids.uuidV7MaskedSlug();
30
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.
31
46
  ```
32
47
 
33
- Create one codec per project policy and reuse it. Schema derivation and sentinel maps are precomputed at construction.
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.
34
51
 
35
- ## Sentinels
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.
36
56
 
37
- Sentinels are precomputed per codec and always use direct raw UUID slugs so they stay recognizable in logs and textual transmission.
57
+ ## Two kinds of slug
38
58
 
39
- Default sentinels:
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.
40
62
 
41
- - `00000000-0000-7000-8000-000000000000` -> `AAAAAAAAcACAAAAAAAAAAA`
42
- - `00000000-0001-7000-8000-000000000000` -> `AAAAAAABcACAAAAAAAAAAA`
43
- - `00000000-0002-7000-8000-000000000000` -> `AAAAAAACcACAAAAAAAAAAA`
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.
44
68
 
45
- ## Runtime
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.
46
73
 
47
- - Bun uses `Bun.randomUUIDv7` for v7 string, bytes, and direct slug paths.
48
- - Node uses native `crypto.randomUUID` for v4 and native `crypto.randomUUIDv7` when present; otherwise it uses the package fallback v7 generator.
49
- - Browser and Deno use Web Crypto for v4/random bytes and the fallback v7 generator.
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.
50
77
 
51
- Runtime dependencies are forbidden. Benchmark candidates are dev-only and excluded from the packed artifact.
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).
52
82
 
53
- ## Publishing
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:
54
87
 
55
- Release checks publish from a cleaned package artifact, not the source tree. The artifact check runs `publish-clean`, blocks private project files and benchmark dependencies, then runs package validators against the final cleaned npm tarball.
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.
56
96
 
57
- Use an explicit npm dist-tag:
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:
58
99
 
59
- ```bash
60
- pnpm run publish:clean
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:
107
+
108
+ ```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
+ ```
115
+
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.
120
+
121
+ ## What masking is not
122
+
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).
128
+
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.
133
+
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.
137
+
138
+ ## Handling errors
139
+
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.
143
+
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`.
147
+
148
+ ## Types
149
+
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.
152
+
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`.
163
+
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.
167
+
168
+ ## API
169
+
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
224
+
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
+ });
61
234
  ```
62
235
 
63
- The project script publishes with `--access public --tag latest --provenance`.
64
- `@anizoptera/publish-clean` is consumed from npm; regenerate `bun.lock` after
65
- the first publish-clean release exists on the registry.
236
+ The current masked format is fixed: 22 base64url characters, including a 16-bit check.
237
+ Changing `slugAlphabet` affects plain slugs only.
238
+
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.
243
+
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.
247
+
248
+ For expensive derivation, await `createMaskSchemaAsync` and pass the completed schema to the codec:
249
+
250
+ ```ts
251
+ import { createMaskSchemaAsync, createUuidSlugCodec } from "@anizoptera/uuid-slug";
252
+
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
258
+ });
259
+ if (schema instanceof Error) throw schema;
260
+ const codec = createUuidSlugCodec({ mask: schema });
261
+ ```
262
+
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.
268
+
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.
274
+
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.
279
+
280
+ ### Changing an existing ID format
281
+
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.
284
+
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.
288
+
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.
293
+
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.
297
+
298
+ ### Reading original slugs during migration
299
+
300
+ Create a migration reader from your codec. Enable only the old formats your application issued:
301
+
302
+ ```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.
307
+ ```
308
+
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.
314
+
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.
318
+
319
+ When you know the input format, name it to avoid trying unrelated formats:
320
+
321
+ ```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.
327
+ ```
328
+
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.
331
+
332
+ For unknown formats, use `candidates` to find the matching record without guessing:
333
+
334
+ ```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.
342
+ ```
343
+
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.
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.
356
+
357
+ ### Rejecting stale ids
358
+
359
+ ```ts
360
+ import { validateUuidV7Fresh } from "@anizoptera/uuid-slug";
361
+
362
+ const ok = validateUuidV7Fresh(uuid, { windowMs: 60_000 });
363
+ ```
364
+
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.
370
+
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.
375
+
376
+ ## Guarantees
377
+
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.
407
+
408
+ ## Runtime
409
+
410
+ No runtime dependencies, on any platform.
411
+
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
+
417
+ ## License
418
+
419
+ Apache-2.0. Copyright 2026 Anizoptera and Art Shendrik.
@@ -0,0 +1,21 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
+ import { UuidSlugErrorCode } from "./errors.js";
4
+ //#region src/alphabet.d.ts
5
+ /**
6
+ * A power-of-two alphabet plus its reverse lookup. Encoding is pure bit packing, so the only
7
+ * thing that varies between base64url and base32 is the character set and how many bits each
8
+ * character carries — one routine serves both rather than two hand-unrolled loops.
9
+ */
10
+ interface Alphabet {
11
+ readonly bitsPerChar: number;
12
+ readonly chars: string;
13
+ readonly code: UuidSlugErrorCode;
14
+ /** Character code -> value, `-1` for anything outside the alphabet. */
15
+ readonly decode: Int16Array;
16
+ readonly name: string;
17
+ readonly invalidChars: RegExp;
18
+ }
19
+ //#endregion
20
+ export { Alphabet };
21
+ //# sourceMappingURL=alphabet.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"alphabet.d.ts","names":[],"sources":["../src/alphabet.ts"],"mappings":";;;;;;;;;UAUiB;WACN;WACA;WACA,MAAM;;WAEN,QAAQ;WACR;WACA,cAAc"}
@@ -0,0 +1,132 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
+ import { UuidSlugError, checkRange } from "./errors.js";
4
+ //#region src/alphabet.ts
5
+ function alphabet(name, chars, code) {
6
+ const bitsPerChar = Math.log2(chars.length);
7
+ if (!Number.isInteger(bitsPerChar)) throw new Error(`${name} alphabet must be a power of two.`);
8
+ const decode = (/* @__PURE__ */ new Int16Array(128)).fill(-1);
9
+ for (let i = 0; i < chars.length; i += 1) decode[chars.charCodeAt(i)] = i;
10
+ return {
11
+ bitsPerChar,
12
+ chars,
13
+ code,
14
+ decode,
15
+ name,
16
+ invalidChars: new RegExp(`[^${chars.replaceAll("-", "\\-")}]`)
17
+ };
18
+ }
19
+ const BASE64URL = alphabet("base64url", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", "invalid_base64url");
20
+ /**
21
+ * The RFC 4648 §7 extended-hex digit values, not the §6 alphabet and not Crockford. Chosen because
22
+ * its characters are in ASCII order, so encoded values sort the same way the underlying bytes do —
23
+ * the one property base64url cannot offer, and the reason a second alphabet exists at all.
24
+ *
25
+ * Spelled LOWERCASE where the RFC writes `0-9A-V`, matching how this package renders UUIDs, and
26
+ * decoding accepts only that spelling so an id has exactly one form. The cost is interop: verified
27
+ * 2026-08-12 against CPython, `base64.b32hexdecode` rejects these slugs unless called with
28
+ * `casefold=True`. Upper-case them at the boundary if a strict RFC decoder has to read them.
29
+ */
30
+ const BASE32HEX = alphabet("base32hex", "0123456789abcdefghijklmnopqrstuv", "invalid_base32");
31
+ const nativeToBase64 = Uint8Array.prototype.toBase64;
32
+ const BASE64_OPTIONS = {
33
+ alphabet: "base64url",
34
+ omitPadding: true
35
+ };
36
+ /**
37
+ * Bits left over when `byteLength` bytes are written in this alphabet. A slug rounds up to whole
38
+ * characters, so the final character has spare low bits that carry no data: 4 for 16 bytes in
39
+ * base64url (22 chars = 132 bits), 2 in base32hex (26 chars = 130 bits). Callers may spend them
40
+ * on a trailing value at zero cost in length — see `encode`.
41
+ */
42
+ function spareBits(alpha, byteLength) {
43
+ const bits = byteLength * 8;
44
+ return (alpha.bitsPerChar - bits % alpha.bitsPerChar) % alpha.bitsPerChar;
45
+ }
46
+ /** Boolean validation needs no output buffer or diagnostic allocation. */
47
+ function isEncoded(value, alpha, byteLength) {
48
+ if (value.length !== Math.ceil(byteLength * 8 / alpha.bitsPerChar) || alpha.invalidChars.test(value)) return false;
49
+ const spare = spareBits(alpha, byteLength);
50
+ return spare === 0 || (alpha.decode[value.charCodeAt(value.length - 1)] & (1 << spare) - 1) === 0;
51
+ }
52
+ /**
53
+ * Pack bytes, optionally followed by `tailBits` low bits of `tail`, into `alpha`.
54
+ *
55
+ * `tailBits` MUST NOT exceed `spareBits`, otherwise the result grows a character. Passing
56
+ * `tail = 0` reproduces a plain encoding byte for byte, which is what keeps identifiers issued
57
+ * before the tail existed valid afterwards.
58
+ */
59
+ function encode(bytes, alpha, tail = 0, tailBits = 0) {
60
+ if (nativeToBase64 && alpha === BASE64URL && tailBits >= 0 && tailBits <= spareBits(alpha, bytes.length)) {
61
+ const encoded = nativeToBase64.call(bytes, BASE64_OPTIONS);
62
+ if (tailBits === 0) return encoded;
63
+ const last = encoded.length - 1;
64
+ const digit = alpha.decode[encoded.charCodeAt(last)];
65
+ const trailing = (tail & (1 << tailBits) - 1) << spareBits(alpha, bytes.length) - tailBits;
66
+ return encoded.slice(0, last) + alpha.chars[digit | trailing];
67
+ }
68
+ const { bitsPerChar, chars } = alpha;
69
+ const mask = (1 << bitsPerChar) - 1;
70
+ let out = "";
71
+ let acc = 0;
72
+ let bits = 0;
73
+ for (let i = 0; i < bytes.length; i += 1) {
74
+ acc = acc << 8 | bytes[i];
75
+ bits += 8;
76
+ while (bits >= bitsPerChar) {
77
+ bits -= bitsPerChar;
78
+ out += chars[acc >>> bits & mask];
79
+ }
80
+ }
81
+ if (tailBits > 0) {
82
+ acc = acc << tailBits | tail & (1 << tailBits) - 1;
83
+ bits += tailBits;
84
+ while (bits >= bitsPerChar) {
85
+ bits -= bitsPerChar;
86
+ out += chars[acc >>> bits & mask];
87
+ }
88
+ }
89
+ if (bits > 0) out += chars[acc << bitsPerChar - bits & mask];
90
+ return out;
91
+ }
92
+ /**
93
+ * Inverse of `encode`, writing into a caller-owned buffer so the slug paths need no intermediate
94
+ * allocation. Returns the trailing value (0 when `tailBits` is 0), or an Error.
95
+ *
96
+ * Rejects any character outside the alphabet, and any padding bit that is not zero. Without that
97
+ * last check one identifier would have several valid spellings, so a corrupted slug could decode
98
+ * successfully instead of being refused.
99
+ */
100
+ function decodeInto(value, alpha, out, offset, byteLength, tailBits = 0) {
101
+ const { bitsPerChar, decode: table, code, name } = alpha;
102
+ const expected = Math.ceil((byteLength * 8 + tailBits) / bitsPerChar);
103
+ if (value.length !== expected) return new UuidSlugError(code, `Expected ${expected} ${name} characters, got ${value.length}.`);
104
+ const badRange = checkRange(out.length, offset, byteLength);
105
+ if (badRange) return badRange;
106
+ let acc = 0;
107
+ let bits = 0;
108
+ let written = 0;
109
+ for (let i = 0; i < value.length; i += 1) {
110
+ const charCode = value.charCodeAt(i);
111
+ const digit = charCode < 128 ? table[charCode] : -1;
112
+ if (digit < 0) return new UuidSlugError(code, `Invalid ${name} character at offset ${i}.`);
113
+ acc = acc << bitsPerChar | digit;
114
+ bits += bitsPerChar;
115
+ while (bits >= 8 && written < byteLength) {
116
+ bits -= 8;
117
+ out[offset + written] = acc >>> bits & 255;
118
+ written += 1;
119
+ }
120
+ }
121
+ let tail = 0;
122
+ if (tailBits > 0) {
123
+ bits -= tailBits;
124
+ tail = acc >>> bits & (1 << tailBits) - 1;
125
+ }
126
+ if (bits > 0 && (acc & (1 << bits) - 1) !== 0) return new UuidSlugError(code, `${name} value has non-canonical trailing bits.`);
127
+ return tail;
128
+ }
129
+ //#endregion
130
+ export { BASE32HEX, BASE64URL, decodeInto, encode, isEncoded, spareBits };
131
+
132
+ //# sourceMappingURL=alphabet.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"alphabet.js","names":[],"sources":["../src/alphabet.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { checkRange, UuidSlugError } from \"./errors\";\nimport type { UuidSlugErrorCode } from \"./errors\";\n\n/**\n * A power-of-two alphabet plus its reverse lookup. Encoding is pure bit packing, so the only\n * thing that varies between base64url and base32 is the character set and how many bits each\n * character carries — one routine serves both rather than two hand-unrolled loops.\n */\nexport interface Alphabet {\n readonly bitsPerChar: number;\n readonly chars: string;\n readonly code: UuidSlugErrorCode;\n /** Character code -> value, `-1` for anything outside the alphabet. */\n readonly decode: Int16Array;\n readonly name: string;\n readonly invalidChars: RegExp;\n}\n\nfunction alphabet(name: string, chars: string, code: UuidSlugErrorCode): Alphabet {\n const bitsPerChar = Math.log2(chars.length);\n if (!Number.isInteger(bitsPerChar)) throw new Error(`${name} alphabet must be a power of two.`);\n const decode = new Int16Array(128).fill(-1);\n for (let i = 0; i < chars.length; i += 1) decode[chars.charCodeAt(i)] = i;\n return {\n bitsPerChar,\n chars,\n code,\n decode,\n name,\n invalidChars: new RegExp(`[^${chars.replaceAll(\"-\", \"\\\\-\")}]`),\n };\n}\n\nexport const BASE64URL: Alphabet = alphabet(\n \"base64url\",\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\",\n \"invalid_base64url\",\n);\n\n/**\n * The RFC 4648 §7 extended-hex digit values, not the §6 alphabet and not Crockford. Chosen because\n * its characters are in ASCII order, so encoded values sort the same way the underlying bytes do —\n * the one property base64url cannot offer, and the reason a second alphabet exists at all.\n *\n * Spelled LOWERCASE where the RFC writes `0-9A-V`, matching how this package renders UUIDs, and\n * decoding accepts only that spelling so an id has exactly one form. The cost is interop: verified\n * 2026-08-12 against CPython, `base64.b32hexdecode` rejects these slugs unless called with\n * `casefold=True`. Upper-case them at the boundary if a strict RFC decoder has to read them.\n */\nexport const BASE32HEX: Alphabet = alphabet(\n \"base32hex\",\n \"0123456789abcdefghijklmnopqrstuv\",\n \"invalid_base32\",\n);\n\n// Native encoding is strict on output; decoding stays here because it must reject aliases,\n// whitespace and nonzero padding that platform decoders may accept.\nconst nativeToBase64 = (\n Uint8Array.prototype as {\n toBase64?: (options: { alphabet: \"base64url\"; omitPadding: boolean }) => string;\n }\n).toBase64;\nconst BASE64_OPTIONS = { alphabet: \"base64url\", omitPadding: true } as const;\n\n/**\n * Bits left over when `byteLength` bytes are written in this alphabet. A slug rounds up to whole\n * characters, so the final character has spare low bits that carry no data: 4 for 16 bytes in\n * base64url (22 chars = 132 bits), 2 in base32hex (26 chars = 130 bits). Callers may spend them\n * on a trailing value at zero cost in length — see `encode`.\n */\nexport function spareBits(alpha: Alphabet, byteLength: number): number {\n const bits = byteLength * 8;\n return (alpha.bitsPerChar - (bits % alpha.bitsPerChar)) % alpha.bitsPerChar;\n}\n\n/** Boolean validation needs no output buffer or diagnostic allocation. */\nexport function isEncoded(value: string, alpha: Alphabet, byteLength: number): boolean {\n if (\n value.length !== Math.ceil((byteLength * 8) / alpha.bitsPerChar) ||\n alpha.invalidChars.test(value)\n )\n return false;\n const spare = spareBits(alpha, byteLength);\n return (\n spare === 0 ||\n ((alpha.decode[value.charCodeAt(value.length - 1)] as number) & ((1 << spare) - 1)) === 0\n );\n}\n\n/**\n * Pack bytes, optionally followed by `tailBits` low bits of `tail`, into `alpha`.\n *\n * `tailBits` MUST NOT exceed `spareBits`, otherwise the result grows a character. Passing\n * `tail = 0` reproduces a plain encoding byte for byte, which is what keeps identifiers issued\n * before the tail existed valid afterwards.\n */\nexport function encode(bytes: Uint8Array, alpha: Alphabet, tail = 0, tailBits = 0): string {\n if (\n nativeToBase64 &&\n alpha === BASE64URL &&\n tailBits >= 0 &&\n tailBits <= spareBits(alpha, bytes.length)\n ) {\n const encoded = nativeToBase64.call(bytes, BASE64_OPTIONS);\n if (tailBits === 0) return encoded;\n // The native result zeroes padding. Spend only those spare low bits on the mask check;\n // replacing the final character leaves the UUID payload and the wire length unchanged.\n const last = encoded.length - 1;\n const digit = alpha.decode[encoded.charCodeAt(last)] as number;\n const trailing = (tail & ((1 << tailBits) - 1)) << (spareBits(alpha, bytes.length) - tailBits);\n return encoded.slice(0, last) + alpha.chars[digit | trailing];\n }\n const { bitsPerChar, chars } = alpha;\n const mask = (1 << bitsPerChar) - 1;\n let out = \"\";\n let acc = 0;\n let bits = 0;\n for (let i = 0; i < bytes.length; i += 1) {\n // At most bitsPerChar-1 bits are held over, so `acc` peaks at 13 bits and stays in int32.\n acc = (acc << 8) | (bytes[i] as number);\n bits += 8;\n while (bits >= bitsPerChar) {\n bits -= bitsPerChar;\n out += chars[(acc >>> bits) & mask];\n }\n }\n if (tailBits > 0) {\n acc = (acc << tailBits) | (tail & ((1 << tailBits) - 1));\n bits += tailBits;\n while (bits >= bitsPerChar) {\n bits -= bitsPerChar;\n out += chars[(acc >>> bits) & mask];\n }\n }\n if (bits > 0) out += chars[(acc << (bitsPerChar - bits)) & mask];\n return out;\n}\n\n/**\n * Inverse of `encode`, writing into a caller-owned buffer so the slug paths need no intermediate\n * allocation. Returns the trailing value (0 when `tailBits` is 0), or an Error.\n *\n * Rejects any character outside the alphabet, and any padding bit that is not zero. Without that\n * last check one identifier would have several valid spellings, so a corrupted slug could decode\n * successfully instead of being refused.\n */\nexport function decodeInto(\n value: string,\n alpha: Alphabet,\n out: Uint8Array,\n offset: number,\n byteLength: number,\n tailBits = 0,\n): UuidSlugError | number {\n const { bitsPerChar, decode: table, code, name } = alpha;\n const expected = Math.ceil((byteLength * 8 + tailBits) / bitsPerChar);\n if (value.length !== expected)\n return new UuidSlugError(code, `Expected ${expected} ${name} characters, got ${value.length}.`);\n const badRange = checkRange(out.length, offset, byteLength);\n if (badRange) return badRange;\n\n let acc = 0;\n let bits = 0;\n let written = 0;\n for (let i = 0; i < value.length; i += 1) {\n const charCode = value.charCodeAt(i);\n const digit = charCode < 128 ? (table[charCode] as number) : -1;\n if (digit < 0) return new UuidSlugError(code, `Invalid ${name} character at offset ${i}.`);\n acc = (acc << bitsPerChar) | digit;\n bits += bitsPerChar;\n while (bits >= 8 && written < byteLength) {\n bits -= 8;\n out[offset + written] = (acc >>> bits) & 0xff;\n written += 1;\n }\n }\n let tail = 0;\n if (tailBits > 0) {\n bits -= tailBits;\n tail = (acc >>> bits) & ((1 << tailBits) - 1);\n }\n if (bits > 0 && (acc & ((1 << bits) - 1)) !== 0)\n return new UuidSlugError(code, `${name} value has non-canonical trailing bits.`);\n return tail;\n}\n"],"mappings":"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"}