@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
@@ -0,0 +1,121 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { findUnknownOption, INVALID_OPTIONS, UuidSlugError } from "./errors.ts";
4
+ import type { UuidV7Payload, UuidV7PayloadLayout } from "./types.ts";
5
+
6
+ const PAYLOAD_BITS = 74;
7
+ const MAX_SUB_MILLISECOND_FRACTION_BITS = 12;
8
+ const PAYLOAD_LAYOUT_OPTIONS = {
9
+ counterBits: true,
10
+ subMillisecondFractionBits: true,
11
+ } as const satisfies Record<keyof UuidV7PayloadLayout, true>;
12
+
13
+ const describeBitCount = (value: unknown): string =>
14
+ typeof value === "number" ? String(value) : `type ${typeof value}`;
15
+
16
+ interface ValidatedUuidV7PayloadLayout {
17
+ readonly subMillisecondFractionBits: number;
18
+ readonly counterBits: number;
19
+ }
20
+
21
+ /** Read every payload-layout field once and validate the complete declared split. */
22
+ export function readUuidV7PayloadLayout(
23
+ layout: unknown,
24
+ ): ValidatedUuidV7PayloadLayout | UuidSlugError {
25
+ let subMillisecondFractionBits: unknown;
26
+ let counterBits: unknown;
27
+ try {
28
+ if (typeof layout !== "object" || layout === null || Array.isArray(layout))
29
+ return new UuidSlugError(INVALID_OPTIONS, "UUIDv7 payload layout must be an object.");
30
+ const unknown = findUnknownOption(layout, PAYLOAD_LAYOUT_OPTIONS);
31
+ if (unknown !== undefined)
32
+ return new UuidSlugError(
33
+ INVALID_OPTIONS,
34
+ `Unknown UUIDv7 payload layout option: ${unknown}.`,
35
+ );
36
+ const source = layout as Partial<Record<keyof UuidV7PayloadLayout, unknown>>;
37
+ subMillisecondFractionBits = source.subMillisecondFractionBits;
38
+ counterBits = source.counterBits;
39
+ } catch (cause) {
40
+ return new UuidSlugError(INVALID_OPTIONS, "UUIDv7 payload layout could not be read.", {
41
+ cause,
42
+ });
43
+ }
44
+ if (
45
+ !Number.isInteger(subMillisecondFractionBits) ||
46
+ (subMillisecondFractionBits as number) < 0 ||
47
+ (subMillisecondFractionBits as number) > MAX_SUB_MILLISECOND_FRACTION_BITS
48
+ )
49
+ return new UuidSlugError(
50
+ INVALID_OPTIONS,
51
+ `subMillisecondFractionBits must be a whole number from 0 through 12; got ${describeBitCount(subMillisecondFractionBits)}.`,
52
+ );
53
+ const fractionBits = subMillisecondFractionBits as number;
54
+ const maximumCounterBits = PAYLOAD_BITS - fractionBits;
55
+ if (
56
+ !Number.isInteger(counterBits) ||
57
+ (counterBits as number) < 0 ||
58
+ (counterBits as number) > maximumCounterBits
59
+ )
60
+ return new UuidSlugError(
61
+ INVALID_OPTIONS,
62
+ `counterBits must be a whole number from 0 through ${maximumCounterBits} when subMillisecondFractionBits is ${fractionBits}; got ${describeBitCount(counterBits)}.`,
63
+ );
64
+ return { subMillisecondFractionBits: fractionBits, counterBits: counterBits as number };
65
+ }
66
+
67
+ /**
68
+ * Join `rand_a` and `rand_b`; version and variant bits are separators, not payload.
69
+ *
70
+ * The upper 34 and lower 40 payload bits are assembled as exact numbers and joined once, because a
71
+ * BigInt conversion and shift per byte cost more than twice as much (bench/PERFORMANCE.md).
72
+ */
73
+ export function uuidV7PayloadFromBytesUnchecked(bytes: Uint8Array, offset: number): bigint {
74
+ const upper =
75
+ ((bytes[offset + 6] as number) & 0x0f) * 0x4000_0000 +
76
+ (bytes[offset + 7] as number) * 0x40_0000 +
77
+ (((bytes[offset + 8] as number) & 0x3f) << 16) +
78
+ ((bytes[offset + 9] as number) << 8) +
79
+ (bytes[offset + 10] as number);
80
+ const lower =
81
+ (bytes[offset + 11] as number) * 0x1_0000_0000 +
82
+ (((bytes[offset + 12] as number) << 24) >>> 0) +
83
+ ((bytes[offset + 13] as number) << 16) +
84
+ ((bytes[offset + 14] as number) << 8) +
85
+ (bytes[offset + 15] as number);
86
+ return (BigInt(upper) << 40n) | BigInt(lower);
87
+ }
88
+
89
+ export function extractPayloadFields(
90
+ bytes: Uint8Array,
91
+ offset: number,
92
+ unixMs: number,
93
+ layout: UuidV7PayloadLayout,
94
+ ): UuidV7Payload | UuidSlugError {
95
+ const validated = readUuidV7PayloadLayout(layout);
96
+ if (validated instanceof Error) return validated;
97
+ const { subMillisecondFractionBits, counterBits } = validated;
98
+ const maximumCounterBits = PAYLOAD_BITS - subMillisecondFractionBits;
99
+
100
+ const payload = uuidV7PayloadFromBytesUnchecked(bytes, offset);
101
+ const remainingBits = maximumCounterBits - counterBits;
102
+ const fractionShift = PAYLOAD_BITS - subMillisecondFractionBits;
103
+ return {
104
+ unixMs,
105
+ subMillisecondFraction:
106
+ subMillisecondFractionBits === 0
107
+ ? undefined
108
+ : {
109
+ value: Number(payload >> BigInt(fractionShift)),
110
+ bits: subMillisecondFractionBits,
111
+ },
112
+ counter:
113
+ counterBits === 0
114
+ ? undefined
115
+ : {
116
+ value: BigInt.asUintN(counterBits, payload >> BigInt(remainingBits)),
117
+ bits: counterBits,
118
+ },
119
+ remaining: { value: BigInt.asUintN(remainingBits, payload), bits: remainingBits },
120
+ };
121
+ }
package/src/v7-slug.ts ADDED
@@ -0,0 +1,293 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { runtime } from "#runtime";
4
+ import { generatedOrThrow, isUuidSlugError, portableAfterNative, stringInput } from "./errors.ts";
5
+ import type { UuidSlugError } from "./errors.ts";
6
+ import { BASE64URL as BASE64URL_ALPHABET, BASE64URL_NAME, encode } from "./alphabet.ts";
7
+ import { readGenerationOptions } from "./generation-options.ts";
8
+ import { UUID_TEXT_LOWERCASE } from "./types.ts";
9
+ import type {
10
+ GeneratedUuidV7,
11
+ GeneratePlainUuidV7SlugOptions,
12
+ GenerateUuidV7WithPlainSlugOptions,
13
+ PlainUuidV7Slug,
14
+ UuidTextCase,
15
+ UuidV7Generator,
16
+ UuidV7StringFor,
17
+ } from "./types.ts";
18
+ import { currentUuidV7Scratch, uuidV7ScratchAt } from "./v7-keyless.ts";
19
+ import { generateUuidV7BytesWithGenerator, readUuidV7Generator } from "./v7-generator-input.ts";
20
+ import { resolveSlugAlphabet } from "./slug.ts";
21
+ import { formatUuidBytesUnchecked, isUuidTextCase, resolveUuidTextCase } from "./uuid.ts";
22
+ import type { SlugAlphabet } from "./slug.ts";
23
+
24
+ const PLAIN_UUID_V7_SLUG_OPTIONS = {
25
+ alphabet: true,
26
+ at: true,
27
+ generator: true,
28
+ } as const satisfies Record<keyof GeneratePlainUuidV7SlugOptions, true>;
29
+ const UUID_V7_WITH_PLAIN_SLUG_OPTIONS = {
30
+ alphabet: true,
31
+ at: true,
32
+ generator: true,
33
+ textCase: true,
34
+ } as const satisfies Record<keyof GenerateUuidV7WithPlainSlugOptions, true>;
35
+ const GENERATOR_PLAIN_SLUG_OPTIONS = {
36
+ alphabet: true,
37
+ at: true,
38
+ } as const satisfies Record<keyof Omit<GeneratePlainUuidV7SlugOptions, "generator">, true>;
39
+ const GENERATOR_WITH_PLAIN_SLUG_OPTIONS = {
40
+ alphabet: true,
41
+ at: true,
42
+ textCase: true,
43
+ } as const satisfies Record<keyof Omit<GenerateUuidV7WithPlainSlugOptions, "generator">, true>;
44
+ const AT_OPTION = "at";
45
+ const PLAIN_UUID_V7_SLUG_GENERATION = "plain UUIDv7 slug generation";
46
+ const hasNativeUuidV7Slug = runtime.uuidV7Slug !== undefined;
47
+
48
+ /** Supply the UUIDv7 bytes one slug operation encodes, from a sequence or from the module clock. */
49
+ type DrawUuidV7Bytes = (values: { readonly at?: unknown }) => Uint8Array | UuidSlugError;
50
+
51
+ // Keep failures as values until the public preset call owns the permitted entropy throw.
52
+ const portableUuidV7Slug = (): string | UuidSlugError => {
53
+ const bytes = currentUuidV7Scratch();
54
+ return bytes instanceof Error ? bytes : encode(bytes, BASE64URL_ALPHABET);
55
+ };
56
+
57
+ // Direct native output removes clock, entropy, byte writing and encoding from ordinary calls.
58
+ // Configured calls and base32hex remain portable. Remeasure complete calls and resources if this
59
+ // boundary changes; bench/PERFORMANCE.md owns evidence. Trust proper native results directly;
60
+ // result validation and identity tracking would impose stronger default guarantees.
61
+ function nativeUuidV7Slug(): string | UuidSlugError {
62
+ const native = runtime.uuidV7Slug;
63
+ if (!native) return portableUuidV7Slug();
64
+ try {
65
+ return native();
66
+ } catch (cause) {
67
+ return portableAfterNative(cause, portableUuidV7Slug, undefined, PLAIN_UUID_V7_SLUG_GENERATION);
68
+ }
69
+ }
70
+
71
+ /** Draw for the module-level calls, where an untrusted `generator` option may select a sequence. */
72
+ const drawKeylessUuidV7Bytes: DrawUuidV7Bytes = (values) => {
73
+ const generator = readUuidV7Generator((values as { generator?: unknown }).generator);
74
+ if (generator instanceof Error) return generator;
75
+ return generator
76
+ ? generateUuidV7BytesWithGenerator(generator, values, true)
77
+ : !Object.hasOwn(values, AT_OPTION)
78
+ ? currentUuidV7Scratch()
79
+ : uuidV7ScratchAt(values.at);
80
+ };
81
+
82
+ /**
83
+ * Read one plain-slug call's options, resolve its alphabet, draw, and encode.
84
+ *
85
+ * `presetFormThrows` carries the module-level rule that an alphabet alone cannot fail once
86
+ * accepted, so a failed draw is thrown on that form and returned on the options form, whose time
87
+ * and generator can fail. A generator method never throws: its clock and sequence state can fail
88
+ * on every form.
89
+ */
90
+ function plainUuidV7SlugFrom(
91
+ alphabetOrOptions: SlugAlphabet | GeneratePlainUuidV7SlugOptions,
92
+ accepted: Record<string, true>,
93
+ drawBytes: DrawUuidV7Bytes,
94
+ presetFormThrows: boolean,
95
+ ): PlainUuidV7Slug | UuidSlugError {
96
+ let alphabetOnly = typeof alphabetOrOptions === "string";
97
+ let values = alphabetOnly
98
+ ? { alphabet: alphabetOrOptions as SlugAlphabet }
99
+ : readGenerationOptions(alphabetOrOptions, accepted, PLAIN_UUID_V7_SLUG_GENERATION);
100
+ if (values instanceof Error) {
101
+ const alphabet = stringInput(alphabetOrOptions);
102
+ if (alphabet !== undefined) {
103
+ values = { alphabet };
104
+ alphabetOnly = true;
105
+ }
106
+ }
107
+ if (values instanceof Error) return values;
108
+ const resolved = resolveSlugAlphabet((values.alphabet ?? BASE64URL_NAME) as SlugAlphabet);
109
+ if (resolved instanceof Error) return resolved;
110
+ const bytes = drawBytes(values);
111
+ if (isUuidSlugError(bytes)) {
112
+ if (alphabetOnly && presetFormThrows) throw bytes;
113
+ return bytes;
114
+ }
115
+ return encode(bytes, resolved) as PlainUuidV7Slug;
116
+ }
117
+
118
+ /**
119
+ * Read one pair call's options, resolve both spellings, draw, and encode.
120
+ *
121
+ * `presetFormThrows` carries the same rule as `plainUuidV7SlugFrom`.
122
+ */
123
+ function uuidV7WithPlainSlugFrom(
124
+ alphabetOrCaseOrOptions: SlugAlphabet | UuidTextCase | GenerateUuidV7WithPlainSlugOptions,
125
+ textCase: UuidTextCase,
126
+ accepted: Record<string, true>,
127
+ drawBytes: DrawUuidV7Bytes,
128
+ presetFormThrows: boolean,
129
+ ): GeneratedUuidV7<PlainUuidV7Slug, UuidTextCase> | UuidSlugError {
130
+ let presetsOnly = typeof alphabetOrCaseOrOptions === "string";
131
+ let values = presetsOnly
132
+ ? isUuidTextCase(alphabetOrCaseOrOptions)
133
+ ? { alphabet: BASE64URL_NAME, textCase: alphabetOrCaseOrOptions }
134
+ : { alphabet: alphabetOrCaseOrOptions as SlugAlphabet, textCase }
135
+ : readGenerationOptions(alphabetOrCaseOrOptions, accepted, "UUIDv7 pair generation");
136
+ if (values instanceof Error) {
137
+ const selector = stringInput(alphabetOrCaseOrOptions);
138
+ if (selector !== undefined) {
139
+ values = isUuidTextCase(selector)
140
+ ? { alphabet: BASE64URL_NAME, textCase: selector }
141
+ : { alphabet: selector, textCase };
142
+ presetsOnly = true;
143
+ }
144
+ }
145
+ if (values instanceof Error) return values;
146
+ const selectedCase = resolveUuidTextCase(values.textCase ?? UUID_TEXT_LOWERCASE);
147
+ if (selectedCase instanceof Error) return selectedCase;
148
+ const resolved = resolveSlugAlphabet((values.alphabet ?? BASE64URL_NAME) as SlugAlphabet);
149
+ if (resolved instanceof Error) return resolved;
150
+ const bytes = drawBytes(values);
151
+ if (isUuidSlugError(bytes)) {
152
+ if (presetsOnly && presetFormThrows) throw bytes;
153
+ return bytes;
154
+ }
155
+ return {
156
+ uuid: formatUuidBytesUnchecked(bytes, 0, selectedCase) as UuidV7StringFor<UuidTextCase>,
157
+ slug: encode(bytes, resolved) as PlainUuidV7Slug,
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Build one generator's slug methods around the sequence's own byte draw. The generator is the
163
+ * package's own, so these skip the untrusted-generator validation the module-level calls run.
164
+ */
165
+ export function uuidV7GeneratorSlugMethods(
166
+ drawBytes: DrawUuidV7Bytes,
167
+ ): Pick<UuidV7Generator, "generatePlainUuidV7Slug" | "generateUuidV7WithPlainSlug"> {
168
+ return {
169
+ generatePlainUuidV7Slug: (
170
+ alphabetOrOptions:
171
+ | SlugAlphabet
172
+ | Omit<GeneratePlainUuidV7SlugOptions, "generator"> = BASE64URL_NAME,
173
+ ) => plainUuidV7SlugFrom(alphabetOrOptions, GENERATOR_PLAIN_SLUG_OPTIONS, drawBytes, false),
174
+ generateUuidV7WithPlainSlug: (
175
+ alphabetOrCaseOrOptions:
176
+ | SlugAlphabet
177
+ | UuidTextCase
178
+ | Omit<GenerateUuidV7WithPlainSlugOptions, "generator"> = BASE64URL_NAME,
179
+ textCase: UuidTextCase = UUID_TEXT_LOWERCASE,
180
+ ) =>
181
+ uuidV7WithPlainSlugFrom(
182
+ alphabetOrCaseOrOptions,
183
+ textCase,
184
+ GENERATOR_WITH_PLAIN_SLUG_OPTIONS,
185
+ drawBytes,
186
+ false,
187
+ ),
188
+ };
189
+ }
190
+
191
+ /**
192
+ * Generate a plain UUIDv7 slug. Lowercase base32hex preserves UUID byte order; base64url does not
193
+ * preserve that order under text comparison. Native runtime results are trusted without
194
+ * additional output guarantees. Module calls may advance their logical timestamp
195
+ * during bursts; select a generator when this result must join its sequence or control its clock.
196
+ *
197
+ * @param alphabet - Output spelling. Omit for the shorter 22-character base64url form.
198
+ * @throws `UuidSlugError` with code `rng_unavailable` when generation cannot obtain
199
+ * secure randomness.
200
+ */
201
+ export function generatePlainUuidV7Slug(alphabet?: SlugAlphabet): PlainUuidV7Slug;
202
+ /** Generate a plain UUIDv7 slug with optional time, alphabet, and sequence state. */
203
+ export function generatePlainUuidV7Slug(
204
+ options: GeneratePlainUuidV7SlugOptions,
205
+ ): PlainUuidV7Slug | UuidSlugError;
206
+ /**
207
+ * Forward either an alphabet preset or generation options without branching at the call site.
208
+ * Configured failures return `UuidSlugError`.
209
+ * @throws `UuidSlugError` with code `rng_unavailable` when a preset or undefined branch cannot obtain secure randomness.
210
+ */
211
+ export function generatePlainUuidV7Slug(
212
+ alphabetOrOptions: SlugAlphabet | GeneratePlainUuidV7SlugOptions | undefined,
213
+ ): PlainUuidV7Slug | UuidSlugError;
214
+ export function generatePlainUuidV7Slug(
215
+ alphabetOrOptions: SlugAlphabet | GeneratePlainUuidV7SlugOptions = BASE64URL_NAME,
216
+ ): PlainUuidV7Slug | UuidSlugError {
217
+ // An exact base64url preset needs no further normalization. Native-capable hosts skip portable
218
+ // generation and encoding; other presets still validate before drawing. Wrapped strings retain
219
+ // their existing normalization path. Remeasure all complete calls if selection changes.
220
+ if (typeof alphabetOrOptions === "string") {
221
+ if (hasNativeUuidV7Slug && alphabetOrOptions === BASE64URL_NAME)
222
+ return generatedOrThrow(nativeUuidV7Slug()) as PlainUuidV7Slug;
223
+ const alphabet = resolveSlugAlphabet(alphabetOrOptions);
224
+ return alphabet instanceof Error
225
+ ? alphabet
226
+ : (encode(generatedOrThrow(currentUuidV7Scratch()), alphabet) as PlainUuidV7Slug);
227
+ }
228
+ return plainUuidV7SlugFrom(
229
+ alphabetOrOptions,
230
+ PLAIN_UUID_V7_SLUG_OPTIONS,
231
+ drawKeylessUuidV7Bytes,
232
+ true,
233
+ );
234
+ }
235
+
236
+ /**
237
+ * Generate UUIDv7 text and a plain slug for the same UUID. Select a generator when this result must
238
+ * join its sequence.
239
+ *
240
+ * @param alphabet - Slug spelling. Omit for the shorter 22-character base64url form.
241
+ * @param textCase - UUID text spelling. Pass it alone to keep the default slug alphabet.
242
+ * @returns UUID text plus one slug in the selected alphabet.
243
+ * @throws `UuidSlugError` with code `rng_unavailable` when generation cannot obtain
244
+ * secure randomness.
245
+ */
246
+ export function generateUuidV7WithPlainSlug(
247
+ alphabet?: SlugAlphabet,
248
+ ): GeneratedUuidV7<PlainUuidV7Slug>;
249
+ export function generateUuidV7WithPlainSlug<Case extends UuidTextCase>(
250
+ textCase: Case,
251
+ ): GeneratedUuidV7<PlainUuidV7Slug, Case>;
252
+ export function generateUuidV7WithPlainSlug<Case extends UuidTextCase>(
253
+ alphabet: SlugAlphabet,
254
+ textCase: Case,
255
+ ): GeneratedUuidV7<PlainUuidV7Slug, Case>;
256
+ /**
257
+ * Generate the pair with optional time, spelling, and sequence state.
258
+ *
259
+ * @returns UUID text plus one slug in the selected alphabet, or `UuidSlugError` when generation fails.
260
+ */
261
+ export function generateUuidV7WithPlainSlug<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
262
+ options: GenerateUuidV7WithPlainSlugOptions<Case>,
263
+ ): GeneratedUuidV7<PlainUuidV7Slug, Case> | UuidSlugError;
264
+ export function generateUuidV7WithPlainSlug(
265
+ alphabetOrCaseOrOptions:
266
+ | SlugAlphabet
267
+ | UuidTextCase
268
+ | GenerateUuidV7WithPlainSlugOptions = BASE64URL_NAME,
269
+ textCase: UuidTextCase = UUID_TEXT_LOWERCASE,
270
+ ): GeneratedUuidV7<PlainUuidV7Slug, UuidTextCase> | UuidSlugError {
271
+ // Primitive presets cannot select a clock or generator. Resolve them before the shared scratch
272
+ // draw, then derive both requested spellings without constructing an internal options record.
273
+ // Wrapped strings and configured calls retain their existing normalization and failure path.
274
+ if (typeof alphabetOrCaseOrOptions === "string") {
275
+ const caseOnly = isUuidTextCase(alphabetOrCaseOrOptions);
276
+ const selectedCase = resolveUuidTextCase(caseOnly ? alphabetOrCaseOrOptions : textCase);
277
+ if (selectedCase instanceof Error) return selectedCase;
278
+ const alphabet = resolveSlugAlphabet(caseOnly ? BASE64URL_NAME : alphabetOrCaseOrOptions);
279
+ if (alphabet instanceof Error) return alphabet;
280
+ const bytes = generatedOrThrow(currentUuidV7Scratch());
281
+ return {
282
+ uuid: formatUuidBytesUnchecked(bytes, 0, selectedCase) as UuidV7StringFor<UuidTextCase>,
283
+ slug: encode(bytes, alphabet) as PlainUuidV7Slug,
284
+ };
285
+ }
286
+ return uuidV7WithPlainSlugFrom(
287
+ alphabetOrCaseOrOptions,
288
+ textCase,
289
+ UUID_V7_WITH_PLAIN_SLUG_OPTIONS,
290
+ drawKeylessUuidV7Bytes,
291
+ true,
292
+ );
293
+ }
@@ -0,0 +1,21 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { INVALID_TIMESTAMP, UuidSlugError } from "./errors.ts";
4
+
5
+ /** The 48 bits RFC 9562 gives the timestamp; beyond it the value cannot be represented. */
6
+ export const MAX_UUID_V7_UNIX_MS = 0xffff_ffff_ffff;
7
+
8
+ /** Return whether a number fits the UUIDv7 millisecond field exactly. */
9
+ export const isValidUuidV7UnixMs = /* @__NO_SIDE_EFFECTS__ */ (unixMs: number): boolean =>
10
+ Number.isInteger(unixMs) && unixMs >= 0 && unixMs <= MAX_UUID_V7_UNIX_MS;
11
+
12
+ /** Reject fractions and out-of-range values before constructing or delegating a UUIDv7 value. */
13
+ export const rejectUuidV7UnixMs = /* @__NO_SIDE_EFFECTS__ */ (
14
+ unixMs: number,
15
+ ): undefined | UuidSlugError =>
16
+ isValidUuidV7UnixMs(unixMs)
17
+ ? undefined
18
+ : new UuidSlugError(
19
+ INVALID_TIMESTAMP,
20
+ `UUIDv7 timestamp must be a whole number of milliseconds in 0..${MAX_UUID_V7_UNIX_MS}.`,
21
+ );
@@ -0,0 +1,62 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { INVALID_OPTIONS, isUuidSlugError, UuidSlugError } from "./errors.ts";
4
+ import { readGenerationOptions } from "./generation-options.ts";
5
+ import type { GenerationOptionValues } from "./generation-options.ts";
6
+ import type { Uuid, UuidV7MaskingCodec } from "./types.ts";
7
+ import { generateUuidV7BytesWithGenerator } from "./v7-generator-input.ts";
8
+ import type { ValidatedUuidV7Generator } from "./v7-generator-input.ts";
9
+ import { createUuidValue } from "./uuid-value.ts";
10
+
11
+ export type UuidV7ValueOptionValues = Pick<
12
+ GenerationOptionValues,
13
+ "at" | "generator" | "maskingCodec"
14
+ >;
15
+
16
+ /** Generate through an untrusted structural generator and validate its bytes and payload layout. */
17
+ export function generateUuidV7ValueWithGenerator(
18
+ generator: ValidatedUuidV7Generator,
19
+ options: Pick<UuidV7ValueOptionValues, "at">,
20
+ maskingCodec: UuidV7MaskingCodec,
21
+ ): Uuid<7, true, true> | UuidSlugError;
22
+ export function generateUuidV7ValueWithGenerator(
23
+ generator: ValidatedUuidV7Generator,
24
+ options: Pick<UuidV7ValueOptionValues, "at">,
25
+ maskingCodec?: UuidV7MaskingCodec,
26
+ ): Uuid<7, boolean, true> | UuidSlugError;
27
+ export function generateUuidV7ValueWithGenerator(
28
+ generator: ValidatedUuidV7Generator,
29
+ options: Pick<UuidV7ValueOptionValues, "at">,
30
+ maskingCodec?: UuidV7MaskingCodec,
31
+ ): Uuid<7, boolean, true> | UuidSlugError {
32
+ const generated = generateUuidV7BytesWithGenerator(generator, options);
33
+ if (isUuidSlugError(generated)) return generated;
34
+ return createUuidValue<7, boolean, true>(generated, maskingCodec, generator.payloadLayout);
35
+ }
36
+
37
+ /** Narrow an untrusted masking codec without relying on package-copy identity. */
38
+ export function readUuidV7MaskingCodec(
39
+ value: unknown,
40
+ ): UuidV7MaskingCodec | UuidSlugError | undefined {
41
+ if (value === undefined) return undefined;
42
+ try {
43
+ if (
44
+ value !== null &&
45
+ typeof value === "object" &&
46
+ typeof (value as { readonly uuidToMaskedSlug?: unknown }).uuidToMaskedSlug === "function"
47
+ )
48
+ return value as UuidV7MaskingCodec;
49
+ } catch (cause) {
50
+ return new UuidSlugError(INVALID_OPTIONS, "Reading UUIDv7 masking codec failed.", { cause });
51
+ }
52
+ return new UuidSlugError(INVALID_OPTIONS, "maskingCodec must be a UUIDv7 masking codec.");
53
+ }
54
+
55
+ /** Read untrusted value-generation options once and reject every unsupported key. */
56
+ export function readUuidV7ValueOptions(
57
+ options: unknown,
58
+ accepted: Readonly<Partial<Record<keyof UuidV7ValueOptionValues, true>>>,
59
+ ): UuidV7ValueOptionValues | UuidSlugError {
60
+ if (options === undefined) return {};
61
+ return readGenerationOptions(options, accepted, "UUIDv7 value generation");
62
+ }
@@ -0,0 +1,54 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type { Uuid, UuidV7MaskingCodec, UuidV7ValueOptions } from "./types.ts";
4
+ import { UuidSlugError } from "./errors.ts";
5
+ import { createUuidValue } from "./uuid-value.ts";
6
+ import { currentUuidV7Bytes, uuidV7BytesAt, uuidV7DefaultPayloadLayout } from "./v7-keyless.ts";
7
+ import {
8
+ generateUuidV7ValueWithGenerator,
9
+ readUuidV7MaskingCodec,
10
+ readUuidV7ValueOptions,
11
+ } from "./v7-value-options.ts";
12
+ import { readUuidV7Generator } from "./v7-generator-input.ts";
13
+
14
+ const UUID_V7_VALUE_OPTIONS = {
15
+ at: true,
16
+ generator: true,
17
+ maskingCodec: true,
18
+ } as const satisfies Record<keyof UuidV7ValueOptions, true>;
19
+
20
+ /**
21
+ * Generate an immutable UUIDv7 for the current clock reading with the module payload layout.
22
+ *
23
+ * @throws `UuidSlugError` with code `rng_unavailable` when generation cannot obtain
24
+ * secure randomness.
25
+ */
26
+ export function generateUuidV7Value(options?: undefined): Uuid<7, false, true>;
27
+ /**
28
+ * Generate an immutable UUIDv7 with optional time, generator, and retained masking codec.
29
+ * Only a supplied codec is retained; an undefined options branch uses default generation.
30
+ * @throws `UuidSlugError` with code `rng_unavailable` if options are undefined and secure randomness is unavailable.
31
+ */
32
+ export function generateUuidV7Value<const Options extends UuidV7ValueOptions | undefined = {}>(
33
+ options: Options,
34
+ ):
35
+ | Uuid<7, Options extends { readonly maskingCodec: UuidV7MaskingCodec } ? true : false, true>
36
+ | UuidSlugError;
37
+ export function generateUuidV7Value(
38
+ options?: UuidV7ValueOptions,
39
+ ): Uuid<7, boolean, true> | UuidSlugError {
40
+ const values = readUuidV7ValueOptions(options, UUID_V7_VALUE_OPTIONS);
41
+ if (values instanceof Error) return values;
42
+ const generator = readUuidV7Generator(values.generator);
43
+ if (generator instanceof Error) return generator;
44
+ const maskingCodec = readUuidV7MaskingCodec(values.maskingCodec);
45
+ if (maskingCodec instanceof Error) return maskingCodec;
46
+ if (generator) return generateUuidV7ValueWithGenerator(generator, values, maskingCodec);
47
+ const generated = !Object.hasOwn(values, "at") ? currentUuidV7Bytes() : uuidV7BytesAt(values.at);
48
+ if (generated instanceof Error) {
49
+ // Without options nothing the caller supplied can fail, so a failed draw is thrown.
50
+ if (options === undefined) throw generated;
51
+ return generated;
52
+ }
53
+ return createUuidValue<7, boolean, true>(generated, maskingCodec, uuidV7DefaultPayloadLayout());
54
+ }