@anizoptera/uuid-slug 0.5.0 → 0.7.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 (141) hide show
  1. package/AGENTS.md +14 -0
  2. package/README.md +54 -140
  3. package/dist/alphabet.d.ts +1 -3
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +33 -91
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +1 -3
  8. package/dist/base64url-name.d.ts.map +1 -1
  9. package/dist/base64url-name.js +2 -3
  10. package/dist/errors.d.ts +1 -3
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +7 -24
  13. package/dist/errors.js.map +1 -1
  14. package/dist/feistel.js +3 -4
  15. package/dist/feistel.js.map +1 -1
  16. package/dist/generation-options.js +2 -3
  17. package/dist/generation-options.js.map +1 -1
  18. package/dist/index.d.ts +10 -10
  19. package/dist/index.js +21 -21
  20. package/dist/instant.js +4 -5
  21. package/dist/instant.js.map +1 -1
  22. package/dist/mask-handle.d.ts +1 -3
  23. package/dist/mask-handle.d.ts.map +1 -1
  24. package/dist/mask-handle.js +19 -17
  25. package/dist/mask-handle.js.map +1 -1
  26. package/dist/mask.d.ts +1 -3
  27. package/dist/mask.d.ts.map +1 -1
  28. package/dist/mask.js +23 -24
  29. package/dist/mask.js.map +1 -1
  30. package/dist/masked-bytes.js +74 -0
  31. package/dist/masked-bytes.js.map +1 -0
  32. package/dist/masking-codec-protocol.js +2 -3
  33. package/dist/masking-codec-protocol.js.map +1 -1
  34. package/dist/masking-codec-types.d.ts +60 -19
  35. package/dist/masking-codec-types.d.ts.map +1 -1
  36. package/dist/masking-codec.d.ts +1 -3
  37. package/dist/masking-codec.d.ts.map +1 -1
  38. package/dist/masking-codec.js +119 -115
  39. package/dist/masking-codec.js.map +1 -1
  40. package/dist/migration.js +39 -40
  41. package/dist/migration.js.map +1 -1
  42. package/dist/node/runtime.js +9 -10
  43. package/dist/node/runtime.js.map +1 -1
  44. package/dist/payload.d.ts +1 -3
  45. package/dist/payload.d.ts.map +1 -1
  46. package/dist/payload.js +65 -64
  47. package/dist/payload.js.map +1 -1
  48. package/dist/runtime/pool.js +2 -3
  49. package/dist/runtime/pool.js.map +1 -1
  50. package/dist/runtime/portable.js +2 -3
  51. package/dist/runtime/portable.js.map +1 -1
  52. package/dist/sentinel.js +2 -3
  53. package/dist/sentinel.js.map +1 -1
  54. package/dist/siphash.js +4 -5
  55. package/dist/siphash.js.map +1 -1
  56. package/dist/slug.d.ts +14 -13
  57. package/dist/slug.d.ts.map +1 -1
  58. package/dist/slug.js +145 -153
  59. package/dist/slug.js.map +1 -1
  60. package/dist/timestamp.d.ts +1 -3
  61. package/dist/timestamp.d.ts.map +1 -1
  62. package/dist/timestamp.js +2 -3
  63. package/dist/timestamp.js.map +1 -1
  64. package/dist/types.d.ts +38 -16
  65. package/dist/types.d.ts.map +1 -1
  66. package/dist/types.js +2 -3
  67. package/dist/types.js.map +1 -1
  68. package/dist/uuid-value-protocol.js +2 -3
  69. package/dist/uuid-value-protocol.js.map +1 -1
  70. package/dist/uuid-value.d.ts +3 -5
  71. package/dist/uuid-value.d.ts.map +1 -1
  72. package/dist/uuid-value.js +74 -78
  73. package/dist/uuid-value.js.map +1 -1
  74. package/dist/uuid.d.ts +6 -8
  75. package/dist/uuid.d.ts.map +1 -1
  76. package/dist/uuid.js +38 -49
  77. package/dist/uuid.js.map +1 -1
  78. package/dist/v4-slug.d.ts +2 -4
  79. package/dist/v4-slug.d.ts.map +1 -1
  80. package/dist/v4-slug.js +6 -7
  81. package/dist/v4-slug.js.map +1 -1
  82. package/dist/v4.d.ts +8 -6
  83. package/dist/v4.d.ts.map +1 -1
  84. package/dist/v4.js +38 -44
  85. package/dist/v4.js.map +1 -1
  86. package/dist/v7-bounds.d.ts +3 -5
  87. package/dist/v7-bounds.d.ts.map +1 -1
  88. package/dist/v7-bounds.js +10 -11
  89. package/dist/v7-bounds.js.map +1 -1
  90. package/dist/v7-generator-input.js +10 -12
  91. package/dist/v7-generator-input.js.map +1 -1
  92. package/dist/v7-generator.d.ts +1 -3
  93. package/dist/v7-generator.d.ts.map +1 -1
  94. package/dist/v7-generator.js +45 -46
  95. package/dist/v7-generator.js.map +1 -1
  96. package/dist/v7-keyless.d.ts +12 -4
  97. package/dist/v7-keyless.d.ts.map +1 -1
  98. package/dist/v7-keyless.js +54 -55
  99. package/dist/v7-keyless.js.map +1 -1
  100. package/dist/v7-payload.js +3 -4
  101. package/dist/v7-payload.js.map +1 -1
  102. package/dist/v7-slug.d.ts +8 -5
  103. package/dist/v7-slug.d.ts.map +1 -1
  104. package/dist/v7-slug.js +69 -70
  105. package/dist/v7-slug.js.map +1 -1
  106. package/dist/v7-timestamp.js +2 -3
  107. package/dist/v7-timestamp.js.map +1 -1
  108. package/dist/v7-value-options.js +2 -3
  109. package/dist/v7-value-options.js.map +1 -1
  110. package/dist/v7-value.d.ts +5 -8
  111. package/dist/v7-value.d.ts.map +1 -1
  112. package/dist/v7-value.js +10 -11
  113. package/dist/v7-value.js.map +1 -1
  114. package/dist/v7.js +16 -17
  115. package/dist/v7.js.map +1 -1
  116. package/package.json +9 -2
  117. package/src/alphabet.ts +82 -237
  118. package/src/errors.ts +27 -40
  119. package/src/feistel.ts +3 -3
  120. package/src/index.ts +3 -0
  121. package/src/mask-handle.ts +7 -11
  122. package/src/mask.ts +16 -14
  123. package/src/masked-bytes.ts +203 -0
  124. package/src/masking-codec-types.ts +124 -24
  125. package/src/masking-codec.ts +43 -42
  126. package/src/migration.ts +8 -7
  127. package/src/payload.ts +69 -51
  128. package/src/runtime/portable.ts +2 -2
  129. package/src/runtime/types.ts +2 -4
  130. package/src/slug.ts +39 -48
  131. package/src/types.ts +107 -17
  132. package/src/uuid-value.ts +2 -9
  133. package/src/uuid.ts +19 -33
  134. package/src/v4.ts +12 -9
  135. package/src/v7-bounds.ts +4 -2
  136. package/src/v7-generator-input.ts +2 -5
  137. package/src/v7-generator.ts +2 -2
  138. package/src/v7-keyless.ts +29 -0
  139. package/src/v7-slug.ts +20 -1
  140. package/src/v7-value.ts +9 -4
  141. package/src/v7.ts +26 -0
package/AGENTS.md ADDED
@@ -0,0 +1,14 @@
1
+ # Using @anizoptera/uuid-slug
2
+
3
+ Rules for code that calls this package. The README beside this file explains every call; read its section before using an API you have not used.
4
+
5
+ - Import named functions from the package root; unused exports tree-shake away. Do not deep-import `dist/` or `src/` files.
6
+ - Conversions return `T | UuidSlugError` and never throw. Check once at the end of a chain: `typeof result === "string"` for string results, `isUuidSlugError(result)` otherwise. Branch on `error.code`, never on `message`. Only generation called with no argument or only a text-case or alphabet preset throws, and only `rng_unavailable`.
7
+ - Store the UUID (text or 16 bytes) as the record's identity. Slugs are spellings of the same 128 bits; convert at the edge, no mapping table.
8
+ - Plain slugs (root functions such as `uuidToPlainSlug`) are keyless and work for any UUID version. Masked slugs need a UUIDv7 masking codec from `createUuidV7MaskingCodec` with an explicit mask. `UUID_V7_TEST_MASK` is public and for tests only.
9
+ - A 22-character base64url string can be both a valid plain slug and a valid masked slug for different UUIDs. A codec's `uuidTo…` methods read it as masked whenever the mask check passes. When you know the source, call the source-specific method (`plainToMaskedUuidSlug`, `maskedToPlainUuidSlug`) instead. Base32hex lengths differ (26 plain, 27 masked) and never overlap.
10
+ - Never change or regenerate a mask that has issued slugs: those slugs would decode to different UUIDs. Rotate by listing the old mask in the codec's `previousMasks`; see README "Masked slugs".
11
+ - Need UUID text and a slug for one new ID? Call `generateUuidV7WithPlainSlug` or `codec.generateUuidV7WithMaskedSlug`; do not generate and then convert.
12
+ - Module-level `generateUuidV7` promises no ordering between calls. Create a generator with `createUuidV7Generator` when IDs must strictly increase or need a recorded time, clock-rollback policy or sub-millisecond bits.
13
+ - Choose base32hex for case-insensitive or filesystem-safe names and UUIDv7 slugs that sort by timestamp; base64url is shorter, and ASCII sorting can reverse nearby timestamps. Masked slugs have no time order.
14
+ - Parse once with `parseUuid` when one UUID is inspected or converted several times; use the direct functions for one-off conversions.
package/README.md CHANGED
@@ -1,15 +1,8 @@
1
1
  # @anizoptera/uuid-slug
2
2
 
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.
3
+ Fastest UUIDv4/v7 generation and handling for TS, Rust, and WASM, short base64/base32 plain and masked slugs.  Zero runtime deps, tree-shakable, and optimised for your runtime.  One efficient ID for databases, URLs and files.
4
4
 
5
- [![npm version](https://img.shields.io/npm/v/@anizoptera/uuid-slug?label=npm)](https://www.npmjs.com/package/@anizoptera/uuid-slug)
6
- [![CI](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml/badge.svg?branch=main)](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml)
7
- [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json)
8
- [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
9
- [![Bun >=1.0](https://img.shields.io/badge/bun-%3E%3D1.0-FBF0DF?logo=bun&logoColor=FBF0DF)](#runtime)
10
- [![Deno >=1.29](https://img.shields.io/badge/deno-%3E%3D1.29-70FFAF?logo=deno&logoColor=white)](#runtime)
11
- [![Cloudflare Workers](https://img.shields.io/badge/cloud-workers-F38020?logo=cloudflare&logoColor=white)](#runtime)
12
- [![License](https://img.shields.io/github/license/Anizoptera/uuid-slug)](LICENSE)
5
+ [![npm version](https://img.shields.io/npm/v/@anizoptera/uuid-slug?label=npm)](https://www.npmjs.com/package/@anizoptera/uuid-slug) [![crates.io version](https://img.shields.io/crates/v/uuid-slug?label=crates.io)](https://crates.io/crates/uuid-slug) [![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) [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json) [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](#runtime) [![Bun >=1.0](https://img.shields.io/badge/bun-%3E%3D1.0-FBF0DF?logo=bun&logoColor=FBF0DF)](#runtime) [![Deno >=1.29](https://img.shields.io/badge/deno-%3E%3D1.29-70FFAF?logo=deno&logoColor=white)](#runtime) [![Minimum Rust version](https://img.shields.io/crates/msrv/uuid-slug?label=Rust&logo=rust)](https://docs.rs/crate/uuid-slug/latest) [![Cloudflare Workers](https://img.shields.io/badge/cloud-workers-F38020?logo=cloudflare&logoColor=white)](#runtime) [![License](https://img.shields.io/github/license/Anizoptera/uuid-slug)](LICENSE)
13
6
 
14
7
  [![One UUIDv7 shown as UUID text, 16 bytes, plain base64url and base32hex slugs, and masked base64url and base32hex slugs, with colours tracing timestamp, version, variant and payload bits](docs/assets/uuid-representations.svg)](https://raw.githubusercontent.com/Anizoptera/uuid-slug/main/docs/assets/uuid-representations.svg)
15
8
 
@@ -59,7 +52,7 @@ Use your favorite TS/JS package manager (npm/bun/pnpm/yarn/..), e.g.:
59
52
  bun install @anizoptera/uuid-slug
60
53
  ```
61
54
 
62
- _The [Rust crate](rust/uuid-slug) and WASM builds live in this repo but are not yet published._
55
+ [Rust](https://crates.io/crates/uuid-slug): `cargo add uuid-slug` · [Rust API reference](https://docs.rs/uuid-slug/latest/uuid_slug/). Build browser WASM from the Rust crate with `wasm-js`.
63
56
 
64
57
 
65
58
  ## Quick start
@@ -73,14 +66,9 @@ import type { GeneratedUuidV7, PlainUuidV7Slug } from "@anizoptera/uuid-slug";
73
66
  const { uuid, slug }: GeneratedUuidV7<PlainUuidV7Slug> = generateUuidV7WithPlainSlug();
74
67
  ```
75
68
 
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.
69
+ `uuid` has type `UuidV7String`; `slug` has type `PlainUuidV7Slug`. These are ordinary strings at runtime; TypeScript retains their UUID version and representation. Unchecked external IDs remain `string` inputs; conversion and parsing validate them.
79
70
 
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).
71
+ Use `generateUuidV4()` for random IDs, `generateUuidV7()` for timestamped IDs, or `generatePlainUuidV7Slug()` for just the slug. Default generation returns the ID and throws `rng_unavailable` only without secure randomness. [Conversions return errors as values](#handling-errors).
84
72
 
85
73
 
86
74
  ## Contents
@@ -100,8 +88,7 @@ Default generation returns the ID and throws `rng_unavailable` only without secu
100
88
 
101
89
  ## Keep your existing UUIDs
102
90
 
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**.
91
+ Encode stored UUIDs; decode incoming slugs before querying the same keys. Plain encoding preserves every bit. Standard encodings let you decode plain slugs without this library; **masked slugs need the matching key and settings**.
105
92
 
106
93
  ```ts
107
94
  import { isUuidSlugError, plainSlugToUuidString, uuidStringToPlainSlug } from "@anizoptera/uuid-slug";
@@ -121,7 +108,7 @@ else console.error(uuid.message);
121
108
 
122
109
  ## Representations
123
110
 
124
- A masking codec holds the keys and settings to encode and decode UUIDv7 slugs.
111
+ A masking codec holds the keys and settings to encode and decode UUIDv7 slugs and masked bytes.
125
112
 
126
113
  All examples encode the same UUIDv7; sizes are characters except for bytes.
127
114
 
@@ -133,15 +120,13 @@ All examples encode the same UUIDv7; sizes are characters except for bytes.
133
120
  | 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
121
  | 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
122
  | Masked base32hex UUIDv7 slug | 27 | `daerdp86nv5qo3f4mg12c307qco` | 25% shorter than UUID text; opaque, unordered; writes lowercase, accepts mixed case; requires its codec to decode |
123
+ | Masked UUIDv7 bytes | 16 | `6a 9d b6 e5 06 bf cb ac 0d e4 b4 02 26 0c 07 d3` | The same mixed block without text encoding; 12-bit check; requires its codec to decode |
136
124
 
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.
125
+ 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). Masked examples use the public `UUID_V7_TEST_MASK`; use a private seed for your IDs.
139
126
 
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.
127
+ Plain and masked base64url slugs can look identical but decode to different UUIDs. 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.
142
128
 
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.
129
+ Generate bytes once when you need several representations, then convert only those you use. Use paired generation when you need UUID text plus one slug.
145
130
 
146
131
  ## Two kinds of slug
147
132
 
@@ -149,27 +134,19 @@ Use paired generation when you need UUID text plus one slug.
149
134
 
150
135
  _Examples: `AZirzRI0eryd7wEjRWeJqw` (base64url), `06canj8i6htbp7ff04hkaps9lc` (base32hex)_
151
136
 
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.
137
+ A plain slug is the UUID's 16 bytes in base64url (22 characters) or base32hex (26), with no key. Use `uuidStringToPlainSlug` to encode a UUID and `plainSlugToUuidString` to recover it. Decoders reject `=` padding and nonzero unused bits in the last character. `isPlainUuidSlug` checks canonical spelling and returns a boolean.
156
138
 
157
139
  Pass `BASE32HEX` to a plain-slug writer, for example `generatePlainUuidV7Slug(BASE32HEX)`; see [ordering](#ordering-and-key-distribution).
158
140
 
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.
141
+ `uuidToString` infers the alphabet from the length automatically, 22 or 26, so old slugs survive alphabet changes. It returns lowercase UUID text by default. Decode before comparing IDs or building cache keys: different spellings can identify the same record. Preserve base64url case; lowercasing changes the value.
163
142
 
164
143
  ### Masked slugs
165
144
 
166
145
  _Examples: `ap225Qa_y6wN5LQCJgwH0z` (base64url), `daerdp86nv5qo3f4mg12c307qco` (base32hex)_
167
146
 
168
- Hide UUIDv7 timestamps and other standard fields with a reusable masking codec.
169
- Codecs default to base64url; set `maskedSlugAlphabet: BASE32HEX` for lowercase filenames.
147
+ Hide UUIDv7 timestamps and other standard fields with a reusable masking codec. Codecs default to base64url; set `maskedSlugAlphabet: BASE32HEX` for lowercase filenames.
170
148
 
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!**
149
+ Supply either `maskSeed` or `mask`; neither or both returns `invalid_mask`. 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!**
173
150
 
174
151
  ```ts
175
152
  import {
@@ -193,33 +170,17 @@ if (isUuidSlugError(maskingCodec)) {
193
170
  }
194
171
  ```
195
172
 
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.
173
+ Construct and check the codec once; reuse it to avoid per-ID key derivation. Its methods need no `bind`. The public test mask makes this example reproducible; production codecs need a private seed. Masking accepts UUIDv7s from other generators and preserves all their payload bits. For new IDs, `maskingCodec.generateUuidV7WithMaskedSlug()` returns the UUID and slug together; `maskingCodec.generateMaskedUuidV7Slug()` returns just the slug. Both can return `UuidSlugError`. [Async mask derivation](docs/api.md#masking-codec-options) lets other work run during long setup and supports cancellation.
202
174
 
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.
175
+ Generate a random seed, for example with `openssl rand -base64 32`, and keep it outside source control. Seeds need at least 16 bytes; length alone does not prevent offline guessing from known UUID/slug pairs.
205
176
 
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.
177
+ Changing the seed or `keyDerivationIterations` changes keys. Keep old mask settings and range starts in `previousMasks` while old slugs must work. Retain each live format's sentinel definitions too. New slugs use current keys. Deploy both readers before switching writers; bookmarks still need their old decoder. See [migration](docs/api.md#changing-an-existing-id-format). `keyDerivationIterations` defaults to `1`. More iterations increase setup and guessing costs; they do not make a human-chosen seed suitable.
212
178
 
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).
179
+ Masking covers roughly 139 years from `timestampRangeStartUnixMs`. The default starts at the Unix epoch and ends in May 2109. Outside that range, masking returns `invalid_timestamp` rather than lose timestamp bits. Plain slugs and sentinels retain the full UUIDv7 range. See [exact bounds and range configuration](docs/design.md#representations-and-bit-budget).
217
180
 
218
181
  ### Sentinels
219
182
 
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).
183
+ Reserve UUIDv7 values that stay recognizable in logs: codecs write them as plain slugs, even after key rotation. Codecs have none by default. Keep their definitions unchanged while their slugs remain in use. See [sentinel setup and collision handling](docs/api.md#sentinels).
223
184
 
224
185
  ## Work with UUID bytes
225
186
 
@@ -235,15 +196,13 @@ if (isUuidSlugError(result)) console.error(result.message);
235
196
  else console.log(result); // The same record, with its ID at bytes 8 through 23.
236
197
  ```
237
198
 
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).
199
+ Write directly into your database or protocol buffer with `uuidStringToBytes`, `plainSlugToUuidBytes` or `maskingCodec.maskedSlugToUuidBytes`. Pass the array and offset; the call returns your array and leaves other bytes unchanged. Failed validation leaves the buffer unchanged. See [buffer examples and accepted byte forms](docs/api.md#work-with-uuid-bytes).
200
+
201
+ For client-visible binary IDs, use `maskingCodec.uuidToMaskedBytes(uuid, record, offset)` or omit storage for an owned 16-byte result. Read directly from a packet with `maskingCodec.maskedBytesToUuidString(record, offset)` or `maskedBytesToUuidBytes(record, offset, output, outputOffset)`. Omit the input offset for a standalone value and output storage for owned bytes. Raw and masked bytes can represent different UUIDs, so ordinary UUID readers never infer masking. Binary preserves the slug's UUID payload and settings, with a 12-bit check instead of text's 16-bit check; neither authorizes access. Registered sentinels retain their raw UUID bytes.
242
202
 
243
203
  ## Parse once for repeated work
244
204
 
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.
205
+ `parseUuid` validates and decodes an ID once for repeated conversion and inspection. It returns an immutable `Uuid` object, not a string. Changes to its byte outputs leave the retained UUID unchanged.
247
206
 
248
207
  ```ts
249
208
  import { isUuidSlugError, parseUuid } from "@anizoptera/uuid-slug";
@@ -263,16 +222,11 @@ if (isUuidSlugError(uuid)) {
263
222
 
264
223
  ## Assign IDs before saving or syncing
265
224
 
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.
225
+ Create IDs before saving, even offline. Related records can reference them without a database round trip and keep them after synchronization. No central allocator or worker number is needed. Any generator works, e.g. `generateUuidV7()`, wherever the record is created.
269
226
 
270
227
  ## Generate at a recorded time
271
228
 
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).
229
+ Set `at` on UUIDv7 generation calls to encode a record's time instead of now. It accepts a `Date`, Unix milliseconds, zoned ISO text, Temporal-style instants and `{ seconds, nanoseconds }` timestamps without manual conversion. See [accepted time forms and configured fractional precision](docs/api.md#supplied-time).
276
230
 
277
231
  ```ts
278
232
  import { BASE32HEX, generatePlainUuidV7Slug } from "@anizoptera/uuid-slug";
@@ -284,19 +238,15 @@ if (typeof slug === "string") console.log(slug);
284
238
  else console.error(slug.message);
285
239
  ```
286
240
 
287
- Use one `createUuidV7Generator` generator across output forms to share a sequence, including `at` calls.
288
- Module-level calls remain independent.
241
+ Use one `createUuidV7Generator` generator across output forms to share a sequence, including `at` calls. Module-level calls remain independent.
289
242
 
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.
243
+ Calls use fresh randomness even at identical timestamps. For retries, retain the first ID or use a deduplication key; existing records keep their UUIDs. Masked IDs need a [timestamp range](#masked-slugs) covering the recorded time.
293
244
 
294
245
  To keep IDs in order, a generator may encode a time slightly after the one you supplied.
295
246
 
296
247
  ## Use the UUID as the timestamp source
297
248
 
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:
249
+ Read UUIDv7's millisecond timestamp without a database lookup or UUID-text conversion. If it is the time you need, omit a separate field:
300
250
 
301
251
  ```ts
302
252
  import { extractUuidV7UnixMs } from "@anizoptera/uuid-slug";
@@ -308,61 +258,37 @@ if (typeof unixMs === "number") console.log(unixMs);
308
258
  else console.error(unixMs.message);
309
259
  ```
310
260
 
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.
261
+ `extractUuidV7UnixMs(bytes, offset)` reads from a larger buffer. `maskingCodec.extractMaskedUuidV7UnixMs(slug)` recovers a masked timestamp with the codec's keys. UUIDv4 has no timestamp and is rejected.
314
262
 
315
263
  For known fraction and counter layouts, use [payload extraction](docs/api.md#uuidv7-payload-fields).
316
264
 
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.
265
+ Keep separate fields for other dates, finer precision, editable times or queries the UUID index cannot serve. Changing the timestamp changes the ID.
319
266
 
320
267
  ## Ordering and key distribution
321
268
 
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.
269
+ Base64url UUIDv7 slugs are almost time-ordered: nearby timestamps have similar prefixes. ASCII sorting can reverse them: `AAAAAAAz` and `AAAAAAA0` encode consecutive milliseconds, but the second prefix sorts first.
325
270
 
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.
271
+ Base32hex preserves UUID byte order: its alphabet, `0-9a-v`, follows numeric order, with the most significant bits first. Equal-length slugs sort by timestamp even across field boundaries. Clocks can move backwards, and UUIDv7 does not promise creation order within a millisecond. Compare one spelling at a time; database collations and natural file sorting can differ from ASCII.
330
272
 
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.
273
+ `uuidV7StringBounds(startMs, endMs)` builds inclusive bounds for time-range queries on UUID keys. The bounds cover every UUIDv7 in the interval, regardless of its payload. For one millisecond, use `uuidV7StringBounds(ms)`. Compare in UUID wire-byte order; SQL Server's `uniqueidentifier` uses a different order.
335
274
 
336
275
  Decode masked filenames or store dates separately to sort them chronologically.
337
276
 
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.
277
+ Changing public URLs leaves the UUID index unchanged. For hash partitioning, hash the UUID so a spelling change does not move the record.
340
278
 
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.
279
+ With unchanged settings, built-in masking gives the same UUID the same slug: URLs and filenames stay stable, and repeated uses are recognizable. Rotation can change the slug; compare decoded UUIDs to identify the same record.
344
280
 
345
281
  ## Masking security
346
282
 
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).
283
+ Masking hides UUIDv7 fields; the matching key restores them. Its cryptographic strength is not established, including against attacks using known UUID/slug pairs. See the [design](docs/design.md) and [security limits](docs/security.md).
350
284
 
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).
285
+ An incorrect key can pass the 16-bit check and return the wrong UUID. Keep the rotation list short and confirm decoded IDs against your records; see the [record lookup example](docs/security.md#masking).
354
286
 
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.
287
+ A browser can use your service's masked IDs without the seed. Keep private masking and decoding on the service; client code exposes the seed. Plain generation and conversion need no seed.
357
288
 
358
289
  ## Handling errors
359
290
 
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.
291
+ Conversions return `T | UuidSlugError` and pass errors through unchanged. Async mask construction resolves to the same union. Compatible chains need one final check. For string results, `typeof result === "string"` keeps the branded string type; the other branch is `UuidSlugError`. Use `isUuidSlugError` for object results or unknown input. It recognizes package errors across realms and package copies.
366
292
 
367
293
  ```ts
368
294
  import { isUuidSlugError, uuidStringToBytes } from "@anizoptera/uuid-slug";
@@ -375,14 +301,11 @@ else console.log(bytes);
375
301
 
376
302
  Check intermediate results only when you also need their values.
377
303
 
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`.
304
+ Handle errors by `code`, with constants such as `INVALID_BUFFER` and the `UuidSlugErrorCode` type. Use `message` for diagnostics; wording can change while codes stay stable. Failed entropy draws, clock readings and custom transforms retain their exception as `cause`.
381
305
 
382
306
  ## API
383
307
 
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.
308
+ 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). Each export also documents its accepted input, result and failures in JSDoc.
386
309
 
387
310
  ## TypeScript API map
388
311
 
@@ -402,41 +325,30 @@ Each export also documents its accepted input, result and failures in JSDoc.
402
325
  | Derive UUIDv7 masks, with optional async cancellation | `deriveUuidV7Mask`, `deriveUuidV7MaskAsync` |
403
326
  | Use an application-defined reversible masking transform | [`createCustomUuidV7Mask`](docs/api.md#masking-codec-options) |
404
327
  | Mask, unmask, rotate keys, or reserve sentinels | `createUuidV7MaskingCodec` and its methods |
328
+ | Transfer masked UUIDv7 as 16 bytes | `maskingCodec.uuidToMaskedBytes`, `maskedBytesToUuidBytes`, `maskedBytesToUuidString` |
405
329
  | Read explicitly enabled old formats | `maskingCodec.createUuidSlugMigrationDecoder` |
406
330
 
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.
331
+ Types catch UUID-version and plain/masked mix-ups; results retain text case and buffer ownership. Generator, masking-codec and migration methods need no `this` binding.
409
332
 
410
333
  ## Guarantees
411
334
 
412
335
  - Generated IDs have RFC 9562 version and variant bits.
413
336
  - 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
337
  - 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.
338
+ - Default calls retain the selected native generator's ordering and clock behavior. Use a created generator to control ordering and clock rollback. Native failures fall back to the package's generator; if both fail, the error retains both causes.
339
+ - UUIDv7 starts with a 48-bit millisecond timestamp, so UUID strings sort by encoded time across different milliseconds. Backfills and clock adjustments can differ from generation order.
340
+ - Successful current-time calls on one created generator strictly increase in UUID byte order under the default `clockRollback` policy, `"preserve"`; `at` calls share its sequence state. Module-level generation and `"reset"` calls beyond their tolerance do not guarantee this order. Independent generators, package copies, workers and processes have separate state; use a sequence column for ordering across them.
341
+ - Plain slugs preserve all UUID bits. Base32hex UUIDv7 slugs sort by timestamp across different milliseconds under ASCII comparison. Base64url UUIDv7 slugs are almost time-ordered; [ASCII sorting can reverse them](#ordering-and-key-distribution). Masked slugs have no chronological order.
427
342
  - 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.
343
+ - `uuidStringToBytes` and `plainSlugToUuidBytes` validate the whole identifier before writing. Invalid text or destination ranges return an error without changing caller storage.
344
+ - Named root imports let supported bundlers remove the cipher, key derivation, sentinel table, and unrelated generation code.
345
+ - A UUIDv7 masking codec requires explicit private mask options or a package-produced mask. Use `UUID_V7_TEST_MASK` explicitly for the public test key; omission does not select it.
434
346
 
435
347
  ## Runtime
436
348
 
437
349
  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
350
 
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).
351
+ The [Rust crate](https://crates.io/crates/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
352
 
441
353
  | Runtime | Package code |
442
354
  | --- | --- |
@@ -466,3 +378,5 @@ Report bugs through [GitHub issues](https://github.com/Anizoptera/uuid-slug/issu
466
378
  ## License
467
379
 
468
380
  Apache-2.0. Copyright 2026 Anizoptera and Art Shendrik.
381
+
382
+ The Rust UUID text parser and hyphenated formatter reuse code from the [uuid crate and its contributors](https://github.com/uuid-rs/uuid), under its MIT license. Only these text-conversion kernels are copied; generation, slug encoding and masking are separate. The opt-in `uuid-interop` feature uses `uuid` directly for parsing, formatting and `uuid::Uuid` conversions, and excludes the copied backend at compile time. Upstream source and license attribution are included with the copied code.
@@ -1,9 +1,7 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.5.0 | https://github.com/Anizoptera/uuid-slug#readme
2
+ // @anizoptera/uuid-slug 0.7.0 | https://github.com/Anizoptera/uuid-slug#readme
3
3
  import { BASE64URL_NAME } from "./base64url-name.js";
4
- //#region src/alphabet.d.ts
5
4
  /** Select lowercase base32hex slug output. */
6
5
  export declare const BASE32HEX_NAME = "base32hex";
7
- //#endregion
8
6
  export { BASE64URL_NAME };
9
7
  //# sourceMappingURL=alphabet.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"alphabet.d.ts","names":[],"sources":["../src/alphabet.ts"],"mappings":";;;;;qBASa"}
1
+ {"version":3,"file":"alphabet.d.ts","names":[],"sources":["../src/alphabet.ts"],"mappings":";;;;qBASa"}
package/dist/alphabet.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.5.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { INVALID_BASE32HEX as e, INVALID_BASE64URL as t, UuidSlugError as n, checkRange as r } from "./errors.js";
4
- import { BASE64URL_NAME as i } from "./base64url-name.js";
5
- import { runtime as a } from "#runtime";
6
- //#region src/alphabet.ts
7
- const o = "base32hex";
2
+ // @anizoptera/uuid-slug 0.7.0 | https://github.com/Anizoptera/uuid-slug#readme
3
+ import { runtime as e } from "#runtime";
4
+ import { BASE64URL_NAME as t } from "./base64url-name.js";
5
+ import { INVALID_BASE32HEX as n, INVALID_BASE64URL as r, UuidSlugError as i, checkRange as a } from "./errors.js";
6
+ // src/alphabet.ts
7
+ const o = "base32hex", s = " value has non-canonical trailing bits";
8
8
  /*#__NO_SIDE_EFFECTS__*/
9
9
  function alphabet(e, t, n, r = !1) {
10
10
  let i = Math.log2(t.length), a = (/* @__PURE__ */ new Int16Array(128)).fill(-1);
@@ -23,28 +23,20 @@ function alphabet(e, t, n, r = !1) {
23
23
  invalidInputChars: new RegExp(o, r ? "i" : "")
24
24
  };
25
25
  }
26
- const s = /*#__PURE__*/ alphabet(i, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", t), c = /*#__PURE__*/ alphabet(o, "0123456789abcdefghijklmnopqrstuv", e, !0), l = globalThis.Deno?.version?.deno, u = Uint8Array.prototype.toBase64, d = l === void 0 ? u : void 0, f = {
27
- alphabet: i,
28
- omitPadding: !0
29
- }, p = a.latin1Scratch;
30
- let m, h, g, _, v;
26
+ const c = /*#__PURE__*/ alphabet(t, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", r), l = /*#__PURE__*/ alphabet(o, "0123456789abcdefghijklmnopqrstuv", n, !0), u = e.latin1Scratch;
27
+ let d, f, p, m, h;
31
28
  /*#__NO_SIDE_EFFECTS__*/
32
29
  function characterCodes(e) {
33
30
  return Uint8Array.from(e.chars, (e) => e.charCodeAt(0));
34
31
  }
35
32
  /*#__NO_SIDE_EFFECTS__*/
36
- function spareBits(e, t) {
37
- let n = t * 8;
38
- return (e.bitsPerChar - n % e.bitsPerChar) % e.bitsPerChar;
39
- }
40
- /*#__NO_SIDE_EFFECTS__*/
41
33
  function isEncoded(e, t, n, r = !1, i = 0) {
42
34
  if (e.length !== Math.ceil((n * 8 + i) / t.bitsPerChar) || (r ? t.invalidInputChars : t.invalidChars).test(e)) return !1;
43
35
  let a = (t.bitsPerChar - (n * 8 + i) % t.bitsPerChar) % t.bitsPerChar;
44
36
  return a === 0 || !(t.decode[e.charCodeAt(e.length - 1)] & (1 << a) - 1);
45
37
  }
46
- function invalidCharacter(e, t, r) {
47
- return new n(e.code, `Invalid ${e.name} character ${JSON.stringify(t[r])} at offset ${r}.`);
38
+ function invalidCharacter(e, t, n) {
39
+ return new i(e.code, `Invalid ${e.name} character ${JSON.stringify(t[n])} at offset ${n}.`);
48
40
  }
49
41
  function firstInvalidCharacter(e, t) {
50
42
  let n = 0;
@@ -57,24 +49,10 @@ function firstInvalidCharacter(e, t) {
57
49
  }
58
50
  /*#__NO_SIDE_EFFECTS__*/
59
51
  function encode(e, t, n = 0, r = 0) {
60
- if (p && e.length === 16) {
61
- if (t === s && (r === 0 || r === 4)) return encodeBase64urlLatin1(p, e, n);
62
- if (t === c && (r === 0 || r === 2 || r === 4)) return encodeBase32hexLatin1(p, e, n, r);
63
- }
64
- if (e.length === 16) {
65
- if (t === s && (r === 0 || r === 4)) return /* @__PURE__ */ writeBase64url(e, _ ??= /* @__PURE__ */ characterCodes(s), n);
66
- if (t === c && (r === 0 || r === 2 || r === 4)) return /* @__PURE__ */ writeBase32hex(e, v ??= /* @__PURE__ */ characterCodes(c), n, r);
67
- }
68
- if (d && t === s && r >= 0 && r <= /* @__PURE__ */ spareBits(t, e.length)) {
69
- let i = d.call(e, f);
70
- if (r === 0) return i;
71
- let a = i.length - 1, o = t.decode[i.charCodeAt(a)], s = (n & (1 << r) - 1) << /* @__PURE__ */ spareBits(t, e.length) - r;
72
- return i.slice(0, a) + t.chars[o | s];
73
- }
74
- return /* @__PURE__ */ encodePortable(e, t, n, r);
52
+ return u ? t === c ? encodeBase64urlLatin1(u, e, n) : encodeBase32hexLatin1(u, e, n, r) : t === c ? /* @__PURE__ */ writeBase64url(e, m ??= /* @__PURE__ */ characterCodes(c), n) : /* @__PURE__ */ writeBase32hex(e, h ??= /* @__PURE__ */ characterCodes(l), n, r);
75
53
  }
76
54
  function encodeBase64urlLatin1(e, t, n) {
77
- let r = m ??= e(22), i = _ ??= /* @__PURE__ */ characterCodes(s), a = r.bytes;
55
+ let r = d ??= e(22), i = m ??= /* @__PURE__ */ characterCodes(c), a = r.bytes;
78
56
  for (let e = 0, n = 0; e < 15; e += 3, n += 4) {
79
57
  let r = t[e] << 16 | t[e + 1] << 8 | t[e + 2];
80
58
  a[n] = i[r >>> 18], a[n + 1] = i[r >>> 12 & 63], a[n + 2] = i[r >>> 6 & 63], a[n + 3] = i[r & 63];
@@ -83,7 +61,7 @@ function encodeBase64urlLatin1(e, t, n) {
83
61
  return a[20] = i[o >>> 2], a[21] = i[(o & 3) << 4 | n & 15], r.text();
84
62
  }
85
63
  function encodeBase32hexLatin1(e, t, n, r) {
86
- let i = r === 4 ? g ??= e(27) : h ??= e(26), a = v ??= /* @__PURE__ */ characterCodes(c), o = i.bytes;
64
+ let i = r === 4 ? p ??= e(27) : f ??= e(26), a = h ??= /* @__PURE__ */ characterCodes(l), o = i.bytes;
87
65
  for (let e = 0, n = 0; e < 15; e += 5, n += 8) {
88
66
  let r = t[e], i = t[e + 1], s = t[e + 2], c = t[e + 3], l = t[e + 4];
89
67
  o[n] = a[r >>> 3], o[n + 1] = a[(r & 7) << 2 | i >>> 6], o[n + 2] = a[i >>> 1 & 31], o[n + 3] = a[(i & 1) << 4 | s >>> 4], o[n + 4] = a[(s & 15) << 1 | c >>> 7], o[n + 5] = a[c >>> 2 & 31], o[n + 6] = a[(c & 3) << 3 | l >>> 5], o[n + 7] = a[l & 31];
@@ -91,64 +69,29 @@ function encodeBase32hexLatin1(e, t, n, r) {
91
69
  let s = t[15];
92
70
  return o[24] = a[s >>> 3], r === 4 ? (o[25] = a[(s & 7) << 2 | n >>> 2 & 3], o[26] = a[(n & 3) << 3]) : o[25] = a[(s & 7) << 2 | n & 3], i.text();
93
71
  }
94
- /*#__NO_SIDE_EFFECTS__*/
95
- function encodePortable(e, t, n = 0, r = 0) {
96
- if (t === s && e.length === 16 && (r === 0 || r === 4)) {
97
- let r = "";
98
- for (let n = 0; n < 15; n += 3) {
99
- let i = e[n] << 16 | e[n + 1] << 8 | e[n + 2];
100
- r += t.chars[i >>> 18] + t.chars[i >>> 12 & 63] + t.chars[i >>> 6 & 63] + t.chars[i & 63];
101
- }
102
- let i = e[15];
103
- return r + t.chars[i >>> 2] + t.chars[(i & 3) << 4 | n & 15];
104
- }
105
- if (t === c && e.length === 16 && (r === 0 || r === 2 || r === 4)) {
106
- let i = "", a = t.chars;
107
- for (let t = 0; t < 15; t += 5) {
108
- let n = e[t], r = e[t + 1], o = e[t + 2], s = e[t + 3], c = e[t + 4];
109
- i += a[n >>> 3] + a[(n & 7) << 2 | r >>> 6] + a[r >>> 1 & 31] + a[(r & 1) << 4 | o >>> 4] + a[(o & 15) << 1 | s >>> 7] + a[s >>> 2 & 31] + a[(s & 3) << 3 | c >>> 5] + a[c & 31];
110
- }
111
- let o = e[15];
112
- return r === 4 ? i + a[o >>> 3] + a[(o & 7) << 2 | n >>> 2 & 3] + a[(n & 3) << 3] : i + a[o >>> 3] + a[(o & 7) << 2 | n & 3];
113
- }
114
- let { bitsPerChar: i, chars: a } = t, o = (1 << i) - 1, l = "", u = 0, d = 0;
115
- for (let t = 0; t < e.length; t += 1) for (u = u << 8 | e[t], d += 8; d >= i;) d -= i, l += a[u >>> d & o];
116
- if (r > 0) for (u = u << r | n & (1 << r) - 1, d += r; d >= i;) d -= i, l += a[u >>> d & o];
117
- return d > 0 && (l += a[u << i - d & o]), l;
118
- }
119
- function decodeInto(e, t, i, a, o, l = 0) {
120
- let { bitsPerChar: u, decode: d, code: f, name: p } = t, m = Math.ceil((o * 8 + l) / u);
121
- if (e.length !== m) return new n(f, `Expected ${m} ${p} characters, got ${e.length}.`);
122
- let h = /* @__PURE__ */ r(i.length, a, o);
123
- if (h) return h;
124
- if (t === s && o === 16 && (l === 0 || l === 4)) {
125
- let r = 0, o = 0, s = a;
72
+ function decodeInto(e, t, n, r, o = 0) {
73
+ let { bitsPerChar: l, decode: u, code: d, name: f } = t, p = Math.ceil((128 + o) / l);
74
+ if (e.length !== p) return new i(d, `Expected ${p} ${f} characters, got ${e.length}.`);
75
+ let m = /* @__PURE__ */ a(n.length, r, 16);
76
+ if (m) return m;
77
+ if (t === c) {
78
+ let a = 0, c = 0, l = r;
126
79
  for (let t = 0; t < 20; t += 4) {
127
- let n = e.charCodeAt(t), a = e.charCodeAt(t + 1), c = e.charCodeAt(t + 2), l = e.charCodeAt(t + 3), u = d[n & 127] << 18 | d[a & 127] << 12 | d[c & 127] << 6 | d[l & 127];
128
- r |= n | a | c | l, o |= u, i[s] = u >>> 16, i[s + 1] = u >>> 8, i[s + 2] = u, s += 3;
129
- }
130
- let c = e.charCodeAt(20), u = e.charCodeAt(21), m = d[c & 127], h = d[u & 127];
131
- return (r | c | u) > 127 || (o | m | h) < 0 ? firstInvalidCharacter(t, e) : (i[s] = m << 2 | h >>> 4, l === 4 ? h & 15 : h & 15 ? new n(f, `${p} value has non-canonical trailing bits; a masked slug of this length decodes only through its codec.`) : 0);
132
- }
133
- if (t === c && o === 16 && (l === 0 || l === 2 || l === 4)) {
134
- let r = 0, o = 0, s = a;
135
- for (let t = 0; t < 24; t += 8) {
136
- let n = e.charCodeAt(t), a = e.charCodeAt(t + 1), c = e.charCodeAt(t + 2), l = e.charCodeAt(t + 3), u = e.charCodeAt(t + 4), f = e.charCodeAt(t + 5), p = e.charCodeAt(t + 6), m = e.charCodeAt(t + 7);
137
- r |= n | a | c | l | u | f | p | m;
138
- let h = d[n & 127], g = d[a & 127], _ = d[c & 127], v = d[l & 127], y = d[u & 127], b = d[f & 127], x = d[p & 127], S = d[m & 127];
139
- o |= h | g | _ | v | y | b | x | S, i[s] = h << 3 | g >>> 2, i[s + 1] = g << 6 | _ << 1 | v >>> 4, i[s + 2] = v << 4 | y >>> 1, i[s + 3] = y << 7 | b << 2 | x >>> 3, i[s + 4] = x << 5 | S, s += 5;
80
+ let r = e.charCodeAt(t), i = e.charCodeAt(t + 1), o = e.charCodeAt(t + 2), s = e.charCodeAt(t + 3), d = u[r & 127] << 18 | u[i & 127] << 12 | u[o & 127] << 6 | u[s & 127];
81
+ a |= r | i | o | s, c |= d, n[l] = d >>> 16, n[l + 1] = d >>> 8, n[l + 2] = d, l += 3;
140
82
  }
141
- let c = e.charCodeAt(24), u = e.charCodeAt(25), m = l === 4 ? e.charCodeAt(26) : 48, h = d[c & 127], g = d[u & 127], _ = d[m & 127];
142
- return (r | c | u | m) > 127 || (o | h | g | _) < 0 ? firstInvalidCharacter(t, e) : (i[s] = h << 3 | g >>> 2, l === 4 ? _ & 7 ? new n(f, `${p} value has non-canonical trailing bits.`) : (g & 3) << 2 | _ >>> 3 : l === 2 ? g & 3 : g & 3 ? new n(f, `${p} value has non-canonical trailing bits.`) : 0);
83
+ let p = e.charCodeAt(20), m = e.charCodeAt(21), h = u[p & 127], g = u[m & 127];
84
+ return (a | p | m) > 127 || (c | h | g) < 0 ? firstInvalidCharacter(t, e) : (n[l] = h << 2 | g >>> 4, o === 4 ? g & 15 : g & 15 ? new i(d, `${f}${s}; a masked slug of this length decodes only through its codec.`) : 0);
143
85
  }
144
- let g = 0, _ = 0, v = 0;
145
- for (let n = 0; n < e.length; n += 1) {
146
- let r = e.charCodeAt(n), s = r < 128 ? d[r] : -1;
147
- if (s < 0) return invalidCharacter(t, e, n);
148
- for (g = g << u | s, _ += u; _ >= 8 && v < o;) _ -= 8, i[a + v] = g >>> _ & 255, v += 1;
86
+ let h = 0, g = 0, _ = r;
87
+ for (let t = 0; t < 24; t += 8) {
88
+ let r = e.charCodeAt(t), i = e.charCodeAt(t + 1), a = e.charCodeAt(t + 2), o = e.charCodeAt(t + 3), s = e.charCodeAt(t + 4), c = e.charCodeAt(t + 5), l = e.charCodeAt(t + 6), d = e.charCodeAt(t + 7);
89
+ h |= r | i | a | o | s | c | l | d;
90
+ let f = u[r & 127], p = u[i & 127], m = u[a & 127], v = u[o & 127], y = u[s & 127], b = u[c & 127], x = u[l & 127], S = u[d & 127];
91
+ g |= f | p | m | v | y | b | x | S, n[_] = f << 3 | p >>> 2, n[_ + 1] = p << 6 | m << 1 | v >>> 4, n[_ + 2] = v << 4 | y >>> 1, n[_ + 3] = y << 7 | b << 2 | x >>> 3, n[_ + 4] = x << 5 | S, _ += 5;
149
92
  }
150
- let y = 0;
151
- return l > 0 && (_ -= l, y = g >>> _ & (1 << l) - 1), _ > 0 && g & (1 << _) - 1 ? new n(f, `${p} value has non-canonical trailing bits.`) : y;
93
+ let v = e.charCodeAt(24), y = e.charCodeAt(25), b = o === 4 ? e.charCodeAt(26) : 48, x = u[v & 127], S = u[y & 127], C = u[b & 127];
94
+ return (h | v | y | b) > 127 || (g | x | S | C) < 0 ? firstInvalidCharacter(t, e) : (n[_] = x << 3 | S >>> 2, o === 4 ? C & 7 ? new i(d, `${f}${s}.`) : (S & 3) << 2 | C >>> 3 : S & 3 ? new i(d, `${f}${s}.`) : 0);
152
95
  }
153
96
  /*#__NO_SIDE_EFFECTS__*/
154
97
  function writeBase64url(e, t, n) {
@@ -160,7 +103,6 @@ function writeBase32hex(e, t, n, r) {
160
103
  let i = e[0], a = e[1], o = e[2], s = e[3], c = e[4], l = e[5], u = e[6], d = e[7], f = e[8], p = e[9], m = e[10], h = e[11], g = e[12], _ = e[13], v = e[14], y = e[15], b = t[(y & 7) << 2 | (r === 4 ? n >>> 2 & 3 : n & 3)];
161
104
  return r === 4 ? String.fromCharCode(t[i >>> 3], t[(i & 7) << 2 | a >>> 6], t[a >>> 1 & 31], t[(a & 1) << 4 | o >>> 4], t[(o & 15) << 1 | s >>> 7], t[s >>> 2 & 31], t[(s & 3) << 3 | c >>> 5], t[c & 31], t[l >>> 3], t[(l & 7) << 2 | u >>> 6], t[u >>> 1 & 31], t[(u & 1) << 4 | d >>> 4], t[(d & 15) << 1 | f >>> 7], t[f >>> 2 & 31], t[(f & 3) << 3 | p >>> 5], t[p & 31], t[m >>> 3], t[(m & 7) << 2 | h >>> 6], t[h >>> 1 & 31], t[(h & 1) << 4 | g >>> 4], t[(g & 15) << 1 | _ >>> 7], t[_ >>> 2 & 31], t[(_ & 3) << 3 | v >>> 5], t[v & 31], t[y >>> 3], b, t[(n & 3) << 3]) : String.fromCharCode(t[i >>> 3], t[(i & 7) << 2 | a >>> 6], t[a >>> 1 & 31], t[(a & 1) << 4 | o >>> 4], t[(o & 15) << 1 | s >>> 7], t[s >>> 2 & 31], t[(s & 3) << 3 | c >>> 5], t[c & 31], t[l >>> 3], t[(l & 7) << 2 | u >>> 6], t[u >>> 1 & 31], t[(u & 1) << 4 | d >>> 4], t[(d & 15) << 1 | f >>> 7], t[f >>> 2 & 31], t[(f & 3) << 3 | p >>> 5], t[p & 31], t[m >>> 3], t[(m & 7) << 2 | h >>> 6], t[h >>> 1 & 31], t[(h & 1) << 4 | g >>> 4], t[(g & 15) << 1 | _ >>> 7], t[_ >>> 2 & 31], t[(_ & 3) << 3 | v >>> 5], t[v & 31], t[y >>> 3], b);
162
105
  }
163
- //#endregion
164
- export { c as BASE32HEX, o as BASE32HEX_NAME, s as BASE64URL, i as BASE64URL_NAME, decodeInto, encode, encodePortable, isEncoded, spareBits };
106
+ export { l as BASE32HEX, o as BASE32HEX_NAME, c as BASE64URL, t as BASE64URL_NAME, decodeInto, encode, isEncoded };
165
107
 
166
108
  //# sourceMappingURL=alphabet.js.map