@anizoptera/uuid-slug 0.2.0 → 0.3.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 (95) hide show
  1. package/README.md +381 -27
  2. package/dist/alphabet.d.ts +21 -0
  3. package/dist/alphabet.d.ts.map +1 -0
  4. package/dist/alphabet.js +132 -0
  5. package/dist/alphabet.js.map +1 -0
  6. package/dist/base64url.d.ts +20 -0
  7. package/dist/base64url.d.ts.map +1 -0
  8. package/dist/base64url.js +33 -0
  9. package/dist/base64url.js.map +1 -0
  10. package/dist/codec.d.ts +17 -0
  11. package/dist/codec.d.ts.map +1 -0
  12. package/dist/codec.js +192 -0
  13. package/dist/codec.js.map +1 -0
  14. package/dist/errors.d.ts +16 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +80 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/feistel.js +105 -0
  19. package/dist/feistel.js.map +1 -0
  20. package/dist/index.d.ts +11 -168
  21. package/dist/index.js +10 -649
  22. package/dist/keyless.d.ts +31 -0
  23. package/dist/keyless.d.ts.map +1 -0
  24. package/dist/keyless.js +93 -0
  25. package/dist/keyless.js.map +1 -0
  26. package/dist/legacy-mask.js +55 -0
  27. package/dist/legacy-mask.js.map +1 -0
  28. package/dist/mask.js +108 -0
  29. package/dist/mask.js.map +1 -0
  30. package/dist/migration.js +66 -0
  31. package/dist/migration.js.map +1 -0
  32. package/dist/node/alphabet.js +130 -0
  33. package/dist/node/base64url.js +31 -0
  34. package/dist/node/codec.js +190 -0
  35. package/dist/node/errors.js +78 -0
  36. package/dist/node/feistel.js +103 -0
  37. package/dist/node/index.js +10 -647
  38. package/dist/node/keyless.js +91 -0
  39. package/dist/node/legacy-mask.js +53 -0
  40. package/dist/node/mask.js +106 -0
  41. package/dist/node/migration.js +64 -0
  42. package/dist/node/runtime/node.js +33 -0
  43. package/dist/node/runtime/pool.js +53 -0
  44. package/dist/node/schema.js +214 -0
  45. package/dist/node/siphash.js +106 -0
  46. package/dist/node/uuid.js +226 -0
  47. package/dist/node/v7.js +185 -0
  48. package/dist/node/yield.js +20 -0
  49. package/dist/runtime/pool.js +55 -0
  50. package/dist/runtime/pool.js.map +1 -0
  51. package/dist/runtime/web.js +39 -0
  52. package/dist/runtime/web.js.map +1 -0
  53. package/dist/schema.d.ts +20 -0
  54. package/dist/schema.d.ts.map +1 -0
  55. package/dist/schema.js +216 -0
  56. package/dist/schema.js.map +1 -0
  57. package/dist/siphash.js +108 -0
  58. package/dist/siphash.js.map +1 -0
  59. package/dist/types.d.ts +255 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/uuid.d.ts +78 -0
  62. package/dist/uuid.d.ts.map +1 -0
  63. package/dist/uuid.js +228 -0
  64. package/dist/uuid.js.map +1 -0
  65. package/dist/v7.d.ts +12 -0
  66. package/dist/v7.d.ts.map +1 -0
  67. package/dist/v7.js +187 -0
  68. package/dist/v7.js.map +1 -0
  69. package/dist/yield.js +22 -0
  70. package/dist/yield.js.map +1 -0
  71. package/package.json +8 -12
  72. package/src/alphabet.ts +187 -0
  73. package/src/base64url.ts +28 -63
  74. package/src/codec.ts +227 -125
  75. package/src/errors.ts +83 -9
  76. package/src/feistel.ts +128 -0
  77. package/src/index.ts +52 -26
  78. package/src/keyless.ts +136 -0
  79. package/src/legacy-mask.ts +25 -0
  80. package/src/mask.ts +129 -67
  81. package/src/migration.ts +104 -0
  82. package/src/runtime/bun.ts +49 -24
  83. package/src/runtime/node.ts +33 -15
  84. package/src/runtime/pool.ts +62 -0
  85. package/src/runtime/types.ts +42 -5
  86. package/src/runtime/web.ts +37 -9
  87. package/src/schema.ts +274 -97
  88. package/src/siphash.ts +127 -0
  89. package/src/types.ts +221 -37
  90. package/src/uuid.ts +189 -50
  91. package/src/v7.ts +217 -45
  92. package/src/yield.ts +22 -0
  93. package/dist/index.d.ts.map +0 -1
  94. package/dist/index.js.map +0 -1
  95. package/dist/web/index.js +0 -648
package/package.json CHANGED
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "name": "@anizoptera/uuid-slug",
3
- "version": "0.2.0",
4
- "description": "Zero-dependency UUID v4/v7 generation, direct base64url slugs, and configurable masked UUID slugs.",
3
+ "version": "0.3.0",
4
+ "description": "Short URL-safe UUIDs: 22-character base64url slugs, plus reversible masking that hides the UUIDv7 timestamp. Zero dependencies.",
5
5
  "keywords": [
6
6
  "base64url",
7
7
  "browser",
8
8
  "bun",
9
9
  "deno",
10
+ "identifier",
10
11
  "node",
12
+ "short-uuid",
11
13
  "slug",
14
+ "url-safe",
12
15
  "uuid",
13
16
  "uuidv7",
14
17
  "zero-dependencies"
@@ -26,12 +29,6 @@
26
29
  "type": "git",
27
30
  "url": "git+https://github.com/Anizoptera/uuid-slug.git"
28
31
  },
29
- "files": [
30
- "dist",
31
- "src",
32
- "README.md",
33
- "LICENSE"
34
- ],
35
32
  "type": "module",
36
33
  "sideEffects": false,
37
34
  "main": "./dist/index.js",
@@ -50,10 +47,10 @@
50
47
  ".": {
51
48
  "types": "./dist/index.d.ts",
52
49
  "bun": "./src/index.ts",
53
- "deno": "./dist/web/index.js",
54
- "browser": "./dist/web/index.js",
50
+ "deno": "./dist/index.js",
51
+ "browser": "./dist/index.js",
55
52
  "node": "./dist/node/index.js",
56
- "default": "./dist/web/index.js"
53
+ "default": "./dist/index.js"
57
54
  },
58
55
  "./package.json": "./package.json"
59
56
  },
@@ -61,7 +58,6 @@
61
58
  "access": "public",
62
59
  "provenance": true
63
60
  },
64
- "dependencies": {},
65
61
  "engines": {
66
62
  "node": ">=20"
67
63
  }
@@ -0,0 +1,187 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { checkRange, UuidSlugError } from "./errors";
4
+ import type { UuidSlugErrorCode } from "./errors";
5
+
6
+ /**
7
+ * A power-of-two alphabet plus its reverse lookup. Encoding is pure bit packing, so the only
8
+ * thing that varies between base64url and base32 is the character set and how many bits each
9
+ * character carries — one routine serves both rather than two hand-unrolled loops.
10
+ */
11
+ export interface Alphabet {
12
+ readonly bitsPerChar: number;
13
+ readonly chars: string;
14
+ readonly code: UuidSlugErrorCode;
15
+ /** Character code -> value, `-1` for anything outside the alphabet. */
16
+ readonly decode: Int16Array;
17
+ readonly name: string;
18
+ readonly invalidChars: RegExp;
19
+ }
20
+
21
+ function alphabet(name: string, chars: string, code: UuidSlugErrorCode): Alphabet {
22
+ const bitsPerChar = Math.log2(chars.length);
23
+ if (!Number.isInteger(bitsPerChar)) throw new Error(`${name} alphabet must be a power of two.`);
24
+ const decode = new Int16Array(128).fill(-1);
25
+ for (let i = 0; i < chars.length; i += 1) decode[chars.charCodeAt(i)] = i;
26
+ return {
27
+ bitsPerChar,
28
+ chars,
29
+ code,
30
+ decode,
31
+ name,
32
+ invalidChars: new RegExp(`[^${chars.replaceAll("-", "\\-")}]`),
33
+ };
34
+ }
35
+
36
+ export const BASE64URL: Alphabet = alphabet(
37
+ "base64url",
38
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
39
+ "invalid_base64url",
40
+ );
41
+
42
+ /**
43
+ * The RFC 4648 §7 extended-hex digit values, not the §6 alphabet and not Crockford. Chosen because
44
+ * its characters are in ASCII order, so encoded values sort the same way the underlying bytes do —
45
+ * the one property base64url cannot offer, and the reason a second alphabet exists at all.
46
+ *
47
+ * Spelled LOWERCASE where the RFC writes `0-9A-V`, matching how this package renders UUIDs, and
48
+ * decoding accepts only that spelling so an id has exactly one form. The cost is interop: verified
49
+ * 2026-08-12 against CPython, `base64.b32hexdecode` rejects these slugs unless called with
50
+ * `casefold=True`. Upper-case them at the boundary if a strict RFC decoder has to read them.
51
+ */
52
+ export const BASE32HEX: Alphabet = alphabet(
53
+ "base32hex",
54
+ "0123456789abcdefghijklmnopqrstuv",
55
+ "invalid_base32",
56
+ );
57
+
58
+ // Native encoding is strict on output; decoding stays here because it must reject aliases,
59
+ // whitespace and nonzero padding that platform decoders may accept.
60
+ const nativeToBase64 = (
61
+ Uint8Array.prototype as {
62
+ toBase64?: (options: { alphabet: "base64url"; omitPadding: boolean }) => string;
63
+ }
64
+ ).toBase64;
65
+ const BASE64_OPTIONS = { alphabet: "base64url", omitPadding: true } as const;
66
+
67
+ /**
68
+ * Bits left over when `byteLength` bytes are written in this alphabet. A slug rounds up to whole
69
+ * characters, so the final character has spare low bits that carry no data: 4 for 16 bytes in
70
+ * base64url (22 chars = 132 bits), 2 in base32hex (26 chars = 130 bits). Callers may spend them
71
+ * on a trailing value at zero cost in length — see `encode`.
72
+ */
73
+ export function spareBits(alpha: Alphabet, byteLength: number): number {
74
+ const bits = byteLength * 8;
75
+ return (alpha.bitsPerChar - (bits % alpha.bitsPerChar)) % alpha.bitsPerChar;
76
+ }
77
+
78
+ /** Boolean validation needs no output buffer or diagnostic allocation. */
79
+ export function isEncoded(value: string, alpha: Alphabet, byteLength: number): boolean {
80
+ if (
81
+ value.length !== Math.ceil((byteLength * 8) / alpha.bitsPerChar) ||
82
+ alpha.invalidChars.test(value)
83
+ )
84
+ return false;
85
+ const spare = spareBits(alpha, byteLength);
86
+ return (
87
+ spare === 0 ||
88
+ ((alpha.decode[value.charCodeAt(value.length - 1)] as number) & ((1 << spare) - 1)) === 0
89
+ );
90
+ }
91
+
92
+ /**
93
+ * Pack bytes, optionally followed by `tailBits` low bits of `tail`, into `alpha`.
94
+ *
95
+ * `tailBits` MUST NOT exceed `spareBits`, otherwise the result grows a character. Passing
96
+ * `tail = 0` reproduces a plain encoding byte for byte, which is what keeps identifiers issued
97
+ * before the tail existed valid afterwards.
98
+ */
99
+ export function encode(bytes: Uint8Array, alpha: Alphabet, tail = 0, tailBits = 0): string {
100
+ if (
101
+ nativeToBase64 &&
102
+ alpha === BASE64URL &&
103
+ tailBits >= 0 &&
104
+ tailBits <= spareBits(alpha, bytes.length)
105
+ ) {
106
+ const encoded = nativeToBase64.call(bytes, BASE64_OPTIONS);
107
+ if (tailBits === 0) return encoded;
108
+ // The native result zeroes padding. Spend only those spare low bits on the mask check;
109
+ // replacing the final character leaves the UUID payload and the wire length unchanged.
110
+ const last = encoded.length - 1;
111
+ const digit = alpha.decode[encoded.charCodeAt(last)] as number;
112
+ const trailing = (tail & ((1 << tailBits) - 1)) << (spareBits(alpha, bytes.length) - tailBits);
113
+ return encoded.slice(0, last) + alpha.chars[digit | trailing];
114
+ }
115
+ const { bitsPerChar, chars } = alpha;
116
+ const mask = (1 << bitsPerChar) - 1;
117
+ let out = "";
118
+ let acc = 0;
119
+ let bits = 0;
120
+ for (let i = 0; i < bytes.length; i += 1) {
121
+ // At most bitsPerChar-1 bits are held over, so `acc` peaks at 13 bits and stays in int32.
122
+ acc = (acc << 8) | (bytes[i] as number);
123
+ bits += 8;
124
+ while (bits >= bitsPerChar) {
125
+ bits -= bitsPerChar;
126
+ out += chars[(acc >>> bits) & mask];
127
+ }
128
+ }
129
+ if (tailBits > 0) {
130
+ acc = (acc << tailBits) | (tail & ((1 << tailBits) - 1));
131
+ bits += tailBits;
132
+ while (bits >= bitsPerChar) {
133
+ bits -= bitsPerChar;
134
+ out += chars[(acc >>> bits) & mask];
135
+ }
136
+ }
137
+ if (bits > 0) out += chars[(acc << (bitsPerChar - bits)) & mask];
138
+ return out;
139
+ }
140
+
141
+ /**
142
+ * Inverse of `encode`, writing into a caller-owned buffer so the slug paths need no intermediate
143
+ * allocation. Returns the trailing value (0 when `tailBits` is 0), or an Error.
144
+ *
145
+ * Rejects any character outside the alphabet, and any padding bit that is not zero. Without that
146
+ * last check one identifier would have several valid spellings, so a corrupted slug could decode
147
+ * successfully instead of being refused.
148
+ */
149
+ export function decodeInto(
150
+ value: string,
151
+ alpha: Alphabet,
152
+ out: Uint8Array,
153
+ offset: number,
154
+ byteLength: number,
155
+ tailBits = 0,
156
+ ): UuidSlugError | number {
157
+ const { bitsPerChar, decode: table, code, name } = alpha;
158
+ const expected = Math.ceil((byteLength * 8 + tailBits) / bitsPerChar);
159
+ if (value.length !== expected)
160
+ return new UuidSlugError(code, `Expected ${expected} ${name} characters, got ${value.length}.`);
161
+ const badRange = checkRange(out.length, offset, byteLength);
162
+ if (badRange) return badRange;
163
+
164
+ let acc = 0;
165
+ let bits = 0;
166
+ let written = 0;
167
+ for (let i = 0; i < value.length; i += 1) {
168
+ const charCode = value.charCodeAt(i);
169
+ const digit = charCode < 128 ? (table[charCode] as number) : -1;
170
+ if (digit < 0) return new UuidSlugError(code, `Invalid ${name} character at offset ${i}.`);
171
+ acc = (acc << bitsPerChar) | digit;
172
+ bits += bitsPerChar;
173
+ while (bits >= 8 && written < byteLength) {
174
+ bits -= 8;
175
+ out[offset + written] = (acc >>> bits) & 0xff;
176
+ written += 1;
177
+ }
178
+ }
179
+ let tail = 0;
180
+ if (tailBits > 0) {
181
+ bits -= tailBits;
182
+ tail = (acc >>> bits) & ((1 << tailBits) - 1);
183
+ }
184
+ if (bits > 0 && (acc & ((1 << bits) - 1)) !== 0)
185
+ return new UuidSlugError(code, `${name} value has non-canonical trailing bits.`);
186
+ return tail;
187
+ }
package/src/base64url.ts CHANGED
@@ -1,76 +1,41 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { BASE64URL, decodeInto, encode, isEncoded } from "./alphabet";
1
4
  import { UuidSlugError } from "./errors";
2
5
  import type { Base64UrlString } from "./types";
3
6
 
4
- const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
5
- const DECODE = new Int16Array(128).fill(-1);
6
- for (let i = 0; i < ALPHABET.length; i += 1) DECODE[ALPHABET.charCodeAt(i)] = i;
7
-
8
- function byteAt(bytes: Uint8Array, index: number) {
9
- return bytes[index] ?? 0;
10
- }
11
-
12
7
  export function encodeBase64Url(bytes: Uint8Array): Base64UrlString {
13
- let out = "";
14
- let i = 0;
15
- for (; i + 2 < bytes.length; i += 3) {
16
- const value = (byteAt(bytes, i) << 16) | (byteAt(bytes, i + 1) << 8) | byteAt(bytes, i + 2);
17
- out += ALPHABET[(value >>> 18) & 63];
18
- out += ALPHABET[(value >>> 12) & 63];
19
- out += ALPHABET[(value >>> 6) & 63];
20
- out += ALPHABET[value & 63];
21
- }
22
- const remaining = bytes.length - i;
23
- if (remaining === 1) {
24
- const value = byteAt(bytes, i) << 16;
25
- out += ALPHABET[(value >>> 18) & 63];
26
- out += ALPHABET[(value >>> 12) & 63];
27
- }
28
- if (remaining === 2) {
29
- const value = (byteAt(bytes, i) << 16) | (byteAt(bytes, i + 1) << 8);
30
- out += ALPHABET[(value >>> 18) & 63];
31
- out += ALPHABET[(value >>> 12) & 63];
32
- out += ALPHABET[(value >>> 6) & 63];
33
- }
34
- return out as Base64UrlString;
8
+ return encode(bytes, BASE64URL);
35
9
  }
36
10
 
37
- export function decodeBase64Url(value: string, out?: Uint8Array, offset = 0): Error | Uint8Array {
11
+ /**
12
+ * Decodes into `out` at `offset` when given one, otherwise into a fresh array.
13
+ *
14
+ * Returns a view over EXACTLY the bytes decoded, in both cases. The two used to disagree: without
15
+ * `out` the result was `byteLength`-exact, with `out` it was the caller's entire buffer at its full
16
+ * size, with the data at `offset` and no way to learn how many bytes had been written short of
17
+ * recomputing `floor(value.length * 6 / 8)` by hand. One rule — "the bytes this call produced" —
18
+ * makes the length usable and leaves the caller's own buffer reachable, since they own it.
19
+ */
20
+ export function decodeBase64Url(
21
+ value: string,
22
+ out?: Uint8Array,
23
+ offset = 0,
24
+ ): UuidSlugError | Uint8Array {
25
+ // Padding is the most common malformed input by far, and the generic "invalid character"
26
+ // message sends the reader looking for a typo instead of a stray "=".
38
27
  if (value.includes("="))
39
28
  return new UuidSlugError("invalid_base64url", "Base64url value must be unpadded.");
40
- if (value.length % 4 === 1)
41
- return new UuidSlugError("invalid_base64url", "Base64url length is impossible.");
42
-
43
- const byteLength = Math.floor((value.length * 6) / 8);
29
+ const byteLength = Math.floor((value.length * BASE64URL.bitsPerChar) / 8);
44
30
  const target = out ?? new Uint8Array(byteLength);
45
- if (offset < 0 || offset + byteLength > target.length)
46
- return new UuidSlugError("invalid_buffer", "Output buffer is too small.");
47
-
48
- let buffer = 0;
49
- let bits = 0;
50
- let written = 0;
51
- for (let i = 0; i < value.length; i += 1) {
52
- const code = value.charCodeAt(i);
53
- const decoded = code < DECODE.length ? (DECODE[code] ?? -1) : -1;
54
- if (decoded < 0)
55
- return new UuidSlugError("invalid_base64url", `Invalid base64url character at offset ${i}.`);
56
- buffer = (buffer << 6) | decoded;
57
- bits += 6;
58
- if (bits >= 8) {
59
- bits -= 8;
60
- target[offset + written] = (buffer >>> bits) & 0xff;
61
- written += 1;
62
- }
63
- }
64
- if (bits > 0 && (buffer & ((1 << bits) - 1)) !== 0) {
65
- return new UuidSlugError(
66
- "invalid_base64url",
67
- "Base64url value has non-canonical trailing bits.",
68
- );
69
- }
70
- return out ? target : target.subarray(0, byteLength);
31
+ const result = decodeInto(value, BASE64URL, target, offset, byteLength);
32
+ if (result instanceof Error) return result;
33
+ return target.subarray(offset, offset + byteLength);
71
34
  }
72
35
 
73
36
  export function isBase64Url(value: null | string | undefined): value is Base64UrlString {
74
- if (!value || value.includes("=") || value.length % 4 === 1) return false;
75
- return decodeBase64Url(value) instanceof Error ? false : true;
37
+ // The empty string decodes to zero bytes without error, but an identifier of no characters is
38
+ // never what a caller means by "is this a slug"; rejecting it keeps the guard usable as one.
39
+ if (!value) return false;
40
+ return isEncoded(value, BASE64URL, Math.floor((value.length * BASE64URL.bitsPerChar) / 8));
76
41
  }