|
| 1 | +import { uuid } from "./utils"; |
| 2 | + |
| 3 | +interface WorkerMessage { |
| 4 | + requestId: string; |
| 5 | + targetSizeInBytes: number; |
| 6 | + seed: string; |
| 7 | +} |
| 8 | + |
| 9 | +interface WorkerResponse { |
| 10 | + requestId: string; |
| 11 | + text: string; |
| 12 | +} |
| 13 | + |
| 14 | +/** |
| 15 | + * Generates the Worker code as a string using the Function.prototype.toString() strategy. |
| 16 | + * This ensures that the Worker code is self-contained and not transformed by the bundler. |
| 17 | + * The worker code is written as a function and then converted to a string. |
| 18 | + */ |
| 19 | +function generateTextOfSizeWorkerCode(): string { |
| 20 | + const workerFunction = () => { |
| 21 | + // Define types for internal worker usage |
| 22 | + interface WorkerMessage { |
| 23 | + requestId: string; |
| 24 | + targetSizeInBytes: number; |
| 25 | + seed: string; |
| 26 | + } |
| 27 | + |
| 28 | + interface WorkerResponse { |
| 29 | + requestId: string; |
| 30 | + text: string; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Utility function to convert a seed string into a numerical hash. |
| 35 | + * |
| 36 | + * @param str - The seed string to hash. |
| 37 | + * @returns A numerical hash derived from the input string. |
| 38 | + */ |
| 39 | + function hashCode(str: string): number { |
| 40 | + let hash = 0; |
| 41 | + for (let i = 0; i < str.length; i++) { |
| 42 | + hash = (hash * 31 + str.charCodeAt(i)) >>> 0; // Ensure unsigned 32-bit integer |
| 43 | + } |
| 44 | + return hash; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Seeded pseudo-random number generator using Linear Congruential Generator (LCG). |
| 49 | + * |
| 50 | + * @param seed - The seed string to initialize the generator. |
| 51 | + * @returns A function that generates a pseudo-random number between 0 (inclusive) and 1 (exclusive). |
| 52 | + */ |
| 53 | + function seededRandom(seed: string): () => number { |
| 54 | + let state: number = hashCode(seed); |
| 55 | + const a: number = 1664525; |
| 56 | + const c: number = 1013904223; |
| 57 | + const m: number = 2 ** 32; |
| 58 | + |
| 59 | + /** |
| 60 | + * Generates the next pseudo-random number in the sequence. |
| 61 | + * |
| 62 | + * @returns A pseudo-random number between 0 (inclusive) and 1 (exclusive). |
| 63 | + */ |
| 64 | + function random(): number { |
| 65 | + state = (a * state + c) >>> 0; // Update state with LCG formula |
| 66 | + return state / m; |
| 67 | + } |
| 68 | + |
| 69 | + return random; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Calculates the byte size of a string using UTF-8 encoding. |
| 74 | + * |
| 75 | + * @param str - The string whose byte size is to be calculated. |
| 76 | + * @returns The byte size of the input string. |
| 77 | + */ |
| 78 | + function calculateByteSize(str: string): number { |
| 79 | + return new TextEncoder().encode(str).length; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Listener for messages from the main thread. |
| 84 | + * Generates a deterministic random text string based on the provided seed and target size. |
| 85 | + */ |
| 86 | + self.onmessage = (event: MessageEvent): void => { |
| 87 | + const data: WorkerMessage = event.data; |
| 88 | + const { requestId, targetSizeInBytes, seed } = data; |
| 89 | + |
| 90 | + const rand: () => number = seededRandom(seed); |
| 91 | + const estimatedChars: number = Math.ceil(targetSizeInBytes); |
| 92 | + const charArray: string[] = new Array(estimatedChars); |
| 93 | + |
| 94 | + for (let i = 0; i < estimatedChars; i++) { |
| 95 | + // Generate a random printable ASCII character (codes 33 to 126) |
| 96 | + charArray[i] = String.fromCharCode(33 + Math.floor(rand() * 94)); |
| 97 | + } |
| 98 | + |
| 99 | + let result: string = charArray.join(""); |
| 100 | + |
| 101 | + // Ensure the generated result matches the exact target size |
| 102 | + while (calculateByteSize(result) > targetSizeInBytes) { |
| 103 | + result = result.slice(0, -1); |
| 104 | + } |
| 105 | + |
| 106 | + const response: WorkerResponse = { requestId, text: result }; |
| 107 | + // Send the generated text back to the main thread |
| 108 | + postMessage(response); |
| 109 | + }; |
| 110 | + }; |
| 111 | + |
| 112 | + // Convert the worker function to a string and invoke it immediately |
| 113 | + return `(${workerFunction.toString()})();`; |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * Creates a Web Worker from a given code string by converting it to a Blob URL. |
| 118 | + * |
| 119 | + * @param code The Worker code as a string. |
| 120 | + * @returns A new Worker instance. |
| 121 | + */ |
| 122 | +function createWorkerFromCode(code: string): Worker { |
| 123 | + const blob: Blob = new Blob([code], { type: "application/javascript" }); |
| 124 | + const blobURL: string = URL.createObjectURL(blob); |
| 125 | + return new Worker(blobURL); |
| 126 | +} |
| 127 | + |
| 128 | +/** |
| 129 | + * Asynchronously generates a deterministic random text string of a specified byte size |
| 130 | + * by offloading the task to a Web Worker. Supports multiple concurrent requests using requestId. |
| 131 | + * |
| 132 | + * @param targetSizeInBytes The desired byte size of the generated string. |
| 133 | + * @param seed Optional seed for the random number generator. Defaults to "default". |
| 134 | + * @returns A Promise that resolves to the generated string. |
| 135 | + */ |
| 136 | +export async function generateTextOfSize( |
| 137 | + targetSizeInBytes: number, |
| 138 | + seed = "default" |
| 139 | +): Promise<string> { |
| 140 | + return new Promise<string>((resolve, reject) => { |
| 141 | + const requestId: string = uuid(); |
| 142 | + |
| 143 | + // Generate the worker code and create a new worker |
| 144 | + const workerCode: string = generateTextOfSizeWorkerCode(); |
| 145 | + const worker: Worker = createWorkerFromCode(workerCode); |
| 146 | + |
| 147 | + /** |
| 148 | + * Handler for messages from the worker. |
| 149 | + * Resolves the promise if the response matches the requestId. |
| 150 | + */ |
| 151 | + const handleMessage = (event: MessageEvent): void => { |
| 152 | + const data: WorkerResponse = event.data; |
| 153 | + if (data.requestId === requestId) { |
| 154 | + resolve(data.text); |
| 155 | + cleanup(); |
| 156 | + } |
| 157 | + }; |
| 158 | + |
| 159 | + /** |
| 160 | + * Handler for errors from the worker. |
| 161 | + * Rejects the promise and cleans up the worker. |
| 162 | + */ |
| 163 | + const handleError = (error: ErrorEvent): void => { |
| 164 | + reject(error); |
| 165 | + cleanup(); |
| 166 | + }; |
| 167 | + |
| 168 | + /** |
| 169 | + * Cleans up event listeners and terminates the worker. |
| 170 | + */ |
| 171 | + const cleanup = (): void => { |
| 172 | + worker.removeEventListener("message", handleMessage); |
| 173 | + worker.removeEventListener("error", handleError); |
| 174 | + worker.terminate(); |
| 175 | + }; |
| 176 | + |
| 177 | + // Attach event listeners |
| 178 | + worker.addEventListener("message", handleMessage); |
| 179 | + worker.addEventListener("error", handleError); |
| 180 | + |
| 181 | + // Send the message with the requestId |
| 182 | + const message: WorkerMessage = { requestId, targetSizeInBytes, seed }; |
| 183 | + worker.postMessage(message); |
| 184 | + }); |
| 185 | +} |
0 commit comments