Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

chore: Add nanoid hash function (#3618)

Ivan Starkov7a8b84959180
diff --git a/apps/builder/app/shared/nano-hash.test.ts b/apps/builder/app/shared/nano-hash.test.ts
new file mode 100644
index 0000000000..fa7cf5926e
--- /dev/null
+++ b/apps/builder/app/shared/nano-hash.test.ts
@@ -0,0 +1,10 @@
+import { expect, test } from "@jest/globals";
+import { nanoHash } from "./nano-hash";
+
+test("NanoHash Equal", async () => {
+ expect(await nanoHash("hello")).toEqual(await nanoHash("hello"));
+});
+
+test("NanoHash Not Equal", async () => {
+ expect(await nanoHash("hello")).not.toEqual(await nanoHash("world"));
+});
diff --git a/apps/builder/app/shared/nano-hash.ts b/apps/builder/app/shared/nano-hash.ts
new file mode 100644
index 0000000000..c085832be0
--- /dev/null
+++ b/apps/builder/app/shared/nano-hash.ts
@@ -0,0 +1,18 @@
+import { customRandom } from "nanoid";
+
+// https://github.com/ai/nanoid/blob/main/url-alphabet/index.js
+const alphabet =
+ "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
+const NANOID_DEFAULT_SIZE = 21;
+
+// Generates hash strings using the same alphabet as nanoid
+export const nanoHash = async (data: string) => {
+ const encoder = new TextEncoder();
+ const dataBuffer = encoder.encode(data);
+ const hashBuffer = await crypto.subtle.digest("SHA-256", dataBuffer);
+ return customRandom(
+ alphabet,
+ NANOID_DEFAULT_SIZE,
+ () => new Uint8Array(hashBuffer)
+ )();
+};