@anizoptera/uuid-slug 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +373 -324
  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 +15 -8
  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/v7.ts CHANGED
@@ -1,23 +1,115 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import { checkRange, fillRandomBytes, readClock, UuidSlugError } from "./errors";
4
- import type { UuidV7Generator, UuidV7String } from "./types";
5
- import { formatUuid } from "./uuid";
6
- import type { Runtime } from "./runtime/types";
3
+ import {
4
+ checkByteRange,
5
+ checkRange,
6
+ diagnosticValue,
7
+ fillRandomBytes,
8
+ INVALID_TIMESTAMP,
9
+ RNG_UNAVAILABLE,
10
+ isUuidSlugError,
11
+ isUint8Array,
12
+ readClock,
13
+ stringInput,
14
+ UuidSlugError,
15
+ } from "./errors.ts";
16
+ import { readGenerationOptions } from "./generation-options.ts";
17
+ import { readUuidV7Instant } from "./instant.ts";
18
+ import type { NormalizedUuidV7Instant } from "./instant.ts";
19
+ import { UUID_TEXT_LOWERCASE, UUID_V7_ROLLBACK_ERROR } from "./types.ts";
20
+ import type {
21
+ GenerateUuidV7BytesIntoOptions,
22
+ GenerateUuidV7BytesOptions,
23
+ GenerateUuidV7Options,
24
+ UuidOutput,
25
+ UuidTextCase,
26
+ UuidTextCaseArguments,
27
+ UuidV7Bytes,
28
+ UuidV7ClockRollbackPolicy,
29
+ UuidV7Generator,
30
+ UuidV7StringFor,
31
+ } from "./types.ts";
32
+ import { formatUuidBytesUnchecked, resolveUuidTextCase } from "./uuid.ts";
33
+ import { MAX_UUID_V7_UNIX_MS, isValidUuidV7UnixMs } from "./v7-timestamp.ts";
7
34
 
8
- export interface UuidV7GeneratorOptions {
9
- readonly clock?: () => number;
10
- readonly fillRandom: (bytes: Uint8Array<ArrayBuffer>) => void;
35
+ /** Internal controls for exercising the portable UUIDv7 state machine. */
36
+ interface PortableUuidV7GeneratorOptions {
37
+ /** Return Unix milliseconds; selected fraction bits consume the fractional part. */
38
+ readonly readUnixMs?: () => number;
39
+ // Package-owned clocks split epoch and elapsed time before addition. Read this bucket only
40
+ // after their paired timestamp succeeds; caller clocks retain their numeric contract.
41
+ readonly readFractionBucket12?: () => number;
42
+ /** Fill every byte. Returned or thrown failures are contained by generation. */
43
+ readonly fillRandom: (bytes: Uint8Array<ArrayBuffer>) => unknown;
44
+ /** Policy already validated at the public seam. */
45
+ readonly clockRollback?: Extract<UuidV7ClockRollbackPolicy, { readonly toleranceMs: number }>;
46
+ /** Number of leading payload bits assigned to the clock fraction. */
47
+ readonly subMillisecondFractionBits?: number;
48
+ /** Keep explicit instants in this generator's ordering and rollback state. */
49
+ readonly coordinateExplicitInstants?: boolean;
50
+ // Module writers share their private 16-byte storage with text generation. Public construction
51
+ // never supplies this control; caller buffers must continue through the range checks below.
52
+ readonly textScratch?: Uint8Array<ArrayBuffer>;
11
53
  }
12
54
 
13
- function writeTimestamp(bytes: Uint8Array, ms: number, offset: number) {
14
- let value = Math.trunc(ms);
15
- for (let i = 5; i >= 0; i -= 1) {
16
- bytes[offset + i] = value & 0xff;
55
+ // The slug and value methods are attached by the public seam, which owns the slug encoder and the
56
+ // UUID value graph; keeping them out here lets a generation-only consumer drop both.
57
+ export type PortableUuidV7Generator = Omit<
58
+ UuidV7Generator,
59
+ "generatePlainUuidV7Slug" | "generateUuidV7Value" | "generateUuidV7WithPlainSlug"
60
+ > & {
61
+ /**
62
+ * Draw after the caller has read its options: `instant` is already normalized and `output` is
63
+ * checked again here. Package callers use it to avoid rebuilding and rereading an options object;
64
+ * it must never reach a public object.
65
+ */
66
+ readonly drawUuidV7Bytes: (
67
+ instant: NormalizedUuidV7Instant | undefined,
68
+ output?: Uint8Array,
69
+ outputOffset?: number,
70
+ ) => Uint8Array | UuidSlugError;
71
+ };
72
+
73
+ const UUID_V7_TEXT_OPTIONS = {
74
+ at: true,
75
+ textCase: true,
76
+ } as const satisfies Record<keyof Omit<GenerateUuidV7Options<UuidTextCase>, "generator">, true>;
77
+ const UUID_V7_BYTE_OPTIONS = {
78
+ at: true,
79
+ output: true,
80
+ outputOffset: true,
81
+ } as const satisfies Record<
82
+ keyof Omit<GenerateUuidV7BytesOptions & GenerateUuidV7BytesIntoOptions<Uint8Array>, "generator">,
83
+ true
84
+ >;
85
+ const AT_OPTION = "at";
86
+
87
+ function writeTimestampWords(bytes: Uint8Array, ms: number, offset: number) {
88
+ // Split the fixed 48-bit field once: JavaScript bitwise operators keep the low 32 bits, while
89
+ // division supplies the independent high 16 bits without BigInt or six iterative divisions.
90
+ const high = Math.floor(ms / 0x1_0000_0000);
91
+ bytes[offset] = high >>> 8;
92
+ bytes[offset + 1] = high;
93
+ bytes[offset + 2] = ms >>> 24;
94
+ bytes[offset + 3] = ms >>> 16;
95
+ bytes[offset + 4] = ms >>> 8;
96
+ bytes[offset + 5] = ms;
97
+ }
98
+
99
+ function writeTimestampLoop(bytes: Uint8Array, ms: number, offset: number) {
100
+ let value = ms;
101
+ for (let index = 5; index >= 0; index -= 1) {
102
+ bytes[offset + index] = value & 0xff;
17
103
  value = Math.floor(value / 256);
18
104
  }
19
105
  }
20
106
 
107
+ // Measured Bun favors the loop while Node and Chromium favor fixed writes; select once so generation
108
+ // pays no per-call branch. bench/decisions.md owns the measurements and replacement condition.
109
+ const writeTimestamp = (globalThis as { Bun?: object }).Bun
110
+ ? writeTimestampLoop
111
+ : writeTimestampWords;
112
+
21
113
  /**
22
114
  * Writes the 42-bit sequence RFC 9562 §6.2 allows in `rand_a` plus the top of `rand_b`, along
23
115
  * with the version and variant bits that bracket it.
@@ -36,41 +128,23 @@ function writeCounter(bytes: Uint8Array, hi: number, lo: number, offset: number)
36
128
  bytes[offset + 11] = lo & 0xff;
37
129
  }
38
130
 
39
- /** The 48 bits RFC 9562 gives the timestamp; beyond it the value cannot be represented. */
40
- const MAX_TIMESTAMP = 0xffff_ffff_ffff;
131
+ // A successful draw returns the exact private destination; callbacks cannot return that buffer.
132
+ // Identity preserves foreign failures without a protocol scan on successful text calls. The writer,
133
+ // rather than the version-neutral formatter, establishes the UUIDv7 brand.
134
+ const formatUuidV7 = /* @__NO_SIDE_EFFECTS__ */ <Case extends UuidTextCase>(
135
+ result: Uint8Array | UuidSlugError,
136
+ textCase: Case,
137
+ output: Uint8Array,
138
+ ): UuidV7StringFor<Case> | UuidSlugError =>
139
+ result === output
140
+ ? (formatUuidBytesUnchecked(output, 0, textCase) as UuidV7StringFor<Case>)
141
+ : (result as UuidSlugError);
41
142
 
42
- /**
43
- * `Number.isInteger` rather than `isFinite`, because the error message promises a WHOLE number of
44
- * milliseconds and `Math.trunc` on the write path would otherwise honour that promise silently:
45
- * 1.5 became 1 with nothing reported. It also rejects NaN and Infinity, which matters because a
46
- * native generator need not — measured 2026-08-12, `Bun.randomUUIDv7("hex", NaN)` and the same
47
- * call at 2^48 both return the 1970 prefix `000000000000` without throwing, while -1 and 1.5 do
48
- * throw. Validating here rather than trusting the platform is what makes the two agree.
49
- */
50
- const isValidUuidV7Timestamp = (ms: number): boolean =>
51
- Number.isInteger(ms) && ms >= 0 && ms <= MAX_TIMESTAMP;
52
-
53
- /**
54
- * The one check and the one message for a caller-supplied instant. Both the portable generator and
55
- * the runtime-backed one call it, and the runtime-backed one calls it BEFORE delegating: a native
56
- * generator may accept what we reject and answer wrongly rather than fail.
57
- */
58
- const rejectInstant = (ms: number): UuidSlugError | undefined =>
59
- isValidUuidV7Timestamp(ms)
60
- ? undefined
61
- : new UuidSlugError(
62
- "invalid_timestamp",
63
- `UUIDv7 timestamp must be a whole number of milliseconds in 0..${MAX_TIMESTAMP}.`,
64
- );
65
-
66
- /**
67
- * Both string forms differ only in where the instant comes from, so the byte-or-error result is
68
- * carried through here rather than unwrapped twice. The narrowing is an assertion because
69
- * `formatUuid` is version-agnostic: the v7-ness is established by the caller having produced the
70
- * bytes, not by anything the formatter can check.
71
- */
72
- const formatUuidV7 = (result: UuidSlugError | Uint8Array): UuidSlugError | UuidV7String =>
73
- result instanceof Error ? result : (formatUuid(result) as UuidSlugError | UuidV7String);
143
+ const reenteredGeneration = /* @__NO_SIDE_EFFECTS__ */ () =>
144
+ new UuidSlugError(
145
+ RNG_UNAVAILABLE,
146
+ "UUIDv7 generation cannot be reentered from its readUnixMs or entropy callback.",
147
+ );
74
148
 
75
149
  /**
76
150
  * Seeds the sequence from the same six random bytes and the same bit positions as before, split
@@ -78,9 +152,10 @@ const formatUuidV7 = (result: UuidSlugError | Uint8Array): UuidSlugError | UuidV
78
152
  * low half. Starting each millisecond at a random point rather than zero is what stops the
79
153
  * sequence leaking how many ids were issued in the previous millisecond.
80
154
  */
81
- const seedHi = (bytes: Uint8Array) => (((bytes[0] ?? 0) << 2) | ((bytes[1] ?? 0) >>> 6)) & 0x3ff;
155
+ const seedHi = /* @__NO_SIDE_EFFECTS__ */ (bytes: Uint8Array) =>
156
+ (((bytes[0] ?? 0) << 2) | ((bytes[1] ?? 0) >>> 6)) & 0x3ff;
82
157
 
83
- const seedLo = (bytes: Uint8Array) =>
158
+ const seedLo = /* @__NO_SIDE_EFFECTS__ */ (bytes: Uint8Array) =>
84
159
  ((((bytes[1] ?? 0) & 0x3f) << 26) |
85
160
  ((bytes[2] ?? 0) << 18) |
86
161
  ((bytes[3] ?? 0) << 10) |
@@ -88,191 +163,293 @@ const seedLo = (bytes: Uint8Array) =>
88
163
  ((bytes[5] ?? 0) & 0x03)) >>>
89
164
  0;
90
165
 
91
- export function createUuidV7Generator(options: UuidV7GeneratorOptions): UuidV7Generator {
92
- const clock = options.clock ?? Date.now;
166
+ /**
167
+ * Create a stateful UUIDv7 generator from package-owned, statically checked dependencies.
168
+ * Clock and entropy failures return `UuidSlugError`; reentrant calls preserve sequence state.
169
+ */
170
+ export function createPortableUuidV7Generator(
171
+ options: PortableUuidV7GeneratorOptions,
172
+ ): PortableUuidV7Generator {
173
+ const readUnixMs = options.readUnixMs ?? Date.now;
93
174
  const fill = options.fillRandom;
94
- const random = new Uint8Array(16);
175
+ const rollback = options.clockRollback;
176
+ const fractionBits = options.subMillisecondFractionBits ?? 0;
177
+ const coordinateExplicitInstants = options.coordinateExplicitInstants ?? true;
178
+ const counterBits = 42 - fractionBits;
179
+ const counterModulus = 2 ** counterBits;
180
+ const payloadLayout = Object.freeze({
181
+ subMillisecondFractionBits: fractionBits,
182
+ counterBits,
183
+ });
184
+ // The sequence seed consumes six bytes and the UUID tail consumes four. Drawing a full UUID
185
+ // block would copy six bytes that version, variant, timestamp, and sequence fields replace.
186
+ const random = new Uint8Array(10);
187
+ // Continuations retain the sequence seed, so expose only the four bytes their UUID tail consumes.
188
+ const randomTail = random.subarray(6);
95
189
  /**
96
- * Below every timestamp the clock check admits, which is what makes it the uninitialised
190
+ * Below every timestamp the readUnixMs check admits, which is what makes it the uninitialised
97
191
  * sentinel rather than a value: `now > lastMs` alone therefore takes the reseed branch on the
98
192
  * first call, and no separate "have we started" flag is needed. The coupling is deliberate and
99
- * is why the clock is validated before this is compared against — an unvalidated clock returning
193
+ * is why the readUnixMs is validated before this is compared against — an unvalidated readUnixMs returning
100
194
  * a negative millisecond would make `lastMs` stay below it forever, so the monotonic counter
101
195
  * would never be used and every call would reseed.
102
196
  */
103
197
  let lastMs = -1;
198
+ let clockHighWaterMs = -1;
104
199
  let counterHi = 0;
105
200
  let counterLo = 0;
201
+ let generating = false;
202
+ const textBytes = options.textScratch ?? new Uint8Array(16);
106
203
 
107
- function reseed(ms: number) {
204
+ function reseed(ms: number, fraction: number) {
108
205
  const failed = fillRandomBytes(fill, random);
109
206
  if (failed) return failed;
207
+ const seededCounter = (seedHi(random) * 0x1_0000_0000 + seedLo(random)) % counterModulus;
208
+ const payloadPrefix = fraction * counterModulus + seededCounter;
110
209
  lastMs = ms;
111
- counterHi = seedHi(random);
112
- counterLo = seedLo(random);
210
+ counterHi = Math.floor(payloadPrefix / 0x1_0000_0000);
211
+ counterLo = payloadPrefix >>> 0;
113
212
  return undefined;
114
213
  }
115
214
 
116
- function bytes(
117
- out?: Uint8Array,
118
- offset = 0,
119
- timestamp?: number,
120
- explicit = false,
121
- ): UuidSlugError | Uint8Array {
122
- const target = out ?? new Uint8Array(16);
123
- const badRange = checkRange(target.length, offset, 16);
124
- if (badRange) return badRange;
125
- // The two modes differ only in where the millisecond and the 42-bit sequence come from, so
126
- // they share one write path. A caller-supplied instant takes a RANDOM sequence rather than
127
- // the monotonic counter, and leaves `lastMs`/`counter` untouched: that counter orders values
128
- // issued inside the CURRENT millisecond, and a caller naming an arbitrary instant is not
129
- // extending that sequence. Feeding a supplied timestamp through it would be worse than
130
- // useless — an older instant fails the `now > lastMs` test and the value would carry the
131
- // clock's millisecond instead of the requested one.
132
- let ms: number;
133
- let sequenceHi: number;
134
- let sequenceLo: number;
135
- if (explicit) {
136
- const invalid = rejectInstant(timestamp as number);
137
- if (invalid) return invalid;
138
- const failed = fillRandomBytes(fill, random);
215
+ function writeBytes(
216
+ target: Uint8Array,
217
+ offset: number,
218
+ ms: number,
219
+ sequenceHi: number,
220
+ sequenceLo: number,
221
+ ) {
222
+ writeTimestamp(target, ms, offset);
223
+ writeCounter(target, sequenceHi, sequenceLo, offset);
224
+ for (let i = 12; i < 16; i += 1) target[offset + i] = randomTail[i - 12] as number;
225
+ return target;
226
+ }
227
+
228
+ function advanceSequence(now: number, fraction: number): UuidSlugError | undefined {
229
+ const rollbackMs = rollback === undefined ? 0 : clockHighWaterMs - now;
230
+ if (rollback !== undefined && rollbackMs > rollback.toleranceMs) {
231
+ if (rollback.action === UUID_V7_ROLLBACK_ERROR)
232
+ return new UuidSlugError(
233
+ INVALID_TIMESTAMP,
234
+ `Clock moved backward by ${rollbackMs} milliseconds; clockRollback allows ${rollback.toleranceMs}. Increase tolerance or choose reset/preserve if this rollback is acceptable.`,
235
+ );
236
+ const failed = reseed(now, fraction);
237
+ if (failed) return failed;
238
+ clockHighWaterMs = now;
239
+ } else if (
240
+ now > lastMs ||
241
+ (now === lastMs &&
242
+ fraction > Math.floor((counterHi * 0x1_0000_0000 + counterLo) / counterModulus))
243
+ ) {
244
+ const failed = reseed(now, fraction);
139
245
  if (failed) return failed;
140
- ms = timestamp as number;
141
- sequenceHi = seedHi(random);
142
- sequenceLo = seedLo(random);
143
246
  } else {
144
- // Truncated THEN validated, in that order and not the other. A clock is allowed to be
247
+ const nextLo = (counterLo + 1) >>> 0;
248
+ const nextHi = counterHi + (nextLo === 0 ? 1 : 0);
249
+ // Past 42 bits the sequence no longer fits `rand_a` plus the borrowed `rand_b` bits.
250
+ // Borrowing the next millisecond keeps ids ordered and unique rather than wrapping into
251
+ // values this millisecond has already issued.
252
+ if (nextHi > 0x3ff) {
253
+ // At the ceiling there is no next millisecond to borrow: `writeTimestamp` truncates to
254
+ // six bytes, so `lastMs + 1` wraps to 0 and the generator restarts in 1970 — ordering
255
+ // broken permanently, and silently, from that call onward. Unreachable on a real clock
256
+ // until the year 10889; reachable from a supplied instant near the ceiling.
257
+ if (lastMs >= MAX_UUID_V7_UNIX_MS)
258
+ return new UuidSlugError(
259
+ INVALID_TIMESTAMP,
260
+ `UUIDv7 sequence exhausted at Unix millisecond ${MAX_UUID_V7_UNIX_MS}; another UUID would exceed the 48-bit timestamp.`,
261
+ );
262
+ const failed = reseed(lastMs + 1, 0);
263
+ if (failed) return failed;
264
+ } else {
265
+ const failed = fillRandomBytes(fill, randomTail);
266
+ if (failed) return failed;
267
+ // Commit only after entropy succeeds; a failed draw must not consume sequence state.
268
+ counterLo = nextLo;
269
+ counterHi = nextHi;
270
+ }
271
+ }
272
+ if (rollback !== undefined && now > clockHighWaterMs) clockHighWaterMs = now;
273
+ return undefined;
274
+ }
275
+
276
+ function bytes(out?: Uint8Array, offset = 0): Uint8Array | UuidSlugError {
277
+ if (generating) return reenteredGeneration();
278
+ generating = true;
279
+ try {
280
+ const target = out ?? new Uint8Array(16);
281
+ // Allocation proves the zero-offset range; caller storage and other offsets still need checks.
282
+ const badRange =
283
+ target === textBytes
284
+ ? undefined
285
+ : out === undefined
286
+ ? offset === 0
287
+ ? undefined
288
+ : checkRange(16, offset, 16)
289
+ : checkByteRange(out, offset, 16);
290
+ if (badRange) return badRange;
291
+ // Split THEN validated, in that order and not the other. A readUnixMs is allowed to be
145
292
  // fractional — `performance.timeOrigin + performance.now()` is, and is a perfectly good one —
146
- // so rejecting non-integers here would refuse a legitimate caller, unlike `rejectInstant`,
147
- // where the fraction is in an argument the caller wrote out. What must not survive is a
293
+ // so rejecting non-integers here would refuse a legitimate caller. What must not survive is a
148
294
  // truncated value the format cannot carry: `writeTimestamp` keeps the low 48 bits of whatever
149
295
  // it is handed, so NaN and 2**48 both silently produced the 1970 prefix and a negative
150
296
  // millisecond produced the year 10889 by two's-complement wrap. All three now report.
151
- // The raw reading is kept for the message rather than calling `clock()` again: a second call
297
+ // The raw reading is kept for the message rather than calling `readUnixMs()` again: a second call
152
298
  // is a second reading, and the message would name a value other than the one refused.
153
- const reading = readClock(clock);
154
- if (reading instanceof Error) return reading;
155
- const now = Math.trunc(reading);
156
- if (reading < 0 || !isValidUuidV7Timestamp(now))
299
+ const reading = readClock(readUnixMs);
300
+ if (isUuidSlugError(reading)) return reading;
301
+ const now = typeof reading === "number" ? Math.trunc(reading) : NaN;
302
+ if (typeof reading !== "number" || reading < 0 || !isValidUuidV7UnixMs(now))
157
303
  return new UuidSlugError(
158
- "invalid_timestamp",
159
- `Clock returned ${String(reading)}, which is not a millisecond in 0..${MAX_TIMESTAMP}.`,
304
+ INVALID_TIMESTAMP,
305
+ `Clock returned ${diagnosticValue(reading)}, which is not a millisecond in 0..${MAX_UUID_V7_UNIX_MS}.`,
160
306
  );
161
- if (now > lastMs) {
162
- const failed = reseed(now);
307
+ const fraction =
308
+ fractionBits === 0
309
+ ? 0
310
+ : options.readFractionBucket12 !== undefined
311
+ ? options.readFractionBucket12() >>> (12 - fractionBits)
312
+ : Math.min(2 ** fractionBits - 1, Math.floor((reading - now) * 2 ** fractionBits));
313
+ const failed = advanceSequence(now, fraction);
314
+ if (failed) return failed;
315
+ return writeBytes(target, offset, lastMs, counterHi, counterLo);
316
+ } finally {
317
+ generating = false;
318
+ }
319
+ }
320
+
321
+ function bytesAt(
322
+ instant: NormalizedUuidV7Instant,
323
+ out?: Uint8Array,
324
+ offset = 0,
325
+ ): Uint8Array | UuidSlugError {
326
+ if (generating) return reenteredGeneration();
327
+ generating = true;
328
+ try {
329
+ const target = out ?? new Uint8Array(16);
330
+ // Match current-time ownership: checking an owned zero-offset range would prove nothing new.
331
+ const badRange =
332
+ out === undefined
333
+ ? offset === 0
334
+ ? undefined
335
+ : checkRange(16, offset, 16)
336
+ : checkByteRange(out, offset, 16);
337
+ if (badRange) return badRange;
338
+ const fraction = fractionBits === 0 ? 0 : instant.fractionBucket12 >>> (12 - fractionBits);
339
+ if (coordinateExplicitInstants) {
340
+ const failed = advanceSequence(instant.unixMs, fraction);
163
341
  if (failed) return failed;
164
- } else {
165
- counterLo = (counterLo + 1) >>> 0;
166
- if (counterLo === 0) counterHi += 1;
167
- // Past 42 bits the sequence no longer fits `rand_a` plus the borrowed `rand_b` bits.
168
- // Borrowing the next millisecond keeps ids ordered and unique rather than wrapping into
169
- // values this millisecond has already issued.
170
- if (counterHi > 0x3ff) {
171
- // At the ceiling there is no next millisecond to borrow: `writeTimestamp` truncates to
172
- // six bytes, so `lastMs + 1` wraps to 0 and the generator restarts in 1970 — ordering
173
- // broken permanently, and silently, from that call onward. Unreachable on a real clock
174
- // until the year 10889; reachable now from any clock that lands near the ceiling, which
175
- // is why refusing is not theoretical.
176
- if (lastMs >= MAX_TIMESTAMP)
177
- return new UuidSlugError(
178
- "invalid_timestamp",
179
- `Sequence exhausted at the last representable millisecond (${MAX_TIMESTAMP}).`,
180
- );
181
- const failed = reseed(lastMs + 1);
182
- if (failed) return failed;
183
- } else {
184
- const failed = fillRandomBytes(fill, random);
185
- if (failed) return failed;
186
- }
342
+ return writeBytes(target, offset, lastMs, counterHi, counterLo);
187
343
  }
188
- ms = lastMs;
189
- sequenceHi = counterHi;
190
- sequenceLo = counterLo;
344
+ const failed = fillRandomBytes(fill, random);
345
+ if (failed) return failed;
346
+ const seededCounter = (seedHi(random) * 0x1_0000_0000 + seedLo(random)) % counterModulus;
347
+ const payloadPrefix = fraction * counterModulus + seededCounter;
348
+ return writeBytes(
349
+ target,
350
+ offset,
351
+ instant.unixMs,
352
+ Math.floor(payloadPrefix / 0x1_0000_0000),
353
+ payloadPrefix >>> 0,
354
+ );
355
+ } finally {
356
+ generating = false;
191
357
  }
192
- // The checked offset applies to every store. Write directly into the target so callers
193
- // reusing an output buffer also avoid allocating a temporary typed-array view.
194
- writeTimestamp(target, ms, offset);
195
- writeCounter(target, sequenceHi, sequenceLo, offset);
196
- for (let i = 12; i < 16; i += 1) target[offset + i] = random[i] as number;
197
- return target;
198
358
  }
199
359
 
200
- return {
201
- uuidV7() {
202
- const formatted = formatUuidV7(bytes());
203
- // Throws rather than returns, because this signature promises a string: the two ways it can
204
- // fail — entropy, and a `clock` that returns something the format cannot carry — are both
205
- // configuration the caller cannot act on per call. `uuidV7At` returns its Error instead,
206
- // because there the failure is a value the caller passed in at the call site.
207
- if (formatted instanceof Error) throw formatted;
208
- return formatted;
209
- },
210
- uuidV7At: (timestamp) => formatUuidV7(bytes(undefined, 0, timestamp, true)),
211
- uuidV7Bytes: (out, offset) => bytes(out, offset),
212
- uuidV7BytesAt: (timestamp, out, offset) => bytes(out, offset, timestamp, true),
213
- };
214
- }
360
+ function generateUuidV7Bytes(): UuidV7Bytes | UuidSlugError;
361
+ function generateUuidV7Bytes<Output extends Uint8Array>(
362
+ out: Output,
363
+ offset?: number,
364
+ ): UuidOutput<Output> | UuidSlugError;
365
+ function generateUuidV7Bytes(
366
+ options: Omit<GenerateUuidV7BytesOptions, "generator">,
367
+ ): UuidV7Bytes | UuidSlugError;
368
+ function generateUuidV7Bytes<Output extends Uint8Array>(
369
+ options: Omit<GenerateUuidV7BytesIntoOptions<Output>, "generator">,
370
+ ): UuidOutput<Output> | UuidSlugError;
371
+ function generateUuidV7Bytes(
372
+ outOrOptions?:
373
+ | Uint8Array
374
+ | Omit<GenerateUuidV7BytesOptions, "generator">
375
+ | Omit<GenerateUuidV7BytesIntoOptions<Uint8Array>, "generator">,
376
+ offset?: number,
377
+ ): Uint8Array | UuidSlugError {
378
+ if (outOrOptions === undefined || isUint8Array(outOrOptions))
379
+ return bytes(outOrOptions, offset);
380
+ if (Array.isArray(outOrOptions) || ArrayBuffer.isView(outOrOptions))
381
+ return checkByteRange(outOrOptions, offset ?? 0, 16) as UuidSlugError;
382
+ const values = readGenerationOptions(
383
+ outOrOptions,
384
+ UUID_V7_BYTE_OPTIONS,
385
+ "UUIDv7 byte generation",
386
+ );
387
+ if (values instanceof Error) return values;
388
+ const output = values.output as Uint8Array | undefined;
389
+ const outputOffset = values.outputOffset as number | undefined;
390
+ if (!Object.hasOwn(values, AT_OPTION)) return bytes(output, outputOffset);
391
+ const instant = readUuidV7Instant(values.at);
392
+ return instant instanceof Error ? instant : bytesAt(instant, output, outputOffset);
393
+ }
394
+
395
+ function drawUuidV7Bytes(
396
+ instant: NormalizedUuidV7Instant | undefined,
397
+ output?: Uint8Array,
398
+ outputOffset?: number,
399
+ ): Uint8Array | UuidSlugError {
400
+ return instant === undefined
401
+ ? bytes(output, outputOffset)
402
+ : bytesAt(instant, output, outputOffset);
403
+ }
404
+
405
+ function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
406
+ ...textCase: UuidTextCaseArguments<Case>
407
+ ): UuidV7StringFor<Case> | UuidSlugError;
408
+ function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
409
+ options: Omit<GenerateUuidV7Options<Case>, "generator">,
410
+ ): UuidV7StringFor<Case> | UuidSlugError;
411
+ function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
412
+ textCaseOrOptions:
413
+ | Case
414
+ | Omit<GenerateUuidV7Options<Case>, "generator"> = UUID_TEXT_LOWERCASE as Case,
415
+ ): UuidV7StringFor<Case> | UuidSlugError {
416
+ if (typeof textCaseOrOptions === "string") {
417
+ const textCase = resolveUuidTextCase(textCaseOrOptions);
418
+ if (textCase instanceof Error) return textCase;
419
+ // Preset text consumes this exact destination, so passing it through a formatting helper
420
+ // adds no information. Keep configured calls shared; remeasure when either writer changes.
421
+ const result = bytes(textBytes);
422
+ return result === textBytes
423
+ ? (formatUuidBytesUnchecked(textBytes, 0, textCase) as UuidV7StringFor<Case>)
424
+ : (result as UuidSlugError);
425
+ }
426
+ let values = readGenerationOptions(
427
+ textCaseOrOptions,
428
+ UUID_V7_TEXT_OPTIONS,
429
+ "UUIDv7 generation",
430
+ );
431
+ if (values instanceof Error) {
432
+ const wrappedCase = stringInput(textCaseOrOptions);
433
+ if (wrappedCase !== undefined) values = { textCase: wrappedCase };
434
+ }
435
+ if (values instanceof Error) return values;
436
+ const textCase = resolveUuidTextCase(values.textCase ?? UUID_TEXT_LOWERCASE);
437
+ if (textCase instanceof Error) return textCase;
438
+ if (!Object.hasOwn(values, AT_OPTION))
439
+ return formatUuidV7(bytes(textBytes), textCase, textBytes) as UuidV7StringFor<Case>;
440
+ const instant = readUuidV7Instant(values.at);
441
+ return instant instanceof Error
442
+ ? instant
443
+ : (formatUuidV7(bytesAt(instant, textBytes), textCase, textBytes) as UuidV7StringFor<Case>);
444
+ }
215
445
 
216
- export function createRuntimeGenerator(runtime: Runtime): UuidV7Generator {
217
- const fallback = createUuidV7Generator({ fillRandom: runtime.fillRandom });
218
446
  return {
219
- uuidV7() {
220
- if (!runtime.uuidV7) return fallback.uuidV7();
221
- try {
222
- return runtime.uuidV7();
223
- } catch {
224
- return fallback.uuidV7();
225
- }
226
- },
227
- // The range is checked BEFORE delegating for the same reason the instant is: a native writer
228
- // is handed the caller's buffer and offset directly, and answers differently from the portable
229
- // path. Measured on Bun 1.3.14, `out.set(bytes, offset)` coerces a NaN offset to 0 and writes
230
- // at the wrong place reporting success, while a fractional one throws a RangeError that the
231
- // catch below would relabel `rng_unavailable` — blaming the entropy source for a caller's
232
- // argument. Checking here is what makes every runtime give the one answer.
233
- uuidV7Bytes(out?: Uint8Array, offset = 0) {
234
- // Guarded only on the branch that leaves this package: the fallback checks the same range
235
- // itself, so checking before the branch would pay for it twice on every Node call.
236
- if (!runtime.uuidV7Bytes) return fallback.uuidV7Bytes(out, offset);
237
- const badRange = checkRange(out?.length ?? 16, offset, 16);
238
- if (badRange) return badRange;
239
- try {
240
- return runtime.uuidV7Bytes(out, offset);
241
- } catch (cause) {
242
- return new UuidSlugError("rng_unavailable", "Runtime UUIDv7 byte generation failed.", {
243
- cause,
244
- });
245
- }
246
- },
247
- // Both timestamped paths reject the instant BEFORE reaching the platform, because a native
248
- // generator that accepts it may answer wrongly instead of failing: measured 2026-08-12,
249
- // `Bun.randomUUIDv7("hex", NaN)` and the same call at 2^48 both return the 1970 prefix
250
- // `000000000000` silently, while -1 and 1.5 throw. Each then mirrors its untimestamped
251
- // sibling on a platform failure — fall back for the string form, report for the byte form —
252
- // so the four entry points behave predictably in pairs.
253
- uuidV7At(timestamp: number) {
254
- if (!runtime.uuidV7At) return fallback.uuidV7At(timestamp);
255
- const invalid = rejectInstant(timestamp);
256
- if (invalid) return invalid;
257
- try {
258
- return runtime.uuidV7At(timestamp);
259
- } catch {
260
- return fallback.uuidV7At(timestamp);
261
- }
262
- },
263
- uuidV7BytesAt(timestamp: number, out?: Uint8Array, offset = 0) {
264
- if (!runtime.uuidV7BytesAt) return fallback.uuidV7BytesAt(timestamp, out, offset);
265
- const invalid = rejectInstant(timestamp);
266
- if (invalid) return invalid;
267
- const badRange = checkRange(out?.length ?? 16, offset, 16);
268
- if (badRange) return badRange;
269
- try {
270
- return runtime.uuidV7BytesAt(timestamp, out, offset);
271
- } catch (cause) {
272
- return new UuidSlugError("rng_unavailable", "Runtime UUIDv7 byte generation failed.", {
273
- cause,
274
- });
275
- }
276
- },
447
+ // Text formatting consumes bytes synchronously, so one generator-owned buffer removes an
448
+ // allocation without exposing mutable storage. The reentrancy guard protects it while readUnixMs
449
+ // and entropy callbacks run.
450
+ payloadLayout,
451
+ generateUuidV7,
452
+ generateUuidV7Bytes,
453
+ drawUuidV7Bytes,
277
454
  };
278
455
  }
@@ -1,20 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
3
- import { UuidSlugError } from "./errors.js";
4
- import { Base64UrlString } from "./types.js";
5
- //#region src/base64url.d.ts
6
- declare function encodeBase64Url(bytes: Uint8Array): Base64UrlString;
7
- /**
8
- * Decodes into `out` at `offset` when given one, otherwise into a fresh array.
9
- *
10
- * Returns a view over EXACTLY the bytes decoded, in both cases. The two used to disagree: without
11
- * `out` the result was `byteLength`-exact, with `out` it was the caller's entire buffer at its full
12
- * size, with the data at `offset` and no way to learn how many bytes had been written short of
13
- * recomputing `floor(value.length * 6 / 8)` by hand. One rule — "the bytes this call produced" —
14
- * makes the length usable and leaves the caller's own buffer reachable, since they own it.
15
- */
16
- declare function decodeBase64Url(value: string, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
17
- declare function isBase64Url(value: null | string | undefined): value is Base64UrlString;
18
- //#endregion
19
- export { decodeBase64Url, encodeBase64Url, isBase64Url };
20
- //# sourceMappingURL=base64url.d.ts.map