@anizoptera/uuid-slug 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1052 -261
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +14 -9
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
package/src/migration.ts CHANGED
@@ -1,55 +1,145 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import { BASE32HEX, BASE64URL, decodeInto, encode } from "./alphabet";
4
- import { UuidSlugError } from "./errors";
5
- import { decodeOriginalMask } from "./legacy-mask";
6
- import { decodeMaskedCandidates } from "./mask";
3
+ import { BASE32HEX, BASE64URL, decodeInto, encode } from "./alphabet.ts";
4
+ import {
5
+ INVALID_OPTIONS,
6
+ INVALID_UUID_SLUG,
7
+ findUnknownOption,
8
+ diagnosticValue,
9
+ isUuidSlugError,
10
+ normalizeUuidSlugInput,
11
+ stringInput,
12
+ UuidSlugError,
13
+ } from "./errors.ts";
14
+ import { decodeFirstMaskedCandidate, decodeMaskedCandidates } from "./payload.ts";
15
+ import { findSentinel } from "./sentinel.ts";
16
+ import type { UuidV7MaskRange } from "./payload.ts";
7
17
  import type {
8
- MaskSchema,
9
- MigrationFormat,
10
- UuidSlugMigration,
18
+ UuidSlugMigrationDecoder,
19
+ UuidSlugMigrationFormat,
11
20
  UuidSlugMigrationOptions,
12
21
  UuidString,
22
+ UppercaseUuidString,
13
23
  UuidV7String,
14
- } from "./types";
15
- import { formatUuid } from "./uuid";
24
+ UuidStringFor,
25
+ UuidTextCase,
26
+ UuidTextCaseArguments,
27
+ } from "./types.ts";
28
+ import {
29
+ SEEDED_MASK_FORMAT,
30
+ PLAIN_SLUG_FORMAT,
31
+ FIXED_MASK_FORMAT,
32
+ UUID_TEXT_LOWERCASE,
33
+ UUID_TEXT_UPPERCASE,
34
+ } from "./types.ts";
35
+ import { bytesToUuidString, isUuidTextCase, resolveUuidTextCase } from "./uuid.ts";
36
+
37
+ // These tables and the four-bit checksum define the original wire format.
38
+ // Changing them would change the UUID recovered from an existing slug.
39
+ const PERMUTE = [9, 13, 3, 8, 14, 0, 11, 7, 6, 1, 15, 4, 2, 5, 10, 12] as const;
40
+ const XOR = [
41
+ 0xa2, 0x70, 0x32, 0x7f, 0x98, 0xb8, 0x9b, 0x5e, 0x1b, 0x26, 0xb6, 0x16, 0x96, 0xf9, 0xea, 0x3e,
42
+ ] as const;
43
+ const MIGRATION_OPTIONS = {
44
+ acceptPlainSlug: true,
45
+ acceptFixedMask: true,
46
+ } as const satisfies Record<keyof UuidSlugMigrationOptions, true>;
47
+
48
+ /** Return a matching candidate or undefined; callers resolve sentinels before trying masks. */
49
+ /*#__NO_SIDE_EFFECTS__*/
50
+ function decodeOriginalMask(mixed: Uint8Array): Uint8Array | undefined {
51
+ const bytes = new Uint8Array(16);
52
+ for (let i = 0; i < 16; i++)
53
+ bytes[PERMUTE[i] as number] = (mixed[i] as number) ^ (XOR[i] as number);
54
+ const found = (bytes[6] as number) >>> 4;
55
+ bytes[6] = ((bytes[6] as number) & 15) | 0x70;
56
+ let checksum = 0;
57
+ for (const byte of bytes) checksum ^= byte;
58
+ // A mismatch is expected while trying formats; allocate diagnostics only if the reader fails.
59
+ return ((checksum >>> 4) ^ (checksum & 15)) === found ? bytes : undefined;
60
+ }
16
61
 
17
62
  /** Read old IDs with the codec's keys and sentinels; never change how new IDs are written. */
18
63
  export function createMigration(
19
- schemas: readonly MaskSchema[],
64
+ masks: readonly UuidV7MaskRange[],
20
65
  sentinels: ReadonlyMap<string, { uuid: UuidV7String }>,
21
- options: UuidSlugMigrationOptions = {},
22
- ): UuidSlugMigration {
23
- const original = options.original === true;
24
- const plain = options.plain === true;
66
+ options?: UuidSlugMigrationOptions,
67
+ ): UuidSlugMigrationDecoder | UuidSlugError {
68
+ if (
69
+ options !== undefined &&
70
+ (typeof options !== "object" || options === null || Array.isArray(options))
71
+ )
72
+ return new UuidSlugError(INVALID_OPTIONS, "Migration options must be an object.");
73
+ let originalOption: boolean | undefined;
74
+ let plainOption: boolean | undefined;
75
+ try {
76
+ const unknown = findUnknownOption(options ?? {}, MIGRATION_OPTIONS);
77
+ if (unknown !== undefined)
78
+ return new UuidSlugError(INVALID_OPTIONS, `Unknown migration option: ${unknown}.`);
79
+ originalOption = options?.acceptFixedMask;
80
+ plainOption = options?.acceptPlainSlug;
81
+ } catch (cause) {
82
+ return new UuidSlugError(INVALID_OPTIONS, "Reading migration options failed.", { cause });
83
+ }
84
+ if (originalOption !== undefined && typeof originalOption !== "boolean")
85
+ return new UuidSlugError(
86
+ INVALID_OPTIONS,
87
+ "Migration acceptFixedMask option must be a boolean.",
88
+ );
89
+ if (plainOption !== undefined && typeof plainOption !== "boolean")
90
+ return new UuidSlugError(
91
+ INVALID_OPTIONS,
92
+ "Migration acceptPlainSlug option must be a boolean.",
93
+ );
94
+ const original = originalOption === true;
95
+ const plain = plainOption === true;
25
96
 
26
- function read(slug: string, format: MigrationFormat | undefined, firstOnly: boolean) {
97
+ function read(
98
+ uuidSlug: string | UuidSlugError,
99
+ format: UuidSlugMigrationFormat | undefined,
100
+ firstOnly: boolean,
101
+ ) {
102
+ const slug = normalizeUuidSlugInput(uuidSlug);
103
+ if (typeof slug !== "string") return slug;
27
104
  if (
28
105
  (format !== undefined &&
29
- format !== "current" &&
30
- format !== "original" &&
31
- format !== "plain") ||
32
- (format === "original" && !original) ||
33
- (format === "plain" && !plain)
106
+ format !== SEEDED_MASK_FORMAT &&
107
+ format !== FIXED_MASK_FORMAT &&
108
+ format !== PLAIN_SLUG_FORMAT) ||
109
+ (format === FIXED_MASK_FORMAT && !original) ||
110
+ (format === PLAIN_SLUG_FORMAT && !plain)
34
111
  )
35
112
  return new UuidSlugError(
36
- "invalid_uuid_slug",
37
- "Enable the requested format when creating the migration reader.",
113
+ INVALID_UUID_SLUG,
114
+ format === FIXED_MASK_FORMAT
115
+ ? "Fixed-mask decoding is disabled; create the migration reader with acceptFixedMask: true."
116
+ : format === PLAIN_SLUG_FORMAT
117
+ ? "Plain-slug decoding is disabled; create the migration reader with acceptPlainSlug: true."
118
+ : `Unknown migration format: ${diagnosticValue(format)}.`,
38
119
  );
39
120
 
40
- const sentinel = sentinels.get(slug);
121
+ const sentinel = findSentinel(sentinels, slug);
41
122
  if (sentinel) return [sentinel.uuid];
42
- const useCurrent = format === undefined || format === "current";
43
- const useOriginal = original && (format === undefined || format === "original");
44
- const usePlain = plain && (format === undefined || format === "plain");
123
+ const useCurrent = format === undefined || format === SEEDED_MASK_FORMAT;
124
+ const useOriginal = original && (format === undefined || format === FIXED_MASK_FORMAT);
125
+ const usePlain = plain && (format === undefined || format === PLAIN_SLUG_FORMAT);
45
126
  const bytes = new Uint8Array(16);
46
127
  // Original readers ignored the four trailing bits. Keep those aliases confined to migration.
47
128
  const base32 = slug.length === 26 && usePlain;
48
- const tail = decodeInto(slug, base32 ? BASE32HEX : BASE64URL, bytes, 0, 16, base32 ? 0 : 4);
129
+ const safeMasked = slug.length === 27 && useCurrent;
130
+ const tail = decodeInto(
131
+ slug,
132
+ base32 || safeMasked ? BASE32HEX : BASE64URL,
133
+ bytes,
134
+ 0,
135
+ 16,
136
+ base32 ? 0 : 4,
137
+ );
49
138
  if (tail instanceof Error) return tail;
50
139
  // A base64 alias differs only in its final four bits; reuse the validated text instead of
51
140
  // encoding all sixteen bytes again. Base32 input still needs the sentinel's base64 spelling.
52
141
  const reserved =
142
+ !safeMasked &&
53
143
  (useOriginal || usePlain) &&
54
144
  sentinels.get(
55
145
  base32
@@ -61,44 +151,107 @@ export function createMigration(
61
151
  if (reserved && firstOnly) return [reserved.uuid];
62
152
  const candidates: UuidString[] = reserved ? [reserved.uuid] : [];
63
153
  function add(value: Uint8Array) {
64
- const uuid = formatUuid(value);
154
+ const uuid = bytesToUuidString(value);
65
155
  if (uuid instanceof Error) return uuid;
66
156
  if (!candidates.includes(uuid)) candidates.push(uuid);
67
157
  return undefined;
68
158
  }
69
159
  if (useCurrent && !base32) {
70
- const matches = decodeMaskedCandidates(bytes, tail, schemas, firstOnly, candidates);
71
- if (matches instanceof Error) return matches;
160
+ const matches = firstOnly
161
+ ? decodeFirstMaskedCandidate(bytes, tail, masks, candidates)
162
+ : decodeMaskedCandidates(bytes, tail, masks, candidates);
163
+ if (isUuidSlugError(matches)) return matches;
72
164
  if (firstOnly && candidates.length) return candidates;
73
165
  }
74
166
  // Legacy aliases reserve the raw identity, but their check bits can also encode a current ID.
75
167
  if (reserved) return candidates;
76
168
  if (useOriginal && slug.length === 22) {
77
169
  const match = decodeOriginalMask(bytes);
78
- if (match instanceof Error) return match;
79
170
  if (match) {
80
171
  const failed = add(match);
81
172
  if (failed) return failed;
82
173
  if (firstOnly) return candidates;
83
174
  }
84
175
  }
85
- if (usePlain) {
176
+ if (usePlain && !safeMasked) {
86
177
  const failed = add(bytes);
87
178
  if (failed) return failed;
88
179
  }
89
180
  return candidates;
90
181
  }
91
182
 
183
+ function uuidSlugToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
184
+ uuidSlug: string | UuidSlugError,
185
+ ...textCase: UuidTextCaseArguments<Case>
186
+ ): UuidStringFor<Case> | UuidSlugError;
187
+ function uuidSlugToUuidString(
188
+ uuidSlug: string | UuidSlugError,
189
+ format: UuidSlugMigrationFormat | undefined,
190
+ ): UuidString | UuidSlugError;
191
+ function uuidSlugToUuidString<Case extends UuidTextCase>(
192
+ uuidSlug: string | UuidSlugError,
193
+ format: UuidSlugMigrationFormat,
194
+ textCase: Case,
195
+ ): UuidStringFor<Case> | UuidSlugError;
196
+ function uuidSlugToUuidString<Case extends UuidTextCase>(
197
+ uuidSlug: string | UuidSlugError,
198
+ formatOrCase?: UuidSlugMigrationFormat | Case,
199
+ textCase?: Case,
200
+ ): UuidStringFor<Case> | UuidSlugError {
201
+ const second =
202
+ formatOrCase === undefined || typeof formatOrCase === "string"
203
+ ? formatOrCase
204
+ : (stringInput(formatOrCase) ?? formatOrCase);
205
+ const format = isUuidTextCase(second) ? undefined : second;
206
+ const selectedCase = resolveUuidTextCase(
207
+ (isUuidTextCase(second) ? second : textCase) ?? UUID_TEXT_LOWERCASE,
208
+ );
209
+ if (selectedCase instanceof Error) return selectedCase;
210
+ const result = read(uuidSlug, format as UuidSlugMigrationFormat | undefined, true);
211
+ if (isUuidSlugError(result)) return result;
212
+ const uuid = result[0];
213
+ if (uuid === undefined)
214
+ return new UuidSlugError(INVALID_UUID_SLUG, "Slug does not match an enabled format.");
215
+ return (
216
+ selectedCase === UUID_TEXT_UPPERCASE ? uuid.toUpperCase() : uuid
217
+ ) as UuidStringFor<Case>;
218
+ }
219
+
220
+ function uuidSlugToUuidStringCandidates<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
221
+ uuidSlug: string | UuidSlugError,
222
+ ...textCase: UuidTextCaseArguments<Case>
223
+ ): readonly UuidStringFor<Case>[] | UuidSlugError;
224
+ function uuidSlugToUuidStringCandidates(
225
+ uuidSlug: string | UuidSlugError,
226
+ format: UuidSlugMigrationFormat | undefined,
227
+ ): readonly UuidString[] | UuidSlugError;
228
+ function uuidSlugToUuidStringCandidates<Case extends UuidTextCase>(
229
+ uuidSlug: string | UuidSlugError,
230
+ format: UuidSlugMigrationFormat,
231
+ textCase: Case,
232
+ ): readonly UuidStringFor<Case>[] | UuidSlugError;
233
+ function uuidSlugToUuidStringCandidates(
234
+ uuidSlug: string | UuidSlugError,
235
+ formatOrCase?: UuidSlugMigrationFormat | UuidTextCase,
236
+ textCase?: UuidTextCase,
237
+ ): readonly UuidString[] | readonly UppercaseUuidString[] | UuidSlugError {
238
+ const second =
239
+ formatOrCase === undefined || typeof formatOrCase === "string"
240
+ ? formatOrCase
241
+ : (stringInput(formatOrCase) ?? formatOrCase);
242
+ const format = isUuidTextCase(second) ? undefined : second;
243
+ const selectedCase = resolveUuidTextCase(
244
+ (isUuidTextCase(second) ? second : textCase) ?? UUID_TEXT_LOWERCASE,
245
+ );
246
+ if (selectedCase instanceof Error) return selectedCase;
247
+ const result = read(uuidSlug, format as UuidSlugMigrationFormat | undefined, false);
248
+ if (isUuidSlugError(result)) return result;
249
+ if (selectedCase === UUID_TEXT_LOWERCASE) return result;
250
+ return result.map((uuid) => uuid.toUpperCase() as UppercaseUuidString);
251
+ }
252
+
92
253
  return {
93
- decode(slug, format) {
94
- const result = read(slug, format, true);
95
- return result instanceof Error
96
- ? result
97
- : (result[0] ??
98
- new UuidSlugError("invalid_uuid_slug", "Slug does not match an enabled format."));
99
- },
100
- candidates(slug, format) {
101
- return read(slug, format, false);
102
- },
254
+ uuidSlugToUuidString,
255
+ uuidSlugToUuidStringCandidates,
103
256
  };
104
257
  }
package/src/payload.ts ADDED
@@ -0,0 +1,321 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { BASE32HEX, BASE64URL, BASE64URL_NAME, decodeInto, encode, spareBits } from "./alphabet.ts";
4
+ import {
5
+ INVALID_MASK,
6
+ INVALID_TIMESTAMP,
7
+ INVALID_UUID_SLUG,
8
+ isUuidSlugError,
9
+ UuidSlugError,
10
+ } from "./errors.ts";
11
+ import { mix32, read32 } from "./feistel.ts";
12
+ import { applyMask } from "./mask-handle.ts";
13
+ import { bytesToUuidString } from "./uuid.ts";
14
+ import type { UuidV7Mask, MaskedUuidV7Slug, UuidString } from "./types.ts";
15
+ import type { SlugAlphabet } from "./slug.ts";
16
+
17
+ export type UuidV7MaskRange = {
18
+ readonly mask: UuidV7Mask;
19
+ readonly timestampRangeStartUnixMs: number;
20
+ };
21
+
22
+ const MASK_DIRECTION = "mask";
23
+ const MASKING = "masking";
24
+ const NO_MASK_MATCH_MESSAGE =
25
+ "No configured mask and timestamp range decodes this slug: its check fails for every configured pair.";
26
+ const UNMASK_DIRECTION = "unmask";
27
+ const UNMASKING = "unmasking";
28
+
29
+ const MAX_MASKED_UUID_V7_HIGH_BYTE = 0x03;
30
+ /** Largest timestamp offset that fits in a masked UUIDv7 payload. */
31
+ export const MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS: number =
32
+ (MAX_MASKED_UUID_V7_HIGH_BYTE + 1) * 2 ** 40 - 1;
33
+
34
+ function readUnixMs(bytes: Uint8Array): number {
35
+ return (
36
+ (bytes[0] as number) * 2 ** 40 +
37
+ (bytes[1] as number) * 2 ** 32 +
38
+ (bytes[2] as number) * 2 ** 24 +
39
+ (bytes[3] as number) * 2 ** 16 +
40
+ (bytes[4] as number) * 2 ** 8 +
41
+ (bytes[5] as number)
42
+ );
43
+ }
44
+
45
+ function writeUnixMs(bytes: Uint8Array, unixMs: number): void {
46
+ bytes[0] = Math.floor(unixMs / 2 ** 40);
47
+ bytes[1] = Math.floor(unixMs / 2 ** 32);
48
+ bytes[2] = unixMs >>> 24;
49
+ bytes[3] = unixMs >>> 16;
50
+ bytes[4] = unixMs >>> 8;
51
+ bytes[5] = unixMs;
52
+ }
53
+
54
+ /** Custom callbacks can fail after construction; preserve their cause in the public error contract. */
55
+ function applyMix(
56
+ mask: UuidV7Mask,
57
+ input: Uint8Array,
58
+ output: Uint8Array,
59
+ direction: typeof MASK_DIRECTION | typeof UNMASK_DIRECTION,
60
+ ): undefined | UuidSlugError {
61
+ try {
62
+ const cause = applyMask(mask, input, output, direction);
63
+ return cause
64
+ ? new UuidSlugError(
65
+ INVALID_MASK,
66
+ `UUIDv7 mask "${mask.diagnosticLabel}" failed while ${direction === MASK_DIRECTION ? MASKING : UNMASKING}.`,
67
+ { cause },
68
+ )
69
+ : undefined;
70
+ } catch (cause) {
71
+ return new UuidSlugError(
72
+ INVALID_MASK,
73
+ `UUIDv7 mask "${mask.diagnosticLabel}" failed while ${direction === MASK_DIRECTION ? MASKING : UNMASKING}.`,
74
+ { cause },
75
+ );
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Spread every input word across the check so structured UUID fields do not collapse into a sum.
81
+ * This avalanche mixer supplies error detection, not authentication or a cryptographic-strength
82
+ * claim; `docs/security.md` defines that boundary.
83
+ *
84
+ * Taken from the TOP so that widening the check never renumbers the bits below it.
85
+ */
86
+ /*#__NO_SIDE_EFFECTS__*/
87
+ function tagFor(bytes: Uint8Array, width: number) {
88
+ let acc = 0;
89
+ for (let offset = 0; offset < 16; offset += 4) acc = mix32(acc ^ read32(bytes, offset));
90
+ return acc >>> (32 - width);
91
+ }
92
+
93
+ /**
94
+ * The 12 check bits a UUIDv7 can hold inside the block, because it spends them on nothing: bits
95
+ * 0-3 in byte 6's version nibble, 4-5 in byte 8's variant bits, 6-11 in byte 0's top six. The
96
+ * timestamp is stored as a 42-bit offset, so those top six bits are zero. The rest of the check
97
+ * rides outside the block, in whatever the encoding has spare.
98
+ *
99
+ * Encoding must reject an offset at or past 2^42 ms rather than truncate it.
100
+ */
101
+ function injectTag(bytes: Uint8Array, tag: number) {
102
+ bytes[6] = ((tag & 0x0f) << 4) | ((bytes[6] ?? 0) & 0x0f);
103
+ bytes[8] = ((tag & 0x30) << 2) | ((bytes[8] ?? 0) & 0x3f);
104
+ bytes[0] = (((tag >>> 6) & 0x3f) << 2) | ((bytes[0] ?? 0) & 0x03);
105
+ }
106
+
107
+ /*#__NO_SIDE_EFFECTS__*/
108
+ function extractTag(bytes: Uint8Array) {
109
+ return ((bytes[6] ?? 0) >>> 4) | (((bytes[8] ?? 0) >>> 6) << 4) | (((bytes[0] ?? 0) >>> 2) << 6);
110
+ }
111
+
112
+ /** Puts back the constants the tag displaced, so the block equals the UUID the caller handed in. */
113
+ function restoreV7(bytes: Uint8Array) {
114
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70;
115
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
116
+ bytes[0] = (bytes[0] ?? 0) & 0x03;
117
+ }
118
+
119
+ /** Restore the fixed ciphertext block without allocating views or per-key buffers. */
120
+ function restoreCiphertext(bytes: Uint8Array, a: number, b: number, c: number, d: number) {
121
+ bytes[0] = a >>> 24;
122
+ bytes[1] = a >>> 16;
123
+ bytes[2] = a >>> 8;
124
+ bytes[3] = a;
125
+ bytes[4] = b >>> 24;
126
+ bytes[5] = b >>> 16;
127
+ bytes[6] = b >>> 8;
128
+ bytes[7] = b;
129
+ bytes[8] = c >>> 24;
130
+ bytes[9] = c >>> 16;
131
+ bytes[10] = c >>> 8;
132
+ bytes[11] = c;
133
+ bytes[12] = d >>> 24;
134
+ bytes[13] = d >>> 16;
135
+ bytes[14] = d >>> 8;
136
+ bytes[15] = d;
137
+ }
138
+
139
+ /** The 12 check bits that fit inside the block; the rest ride in the encoding's spare bits. */
140
+ const INNER_TAG_BITS = 12;
141
+
142
+ /**
143
+ * The existing base64url wire format fixes four outer check bits. Alternate spellings preserve
144
+ * all 132 bits; the safe base32hex spelling adds three zero padding bits, not more check bits.
145
+ */
146
+ const OUTER_TAG_BITS = spareBits(BASE64URL, 16);
147
+ const TAG_BITS = INNER_TAG_BITS + OUTER_TAG_BITS;
148
+
149
+ /**
150
+ * Mask a private block in place. Callers must own `raw`: tag injection destroys its UUID bytes.
151
+ * This separate entry keeps mutation impossible on the ordinary caller-owned byte path while a
152
+ * freshly parsed UUID string can avoid an otherwise redundant copy.
153
+ */
154
+ export function ownedUuidV7BytesToMaskedSlug(
155
+ raw: Uint8Array,
156
+ mask: UuidV7Mask,
157
+ alphabet: SlugAlphabet = BASE64URL_NAME,
158
+ reserved?: { readonly size: number; has(slug: string): boolean },
159
+ timestampRangeStartUnixMs = 0,
160
+ ): MaskedUuidV7Slug | UuidSlugError {
161
+ // Truncating instead would make encoding non-injective — two UUIDs would share one slug, and no
162
+ // decoder could ever tell which was meant. Refusing is the only recoverable answer.
163
+ const timestamp = readUnixMs(raw);
164
+ const timestampOffset = timestamp - timestampRangeStartUnixMs;
165
+ if (timestampOffset < 0 || timestampOffset > MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS)
166
+ return new UuidSlugError(
167
+ INVALID_TIMESTAMP,
168
+ `Masking accepts UUIDv7 timestamps from Unix millisecond ${timestampRangeStartUnixMs} through ${timestampRangeStartUnixMs + MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS}; got ${timestamp}.`,
169
+ );
170
+ const tag = tagFor(raw, TAG_BITS);
171
+ writeUnixMs(raw, timestampOffset);
172
+ injectTag(raw, tag >>> OUTER_TAG_BITS);
173
+ // Every mask receives an isolated block. Reusing that block as output removes a second
174
+ // allocation; built-in transforms read all words before writing and custom transforms copy input.
175
+ const failed = applyMix(mask, raw, raw, MASK_DIRECTION);
176
+ if (failed) return failed;
177
+ const tail = tag & ((1 << OUTER_TAG_BITS) - 1);
178
+ // Raw sentinels have zero outer bits. Only that tail can collide with retained base64 reads;
179
+ // other writes need neither a second encoding nor a lookup for a collision that cannot occur.
180
+ // Skipping the lookup matters: on V8 it hashed and flattened every base64url slug
181
+ // (bench/PERFORMANCE.md).
182
+ const canonical =
183
+ alphabet === BASE64URL_NAME || (tail === 0 && reserved?.size)
184
+ ? encode(raw, BASE64URL, tail, OUTER_TAG_BITS)
185
+ : undefined;
186
+ if (tail === 0 && canonical !== undefined && reserved?.has(canonical))
187
+ return new UuidSlugError(
188
+ INVALID_MASK,
189
+ "Masked output collides with a reserved sentinel. Configure a different mask or sentinel set.",
190
+ );
191
+ return (
192
+ canonical !== undefined && alphabet === BASE64URL_NAME
193
+ ? canonical
194
+ : encode(raw, BASE32HEX, tail, OUTER_TAG_BITS)
195
+ ) as MaskedUuidV7Slug;
196
+ }
197
+
198
+ /** Report a slug that every configured mask's check rejects. */
199
+ export const noMaskedSlugMatch = /* @__NO_SIDE_EFFECTS__ */ (): UuidSlugError =>
200
+ new UuidSlugError(INVALID_UUID_SLUG, NO_MASK_MATCH_MESSAGE);
201
+
202
+ /**
203
+ * Decode a masked slug and return `undefined` when every mask's check rejects it. Source-specific
204
+ * readers report that miss with `noMaskedSlugMatch`; a codec reading an ambiguous 22-character slug
205
+ * takes the plain reading instead, so the miss builds no error. Readers call this directly: a wrapper
206
+ * that built the error slowed the masked-slug text reader on Node (bench/PERFORMANCE.md).
207
+ */
208
+ export function unmaskSlug(
209
+ slug: string,
210
+ current: UuidV7MaskRange,
211
+ previous: readonly UuidV7MaskRange[] = [],
212
+ ): Uint8Array | UuidSlugError | undefined {
213
+ if (typeof slug !== "string")
214
+ return new UuidSlugError(INVALID_UUID_SLUG, "Masked UUID slug must be a string.");
215
+ const mixed = new Uint8Array(16);
216
+ const outerTag = decodeInto(
217
+ slug,
218
+ slug.length === 27 ? BASE32HEX : BASE64URL,
219
+ mixed,
220
+ 0,
221
+ 16,
222
+ OUTER_TAG_BITS,
223
+ );
224
+ if (outerTag instanceof Error) return outerTag;
225
+ if (!previous.length) {
226
+ return unmix(mixed, outerTag, current);
227
+ }
228
+ const word0 = read32(mixed, 0);
229
+ const word1 = read32(mixed, 4);
230
+ const word2 = read32(mixed, 8);
231
+ const word3 = read32(mixed, 12);
232
+ const primary = unmix(mixed, outerTag, current);
233
+ if (isUuidSlugError(primary)) return primary;
234
+ if (primary) return primary;
235
+ // Scalar ciphertext survives in-place attempts without allocating a block for every decode.
236
+ for (const older of previous) {
237
+ restoreCiphertext(mixed, word0, word1, word2, word3);
238
+ const decoded = unmix(mixed, outerTag, older);
239
+ if (isUuidSlugError(decoded)) return decoded;
240
+ if (decoded) return decoded;
241
+ }
242
+ return undefined;
243
+ }
244
+
245
+ /** Capture the first passing UUID before another callback can mutate its private bytes. */
246
+ export function decodeFirstMaskedCandidate(
247
+ mixed: Uint8Array,
248
+ outerTag: number,
249
+ masks: readonly UuidV7MaskRange[],
250
+ candidates: UuidString[] = [],
251
+ ): UuidString[] | UuidSlugError {
252
+ for (const mask of masks) {
253
+ const decoded = unmix(mixed.slice(), outerTag, mask);
254
+ if (isUuidSlugError(decoded)) return decoded;
255
+ if (decoded) {
256
+ const uuid = bytesToUuidString(decoded);
257
+ if (uuid instanceof Error) return uuid;
258
+ if (!candidates.includes(uuid)) candidates.push(uuid);
259
+ break;
260
+ }
261
+ }
262
+ return candidates;
263
+ }
264
+
265
+ /** Append every distinct candidate while allocating one callback-isolated block for the scan. */
266
+ export function decodeMaskedCandidates(
267
+ mixed: Uint8Array,
268
+ outerTag: number,
269
+ masks: readonly UuidV7MaskRange[],
270
+ candidates: UuidString[] = [],
271
+ ): UuidString[] | UuidSlugError {
272
+ if (!masks.length) return candidates;
273
+ const working = mixed.slice();
274
+ const firstMask = masks[0];
275
+ if (!firstMask) return candidates;
276
+ const firstDecoded = unmix(working, outerTag, firstMask);
277
+ if (isUuidSlugError(firstDecoded)) return firstDecoded;
278
+ if (firstDecoded) {
279
+ const uuid = bytesToUuidString(firstDecoded);
280
+ if (uuid instanceof Error) return uuid;
281
+ if (!candidates.includes(uuid)) candidates.push(uuid);
282
+ }
283
+ if (masks.length === 1) return candidates;
284
+ const word0 = read32(mixed, 0);
285
+ const word1 = read32(mixed, 4);
286
+ const word2 = read32(mixed, 8);
287
+ const word3 = read32(mixed, 12);
288
+ for (let index = 1; index < masks.length; index += 1) {
289
+ const mask = masks[index];
290
+ if (!mask) continue;
291
+ // Custom callbacks may mutate their input; no key may alter what the next one sees.
292
+ restoreCiphertext(working, word0, word1, word2, word3);
293
+ const decoded = unmix(working, outerTag, mask);
294
+ // A failed callback means the candidate list is incomplete, not that its key mismatched.
295
+ if (isUuidSlugError(decoded)) return decoded;
296
+ if (decoded) {
297
+ const uuid = bytesToUuidString(decoded);
298
+ if (uuid instanceof Error) return uuid;
299
+ if (!candidates.includes(uuid)) candidates.push(uuid);
300
+ }
301
+ }
302
+ return candidates;
303
+ }
304
+
305
+ function unmix(
306
+ mixed: Uint8Array,
307
+ outerTag: number,
308
+ range: UuidV7MaskRange,
309
+ ): Uint8Array | undefined | UuidSlugError {
310
+ // `mixed` is already private to this mask attempt, so the same alias-safe transform contract
311
+ // can write back into it instead of allocating another block.
312
+ const failed = applyMix(range.mask, mixed, mixed, UNMASK_DIRECTION);
313
+ if (failed) return failed;
314
+ // Both halves come out of the same decryption, so a wrong key garbles the observed check as
315
+ // thoroughly as the payload: the tag needs no key of its own to tell keys apart.
316
+ const foundTag = (extractTag(mixed) << OUTER_TAG_BITS) | outerTag;
317
+ restoreV7(mixed);
318
+ writeUnixMs(mixed, readUnixMs(mixed) + range.timestampRangeStartUnixMs);
319
+ if (tagFor(mixed, TAG_BITS) !== foundTag) return undefined;
320
+ return mixed;
321
+ }