Различное поведение с Mocha между `pnpm ln -g <pkg>` и `pnpm add github:<pkg>`

У меня возникла довольно сложная проблема, которую я не могу найти:

Контекст

Я хотел бы использовать версию ts библиотеки algebrite: https://github.com/davidedc/Algebrite

Но мне также требовались некоторые внутренние типы и структура, поэтому я разветвил его и скомпилировал с помощью tsc вместо bazel, потому что я не смог заставить его генерировать файлы объявлений... Вот мой форк: https://github.com/hl037/алгебра/дерево/SO_question

Репозиторий, над которым я работаю, является частным, поэтому я могу публиковать только отрывки.

Для тестирования мы используем Mocha’stestname.spec.ts, выполненный сmocha -r ts-node/register 'tests/**/*.spec.ts'

Я использую pnpm в качестве менеджера пакетов.

Проблема

Когда я устанавливаю algebrite локально и используюpnpm ln -g/pnpm ln -g algebriteчтобы установить его в частном репо, тест Mocha проходит.

Но когда я используюpnpm add github:hl037/Algebrite#SO_question (на самом деле #master, но я создал ветку, чтобы заморозить содержимое репо для этого вопроса на случай, если я попробую что-то другое) , тогда я получаю эту ошибку:

      TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /repo/tests/testname.spec.ts
    at new NodeError (node:internal/errors:371:5)
    at Loader.defaultGetFormat [as _getFormat] (node:internal/modules/esm/get_format:71:15)
    at Loader.getFormat (node:internal/modules/esm/loader:105:42)
    at Loader.getModuleJob (node:internal/modules/esm/loader:243:31)
    at async Loader.import (node:internal/modules/esm/loader:177:17)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async formattedImport (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
    at async Object.exports.requireOrImport (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/nodejs/esm-utils.js:38:28)
    at async Object.exports.loadFilesAsync (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/nodejs/esm-utils.js:91:20)
    at async singleRun (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/cli/run-helpers.js:125:3)
    at async Object.exports.handler (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/cli/run.js:370:5)

Эта ошибка вообще не имеет смысла и на самом деле полностью вводит в заблуждение. Мне пришлось осмотреть исполнение мокко, чтобы найти истинный тот, который замаскирован вnode_modules/mocha/lib/nodejs/esm-utils.js:33:

      exports.requireOrImport = async file => {
  if (path.extname(file) === '.mjs') {
    return formattedImport(file);
  }
  try {
    return dealWithExports(await formattedImport(file));
  } catch (err) {
    if (
      err.code === 'ERR_MODULE_NOT_FOUND' ||
      err.code === 'ERR_UNKNOWN_FILE_EXTENSION' ||
      err.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
    ) {
      try {
        // Importing a file usually works, but the resolution of `import` is the ESM
        // resolution algorithm, and not the CJS resolution algorithm. We may have
        // failed because we tried the ESM resolution, so we try to `require` it.
        return require(file);
      } catch (requireErr) {
        if (
          requireErr.code === 'ERR_REQUIRE_ESM' ||
          (requireErr instanceof SyntaxError &&
            requireErr
              .toString()
              .includes('Cannot use import statement outside a module'))
        ) {
          // ERR_REQUIRE_ESM happens when the test file is a JS file, but via type:module is actually ESM,
          // AND has an import to a file that doesn't exist.
          // This throws an `ERR_MODULE_NOT_FOUND` error above,
          // and when we try to `require` it here, it throws an `ERR_REQUIRE_ESM`.
          // What we want to do is throw the original error (the `ERR_MODULE_NOT_FOUND`),
          // and not the `ERR_REQUIRE_ESM` error, which is a red herring.
          //
          // SyntaxError happens when in an edge case: when we're using an ESM loader that loads
          // a `test.ts` file (i.e. unrecognized extension), and that file includes an unknown
          // import (which throws an ERR_MODULE_NOT_FOUND). `require`-ing it will throw the
          // syntax error, because we cannot require a file that has `import`-s.
          throw err;
        } else {
          throw requireErr;
        }
      }
    } else {
      throw err;
    }
  }
};

Настоящая ошибка:

      
/repo/node_modules/.pnpm/github.com+hl037+Algebrite@0c4b3796055f2766c4da408_l733cdhqtfuxjtcwx5qyxbl4jm/node_modules/algebrite/dist/index.js:8
import { caadr, caar, cadadr, caddddr, cadddr, caddr, cadr, car, cdadr, cdar, cdddr, cddr, cdr, CONS, Cons, DOUBLE, Double, isadd, iscons, isdouble, isfactorial, ismultiply, isNumericAtom, ispower, isrational, isstr, issymbol, istensor, NUM, Num, STR, Str, SYM, Sym, TENSOR, Tensor, version, cadar, cddar, caaddr, caddar, cdaddr, cddddr, cadaddr, cddaddr, caddadr, cdddaddr, caddaddr, } from './runtime/defs';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .js] (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1608:43)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
    at Object.<anonymous> (/repo/src/main/AstProcessing/Algebrite.ts:1:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Module.m._compile (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
    at Object.<anonymous> (/repo/src/main/Functions/Math.ts:2:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Module.m._compile (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
    at Object.<anonymous> (/repo/src/main/Functions/Functions.ts:5:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Module.m._compile (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
    at Object.<anonymous> (/repo/src/main/Functions/Runtime.ts:8:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Module.m._compile (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
    at Object.<anonymous> (/repo/tests/tests/testname.spec.ts:5:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Module.m._compile (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/repo/node_modules/.pnpm/ts-node@10.9.1_typescript@4.7.4/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
    at Object.exports.requireOrImport (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/nodejs/esm-utils.js:49:16)
    at async Object.exports.loadFilesAsync (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/nodejs/esm-utils.js:91:20)
    at async singleRun (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/cli/run-helpers.js:125:3)
    at async Object.exports.handler (/repo/node_modules/.pnpm/mocha@10.0.0/node_modules/mocha/lib/cli/run.js:370:5)

Важное примечание. Когда algebrite установлен с помощью , на самом деле появляется первая ошибка, но in ничего не выдает.

Что я пробовал до сих пор

я пытался добавить"type" : "module"в package.json algebrite, но потом у меня возникает эта ошибка:

       Error [ERR_REQUIRE_ESM]: require() of ES Module /repo/node_modules/.pnpm/github.com+hl037+Algebrite@0c4b3796055f2766c4da408_l733cdhqtfuxjtcwx5qyxbl4jm/node_modules/algebrite/dist/index.js from /repo/src/main/AstProcessing/Algebrite.ts not supported.
Instead change the require of index.js in /repo/src/main/AstProcessing/Algebrite.ts to a dynamic import() which is available in all CommonJS modules.
    at Object.require.extensions.<computed> [as .js] (index.ts:1608:43)
    at Object.<anonymous> (Algebrite.ts? [sm]:1:1)
    at Module.m._compile (index.ts:1618:23)
    at Object.require.extensions.<computed> [as .ts] (index.ts:1621:12)
    at Object.<anonymous> (Math.ts? [sm]:2:1)
    at Module.m._compile (index.ts:1618:23)
    at Object.require.extensions.<computed> [as .ts] (index.ts:1621:12)
    at Object.<anonymous> (Functions.ts? [sm]:5:1)
    at Module.m._compile (index.ts:1618:23)
    at Object.require.extensions.<computed> [as .ts] (index.ts:1621:12)
    at Object.<anonymous> (Runtime.ts? [sm]:8:1)
    at Module.m._compile (index.ts:1618:23)
    at Object.require.extensions.<computed> [as .ts] (index.ts:1621:12)
    at Object.<anonymous> (SignatureMatching.spec.ts? [sm]:5:1)
    at Module.m._compile (index.ts:1618:23)
    at Object.require.extensions.<computed> [as .ts] (index.ts:1621:12)
    at Object.exports.requireOrImport (esm-utils.js:49:16)
    at async Object.exports.loadFilesAsync (esm-utils.js:91:20)
    at async singleRun (run-helpers.js:125:3)
    at async Object.exports.handler (run.js:370:5)

...Что кажется логичным, поскольку вызов кода, как вы можете видеть в частиesm-utils.jsЯ скопировал вставленный ранее.

Вопросы

Во-первых, что я могу сделать, чтобы тест мокко работал, когда algebrite установлен из git?

Тогда, Почему мог сделатьrequire(file)работать сpnpm lnи не работает при установке из git?

0 ответов

Другие вопросы по тегам