Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(media): no require in mjs modules #473

Merged
merged 9 commits into from
Nov 28, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions langfuse-core/src/media/LangfuseMedia.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
let fs: any = null;
let cryptoModule: any = null;
let crypto: any = null;

if (typeof process !== "undefined" && process.versions?.node) {
// Use wrapper to prevent bundlers from trying to resolve the dynamic import
// Otherwise, the import will be incorrectly resolved as a static import even though it's dynamic
// Test for browser environment would fail because the import will be incorrectly resolved as a static import and fs and crypto will be unavailable
const dynamicImport = (module: string): Promise<any> => {
return import(module);
};

// Node
try {
fs = require("fs");
cryptoModule = require("crypto");
} catch (error) {
console.error("Error loading crypto or fs module", error);
}
} else if (typeof crypto !== "undefined") {
// Edge Runtime, Cloudflare Workers, etc.
cryptoModule = crypto;
Promise.all([dynamicImport("fs"), dynamicImport("crypto")])
.then(([fsModule, cryptoModule]) => {
fs = fsModule;
crypto = cryptoModule;
})
.catch((error) => {
console.error("Error loading crypto or fs module", error);
});
}

import { type MediaContentType } from "../types";
Expand Down Expand Up @@ -128,12 +134,12 @@ class LangfuseMedia {
return undefined;
}

if (!cryptoModule) {
if (!crypto) {
console.error("Crypto support is not available in this environment");
return undefined;
}
hassiebp marked this conversation as resolved.
Show resolved Hide resolved

const sha256Hash = cryptoModule.createHash("sha256").update(this._contentBytes).digest("base64");
const sha256Hash = crypto.createHash("sha256").update(this._contentBytes).digest("base64");
return sha256Hash;
}

Expand Down
Loading