@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/types.ts CHANGED
@@ -1,273 +1,827 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import type { UuidSlugError } from "./errors";
4
- import type { SlugAlphabet } from "./uuid";
3
+ import type { UuidSlugError } from "./errors.ts";
4
+ import type { SlugAlphabet } from "./slug.ts";
5
+ import type { UuidV7MaskingCodec } from "./masking-codec-types.ts";
6
+
7
+ export type {
8
+ UuidV7MaskingCodec,
9
+ UuidV7MaskingCodecOptions,
10
+ UuidV7MaskingCodecSharedOptions,
11
+ UuidV7PreviousMask,
12
+ } from "./masking-codec-types.ts";
5
13
 
6
14
  declare const brand: unique symbol;
15
+ declare const uuidV7MaskBrand: unique symbol;
16
+
17
+ /** Select the standard lowercase UUID text spelling. */
18
+ export const UUID_TEXT_LOWERCASE = "lowercase";
19
+ /** Select the standard uppercase UUID text spelling. */
20
+ export const UUID_TEXT_UPPERCASE = "uppercase";
21
+ /** Keep emitting from the last UUID timestamp when the clock moves backward. */
22
+ export const UUID_V7_ROLLBACK_PRESERVE = "preserve";
23
+ /** Restart the sequence at the earlier clock reading after the configured tolerance. */
24
+ export const UUID_V7_ROLLBACK_RESET = "reset";
25
+ /** Return `invalid_timestamp` after the configured rollback tolerance. */
26
+ export const UUID_V7_ROLLBACK_ERROR = "error";
27
+
28
+ /** Select the hexadecimal letter case of UUID text output. JavaScript also accepts genuine `String` objects. */
29
+ export type UuidTextCase = typeof UUID_TEXT_LOWERCASE | typeof UUID_TEXT_UPPERCASE;
30
+
31
+ // Only case sets containing the runtime default may omit the selector. A required uppercase
32
+ // tuple prevents explicit generics from inventing a spelling without changing runtime work.
33
+ export type UuidTextCaseArguments<Case extends UuidTextCase> =
34
+ typeof UUID_TEXT_LOWERCASE extends Case ? [textCase?: Case] : [textCase: Case];
35
+
36
+ // Keep selector inference at the property while requiring a non-default selector in reusable options.
37
+ type UuidTextCaseOptions<Case extends UuidTextCase> = typeof UUID_TEXT_LOWERCASE extends Case
38
+ ? { readonly textCase?: Case }
39
+ : { readonly textCase: Case };
40
+
41
+ /** The complete four-bit UUID version field, whether assigned or reserved. */
42
+ export type UuidVersion = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15;
43
+
44
+ /** UUID bits use the Apollo NCS layout. */
45
+ export const UUID_VARIANT_NCS = "ncs";
46
+ /** UUID bits use the RFC 9562 layout. */
47
+ export const UUID_VARIANT_RFC = "rfc";
48
+ /** UUID bits use the reserved Microsoft layout. */
49
+ export const UUID_VARIANT_MICROSOFT = "microsoft";
50
+ /** UUID bits use the reserved future layout. */
51
+ export const UUID_VARIANT_FUTURE = "future";
52
+
53
+ /** The layout family selected by the UUID variant bits. */
54
+ export type UuidVariant =
55
+ | typeof UUID_VARIANT_NCS
56
+ | typeof UUID_VARIANT_RFC
57
+ | typeof UUID_VARIANT_MICROSOFT
58
+ | typeof UUID_VARIANT_FUTURE;
59
+
60
+ /** Choose how one created generator handles a clock reading below its accepted high-water mark. JavaScript also accepts a genuine `String` object for `action`. */
61
+ export type UuidV7ClockRollbackPolicy =
62
+ | { readonly action: typeof UUID_V7_ROLLBACK_PRESERVE }
63
+ | {
64
+ readonly action: typeof UUID_V7_ROLLBACK_RESET | typeof UUID_V7_ROLLBACK_ERROR;
65
+ /** Preserve the previous timestamp while total clock skew is at most this many milliseconds. */
66
+ readonly toleranceMs: number;
67
+ };
7
68
 
8
69
  /**
9
- * Nominal marker. The names ACCUMULATE as a key set rather than replacing one another, which is
10
- * what makes nesting work: `Brand<Brand<string, "A">, "B">` carries both keys, so it is assignable
11
- * to the "A" brand but not the reverse and not to a sibling "C".
12
- *
13
- * Writing the name as the property's TYPE instead — `{ [brand]?: Name }` — intersects to
14
- * `"A" & "B"`, i.e. `never`, on the second level. Every nested brand then has the same `never`
15
- * marker and they are all mutually assignable: measured 2026-08-12, `UuidV4Slug` and `UuidV7Slug`
16
- * were interchangeable, as were a plain slug and a masked one, for the entire life of the type.
17
- *
18
- * The property stays OPTIONAL so a string literal is still accepted wherever a brand is asked for.
19
- * These types separate values the package produces; they are not a parsing obligation on callers.
70
+ * Fill every requested byte synchronously or return `UuidSlugError`.
71
+ * The caller owns entropy quality; partial fills cannot be detected. Recognized package errors
72
+ * propagate unchanged. Thrown values and other Error values become `rng_unavailable` with a cause.
73
+ */
74
+ export type UuidRandomFill = (bytes: Uint8Array) => void | UuidSlugError;
75
+
76
+ /** Accumulate validated value kinds without changing their runtime representation. */
77
+ type Brand<Value, Name extends string> = Value & {
78
+ readonly [brand]: { [BrandName in Name]: true };
79
+ };
80
+
81
+ /** Valid mixed-case canonical, compact, URN, or brace-wrapped UUID text; this proves syntax only. */
82
+ export type UuidText = Brand<string, "UuidText">;
83
+ /** Valid UUIDv4 text with RFC variant bits, in any accepted spelling. */
84
+ export type UuidV4Text = Brand<UuidText, "UuidV4Text">;
85
+ /** Valid UUIDv7 text with RFC variant bits, in any accepted spelling. Its 74 payload bits have no inferred meaning. */
86
+ export type UuidV7Text = Brand<UuidText, "UuidV7Text">;
87
+ /** Canonical lowercase UUID text. This proves syntax only, not version or issuance. */
88
+ export type UuidString = Brand<UuidText, "UuidString">;
89
+ /** Standard uppercase UUID text. This proves syntax only, not version or issuance. */
90
+ export type UppercaseUuidString = Brand<UuidText, "UppercaseUuidString">;
91
+ /** UUID text inferred from its requested output case. */
92
+ export type UuidStringFor<Case extends UuidTextCase> = Case extends typeof UUID_TEXT_UPPERCASE
93
+ ? UppercaseUuidString
94
+ : UuidString;
95
+ /** Canonical lowercase UUIDv4 text with RFC variant bits. */
96
+ export type UuidV4String = Brand<UuidString & UuidV4Text, "UuidV4String">;
97
+ /** Uppercase UUIDv4 text with RFC variant bits. */
98
+ export type UppercaseUuidV4String = Brand<UppercaseUuidString & UuidV4Text, "UuidV4String">;
99
+ /** UUIDv4 text inferred from its requested output case. */
100
+ export type UuidV4StringFor<Case extends UuidTextCase> = Case extends typeof UUID_TEXT_UPPERCASE
101
+ ? UppercaseUuidV4String
102
+ : UuidV4String;
103
+ /** Canonical lowercase UUIDv7 text with RFC variant bits. */
104
+ export type UuidV7String = Brand<UuidString & UuidV7Text, "UuidV7String">;
105
+ /** Uppercase UUIDv7 text with RFC variant bits. */
106
+ export type UppercaseUuidV7String = Brand<UppercaseUuidString & UuidV7Text, "UuidV7String">;
107
+ /** UUIDv7 text inferred from its requested output case. */
108
+ export type UuidV7StringFor<Case extends UuidTextCase> = Case extends typeof UUID_TEXT_UPPERCASE
109
+ ? UppercaseUuidV7String
110
+ : UuidV7String;
111
+ /** A reversible plain UUID encoding: 22 base64url or 26 lowercase base32hex characters. */
112
+ export type PlainUuidSlug = Brand<string, "PlainUuidSlug">;
113
+ /** A plain slug whose decoded UUID is version 4 with the RFC variant. */
114
+ export type PlainUuidV4Slug = Brand<PlainUuidSlug, "PlainUuidV4Slug">;
115
+ /** A plain slug whose decoded UUID is version 7 with the RFC variant. */
116
+ export type PlainUuidV7Slug = Brand<PlainUuidSlug, "PlainUuidV7Slug">;
117
+ // Byte brands record generation or a guard, but a later write can change any UUID bit. Keeping
118
+ // their old version on immutable output would make a false promise. Infer it only from immutable
119
+ // values; revisit if byte inputs acquire an enforced immutable representation.
120
+ /** Carry a UUID version from immutable input; mutable bytes cannot prove their current version. */
121
+ export type PreserveUuidVersion<Input, UnknownVersion, Version4, Version7> =
122
+ Input extends UuidSlugError
123
+ ? never
124
+ : Input extends Uuid<infer Version, boolean, boolean>
125
+ ? Version extends 4
126
+ ? Version4
127
+ : Version extends 7
128
+ ? Version7
129
+ : UnknownVersion
130
+ : Input extends UuidV4Text | PlainUuidV4Slug
131
+ ? Version4
132
+ : Input extends UuidV7Text | PlainUuidV7Slug | MaskedUuidSlug
133
+ ? Version7
134
+ : UnknownVersion;
135
+ /** Infer a version from immutable input; mutable bytes retain the complete version-field range. */
136
+ export type UuidVersionOf<Input> = Input extends UuidSlugError
137
+ ? never
138
+ : Input extends Uuid<infer Version, boolean, boolean>
139
+ ? Version
140
+ : Input extends UuidV4Text | PlainUuidV4Slug
141
+ ? 4
142
+ : Input extends UuidV7Text | PlainUuidV7Slug | MaskedUuidSlug
143
+ ? 7
144
+ : UuidVersion;
145
+ // Plain slug brands do not carry the alphabet. A plain UUIDv4 base64url spelling can pass a
146
+ // codec's mask check and name a UUIDv7 instead; preserving v4 alone would promise false facts.
147
+ // Keyless readers keep the original brand. Revisit if input brands distinguish the alphabets.
148
+ export type MaskingCodecUuidInput<Input> = Input extends PlainUuidV4Slug
149
+ ? PlainUuidV4Slug | MaskedUuidV7Slug
150
+ : Input;
151
+
152
+ /** A masked payload in either spelling; its check bits are not plain-encoding padding. */
153
+ type MaskedUuidSlug = Brand<string, "MaskedUuidSlug">;
154
+ /**
155
+ * A checked, keyed UUIDv7 payload: 22 base64url or 27 lowercase base32hex characters.
156
+ * Both spellings hide recognizable UUID field positions. The check detects wrong keys and
157
+ * malformed values; it does not prove issuance or authorization.
20
158
  */
21
- export type Brand<T, Name extends string> = T & { readonly [brand]?: { [K in Name]: true } };
22
-
23
- export type Base64UrlString = Brand<string, "Base64UrlString">;
24
- export type UuidString = Brand<string, "UuidString">;
25
- export type UuidV4String = Brand<UuidString, "UuidV4String">;
26
- export type UuidV7String = Brand<UuidString, "UuidV7String">;
27
- /** Either alphabet — 22 base64url characters or 26 base32hex — so NOT a `Base64UrlString`. */
28
- export type UuidSlug = Brand<string, "UuidSlug">;
29
- export type UuidV4Slug = Brand<UuidSlug, "UuidV4Slug">;
30
- export type UuidV7Slug = Brand<UuidSlug, "UuidV7Slug">;
31
- /** Masked slugs are base64url only, so this narrows where `UuidSlug` cannot. */
32
- export type MaskedUuidSlug = Brand<Base64UrlString & UuidSlug, "MaskedUuidSlug">;
33
159
  export type MaskedUuidV7Slug = Brand<MaskedUuidSlug, "MaskedUuidV7Slug">;
34
- export type SentinelUuidV7Slug = Brand<UuidV7Slug, "SentinelUuidV7Slug">;
35
- export type PublicUuidV7Slug = MaskedUuidV7Slug | SentinelUuidV7Slug;
36
- export type UuidBytes = Brand<Uint8Array, "UuidBytes">;
160
+ /** An application sentinel written as its ordinary 22- or 26-character plain UUIDv7 slug. */
161
+ export type SentinelUuidV7Slug = Brand<PlainUuidV7Slug, "SentinelUuidV7Slug">;
162
+ /** A masking result: either a masked UUIDv7 or a registered plain sentinel. */
163
+ export type MaskedOrSentinelUuidV7Slug = MaskedUuidV7Slug | SentinelUuidV7Slug;
37
164
 
38
- export interface FreshValidationOptions {
39
- /** Finite Unix milliseconds; read once per validation. */
40
- now?: () => number;
41
- /** Finite, nonnegative radius around now, inclusive in both directions; default 24 hours. */
42
- windowMs?: number;
165
+ /** One generated UUIDv7 in the selected text case and one selected slug made from the same bytes. */
166
+ export interface GeneratedUuidV7<
167
+ Slug extends PlainUuidV7Slug | MaskedOrSentinelUuidV7Slug,
168
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
169
+ > {
170
+ /** UUIDv7 text in the requested case. */
171
+ readonly uuid: UuidV7StringFor<Case>;
172
+ /** Selected plain, masked, or sentinel spelling of the same UUID bytes. */
173
+ readonly slug: Slug;
43
174
  }
44
175
 
45
- export interface UuidV7Generator {
46
- uuidV7(this: void): UuidV7String;
47
- uuidV7Bytes(this: void, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
176
+ /** Inclusive bounds that contain every UUIDv7 from the requested Unix-millisecond interval. */
177
+ export interface UuidV7Bounds<Value extends UuidV7StringFor<UuidTextCase> | UuidV7Bytes> {
178
+ /** Smallest RFC-variant UUIDv7 at the first requested millisecond. */
179
+ readonly startInclusive: Value;
180
+ /** Largest RFC-variant UUIDv7 at the last requested millisecond. */
181
+ readonly endInclusive: Value;
182
+ }
183
+
184
+ /** Describe the leading UUIDv7 payload fields that the caller already knows were encoded. */
185
+ export interface UuidV7PayloadLayout {
186
+ /** Number of leading `rand_a` bits holding an RFC 9562 Method 3 fraction; `0` means absent. */
187
+ readonly subMillisecondFractionBits: number;
188
+ /** Number of following bits holding an RFC 9562 Method 1 fixed counter; `0` means absent. */
189
+ readonly counterBits: number;
190
+ }
191
+
192
+ /** UUIDv7 payload decoded under a caller-supplied layout. */
193
+ export interface UuidV7Payload {
194
+ /** Standard 48-bit Unix millisecond timestamp. */
195
+ readonly unixMs: number;
196
+ /** Method 3 fraction bucket, or `undefined` when the layout assigns no fraction bits. */
197
+ readonly subMillisecondFraction: { readonly value: number; readonly bits: number } | undefined;
198
+ /** Method 1 counter, or `undefined` when the layout assigns no counter bits. */
199
+ readonly counter: { readonly value: bigint; readonly bits: number } | undefined;
200
+ /** Least-significant payload bits whose meaning the layout does not declare. */
201
+ readonly remaining: { readonly value: bigint; readonly bits: number };
202
+ }
203
+
204
+ /** Stable facts read from one immutable UUID without interpreting application-owned payload bits. */
205
+ export interface UuidInspection<Version extends UuidVersion = UuidVersion> {
206
+ /** Canonical lowercase UUID text. */
207
+ readonly uuid: UuidStringForVersion<Version, typeof UUID_TEXT_LOWERCASE>;
208
+ /** The complete four-bit version field, whether assigned or reserved. */
209
+ readonly version: Version;
210
+ /** The UUID layout family selected by the variant bits. */
211
+ readonly variant: UuidVariant;
212
+ /** Standard UUIDv7 Unix milliseconds, present only for an RFC-variant UUIDv7. */
213
+ readonly unixMs: number | undefined;
214
+ /** Whether every UUID bit is zero. */
215
+ readonly isNil: boolean;
216
+ /** Whether every UUID bit is one. */
217
+ readonly isMax: boolean;
218
+ }
219
+
220
+ /** Canonical UUID text narrowed when the parsed value proves version 4 or 7. */
221
+ export type UuidStringForVersion<Version, Case extends UuidTextCase> = Version extends 4
222
+ ? UuidV4StringFor<Case>
223
+ : Version extends 7
224
+ ? UuidV7StringFor<Case>
225
+ : UuidStringFor<Case>;
226
+ /** UUID bytes narrowed when the parsed value proves version 4 or 7. */
227
+ export type UuidBytesForVersion<Version> = Version extends 4
228
+ ? UuidV4Bytes
229
+ : Version extends 7
230
+ ? UuidV7Bytes
231
+ : UuidBytes;
232
+ /** Plain UUID slug narrowed when the parsed value proves version 4 or 7. */
233
+ export type PlainUuidSlugForVersion<Version> = Version extends 4
234
+ ? PlainUuidV4Slug
235
+ : Version extends 7
236
+ ? PlainUuidV7Slug
237
+ : PlainUuidSlug;
238
+
239
+ /** An immutable parsed UUID with optional preset masking and UUIDv7 payload-layout capabilities. */
240
+ export interface Uuid<
241
+ Version extends UuidVersion = UuidVersion,
242
+ HasMaskingCodec extends boolean = false,
243
+ HasPayloadLayout extends boolean = false,
244
+ > {
245
+ // Only true promises a preset; false discards that knowledge so general Uuid storage stays valid.
246
+ // Optional phantom state rejects invented presets without adding runtime properties;
247
+ // method arity alone is assignable in both directions.
248
+ /** Compile-time preset distinctions; no property is stored on the UUID. */
249
+ readonly [brand]?: {
250
+ readonly maskingCodec: [HasMaskingCodec] extends [true] ? true : boolean;
251
+ readonly payloadLayout: [HasPayloadLayout] extends [true] ? true : boolean;
252
+ };
253
+ /** The UUID version field. */
254
+ readonly version: Version;
255
+ // Infer bit facts from the actual receiver so mixed versions stay callable. Merely widening
256
+ // the receiver while retaining Version would let a borrowed method invent a version brand.
257
+ /** Return stable UUID facts in one serializable record. */
258
+ inspect<Receiver extends AnyUuid>(this: Receiver): UuidInspection<Receiver["version"]>;
259
+ /** Return canonical UUID text, lowercase by default. */
260
+ toString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
261
+ this: Uuid<Version, boolean, boolean>,
262
+ ...textCase: UuidTextCaseArguments<Case>
263
+ ): UuidStringForVersion<Version, Case>;
264
+ /** Convert a mixed-version receiver while retaining every version it proves. */
265
+ toString<
266
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
267
+ Receiver extends AnyUuid = AnyUuid,
268
+ >(
269
+ this: Receiver,
270
+ ...textCase: UuidTextCaseArguments<Case>
271
+ ): UuidStringForVersion<Receiver["version"], Case>;
272
+ /** Return a new plain 16-byte UUID array. */
273
+ toBytes<Receiver extends AnyUuid>(this: Receiver): UuidBytesForVersion<Receiver["version"]>;
274
+ /** Write the UUID into caller-owned storage after validating the complete destination range. */
275
+ toBytes<Output extends Uint8Array>(
276
+ this: AnyUuid,
277
+ output: Output,
278
+ outputOffset?: number,
279
+ ): UuidOutput<Output> | UuidSlugError;
280
+ /** Return a plain UUID slug, using base64url by default. */
281
+ toPlainSlug<Receiver extends AnyUuid>(
282
+ this: Receiver,
283
+ alphabet?: SlugAlphabet,
284
+ ): PlainUuidSlugForVersion<Receiver["version"]>;
285
+ // Explicit configuration needs no preset evidence. Keep the preset overload last so bind/call
286
+ // retain its omission rule; the other retained capability cannot affect this operation.
287
+ /** Convert UUIDv7 with an explicit codec, including receivers with mixed preset capabilities. */
288
+ toMaskedSlug(
289
+ this: Uuid<Version, boolean, boolean>,
290
+ maskingCodec: 7 extends Version ? UuidV7MaskingCodec : never,
291
+ ): MaskedOrSentinelUuidV7Slug | UuidSlugError;
48
292
  /**
49
- * Generate at a caller-supplied millisecond. A SEPARATE entry point rather than an optional
50
- * trailing parameter on the pair above, because an optional positional timestamp is silently
51
- * mappable: `Array.from({length: n}, gen.uuidV7Bytes)` would pass the index as the instant and
52
- * mint n ids dated 1970, with no type error. Taking the timestamp FIRST makes that impossible.
53
- *
54
- * Returns an Error rather than throwing on a bad instant: a caller-supplied value out of range
55
- * is ordinary input validation, not an exceptional condition.
293
+ * Return the masked UUIDv7 spelling using an explicit or preset masking codec.
294
+ * External codec callbacks receive isolated bytes; malformed results return `invalid_options`,
295
+ * and thrown exceptions remain available as the error's `cause`.
56
296
  */
57
- uuidV7At(this: void, timestamp: number): UuidSlugError | UuidV7String;
58
- uuidV7BytesAt(
59
- this: void,
60
- timestamp: number,
61
- out?: Uint8Array,
62
- offset?: number,
63
- ): UuidSlugError | Uint8Array;
297
+ toMaskedSlug(
298
+ this: Uuid<Version, HasMaskingCodec, boolean>,
299
+ ...codec: 7 extends Version
300
+ ? [HasMaskingCodec] extends [true]
301
+ ? readonly [maskingCodec?: UuidV7MaskingCodec]
302
+ : readonly [maskingCodec: UuidV7MaskingCodec]
303
+ : readonly [maskingCodec: never]
304
+ ): MaskedOrSentinelUuidV7Slug | UuidSlugError;
305
+ /** Interpret UUIDv7 with an explicit layout, including receivers with mixed preset capabilities. */
306
+ extractV7Payload(
307
+ this: Uuid<Version, boolean, boolean>,
308
+ payloadLayout: 7 extends Version ? UuidV7PayloadLayout : never,
309
+ ): UuidV7Payload | UuidSlugError;
310
+ /** Decode UUIDv7 payload fields using an explicit or generated preset layout. */
311
+ extractV7Payload(
312
+ this: Uuid<Version, boolean, HasPayloadLayout>,
313
+ ...layout: 7 extends Version
314
+ ? [HasPayloadLayout] extends [true]
315
+ ? readonly [payloadLayout?: UuidV7PayloadLayout]
316
+ : readonly [payloadLayout: UuidV7PayloadLayout]
317
+ : readonly [payloadLayout: never]
318
+ ): UuidV7Payload | UuidSlugError;
319
+ /** Serialize as canonical lowercase UUID text; capabilities are process-local. */
320
+ toJSON<Receiver extends AnyUuid>(
321
+ this: Receiver,
322
+ ): UuidStringForVersion<Receiver["version"], typeof UUID_TEXT_LOWERCASE>;
64
323
  }
65
324
 
325
+ /*
326
+ * Reject a captured brand that proves an input cannot satisfy an operation. Bare strings remain
327
+ * valid because widening erases their child brand, leaving runtime validation as the only sound
328
+ * judge; tuple wrapping makes one invalid member reject the entire known union.
329
+ */
330
+ type RejectKnownInput<Input, Invalid> = [Extract<Exclude<Input, UuidSlugError>, Invalid>] extends [
331
+ never,
332
+ ]
333
+ ? Input
334
+ : never;
335
+
336
+ /** Reject a known slug; the operation parses UUID text. A bare string is validated at runtime. */
337
+ export type UuidStringInput<Input extends string | UuidSlugError> = RejectKnownInput<
338
+ Input,
339
+ PlainUuidSlug | MaskedUuidSlug
340
+ >;
341
+ /** Reject known UUID text and masked slugs; only a plain slug decodes without a key. */
342
+ export type PlainUuidSlugInput<Input extends string | UuidSlugError> = RejectKnownInput<
343
+ Input,
344
+ UuidText | MaskedUuidSlug
345
+ >;
346
+ /** Reject known UUID text; slug brands stay accepted because plain and masked spellings overlap. */
347
+ export type SlugStringInput<Input extends string | UuidSlugError> = RejectKnownInput<
348
+ Input,
349
+ UuidText
350
+ >;
351
+ /** Reject known slugs and UUIDv4 text; the operation reads a UUIDv7 timestamp from text. */
352
+ export type UuidV7StringInput<Input extends string | UuidSlugError> = RejectKnownInput<
353
+ Input,
354
+ PlainUuidSlug | MaskedUuidSlug | UuidV4Text
355
+ >;
356
+ /** Reject known UUID text, masked slugs, and UUIDv4 slugs; the operation needs a plain UUIDv7 slug. */
357
+ export type PlainUuidV7SlugInput<Input extends string | UuidSlugError> = RejectKnownInput<
358
+ Input,
359
+ UuidText | MaskedUuidSlug | PlainUuidV4Slug
360
+ >;
361
+ /** Reject masked slugs and known UUIDv4 values across text and byte timestamp inputs. */
362
+ export type UuidV7TimestampInput<Input extends string | UuidByteInput | UuidSlugError> =
363
+ RejectKnownInput<Input, MaskedUuidSlug | UuidV4Text | PlainUuidV4Slug | UuidV4Bytes>;
364
+ /** Reject known UUIDv4 bytes; the operation needs UUIDv7 bytes. */
365
+ export type UuidV7BytesInput<Input extends UuidByteInput | UuidSlugError> = RejectKnownInput<
366
+ Input,
367
+ UuidV4Bytes
368
+ >;
369
+ /** Reject known non-v7 values; a masking codec accepts every UUIDv7 form. */
370
+ export type UuidV7ValueInput<Input extends UuidInput> = RejectKnownInput<
371
+ Input,
372
+ UuidV4Text | UuidV4Bytes | PlainUuidV4Slug | AnyUuidForVersion<Exclude<UuidVersion, 7>>
373
+ >;
374
+ /** Exactly 16 validated UUID bytes. Package-owned values are plain `Uint8Array`. */
375
+ export type UuidBytes = Brand<Uint8Array, "UuidBytes">;
376
+ /** UUID bytes with version 4 and RFC variant bits. */
377
+ export type UuidV4Bytes = Brand<UuidBytes, "UuidV4Bytes">;
378
+ /** UUID bytes with version 7 and RFC variant bits. */
379
+ export type UuidV7Bytes = Brand<UuidBytes, "UuidV7Bytes">;
380
+
381
+ // Writers preserve the array and its methods, but prior UUID facts describe the replaced bytes.
382
+ // Strip only the package brand; erasing every subtype would also discard useful caller storage APIs.
383
+ export type UuidOutput<Output extends Uint8Array> = Output extends UuidBytes
384
+ ? Omit<Output, typeof brand>
385
+ : Output;
386
+
387
+ /** A UUID byte source: a `Uint8Array`, a complete `ArrayBuffer`, or a `DataView`'s declared range. */
388
+ export type UuidByteInput = Uint8Array | ArrayBuffer | DataView;
389
+ type AnyUuidForVersion<Version extends UuidVersion> = Uuid<Version, boolean, boolean>;
390
+ type AnyUuid =
391
+ | AnyUuidForVersion<UuidVersion>
392
+ | { [Version in UuidVersion]: AnyUuidForVersion<Version> }[UuidVersion];
393
+
394
+ // Only presets shared by every successful input variant survive a reparse; raw inputs prove none.
395
+ type UuidPreset<Input, Preset extends "maskingCodec" | "payloadLayout"> = Input extends AnyUuid
396
+ ? NonNullable<Input[typeof brand]>[Preset]
397
+ : false;
398
+ export type ParsedUuidResult<Input, WithCodec extends boolean = false> = Uuid<
399
+ UuidVersionOf<WithCodec extends true ? MaskingCodecUuidInput<Input> : Input>,
400
+ WithCodec extends true
401
+ ? true
402
+ : [UuidPreset<Exclude<Input, UuidSlugError>, "maskingCodec">] extends [true]
403
+ ? true
404
+ : false,
405
+ [UuidPreset<Exclude<Input, UuidSlugError>, "payloadLayout">] extends [true] ? true : false
406
+ >;
407
+ /**
408
+ * Any supported UUID text, byte, or slug input, plus a preceding package error. JavaScript
409
+ * implementations also normalize genuine `String` objects; TypeScript uses primitive strings.
410
+ */
411
+ export type UuidInput = string | UuidByteInput | AnyUuid | UuidSlugError;
412
+ /** Reject a branded masked slug where no masking codec is available. */
413
+ export type KeylessUuidInput<Input> = [
414
+ Extract<Exclude<Input, UuidSlugError>, MaskedUuidV7Slug>,
415
+ ] extends [never]
416
+ ? Input
417
+ : never;
418
+ /** UUID text or the error returned while converting the captured input. */
419
+ export type UuidStringResult<Input, Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE> =
420
+ | PreserveUuidVersion<Input, UuidStringFor<Case>, UuidV4StringFor<Case>, UuidV7StringFor<Case>>
421
+ | UuidSlugError;
422
+ /** UUID bytes or the error returned while converting the captured input. */
423
+ export type UuidBytesResult<Input> =
424
+ | PreserveUuidVersion<Input, UuidBytes, UuidV4Bytes, UuidV7Bytes>
425
+ | UuidSlugError;
426
+ /** A plain UUID slug or the error returned while converting the captured input. */
427
+ export type PlainUuidSlugResult<Input> =
428
+ | PreserveUuidVersion<Input, PlainUuidSlug, PlainUuidV4Slug, PlainUuidV7Slug>
429
+ | UuidSlugError;
430
+
66
431
  /**
67
- * A schema is its mixing step, not the data behind one. Holding `mix` as a function rather than
68
- * exposing a permutation and an XOR table is what lets the masking code stay ignorant of which
69
- * scheme it is running: adding one is a new constructor in `schema.ts` and no branch anywhere.
70
- *
71
- * It is also the ONLY extension point, and deliberately so. This interface is public, so a caller
72
- * with a scheme of their own supplies it directly; the package ships no table-shaped constructor
73
- * beside it, because one would privilege a single foreign layout while being strictly less
74
- * capable than the function it wraps. `createUuidSlugCodec` smoke-tests supplied schemas; callers remain responsible for
75
- * invertibility across their full input domain.
432
+ * An inclusive timestamp window around `referenceUnixMs` or the current time.
433
+ * This checks clock plausibility, not expiry, authentication, replay, or issuance.
76
434
  */
77
- export interface MaskSchema {
78
- readonly id: string;
435
+ export interface UuidV7TimestampWindow {
436
+ /** Maximum absolute difference from the reference time, inclusive. Must be finite and nonnegative. */
437
+ readonly maxTimestampDeltaMs: number;
79
438
  /**
80
- * Transforms 16 bytes; `forward: false` MUST be the exact inverse. `input` and `output` MUST
81
- * NOT be the same array: a scheme that permutes reads source bytes it would already have
82
- * overwritten, which corrupts silently rather than failing.
439
+ * Finite Unix milliseconds used as the reference.
440
+ *
441
+ * @defaultValue One `Date.now()` reading per validation call.
83
442
  */
84
- mix(input: Uint8Array, output: Uint8Array, forward: boolean): void;
443
+ readonly referenceUnixMs?: number;
85
444
  }
86
445
 
87
446
  /**
88
- * There is no scheme to choose. The check's width is fixed by arithmetic — a UUIDv7 carries 116
89
- * bits of content, so the encoding's remainder is the check — and the mixing step is the Feistel,
90
- * because the only alternative this package ever shipped left the timestamp legible: one output
91
- * byte per input byte meant 4 of 16 bytes held constant across a second, defeating the entire
92
- * point of masking. A caller who genuinely needs a different cipher passes a `MaskSchema`.
447
+ * A stateful UUIDv7 sequence using one clock and entropy source. Successful
448
+ * calls strictly increase in UUID byte order under the default preserve rollback policy, including
449
+ * calls with `at`. Methods may be detached. Expected clock
450
+ * and entropy failures return `UuidSlugError` without corrupting the next generation attempt.
93
451
  */
94
- export interface MaskSchemaOptions {
95
- readonly id?: string;
452
+ export interface UuidV7Generator {
453
+ /** Payload layout emitted by this generator; pass it to UUIDv7 payload extraction. */
454
+ readonly payloadLayout: UuidV7PayloadLayout;
455
+ /** Generate an immutable UUIDv7 that remembers this generator's payload layout. */
456
+ generateUuidV7Value(this: void, options?: undefined): Uuid<7, false, true> | UuidSlugError;
457
+ /** Generate with supplied time or masking options; only a supplied codec is retained. */
458
+ generateUuidV7Value<const Options extends UuidV7GeneratorValueOptions | undefined>(
459
+ this: void,
460
+ options: Options,
461
+ ):
462
+ | Uuid<7, Options extends { readonly maskingCodec: UuidV7MaskingCodec } ? true : false, true>
463
+ | UuidSlugError;
464
+ /** Generate UUIDv7 text for the current clock reading in the selected case, lowercase by default. */
465
+ generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
466
+ this: void,
467
+ ...textCase: UuidTextCaseArguments<Case>
468
+ ): UuidV7StringFor<Case> | UuidSlugError;
469
+ /** Generate UUIDv7 text at an explicit time or the current clock reading. */
470
+ generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
471
+ this: void,
472
+ options: Omit<GenerateUuidV7Options<Case>, "generator">,
473
+ ): UuidV7StringFor<Case> | UuidSlugError;
474
+ /** Generate a new plain 16-byte `Uint8Array` for the current clock reading. */
475
+ generateUuidV7Bytes(this: void): UuidV7Bytes | UuidSlugError;
96
476
  /**
97
- * Generate a secret, for example with `openssl rand -base64 32`, and keep it outside source
98
- * control. At least 16 bytes are required; strings are UTF-8 encoded. A known UUID/slug pair
99
- * permits offline guesses, so length alone is not protection. Preserve old seeds for decoding
100
- * issued slugs; rotate by retaining their schema settings in `previousMasks`.
477
+ * Write 16 bytes only after success and return the exact supplied array.
478
+ *
479
+ * @param output - Caller-owned array that receives the 16 UUID bytes.
480
+ * @param outputOffset - Zero-based index where writing starts. Omit to start at index 0. Bytes
481
+ * outside the written range stay unchanged.
101
482
  */
102
- readonly seed: string | Uint8Array;
483
+ generateUuidV7Bytes<Output extends Uint8Array>(
484
+ this: void,
485
+ output: Output,
486
+ outputOffset?: number,
487
+ ): UuidOutput<Output> | UuidSlugError;
488
+ /** Generate package-owned UUIDv7 bytes at an explicit time or the current clock reading. */
489
+ generateUuidV7Bytes(
490
+ this: void,
491
+ options: Omit<GenerateUuidV7BytesOptions, "generator">,
492
+ ): UuidV7Bytes | UuidSlugError;
493
+ /** Write UUIDv7 bytes at an explicit time or the current clock reading into caller-owned storage. */
494
+ generateUuidV7Bytes<Output extends Uint8Array>(
495
+ this: void,
496
+ options: Omit<GenerateUuidV7BytesIntoOptions<Output>, "generator">,
497
+ ): UuidOutput<Output> | UuidSlugError;
498
+ /**
499
+ * Generate a plain UUIDv7 slug in this sequence. Lowercase base32hex preserves UUID byte order;
500
+ * base64url does not preserve that order under text comparison.
501
+ *
502
+ * @param alphabetOrOptions - Output spelling, or an explicit time with that spelling. Omit for
503
+ * the shorter 22-character base64url form at the current clock reading.
504
+ */
505
+ generatePlainUuidV7Slug(
506
+ this: void,
507
+ alphabetOrOptions?: SlugAlphabet | Omit<GeneratePlainUuidV7SlugOptions, "generator">,
508
+ ): PlainUuidV7Slug | UuidSlugError;
103
509
  /**
104
- * Work factor for turning the seed into key material, default 1 — the cheapest setting, chosen so
105
- * that codec construction does only the requested work. Higher counts add construction and
106
- * seed-guessing cost; they are paid when the schema is built, never per id.
510
+ * Generate UUIDv7 text and a plain slug for the same UUID in this sequence.
107
511
  *
108
- * WIRE-FORMAT-BEARING, exactly as `seed` is: a different count derives different keys, so every
109
- * masked slug issued under the old count stops decoding. Rotate it the way a seed is rotated —
110
- * the new setting in `mask`, the old one kept in `previousMasks` — never by editing in place.
512
+ * @param alphabet - Slug spelling. Omit for the shorter 22-character base64url form.
513
+ * @param textCase - UUID text spelling. Pass it alone to keep the default slug alphabet.
514
+ * @returns UUID text plus one slug in the selected alphabet, or `UuidSlugError` when generation fails.
111
515
  */
112
- readonly keyIterations?: number;
516
+ generateUuidV7WithPlainSlug(
517
+ this: void,
518
+ alphabet?: SlugAlphabet,
519
+ ): GeneratedUuidV7<PlainUuidV7Slug> | UuidSlugError;
520
+ generateUuidV7WithPlainSlug<Case extends UuidTextCase>(
521
+ this: void,
522
+ textCase: Case,
523
+ ): GeneratedUuidV7<PlainUuidV7Slug, Case> | UuidSlugError;
524
+ generateUuidV7WithPlainSlug<Case extends UuidTextCase>(
525
+ this: void,
526
+ alphabet: SlugAlphabet,
527
+ textCase: Case,
528
+ ): GeneratedUuidV7<PlainUuidV7Slug, Case> | UuidSlugError;
529
+ /** Generate the pair at an explicit time or the current clock reading, in the selected spellings. */
530
+ generateUuidV7WithPlainSlug<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
531
+ this: void,
532
+ options: Omit<GenerateUuidV7WithPlainSlugOptions<Case>, "generator">,
533
+ ): GeneratedUuidV7<PlainUuidV7Slug, Case> | UuidSlugError;
113
534
  }
114
535
 
115
- /** The synchronous seed options plus cooperative cancellation; no scheduling knobs are required. */
116
- export interface AsyncMaskSchemaOptions extends MaskSchemaOptions {
117
- readonly signal?: AbortSignal;
536
+ /**
537
+ * A standard host instant; generation uses every sub-millisecond fraction bit its layout provides.
538
+ * JavaScript also accepts genuine `String` objects for zoned timestamp text.
539
+ */
540
+ export type UuidV7Instant =
541
+ | number
542
+ | bigint
543
+ | string
544
+ | Date
545
+ | { readonly epochMilliseconds: number | bigint }
546
+ | { readonly epochNanoseconds: bigint }
547
+ | { readonly seconds: number | bigint; readonly nanoseconds?: number | bigint };
548
+
549
+ /** Select an explicit time and UUID text spelling for one UUIDv7. */
550
+ export type GenerateUuidV7Options<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE> = {
551
+ /** Time to encode. A created generator joins its sequence; a module call stays independent. */
552
+ readonly at?: UuidV7Instant;
553
+ /** Generator that supplies entropy, payload layout, and sequence policy. */
554
+ readonly generator?: UuidV7Generator;
555
+ /** UUID text spelling. Omit for lowercase. */
556
+ readonly textCase?: Case;
557
+ } & UuidTextCaseOptions<Case>;
558
+
559
+ /** Select an explicit time and alphabet for one plain UUIDv7 slug. */
560
+ export interface GeneratePlainUuidV7SlugOptions {
561
+ /** Time to encode. A selected generator may advance it to preserve its sequence. */
562
+ readonly at?: UuidV7Instant;
563
+ /** Slug spelling. Omit for the shorter base64url form. */
564
+ readonly alphabet?: SlugAlphabet;
565
+ /** Generator that supplies entropy, payload layout, and sequence policy. */
566
+ readonly generator?: UuidV7Generator;
118
567
  }
119
568
 
120
- export interface UuidV7SentinelDefinition {
121
- readonly name: string;
122
- readonly uuid: UuidV7String;
569
+ /** Select an explicit time for package-owned UUIDv7 bytes. */
570
+ export interface GenerateUuidV7BytesOptions {
571
+ /** Time to encode. A created generator joins its sequence; a module call stays independent. */
572
+ readonly at?: UuidV7Instant;
573
+ /** Generator that supplies entropy, payload layout, and sequence policy. */
574
+ readonly generator?: UuidV7Generator;
575
+ readonly output?: never;
576
+ readonly outputOffset?: never;
123
577
  }
124
578
 
125
- export interface UuidV7Sentinel {
126
- readonly name: string;
127
- readonly slug: SentinelUuidV7Slug;
128
- readonly uuid: UuidV7String;
579
+ /** Select an explicit time and caller-owned storage for UUIDv7 bytes. */
580
+ export interface GenerateUuidV7BytesIntoOptions<Output extends Uint8Array> {
581
+ /** Time to encode. A created generator joins its sequence; a module call stays independent. */
582
+ readonly at?: UuidV7Instant;
583
+ /** Generator that supplies entropy, payload layout, and sequence policy. */
584
+ readonly generator?: UuidV7Generator;
585
+ /** Caller-owned array that receives the 16 UUID bytes after successful generation. */
586
+ readonly output: Output;
587
+ /** Zero-based index where writing starts. Omit to start at index 0. */
588
+ readonly outputOffset?: number;
129
589
  }
130
590
 
131
- /** Select a known encoding instead of guessing from overlapping slug text. */
132
- export type MigrationFormat = "current" | "original" | "plain";
591
+ /** Select time and both spellings for one UUIDv7 text-and-plain-slug pair. */
592
+ export type GenerateUuidV7WithPlainSlugOptions<
593
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
594
+ > = {
595
+ /** Time to encode. A selected generator may advance it to preserve its sequence. */
596
+ readonly at?: UuidV7Instant;
597
+ /** Slug spelling. Omit for the shorter base64url form. */
598
+ readonly alphabet?: SlugAlphabet;
599
+ /** Generator that supplies entropy, payload layout, and sequence policy. */
600
+ readonly generator?: UuidV7Generator;
601
+ /** UUID text spelling. Omit for lowercase. */
602
+ readonly textCase?: Case;
603
+ } & UuidTextCaseOptions<Case>;
133
604
 
134
- /** Enable only formats your application has issued; writers keep using the codec. */
135
- export interface UuidSlugMigrationOptions {
136
- readonly original?: boolean;
137
- readonly plain?: boolean;
605
+ /** Select optional state for immutable UUIDv7 generation through a generator. */
606
+ export interface UuidV7GeneratorValueOptions {
607
+ /** Time to encode through this generator's sequence state. */
608
+ readonly at?: UuidV7Instant;
609
+ /** Masking codec retained by the generated UUID for later masked conversion. */
610
+ readonly maskingCodec?: UuidV7MaskingCodec;
138
611
  }
139
612
 
140
- export interface UuidSlugMigration {
141
- /** Return the first candidate: sentinel, current keys, original mask, then plain UUID. */
142
- decode(this: void, slug: string, format?: MigrationFormat): UuidSlugError | UuidString;
143
- /** Return distinct candidates for one application lookup; an empty array means no match. */
144
- candidates(this: void, slug: string, format?: MigrationFormat): UuidSlugError | UuidString[];
613
+ /** Select independent owners and time for top-level immutable UUIDv7 generation. */
614
+ export interface UuidV7ValueOptions extends UuidV7GeneratorValueOptions {
615
+ /** Generator that supplies entropy, sequence policy, and the retained payload layout. */
616
+ readonly generator?: UuidV7Generator;
145
617
  }
146
618
 
147
- export interface UuidSlugCodecOptions {
619
+ /** Select optional generation state when a masking codec is already preset. */
620
+ export interface UuidV7MaskingCodecValueOptions {
621
+ /** Time to encode. A selected generator may advance it to preserve its sequence. */
622
+ readonly at?: UuidV7Instant;
623
+ /** Generator that supplies entropy, sequence policy, and the retained payload layout. */
148
624
  readonly generator?: UuidV7Generator;
625
+ }
626
+
627
+ /** Select generation state and UUID text spelling for one masked UUIDv7 pair. */
628
+ export type GenerateUuidV7WithMaskedSlugOptions<
629
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
630
+ > = UuidV7MaskingCodecValueOptions & {
631
+ /** UUID text spelling. Omit for lowercase. */
632
+ readonly textCase?: Case;
633
+ } & UuidTextCaseOptions<Case>;
634
+
635
+ /** An immutable handle for masking the recognizable fields of a UUIDv7; key material is not exposed. */
636
+ export interface UuidV7Mask {
637
+ /** Diagnostic label only; mask objects and caller order select decoding behavior. */
638
+ readonly diagnosticLabel: string;
639
+ readonly [uuidV7MaskBrand]: true;
640
+ }
641
+
642
+ /** Define a reversible 16-byte transform for `createCustomUuidV7Mask`. */
643
+ export interface CustomUuidV7MaskOptions {
149
644
  /**
150
- * Also decode plain, unmasked slugs when no schema matches — the migration path for ids issued
151
- * before masking existed. Its own option rather than a field beside the key list, because the
152
- * two answer different questions and share only the accident of both concerning the past.
153
- *
154
- * Turn it off once the migration ends. It costs one wrong answer per 2^checkBits: a direct slug
155
- * that happens to satisfy a mask's check decodes as that mask instead, and both are the same 22
156
- * characters of the same alphabet, so nothing else can tell them apart.
645
+ * Names this mask in the error returned when a callback fails after construction, which is why
646
+ * it is required here and optional for seeded masks, whose transform cannot fail. It does not
647
+ * select the mask during decoding. JavaScript also accepts a genuine `String` object.
157
648
  */
158
- readonly acceptUnmaskedSlugs?: boolean;
649
+ readonly diagnosticLabel: string;
650
+ /** Transform an isolated 16-byte array; return exactly 16 bytes or `UuidSlugError`. */
651
+ readonly mask: (bytes: Uint8Array) => Uint8Array | UuidSlugError;
652
+ /** Invert `mask` for every possible 16-byte input. */
653
+ readonly unmask: (bytes: Uint8Array) => Uint8Array | UuidSlugError;
654
+ }
655
+
656
+ /**
657
+ * Options for deriving an immutable UUIDv7 mask from stable secret key material. Keep the seed and
658
+ * iteration count available while identifiers produced with this mask must remain readable.
659
+ */
660
+ export interface UuidV7MaskOptions {
159
661
  /**
160
- * Schemas to try after `mask`, in the order given — how a seed is rotated. Takes a seed exactly
161
- * as `mask` does: a rotated seed is the ordinary reason this list exists, and requiring a
162
- * pre-built schema for it cost the commonest case a constructor and an error branch that naming
163
- * the current seed never needed. Named for rotation rather than for legacy, because a previous
164
- * key is not a different kind of thing from the current one — rotation is only a change of
165
- * position between this list and `mask`.
662
+ * Diagnostic label only; decoding uses the mask object and caller-specified order. JavaScript
663
+ * also accepts a genuine `String` object.
166
664
  *
167
- * Keep it short. Each entry is tried in turn, so the codec's wrong-answer rate is the sum over
168
- * the whole list.
665
+ * @defaultValue `"seeded"`
169
666
  */
170
- readonly previousMasks?: readonly (MaskSchema | MaskSchemaOptions)[];
667
+ readonly diagnosticLabel?: string;
171
668
  /**
172
- * The schema that ENCODES, and the first tried when decoding. Kept separate from the list above
173
- * rather than folded into one ordered array: in a single list the encoding schema is whichever
174
- * happens to be first, so appending a rotated seed leaves you still issuing ids under the old
175
- * one while believing you rotated. Nothing about that failure is visible.
176
- *
177
- * OPTIONAL, and omitting it is the one choice here with a security consequence: the codec then
178
- * masks under `DEFAULT_MASK_SCHEMA`, whose seed is a string literal in this published package,
179
- * so its masked slugs are readable by anyone who installed it. Supply `{ seed }` — any stable
180
- * string you keep out of the repository — for masking to obfuscate anything at all.
669
+ * Stable secret key material. Generate at least 16 bytes, keep it outside source control, and
670
+ * retain old values in `previousMasks`; a known UUID/slug pair permits offline guesses.
671
+ * JavaScript also accepts a genuine `String` object.
181
672
  */
182
- readonly mask?: MaskSchema | MaskSchemaOptions;
183
- readonly sentinels?: readonly UuidV7SentinelDefinition[];
673
+ readonly seed: string | Uint8Array;
184
674
  /**
185
- * Alphabet for PLAIN slugs from `uuidV4Slug` and `uuidV7Slug`. `"base32hex"` costs four characters
186
- * (26 rather than 22) and buys chronological sort order: its characters are in ASCII order and a
187
- * UUIDv7's leading bytes are its timestamp, so base32hex slugs sort by creation time as plain
188
- * strings. base64url's alphabet cannot — it runs `A-Za-z0-9-_`, so its character order and its
189
- * value order disagree. Being alphanumeric also spares base32hex the `-` and `_` that make a
190
- * base64url slug awkward to select by double-click.
675
+ * Key-derivation work factor in `1..16777216` (2^24), paid at mask construction rather than per ID.
676
+ * Changing it changes every derived key, so retain the old seed and count in `previousMasks`
677
+ * when identifiers issued under them must remain readable.
191
678
  *
192
- * Codec-level rather than per call so a system cannot mint half its ids in each spelling.
193
- * Decoding takes no such option: the two lengths are disjoint, so `slugToUuid` reads both and a
194
- * change of alphabet leaves every previously issued slug working.
195
- *
196
- * It does NOT reach masked slugs or sentinels, which stay base64url. Masked bytes are ciphertext
197
- * and sort in no useful order, and a sentinel is matched against masked input, so a sentinel in a
198
- * different alphabet could never be recognised there.
679
+ * @defaultValue `1`
680
+ */
681
+ readonly keyDerivationIterations?: number;
682
+ }
683
+
684
+ /** Mask derivation options with cooperative cancellation for expensive construction. */
685
+ export interface AsyncUuidV7MaskOptions extends UuidV7MaskOptions {
686
+ /**
687
+ * Stop cooperative derivation and return an `aborted` error with `reason` as its cause.
199
688
  *
200
- * Costs throughput when set: `uuidV7Slug` can no longer use a runtime's native base64url slug
201
- * generator and falls back to generating bytes and encoding them.
689
+ * @defaultValue No cancellation.
202
690
  */
203
- readonly slugAlphabet?: SlugAlphabet;
691
+ readonly signal?: AbortSignal;
204
692
  }
205
693
 
206
- /**
207
- * Only what depends on the codec's own state: the generator it draws from, and the mask schema
208
- * plus sentinels it was built with.
209
- *
210
- * The plain conversions (`uuidToSlug`, `parseUuid`, `formatUuidSlug`, …) are module-level
211
- * functions and deliberately absent here. They are pure — the same input gives the same output
212
- * whatever seed the codec holds — so carrying them as methods implied a dependency on the seed
213
- * that does not exist, and was the single most misleading thing about the previous shape.
214
- *
215
- * Extending `UuidV7Generator` makes the compiler require forwarding every generator method.
216
- */
217
- export interface UuidSlugCodec extends UuidV7Generator {
218
- readonly sentinels: readonly UuidV7Sentinel[];
219
- /** Create an opt-in reader without changing generation or ordinary codec decoding. */
220
- migration(this: void, options?: UuidSlugMigrationOptions): UuidSlugMigration;
694
+ /** Define a named UUIDv7 that must bypass masking. */
695
+ export interface UuidV7SentinelConfig {
696
+ /** Nonempty application-facing name, unique within one masking codec. JavaScript also accepts a genuine `String` object. */
697
+ readonly name: string;
221
698
  /**
222
- * `this: void` lets callers detach methods without `.bind`; implementations cannot rely on `this`.
699
+ * UUIDv7 text in an accepted spelling, unique after normalization. Sentinels bypass
700
+ * masking, so their timestamps may lie outside the codec's configured range.
223
701
  */
224
- uuidV4(this: void): UuidV4String;
225
- uuidV4Bytes(this: void, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
226
- uuidV4Slug(this: void): UuidV4Slug;
227
- uuidV7Slug(this: void): UuidV7Slug;
228
- uuidV7MaskedSlug(this: void): PublicUuidV7Slug;
702
+ readonly uuid: string;
703
+ }
704
+
705
+ /** A validated sentinel and its ordinary plain slug in the masking codec's masked-slug alphabet. */
706
+ export interface UuidV7Sentinel {
707
+ /** The definition's application-facing name. */
708
+ readonly name: string;
709
+ /** The reserved raw slug; it is not a masked payload. */
710
+ readonly slug: SentinelUuidV7Slug;
711
+ /** The canonical UUIDv7 represented by `slug`. */
712
+ readonly uuid: UuidV7String;
713
+ }
714
+
715
+ /** Select decoding with the codec's seeded mask. */
716
+ export const SEEDED_MASK_FORMAT = "seeded-mask";
717
+ /** Select decoding with the opt-in fixed mask. */
718
+ export const FIXED_MASK_FORMAT = "fixed-mask";
719
+ /** Select decoding as an opt-in plain UUID slug. */
720
+ export const PLAIN_SLUG_FORMAT = "plain-slug";
721
+
722
+ /** Select one enabled migration format when the input's original encoding is known. */
723
+ export type UuidSlugMigrationFormat =
724
+ | typeof SEEDED_MASK_FORMAT
725
+ | typeof FIXED_MASK_FORMAT
726
+ | typeof PLAIN_SLUG_FORMAT;
727
+
728
+ /** Enable only formats your application has issued; writers keep using the codec. */
729
+ export interface UuidSlugMigrationOptions {
229
730
  /**
230
- * Masking is UUIDv7-only, and the reason is that the whole format is spent. The check rides in
231
- * bits a v7 provably wastes — its constant version and variant, and the timestamp's top six —
232
- * plus whatever the encoding has left over. Another version would have to store its real
233
- * version and its full timestamp somewhere, and there is no somewhere: every one of the 132
234
- * bits in 22 characters already has a job. Supporting all versions would cost a 23rd character
235
- * on every masked slug forever, to hide a creation time only v7 discloses.
731
+ * Accept the fixed-key format with a four-bit check that predates seeded masking, from before
732
+ * package 0.2.0. Releases from 0.2.0 on write different formats, so enable it only for slugs
733
+ * issued under that earlier scheme.
734
+ *
735
+ * @defaultValue `false`
236
736
  */
237
- uuidV7ToMaskedSlug(this: void, uuid: string): UuidSlugError | PublicUuidV7Slug;
238
- maskedSlugToUuidV7(this: void, slug: string): UuidSlugError | UuidV7String;
737
+ readonly acceptFixedMask?: boolean;
239
738
  /**
240
- * Decodes to whatever version comes out, where `maskedSlugToUuidV7` insists on v7.
739
+ * Accept plain UUID slugs of any version, including retained trailing-bit aliases.
241
740
  *
242
- * NOT a redundant widening of that method, which is what it looks like: with
243
- * `acceptUnmaskedSlugs` enabled a slug that matches no schema is tried as a plain unmasked
244
- * slug, and a system migrating off unmasked ids may well have UUIDv4 ones. Those decode here
245
- * and are rejected by the v7 form. Deleting this on the assumption it was a duplicate was
246
- * measured to break exactly that migration path.
741
+ * @defaultValue `false`
247
742
  */
248
- maskedSlugToUuid(this: void, slug: string): UuidSlugError | UuidString;
743
+ readonly acceptPlainSlug?: boolean;
744
+ }
745
+
746
+ type EnabledMigrationOption<
747
+ Options,
748
+ Option extends keyof UuidSlugMigrationOptions,
749
+ > = Option extends keyof Options ? (true extends Options[Option] ? Option : never) : never;
750
+
751
+ /** Project enabled options into the only format selectors that decoder can accept. */
752
+ export type EnabledMigrationFormat<Options extends UuidSlugMigrationOptions> =
753
+ | typeof SEEDED_MASK_FORMAT
754
+ | (EnabledMigrationOption<Options, "acceptFixedMask"> extends never
755
+ ? never
756
+ : typeof FIXED_MASK_FORMAT)
757
+ | (EnabledMigrationOption<Options, "acceptPlainSlug"> extends never
758
+ ? never
759
+ : typeof PLAIN_SLUG_FORMAT);
760
+
761
+ /**
762
+ * Decode current and explicitly enabled old formats without changing masking-codec output.
763
+ * Methods may be detached. A successful decode identifies a candidate UUID, not the issuing format
764
+ * or a stored record. A preceding `UuidSlugError` is returned unchanged. JavaScript callers may
765
+ * pass genuine `String` objects; TypeScript uses primitive strings.
766
+ */
767
+ export interface UuidSlugMigrationDecoder<
768
+ in Format extends UuidSlugMigrationFormat = UuidSlugMigrationFormat,
769
+ > {
249
770
  /**
250
- * `maskedSlugToUuidV7` plus the freshness rules of `validateUuidV7Fresh`, returning the slug.
771
+ * Return the first candidate in this order: sentinel, seeded masks, fixed mask, plain slug.
772
+ * Pass `format` when its origin is known to avoid trying unrelated readers.
251
773
  *
252
- * Lives on the codec because unmasking needs the codec's key. Its module-level predecessor
253
- * `validateMaskedUuidV7SlugFresh` did not: it reached for `defaultCodec`, whose seed is
254
- * published in this package's source, so it answered under the wrong key for every caller who
255
- * supplied their own and returned a confident Error for valid slugs. There is no keyless
256
- * counterpart to this for the same reason; `validateUuidV7SlugFresh` stays module-level because
257
- * a PLAIN slug decodes without one.
774
+ * @param uuidSlug - Identifier accepted by one enabled migration reader.
775
+ * @param format - Known source format. Omit to try enabled readers in documented order. JavaScript also accepts a genuine `String` object.
776
+ * @param textCase - UUID text spelling. Pass it after `uuidSlug` when format is unknown, or after a
777
+ * known format. Omit for lowercase.
778
+ */
779
+ uuidSlugToUuidString<
780
+ Input extends string | UuidSlugError,
781
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
782
+ >(
783
+ this: void,
784
+ uuidSlug: SlugStringInput<Input>,
785
+ ...textCase: UuidTextCaseArguments<Case>
786
+ ): UuidStringFor<Case> | UuidSlugError;
787
+ uuidSlugToUuidString<Input extends string | UuidSlugError>(
788
+ this: void,
789
+ uuidSlug: SlugStringInput<Input>,
790
+ format: Format | undefined,
791
+ ): UuidString | UuidSlugError;
792
+ uuidSlugToUuidString<Input extends string | UuidSlugError, Case extends UuidTextCase>(
793
+ this: void,
794
+ uuidSlug: SlugStringInput<Input>,
795
+ format: Format,
796
+ textCase: Case,
797
+ ): UuidStringFor<Case> | UuidSlugError;
798
+ /**
799
+ * Return every distinct candidate in decode order for one application lookup. An empty array
800
+ * means no enabled format matched; callback failure returns `UuidSlugError`, not a partial list.
801
+ * A preceding `UuidSlugError` is returned unchanged.
258
802
  *
259
- * Returns the slug it was GIVEN, at the type it was given, which is the only type that is true
260
- * of it. Declaring `MaskedUuidV7Slug` was a lie the compiler could not catch: that brand is
261
- * `Base64UrlString & UuidSlug`, but with `acceptUnmaskedSlugs` the decode falls through to
262
- * `slugToUuid`, which accepts 26-character base32hex too — so a base32hex slug came back typed as
263
- * base64url and `isBase64Url` on it was false. Narrowing the fallback to base64url would have
264
- * been the wrong repair: a codec built with `slugAlphabet: "base32hex"` has exactly those legacy
265
- * ids, and refusing them breaks the migration this flag exists for. The behaviour is right; the
266
- * claim about it was not.
803
+ * @param uuidSlug - Identifier accepted by one or more enabled migration readers.
804
+ * @param format - Known source format. Omit to try enabled readers in documented order. JavaScript also accepts a genuine `String` object.
805
+ * @param textCase - UUID text spelling. Pass it after `uuidSlug` when format is unknown, or after a
806
+ * known format. Omit for lowercase.
267
807
  */
268
- validateMaskedSlugFresh<S extends string>(
808
+ uuidSlugToUuidStringCandidates<
809
+ Input extends string | UuidSlugError,
810
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
811
+ >(
812
+ this: void,
813
+ uuidSlug: SlugStringInput<Input>,
814
+ ...textCase: UuidTextCaseArguments<Case>
815
+ ): readonly UuidStringFor<Case>[] | UuidSlugError;
816
+ uuidSlugToUuidStringCandidates<Input extends string | UuidSlugError>(
817
+ this: void,
818
+ uuidSlug: SlugStringInput<Input>,
819
+ format: Format | undefined,
820
+ ): readonly UuidString[] | UuidSlugError;
821
+ uuidSlugToUuidStringCandidates<Input extends string | UuidSlugError, Case extends UuidTextCase>(
269
822
  this: void,
270
- slug: S,
271
- freshness?: FreshValidationOptions,
272
- ): UuidSlugError | S;
823
+ uuidSlug: SlugStringInput<Input>,
824
+ format: Format,
825
+ textCase: Case,
826
+ ): readonly UuidStringFor<Case>[] | UuidSlugError;
273
827
  }