scttcper / torrent-file

TypeScript torrent file parser
MIT License
11 stars 2 forks source link

bug: unable to build nextjs application with @ctrl/qbittorrent #76

Closed Meierschlumpf closed 2 months ago

Meierschlumpf commented 2 months ago

Hey, hope you have a good weekend. I wanted to report a bug where we get the following error during build with nextjs:

Failed to compile.

static/media/thread.4bee11a3.js from Terser
  x 'import', and 'export' cannot be used outside of module code
   ,-[1:1]
 1 | import crypto from 'node:crypto';
   : ^^^^^^
 2 | import {parentPort} from 'node:worker_threads';
 3 |
 4 | parentPort.on('message', ({id, value: {algorithm, buffer}}) => {
   `----

Caused by:
    0: failed to parse input file
    1: Syntax Error
Error:
  x 'import', and 'export' cannot be used outside of module code
   ,-[1:1]
 1 | import crypto from 'node:crypto';
   : ^^^^^^
 2 | import {parentPort} from 'node:worker_threads';
 3 |
 4 | parentPort.on('message', ({id, value: {algorithm, buffer}}) => {
   `----

Caused by:
    0: failed to parse input file
    1: Syntax Error

> Build failed because of webpack errors
 ELIFECYCLE  Command failed with exit code 1.
 ELIFECYCLE  Command failed with exit code 1.

After digging for about 6 hours we were able to link it to crypto-hash and would like to suggest a small change:

Here you can find people having the same issue with crypto-hash: https://stackoverflow.com/questions/77541075/when-i-try-to-push-my-project-in-build-i-got-a-below-error-in-next-js

We would suggest to try it out with the method provided in the stack overflow post. I think it's mostly related to esm / cjs support of the library.

So instead of the usage

import { sha1 } from 'crypto-hash';
import { isUint8Array, uint8ArrayToHex, uint8ArrayToString } from 'uint8array-extras';

import { decode, encode } from './bencode/index.js';

/**
 * sha1 of torrent file info. This hash is commenly used by torrent clients as the ID of the torrent.
 */
export async function hash(file: Uint8Array): Promise<string> {
  const torrent: any = decode(file);
  return sha1(encode(torrent.info));
}

I would suggest something like this to replace the import:

import { createHash } from "crypto";

function sha1(arrayBuffer: ArrayBuffer): Promise<string> {
  const buffer = Buffer.from(arrayBuffer);
  const hash = createHash("sha1");
  hash.update(buffer);
  return Promise.resolve(hash.digest("hex"));
}

And to remove the crypto-hash dependency.

If you have any questions let me know!

scttcper commented 2 months ago

@Meierschlumpf thanks for opening a PR, i've made a similar pr just because i had various notes and it was easier to just do them then type them all out.

Good luck with homarr

Meierschlumpf commented 2 months ago

Hey, thank you for fixing it and maintaining those libaries, they simplified the integration in Homarr a lot 🎉

SeDemal commented 2 months ago

Thanks a whole lot !