@anizoptera/uuid-slug 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +373 -324
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +15 -8
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
@@ -0,0 +1,48 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { findUnknownOption, INVALID_OPTIONS, isPlainRecord, UuidSlugError } from "./errors.ts";
4
+
5
+ export interface GenerationOptionValues {
6
+ readonly alphabet?: unknown;
7
+ readonly at?: unknown;
8
+ readonly generator?: unknown;
9
+ readonly maskingCodec?: unknown;
10
+ readonly output?: unknown;
11
+ readonly outputOffset?: unknown;
12
+ readonly textCase?: unknown;
13
+ }
14
+
15
+ /** Read selected generation options once and reject every unsupported key. */
16
+ export function readGenerationOptions(
17
+ options: unknown,
18
+ accepted: Readonly<Partial<Record<keyof GenerationOptionValues, true>>>,
19
+ operation: string,
20
+ ): GenerationOptionValues | UuidSlugError {
21
+ if (options === null || typeof options !== "object")
22
+ return new UuidSlugError(INVALID_OPTIONS, `${operation} options must be a plain object.`);
23
+ try {
24
+ if (!isPlainRecord(options))
25
+ return new UuidSlugError(INVALID_OPTIONS, `${operation} options must be a plain object.`);
26
+ const unknown = findUnknownOption(options, accepted);
27
+ if (unknown !== undefined)
28
+ return new UuidSlugError(INVALID_OPTIONS, `Unknown ${operation} option: ${unknown}.`);
29
+ const source = options as GenerationOptionValues;
30
+ // Direct assignments build one object; a conditional spread per option allocated a temporary
31
+ // object for each (bench/decisions.md). Each accepted own property is read once, in this
32
+ // order. Callers resolve `alphabet` and `textCase`, which also unwraps `String` objects.
33
+ const values: { -readonly [Key in keyof GenerationOptionValues]: unknown } = {};
34
+ if (accepted.alphabet && Object.hasOwn(source, "alphabet")) values.alphabet = source.alphabet;
35
+ if (accepted.at && Object.hasOwn(source, "at")) values.at = source.at;
36
+ if (accepted.generator && Object.hasOwn(source, "generator"))
37
+ values.generator = source.generator;
38
+ if (accepted.maskingCodec && Object.hasOwn(source, "maskingCodec"))
39
+ values.maskingCodec = source.maskingCodec;
40
+ if (accepted.output && Object.hasOwn(source, "output")) values.output = source.output;
41
+ if (accepted.outputOffset && Object.hasOwn(source, "outputOffset"))
42
+ values.outputOffset = source.outputOffset;
43
+ if (accepted.textCase && Object.hasOwn(source, "textCase")) values.textCase = source.textCase;
44
+ return values;
45
+ } catch (cause) {
46
+ return new UuidSlugError(INVALID_OPTIONS, `Reading ${operation} options failed.`, { cause });
47
+ }
48
+ }
package/src/index.ts CHANGED
@@ -1,100 +1,154 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- export { decodeBase64Url, encodeBase64Url, isBase64Url } from "./base64url";
3
+ export { createUuidV7MaskingCodec } from "./masking-codec.ts";
4
+ export { MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS } from "./payload.ts";
5
+ export { validateUuidV7StringUnixMs } from "./timestamp.ts";
4
6
  export {
5
- UUID_V7_SENTINEL_DEFINITIONS,
6
- createUuidSlugCodec,
7
- defaultCodec,
8
- validateUuidV7Fresh,
9
- validateUuidV7SlugFresh,
10
- } from "./codec";
11
- export { UUID_SLUG_ERROR_CODES, UuidRuntimeError, UuidSlugError } from "./errors";
12
- /**
13
- * Exported because `UuidSlugError.code` is public and the README tells consumers to branch on it.
14
- * The type was emitted into the declarations and left out of the export list, so the property had
15
- * a type no consumer could name — a switch over it could not be written without restating the
16
- * literals by hand, which is exactly the duplication `UUID_SLUG_ERROR_CODES` exists to prevent.
17
- */
18
- export type { UuidSlugErrorCode } from "./errors";
19
- export { DEFAULT_MASK_SCHEMA, createMaskSchema, createMaskSchemaAsync } from "./schema";
7
+ ABORTED,
8
+ INVALID_BASE32HEX,
9
+ INVALID_BASE64URL,
10
+ INVALID_BUFFER,
11
+ INVALID_MASK,
12
+ INVALID_OPTIONS,
13
+ INVALID_SENTINEL,
14
+ INVALID_TIMESTAMP,
15
+ INVALID_UUID,
16
+ INVALID_UUID_SLUG,
17
+ INVALID_UUID_VERSION,
18
+ RNG_UNAVAILABLE,
19
+ TIMESTAMP_OUTSIDE_WINDOW,
20
+ UuidSlugError,
21
+ isUuidSlugError,
22
+ } from "./errors.ts";
23
+ export { BASE32HEX_NAME as BASE32HEX, BASE64URL_NAME as BASE64URL } from "./alphabet.ts";
24
+ /** Export the code type so consumers can write exhaustive handlers without copying its literals. */
25
+ export type { UuidSlugErrorCode } from "./errors.ts";
26
+ export { UUID_V7_TEST_MASK, deriveUuidV7Mask, deriveUuidV7MaskAsync } from "./mask.ts";
27
+ export { createCustomUuidV7Mask } from "./mask-handle.ts";
28
+ export {
29
+ SEEDED_MASK_FORMAT,
30
+ PLAIN_SLUG_FORMAT,
31
+ FIXED_MASK_FORMAT,
32
+ UUID_TEXT_LOWERCASE,
33
+ UUID_TEXT_UPPERCASE,
34
+ UUID_V7_ROLLBACK_ERROR,
35
+ UUID_V7_ROLLBACK_PRESERVE,
36
+ UUID_V7_ROLLBACK_RESET,
37
+ UUID_VARIANT_NCS,
38
+ UUID_VARIANT_RFC,
39
+ UUID_VARIANT_MICROSOFT,
40
+ UUID_VARIANT_FUTURE,
41
+ } from "./types.ts";
20
42
  export type {
21
- AsyncMaskSchemaOptions,
22
- Base64UrlString,
23
- FreshValidationOptions,
24
- MaskSchema,
25
- MaskSchemaOptions,
26
- MigrationFormat,
27
- MaskedUuidSlug,
43
+ AsyncUuidV7MaskOptions,
44
+ CustomUuidV7MaskOptions,
45
+ GeneratedUuidV7,
46
+ GeneratePlainUuidV7SlugOptions,
47
+ GenerateUuidV7BytesIntoOptions,
48
+ GenerateUuidV7BytesOptions,
49
+ GenerateUuidV7Options,
50
+ GenerateUuidV7WithMaskedSlugOptions,
51
+ GenerateUuidV7WithPlainSlugOptions,
52
+ UuidV7TimestampWindow,
53
+ UuidV7Mask,
54
+ UuidV7MaskOptions,
55
+ UuidSlugMigrationFormat,
28
56
  MaskedUuidV7Slug,
29
- PublicUuidV7Slug,
57
+ MaskedOrSentinelUuidV7Slug,
30
58
  SentinelUuidV7Slug,
31
59
  UuidBytes,
32
- UuidSlug,
33
- UuidSlugCodec,
34
- UuidSlugCodecOptions,
35
- UuidSlugMigration,
60
+ UuidByteInput,
61
+ UuidInput,
62
+ UuidStringResult,
63
+ UuidBytesResult,
64
+ PlainUuidSlugResult,
65
+ UuidV4Bytes,
66
+ PlainUuidSlug,
67
+ UuidSlugMigrationDecoder,
36
68
  UuidSlugMigrationOptions,
37
69
  UuidString,
38
- UuidV4Slug,
70
+ UuidText,
71
+ UppercaseUuidString,
72
+ UppercaseUuidV4String,
73
+ UppercaseUuidV7String,
74
+ UuidStringFor,
75
+ UuidV4StringFor,
76
+ UuidV7StringFor,
77
+ UuidTextCase,
78
+ UuidVersion,
79
+ UuidVariant,
80
+ UuidInspection,
81
+ Uuid,
82
+ PlainUuidV4Slug,
39
83
  UuidV4String,
84
+ UuidV4Text,
40
85
  UuidV7Generator,
86
+ UuidV7Instant,
87
+ UuidV7GeneratorValueOptions,
88
+ UuidV7ValueOptions,
89
+ UuidV7ClockRollbackPolicy,
90
+ UuidRandomFill,
91
+ UuidV7MaskingCodec,
92
+ UuidV7MaskingCodecValueOptions,
93
+ UuidV7MaskingCodecOptions,
94
+ UuidV7PreviousMask,
95
+ UuidV7Bytes,
96
+ UuidV7Bounds,
97
+ UuidV7Payload,
98
+ UuidV7PayloadLayout,
41
99
  UuidV7Sentinel,
42
- UuidV7SentinelDefinition,
43
- UuidV7Slug,
100
+ UuidV7SentinelConfig,
101
+ PlainUuidV7Slug,
44
102
  UuidV7String,
45
- } from "./types";
103
+ UuidV7Text,
104
+ } from "./types.ts";
105
+ export { uuidV7StringBounds, uuidV7ByteBounds } from "./v7-bounds.ts";
46
106
  export {
47
- extractUuidV7Timestamp,
48
- formatUuid,
49
- formatUuidSlug,
50
- hasUuidV7Entropy,
51
- isUuidSlug,
52
- isUuidV4Slug,
107
+ MAX_UUID,
108
+ NIL_UUID,
109
+ bytesToUuidString,
110
+ isUuidBytes,
111
+ isUuidV4Bytes,
53
112
  isUuidV4String,
113
+ isUuidV4Text,
54
114
  isUuidV7Bytes,
55
- isUuidV7Slug,
56
115
  isUuidV7String,
116
+ isUuidV7Text,
57
117
  isUuidString,
58
- parseUuid,
59
- parseUuidSlug,
60
- slugToUuid,
61
- uuidToSlug,
62
- } from "./uuid";
63
- export type { SlugAlphabet } from "./uuid";
64
- /**
65
- * `createRuntimeGenerator` is NOT exported (Art's ruling, 2026-08-12), pending the whole-API-shape
66
- * review. It takes a `Runtime`, which is not exported either, so no consumer could construct an
67
- * argument for it — a public function nobody could call. The capability it provides is already
68
- * applied: every codec built without an explicit `generator` gets one.
69
- */
70
- export { createUuidV7Generator } from "./v7";
71
- export type { UuidV7GeneratorOptions } from "./v7";
118
+ isUuidText,
119
+ uuidStringToBytes,
120
+ } from "./uuid.ts";
121
+ export {
122
+ uuidBytesToPlainSlug,
123
+ extractUuidV7UnixMs,
124
+ extractUuidV7Payload,
125
+ extractUuidVersion,
126
+ isPlainUuidSlug,
127
+ isPlainUuidV4Slug,
128
+ isPlainUuidV7Slug,
129
+ plainSlugToUuidBytes,
130
+ plainSlugToUuidString,
131
+ uuidToString,
132
+ uuidToBytes,
133
+ uuidToPlainSlug,
134
+ uuidStringToPlainSlug,
135
+ validatePlainUuidV7SlugUnixMs,
136
+ } from "./slug.ts";
137
+ export { parseUuid } from "./uuid-value.ts";
138
+ export type { SlugAlphabet } from "./slug.ts";
139
+ export { createUuidV7Generator, createUuidV7GeneratorWithRandomFill } from "./v7-generator.ts";
140
+ export type { UuidV7GeneratorOptions } from "./v7-generator.ts";
72
141
 
73
- /*
74
- * The keyless shortcuts. They come from `keyless.ts`, which builds them from a bare generator and
75
- * never touches a codec — see that file for the measured cost of the alternative. They were once
76
- * bound here as `export const uuidV7 = defaultCodec.uuidV7`, and that spelling is the defect: a
77
- * property read at module scope evaluates the singleton, so every consumer of ANY export in this
78
- * barrel carried the cipher, the mask schema and the sentinel table whether or not it masked.
79
- *
80
- * The MASKED methods are deliberately absent, and must stay absent (Art's ruling, 2026-08-12).
81
- * Everything below is keyless — the same value whoever calls it — so a bare function is an honest
82
- * shape for it. Masking is keyed, and the only key a bare function could carry is `defaultCodec`'s,
83
- * which is derived from a seed published in this package's source. Exported that way, the
84
- * easiest-to-reach spelling of the headline feature was the one that obfuscates nothing, and a
85
- * README paragraph was the only thing standing between a caller and it.
86
- *
87
- * Reach masking through a codec you built with your own seed: `createUuidSlugCodec({ mask: {
88
- * seed } })`. Sentinels went with them for the same reason — a sentinel exists to be matched
89
- * against masked input, so a sentinel list has no meaning apart from the codec that masks.
90
- */
142
+ /* Keyless operations stay module-level and avoid codec setup. Masking and sentinels stay on the
143
+ * codec because their meaning depends on its seed and sentinel table. */
91
144
  export {
92
- uuidV4,
93
- uuidV4Bytes,
94
- uuidV4Slug,
95
- uuidV7,
96
- uuidV7At,
97
- uuidV7Bytes,
98
- uuidV7BytesAt,
99
- uuidV7Slug,
100
- } from "./keyless";
145
+ generateUuidV4,
146
+ generateUuidV4WithRandomFill,
147
+ generateUuidV4Bytes,
148
+ generatePlainUuidV4Slug,
149
+ generateUuidV7,
150
+ generateUuidV7Bytes,
151
+ generatePlainUuidV7Slug,
152
+ generateUuidV7WithPlainSlug,
153
+ } from "./keyless.ts";
154
+ export { generateUuidV7Value } from "./v7-value.ts";
package/src/instant.ts ADDED
@@ -0,0 +1,196 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { INVALID_TIMESTAMP, stringInput, UuidSlugError } from "./errors.ts";
4
+ import type { UuidV7Instant } from "./types.ts";
5
+ import { MAX_UUID_V7_UNIX_MS } from "./v7-timestamp.ts";
6
+
7
+ const INVALID_INSTANT =
8
+ "UUIDv7 instant must be a finite Unix-millisecond value, a valid Date, zoned ISO timestamp text, or a supported epoch timestamp object.";
9
+ const ZONED_TIMESTAMP =
10
+ /^([+-]\d{6}|\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/;
11
+ const MAX_UUID_V7_UNIX_MS_BIGINT = BigInt(MAX_UUID_V7_UNIX_MS);
12
+ const NANOS_PER_MILLISECOND = 1_000_000n;
13
+ const MAX_FRACTION_BITS = 12;
14
+ const FRACTION_BUCKETS = 2 ** MAX_FRACTION_BITS;
15
+ const DECIMAL_FRACTION_SCALE = 1_000_000_000_000;
16
+ const NEGATIVE_OFFSET_SIGN = "-";
17
+ const ZERO_DIGIT = "0";
18
+
19
+ /** The UUIDv7 millisecond field and the remaining fraction of that millisecond. */
20
+ export interface NormalizedUuidV7Instant {
21
+ readonly unixMs: number;
22
+ /** Exact bucket at the maximum UUIDv7 fraction width; narrower layouts use its leading bits. */
23
+ readonly fractionBucket12: number;
24
+ }
25
+
26
+ const invalidInstant = (cause?: unknown) =>
27
+ new UuidSlugError(
28
+ INVALID_TIMESTAMP,
29
+ INVALID_INSTANT,
30
+ cause === undefined ? undefined : { cause },
31
+ );
32
+
33
+ function readUnixMilliseconds(value: unknown): NormalizedUuidV7Instant | UuidSlugError {
34
+ if (typeof value === "number") {
35
+ if (!Number.isFinite(value) || value < 0 || value >= MAX_UUID_V7_UNIX_MS + 1)
36
+ return invalidInstant();
37
+ const unixMs = Math.floor(value);
38
+ return {
39
+ unixMs,
40
+ fractionBucket12: Math.min(
41
+ FRACTION_BUCKETS - 1,
42
+ Math.floor((value - unixMs) * FRACTION_BUCKETS),
43
+ ),
44
+ };
45
+ }
46
+ if (typeof value !== "bigint" || value < 0n || value > MAX_UUID_V7_UNIX_MS_BIGINT)
47
+ return invalidInstant();
48
+ return { unixMs: Number(value), fractionBucket12: 0 };
49
+ }
50
+
51
+ function readEpochNanoseconds(value: unknown): NormalizedUuidV7Instant | UuidSlugError {
52
+ if (typeof value !== "bigint" || value < 0n) return invalidInstant();
53
+ const unixMs = value / NANOS_PER_MILLISECOND;
54
+ if (unixMs > MAX_UUID_V7_UNIX_MS_BIGINT) return invalidInstant();
55
+ return {
56
+ unixMs: Number(unixMs),
57
+ fractionBucket12: Number(
58
+ ((value % NANOS_PER_MILLISECOND) * BigInt(FRACTION_BUCKETS)) / NANOS_PER_MILLISECOND,
59
+ ),
60
+ };
61
+ }
62
+
63
+ function readDecimalFraction(fractionDigits: string) {
64
+ const wholeMilliseconds = Number(fractionDigits.slice(0, 3).padEnd(3, ZERO_DIGIT));
65
+ // Every k / 4096 boundary terminates within twelve decimal places. Digits beyond this window
66
+ // can refine the source instant but cannot change its exact 12-bit UUID fraction bucket.
67
+ const subMillisecondDigits = fractionDigits.slice(3, 15).padEnd(12, ZERO_DIGIT);
68
+ const fractionBucket12 = Math.floor(
69
+ (Number(subMillisecondDigits) * FRACTION_BUCKETS) / DECIMAL_FRACTION_SCALE,
70
+ );
71
+ return { wholeMilliseconds, fractionBucket12 };
72
+ }
73
+
74
+ function readZonedTimestamp(instant: string): NormalizedUuidV7Instant | UuidSlugError {
75
+ const match = ZONED_TIMESTAMP.exec(instant);
76
+ if (match === null) return invalidInstant();
77
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number) as [
78
+ number,
79
+ number,
80
+ number,
81
+ number,
82
+ number,
83
+ number,
84
+ ];
85
+ const fractionDigits = match[7] ?? "";
86
+ const offsetSign = match[8];
87
+ const offsetHour = Number(match[9] ?? 0);
88
+ const offsetMinute = Number(match[10] ?? 0);
89
+ if (
90
+ month < 1 ||
91
+ month > 12 ||
92
+ day < 1 ||
93
+ hour > 23 ||
94
+ minute > 59 ||
95
+ second > 59 ||
96
+ offsetHour > 23 ||
97
+ offsetMinute > 59 ||
98
+ (offsetSign === NEGATIVE_OFFSET_SIGN && offsetHour === 0 && offsetMinute === 0)
99
+ )
100
+ return invalidInstant();
101
+
102
+ const local = new Date(0);
103
+ local.setUTCFullYear(year, month - 1, day);
104
+ local.setUTCHours(hour, minute, second, 0);
105
+ if (
106
+ local.getUTCFullYear() !== year ||
107
+ local.getUTCMonth() !== month - 1 ||
108
+ local.getUTCDate() !== day ||
109
+ local.getUTCHours() !== hour ||
110
+ local.getUTCMinutes() !== minute ||
111
+ local.getUTCSeconds() !== second
112
+ )
113
+ return invalidInstant();
114
+
115
+ const fraction = readDecimalFraction(fractionDigits);
116
+ const offset = (offsetHour * 60 + offsetMinute) * 60_000;
117
+ const unixMs =
118
+ local.getTime() +
119
+ fraction.wholeMilliseconds +
120
+ (offsetSign === "+" ? -offset : offsetSign === NEGATIVE_OFFSET_SIGN ? offset : 0);
121
+ if (unixMs < 0 || unixMs > MAX_UUID_V7_UNIX_MS) return invalidInstant();
122
+ return { unixMs, fractionBucket12: fraction.fractionBucket12 };
123
+ }
124
+
125
+ /** Read an explicit UUIDv7 instant once and retain the precision its source provides. */
126
+ export function readUuidV7Instant(instant: UuidV7Instant): NormalizedUuidV7Instant | UuidSlugError;
127
+ export function readUuidV7Instant(instant: unknown): NormalizedUuidV7Instant | UuidSlugError;
128
+ export function readUuidV7Instant(instant: unknown): NormalizedUuidV7Instant | UuidSlugError {
129
+ if (typeof instant === "number" || typeof instant === "bigint")
130
+ return readUnixMilliseconds(instant);
131
+ if (typeof instant === "string") return readZonedTimestamp(instant);
132
+ if (instant === null || typeof instant !== "object") return invalidInstant();
133
+
134
+ let dateCause: unknown;
135
+ try {
136
+ // The intrinsic brand check works across realms and runs before record access so attaching
137
+ // fields to a Date cannot change its meaning or invoke caller code only in another realm.
138
+ return readUnixMilliseconds(Date.prototype.getTime.call(instant));
139
+ } catch (cause) {
140
+ dateCause = cause;
141
+ }
142
+
143
+ const timestamp = stringInput(instant);
144
+ if (timestamp !== undefined) return readZonedTimestamp(timestamp);
145
+
146
+ try {
147
+ const source = instant as {
148
+ readonly epochMilliseconds?: unknown;
149
+ readonly epochNanoseconds?: unknown;
150
+ readonly seconds?: unknown;
151
+ readonly nanoseconds?: unknown;
152
+ };
153
+ const epochMilliseconds = source.epochMilliseconds;
154
+ const epochNanoseconds = source.epochNanoseconds;
155
+ const seconds = source.seconds;
156
+ const nanoseconds = source.nanoseconds;
157
+ if (
158
+ (seconds !== undefined || nanoseconds !== undefined) &&
159
+ (epochMilliseconds !== undefined || epochNanoseconds !== undefined)
160
+ )
161
+ return invalidInstant();
162
+ if (epochNanoseconds !== undefined) {
163
+ const normalized = readEpochNanoseconds(epochNanoseconds);
164
+ if (normalized instanceof Error || epochMilliseconds === undefined) return normalized;
165
+ const stated = readUnixMilliseconds(epochMilliseconds);
166
+ return stated instanceof Error ||
167
+ stated.unixMs !== normalized.unixMs ||
168
+ (stated.fractionBucket12 !== normalized.fractionBucket12 &&
169
+ (stated.fractionBucket12 !== 0 ||
170
+ (typeof epochMilliseconds === "number" && !Number.isInteger(epochMilliseconds))))
171
+ ? invalidInstant()
172
+ : normalized;
173
+ }
174
+
175
+ if (epochMilliseconds !== undefined) return readUnixMilliseconds(epochMilliseconds);
176
+
177
+ if (seconds !== undefined) {
178
+ const resolvedNanoseconds = nanoseconds ?? 0;
179
+ if (
180
+ (typeof seconds !== "bigint" &&
181
+ (typeof seconds !== "number" || !Number.isSafeInteger(seconds))) ||
182
+ (typeof resolvedNanoseconds !== "bigint" &&
183
+ (typeof resolvedNanoseconds !== "number" ||
184
+ !Number.isSafeInteger(resolvedNanoseconds))) ||
185
+ resolvedNanoseconds < 0 ||
186
+ resolvedNanoseconds > 999_999_999
187
+ )
188
+ return invalidInstant();
189
+ return readEpochNanoseconds(BigInt(seconds) * 1_000_000_000n + BigInt(resolvedNanoseconds));
190
+ }
191
+ } catch (cause) {
192
+ return invalidInstant(cause);
193
+ }
194
+
195
+ return invalidInstant(dateCause);
196
+ }
package/src/keyless.ts CHANGED
@@ -1,136 +1,9 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- /**
4
- * The operations that need no key, built WITHOUT a codec.
5
- *
6
- * Generating an id and re-encoding one are keyless: the result is the same value whoever asks, so
7
- * a bare function is an honest shape for them. Reaching them through a codec is what made them
8
- * expensive — a codec carries a mask schema, a cipher and a sentinel table, none of which a caller
9
- * who never masks will ever execute, and all of which a bundler must keep once the graph reaches
10
- * them. Measured 2026-08-12 on the built package: an entry importing only `uuidV7Slug` minified to
11
- * 12,735 bytes through the codec and 4,559 from a bare generator; `uuidToSlug` alone, 12,725
12
- * against 2,188. `defaultCodec` still exists and still works — it is simply no longer on the path
13
- * every consumer walks.
14
- *
15
- * NOTHING KEYED MAY BE ADDED HERE (Art's ruling, 2026-08-12). The only key a bare function could
16
- * carry is `DEFAULT_MASK_SCHEMA`'s, whose seed is a string literal in this published package, so a
17
- * masked operation exported this way would be the shortest spelling of the headline feature and
18
- * the one that obfuscates nothing. Masking is reached through a codec built with your own seed.
19
- */
20
- import { runtime } from "#runtime";
21
- import {
22
- checkRange,
23
- errorOrThrow,
24
- fillRandomBytes,
25
- UuidRuntimeError,
26
- UuidSlugError,
27
- } from "./errors";
28
- import type { UuidV4Slug, UuidV4String, UuidV7Generator, UuidV7Slug, UuidV7String } from "./types";
29
- import { formatUuid, formatUuidSlug } from "./uuid";
30
- import type { SlugAlphabet } from "./uuid";
31
- import { createRuntimeGenerator } from "./v7";
32
-
33
- /**
34
- * Built on first use, and the laziness is what the measurement above depends on: a module-scope
35
- * CONSTRUCTION call is a side effect a bundler may not remove, so an eager one would pin the
36
- * generator, the runtime adapter and the entropy pool into a bundle that only ever re-encodes a
37
- * UUID. Measured the same day, the eager spelling cost 5,130 bytes for `uuidToSlug` alone against
38
- * 2,188 here.
39
- *
40
- * It also keeps import-time work at zero, which `test/entropy.test.ts` gates for a different
41
- * reason — a heap snapshot taken at module load must capture no drawn randomness.
42
- */
43
- let generator: UuidV7Generator | undefined;
44
- const v7 = () => (generator ??= createRuntimeGenerator(runtime));
45
-
46
- /**
47
- * Randomness is drawn into a private buffer and copied out instead of filled through a view of the
48
- * caller's array: `fillRandom` requires a plain `ArrayBuffer` because Web Crypto rejects a
49
- * `SharedArrayBuffer` view, and a caller-supplied `out` carries no such guarantee. Reused rather
50
- * than allocated per call, matching the v7 generator, so the cost is one 16-byte copy.
51
- */
52
- const v4Random = new Uint8Array(16);
53
-
54
- /** Shared with `createUuidSlugCodec`, so a v4 has one implementation however it is reached. */
55
- export function uuidV4Bytes(out?: Uint8Array, offset = 0): UuidSlugError | Uint8Array {
56
- const target = out ?? new Uint8Array(16);
57
- const badRange = checkRange(target.length, offset, 16);
58
- if (badRange) return badRange;
59
- const failed = fillRandomBytes(runtime.fillRandom, v4Random);
60
- if (failed) return failed;
61
- target.set(v4Random, offset);
62
- target[offset + 6] = ((target[offset + 6] ?? 0) & 0x0f) | 0x40;
63
- target[offset + 8] = ((target[offset + 8] ?? 0) & 0x3f) | 0x80;
64
- return target;
65
- }
66
-
67
- export function uuidV4(): UuidV4String {
68
- try {
69
- const native = runtime.uuidV4?.();
70
- if (native) return native;
71
- } catch (cause) {
72
- throw new UuidRuntimeError("Runtime UUIDv4 generation failed.", { cause });
73
- }
74
- return errorOrThrow(formatUuid(errorOrThrow(uuidV4Bytes()))) as UuidV4String;
75
- }
76
-
77
- /**
78
- * Takes the alphabet for the same reason `uuidV7Slug` does, and NOT because a v4 slug sorts — it
79
- * does not. The alphabet is a choice of representation, so a project that has standardised on the
80
- * 26-character lowercase form for its public ids needs its v4 slugs in it too; the pair differing
81
- * would be an asymmetry with nothing behind it.
82
- */
83
- export function uuidV4Slug(alphabet: SlugAlphabet = "base64url"): UuidV4Slug {
84
- // The bytes came from `uuidV4Bytes`, which stamps version 4; the encoder sees only bytes and
85
- // cannot carry that through, which is what the assertion stands in for.
86
- return errorOrThrow(formatUuidSlug(errorOrThrow(uuidV4Bytes()), 0, alphabet)) as UuidV4Slug;
87
- }
88
-
89
- /*
90
- * Return types are DECLARED, not inferred, on all four. Inference reads them off the generator, so
91
- * a widened method there silently widens the package's public surface — and this package has
92
- * already been bitten by exactly that: `uuidV7Slug` once inferred `string | UuidSlug`, which
93
- * collapses to `string` because `Brand`'s marker is optional, so a branded return was promised that
94
- * nothing checked. A declared type turns that into a compile error at the one site that is wrong.
95
- */
96
- export const uuidV7 = (): UuidV7String => v7().uuidV7();
97
-
98
- export const uuidV7Bytes = (out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array =>
99
- v7().uuidV7Bytes(out, offset);
100
-
101
- export const uuidV7At = (timestamp: number): UuidSlugError | UuidV7String =>
102
- v7().uuidV7At(timestamp);
103
-
104
- export const uuidV7BytesAt = (
105
- timestamp: number,
106
- out?: Uint8Array,
107
- offset?: number,
108
- ): UuidSlugError | Uint8Array => v7().uuidV7BytesAt(timestamp, out, offset);
109
-
110
- /**
111
- * The alphabet is an argument here, exactly as it is on `uuidToSlug(uuid, alphabet)`, because
112
- * choosing it needs no key: without it the only way to GENERATE a base32hex slug was to build a
113
- * codec, so the sortable form cost the whole masking machinery while the unsortable one was free.
114
- * Positional and last, matching `uuidToSlug`, so the two spellings of "encode in this alphabet"
115
- * do not diverge.
116
- */
117
- export function uuidV7Slug(alphabet: SlugAlphabet = "base64url"): UuidV7Slug {
118
- // Gated on the ALPHABET, not merely on the hook's presence. The runtime's slug generator emits
119
- // base64url and nothing else, so an ungated branch answers a base32hex request with a 22-char
120
- // base64url string — and only Bun defines the hook, so vitest on Node cannot reach the branch at
121
- // all and the entire suite stays green. `test/runtime.bun.test.ts` is what actually covers it.
122
- // Probed per call rather than resolved once: resolving at module scope would reintroduce the
123
- // eager work the lazy cell above exists to avoid.
124
- //
125
- // The gate is also where the two alphabets stop costing the same, which is worth knowing before
126
- // standardising on the sortable one: measured on Bun 2026-08-12, base64url runs 17.0M/s and
127
- // base32hex 4.2M/s. Not an encoder deficiency -- base64url is handed straight to the engine's
128
- // own slug generator here, while base32hex must draw bytes and encode them in JavaScript. 4M
129
- // ids/sec is ample for identifier issuance; the number is recorded so the 4x is not rediscovered
130
- // as a mystery.
131
- const native = alphabet === "base64url" ? runtime.uuidV7Slug : undefined;
132
- if (native) return native();
133
- // Asserted for the same reason `uuidV4Slug` asserts: the bytes come from a v7 generator and the
134
- // encoder sees only bytes, so it returns the version-agnostic brand.
135
- return errorOrThrow(formatUuidSlug(errorOrThrow(v7().uuidV7Bytes()), 0, alphabet)) as UuidV7Slug;
136
- }
3
+ export { generateUuidV4, generateUuidV4Bytes, generateUuidV4WithRandomFill } from "./v4.ts";
4
+ export { generateUuidV7, generateUuidV7Bytes } from "./v7-keyless.ts";
5
+ export { createUuidV7Generator, createUuidV7GeneratorWithRandomFill } from "./v7-generator.ts";
6
+ export type { UuidV7GeneratorOptions } from "./v7-generator.ts";
7
+ export { generateUuidV7Value } from "./v7-value.ts";
8
+ export { generatePlainUuidV4Slug } from "./v4-slug.ts";
9
+ export { generatePlainUuidV7Slug, generateUuidV7WithPlainSlug } from "./v7-slug.ts";