Skip to content

Commit 3689d59

Browse files
authored
fix: improve createHmacSignatureAsync compatibility with worker-based environments (#573)
Worker-based environments (e.g. `jest` tests) do not have access to `globalThis.require()` (while calling `require()` instead works). Deeper investigation shows that `tsup` doesn't transpile this in a dangerous way, so we can use this here. Unblocks apify/apify-client-js#782 (tested) Unblocks failing tests in #570
1 parent c0b8030 commit 3689d59

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

packages/utilities/src/hmac.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,18 @@ let subtleCrypto = globalThis.crypto?.subtle;
4141

4242
async function ensureSubtleCryptoExists() {
4343
if (!subtleCrypto) {
44-
if (globalThis.require) {
45-
subtleCrypto = globalThis.require('node:crypto')?.webcrypto?.subtle;
46-
} else {
44+
try {
45+
// eslint-disable-next-line @typescript-eslint/no-require-imports, global-require -- Backward compatibility for Node.js versions < 19
46+
subtleCrypto = require('node:crypto')?.webcrypto?.subtle;
47+
if (subtleCrypto) return;
48+
} catch {
49+
// Ignore require error
50+
}
51+
52+
try {
4753
subtleCrypto = (await import('node:crypto'))?.webcrypto?.subtle as SubtleCrypto;
54+
} catch {
55+
// Ignore import error
4856
}
4957

5058
if (!subtleCrypto) {

0 commit comments

Comments
 (0)