@anizoptera/uuid-slug 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1175 -30
  3. package/dist/alphabet.d.ts +9 -0
  4. package/dist/alphabet.d.ts.map +1 -0
  5. package/dist/alphabet.js +166 -0
  6. package/dist/alphabet.js.map +1 -0
  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 +57 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +162 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/feistel.js +39 -0
  16. package/dist/feistel.js.map +1 -0
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +23 -168
  20. package/dist/index.js +22 -649
  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 +164 -0
  30. package/dist/mask.js.map +1 -0
  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 +129 -0
  40. package/dist/migration.js.map +1 -0
  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 +30 -0
  48. package/dist/runtime/pool.js.map +1 -0
  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 +29 -0
  54. package/dist/siphash.js.map +1 -0
  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 +535 -0
  64. package/dist/types.d.ts.map +1 -0
  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 +65 -0
  74. package/dist/uuid.d.ts.map +1 -0
  75. package/dist/uuid.js +232 -0
  76. package/dist/uuid.js.map +1 -0
  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 +143 -0
  114. package/dist/v7.js.map +1 -0
  115. package/package.json +18 -17
  116. package/src/alphabet.ts +616 -0
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +423 -13
  119. package/src/feistel.ts +141 -0
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +137 -57
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +9 -0
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +377 -90
  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 +257 -0
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +31 -25
  132. package/src/runtime/node.ts +55 -18
  133. package/src/runtime/pool.ts +90 -0
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +30 -5
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +128 -0
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +799 -61
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +527 -108
  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 +433 -84
  156. package/dist/index.d.ts.map +0 -1
  157. package/dist/index.js.map +0 -1
  158. package/dist/node/index.js +0 -647
  159. package/dist/web/index.js +0 -648
  160. package/src/base64url.ts +0 -76
  161. package/src/codec.ts +0 -218
  162. package/src/runtime/web.ts +0 -20
  163. package/src/schema.ts +0 -123
package/src/index.ts CHANGED
@@ -1,74 +1,154 @@
1
- export { decodeBase64Url, encodeBase64Url, isBase64Url } from "./base64url";
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
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";
2
6
  export {
3
- UUID_V7_SENTINEL_DEFINITIONS,
4
- createUuidSlugCodec,
5
- defaultCodec,
6
- validateMaskedUuidV7SlugFresh,
7
- validateUuidV7Fresh,
8
- validateUuidV7SlugFresh,
9
- } from "./codec";
10
- export { UuidRuntimeError, UuidSlugError } from "./errors";
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";
11
28
  export {
12
- DEFAULT_MASK_SCHEMA,
13
- LEGACY_MASK_SCHEMA_V1,
14
- createMaskSchema,
15
- defineMaskSchema,
16
- } from "./schema";
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";
17
42
  export type {
18
- Base64UrlString,
19
- ExplicitMaskSchema,
20
- FreshValidationOptions,
21
- MaskSchema,
22
- MaskSchemaOptions,
23
- 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,
24
56
  MaskedUuidV7Slug,
25
- PublicUuidV7Slug,
57
+ MaskedOrSentinelUuidV7Slug,
26
58
  SentinelUuidV7Slug,
27
59
  UuidBytes,
28
- UuidSlug,
29
- UuidSlugCodec,
30
- UuidSlugCodecOptions,
60
+ UuidByteInput,
61
+ UuidInput,
62
+ UuidStringResult,
63
+ UuidBytesResult,
64
+ PlainUuidSlugResult,
65
+ UuidV4Bytes,
66
+ PlainUuidSlug,
67
+ UuidSlugMigrationDecoder,
68
+ UuidSlugMigrationOptions,
31
69
  UuidString,
32
- 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,
33
83
  UuidV4String,
84
+ UuidV4Text,
34
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,
35
99
  UuidV7Sentinel,
36
- UuidV7SentinelDefinition,
37
- UuidV7Slug,
100
+ UuidV7SentinelConfig,
101
+ PlainUuidV7Slug,
38
102
  UuidV7String,
39
- } from "./types";
103
+ UuidV7Text,
104
+ } from "./types.ts";
105
+ export { uuidV7StringBounds, uuidV7ByteBounds } from "./v7-bounds.ts";
40
106
  export {
41
- extractUuidV7Timestamp,
42
- formatUuid,
43
- formatUuidSlug,
44
- hasUuidV7Entropy,
45
- isUuidSlug,
46
- isUuidV4Slug,
107
+ MAX_UUID,
108
+ NIL_UUID,
109
+ bytesToUuidString,
110
+ isUuidBytes,
111
+ isUuidV4Bytes,
47
112
  isUuidV4String,
113
+ isUuidV4Text,
48
114
  isUuidV7Bytes,
49
- isUuidV7Slug,
50
115
  isUuidV7String,
116
+ isUuidV7Text,
51
117
  isUuidString,
52
- parseUuid,
53
- parseUuidSlug,
54
- slugToUuid,
55
- slugToUuidBytes,
56
- uuidBytesToSlug,
57
- uuidToSlug,
58
- } from "./uuid";
59
- export { createRuntimeGenerator, createUuidV7Generator } from "./v7";
60
-
61
- import { defaultCodec } from "./codec";
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";
62
141
 
63
- export const uuidV4 = defaultCodec.uuidV4;
64
- export const uuidV7 = defaultCodec.uuidV7;
65
- export const uuidV4Bytes = defaultCodec.uuidV4Bytes;
66
- export const uuidV7Bytes = defaultCodec.uuidV7Bytes;
67
- export const uuidV4Slug = defaultCodec.uuidV4Slug;
68
- export const uuidV7Slug = defaultCodec.uuidV7Slug;
69
- export const uuidV7MaskedSlug = defaultCodec.uuidV7MaskedSlug;
70
- export const uuidToMaskedSlug = defaultCodec.uuidToMaskedSlug;
71
- export const maskedSlugToUuid = defaultCodec.maskedSlugToUuid;
72
- export const uuidV7ToMaskedSlug = defaultCodec.uuidV7ToMaskedSlug;
73
- export const maskedSlugToUuidV7 = defaultCodec.maskedSlugToUuidV7;
74
- export const UUID_V7_SENTINELS = defaultCodec.sentinels;
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. */
144
+ export {
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 ADDED
@@ -0,0 +1,9 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
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";
@@ -0,0 +1,141 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import {
4
+ findUnknownOption,
5
+ INVALID_MASK,
6
+ isUint8Array,
7
+ isUuidSlugError,
8
+ stringInput,
9
+ UuidSlugError,
10
+ } from "./errors.ts";
11
+ import type { CustomUuidV7MaskOptions, UuidV7Mask } from "./types.ts";
12
+
13
+ const MASK_PROTOCOL = Symbol.for("@anizoptera/uuid-slug/mask/1");
14
+ const CUSTOM_MASK_FAILURE_MESSAGE = "Custom mask construction failed.";
15
+ const MASK_DIRECTION = "mask";
16
+ const CUSTOM_MASK_OPTIONS = {
17
+ diagnosticLabel: true,
18
+ [MASK_DIRECTION]: true,
19
+ unmask: true,
20
+ } as const satisfies Record<keyof CustomUuidV7MaskOptions, true>;
21
+
22
+ interface MaskProtocol {
23
+ readonly version: 1;
24
+ readonly mix: (
25
+ input: Uint8Array,
26
+ output: Uint8Array,
27
+ direction: "mask" | "unmask",
28
+ ) => undefined | UuidSlugError;
29
+ }
30
+
31
+ type MaskHandle = UuidV7Mask & { readonly [MASK_PROTOCOL]: MaskProtocol };
32
+
33
+ /**
34
+ * The versioned global symbol lets genuine handles cross duplicate same-version package copies.
35
+ * The protocol is internal representation, not an authenticity boundary for trusted codec options.
36
+ */
37
+ /*#__NO_SIDE_EFFECTS__*/
38
+ export function createMaskHandle(diagnosticLabel: string, mix: MaskProtocol["mix"]): UuidV7Mask {
39
+ const mask = { diagnosticLabel } as MaskHandle;
40
+ Object.defineProperty(mask, MASK_PROTOCOL, {
41
+ value: Object.freeze<MaskProtocol>({ version: 1, mix }),
42
+ });
43
+ return Object.freeze(mask);
44
+ }
45
+
46
+ function maskProtocol(mask: UuidV7Mask): MaskProtocol | undefined {
47
+ if (typeof mask !== "object" || mask === null) return undefined;
48
+ const protocol = (mask as Partial<MaskHandle>)[MASK_PROTOCOL];
49
+ return protocol?.version === 1 && typeof protocol.mix === "function" ? protocol : undefined;
50
+ }
51
+
52
+ export function isMaskHandle(mask: unknown): mask is UuidV7Mask {
53
+ return maskProtocol(mask as UuidV7Mask) !== undefined;
54
+ }
55
+
56
+ export function applyMask(
57
+ mask: UuidV7Mask,
58
+ input: Uint8Array,
59
+ output: Uint8Array,
60
+ direction: "mask" | "unmask",
61
+ ): undefined | UuidSlugError {
62
+ const protocol = maskProtocol(mask);
63
+ if (!protocol) return new UuidSlugError(INVALID_MASK, "Mask handle is invalid or incompatible.");
64
+ return protocol.mix(input, output, direction);
65
+ }
66
+
67
+ function runCustom(
68
+ transform: CustomUuidV7MaskOptions["mask"],
69
+ input: Uint8Array,
70
+ ): Uint8Array | UuidSlugError {
71
+ // Callbacks never receive package or caller storage. Copy their result at the codec boundary too,
72
+ // because a callback may retain and mutate the array it returns.
73
+ const output = transform(input.slice());
74
+ if (isUuidSlugError(output)) return output;
75
+ if (!isUint8Array(output) || output.length !== 16)
76
+ return new UuidSlugError(INVALID_MASK, "A custom mask transform must return exactly 16 bytes.");
77
+ return output;
78
+ }
79
+
80
+ /**
81
+ * Build an immutable mask from reversible 16-byte callbacks. Each callback receives isolated bytes,
82
+ * so returning the same array is safe. Invalid results and thrown values return `UuidSlugError`.
83
+ * The caller must ensure `unmask(mask(bytes))` restores every possible 16-byte input.
84
+ *
85
+ * @param options - Diagnostic label and mutually inverse 16-byte transforms.
86
+ * @returns The validated mask, or `UuidSlugError` for an invalid contract or callback result.
87
+ */
88
+ export function createCustomUuidV7Mask(
89
+ options: CustomUuidV7MaskOptions,
90
+ ): UuidV7Mask | UuidSlugError {
91
+ try {
92
+ if (typeof options !== "object" || options === null || Array.isArray(options))
93
+ return new UuidSlugError(INVALID_MASK, "Custom mask options must be an object.");
94
+ const unknown = findUnknownOption(options, CUSTOM_MASK_OPTIONS);
95
+ if (unknown !== undefined)
96
+ return new UuidSlugError(INVALID_MASK, `Unknown custom mask option: ${unknown}.`);
97
+ const { mask, unmask } = options;
98
+ const diagnosticLabel = stringInput(options.diagnosticLabel);
99
+ if (
100
+ typeof diagnosticLabel !== "string" ||
101
+ typeof mask !== "function" ||
102
+ typeof unmask !== "function"
103
+ )
104
+ return new UuidSlugError(
105
+ INVALID_MASK,
106
+ "A custom UUIDv7 mask requires a string diagnosticLabel plus mask and unmask functions.",
107
+ );
108
+ // These probes reject common non-inverses cheaply; no finite sample can prove a bijection over
109
+ // 128 bits, so the public contract keeps full invertibility as the callback author's duty.
110
+ for (const probe of [
111
+ new Uint8Array(16),
112
+ Uint8Array.from({ length: 16 }, (_, index) => index * 17),
113
+ ]) {
114
+ const mixed = runCustom(mask, probe);
115
+ if (isUuidSlugError(mixed))
116
+ return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
117
+ cause: mixed,
118
+ });
119
+ const restored = runCustom(unmask, mixed);
120
+ if (isUuidSlugError(restored))
121
+ return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
122
+ cause: restored,
123
+ });
124
+ if (restored.some((byte, index) => byte !== probe[index]))
125
+ return new UuidSlugError(
126
+ INVALID_MASK,
127
+ `UUIDv7 mask "${diagnosticLabel}" does not unmask its own masked output.`,
128
+ );
129
+ }
130
+ return createMaskHandle(diagnosticLabel, (input, output, direction) => {
131
+ const mixed = runCustom(direction === MASK_DIRECTION ? mask : unmask, input);
132
+ if (isUuidSlugError(mixed)) return mixed;
133
+ output.set(mixed);
134
+ return undefined;
135
+ });
136
+ } catch (cause) {
137
+ return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
138
+ cause,
139
+ });
140
+ }
141
+ }