From c181a2367ae52b11bd80eb03106036ae5af698d7 Mon Sep 17 00:00:00 2001 From: Junil Kim Date: Mon, 9 Dec 2024 18:25:37 +0900 Subject: [PATCH] Fix: Add crypto-js for the case of missing crypto.subtle in the browser crypto.subtle is avaiable if the browser open the browser example in localhost or 127.0.0.1. But it is not available if the browser open the browser example in other ip address. So we need to add crypto-js for the case of missing crypto.subtle in the browser. --- clients/js/examples/browser/app.tsx | 14 +++++++++++++- clients/js/examples/browser/package.json | 1 + clients/js/examples/browser/vite.config.mjs | 1 + 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/clients/js/examples/browser/app.tsx b/clients/js/examples/browser/app.tsx index c70fdac96f9..e9fd3e98072 100644 --- a/clients/js/examples/browser/app.tsx +++ b/clients/js/examples/browser/app.tsx @@ -1,6 +1,7 @@ import React, { useCallback, useEffect, useState } from "react"; import { ChromaClient } from "../../src/ChromaClient"; import { Collection } from "../../src/types"; +import CryptoJS from "crypto-js"; const SAMPLE_DOCUMENTS = [ "apple", @@ -14,7 +15,18 @@ const SAMPLE_DOCUMENTS = [ const hashString = async (message: string) => { const encoder = new TextEncoder(); const data = encoder.encode(message); - const hashBuffer = await crypto.subtle.digest("SHA-256", data); + let hashBuffer; + if (crypto.subtle) { + hashBuffer = await crypto.subtle.digest("SHA-256", data); + } else { + const hash = CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(message)); + hashBuffer = new Uint8Array(hash.words.map(word => [ + (word >> 24) & 0xff, + (word >> 16) & 0xff, + (word >> 8) & 0xff, + word & 0xff + ]).flat()); + } const hashArray = Array.from(new Uint8Array(hashBuffer)); return hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); }; diff --git a/clients/js/examples/browser/package.json b/clients/js/examples/browser/package.json index 4ff2cd56bce..4498641b41a 100644 --- a/clients/js/examples/browser/package.json +++ b/clients/js/examples/browser/package.json @@ -16,6 +16,7 @@ }, "dependencies": { "chromadb": "link:../..", + "crypto-js": "^4.2.0", "react": "^18.2.0", "react-dom": "^18.2.0" }, diff --git a/clients/js/examples/browser/vite.config.mjs b/clients/js/examples/browser/vite.config.mjs index 34725b4d444..9ecf11686d0 100644 --- a/clients/js/examples/browser/vite.config.mjs +++ b/clients/js/examples/browser/vite.config.mjs @@ -5,6 +5,7 @@ import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], server: { + host: "0.0.0.0", port: 3000, }, // This manual remapping is only needed because we're loading a locally linked version of the JS client