@anizoptera/uuid-slug 0.2.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.
- package/LICENSE +54 -31
- package/README.md +1175 -30
- package/dist/alphabet.d.ts +9 -0
- package/dist/alphabet.d.ts.map +1 -0
- package/dist/alphabet.js +166 -0
- package/dist/alphabet.js.map +1 -0
- package/dist/base64url-name.d.ts +7 -0
- package/dist/base64url-name.d.ts.map +1 -0
- package/dist/base64url-name.js +8 -0
- package/dist/base64url-name.js.map +1 -0
- package/dist/errors.d.ts +57 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +162 -0
- package/dist/errors.js.map +1 -0
- package/dist/feistel.js +39 -0
- package/dist/feistel.js.map +1 -0
- package/dist/generation-options.js +20 -0
- package/dist/generation-options.js.map +1 -0
- package/dist/index.d.ts +23 -168
- package/dist/index.js +22 -649
- package/dist/instant.js +83 -0
- package/dist/instant.js.map +1 -0
- package/dist/mask-handle.d.ts +16 -0
- package/dist/mask-handle.d.ts.map +1 -0
- package/dist/mask-handle.js +60 -0
- package/dist/mask-handle.js.map +1 -0
- package/dist/mask.d.ts +27 -0
- package/dist/mask.d.ts.map +1 -0
- package/dist/mask.js +164 -0
- package/dist/mask.js.map +1 -0
- package/dist/masking-codec-protocol.js +23 -0
- package/dist/masking-codec-protocol.js.map +1 -0
- package/dist/masking-codec-types.d.ts +245 -0
- package/dist/masking-codec-types.d.ts.map +1 -0
- package/dist/masking-codec.d.ts +19 -0
- package/dist/masking-codec.d.ts.map +1 -0
- package/dist/masking-codec.js +391 -0
- package/dist/masking-codec.js.map +1 -0
- package/dist/migration.js +129 -0
- package/dist/migration.js.map +1 -0
- package/dist/node/runtime.js +39 -0
- package/dist/node/runtime.js.map +1 -0
- package/dist/payload.d.ts +7 -0
- package/dist/payload.d.ts.map +1 -0
- package/dist/payload.js +118 -0
- package/dist/payload.js.map +1 -0
- package/dist/runtime/pool.js +30 -0
- package/dist/runtime/pool.js.map +1 -0
- package/dist/runtime/portable.js +27 -0
- package/dist/runtime/portable.js.map +1 -0
- package/dist/sentinel.js +10 -0
- package/dist/sentinel.js.map +1 -0
- package/dist/siphash.js +29 -0
- package/dist/siphash.js.map +1 -0
- package/dist/slug.d.ts +169 -0
- package/dist/slug.d.ts.map +1 -0
- package/dist/slug.js +268 -0
- package/dist/slug.js.map +1 -0
- package/dist/timestamp.d.ts +19 -0
- package/dist/timestamp.d.ts.map +1 -0
- package/dist/timestamp.js +44 -0
- package/dist/timestamp.js.map +1 -0
- package/dist/types.d.ts +535 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +8 -0
- package/dist/types.js.map +1 -0
- package/dist/uuid-value-protocol.js +46 -0
- package/dist/uuid-value-protocol.js.map +1 -0
- package/dist/uuid-value.d.ts +17 -0
- package/dist/uuid-value.d.ts.map +1 -0
- package/dist/uuid-value.js +127 -0
- package/dist/uuid-value.js.map +1 -0
- package/dist/uuid.d.ts +65 -0
- package/dist/uuid.d.ts.map +1 -0
- package/dist/uuid.js +232 -0
- package/dist/uuid.js.map +1 -0
- package/dist/v4-slug.d.ts +16 -0
- package/dist/v4-slug.d.ts.map +1 -0
- package/dist/v4-slug.js +16 -0
- package/dist/v4-slug.js.map +1 -0
- package/dist/v4.d.ts +42 -0
- package/dist/v4.d.ts.map +1 -0
- package/dist/v4.js +85 -0
- package/dist/v4.js.map +1 -0
- package/dist/v7-bounds.d.ts +36 -0
- package/dist/v7-bounds.d.ts.map +1 -0
- package/dist/v7-bounds.js +49 -0
- package/dist/v7-bounds.js.map +1 -0
- package/dist/v7-generator-input.js +75 -0
- package/dist/v7-generator-input.js.map +1 -0
- package/dist/v7-generator.d.ts +43 -0
- package/dist/v7-generator.d.ts.map +1 -0
- package/dist/v7-generator.js +105 -0
- package/dist/v7-generator.js.map +1 -0
- package/dist/v7-keyless.d.ts +46 -0
- package/dist/v7-keyless.d.ts.map +1 -0
- package/dist/v7-keyless.js +106 -0
- package/dist/v7-keyless.js.map +1 -0
- package/dist/v7-payload.js +54 -0
- package/dist/v7-payload.js.map +1 -0
- package/dist/v7-slug.d.ts +46 -0
- package/dist/v7-slug.d.ts.map +1 -0
- package/dist/v7-slug.js +127 -0
- package/dist/v7-slug.js.map +1 -0
- package/dist/v7-timestamp.js +9 -0
- package/dist/v7-timestamp.js.map +1 -0
- package/dist/v7-value-options.js +28 -0
- package/dist/v7-value-options.js.map +1 -0
- package/dist/v7-value.d.ts +23 -0
- package/dist/v7-value.d.ts.map +1 -0
- package/dist/v7-value.js +31 -0
- package/dist/v7-value.js.map +1 -0
- package/dist/v7.js +143 -0
- package/dist/v7.js.map +1 -0
- package/package.json +18 -17
- package/src/alphabet.ts +616 -0
- package/src/base64url-name.ts +5 -0
- package/src/errors.ts +423 -13
- package/src/feistel.ts +141 -0
- package/src/generation-options.ts +48 -0
- package/src/index.ts +137 -57
- package/src/instant.ts +196 -0
- package/src/keyless.ts +9 -0
- package/src/mask-handle.ts +141 -0
- package/src/mask.ts +377 -90
- package/src/masking-codec-protocol.ts +29 -0
- package/src/masking-codec-types.ts +380 -0
- package/src/masking-codec.ts +923 -0
- package/src/migration.ts +257 -0
- package/src/payload.ts +321 -0
- package/src/runtime/bun.ts +31 -25
- package/src/runtime/node.ts +55 -18
- package/src/runtime/pool.ts +90 -0
- package/src/runtime/portable.ts +68 -0
- package/src/runtime/types.ts +30 -5
- package/src/sentinel.ts +13 -0
- package/src/siphash.ts +128 -0
- package/src/slug.ts +884 -0
- package/src/timestamp.ts +122 -0
- package/src/types.ts +799 -61
- package/src/uuid-value-protocol.ts +77 -0
- package/src/uuid-value.ts +341 -0
- package/src/uuid.ts +527 -108
- package/src/v4-slug.ts +27 -0
- package/src/v4.ts +234 -0
- package/src/v7-bounds.ts +171 -0
- package/src/v7-generator-input.ts +169 -0
- package/src/v7-generator.ts +245 -0
- package/src/v7-keyless.ts +354 -0
- package/src/v7-payload.ts +121 -0
- package/src/v7-slug.ts +293 -0
- package/src/v7-timestamp.ts +21 -0
- package/src/v7-value-options.ts +62 -0
- package/src/v7-value.ts +54 -0
- package/src/v7.ts +433 -84
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/node/index.js +0 -647
- package/dist/web/index.js +0 -648
- package/src/base64url.ts +0 -76
- package/src/codec.ts +0 -218
- package/src/runtime/web.ts +0 -20
- package/src/schema.ts +0 -123
package/src/v7.ts
CHANGED
|
@@ -1,106 +1,455 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
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";
|
|
34
|
+
|
|
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>;
|
|
9
53
|
}
|
|
10
54
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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;
|
|
15
103
|
value = Math.floor(value / 256);
|
|
16
104
|
}
|
|
17
105
|
}
|
|
18
106
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
107
|
+
// Measured Bun favors the loop while Node and Chromium favor fixed writes; select once so generation
|
|
108
|
+
// pays no per-call branch. bench/PERFORMANCE.md owns the measurements and replacement condition.
|
|
109
|
+
const writeTimestamp = (globalThis as { Bun?: object }).Bun
|
|
110
|
+
? writeTimestampLoop
|
|
111
|
+
: writeTimestampWords;
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Writes the 42-bit sequence RFC 9562 §6.2 allows in `rand_a` plus the top of `rand_b`, along
|
|
115
|
+
* with the version and variant bits that bracket it.
|
|
116
|
+
*
|
|
117
|
+
* The sequence is carried as a 10-bit high half and a 32-bit low half rather than one 42-bit
|
|
118
|
+
* BigInt, so every operation here is a 32-bit integer op the JIT emits directly. Measured on the
|
|
119
|
+
* increment-and-write step alone: 9.99M ops/s (Bun) and 11.8M (Node) as a BigInt, against 252M
|
|
120
|
+
* and 149M in this form. The bit layout is unchanged, so the ids are identical either way.
|
|
121
|
+
*/
|
|
122
|
+
function writeCounter(bytes: Uint8Array, hi: number, lo: number, offset: number) {
|
|
123
|
+
bytes[offset + 6] = 0x70 | ((hi >>> 6) & 0x0f);
|
|
124
|
+
bytes[offset + 7] = (((hi & 0x3f) << 2) | (lo >>> 30)) & 0xff;
|
|
125
|
+
bytes[offset + 8] = 0x80 | ((lo >>> 24) & 0x3f);
|
|
126
|
+
bytes[offset + 9] = (lo >>> 16) & 0xff;
|
|
127
|
+
bytes[offset + 10] = (lo >>> 8) & 0xff;
|
|
128
|
+
bytes[offset + 11] = lo & 0xff;
|
|
26
129
|
}
|
|
27
130
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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);
|
|
142
|
+
|
|
143
|
+
const reenteredGeneration = /* @__NO_SIDE_EFFECTS__ */ () =>
|
|
144
|
+
new UuidSlugError(
|
|
145
|
+
RNG_UNAVAILABLE,
|
|
146
|
+
"UUIDv7 generation cannot be reentered from its readUnixMs or entropy callback.",
|
|
36
147
|
);
|
|
37
|
-
}
|
|
38
148
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
149
|
+
/**
|
|
150
|
+
* Seeds the sequence from the same six random bytes and the same bit positions as before, split
|
|
151
|
+
* across the two halves: byte 0 and the top 2 bits of byte 1 form the high half, the rest the
|
|
152
|
+
* low half. Starting each millisecond at a random point rather than zero is what stops the
|
|
153
|
+
* sequence leaking how many ids were issued in the previous millisecond.
|
|
154
|
+
*/
|
|
155
|
+
const seedHi = /* @__NO_SIDE_EFFECTS__ */ (bytes: Uint8Array) =>
|
|
156
|
+
(((bytes[0] ?? 0) << 2) | ((bytes[1] ?? 0) >>> 6)) & 0x3ff;
|
|
157
|
+
|
|
158
|
+
const seedLo = /* @__NO_SIDE_EFFECTS__ */ (bytes: Uint8Array) =>
|
|
159
|
+
((((bytes[1] ?? 0) & 0x3f) << 26) |
|
|
160
|
+
((bytes[2] ?? 0) << 18) |
|
|
161
|
+
((bytes[3] ?? 0) << 10) |
|
|
162
|
+
((bytes[4] ?? 0) << 2) |
|
|
163
|
+
((bytes[5] ?? 0) & 0x03)) >>>
|
|
164
|
+
0;
|
|
165
|
+
|
|
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;
|
|
174
|
+
const fill = options.fillRandom;
|
|
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);
|
|
189
|
+
/**
|
|
190
|
+
* Below every timestamp the readUnixMs check admits, which is what makes it the uninitialised
|
|
191
|
+
* sentinel rather than a value: `now > lastMs` alone therefore takes the reseed branch on the
|
|
192
|
+
* first call, and no separate "have we started" flag is needed. The coupling is deliberate and
|
|
193
|
+
* is why the readUnixMs is validated before this is compared against — an unvalidated readUnixMs returning
|
|
194
|
+
* a negative millisecond would make `lastMs` stay below it forever, so the monotonic counter
|
|
195
|
+
* would never be used and every call would reseed.
|
|
196
|
+
*/
|
|
42
197
|
let lastMs = -1;
|
|
43
|
-
let
|
|
198
|
+
let clockHighWaterMs = -1;
|
|
199
|
+
let counterHi = 0;
|
|
200
|
+
let counterLo = 0;
|
|
201
|
+
let generating = false;
|
|
202
|
+
const textBytes = options.textScratch ?? new Uint8Array(16);
|
|
44
203
|
|
|
45
|
-
function reseed(ms: number) {
|
|
46
|
-
|
|
204
|
+
function reseed(ms: number, fraction: number) {
|
|
205
|
+
const failed = fillRandomBytes(fill, random);
|
|
206
|
+
if (failed) return failed;
|
|
207
|
+
const seededCounter = (seedHi(random) * 0x1_0000_0000 + seedLo(random)) % counterModulus;
|
|
208
|
+
const payloadPrefix = fraction * counterModulus + seededCounter;
|
|
47
209
|
lastMs = ms;
|
|
48
|
-
|
|
210
|
+
counterHi = Math.floor(payloadPrefix / 0x1_0000_0000);
|
|
211
|
+
counterLo = payloadPrefix >>> 0;
|
|
212
|
+
return undefined;
|
|
49
213
|
}
|
|
50
214
|
|
|
51
|
-
function
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
const uuid = target.subarray(offset, offset + 16);
|
|
63
|
-
writeTimestamp(uuid, lastMs);
|
|
64
|
-
writeCounter(uuid, counter);
|
|
65
|
-
target[offset + 12] = random[12] ?? 0;
|
|
66
|
-
target[offset + 13] = random[13] ?? 0;
|
|
67
|
-
target[offset + 14] = random[14] ?? 0;
|
|
68
|
-
target[offset + 15] = random[15] ?? 0;
|
|
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;
|
|
69
225
|
return target;
|
|
70
226
|
}
|
|
71
227
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
if (
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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);
|
|
245
|
+
if (failed) return failed;
|
|
246
|
+
} else {
|
|
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;
|
|
93
270
|
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
|
292
|
+
// fractional — `performance.timeOrigin + performance.now()` is, and is a perfectly good one —
|
|
293
|
+
// so rejecting non-integers here would refuse a legitimate caller. What must not survive is a
|
|
294
|
+
// truncated value the format cannot carry: `writeTimestamp` keeps the low 48 bits of whatever
|
|
295
|
+
// it is handed, so NaN and 2**48 both silently produced the 1970 prefix and a negative
|
|
296
|
+
// millisecond produced the year 10889 by two's-complement wrap. All three now report.
|
|
297
|
+
// The raw reading is kept for the message rather than calling `readUnixMs()` again: a second call
|
|
298
|
+
// is a second reading, and the message would name a value other than the one refused.
|
|
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))
|
|
303
|
+
return new UuidSlugError(
|
|
304
|
+
INVALID_TIMESTAMP,
|
|
305
|
+
`Clock returned ${diagnosticValue(reading)}, which is not a millisecond in 0..${MAX_UUID_V7_UNIX_MS}.`,
|
|
306
|
+
);
|
|
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);
|
|
341
|
+
if (failed) return failed;
|
|
342
|
+
return writeBytes(target, offset, lastMs, counterHi, counterLo);
|
|
103
343
|
}
|
|
104
|
-
|
|
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;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
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
|
+
}
|
|
445
|
+
|
|
446
|
+
return {
|
|
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,
|
|
105
454
|
};
|
|
106
455
|
}
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/base64url.ts","../src/uuid.ts","../src/codec.ts","../src/errors.ts","../src/schema.ts","../src/runtime/types.ts","../src/v7.ts","../src/index.ts"],"mappings":";cAAc;KAEF,MAAM,GAAG,uBAAuB;YAAgB,SAAS;;KAEzD,kBAAkB;KAClB,aAAa;KACb,eAAe,MAAM;KACrB,eAAe,MAAM;KACrB,WAAW,MAAM;KACjB,aAAa,MAAM;KACnB,aAAa,MAAM;KACnB,iBAAiB,MAAM;KACvB,mBAAmB,MAAM;KACzB,qBAAqB,MAAM;KAC3B,mBAAmB,mBAAmB;KACtC,YAAY,MAAM;UAEb;EACf;EACA;;UAGe;EACf,UAAU;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