@anizoptera/uuid-slug 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1052 -261
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +14 -9
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
package/dist/node/uuid.js DELETED
@@ -1,226 +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, checkRange } from "./errors.js";
4
- import { BASE32HEX, BASE64URL, decodeInto, encode, isEncoded } from "./alphabet.js";
5
- //#region src/uuid.ts
6
- const HEX = "0123456789abcdef";
7
- const nativeToHex = Uint8Array.prototype.toHex;
8
- const HEX_BYTES = nativeToHex ? [] : /*#__PURE__*/ Array.from({ length: 256 }, (_, byte) => HEX[byte >>> 4] + HEX[byte & 15]);
9
- const HEX_DECODE = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
10
- for (let i = 0; i < 10; i += 1) HEX_DECODE[48 + i] = i;
11
- for (let i = 0; i < 6; i += 1) HEX_DECODE[97 + i] = 10 + i;
12
- const UUID_LENGTH = 36;
13
- const UUID_BYTE_OFFSETS = [
14
- 0,
15
- 2,
16
- 4,
17
- 6,
18
- 9,
19
- 11,
20
- 14,
21
- 16,
22
- 19,
23
- 21,
24
- 24,
25
- 26,
26
- 28,
27
- 30,
28
- 32,
29
- 34
30
- ];
31
- /**
32
- * The alphabets a plain slug may be written in. base64url is the default and the shortest;
33
- * base32hex costs four more characters and buys the one property base64url cannot offer: its
34
- * characters are in ASCII order, so base32hex slugs of UUIDv7s sort chronologically as plain
35
- * strings. Only the lowercase spelling decodes — the table is built from `chars` — so slugs have
36
- * no second spelling, as everywhere else in this format.
37
- *
38
- * MASKED slugs are always base64url (Art's ruling, 2026-08-12). Sort order there would be order of
39
- * ciphertext, which carries nothing, so the extra characters would buy only the case-insensitivity.
40
- */
41
- const SLUG_ALPHABETS = {
42
- base32hex: BASE32HEX,
43
- base64url: BASE64URL
44
- };
45
- /** Reject inherited property names as well as unknown names from JavaScript callers. */
46
- function resolveSlugAlphabet(alphabet) {
47
- return Object.hasOwn(SLUG_ALPHABETS, alphabet) ? SLUG_ALPHABETS[alphabet] : new UuidSlugError("invalid_uuid_slug", `Unknown slug alphabet "${alphabet}"; expected ${Object.keys(SLUG_ALPHABETS).join(" or ")}.`);
48
- }
49
- /** Characters needed for 16 bytes: 22 in base64url, 26 in base32hex. */
50
- function slugLength(alpha) {
51
- return Math.ceil(128 / alpha.bitsPerChar);
52
- }
53
- /**
54
- * Length -> alphabet, which is why decoding takes no alphabet argument: the two lengths are
55
- * disjoint, so a slug names its own encoding and a caller cannot pick the wrong one. Indexed
56
- * rather than searched because every decode and every type guard pays this lookup.
57
- */
58
- const SLUG_ALPHABET_BY_LENGTH = Object.values(SLUG_ALPHABETS).reduce((table, alpha) => {
59
- table[slugLength(alpha)] = alpha;
60
- return table;
61
- }, []);
62
- const SLUG_LENGTHS = Object.values(SLUG_ALPHABETS).map((alpha) => `${slugLength(alpha)} (${alpha.name})`).join(" or ");
63
- function hexValue(code) {
64
- return HEX_DECODE[code] ?? -1;
65
- }
66
- function parseUuid(uuid, out, offset = 0) {
67
- if (uuid.length !== UUID_LENGTH) return new UuidSlugError("invalid_uuid", "UUID must be 36 characters.");
68
- if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") return new UuidSlugError("invalid_uuid", "UUID hyphen positions are invalid.");
69
- const target = out ?? /* @__PURE__ */ new Uint8Array(16);
70
- const badRange = checkRange(target.length, offset, 16);
71
- if (badRange) return badRange;
72
- for (let byteIndex = 0; byteIndex < UUID_BYTE_OFFSETS.length; byteIndex += 1) {
73
- const textOffset = UUID_BYTE_OFFSETS[byteIndex];
74
- const high = hexValue(uuid.charCodeAt(textOffset));
75
- const low = hexValue(uuid.charCodeAt(textOffset + 1));
76
- if (high < 0 || low < 0) return new UuidSlugError("invalid_uuid", `Invalid UUID hex at offset ${textOffset}.`);
77
- target[offset + byteIndex] = high << 4 | low;
78
- }
79
- return target;
80
- }
81
- function formatUuid(bytes, offset = 0) {
82
- const badRange = checkRange(bytes.length, offset, 16);
83
- if (badRange) return badRange;
84
- if (nativeToHex) {
85
- const hex = nativeToHex.call(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16));
86
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
87
- }
88
- let out = "";
89
- for (let i = 0; i < 16; i += 1) {
90
- if (i === 4 || i === 6 || i === 8 || i === 10) out += "-";
91
- const byte = bytes[offset + i] ?? 0;
92
- out += HEX_BYTES[byte];
93
- }
94
- return out;
95
- }
96
- function uuidVersion(bytes, offset = 0) {
97
- return (bytes[offset + 6] ?? 0) >>> 4;
98
- }
99
- function isRfcVariant(bytes, offset = 0) {
100
- return (bytes[offset + 8] ?? 0) >>> 6 === 2;
101
- }
102
- function isUuidString(uuid) {
103
- if (!uuid || uuid.length !== UUID_LENGTH) return false;
104
- if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") return false;
105
- for (let i = 0; i < UUID_BYTE_OFFSETS.length; i += 1) {
106
- const offset = UUID_BYTE_OFFSETS[i];
107
- if (hexValue(uuid.charCodeAt(offset)) < 0 || hexValue(uuid.charCodeAt(offset + 1)) < 0) return false;
108
- }
109
- return true;
110
- }
111
- /** The string has already passed canonical validation, so the variant digit is a known hex value. */
112
- function stringHasRfcVariant(uuid) {
113
- return HEX_DECODE[uuid.charCodeAt(19)] >>> 2 === 2;
114
- }
115
- function isUuidV4String(uuid) {
116
- return isUuidString(uuid) && uuid[14] === "4" && stringHasRfcVariant(uuid);
117
- }
118
- function isUuidV7String(uuid) {
119
- return isUuidString(uuid) && uuid[14] === "7" && stringHasRfcVariant(uuid);
120
- }
121
- /**
122
- * The only BYTE-level predicate, and the asymmetry against `isUuidV4String` is deliberate: masking
123
- * accepts v7 alone, so a caller holding raw bytes has a reason to ask this and none to ask the v4
124
- * question. `isUuidV4Bytes` is absent because nothing needs it, not because it was overlooked —
125
- * add it when a caller appears, never for symmetry, since an export is permanent surface.
126
- */
127
- function isUuidV7Bytes(bytes) {
128
- return bytes.length === 16 && uuidVersion(bytes) === 7 && isRfcVariant(bytes);
129
- }
130
- function formatUuidSlug(bytes, offset = 0, alphabet = "base64url") {
131
- const badRange = checkRange(bytes.length, offset, 16);
132
- if (badRange) return badRange;
133
- const alpha = resolveSlugAlphabet(alphabet);
134
- if (alpha instanceof Error) return alpha;
135
- return encode(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16), alpha);
136
- }
137
- /** Accepts either alphabet; the length says which, so there is nothing to pass and nothing to get wrong. */
138
- function parseUuidSlug(slug, out, offset = 0) {
139
- const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
140
- if (!alpha) return new UuidSlugError("invalid_uuid_slug", `UUID slug must be ${SLUG_LENGTHS} characters, got ${slug.length}.`);
141
- const target = out ?? /* @__PURE__ */ new Uint8Array(16);
142
- const result = decodeInto(slug, alpha, target, offset, 16);
143
- return result instanceof Error ? result : target;
144
- }
145
- function uuidToSlug(uuid, alphabet = "base64url") {
146
- const bytes = parseUuid(uuid);
147
- if (bytes instanceof Error) return bytes;
148
- return formatUuidSlug(bytes, 0, alphabet);
149
- }
150
- function slugToUuid(slug) {
151
- const bytes = parseUuidSlug(slug);
152
- if (bytes instanceof Error) return bytes;
153
- return formatUuid(bytes);
154
- }
155
- function isUuidSlug(slug) {
156
- if (!slug) return false;
157
- const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
158
- return alpha !== void 0 && isEncoded(slug, alpha, 16);
159
- }
160
- /** Read only the version/variant bytes after canonical validation, without decoding a whole UUID. */
161
- function slugByte(slug, alpha, offset) {
162
- const start = Math.floor(offset * 8 / alpha.bitsPerChar);
163
- const end = Math.floor((offset * 8 + 7) / alpha.bitsPerChar);
164
- let value = 0;
165
- for (let i = start; i <= end; i += 1) value = value << alpha.bitsPerChar | alpha.decode[slug.charCodeAt(i)];
166
- return value >>> (end + 1) * alpha.bitsPerChar - (offset + 1) * 8 & 255;
167
- }
168
- function isVersionedSlug(slug, version) {
169
- if (!isUuidSlug(slug)) return false;
170
- const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
171
- return slugByte(slug, alpha, 6) >>> 4 === version && slugByte(slug, alpha, 8) >>> 6 === 2;
172
- }
173
- function isUuidV4Slug(slug) {
174
- return isVersionedSlug(slug, 4);
175
- }
176
- function isUuidV7Slug(slug) {
177
- return isVersionedSlug(slug, 7);
178
- }
179
- /**
180
- * The 48-bit millisecond a UUIDv7 was minted at.
181
- *
182
- * It REFUSES anything that is not a v7, which is the whole point of the return type: the first six
183
- * bytes of a v4 are random, so reading them yields a confident, well-formed date drawn uniformly
184
- * from the next nine thousand years. A caller that passed the wrong version got that date silently,
185
- * and a freshness check built on it would accept or reject by coin flip while looking correct.
186
- *
187
- * Short input is reported separately from wrong version, because `uuidVersion` reads a missing byte
188
- * as zero and would otherwise blame a truncated buffer for holding a v0.
189
- */
190
- function extractUuidV7Timestamp(bytes, offset = 0) {
191
- const badRange = checkRange(bytes.length, offset, 16);
192
- if (badRange) return badRange;
193
- if (uuidVersion(bytes, offset) !== 7 || !isRfcVariant(bytes, offset)) return new UuidSlugError("invalid_uuid_version", "Timestamp is only defined for UUIDv7.");
194
- let timestamp = 0;
195
- for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[offset + i] ?? 0);
196
- return timestamp;
197
- }
198
- /**
199
- * Whether a v7's 74 random bits are anything other than all-zero or all-one — the two patterns a
200
- * generator produces when its entropy source is absent rather than working.
201
- *
202
- * Out of range answers `false`, and the direction is the whole point. Without the check the reads
203
- * below fall through `?? 0`, so a missing byte is indistinguishable from a zero byte and only ever
204
- * in the reassuring direction: a short buffer reported entropy PRESENT, and an offset past the end
205
- * reported the degenerate case for data that was never examined. Both are answers about bytes the
206
- * caller does not have. `false` is the honest one — it means "cannot be shown to carry entropy",
207
- * which is what a caller acts on, and it is what a truly degenerate id gets too.
208
- *
209
- * Boolean rather than `UuidSlugError | boolean` because the sole use is a guard in a condition; an error
210
- * return would have every call site unwrap a value it is already treating as a yes/no.
211
- */
212
- function hasUuidV7Entropy(bytes, offset = 0) {
213
- if (checkRange(bytes.length, offset, 16)) return false;
214
- const randA = ((bytes[offset + 6] ?? 0) & 15) << 8 | (bytes[offset + 7] ?? 0);
215
- const randBFirst = (bytes[offset + 8] ?? 0) & 63;
216
- let restZero = true;
217
- let restMax = true;
218
- for (let i = 9; i < 16; i += 1) {
219
- const byte = bytes[offset + i] ?? 0;
220
- if (byte !== 0) restZero = false;
221
- if (byte !== 255) restMax = false;
222
- }
223
- return !(randA === 0 && randBFirst === 0 && restZero) && !(randA === 4095 && randBFirst === 63 && restMax);
224
- }
225
- //#endregion
226
- export { extractUuidV7Timestamp, formatUuid, formatUuidSlug, hasUuidV7Entropy, isRfcVariant, isUuidSlug, isUuidString, isUuidV4Slug, isUuidV4String, isUuidV7Bytes, isUuidV7Slug, isUuidV7String, parseUuid, parseUuidSlug, resolveSlugAlphabet, slugToUuid, uuidToSlug, uuidVersion };
package/dist/node/v7.js DELETED
@@ -1,185 +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, checkRange, fillRandomBytes, readClock } from "./errors.js";
4
- import { formatUuid } from "./uuid.js";
5
- //#region src/v7.ts
6
- function writeTimestamp(bytes, ms, offset) {
7
- let value = Math.trunc(ms);
8
- for (let i = 5; i >= 0; i -= 1) {
9
- bytes[offset + i] = value & 255;
10
- value = Math.floor(value / 256);
11
- }
12
- }
13
- /**
14
- * Writes the 42-bit sequence RFC 9562 §6.2 allows in `rand_a` plus the top of `rand_b`, along
15
- * with the version and variant bits that bracket it.
16
- *
17
- * The sequence is carried as a 10-bit high half and a 32-bit low half rather than one 42-bit
18
- * BigInt, so every operation here is a 32-bit integer op the JIT emits directly. Measured on the
19
- * increment-and-write step alone: 9.99M ops/s (Bun) and 11.8M (Node) as a BigInt, against 252M
20
- * and 149M in this form. The bit layout is unchanged, so the ids are identical either way.
21
- */
22
- function writeCounter(bytes, hi, lo, offset) {
23
- bytes[offset + 6] = 112 | hi >>> 6 & 15;
24
- bytes[offset + 7] = ((hi & 63) << 2 | lo >>> 30) & 255;
25
- bytes[offset + 8] = 128 | lo >>> 24 & 63;
26
- bytes[offset + 9] = lo >>> 16 & 255;
27
- bytes[offset + 10] = lo >>> 8 & 255;
28
- bytes[offset + 11] = lo & 255;
29
- }
30
- /** The 48 bits RFC 9562 gives the timestamp; beyond it the value cannot be represented. */
31
- const MAX_TIMESTAMP = 0xffffffffffff;
32
- /**
33
- * `Number.isInteger` rather than `isFinite`, because the error message promises a WHOLE number of
34
- * milliseconds and `Math.trunc` on the write path would otherwise honour that promise silently:
35
- * 1.5 became 1 with nothing reported. It also rejects NaN and Infinity, which matters because a
36
- * native generator need not — measured 2026-08-12, `Bun.randomUUIDv7("hex", NaN)` and the same
37
- * call at 2^48 both return the 1970 prefix `000000000000` without throwing, while -1 and 1.5 do
38
- * throw. Validating here rather than trusting the platform is what makes the two agree.
39
- */
40
- const isValidUuidV7Timestamp = (ms) => Number.isInteger(ms) && ms >= 0 && ms <= MAX_TIMESTAMP;
41
- /**
42
- * The one check and the one message for a caller-supplied instant. Both the portable generator and
43
- * the runtime-backed one call it, and the runtime-backed one calls it BEFORE delegating: a native
44
- * generator may accept what we reject and answer wrongly rather than fail.
45
- */
46
- const rejectInstant = (ms) => isValidUuidV7Timestamp(ms) ? void 0 : new UuidSlugError("invalid_timestamp", `UUIDv7 timestamp must be a whole number of milliseconds in 0..${MAX_TIMESTAMP}.`);
47
- /**
48
- * Both string forms differ only in where the instant comes from, so the byte-or-error result is
49
- * carried through here rather than unwrapped twice. The narrowing is an assertion because
50
- * `formatUuid` is version-agnostic: the v7-ness is established by the caller having produced the
51
- * bytes, not by anything the formatter can check.
52
- */
53
- const formatUuidV7 = (result) => result instanceof Error ? result : formatUuid(result);
54
- /**
55
- * Seeds the sequence from the same six random bytes and the same bit positions as before, split
56
- * across the two halves: byte 0 and the top 2 bits of byte 1 form the high half, the rest the
57
- * low half. Starting each millisecond at a random point rather than zero is what stops the
58
- * sequence leaking how many ids were issued in the previous millisecond.
59
- */
60
- const seedHi = (bytes) => ((bytes[0] ?? 0) << 2 | (bytes[1] ?? 0) >>> 6) & 1023;
61
- const seedLo = (bytes) => (((bytes[1] ?? 0) & 63) << 26 | (bytes[2] ?? 0) << 18 | (bytes[3] ?? 0) << 10 | (bytes[4] ?? 0) << 2 | (bytes[5] ?? 0) & 3) >>> 0;
62
- function createUuidV7Generator(options) {
63
- const clock = options.clock ?? Date.now;
64
- const fill = options.fillRandom;
65
- const random = /* @__PURE__ */ new Uint8Array(16);
66
- /**
67
- * Below every timestamp the clock check admits, which is what makes it the uninitialised
68
- * sentinel rather than a value: `now > lastMs` alone therefore takes the reseed branch on the
69
- * first call, and no separate "have we started" flag is needed. The coupling is deliberate and
70
- * is why the clock is validated before this is compared against — an unvalidated clock returning
71
- * a negative millisecond would make `lastMs` stay below it forever, so the monotonic counter
72
- * would never be used and every call would reseed.
73
- */
74
- let lastMs = -1;
75
- let counterHi = 0;
76
- let counterLo = 0;
77
- function reseed(ms) {
78
- const failed = fillRandomBytes(fill, random);
79
- if (failed) return failed;
80
- lastMs = ms;
81
- counterHi = seedHi(random);
82
- counterLo = seedLo(random);
83
- }
84
- function bytes(out, offset = 0, timestamp, explicit = false) {
85
- const target = out ?? /* @__PURE__ */ new Uint8Array(16);
86
- const badRange = checkRange(target.length, offset, 16);
87
- if (badRange) return badRange;
88
- let ms;
89
- let sequenceHi;
90
- let sequenceLo;
91
- if (explicit) {
92
- const invalid = rejectInstant(timestamp);
93
- if (invalid) return invalid;
94
- const failed = fillRandomBytes(fill, random);
95
- if (failed) return failed;
96
- ms = timestamp;
97
- sequenceHi = seedHi(random);
98
- sequenceLo = seedLo(random);
99
- } else {
100
- const reading = readClock(clock);
101
- if (reading instanceof Error) return reading;
102
- const now = Math.trunc(reading);
103
- if (reading < 0 || !isValidUuidV7Timestamp(now)) return new UuidSlugError("invalid_timestamp", `Clock returned ${String(reading)}, which is not a millisecond in 0..${MAX_TIMESTAMP}.`);
104
- if (now > lastMs) {
105
- const failed = reseed(now);
106
- if (failed) return failed;
107
- } else {
108
- counterLo = counterLo + 1 >>> 0;
109
- if (counterLo === 0) counterHi += 1;
110
- if (counterHi > 1023) {
111
- if (lastMs >= MAX_TIMESTAMP) return new UuidSlugError("invalid_timestamp", `Sequence exhausted at the last representable millisecond (${MAX_TIMESTAMP}).`);
112
- const failed = reseed(lastMs + 1);
113
- if (failed) return failed;
114
- } else {
115
- const failed = fillRandomBytes(fill, random);
116
- if (failed) return failed;
117
- }
118
- }
119
- ms = lastMs;
120
- sequenceHi = counterHi;
121
- sequenceLo = counterLo;
122
- }
123
- writeTimestamp(target, ms, offset);
124
- writeCounter(target, sequenceHi, sequenceLo, offset);
125
- for (let i = 12; i < 16; i += 1) target[offset + i] = random[i];
126
- return target;
127
- }
128
- return {
129
- uuidV7() {
130
- const formatted = formatUuidV7(bytes());
131
- if (formatted instanceof Error) throw formatted;
132
- return formatted;
133
- },
134
- uuidV7At: (timestamp) => formatUuidV7(bytes(void 0, 0, timestamp, true)),
135
- uuidV7Bytes: (out, offset) => bytes(out, offset),
136
- uuidV7BytesAt: (timestamp, out, offset) => bytes(out, offset, timestamp, true)
137
- };
138
- }
139
- function createRuntimeGenerator(runtime) {
140
- const fallback = createUuidV7Generator({ fillRandom: runtime.fillRandom });
141
- return {
142
- uuidV7() {
143
- if (!runtime.uuidV7) return fallback.uuidV7();
144
- try {
145
- return runtime.uuidV7();
146
- } catch {
147
- return fallback.uuidV7();
148
- }
149
- },
150
- uuidV7Bytes(out, offset = 0) {
151
- if (!runtime.uuidV7Bytes) return fallback.uuidV7Bytes(out, offset);
152
- const badRange = checkRange(out?.length ?? 16, offset, 16);
153
- if (badRange) return badRange;
154
- try {
155
- return runtime.uuidV7Bytes(out, offset);
156
- } catch (cause) {
157
- return new UuidSlugError("rng_unavailable", "Runtime UUIDv7 byte generation failed.", { cause });
158
- }
159
- },
160
- uuidV7At(timestamp) {
161
- if (!runtime.uuidV7At) return fallback.uuidV7At(timestamp);
162
- const invalid = rejectInstant(timestamp);
163
- if (invalid) return invalid;
164
- try {
165
- return runtime.uuidV7At(timestamp);
166
- } catch {
167
- return fallback.uuidV7At(timestamp);
168
- }
169
- },
170
- uuidV7BytesAt(timestamp, out, offset = 0) {
171
- if (!runtime.uuidV7BytesAt) return fallback.uuidV7BytesAt(timestamp, out, offset);
172
- const invalid = rejectInstant(timestamp);
173
- if (invalid) return invalid;
174
- const badRange = checkRange(out?.length ?? 16, offset, 16);
175
- if (badRange) return badRange;
176
- try {
177
- return runtime.uuidV7BytesAt(timestamp, out, offset);
178
- } catch (cause) {
179
- return new UuidSlugError("rng_unavailable", "Runtime UUIDv7 byte generation failed.", { cause });
180
- }
181
- }
182
- };
183
- }
184
- //#endregion
185
- export { createRuntimeGenerator, createUuidV7Generator };
@@ -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
- //#region src/yield.ts
4
- const host = globalThis;
5
- const immediate = host.setImmediate?.bind(host);
6
- /** Yield to a host task so timers, input and cancellation can run; a microtask would starve them. */
7
- function yieldToHost() {
8
- if (immediate) return new Promise((resolve) => immediate(resolve));
9
- return new Promise((resolve) => {
10
- const channel = new MessageChannel();
11
- channel.port1.onmessage = () => {
12
- channel.port1.close();
13
- channel.port2.close();
14
- resolve();
15
- };
16
- channel.port2.postMessage(null);
17
- });
18
- }
19
- //#endregion
20
- export { yieldToHost };
@@ -1,39 +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 { UuidRuntimeError } from "../errors.js";
4
- import { pooledFill } from "./pool.js";
5
- //#region src/runtime/web.ts
6
- /**
7
- * Resolve Web Crypto per draw so instrumentation installed after import can observe the source.
8
- * Binding it at module load would bypass `test/instrument.ts` and hide those calls from the gate.
9
- */
10
- function cryptoObject() {
11
- const value = globalThis.crypto;
12
- if (!value?.getRandomValues) throw new UuidRuntimeError("Web Crypto getRandomValues is unavailable.");
13
- return value;
14
- }
15
- const runtimeCapabilities = {
16
- /**
17
- * Pooled for the same reason as Node's: `getRandomValues` costs far more per call than per
18
- * byte, and a v7 id needs 16. Bun draws this path too, where pooling measured 16x.
19
- */
20
- fillRandom: pooledFill((into) => {
21
- cryptoObject().getRandomValues(into);
22
- }) };
23
- /**
24
- * `randomUUID` is probed ONCE here and the method left undefined when it is absent — the rule
25
- * `runtime/node.ts` already follows and the reason `Runtime`'s methods are optional.
26
- *
27
- * It is not the same capability as `getRandomValues`, and a browser can have one without the
28
- * other: `crypto.randomUUID` is restricted to secure contexts, `getRandomValues` is not. Defined
29
- * unconditionally with a throw inside, `uuidV4()` was the only one of four entry points that
30
- * failed on such a page — `uuidV4Slug`, `uuidV4Bytes` and `uuidV7` all answered, because they
31
- * reach the byte generator rather than this method. Leaving it undefined routes `uuidV4` to that
32
- * same generator, so the four agree.
33
- */
34
- if (globalThis.crypto?.randomUUID) runtimeCapabilities.uuidV4 = () => cryptoObject().randomUUID();
35
- const runtime = runtimeCapabilities;
36
- //#endregion
37
- export { runtime };
38
-
39
- //# sourceMappingURL=web.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"web.js","names":[],"sources":["../../src/runtime/web.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { UuidRuntimeError } from \"../errors\";\nimport { pooledFill } from \"./pool\";\nimport type { Runtime } from \"./types\";\n\n/**\n * Resolve Web Crypto per draw so instrumentation installed after import can observe the source.\n * Binding it at module load would bypass `test/instrument.ts` and hide those calls from the gate.\n */\nfunction cryptoObject(): Crypto {\n const value = globalThis.crypto;\n if (!value?.getRandomValues)\n throw new UuidRuntimeError(\"Web Crypto getRandomValues is unavailable.\");\n return value;\n}\n\nconst runtimeCapabilities: Runtime = {\n /**\n * Pooled for the same reason as Node's: `getRandomValues` costs far more per call than per\n * byte, and a v7 id needs 16. Bun draws this path too, where pooling measured 16x.\n */\n fillRandom: pooledFill((into) => {\n cryptoObject().getRandomValues(into);\n }),\n};\n\n/**\n * `randomUUID` is probed ONCE here and the method left undefined when it is absent — the rule\n * `runtime/node.ts` already follows and the reason `Runtime`'s methods are optional.\n *\n * It is not the same capability as `getRandomValues`, and a browser can have one without the\n * other: `crypto.randomUUID` is restricted to secure contexts, `getRandomValues` is not. Defined\n * unconditionally with a throw inside, `uuidV4()` was the only one of four entry points that\n * failed on such a page — `uuidV4Slug`, `uuidV4Bytes` and `uuidV7` all answered, because they\n * reach the byte generator rather than this method. Leaving it undefined routes `uuidV4` to that\n * same generator, so the four agree.\n */\n/*\n * Probed through `Partial<Crypto>` because the DOM lib declares `randomUUID` as always present,\n * so the plain condition is \"always true\" to the compiler (TS2774) while being false on any\n * insecure page. The cast states the divergence rather than suppressing it: the types describe a\n * secure context, the check describes every context.\n */\nif ((globalThis.crypto as Partial<Crypto> | undefined)?.randomUUID)\n runtimeCapabilities.uuidV4 = () => cryptoObject().randomUUID();\n\nexport const runtime: Runtime = runtimeCapabilities;\n"],"mappings":";;;;;;;;;AAUA,SAAS,eAAuB;CAC9B,MAAM,QAAQ,WAAW;CACzB,IAAI,CAAC,OAAO,iBACV,MAAM,IAAI,iBAAiB,4CAA4C;CACzE,OAAO;AACT;AAEA,MAAM,sBAA+B;;;;;AAKnC,YAAY,YAAY,SAAS;CAC/B,aAAa,CAAC,CAAC,gBAAgB,IAAI;AACrC,CAAC,EACH;;;;;;;;;;;;AAmBA,IAAK,WAAW,QAAwC,YACtD,oBAAoB,eAAe,aAAa,CAAC,CAAC,WAAW;AAE/D,MAAa,UAAmB"}
package/dist/schema.d.ts DELETED
@@ -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 { AsyncMaskSchemaOptions, MaskSchema, MaskSchemaOptions } from "./types.js";
5
- //#region src/schema.d.ts
6
- declare function createMaskSchema(options: MaskSchemaOptions): UuidSlugError | MaskSchema;
7
- /**
8
- * Derive the same schema while allowing other host tasks to run. Options and byte contents are
9
- * captured before suspension; cancellation returns an `aborted` error with the signal's reason
10
- * as its cause. Checkpoints stop computation rather than racing a still-running derivation.
11
- *
12
- * Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,
13
- * not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations
14
- * need no host yield. Passing the result as a codec's `mask` avoids deriving it again.
15
- */
16
- declare function createMaskSchemaAsync(options: AsyncMaskSchemaOptions): Promise<MaskSchema | UuidSlugError>;
17
- declare const DEFAULT_MASK_SCHEMA: MaskSchema;
18
- //#endregion
19
- export { DEFAULT_MASK_SCHEMA, createMaskSchema, createMaskSchemaAsync };
20
- //# sourceMappingURL=schema.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema.d.ts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;iBA2GgB,iBAAiB,SAAS,oBAAoB,gBAAgB;;;;;;;;;;iBA8GxD,sBACpB,SAAS,yBACR,QAAQ,aAAa;cAgFX,qBAAqB"}