@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
@@ -1,64 +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 { BASE32HEX, BASE64URL, decodeInto, encode } from "./alphabet.js";
5
- import { formatUuid } from "./uuid.js";
6
- import { decodeMaskedCandidates } from "./mask.js";
7
- import { decodeOriginalMask } from "./legacy-mask.js";
8
- //#region src/migration.ts
9
- /** Read old IDs with the codec's keys and sentinels; never change how new IDs are written. */
10
- function createMigration(schemas, sentinels, options = {}) {
11
- const original = options.original === true;
12
- const plain = options.plain === true;
13
- function read(slug, format, firstOnly) {
14
- if (format !== void 0 && format !== "current" && format !== "original" && format !== "plain" || format === "original" && !original || format === "plain" && !plain) return new UuidSlugError("invalid_uuid_slug", "Enable the requested format when creating the migration reader.");
15
- const sentinel = sentinels.get(slug);
16
- if (sentinel) return [sentinel.uuid];
17
- const useCurrent = format === void 0 || format === "current";
18
- const useOriginal = original && (format === void 0 || format === "original");
19
- const usePlain = plain && (format === void 0 || format === "plain");
20
- const bytes = /* @__PURE__ */ new Uint8Array(16);
21
- const base32 = slug.length === 26 && usePlain;
22
- const tail = decodeInto(slug, base32 ? BASE32HEX : BASE64URL, bytes, 0, 16, base32 ? 0 : 4);
23
- if (tail instanceof Error) return tail;
24
- const reserved = (useOriginal || usePlain) && sentinels.get(base32 ? encode(bytes, BASE64URL) : tail === 0 ? slug : slug.slice(0, 21) + BASE64URL.chars[(bytes[15] & 3) << 4]);
25
- if (reserved && firstOnly) return [reserved.uuid];
26
- const candidates = reserved ? [reserved.uuid] : [];
27
- function add(value) {
28
- const uuid = formatUuid(value);
29
- if (uuid instanceof Error) return uuid;
30
- if (!candidates.includes(uuid)) candidates.push(uuid);
31
- }
32
- if (useCurrent && !base32) {
33
- const matches = decodeMaskedCandidates(bytes, tail, schemas, firstOnly, candidates);
34
- if (matches instanceof Error) return matches;
35
- if (firstOnly && candidates.length) return candidates;
36
- }
37
- if (reserved) return candidates;
38
- if (useOriginal && slug.length === 22) {
39
- const match = decodeOriginalMask(bytes);
40
- if (match instanceof Error) return match;
41
- if (match) {
42
- const failed = add(match);
43
- if (failed) return failed;
44
- if (firstOnly) return candidates;
45
- }
46
- }
47
- if (usePlain) {
48
- const failed = add(bytes);
49
- if (failed) return failed;
50
- }
51
- return candidates;
52
- }
53
- return {
54
- decode(slug, format) {
55
- const result = read(slug, format, true);
56
- return result instanceof Error ? result : result[0] ?? new UuidSlugError("invalid_uuid_slug", "Slug does not match an enabled format.");
57
- },
58
- candidates(slug, format) {
59
- return read(slug, format, false);
60
- }
61
- };
62
- }
63
- //#endregion
64
- export { createMigration };
@@ -1,33 +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 { pooledFill } from "./pool.js";
4
- import crypto from "node:crypto";
5
- //#region src/runtime/node.ts
6
- /**
7
- * Node grew `crypto.randomUUIDv7` in 26.6.0, so on every earlier release this is `undefined`
8
- * and the capability is simply absent. Probed once here rather than inside the method:
9
- * `Runtime.uuidV7` is optional precisely so a consumer can branch on its presence, and a
10
- * method that exists but always throws defeats that — the caller reaches for it, catches, and
11
- * falls back on EVERY call. Measured 2026-08-11 on Node 24.15.0, that throw cost 64% of v7
12
- * throughput (400k against 1.11M ops/s).
13
- */
14
- const nativeUuidV7 = crypto.randomUUIDv7;
15
- const nodeRuntime = {
16
- /**
17
- * `randomFillSync` writes into the buffer it is given. `randomBytes` would allocate a fresh
18
- * `Buffer` per call and copy out of it, leaving a second, unzeroed copy of the random
19
- * material on the heap for the collector to get to whenever it does. Measured 14% faster
20
- * as well, but the copy is the reason. Pooled because the per-call cost dominates at 16
21
- * bytes; see `pool.ts`.
22
- */
23
- fillRandom: pooledFill((into) => {
24
- crypto.randomFillSync(into);
25
- }),
26
- uuidV4() {
27
- return crypto.randomUUID();
28
- }
29
- };
30
- if (nativeUuidV7) nodeRuntime.uuidV7 = () => nativeUuidV7.call(crypto);
31
- const runtime = nodeRuntime;
32
- //#endregion
33
- export { runtime };
@@ -1,53 +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/runtime/pool.ts
4
- /**
5
- * Draws cryptographic randomness a page at a time instead of per id.
6
- *
7
- * The underlying primitives cost far more per call than per byte, and a v7 id needs only 16
8
- * bytes, so per-id draws spend nearly all of their time on call overhead. Measured 2026-08-11
9
- * filling 16 bytes: 1.94M/s (Node 24) and 4.85M/s (Bun) drawing directly, against 38.9M/s and
10
- * 77.9M/s from an 8 KiB pool — 20x and 16x. Node's own `randomUUID` batches for the same reason,
11
- * which is why `crypto.randomUUID` measures 8.9M/s against 1.5M/s with its cache disabled.
12
- *
13
- * 8 KiB is the knee: 64 KiB gains nothing further on Node and measured slightly worse on Bun,
14
- * while holding eight times as much unissued material in memory.
15
- *
16
- * The source is unchanged — this batches the same CSPRNG, it does not replace or stretch it.
17
- */
18
- const POOL_BYTES = 8192;
19
- /**
20
- * Wraps a direct random-fill primitive in a pool.
21
- *
22
- * Consumed bytes are zeroed as they are handed out. Batching is what creates the need: without
23
- * a pool, material for an id is gone once used, whereas a live 8 KiB buffer would otherwise
24
- * retain the random half of up to 512 already-issued ids, so a heap dump would expose ids the
25
- * process had already handed out. Zeroing restores the property batching would remove; the cost
26
- * is one write per byte already being copied.
27
- *
28
- * Each module instance owns its pool, so worker threads never share one. This is safe under
29
- * Node's process model because a new process gets a fresh heap; it would NOT be safe under a
30
- * POSIX `fork` that copies the heap, where parent and child would issue identical bytes.
31
- */
32
- function pooledFill(fill) {
33
- const pool = new Uint8Array(POOL_BYTES);
34
- let offset = POOL_BYTES;
35
- return (bytes) => {
36
- const { length } = bytes;
37
- if (length > POOL_BYTES) {
38
- fill(bytes);
39
- return;
40
- }
41
- if (offset + length > POOL_BYTES) {
42
- fill(pool);
43
- offset = 0;
44
- }
45
- for (let i = 0; i < length; i += 1) {
46
- bytes[i] = pool[offset + i];
47
- pool[offset + i] = 0;
48
- }
49
- offset += length;
50
- };
51
- }
52
- //#endregion
53
- export { pooledFill };
@@ -1,214 +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 { halfSipHash } from "./siphash.js";
5
- import { feistel16 } from "./feistel.js";
6
- import { yieldToHost } from "./yield.js";
7
- //#region src/schema.ts
8
- /** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */
9
- const SEED_MIN_BYTES = 16;
10
- /** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */
11
- const MAX_KEY_ITERATIONS = 1 << 24;
12
- /**
13
- * Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of
14
- * "uuid" with "slgA" and "slgB", so a reader can check they conceal no chosen structure.
15
- *
16
- * Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every
17
- * seed different round keys and make every masked slug ever issued undecodable.
18
- */
19
- const CHAIN_A_KEY1 = 1097297011;
20
- const CHAIN_B_KEY1 = 1114074227;
21
- const CHAIN_KEY0 = 1684632949;
22
- function seedBytes(seed) {
23
- if (typeof seed !== "string") return new Uint8Array(seed);
24
- return new TextEncoder().encode(seed);
25
- }
26
- /** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */
27
- function seedWords(seed) {
28
- const words = new Int32Array(Math.ceil(seed.length / 4) + 1);
29
- writeSeedWords(seed, words);
30
- return words;
31
- }
32
- /** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */
33
- function writeSeedWords(seed, words, offset = 0, start = 0, end = seed.length) {
34
- for (let index = start; index < end; index += 1) {
35
- const absolute = offset + index;
36
- words[absolute >>> 2] = words[absolute >>> 2] | seed[index] << (absolute & 3) * 8;
37
- }
38
- }
39
- /**
40
- * Hash the seed under successive outputs, for `iterations` total hashes. This work is paid
41
- * at construction, never per id. The count changes key material and must remain stable for
42
- * issued slugs; retain the old count with its seed when rotating schemas.
43
- */
44
- function chain(key0, key1, words, length, iterations) {
45
- const out = /* @__PURE__ */ new Int32Array(2);
46
- halfSipHash(key0, key1, words, length, out);
47
- for (let i = 1; i < iterations; i += 1) halfSipHash(out[0], out[1], words, length, out);
48
- return out;
49
- }
50
- /**
51
- * Derive each round key by XORing outputs from two fixed derivation chains. Their combined
52
- * state is 128 bits; that representation does not establish 128-bit security. Chain constants,
53
- * word indices and byte order are frozen by the issued wire format.
54
- */
55
- function derivedKeys(seed, iterations) {
56
- const words = seedWords(seed);
57
- return roundKeys(chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations), chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations));
58
- }
59
- /** The same final key expansion follows synchronous and cooperative derivation. */
60
- function roundKeys(chainA, chainB) {
61
- const keys = /* @__PURE__ */ new Int32Array(8);
62
- const index = /* @__PURE__ */ new Int32Array(1);
63
- const fromA = /* @__PURE__ */ new Int32Array(2);
64
- const fromB = /* @__PURE__ */ new Int32Array(2);
65
- for (let word = 0; word < 8; word += 2) {
66
- index[0] = word;
67
- halfSipHash(chainA[0], chainA[1], index, 4, fromA);
68
- halfSipHash(chainB[0], chainB[1], index, 4, fromB);
69
- keys[word] = fromA[0] ^ fromB[0];
70
- keys[word + 1] = fromA[1] ^ fromB[1];
71
- }
72
- return keys;
73
- }
74
- function feistelSchema(id, seed, iterations) {
75
- return schemaFromKeys(id, derivedKeys(seed, iterations));
76
- }
77
- function schemaFromKeys(id, keys) {
78
- return {
79
- id,
80
- mix(input, output, forward) {
81
- feistel16(input, 0, keys, forward, output, 0);
82
- }
83
- };
84
- }
85
- function createMaskSchema(options) {
86
- const seed = seedBytes(options.seed);
87
- const short = invalidSeedLength(seed.length);
88
- if (short) return short;
89
- const iterations = options.keyIterations ?? 1;
90
- const invalid = invalidIterations(iterations);
91
- if (invalid) return invalid;
92
- return feistelSchema(options.id ?? "seeded", seed, iterations);
93
- }
94
- function invalidSeedLength(length) {
95
- if (length < SEED_MIN_BYTES) return new UuidSlugError("invalid_mask_schema", `Mask seed must be at least ${SEED_MIN_BYTES} bytes, got ${length}. Generate one with \`openssl rand -base64 32\` rather than choosing it; a guessable seed hides nothing however long it is.`);
96
- }
97
- function invalidIterations(iterations) {
98
- if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_KEY_ITERATIONS) return new UuidSlugError("invalid_mask_schema", `Mask keyIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`);
99
- }
100
- /** Bounded byte work between checkpoints, independent of total seed size or iteration count. */
101
- const CHUNK_BYTES = 4096;
102
- function* cooperativeChain(key0, key1, words, length, iterations) {
103
- const out = /* @__PURE__ */ new Int32Array(2);
104
- out[0] = key0;
105
- out[1] = key1;
106
- const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));
107
- let sinceCheckpoint = 0;
108
- for (let i = 0; i < iterations; i += 1) {
109
- let continuation;
110
- do {
111
- continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);
112
- if (continuation) yield;
113
- } while (continuation);
114
- sinceCheckpoint += 1;
115
- if (sinceCheckpoint >= hashesPerChunk) {
116
- sinceCheckpoint = 0;
117
- yield;
118
- }
119
- }
120
- return out;
121
- }
122
- function* cooperativeKeys(seed, iterations) {
123
- const chunks = [];
124
- let length = 0;
125
- if (typeof seed === "string") {
126
- const encoder = new TextEncoder();
127
- for (let start = 0; start < seed.length;) {
128
- let end = Math.min(seed.length, start + CHUNK_BYTES);
129
- const last = seed.charCodeAt(end - 1);
130
- const next = seed.charCodeAt(end);
131
- if (end < seed.length && last >= 55296 && last <= 56319 && next >= 56320 && next <= 57343) end -= 1;
132
- const bytes = encoder.encode(seed.slice(start, end));
133
- chunks.push(bytes);
134
- length += bytes.length;
135
- start = end;
136
- yield;
137
- }
138
- } else {
139
- chunks.push(seed);
140
- length = seed.length;
141
- }
142
- const short = invalidSeedLength(length);
143
- if (short) return short;
144
- const words = new Int32Array(Math.ceil(length / 4) + 1);
145
- let offset = 0;
146
- for (const bytes of chunks) {
147
- for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {
148
- writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));
149
- yield;
150
- }
151
- offset += bytes.length;
152
- }
153
- chunks.length = 0;
154
- return roundKeys(yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations), yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations));
155
- }
156
- /**
157
- * Derive the same schema while allowing other host tasks to run. Options and byte contents are
158
- * captured before suspension; cancellation returns an `aborted` error with the signal's reason
159
- * as its cause. Checkpoints stop computation rather than racing a still-running derivation.
160
- *
161
- * Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,
162
- * not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations
163
- * need no host yield. Passing the result as a codec's `mask` avoids deriving it again.
164
- */
165
- async function createMaskSchemaAsync(options) {
166
- try {
167
- const { signal } = options;
168
- const aborted = () => new UuidSlugError("aborted", "Mask schema construction was aborted.", { cause: signal?.reason });
169
- if (signal?.aborted) return aborted();
170
- const { seed: input, keyIterations = 1, id = "seeded" } = options;
171
- const invalid = invalidIterations(keyIterations);
172
- if (invalid) return invalid;
173
- const steps = cooperativeKeys(typeof input === "string" ? input : new Uint8Array(input), keyIterations);
174
- let deadline = performance.now() + 2;
175
- while (true) {
176
- if (signal?.aborted) {
177
- const failure = aborted();
178
- steps.return(failure);
179
- return failure;
180
- }
181
- const step = steps.next();
182
- if (step.done) return step.value instanceof Error ? step.value : schemaFromKeys(id, step.value);
183
- if (performance.now() >= deadline) {
184
- await yieldToHost();
185
- deadline = performance.now() + 2;
186
- }
187
- }
188
- } catch (cause) {
189
- return new UuidSlugError("invalid_mask_schema", "Mask schema construction failed.", { cause });
190
- }
191
- }
192
- /**
193
- * Refuse schemas that cannot undo these representative blocks. The reverse call must invert
194
- * the forward call; the same function need not be an involution. Finite probes are not a proof
195
- * over the full domain. Preserve each original input separately so a mutating callback cannot
196
- * rewrite the witness and make a destructive transformation appear reversible.
197
- */
198
- function verifyInvertible(schema) {
199
- const mixed = /* @__PURE__ */ new Uint8Array(16);
200
- const restored = /* @__PURE__ */ new Uint8Array(16);
201
- for (const probe of [/* @__PURE__ */ new Uint8Array(16), Uint8Array.from({ length: 16 }, (_, i) => i * 17)]) {
202
- try {
203
- schema.mix(probe.slice(), mixed, true);
204
- schema.mix(mixed, restored, false);
205
- } catch (cause) {
206
- return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" failed its invertibility check.`, { cause });
207
- }
208
- if (restored.some((byte, i) => byte !== probe[i])) return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" does not reverse its own mixing step.`);
209
- }
210
- return schema;
211
- }
212
- const DEFAULT_MASK_SCHEMA = feistelSchema("default", seedBytes("anizoptera.uuid-slug.default-mask.v1"), 1);
213
- //#endregion
214
- export { DEFAULT_MASK_SCHEMA, createMaskSchema, createMaskSchemaAsync, verifyInvertible };
@@ -1,106 +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/siphash.ts
4
- /**
5
- * HalfSipHash-2-4 with 64-bit output — the 32-bit-word member of the SipHash family (Aumasson and
6
- * Bernstein), transcribed from the reference implementation. It is a KEYED pseudorandom function:
7
- * without the key its output on a chosen input is not computable, which is exactly what `mix32` — a
8
- * fixed, public, unkeyed bijection — could never be, and the reason it replaced it.
9
- *
10
- * One primitive serves both callers that need one: the Feistel round function (`feistel.ts`) and the
11
- * key derivation (`schema.ts`). Neither justifies its own.
12
- *
13
- * Chosen over full SipHash-2-4 because that is defined over 64-bit words, which JavaScript has only
14
- * as `BigInt` or as hand-emulated 32-bit pairs — the first far too slow for a hot path, the second a
15
- * re-implementation whose errors nothing would catch. HalfSipHash is 32-bit BY SPECIFICATION, so
16
- * this is a transcription, and `test/siphash.test.ts` holds it to all 64 published vectors. That
17
- * external check is the whole reason a standard primitive beat anything tuned here: nothing in this
18
- * repository can grade a mixing function (see `feistel.ts` — every instrument here passes a
19
- * two-round network), so agreement with a specification somebody else wrote is the only evidence
20
- * available that can actually fail.
21
- *
22
- * Its key is 64 bits. `schema.ts` runs two independently keyed instances and XORs them, the standard
23
- * cascade for widening a PRF's key; see there.
24
- */
25
- /** Message-absorption rounds per block — the `2` of HalfSipHash-**2**-4. */
26
- const C_ROUNDS = 2;
27
- /** Finalisation rounds per output word — the `4` of HalfSipHash-2-**4**. */
28
- const D_ROUNDS = 4;
29
- /**
30
- * HalfSipHash-2-4 over a message supplied as 32-bit LITTLE-ENDIAN words, writing the two output
31
- * words into `out`.
32
- *
33
- * Words rather than bytes because both callers already hold words, and the specification absorbs the
34
- * message in 32-bit little-endian blocks regardless — so this is the same function with the byte
35
- * reassembly left to whoever actually has bytes. Taking a `Uint8Array` would make the hot path pack
36
- * bytes it had just unpacked.
37
- *
38
- * `byteLength` is the message length the specification hashes and stamps into the final block.
39
- * `words` must therefore hold `ceil(byteLength / 4)` entries, with any trailing 1-3 bytes packed
40
- * little-endian into the low bytes of the last one. Internal cooperative callers may pass a
41
- * positive block limit and resume the returned continuation with exactly the same inputs.
42
- */
43
- function halfSipHash(key0, key1, words, byteLength, out, continuation, blockLimit = Infinity) {
44
- let v0 = key0 | 0;
45
- let v1 = key1 ^ 238 | 0;
46
- let v2 = key0 ^ 1819895653 | 0;
47
- let v3 = key1 ^ 1952801890 | 0;
48
- if (continuation) ({v0, v1, v2, v3} = continuation);
49
- const fullWords = byteLength >>> 2;
50
- const spare = byteLength & 3;
51
- const tail = spare === 0 ? 0 : words[fullWords] & (1 << spare * 8) - 1;
52
- const lengthBlock = byteLength << 24 | tail | 0;
53
- const start = continuation?.block ?? 0;
54
- const end = blockLimit === Infinity ? fullWords : Math.min(fullWords, start + blockLimit - 1);
55
- for (let block = start; block <= end; block += 1) {
56
- const m = block === fullWords ? lengthBlock : words[block];
57
- v3 ^= m;
58
- for (let round = 0; round < C_ROUNDS; round += 1) {
59
- v0 = v0 + v1 | 0;
60
- v1 = v1 << 5 | v1 >>> 27;
61
- v1 ^= v0;
62
- v0 = v0 << 16 | v0 >>> 16;
63
- v2 = v2 + v3 | 0;
64
- v3 = v3 << 8 | v3 >>> 24;
65
- v3 ^= v2;
66
- v0 = v0 + v3 | 0;
67
- v3 = v3 << 7 | v3 >>> 25;
68
- v3 ^= v0;
69
- v2 = v2 + v1 | 0;
70
- v1 = v1 << 13 | v1 >>> 19;
71
- v1 ^= v2;
72
- v2 = v2 << 16 | v2 >>> 16;
73
- }
74
- v0 ^= m;
75
- }
76
- if (end < fullWords) return {
77
- block: end + 1,
78
- v0,
79
- v1,
80
- v2,
81
- v3
82
- };
83
- v2 ^= 238;
84
- for (let half = 0; half < 2; half += 1) {
85
- for (let round = 0; round < D_ROUNDS; round += 1) {
86
- v0 = v0 + v1 | 0;
87
- v1 = v1 << 5 | v1 >>> 27;
88
- v1 ^= v0;
89
- v0 = v0 << 16 | v0 >>> 16;
90
- v2 = v2 + v3 | 0;
91
- v3 = v3 << 8 | v3 >>> 24;
92
- v3 ^= v2;
93
- v0 = v0 + v3 | 0;
94
- v3 = v3 << 7 | v3 >>> 25;
95
- v3 ^= v0;
96
- v2 = v2 + v1 | 0;
97
- v1 = v1 << 13 | v1 >>> 19;
98
- v1 ^= v2;
99
- v2 = v2 << 16 | v2 >>> 16;
100
- }
101
- out[half] = v1 ^ v3;
102
- v1 ^= 221;
103
- }
104
- }
105
- //#endregion
106
- export { halfSipHash };