@@ -37,11 +37,22 @@ export function createHmacSignature(secretKey: string, message: string): string
3737 return encodeBase62 ( BigInt ( `0x${ signature } ` ) ) ;
3838}
3939
40- let webcrypto = globalThis . crypto ?. subtle ;
40+ let subtleCrypto = globalThis . crypto ?. subtle ;
4141
42- async function ensureCryptoSubtleExists ( ) {
43- // this might happen in Node.js versions < 19
44- webcrypto ??= ( await import ( 'node:crypto' ) ) . webcrypto . subtle as typeof webcrypto ;
42+ async function ensureSubtleCryptoExists ( ) {
43+ if ( ! subtleCrypto ) {
44+ if ( globalThis . require ) {
45+ subtleCrypto = globalThis . require ( 'node:crypto' ) ?. webcrypto ?. subtle ;
46+ } else {
47+ subtleCrypto = ( await import ( 'node:crypto' ) ) ?. webcrypto ?. subtle as SubtleCrypto ;
48+ }
49+
50+ if ( ! subtleCrypto ) {
51+ throw new Error ( `SubtleCrypto is not available in this environment.
52+ Please ensure you're running in an environment that supports Web Crypto API,
53+ or submit an issue to https://github.com/apify/apify-shared-js so we can help you further.` ) ;
54+ }
55+ }
4556}
4657
4758/**
@@ -53,18 +64,18 @@ async function ensureCryptoSubtleExists() {
5364 * @returns Promise<string>
5465 */
5566export async function createHmacSignatureAsync ( secretKey : string , message : string ) : Promise < string > {
56- await ensureCryptoSubtleExists ( ) ;
67+ await ensureSubtleCryptoExists ( ) ;
5768 const encoder = new TextEncoder ( ) ;
5869
59- const key = await webcrypto . importKey (
70+ const key = await subtleCrypto . importKey (
6071 'raw' ,
6172 encoder . encode ( secretKey ) ,
6273 { name : 'HMAC' , hash : 'SHA-256' } ,
6374 false ,
6475 [ 'sign' ] ,
6576 ) ;
6677
67- const signatureBuffer = await webcrypto . sign (
78+ const signatureBuffer = await subtleCrypto . sign (
6879 'HMAC' ,
6980 key ,
7081 encoder . encode ( message ) ,
0 commit comments