altcha-org / altcha-lib

A JavaScript library for creating and verifying ALTCHA challenges.
https://altcha.org
MIT License
18 stars 4 forks source link

/dist/crypto.js uses CommonJS syntax, even though it is in an ES module #6

Closed max64mode closed 1 month ago

max64mode commented 1 month ago

Hi! I'm trying to make a function for generating ALTCHA challenges on my Appwrite server, but while doing so I've found a bug in altcha-lib.

This bug prevents the altcha-lib library from working in NodeJS 16.0, as this condition is only triggered when crypto is not present in globalThis.

if (!('crypto' in globalThis)) {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    globalThis.crypto = require('node:crypto').webcrypto; // <-- Should be using import, not require
}
export {};

Trying to use altcha-lib in NodeJS 16.0 gives this error:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/usr/local/server/src/function/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///usr/local/server/src/function/node_modules/altcha-lib/dist/crypto.js:3:5
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async execute (/usr/local/server/src/server.js:142:32)
    at async action (/usr/local/server/src/server.js:174:13)
    at async /usr/local/server/src/server.js:10:9

Would it be possible to change the syntax to ES module syntax (for compatibility reasons)? Thank you!

ovx commented 1 month ago

Hi, thanks for reporting, this part of code has been removed from the latest version 0.4.0, allowing you to add the global reference manually depending your setup. You'll have to add this before using the lib:

import { webcrypto } from 'node:crypto';

globalThis.crypto = webcrypto;