@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,25 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
-
3
- import { UuidSlugError } from "./errors";
4
-
5
- // These tables and the four-bit checksum define the original wire format.
6
- // Changing them would change the UUID recovered from an existing slug.
7
- const PERMUTE = [9, 13, 3, 8, 14, 0, 11, 7, 6, 1, 15, 4, 2, 5, 10, 12] as const;
8
- const XOR = [
9
- 0xa2, 0x70, 0x32, 0x7f, 0x98, 0xb8, 0x9b, 0x5e, 0x1b, 0x26, 0xb6, 0x16, 0x96, 0xf9, 0xea, 0x3e,
10
- ] as const;
11
-
12
- /** Return a matching candidate or undefined; callers resolve sentinels before trying masks. */
13
- export function decodeOriginalMask(mixed: Uint8Array): Uint8Array | UuidSlugError | undefined {
14
- if (mixed.length !== 16)
15
- return new UuidSlugError("invalid_buffer", "Original masked slugs require 16 decoded bytes.");
16
- const bytes = new Uint8Array(16);
17
- for (let i = 0; i < 16; i++)
18
- bytes[PERMUTE[i] as number] = (mixed[i] as number) ^ (XOR[i] as number);
19
- const found = (bytes[6] as number) >>> 4;
20
- bytes[6] = ((bytes[6] as number) & 15) | 0x70;
21
- let checksum = 0;
22
- for (const byte of bytes) checksum ^= byte;
23
- // A mismatch is expected while trying formats; allocate diagnostics only if the reader fails.
24
- return ((checksum >>> 4) ^ (checksum & 15)) === found ? bytes : undefined;
25
- }
@@ -1,48 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
-
3
- import { UuidRuntimeError } from "../errors";
4
- import { pooledFill } from "./pool";
5
- import type { Runtime } from "./types";
6
-
7
- /**
8
- * Resolve Web Crypto per draw so instrumentation installed after import can observe the source.
9
- * Binding it at module load would bypass `test/instrument.ts` and hide those calls from the gate.
10
- */
11
- function cryptoObject(): Crypto {
12
- const value = globalThis.crypto;
13
- if (!value?.getRandomValues)
14
- throw new UuidRuntimeError("Web Crypto getRandomValues is unavailable.");
15
- return value;
16
- }
17
-
18
- const runtimeCapabilities: Runtime = {
19
- /**
20
- * Pooled for the same reason as Node's: `getRandomValues` costs far more per call than per
21
- * byte, and a v7 id needs 16. Bun draws this path too, where pooling measured 16x.
22
- */
23
- fillRandom: pooledFill((into) => {
24
- cryptoObject().getRandomValues(into);
25
- }),
26
- };
27
-
28
- /**
29
- * `randomUUID` is probed ONCE here and the method left undefined when it is absent — the rule
30
- * `runtime/node.ts` already follows and the reason `Runtime`'s methods are optional.
31
- *
32
- * It is not the same capability as `getRandomValues`, and a browser can have one without the
33
- * other: `crypto.randomUUID` is restricted to secure contexts, `getRandomValues` is not. Defined
34
- * unconditionally with a throw inside, `uuidV4()` was the only one of four entry points that
35
- * failed on such a page — `uuidV4Slug`, `uuidV4Bytes` and `uuidV7` all answered, because they
36
- * reach the byte generator rather than this method. Leaving it undefined routes `uuidV4` to that
37
- * same generator, so the four agree.
38
- */
39
- /*
40
- * Probed through `Partial<Crypto>` because the DOM lib declares `randomUUID` as always present,
41
- * so the plain condition is "always true" to the compiler (TS2774) while being false on any
42
- * insecure page. The cast states the divergence rather than suppressing it: the types describe a
43
- * secure context, the check describes every context.
44
- */
45
- if ((globalThis.crypto as Partial<Crypto> | undefined)?.randomUUID)
46
- runtimeCapabilities.uuidV4 = () => cryptoObject().randomUUID();
47
-
48
- export const runtime: Runtime = runtimeCapabilities;
package/src/schema.ts DELETED
@@ -1,300 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
-
3
- import { UuidSlugError } from "./errors";
4
- import { FEISTEL_KEY_WORDS, feistel16 } from "./feistel";
5
- import { halfSipHash } from "./siphash";
6
- import type { HashContinuation } from "./siphash";
7
- import { yieldToHost } from "./yield";
8
- import type { AsyncMaskSchemaOptions, MaskSchema, MaskSchemaOptions } from "./types";
9
-
10
- /** Reject short seeds early; length alone cannot make a chosen secret unpredictable. */
11
- const SEED_MIN_BYTES = 16;
12
-
13
- /** Bound accidental work-factor typos; construction cost still depends on the runtime and seed. */
14
- const MAX_KEY_ITERATIONS = 1 << 24;
15
-
16
- /**
17
- * Initial keys for the two derivation chains, nothing-up-my-sleeve: the little-endian ASCII of
18
- * "uuid" with "slgA" and "slgB", so a reader can check they conceal no chosen structure.
19
- *
20
- * Their VALUES are arbitrary. Their STABILITY is wire-format-bearing — any other numbers give every
21
- * seed different round keys and make every masked slug ever issued undecodable.
22
- */
23
- const CHAIN_A_KEY1 = 0x41676c73;
24
- const CHAIN_B_KEY1 = 0x42676c73;
25
- const CHAIN_KEY0 = 0x64697575;
26
-
27
- function seedBytes(seed: string | Uint8Array) {
28
- if (typeof seed !== "string") return new Uint8Array(seed);
29
- return new TextEncoder().encode(seed);
30
- }
31
-
32
- /** Repack bytes as the little-endian 32-bit words `halfSipHash` absorbs. */
33
- function seedWords(seed: Uint8Array) {
34
- const words = new Int32Array(Math.ceil(seed.length / 4) + 1);
35
- writeSeedWords(seed, words);
36
- return words;
37
- }
38
-
39
- /** Pack one byte range; a running byte offset also handles UTF-8 chunks ending mid-word. */
40
- function writeSeedWords(
41
- seed: Uint8Array,
42
- words: Int32Array,
43
- offset = 0,
44
- start = 0,
45
- end = seed.length,
46
- ) {
47
- for (let index = start; index < end; index += 1) {
48
- const absolute = offset + index;
49
- words[absolute >>> 2] =
50
- (words[absolute >>> 2] as number) | ((seed[index] as number) << ((absolute & 3) * 8));
51
- }
52
- }
53
-
54
- /**
55
- * Hash the seed under successive outputs, for `iterations` total hashes. This work is paid
56
- * at construction, never per id. The count changes key material and must remain stable for
57
- * issued slugs; retain the old count with its seed when rotating schemas.
58
- */
59
- function chain(key0: number, key1: number, words: Int32Array, length: number, iterations: number) {
60
- const out = new Int32Array(2);
61
- halfSipHash(key0, key1, words, length, out);
62
- for (let i = 1; i < iterations; i += 1)
63
- halfSipHash(out[0] as number, out[1] as number, words, length, out);
64
- return out;
65
- }
66
-
67
- /**
68
- * Derive each round key by XORing outputs from two fixed derivation chains. Their combined
69
- * state is 128 bits; that representation does not establish 128-bit security. Chain constants,
70
- * word indices and byte order are frozen by the issued wire format.
71
- */
72
- function derivedKeys(seed: Uint8Array, iterations: number) {
73
- const words = seedWords(seed);
74
- const chainA = chain(CHAIN_KEY0, CHAIN_A_KEY1, words, seed.length, iterations);
75
- const chainB = chain(CHAIN_KEY0, CHAIN_B_KEY1, words, seed.length, iterations);
76
- return roundKeys(chainA, chainB);
77
- }
78
-
79
- /** The same final key expansion follows synchronous and cooperative derivation. */
80
- function roundKeys(chainA: Int32Array, chainB: Int32Array) {
81
- const keys = new Int32Array(FEISTEL_KEY_WORDS);
82
- const index = new Int32Array(1);
83
- const fromA = new Int32Array(2);
84
- const fromB = new Int32Array(2);
85
- for (let word = 0; word < FEISTEL_KEY_WORDS; word += 2) {
86
- index[0] = word;
87
- halfSipHash(chainA[0] as number, chainA[1] as number, index, 4, fromA);
88
- halfSipHash(chainB[0] as number, chainB[1] as number, index, 4, fromB);
89
- keys[word] = (fromA[0] as number) ^ (fromB[0] as number);
90
- keys[word + 1] = (fromA[1] as number) ^ (fromB[1] as number);
91
- }
92
- return keys;
93
- }
94
-
95
- function feistelSchema(id: string, seed: Uint8Array, iterations: number): MaskSchema {
96
- return schemaFromKeys(id, derivedKeys(seed, iterations));
97
- }
98
-
99
- function schemaFromKeys(id: string, keys: Int32Array): MaskSchema {
100
- return {
101
- id,
102
- mix(input, output, forward) {
103
- feistel16(input, 0, keys, forward, output, 0);
104
- },
105
- };
106
- }
107
-
108
- export function createMaskSchema(options: MaskSchemaOptions): UuidSlugError | MaskSchema {
109
- const seed = seedBytes(options.seed);
110
- const short = invalidSeedLength(seed.length);
111
- if (short) return short;
112
- const iterations = options.keyIterations ?? 1;
113
- const invalid = invalidIterations(iterations);
114
- if (invalid) return invalid;
115
- return feistelSchema(options.id ?? "seeded", seed, iterations);
116
- }
117
-
118
- function invalidSeedLength(length: number): UuidSlugError | undefined {
119
- if (length < SEED_MIN_BYTES)
120
- return new UuidSlugError(
121
- "invalid_mask_schema",
122
- `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.`,
123
- );
124
- return undefined;
125
- }
126
-
127
- function invalidIterations(iterations: number): UuidSlugError | undefined {
128
- if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_KEY_ITERATIONS)
129
- return new UuidSlugError(
130
- "invalid_mask_schema",
131
- `Mask keyIterations must be a whole number in 1..${MAX_KEY_ITERATIONS}, got ${String(iterations)}.`,
132
- );
133
- return undefined;
134
- }
135
-
136
- /** Bounded byte work between checkpoints, independent of total seed size or iteration count. */
137
- const CHUNK_BYTES = 4096;
138
-
139
- function* cooperativeChain(
140
- key0: number,
141
- key1: number,
142
- words: Int32Array,
143
- length: number,
144
- iterations: number,
145
- ): Generator<void, Int32Array, void> {
146
- const out = new Int32Array(2);
147
- out[0] = key0;
148
- out[1] = key1;
149
- const hashesPerChunk = Math.max(1, Math.floor(CHUNK_BYTES / (length + 4)));
150
- let sinceCheckpoint = 0;
151
- for (let i = 0; i < iterations; i += 1) {
152
- let continuation: HashContinuation | undefined;
153
- do {
154
- continuation = halfSipHash(out[0], out[1], words, length, out, continuation, CHUNK_BYTES / 4);
155
- if (continuation) yield;
156
- } while (continuation);
157
- sinceCheckpoint += 1;
158
- if (sinceCheckpoint >= hashesPerChunk) {
159
- sinceCheckpoint = 0;
160
- yield;
161
- }
162
- }
163
- return out;
164
- }
165
-
166
- function* cooperativeKeys(
167
- seed: string | Uint8Array,
168
- iterations: number,
169
- ): Generator<void, Int32Array | UuidSlugError, void> {
170
- // Byte seeds were snapshotted before suspension. Strings are immutable, so encoding can yield.
171
- const chunks: Uint8Array[] = [];
172
- let length = 0;
173
- if (typeof seed === "string") {
174
- const encoder = new TextEncoder();
175
- for (let start = 0; start < seed.length;) {
176
- let end = Math.min(seed.length, start + CHUNK_BYTES);
177
- // Do not split a surrogate pair: encoding either half alone would substitute U+FFFD.
178
- const last = seed.charCodeAt(end - 1);
179
- const next = seed.charCodeAt(end);
180
- if (end < seed.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff)
181
- end -= 1;
182
- const bytes = encoder.encode(seed.slice(start, end));
183
- chunks.push(bytes);
184
- length += bytes.length;
185
- start = end;
186
- yield;
187
- }
188
- } else {
189
- chunks.push(seed);
190
- length = seed.length;
191
- }
192
- const short = invalidSeedLength(length);
193
- if (short) return short;
194
- const words = new Int32Array(Math.ceil(length / 4) + 1);
195
- let offset = 0;
196
- for (const bytes of chunks) {
197
- for (let start = 0; start < bytes.length; start += CHUNK_BYTES) {
198
- writeSeedWords(bytes, words, offset, start, Math.min(bytes.length, start + CHUNK_BYTES));
199
- yield;
200
- }
201
- offset += bytes.length;
202
- }
203
- chunks.length = 0;
204
- const chainA = yield* cooperativeChain(CHAIN_KEY0, CHAIN_A_KEY1, words, length, iterations);
205
- const chainB = yield* cooperativeChain(CHAIN_KEY0, CHAIN_B_KEY1, words, length, iterations);
206
- return roundKeys(chainA, chainB);
207
- }
208
-
209
- /**
210
- * Derive the same schema while allowing other host tasks to run. Options and byte contents are
211
- * captured before suspension; cancellation returns an `aborted` error with the signal's reason
212
- * as its cause. Checkpoints stop computation rather than racing a still-running derivation.
213
- *
214
- * Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,
215
- * not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations
216
- * need no host yield. Passing the result as a codec's `mask` avoids deriving it again.
217
- */
218
- export async function createMaskSchemaAsync(
219
- options: AsyncMaskSchemaOptions,
220
- ): Promise<MaskSchema | UuidSlugError> {
221
- try {
222
- const { signal } = options;
223
- const aborted = () =>
224
- new UuidSlugError("aborted", "Mask schema construction was aborted.", {
225
- cause: signal?.reason,
226
- });
227
- if (signal?.aborted) return aborted();
228
- const { seed: input, keyIterations = 1, id = "seeded" } = options;
229
- const invalid = invalidIterations(keyIterations);
230
- if (invalid) return invalid;
231
- const seed = typeof input === "string" ? input : new Uint8Array(input);
232
- const steps = cooperativeKeys(seed, keyIterations);
233
- let deadline = performance.now() + 2;
234
- while (true) {
235
- if (signal?.aborted) {
236
- const failure = aborted();
237
- steps.return(failure);
238
- return failure;
239
- }
240
- const step = steps.next();
241
- if (step.done)
242
- return step.value instanceof Error ? step.value : schemaFromKeys(id, step.value);
243
- if (performance.now() >= deadline) {
244
- // eslint-disable-next-line no-await-in-loop -- each slice must yield before continuing the dependent derivation
245
- await yieldToHost();
246
- deadline = performance.now() + 2;
247
- }
248
- }
249
- } catch (cause) {
250
- return new UuidSlugError("invalid_mask_schema", "Mask schema construction failed.", { cause });
251
- }
252
- }
253
-
254
- /**
255
- * Refuse schemas that cannot undo these representative blocks. The reverse call must invert
256
- * the forward call; the same function need not be an involution. Finite probes are not a proof
257
- * over the full domain. Preserve each original input separately so a mutating callback cannot
258
- * rewrite the witness and make a destructive transformation appear reversible.
259
- */
260
- export function verifyInvertible(schema: MaskSchema): UuidSlugError | MaskSchema {
261
- const mixed = new Uint8Array(16);
262
- const restored = new Uint8Array(16);
263
- for (const probe of [new Uint8Array(16), Uint8Array.from({ length: 16 }, (_, i) => i * 17)]) {
264
- try {
265
- schema.mix(probe.slice(), mixed, true);
266
- schema.mix(mixed, restored, false);
267
- } catch (cause) {
268
- return new UuidSlugError(
269
- "invalid_mask_schema",
270
- `Mask schema "${schema.id}" failed its invertibility check.`,
271
- { cause },
272
- );
273
- }
274
- if (restored.some((byte, i) => byte !== probe[i]))
275
- return new UuidSlugError(
276
- "invalid_mask_schema",
277
- `Mask schema "${schema.id}" does not reverse its own mixing step.`,
278
- );
279
- }
280
- return schema;
281
- }
282
-
283
- /**
284
- * A PUBLIC key. It ships in the tarball, so every masked slug produced under it is decodable by
285
- * anyone who installed this package, and it therefore provides none of the obscurity masking
286
- * exists for.
287
- *
288
- * It is exported rather than hidden so that choosing it can be DELIBERATE: a test or demo wanting
289
- * byte-identical output across machines writes `mask: DEFAULT_MASK_SCHEMA` and says so at the call
290
- * site. The hazard is the SILENT path — `createUuidSlugCodec()` with no `mask` lands here without
291
- * the caller writing anything — which is why that fallback and `defaultCodec` both carry the same
292
- * warning, and why the masked methods are not exported as bare functions.
293
- */
294
- const DEFAULT_SEED = "anizoptera.uuid-slug.default-mask.v1";
295
-
296
- // Built from `feistelSchema` rather than through `createMaskSchema`, whose failures are a short seed and a
297
- // bad iteration count — checks on CALLER input that the literals here cannot fail. Routing through it would return
298
- // `UuidSlugError | MaskSchema` and force a cast that, at module scope, could only ever hide a real Error
299
- // behind a `MaskSchema` type for every default codec in the process.
300
- export const DEFAULT_MASK_SCHEMA: MaskSchema = feistelSchema("default", seedBytes(DEFAULT_SEED), 1);
package/src/yield.ts DELETED
@@ -1,22 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
-
3
- const host = globalThis as {
4
- setImmediate?: (callback: () => void) => unknown;
5
- };
6
- const immediate = host.setImmediate?.bind(host);
7
-
8
- /** Yield to a host task so timers, input and cancellation can run; a microtask would starve them. */
9
- export function yieldToHost(): Promise<void> {
10
- // Prioritized scheduler continuations can overtake queued cancellation tasks in browsers.
11
- if (immediate) return new Promise((resolve) => immediate(resolve));
12
- return new Promise((resolve) => {
13
- const channel = new MessageChannel();
14
- // eslint-disable-next-line unicorn/prefer-add-event-listener -- this private port has one handler; assignment also starts delivery
15
- channel.port1.onmessage = () => {
16
- channel.port1.close();
17
- channel.port2.close();
18
- resolve();
19
- };
20
- channel.port2.postMessage(null);
21
- });
22
- }