diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 72f98eb58b..0000000000 --- a/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -src/proto/* diff --git a/.eslintrc b/.eslintrc index 3fe5e4c3e3..92813260bb 100644 --- a/.eslintrc +++ b/.eslintrc @@ -7,18 +7,18 @@ "jest": true }, "parser": "@typescript-eslint/parser", + "parserOptions": { + "project": "tsconfig.json", + "sourceType": "module" + }, + "plugins": [ + "import" + ], "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended" ], - "plugins": [ - "import" - ], - "parserOptions": { - "project": "tsconfig.json", - "sourceType": "module" - }, "rules": { "linebreak-style": ["error", "unix"], "no-empty": 1, diff --git a/README.md b/README.md index 99ff954338..7737773046 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ npm install # build the dist npm run build # run the repl (this allows you to import from ./src) -npm run ts-node +npm run tsx # run the tests npm run test # lint the source code diff --git a/benches/suites/basic/buffer_encoding_decoding.ts b/benches/basic_buffer_encoding_decoding.ts similarity index 62% rename from benches/suites/basic/buffer_encoding_decoding.ts rename to benches/basic_buffer_encoding_decoding.ts index 123e8ae6db..91ad4d69f5 100644 --- a/benches/suites/basic/buffer_encoding_decoding.ts +++ b/benches/basic_buffer_encoding_decoding.ts @@ -1,10 +1,14 @@ +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { const buf = Buffer.allocUnsafe(64); const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('JSON stringify and parse buffer', () => { const bufJSON = JSON.stringify(buf); Buffer.from(JSON.parse(bufJSON)); @@ -22,8 +26,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/suites/git/gitgc.ts b/benches/git_garbage_collection.ts similarity index 84% rename from benches/suites/git/gitgc.ts rename to benches/git_garbage_collection.ts index 31a94b5d03..156834dc5c 100644 --- a/benches/suites/git/gitgc.ts +++ b/benches/git_garbage_collection.ts @@ -1,5 +1,9 @@ +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { let map = new Map(); @@ -7,7 +11,7 @@ async function main() { let arr: any = []; let set = new Set(); const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('map', async () => { map = new Map(); return async () => { @@ -83,8 +87,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/index.ts b/benches/index.ts index 553f154f80..eea89ffceb 100644 --- a/benches/index.ts +++ b/benches/index.ts @@ -1,56 +1,76 @@ #!/usr/bin/env ts-node -import type { Summary } from 'benny/lib/internal/common-types'; -import fs from 'fs'; -import path from 'path'; +import fs from 'node:fs'; +import path from 'node:path'; +import url from 'node:url'; import si from 'systeminformation'; -import { fsWalk, resultsPath, suitesPath } from './utils'; +import { benchesPath } from './utils/utils.js'; +import basicBufferEncodingDecoding from './basic_buffer_encoding_decoding.js'; +import gitGarbageCollection from './git_garbage_collection.js'; +import keysAsymmetricCrypto from './keys_asymmetric_crypto.js'; +import keysKeyGeneration from './keys_key_generation.js'; +import keysKeyringLifecycle from './keys_keyring_lifecycle.js'; +import keysPasswordHashing from './keys_password_hashing.js'; +import keysRandomBytes from './keys_random_bytes.js'; +import keysRecoveryCode from './keys_recovery_code.js'; +import keysSymmetricCrypto from './keys_symmetric_crypto.js'; +import keysX509 from './keys_x509.js'; +import workersKeys from './workers_keys.js'; +import workersOverhead from './workers_overhead.js'; async function main(): Promise { - await fs.promises.mkdir(path.join(__dirname, 'results'), { recursive: true }); - // Running all suites - for await (const suitePath of fsWalk(suitesPath)) { - // Skip over non-ts and non-js files - const ext = path.extname(suitePath); - if (ext !== '.ts' && ext !== '.js') { - continue; - } - const suite: () => Promise = (await import(suitePath)).default; - // Skip default exports that are not functions and are not called "main" - // They might be utility files - if (typeof suite === 'function' && suite.name === 'main') { - await suite(); - } - } - // Concatenating metrics - const metricsPath = path.join(resultsPath, 'metrics.txt'); - await fs.promises.rm(metricsPath, { force: true }); + await fs.promises.mkdir(path.join(benchesPath, 'results'), { + recursive: true, + }); + await basicBufferEncodingDecoding(); + await gitGarbageCollection(); + await keysAsymmetricCrypto(); + await keysKeyGeneration(); + await keysKeyringLifecycle(); + await keysPasswordHashing(); + await keysRandomBytes(); + await keysRecoveryCode(); + await keysSymmetricCrypto(); + await keysX509(); + await workersKeys(); + await workersOverhead(); + const resultFilenames = await fs.promises.readdir( + path.join(benchesPath, 'results'), + ); + const metricsFile = await fs.promises.open( + path.join(benchesPath, 'results', 'metrics.txt'), + 'w', + ); let concatenating = false; - for await (const metricPath of fsWalk(resultsPath)) { - // Skip over non-metrics files - if (!metricPath.endsWith('_metrics.txt')) { - continue; + for (const resultFilename of resultFilenames) { + if (/.+_metrics\.txt$/.test(resultFilename)) { + const metricsData = await fs.promises.readFile( + path.join(benchesPath, 'results', resultFilename), + ); + if (concatenating) { + await metricsFile.write('\n'); + } + await metricsFile.write(metricsData); + concatenating = true; } - const metricData = await fs.promises.readFile(metricPath); - if (concatenating) { - await fs.promises.appendFile(metricsPath, '\n'); - } - await fs.promises.appendFile(metricsPath, metricData); - concatenating = true; } + await metricsFile.close(); const systemData = await si.get({ cpu: '*', osInfo: 'platform, distro, release, kernel, arch', system: 'model, manufacturer', }); await fs.promises.writeFile( - path.join(__dirname, 'results', 'system.json'), + path.join(benchesPath, 'results', 'system.json'), JSON.stringify(systemData, null, 2), ); } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/suites/keys/asymmetric_crypto.ts b/benches/keys_asymmetric_crypto.ts similarity index 82% rename from benches/suites/keys/asymmetric_crypto.ts rename to benches/keys_asymmetric_crypto.ts index ef36d61477..9d3afc0f07 100644 --- a/benches/suites/keys/asymmetric_crypto.ts +++ b/benches/keys_asymmetric_crypto.ts @@ -1,8 +1,12 @@ +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; -import * as random from '@/keys/utils/random'; -import * as generate from '@/keys/utils/generate'; -import * as asymmetric from '@/keys/utils/asymmetric'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; +import * as random from '#keys/utils/random.js'; +import * as generate from '#keys/utils/generate.js'; +import * as asymmetric from '#keys/utils/asymmetric.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { const keyPair = generate.generateKeyPair(); @@ -34,7 +38,7 @@ async function main() { plain10KiB, ); const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('encrypt 512 B of data', () => { asymmetric.encryptWithPublicKey(keyPair.publicKey, plain512B); }), @@ -88,8 +92,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/suites/keys/key_generation.ts b/benches/keys_key_generation.ts similarity index 51% rename from benches/suites/keys/key_generation.ts rename to benches/keys_key_generation.ts index 382902b5f9..89a89ccc58 100644 --- a/benches/suites/keys/key_generation.ts +++ b/benches/keys_key_generation.ts @@ -1,12 +1,16 @@ +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; -import * as generate from '@/keys/utils/generate'; -import * as recoveryCode from '@/keys/utils/recoveryCode'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; +import * as generate from '#keys/utils/generate.js'; +import * as recoveryCode from '#keys/utils/recoveryCode.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { const code = recoveryCode.generateRecoveryCode(24); const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('generate root asymmetric keypair', () => { generate.generateKeyPair(); }), @@ -21,8 +25,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/suites/keys/keyring_lifecycle.ts b/benches/keys_keyring_lifecycle.ts similarity index 74% rename from benches/suites/keys/keyring_lifecycle.ts rename to benches/keys_keyring_lifecycle.ts index 9185e5c631..2b47822485 100644 --- a/benches/suites/keys/keyring_lifecycle.ts +++ b/benches/keys_keyring_lifecycle.ts @@ -1,14 +1,17 @@ -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import fs from 'node:fs'; +import os from 'node:os'; +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import KeyRing from '@/keys/KeyRing'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; +import KeyRing from '#keys/KeyRing.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('KeyRing fresh creation', async () => { const dataDir = await fs.promises.mkdtemp( path.join(os.tmpdir(), 'polykey-bench-'), @@ -52,8 +55,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/suites/keys/password_hashing.ts b/benches/keys_password_hashing.ts similarity index 70% rename from benches/suites/keys/password_hashing.ts rename to benches/keys_password_hashing.ts index 3f6fa6c9c3..7f7ffb5021 100644 --- a/benches/suites/keys/password_hashing.ts +++ b/benches/keys_password_hashing.ts @@ -1,10 +1,14 @@ +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; -import * as password from '@/keys/utils/password'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; +import * as password from '#keys/utils/password.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('password hashing - min', () => { password.hashPassword( 'password', @@ -42,8 +46,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/keys_random_bytes.ts b/benches/keys_random_bytes.ts new file mode 100644 index 0000000000..bc13e4a460 --- /dev/null +++ b/benches/keys_random_bytes.ts @@ -0,0 +1,33 @@ +import path from 'node:path'; +import url from 'node:url'; +import b from 'benny'; +import { suiteCommon } from './utils/utils.js'; +import * as random from '#keys/utils/random.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); + +async function main() { + const summary = await b.suite( + path.basename(filename, path.extname(filename)), + b.add('random 512 B of data', () => { + random.getRandomBytes(512); + }), + b.add('random 1 KiB of data', () => { + random.getRandomBytes(1024); + }), + b.add('random 10 KiB of data', () => { + random.getRandomBytes(1024 * 10); + }), + ...suiteCommon, + ); + return summary; +} + +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } +} + +export default main; diff --git a/benches/keys_recovery_code.ts b/benches/keys_recovery_code.ts new file mode 100644 index 0000000000..4a31489975 --- /dev/null +++ b/benches/keys_recovery_code.ts @@ -0,0 +1,30 @@ +import path from 'node:path'; +import url from 'node:url'; +import b from 'benny'; +import { suiteCommon } from './utils/utils.js'; +import * as recoveryCode from '#keys/utils/recoveryCode.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); + +async function main() { + const summary = await b.suite( + path.basename(filename, path.extname(filename)), + b.add('generate 24 word recovery code', async () => { + recoveryCode.generateRecoveryCode(24); + }), + b.add('generate 12 word recovery code', async () => { + recoveryCode.generateRecoveryCode(12); + }), + ...suiteCommon, + ); + return summary; +} + +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } +} + +export default main; diff --git a/benches/suites/keys/symmetric_crypto.ts b/benches/keys_symmetric_crypto.ts similarity index 76% rename from benches/suites/keys/symmetric_crypto.ts rename to benches/keys_symmetric_crypto.ts index 6a0656bbe7..6cc4ccc649 100644 --- a/benches/suites/keys/symmetric_crypto.ts +++ b/benches/keys_symmetric_crypto.ts @@ -1,8 +1,12 @@ +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; -import * as random from '@/keys/utils/random'; -import * as generate from '@/keys/utils/generate'; -import * as symmetric from '@/keys/utils/symmetric'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; +import * as random from '#keys/utils/random.js'; +import * as generate from '#keys/utils/generate.js'; +import * as symmetric from '#keys/utils/symmetric.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { const key = generate.generateKey(); @@ -17,7 +21,7 @@ async function main() { const cipher1MiB = symmetric.encryptWithKey(key, plain1MiB); const cipher10MiB = symmetric.encryptWithKey(key, plain10MiB); const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('encrypt 512 B of data', () => { symmetric.encryptWithKey(key, plain512B); }), @@ -53,8 +57,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/suites/keys/x509.ts b/benches/keys_x509.ts similarity index 76% rename from benches/suites/keys/x509.ts rename to benches/keys_x509.ts index 9589edb332..ee71caf05e 100644 --- a/benches/suites/keys/x509.ts +++ b/benches/keys_x509.ts @@ -1,15 +1,19 @@ +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; -import * as generate from '@/keys/utils/generate'; -import * as x509 from '@/keys/utils/x509'; -import * as ids from '@/ids'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; +import * as generate from '#keys/utils/generate.js'; +import * as x509 from '#keys/utils/x509.js'; +import * as ids from '#ids/index.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { const issuerKeyPair = generate.generateKeyPair(); const subjectKeyPair = generate.generateKeyPair(); const certIdGenerator = ids.createCertIdGenerator(); const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('generate certificate', async () => { await x509.generateCertificate({ certId: certIdGenerator(), @@ -61,8 +65,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/benches/suites/keys/random_bytes.ts b/benches/suites/keys/random_bytes.ts deleted file mode 100644 index 5ee76187bb..0000000000 --- a/benches/suites/keys/random_bytes.ts +++ /dev/null @@ -1,26 +0,0 @@ -import b from 'benny'; -import * as random from '@/keys/utils/random'; -import { summaryName, suiteCommon } from '../../utils'; - -async function main() { - const summary = await b.suite( - summaryName(__filename), - b.add('random 512 B of data', () => { - random.getRandomBytes(512); - }), - b.add('random 1 KiB of data', () => { - random.getRandomBytes(1024); - }), - b.add('random 10 KiB of data', () => { - random.getRandomBytes(1024 * 10); - }), - ...suiteCommon, - ); - return summary; -} - -if (require.main === module) { - void main(); -} - -export default main; diff --git a/benches/suites/keys/recovery_code.ts b/benches/suites/keys/recovery_code.ts deleted file mode 100644 index 0698d46d18..0000000000 --- a/benches/suites/keys/recovery_code.ts +++ /dev/null @@ -1,23 +0,0 @@ -import b from 'benny'; -import * as recoveryCode from '@/keys/utils/recoveryCode'; -import { summaryName, suiteCommon } from '../../utils'; - -async function main() { - const summary = await b.suite( - summaryName(__filename), - b.add('generate 24 word recovery code', async () => { - recoveryCode.generateRecoveryCode(24); - }), - b.add('generate 12 word recovery code', async () => { - recoveryCode.generateRecoveryCode(12); - }), - ...suiteCommon, - ); - return summary; -} - -if (require.main === module) { - void main(); -} - -export default main; diff --git a/benches/suites/workers/worker_keys.ts b/benches/suites/workers/worker_keys.ts deleted file mode 100644 index 72711d730d..0000000000 --- a/benches/suites/workers/worker_keys.ts +++ /dev/null @@ -1,80 +0,0 @@ -import type { Summary } from 'benny/lib/internal/common-types'; -import type { CertificateASN1 } from '@/keys/types'; -import b from 'benny'; -import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import * as workersUtils from '@/workers/utils'; -import * as keysUtils from '@/keys/utils'; -import { summaryName, suiteCommon } from '../../utils'; - -async function main() { - const cores = 1; - const logger = new Logger(`worker_overhead bench`, LogLevel.WARN, [ - new StreamHandler(), - ]); - const workerManager = await workersUtils.createWorkerManager({ - cores, - logger, - }); - let summary: Summary; - try { - summary = await b.suite( - summaryName(__filename), - b.add('hash password', async () => { - await workerManager.call(async (w) => { - const [hash, salt] = await w.hashPassword('password'); - return [Buffer.from(hash), Buffer.from(salt)]; - }); - }), - b.add('check password', async () => { - const [hash, salt] = keysUtils.hashPassword('password'); - return async () => { - await workerManager.call(async (w) => { - return await w.checkPassword('password', hash.buffer, salt.buffer); - }); - }; - }), - b.add('generate deterministic key pair', async () => { - const recoveryCode = keysUtils.generateRecoveryCode(24); - return async () => { - await workerManager.call(async (w) => { - const result = await w.generateDeterministicKeyPair(recoveryCode); - result.publicKey = Buffer.from(result.publicKey); - result.privateKey = Buffer.from(result.privateKey); - result.secretKey = Buffer.from(result.secretKey); - return result; - }); - }; - }), - b.add('generate certificate', async () => { - const certIdGenerator = keysUtils.createCertIdGenerator(); - const subjectKeyPair = keysUtils.generateKeyPair(); - return async () => { - await workerManager.call(async (w) => { - const result = await w.generateCertificate({ - certId: certIdGenerator(), - subjectKeyPair: { - publicKey: subjectKeyPair.publicKey.buffer, - privateKey: subjectKeyPair.privateKey.buffer, - }, - issuerPrivateKey: subjectKeyPair.privateKey.buffer, - duration: 1000, - }); - return keysUtils.certFromASN1( - Buffer.from(result) as CertificateASN1, - )!; - }); - }; - }), - ...suiteCommon, - ); - } finally { - await workerManager.destroy(); - } - return summary; -} - -if (require.main === module) { - void main(); -} - -export default main; diff --git a/benches/utils.ts b/benches/utils.ts deleted file mode 100644 index b8d7758a20..0000000000 --- a/benches/utils.ts +++ /dev/null @@ -1,100 +0,0 @@ -import fs from 'fs'; -import path from 'path'; -import b from 'benny'; -import { codeBlock } from 'common-tags'; -import packageJson from '../package.json'; - -const suitesPath = path.join(__dirname, 'suites'); -const resultsPath = path.join(__dirname, 'results'); - -function summaryName(suitePath: string) { - return path - .relative(suitesPath, suitePath) - .replace(/\.[^.]*$/, '') - .replace(/\//g, '.'); -} - -const suiteCommon = [ - b.cycle(), - b.complete(), - b.save({ - file: (summary) => { - // Replace dots with slashes - const relativePath = summary.name.replace(/\./g, '/'); - // To `results/path/to/suite` - const resultPath = path.join(resultsPath, relativePath); - // This creates directory `results/path/to` - fs.mkdirSync(path.dirname(resultPath), { recursive: true }); - return relativePath; - }, - folder: resultsPath, - version: packageJson.version, - details: true, - }), - b.save({ - file: (summary) => { - // Replace dots with slashes - const relativePath = summary.name.replace(/\./g, '/'); - // To `results/path/to/suite` - const resultPath = path.join(resultsPath, relativePath); - // This creates directory `results/path/to` - fs.mkdirSync(path.dirname(resultPath), { recursive: true }); - return relativePath; - }, - folder: resultsPath, - version: packageJson.version, - format: 'chart.html', - }), - b.complete((summary) => { - // Replace dots with slashes - const relativePath = summary.name.replace(/\./g, '/'); - // To `results/path/to/suite_metrics.txt` - const resultPath = path.join(resultsPath, relativePath) + '_metrics.txt'; - // This creates directory `results/path/to` - fs.mkdirSync(path.dirname(resultPath), { recursive: true }); - fs.writeFileSync( - resultPath, - codeBlock` - # TYPE ${summary.name}_ops gauge - ${summary.results - .map( - (result) => - `${summary.name}_ops{name="${result.name}"} ${result.ops}`, - ) - .join('\n')} - - # TYPE ${summary.name}_margin gauge - ${summary.results - .map( - (result) => - `${summary.name}_margin{name="${result.name}"} ${result.margin}`, - ) - .join('\n')} - - # TYPE ${summary.name}_samples counter - ${summary.results - .map( - (result) => - `${summary.name}_samples{name="${result.name}"} ${result.samples}`, - ) - .join('\n')} - ` + '\n', - ); - // eslint-disable-next-line no-console - console.log('\nSaved to:', path.resolve(resultPath)); - }), -]; - -async function* fsWalk(dir: string): AsyncGenerator { - const dirents = await fs.promises.readdir(dir, { withFileTypes: true }); - for (const dirent of dirents) { - const res = path.resolve(dir, dirent.name); - if (dirent.isDirectory()) { - yield* fsWalk(res); - } else { - yield res; - } - } -} - -export { suitesPath, resultsPath, summaryName, suiteCommon, fsWalk }; diff --git a/benches/utils/index.ts b/benches/utils/index.ts new file mode 100644 index 0000000000..9be8099fb9 --- /dev/null +++ b/benches/utils/index.ts @@ -0,0 +1 @@ +export * from './utils.js'; diff --git a/benches/utils/utils.ts b/benches/utils/utils.ts new file mode 100644 index 0000000000..ce8ec15b2b --- /dev/null +++ b/benches/utils/utils.ts @@ -0,0 +1,66 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import url from 'node:url'; +import b from 'benny'; +import { codeBlock } from 'common-tags'; +import packageJson from '../../package.json' assert { type: 'json' }; + +const benchesPath = path.dirname( + path.dirname(url.fileURLToPath(import.meta.url)), +); + +const suiteCommon = [ + b.cycle(), + b.complete(), + b.save({ + file: (summary) => summary.name, + folder: path.join(benchesPath, 'results'), + version: packageJson.version, + details: true, + }), + b.save({ + file: (summary) => summary.name, + folder: path.join(benchesPath, 'results'), + version: packageJson.version, + format: 'chart.html', + }), + b.complete((summary) => { + const filePath = path.join( + benchesPath, + 'results', + summary.name + '_metrics.txt', + ); + fs.writeFileSync( + filePath, + codeBlock` + # TYPE ${summary.name}_ops gauge + ${summary.results + .map( + (result) => + `${summary.name}_ops{name="${result.name}"} ${result.ops}`, + ) + .join('\n')} + + # TYPE ${summary.name}_margin gauge + ${summary.results + .map( + (result) => + `${summary.name}_margin{name="${result.name}"} ${result.margin}`, + ) + .join('\n')} + + # TYPE ${summary.name}_samples counter + ${summary.results + .map( + (result) => + `${summary.name}_samples{name="${result.name}"} ${result.samples}`, + ) + .join('\n')} + ` + '\n', + ); + // eslint-disable-next-line no-console + console.log('\nSaved to:', path.resolve(filePath)); + }), +]; + +export { benchesPath, suiteCommon }; diff --git a/benches/workers_keys.ts b/benches/workers_keys.ts new file mode 100644 index 0000000000..ce0e4e7f34 --- /dev/null +++ b/benches/workers_keys.ts @@ -0,0 +1,93 @@ +import type { CertificateASN1 } from '#keys/types.js'; +import url from 'node:url'; +import path from 'node:path'; +import b from 'benny'; +import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; +import { suiteCommon } from './utils/utils.js'; +import * as workersUtils from '#workers/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); + +async function main() { + const cores = 1; + const logger = new Logger(`worker_overhead bench`, LogLevel.WARN, [ + new StreamHandler(), + ]); + const workerManager = await workersUtils.createWorkerManager({ + cores, + logger, + }); + let summary: Awaited>; + try { + summary = await b.suite( + path.basename(filename, path.extname(filename)), + b.add('hash password', async () => { + await workerManager.methods.hashPassword({ password: 'password' }); + }), + b.add('check password', async () => { + const [hash, salt] = keysUtils.hashPassword('password'); + return async () => { + const hashAB = workersUtils.toArrayBuffer(hash); + const saltAB = workersUtils.toArrayBuffer(salt); + await workerManager.methods.checkPassword({ + password: 'password', + hash: hashAB, + salt: saltAB, + }); + }; + }), + b.add('generate deterministic key pair', async () => { + const recoveryCode = keysUtils.generateRecoveryCode(24); + return async () => { + await workerManager.methods.generateDeterministicKeyPair({ + recoveryCode, + }); + }; + }), + b.add('generate certificate', async () => { + const certIdGenerator = keysUtils.createCertIdGenerator(); + const subjectKeyPair = keysUtils.generateKeyPair(); + return async () => { + const certIdAB = workersUtils.toArrayBuffer( + certIdGenerator().toBuffer(), + ); + const privateKeyAB = workersUtils.toArrayBuffer( + subjectKeyPair.privateKey, + ); + const { data: result } = + await workerManager.methods.generateCertificate( + { + certId: certIdAB, + subjectKeyPair: { + publicKey: workersUtils.toArrayBuffer( + subjectKeyPair.publicKey, + ), + privateKey: privateKeyAB, + }, + issuerPrivateKey: privateKeyAB, + duration: 1000, + }, + [certIdAB], + ); + void keysUtils.certFromASN1( + workersUtils.fromArrayBuffer(result) as CertificateASN1, + )!; + }; + }), + ...suiteCommon, + ); + } finally { + await workerManager.destroy(); + } + return summary; +} + +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } +} + +export default main; diff --git a/benches/suites/workers/worker_overhead.ts b/benches/workers_overhead.ts similarity index 57% rename from benches/suites/workers/worker_overhead.ts rename to benches/workers_overhead.ts index a55722eb87..94f40705c8 100644 --- a/benches/suites/workers/worker_overhead.ts +++ b/benches/workers_overhead.ts @@ -1,7 +1,11 @@ +import url from 'node:url'; +import path from 'node:path'; import b from 'benny'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import * as workersUtils from '@/workers/utils'; -import { summaryName, suiteCommon } from '../../utils'; +import { suiteCommon } from './utils/utils.js'; +import * as workersUtils from '#workers/utils.js'; + +const filename = url.fileURLToPath(new URL(import.meta.url)); async function main() { const cores = 1; @@ -15,38 +19,20 @@ async function main() { // 1 MiB worth of data is the ballpark range of data to be worth parallelising // 1 KiB of data is still too small const summary = await b.suite( - summaryName(__filename), + path.basename(filename, path.extname(filename)), b.add('call overhead', async () => { // This calls a noop, this will show the overhead costs // All parallelised operation can never be faster than this // Therefore any call that takes less time than the overhead cost // e.g. 1.5ms is not worth parallelising - await workerManager.call(async (w) => { - await w.sleep(0); - }); + await workerManager.methods.sleep({ delay: 0 }); }), b.add('parallel call overhead', async () => { // Assuming core count is 1 // the performance should be half of `call overhead` await Promise.all([ - workerManager.call(async (w) => { - await w.sleep(0); - }), - workerManager.call(async (w) => { - await w.sleep(0); - }), - ]); - }), - b.add('parallel queue overhead', async () => { - // This should be slightly faster than using call - // This avoids an unnecessary wrapper into Promise - await Promise.all([ - workerManager.queue(async (w) => { - await w.sleep(0); - }), - workerManager.queue(async (w) => { - await w.sleep(0); - }), + await workerManager.methods.sleep({ delay: 0 }), + await workerManager.methods.sleep({ delay: 0 }), ]); }), ...suiteCommon, @@ -55,8 +41,11 @@ async function main() { return summary; } -if (require.main === module) { - void main(); +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } } export default main; diff --git a/jest.config.js b/jest.config.mjs similarity index 72% rename from jest.config.js rename to jest.config.mjs index f4b4457f3b..63bb380ae4 100644 --- a/jest.config.js +++ b/jest.config.mjs @@ -1,18 +1,16 @@ -const path = require('path'); -const { pathsToModuleNameMapper } = require('ts-jest'); -const { compilerOptions } = require('./tsconfig'); +import path from 'node:path'; +import url from 'node:url'; +import tsconfigJSON from './tsconfig.json' assert { type: "json" }; -const moduleNameMapper = pathsToModuleNameMapper(compilerOptions.paths, { - prefix: '/src/', -}); +const projectPath = path.dirname(url.fileURLToPath(import.meta.url)); // Global variables that are shared across the jest worker pool // These variables must be static and serializable const globals = { // Absolute directory to the project root - projectDir: __dirname, + projectDir: projectPath, // Absolute directory to the test root - testDir: path.join(__dirname, 'tests'), + testDir: path.join(projectPath, 'tests'), // Default asynchronous test timeout defaultTimeout: 20000, failedConnectionTimeout: 50000, @@ -25,7 +23,7 @@ const globals = { // They can however receive the process environment // Use `process.env` to set variables -module.exports = { +const config = { testEnvironment: 'node', verbose: true, collectCoverage: false, @@ -37,15 +35,15 @@ module.exports = { "^.+\\.(t|j)sx?$": [ "@swc/jest", { - "jsc": { - "parser": { - "syntax": "typescript", - "dynamicImport": true, - "tsx": true, - "decorators": compilerOptions.experimentalDecorators, + jsc: { + parser: { + syntax: "typescript", + tsx: true, + decorators: tsconfigJSON.compilerOptions.experimentalDecorators, + dynamicImport: true, }, - "target": compilerOptions.target.toLowerCase(), - "keepClassNames": true, + target: tsconfigJSON.compilerOptions.target.toLowerCase(), + keepClassNames: true, }, } ], @@ -61,7 +59,7 @@ module.exports = { reportTestSuiteErrors: 'true', }], ], - collectCoverageFrom: ['src/**/*.{ts,tsx,js,jsx}', '!src/**/*.d.ts', '!src/proto/**'], + collectCoverageFrom: ['src/**/*.{ts,tsx,js,jsx}', '!src/**/*.d.ts'], coverageReporters: ['text', 'cobertura'], globals, // Global setup script executed once before all test files @@ -78,5 +76,10 @@ module.exports = { 'jest-extended/all', '/tests/setupAfterEnv.ts' ], - moduleNameMapper: moduleNameMapper, + moduleNameMapper: { + "^(\\.{1,2}/.*)\\.js$": "$1", + }, + extensionsToTreatAsEsm: ['.ts', '.tsx', '.mts'], }; + +export default config; diff --git a/package-lock.json b/package-lock.json index ee206f7fb4..74328016f9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,22 +9,22 @@ "version": "1.21.4", "license": "GPL-3.0", "dependencies": { - "@matrixai/async-cancellable": "^1.1.1", - "@matrixai/async-init": "^1.10.0", - "@matrixai/async-locks": "^4.0.0", - "@matrixai/contexts": "^1.1.0", - "@matrixai/db": "^5.3.0", - "@matrixai/errors": "^1.2.0", - "@matrixai/events": "^3.2.3", - "@matrixai/id": "^3.3.6", - "@matrixai/logger": "^3.1.2", - "@matrixai/mdns": "^1.2.6", - "@matrixai/quic": "^1.3.13", - "@matrixai/resources": "^1.1.5", - "@matrixai/rpc": "^0.6.2", - "@matrixai/timer": "^1.1.3", - "@matrixai/workers": "^1.3.7", - "@matrixai/ws": "^1.1.7", + "@matrixai/async-cancellable": "^2.0.1", + "@matrixai/async-init": "^2.1.2", + "@matrixai/async-locks": "^5.0.2", + "@matrixai/contexts": "^2.0.2", + "@matrixai/db": "^6.0.20", + "@matrixai/errors": "^2.1.3", + "@matrixai/events": "^4.0.1", + "@matrixai/id": "^4.0.0", + "@matrixai/logger": "^4.0.3", + "@matrixai/mdns": "^2.0.7", + "@matrixai/quic": "^2.0.9", + "@matrixai/resources": "^2.0.1", + "@matrixai/rpc": "^1.0.0", + "@matrixai/timer": "^2.1.1", + "@matrixai/workers": "^2.0.0", + "@matrixai/ws": "^2.0.5", "@peculiar/asn1-pkcs8": "^2.3.0", "@peculiar/asn1-schema": "^2.3.0", "@peculiar/asn1-x509": "^2.3.0", @@ -36,23 +36,21 @@ "cheerio": "^1.0.0-rc.5", "cross-fetch": "^3.0.6", "cross-spawn": "^7.0.3", - "encryptedfs": "^3.5.6", + "encryptedfs": "^4.0.2", "fast-fuzzy": "^1.10.8", "fd-lock": "^1.2.0", "ip-num": "^1.3.3-0", "isomorphic-git": "^1.8.1", - "ix": "^5.0.0", "lexicographic-integer": "^1.1.0", "minimatch": "^10.0.1", - "multiformats": "^9.4.8", + "multiformats": "^13.3.2", "pako": "^1.0.11", "prompts": "^2.4.1", "resource-counter": "^1.2.4", - "sodium-native": "^3.4.1", - "threads": "^1.6.5" + "sodium-native": "^3.4.1" }, "devDependencies": { - "@fast-check/jest": "^1.1.0", + "@fast-check/jest": "^2.1.1", "@swc/core": "1.3.82", "@swc/jest": "^0.2.29", "@types/cross-spawn": "^6.0.2", @@ -70,7 +68,7 @@ "eslint-config-prettier": "^8.8.0", "eslint-plugin-import": "^2.27.5", "eslint-plugin-prettier": "^5.0.0-alpha.2", - "fast-check": "^3.0.1", + "fast-check": "^4.0.1", "jest": "^29.6.2", "jest-extended": "^4.0.0", "jest-junit": "^16.0.0", @@ -78,9 +76,8 @@ "prettier": "^3.0.0", "shx": "^0.3.4", "systeminformation": "^5.18.5", - "ts-jest": "^29.1.1", "ts-node": "^10.9.1", - "tsconfig-paths": "^3.9.0", + "tsx": "^3.12.7", "typedoc": "^0.24.8", "typescript": "^5.1.6" } @@ -802,7 +799,6 @@ "version": "0.8.1", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", - "dev": true, "dependencies": { "@jridgewell/trace-mapping": "0.3.9" }, @@ -814,12 +810,363 @@ "version": "0.3.9", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", - "dev": true, "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@esbuild/android-arm": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.18.20.tgz", + "integrity": "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.18.20.tgz", + "integrity": "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.18.20.tgz", + "integrity": "sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.18.20.tgz", + "integrity": "sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.18.20.tgz", + "integrity": "sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.18.20.tgz", + "integrity": "sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.18.20.tgz", + "integrity": "sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.18.20.tgz", + "integrity": "sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.18.20.tgz", + "integrity": "sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.18.20.tgz", + "integrity": "sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.18.20.tgz", + "integrity": "sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.18.20.tgz", + "integrity": "sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.18.20.tgz", + "integrity": "sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.18.20.tgz", + "integrity": "sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.18.20.tgz", + "integrity": "sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.18.20.tgz", + "integrity": "sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.18.20.tgz", + "integrity": "sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.18.20.tgz", + "integrity": "sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.18.20.tgz", + "integrity": "sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.18.20.tgz", + "integrity": "sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.18.20.tgz", + "integrity": "sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.18.20.tgz", + "integrity": "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", @@ -921,9 +1268,9 @@ } }, "node_modules/@fast-check/jest": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/@fast-check/jest/-/jest-1.7.3.tgz", - "integrity": "sha512-6NcpYIIUnLwEdEfPhijYT5mnFPiQNP/isC+os+P+rV8qHRzUxRNx8WyPTOx+oVkBMm1+XSn00ZqfD3ANfciTZQ==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@fast-check/jest/-/jest-2.1.1.tgz", + "integrity": "sha512-t9m3u3tikj/+Ph+gRLGb7fFS/aqnIafsAc6qhXIFJytkqOFRSF70Y5yUUyTtR0idcb6Ald7AnC0AChLCLxv2Tg==", "dev": true, "funding": [ { @@ -936,10 +1283,10 @@ } ], "dependencies": { - "fast-check": "^3.0.0" + "fast-check": "^3.0.0 || ^4.0.0" }, "peerDependencies": { - "@fast-check/worker": "~0.0.7", + "@fast-check/worker": ">=0.0.7 <0.6.0", "@jest/expect": ">=28.0.0", "@jest/globals": ">=25.5.2" }, @@ -1448,7 +1795,6 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", - "dev": true, "engines": { "node": ">=6.0.0" } @@ -1465,8 +1811,7 @@ "node_modules/@jridgewell/sourcemap-codec": { "version": "1.4.15", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", - "dev": true + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" }, "node_modules/@jridgewell/trace-mapping": { "version": "0.3.19", @@ -1479,57 +1824,56 @@ } }, "node_modules/@matrixai/async-cancellable": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@matrixai/async-cancellable/-/async-cancellable-1.1.1.tgz", - "integrity": "sha512-f0yxu7dHwvffZ++7aCm2WIcCJn18uLcOTdCCwEA3R3KVHYE3TG/JNoTWD9/mqBkAV1AI5vBfJzg27WnF9rOUXQ==" + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@matrixai/async-cancellable/-/async-cancellable-2.0.1.tgz", + "integrity": "sha512-4oZC7RMehzZCfyVLk33fOZpW1Nz4WFxuHzznrjFDBre6FmGb63jc2uWjwn+BKplqyby1J/sdJbjO0iqNcweWHg==" }, "node_modules/@matrixai/async-init": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@matrixai/async-init/-/async-init-1.10.0.tgz", - "integrity": "sha512-JjUFu6rqd+dtTHFJ6z8bjbceuFGBj/APWfJByVsfbEH1DJsOgWERFcW3DBUrS0mgTph4Vl518tsNcsSwKT5Y+g==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@matrixai/async-init/-/async-init-2.1.2.tgz", + "integrity": "sha512-i8Hj9Q/FGM725/LpsUyXk2APHn6y7yV9VmPoayAMkzM54+7p9ylmyxIwpYzw1A2zslrgUUvszg++uSM4a+5REw==", "dependencies": { - "@matrixai/async-locks": "^4.0.0", - "@matrixai/errors": "^1.2.0", - "@matrixai/events": "^3.2.0" + "@matrixai/async-locks": "^5.0.1", + "@matrixai/errors": "^2.1.0", + "@matrixai/events": "^4.0.0" } }, "node_modules/@matrixai/async-locks": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@matrixai/async-locks/-/async-locks-4.0.0.tgz", - "integrity": "sha512-u/3fOdtjOKcDYF8dDoPR1/+7nmOkhxo42eBpXTEgfI0hLPGI37PoW7tjLvwy+O51Quy1HGOwhsR/Dgr4x+euug==", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@matrixai/async-locks/-/async-locks-5.0.2.tgz", + "integrity": "sha512-YX3LUt4okyXPnDpx78PgPQybn8duh/FvWKx0t3UTaJW/0HL0/ZOQEEOsX1qefV1fQps1nKUHfjK1VeqZciCvXQ==", "dependencies": { - "@matrixai/async-cancellable": "^1.1.1", - "@matrixai/errors": "^1.1.7", - "@matrixai/resources": "^1.1.5", - "@matrixai/timer": "^1.1.1" + "@matrixai/async-cancellable": "^2.0.0", + "@matrixai/errors": "^2.0.1", + "@matrixai/resources": "^2.0.0", + "@matrixai/timer": "^2.0.0" } }, "node_modules/@matrixai/contexts": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@matrixai/contexts/-/contexts-1.2.0.tgz", - "integrity": "sha512-MR/B02Kf4UoliP9b/gMMKsvWV6QM4JSPKTIqrhQP2tbOl3FwLI+AIhL3vgYEj1Xw+PP8bY5cr8ontJ8x6AJyMg==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@matrixai/contexts/-/contexts-2.0.2.tgz", + "integrity": "sha512-nI29nv2UP43s+hO+N8SDNxlDHHfj0Evypg5IxZ/Y04o6/InDhCQmZErxMu4ZAOTtt21yuI4zssPRcBQdhtQygA==", "dependencies": { - "@matrixai/async-cancellable": "^1.1.1", - "@matrixai/async-locks": "^4.0.0", - "@matrixai/errors": "^1.1.7", - "@matrixai/resources": "^1.1.5", - "@matrixai/timer": "^1.1.1" + "@matrixai/async-cancellable": "^2.0.0", + "@matrixai/async-locks": "^5.0.1", + "@matrixai/errors": "^2.1.2", + "@matrixai/resources": "^2.0.0", + "@matrixai/timer": "^2.1.0" } }, "node_modules/@matrixai/db": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/@matrixai/db/-/db-5.3.0.tgz", - "integrity": "sha512-MI43pA/XjkNceSUwTvj1ohOzcR/7pCRuhvmhT7u39NnUGQN1kpdxPfHKxDlX2B/zatExRkVNA+sPIhE3+sThYg==", + "version": "6.0.20", + "resolved": "https://registry.npmjs.org/@matrixai/db/-/db-6.0.20.tgz", + "integrity": "sha512-jHXI6baQSh/zQHQhix55B/Fu9y7h/578NKyuBRPzHTGK6TzMEnJZBdyb3EmOQOIHSUjC6Z97x3Nj3KZfXSlQiw==", "hasInstallScript": true, "dependencies": { - "@matrixai/async-init": "^1.9.1", - "@matrixai/async-locks": "^4.0.0", - "@matrixai/errors": "^1.2.0", - "@matrixai/logger": "^3.1.0", - "@matrixai/resources": "^1.1.5", - "@matrixai/workers": "^1.4.0", - "node-gyp-build": "4.4.0", - "threads": "^1.6.5" + "@matrixai/async-init": "^2.0.0", + "@matrixai/async-locks": "^5.0.1", + "@matrixai/errors": "^2.0.1", + "@matrixai/logger": "^4.0.1", + "@matrixai/resources": "^2.0.0", + "@matrixai/workers": "^2.0.0", + "node-gyp-build": "4.4.0" }, "engines": { "msvs": "2019", @@ -1537,47 +1881,47 @@ } }, "node_modules/@matrixai/errors": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@matrixai/errors/-/errors-1.2.0.tgz", - "integrity": "sha512-eZHPHFla5GFmi0O0yGgbtkca+ZjwpDbMz+60NC3y+DzQq6BMoe4gHmPjDalAHTxyxv0+Q+AWJTuV8Ows+IqBfQ==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@matrixai/errors/-/errors-2.1.3.tgz", + "integrity": "sha512-uPH09OHLykjCdX17Piyc1P0kw3pkJC8l2ydr6LzcWUPmP8i38oO9oq2AqX21UeyeBhGvDcBzQk890GUMb6iOIA==", "dependencies": { "ts-custom-error": "3.2.2" } }, "node_modules/@matrixai/events": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/@matrixai/events/-/events-3.2.3.tgz", - "integrity": "sha512-bZrNCwzYeFalGQpn8qa/jgD10mUAwLRbv6xGMI7gGz1f+vE65d3GPoJ6JoFOJSg9iCmRSayQJ+IipH3LMATvDA==" + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@matrixai/events/-/events-4.0.1.tgz", + "integrity": "sha512-75hH7ZTmhM/VXeICXCPiVr/ZxQSoBwXh2HOI3AhD8AGYDDsEJsm4tnDSr/6vT3vS0ryZb3kb9mpAmCeibdrF3w==" }, "node_modules/@matrixai/id": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/@matrixai/id/-/id-3.3.6.tgz", - "integrity": "sha512-BpHX/iYxTMuRYtuTzPxKdf6DSwJNVE/EMjLgf/4DSCLGjhT0RQJ8FKKfZReDfb2cx+BsvqL6/LSFM6lfG8v2dw==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@matrixai/id/-/id-4.0.0.tgz", + "integrity": "sha512-xLwYlK4d75wnpfIF+A0XRS5VmX/aDj/4E/XFkwrYsSDxoiWj7DoRRVSs/ryorwZHgufs/kL8aS1eTKadUQRevg==", "dependencies": { - "multiformats": "^9.4.8", + "multiformats": "^13.3.2", "uuid": "^8.3.2" } }, "node_modules/@matrixai/logger": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@matrixai/logger/-/logger-3.1.2.tgz", - "integrity": "sha512-nNliLCnbg6hGS2+gGtQfeeyVNJzOmvqz90AbrQsHPNiE08l3YsENL2JQt9d454SorD1Ud51ymZdDCkeMLWY93A==" + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@matrixai/logger/-/logger-4.0.3.tgz", + "integrity": "sha512-cu7e82iwN32H+K8HxsrvrWEYSEj7+RP/iVFhJ4RuacC8/BSOLFOYxry3EchVjrx4FP5G7QP1HnKYXAGpZN/46w==" }, "node_modules/@matrixai/mdns": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@matrixai/mdns/-/mdns-1.2.6.tgz", - "integrity": "sha512-D42oPeGqMi9mC957N1bN3c+W0N2Vyk5GjXtsk/B2AnKilXtQyzjzFEuQXrMBsL7/nsM/ovv3cy/J7V86rwyShQ==", + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@matrixai/mdns/-/mdns-2.0.7.tgz", + "integrity": "sha512-b2aGHOAIgA+pws6IShqsyNnCck3yuyrEQABuilz0yhcqvg1h0f4G10Fr+5XH7NsVrIdC7s3wM0h/wpCXJPuPTA==", "hasInstallScript": true, "dependencies": { - "@matrixai/async-cancellable": "^1.1.1", - "@matrixai/async-init": "^1.10.0", - "@matrixai/contexts": "^1.1.0", - "@matrixai/errors": "^1.1.7", - "@matrixai/events": "^3.2.0", - "@matrixai/logger": "^3.1.0", - "@matrixai/table": "^1.2.0", - "@matrixai/timer": "^1.1.1", - "canonicalize": "^2.0.0", + "@matrixai/async-cancellable": "^2.0.1", + "@matrixai/async-init": "^2.1.2", + "@matrixai/contexts": "^2.0.2", + "@matrixai/errors": "^2.1.3", + "@matrixai/events": "^4.0.1", + "@matrixai/logger": "^4.0.3", + "@matrixai/table": "^2.0.0", + "@matrixai/timer": "^2.1.1", + "canonicalize": "^2.1.0", "ip-num": "^1.5.1" }, "engines": { @@ -1585,13 +1929,13 @@ "node": "^20.5.1" }, "optionalDependencies": { - "@matrixai/mdns-linux-x64": "1.2.6" + "@matrixai/mdns-linux-x64": "2.0.7" } }, "node_modules/@matrixai/mdns-linux-x64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@matrixai/mdns-linux-x64/-/mdns-linux-x64-1.2.6.tgz", - "integrity": "sha512-2VjyuEz853l8QDZ9vWbVCjZFtReblJl5vsGdjk76ZanLb2ipCX5/JI3HvKUehaWGn+x1gbdJbvUP8gibWhbNRQ==", + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@matrixai/mdns-linux-x64/-/mdns-linux-x64-2.0.7.tgz", + "integrity": "sha512-yuSJ+nFZhbmmmoAB9Cl2O3evdCBOQGT2GMHLzoUn4UgGqZuwb9NJ8tMXei90WdGIfEuTj5YBzusFEfMJNPmC/g==", "cpu": [ "x64" ], @@ -1601,38 +1945,41 @@ ] }, "node_modules/@matrixai/mdns/node_modules/canonicalize": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/canonicalize/-/canonicalize-2.0.0.tgz", - "integrity": "sha512-ulDEYPv7asdKvqahuAY35c1selLdzDwHqugK92hfkzvlDCwXRRelDkR+Er33md/PtnpqHemgkuDPanZ4fiYZ8w==" + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/canonicalize/-/canonicalize-2.1.0.tgz", + "integrity": "sha512-F705O3xrsUtgt98j7leetNhTWPe+5S72rlL5O4jA1pKqBVQ/dT1O1D6PFxmSXvc0SUOinWS57DKx0I3CHrXJHQ==", + "bin": { + "canonicalize": "bin/canonicalize.js" + } }, "node_modules/@matrixai/quic": { - "version": "1.3.13", - "resolved": "https://registry.npmjs.org/@matrixai/quic/-/quic-1.3.13.tgz", - "integrity": "sha512-hZ2ojPyfih4wfVf8ayG2SHonue83Id/W5HPCEYMMeBXc5W9saV99MG2mKrPnLUmOR+im78Bgi3XrVcVrB0uNDw==", - "dependencies": { - "@matrixai/async-cancellable": "^1.1.1", - "@matrixai/async-init": "^1.10.0", - "@matrixai/async-locks": "^4.0.0", - "@matrixai/contexts": "^1.2.0", - "@matrixai/errors": "^1.2.0", - "@matrixai/events": "^3.2.3", - "@matrixai/logger": "^3.1.2", - "@matrixai/resources": "^1.1.5", - "@matrixai/timer": "^1.1.3", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/@matrixai/quic/-/quic-2.0.9.tgz", + "integrity": "sha512-3Ld/RTZsqOVTggOYalt0U9yCmoseY9IfzUM+QOSU5+nxCs23ds4ol7dmbXon9NcGXsuePs6UkVFsNwwL7x9ZlQ==", + "dependencies": { + "@matrixai/async-cancellable": "^2.0.1", + "@matrixai/async-init": "^2.1.2", + "@matrixai/async-locks": "^5.0.2", + "@matrixai/contexts": "^2.0.2", + "@matrixai/errors": "^2.1.3", + "@matrixai/events": "^4.0.1", + "@matrixai/logger": "^4.0.3", + "@matrixai/resources": "^2.0.1", + "@matrixai/timer": "^2.1.1", "ip-num": "^1.5.0" }, "optionalDependencies": { - "@matrixai/quic-darwin-arm64": "1.3.13", - "@matrixai/quic-darwin-universal": "1.3.13", - "@matrixai/quic-darwin-x64": "1.3.13", - "@matrixai/quic-linux-x64": "1.3.13", - "@matrixai/quic-win32-x64": "1.3.13" + "@matrixai/quic-darwin-arm64": "2.0.9", + "@matrixai/quic-darwin-universal": "2.0.9", + "@matrixai/quic-darwin-x64": "2.0.9", + "@matrixai/quic-linux-x64": "2.0.9", + "@matrixai/quic-win32-x64": "2.0.9" } }, "node_modules/@matrixai/quic-darwin-arm64": { - "version": "1.3.13", - "resolved": "https://registry.npmjs.org/@matrixai/quic-darwin-arm64/-/quic-darwin-arm64-1.3.13.tgz", - "integrity": "sha512-cnosZctgd6W8KaTHMnxiy/0eWmLjN7ciuOLzmYooZeOCXKGCTxyKpHYBXylSKvL1i8Jm0725tk9InbEegViJmw==", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/@matrixai/quic-darwin-arm64/-/quic-darwin-arm64-2.0.9.tgz", + "integrity": "sha512-PLJvRXmeTJ2OLPnnDP8GBbXjGns2ltouZOcZqJB60DTIR+ijH6LAflvCw+0JT6a6jByD3gjRqSUIGsPbK7OMWg==", "cpu": [ "arm64" ], @@ -1642,9 +1989,9 @@ ] }, "node_modules/@matrixai/quic-darwin-universal": { - "version": "1.3.13", - "resolved": "https://registry.npmjs.org/@matrixai/quic-darwin-universal/-/quic-darwin-universal-1.3.13.tgz", - "integrity": "sha512-pnoPZFD2FPrtPKa7mvho6c1YKKXBeIT5KlJ4QNMfx3UKh8XZCYGXWSJs8NlhAl6VdzN/3ik9glIGxTPLHtJjSQ==", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/@matrixai/quic-darwin-universal/-/quic-darwin-universal-2.0.9.tgz", + "integrity": "sha512-WjhxEoHIrIVpxBrIJH1Iy9jXDJygniXZxqGKTJd5+VrBttPn7ab9Ywe2SEly6DTH+rk8UlhTQpSgqz1Z+v5eww==", "cpu": [ "x64", "arm64" @@ -1655,9 +2002,9 @@ ] }, "node_modules/@matrixai/quic-darwin-x64": { - "version": "1.3.13", - "resolved": "https://registry.npmjs.org/@matrixai/quic-darwin-x64/-/quic-darwin-x64-1.3.13.tgz", - "integrity": "sha512-wsLmrr98Ae4104LTlx/Tgt5WN4rs0uzUpYFlvAiW2KmoS5tVEXm8eBwUj2HHp6xmuKrlT5ERU06HFhZFsGmXuA==", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/@matrixai/quic-darwin-x64/-/quic-darwin-x64-2.0.9.tgz", + "integrity": "sha512-J/RAWtbz7UMcaUTsgbbvBeXSwfZpq+DMkhfXhsqECgUwBAAsDW5UyZlemD/5mgYhYyFiwcaybOkttj11bKqyOg==", "cpu": [ "x64" ], @@ -1667,9 +2014,9 @@ ] }, "node_modules/@matrixai/quic-linux-x64": { - "version": "1.3.13", - "resolved": "https://registry.npmjs.org/@matrixai/quic-linux-x64/-/quic-linux-x64-1.3.13.tgz", - "integrity": "sha512-dCMnMQf8t0qy7no3vyuETw9abKUtia7UGN0sGAZygjscYWRXtLMuoNyiHNSTaORP0pVIYl3rPDD39BuevcqtrA==", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/@matrixai/quic-linux-x64/-/quic-linux-x64-2.0.9.tgz", + "integrity": "sha512-2m2mBp2c+qdlh3mBbHT7iHqLGPksFJGxxKWcJRJXiHUnyeh9M5gMXia2bWc7VXty0n6eGZak4txD8CPaeINDRQ==", "cpu": [ "x64" ], @@ -1679,9 +2026,9 @@ ] }, "node_modules/@matrixai/quic-win32-x64": { - "version": "1.3.13", - "resolved": "https://registry.npmjs.org/@matrixai/quic-win32-x64/-/quic-win32-x64-1.3.13.tgz", - "integrity": "sha512-mmDv7B0kkF2E64DnZ2OXLYDCbWy148uG7cgtgyf+d7iWbCrx90uX4vSsyUTbg74/xjPKxX+tJOJFRnEeMlfV6w==", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/@matrixai/quic-win32-x64/-/quic-win32-x64-2.0.9.tgz", + "integrity": "sha512-VNdEh74Db/pX2BByuYaZ/3haGCejrAfDmVe+7OD/FKlHyIJkicKWjhNaeTDK2Nh2laaRF54MDZV+1FqO6TGePg==", "cpu": [ "x64" ], @@ -1691,65 +2038,65 @@ ] }, "node_modules/@matrixai/resources": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@matrixai/resources/-/resources-1.1.5.tgz", - "integrity": "sha512-m/DEZEe3wHqWEPTyoBtzFF6U9vWYhEnQtGgwvqiAlTxTM0rk96UBpWjDZCTF/vYG11ZlmlQFtg5H+zGgbjaB3Q==" + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@matrixai/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-qP7wDz1HnQY7wV4NxybAE+A+488D7bGkkdgk2TIRaw8/fTWENi9Y/AFvOJrdKt3q5rDybB4OeTJIkN5qULE35A==" }, "node_modules/@matrixai/rpc": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/@matrixai/rpc/-/rpc-0.6.3.tgz", - "integrity": "sha512-jLR+SpAnv6NR2xRtXGBnyBGipLBv/Nnn/8b6OYx2loyNT4WHoxtqh51U6QwKCHU6qZii/K/2L5XRRKxYUgmmVg==", - "dependencies": { - "@matrixai/async-init": "^1.10.0", - "@matrixai/contexts": "^1.2.0", - "@matrixai/errors": "^1.2.0", - "@matrixai/events": "^3.2.3", - "@matrixai/logger": "^3.1.2", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@matrixai/rpc/-/rpc-1.0.0.tgz", + "integrity": "sha512-VwplA8PLxoRs4YdkoVM5YsRWBtdpv/R4gookK3jmZSsymI4KSEHs/mP6ndotimy/qbajnzMtbJwHt7DEH0tW5w==", + "dependencies": { + "@matrixai/async-init": "^2.1.2", + "@matrixai/contexts": "^2.0.2", + "@matrixai/errors": "^2.1.3", + "@matrixai/events": "^4.0.1", + "@matrixai/logger": "^4.0.3", "@streamparser/json": "^0.0.17" } }, "node_modules/@matrixai/table": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@matrixai/table/-/table-1.2.0.tgz", - "integrity": "sha512-vMj9YygnigmtBVgbzhKQdchtRuPqGL6vutqRGTC0tcZKHYiNh08N6AGQMXoIUe+iYP9A1WNYg2M3LXZZ54xvGg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@matrixai/table/-/table-2.0.0.tgz", + "integrity": "sha512-DpgPQhtn3eNiDC+HCLRruipv7I3CCBo71U0Yw562FgpGB+fa3YNjvl9+nXULkrUS+3OIWa81vnhjVU0rXyfMBw==", "dependencies": { "resource-counter": "^1.2.4" } }, "node_modules/@matrixai/timer": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@matrixai/timer/-/timer-1.1.3.tgz", - "integrity": "sha512-BG5bAZMIt7qxc9iqAOCk2zm7V0+yNQLwp+WhsWVkP25Nvd1klqKpScE1lGwoLA27ygxEi+8IRU3wa8PLrhs0DQ==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@matrixai/timer/-/timer-2.1.1.tgz", + "integrity": "sha512-8N4t3eISASJttKIuQKitVfCNxfaUp1Tritg9/92biGDxVwoP+Err8FVrjG30yWz56K/H+T9xUcZ58AH/mk15Sw==", "dependencies": { - "@matrixai/async-cancellable": "^1.1.1", - "@matrixai/errors": "^1.1.7" + "@matrixai/async-cancellable": "^2.0.0", + "@matrixai/errors": "^2.0.1" } }, "node_modules/@matrixai/workers": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@matrixai/workers/-/workers-1.4.0.tgz", - "integrity": "sha512-2WPVPChVWNPFBoabd/4/46kLhe2cnwP9yx1h9D4+Fj9Ctm4r9h+AvnB1jAJ1OgKDTRl22WNsZDfa6Aj1cyzI0Q==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@matrixai/workers/-/workers-2.0.0.tgz", + "integrity": "sha512-hko/uZHxc7ps57gW3ZQCFTlgz7XFeUVgaY9aRaVFxyVLpCfTL59n0PKAxwbXyb67y+Tb3wayBoejgCbtB7k6YA==", "dependencies": { - "@matrixai/async-init": "^1.9.1", - "@matrixai/errors": "^1.2.0", - "@matrixai/logger": "^3.1.0", - "threads": "^1.6.5" + "@matrixai/async-init": "^2.1.2", + "@matrixai/errors": "^2.1.3", + "@matrixai/logger": "^4.0.3", + "rxjs": "^7.8.2", + "ts-node": "^10.9.1" } }, "node_modules/@matrixai/ws": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/@matrixai/ws/-/ws-1.1.7.tgz", - "integrity": "sha512-VISB1o6FdlPS0MJAJuMQq6dnfpltVVtYThaFsS3m21UMKShM/Y7+eIyCcuQaDCFWcKa3FBEQSHYmjK5/oBtwwQ==", - "dependencies": { - "@matrixai/async-cancellable": "^1.1.1", - "@matrixai/async-init": "^1.10.0", - "@matrixai/async-locks": "^4.0.0", - "@matrixai/contexts": "^1.2.0", - "@matrixai/errors": "^1.2.0", - "@matrixai/events": "^3.2.0", - "@matrixai/logger": "^3.1.0", - "@matrixai/resources": "^1.1.5", - "@matrixai/timer": "^1.1.1", + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@matrixai/ws/-/ws-2.0.5.tgz", + "integrity": "sha512-0dvLlQw06lSVm/+JWlOVN/F7YJyTdgdtT40rSGWgLm8weGoFm5iY6kcHRSH4PLL9vkRrNEAtaxpbpam3/9A8VA==", + "dependencies": { + "@matrixai/async-cancellable": "^2.0.1", + "@matrixai/async-init": "^2.1.2", + "@matrixai/async-locks": "^5.0.2", + "@matrixai/contexts": "^2.0.2", + "@matrixai/errors": "^2.1.3", + "@matrixai/events": "^4.0.1", + "@matrixai/logger": "^4.0.3", + "@matrixai/timer": "^2.1.1", "ip-num": "^1.5.0", "resource-counter": "^1.2.4", "ws": "^8.13.0" @@ -2035,7 +2382,7 @@ "version": "1.3.82", "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.3.82.tgz", "integrity": "sha512-jpC1a18HMH67018Ij2jh+hT7JBFu7ZKcQVfrZ8K6JuEY+kjXmbea07P9MbQUZbAe0FB+xi3CqEVCP73MebodJQ==", - "dev": true, + "devOptional": true, "hasInstallScript": true, "dependencies": { "@swc/types": "^0.1.4" @@ -2075,7 +2422,6 @@ "cpu": [ "arm64" ], - "dev": true, "optional": true, "os": [ "darwin" @@ -2091,7 +2437,6 @@ "cpu": [ "x64" ], - "dev": true, "optional": true, "os": [ "darwin" @@ -2107,7 +2452,6 @@ "cpu": [ "arm" ], - "dev": true, "optional": true, "os": [ "linux" @@ -2123,7 +2467,6 @@ "cpu": [ "arm64" ], - "dev": true, "optional": true, "os": [ "linux" @@ -2139,7 +2482,6 @@ "cpu": [ "arm64" ], - "dev": true, "optional": true, "os": [ "linux" @@ -2155,7 +2497,6 @@ "cpu": [ "x64" ], - "dev": true, "optional": true, "os": [ "linux" @@ -2171,7 +2512,6 @@ "cpu": [ "x64" ], - "dev": true, "optional": true, "os": [ "linux" @@ -2187,7 +2527,6 @@ "cpu": [ "arm64" ], - "dev": true, "optional": true, "os": [ "win32" @@ -2203,7 +2542,6 @@ "cpu": [ "ia32" ], - "dev": true, "optional": true, "os": [ "win32" @@ -2219,7 +2557,6 @@ "cpu": [ "x64" ], - "dev": true, "optional": true, "os": [ "win32" @@ -2248,31 +2585,27 @@ "version": "0.1.5", "resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.5.tgz", "integrity": "sha512-myfUej5naTBWnqOCc/MdVOLVjXUXtIA+NpDrDBKJtLLg2shUjBu3cZmB/85RyitKc55+lUUyl7oRfLOvkr2hsw==", - "dev": true + "devOptional": true }, "node_modules/@tsconfig/node10": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", - "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==", - "dev": true + "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==" }, "node_modules/@tsconfig/node12": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", - "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", - "dev": true + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==" }, "node_modules/@tsconfig/node14": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", - "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", - "dev": true + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==" }, "node_modules/@tsconfig/node16": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", - "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", - "dev": true + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==" }, "node_modules/@types/babel__core": { "version": "7.20.2", @@ -2389,7 +2722,6 @@ "version": "20.8.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.5.tgz", "integrity": "sha512-SPlobFgbidfIeOYlzXiEjSYeIJiOCthv+9tSQVpvk4PAdIIc+2SmjNVzWXk9t0Y7dl73Zdf+OgXKHX9XtkqUpw==", - "dev": true, "dependencies": { "undici-types": "~5.25.1" } @@ -2639,7 +2971,6 @@ "version": "8.10.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", - "dev": true, "bin": { "acorn": "bin/acorn" }, @@ -2660,7 +2991,6 @@ "version": "8.2.0", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", - "dev": true, "engines": { "node": ">=0.4.0" } @@ -2753,8 +3083,7 @@ "node_modules/arg": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", - "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", - "dev": true + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==" }, "node_modules/argparse": { "version": "2.0.1", @@ -3188,18 +3517,6 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, - "node_modules/bs-logger": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", - "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", - "dev": true, - "dependencies": { - "fast-json-stable-stringify": "2.x" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/bser": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", @@ -3246,6 +3563,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, "engines": { "node": ">=6" } @@ -3520,8 +3838,7 @@ "node_modules/create-require": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", - "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", - "dev": true + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==" }, "node_modules/cross-fetch": { "version": "3.1.8", @@ -3574,6 +3891,7 @@ "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, "dependencies": { "ms": "2.1.2" }, @@ -3827,7 +4145,6 @@ "version": "4.0.2", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", - "dev": true, "engines": { "node": ">=0.3.1" } @@ -3946,23 +4263,22 @@ "dev": true }, "node_modules/encryptedfs": { - "version": "3.5.8", - "resolved": "https://registry.npmjs.org/encryptedfs/-/encryptedfs-3.5.8.tgz", - "integrity": "sha512-NDTQvfeLfWGbgq5ceJwyE4fiwE1z1F5eNI6U7iMYDJLvYblEFCJ8B4x9xOR/vknBCQ3CrrvGVvamX8NPCnMOPA==", - "dependencies": { - "@matrixai/async-init": "^1.8.4", - "@matrixai/async-locks": "^4.0.0", - "@matrixai/db": "^5.2.0", - "@matrixai/errors": "^1.1.7", - "@matrixai/logger": "^3.1.0", - "@matrixai/resources": "^1.1.5", - "@matrixai/workers": "^1.3.7", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/encryptedfs/-/encryptedfs-4.0.2.tgz", + "integrity": "sha512-ipetavt0jnWHLEmN6puzbJ2H0R7eXW/HMju8lC9z4QWC0fRjgj+OQfQoSc9YqZkKobq45sCTrl8iw4B0bxw8ow==", + "dependencies": { + "@matrixai/async-init": "^2.1.2", + "@matrixai/async-locks": "^5.0.2", + "@matrixai/db": "^6.0.20", + "@matrixai/errors": "^2.1.3", + "@matrixai/logger": "^4.0.3", + "@matrixai/resources": "^2.0.1", + "@matrixai/workers": "^2.0.0", "errno": "^0.1.7", "lexicographic-integer": "^1.1.0", "node-forge": "^1.3.1", "readable-stream": "^3.6.0", "resource-counter": "^1.2.4", - "threads": "^1.6.5", "util-callbackify": "^1.0.0" } }, @@ -4092,6 +4408,43 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/esbuild": { + "version": "0.18.20", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.18.20.tgz", + "integrity": "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/android-arm": "0.18.20", + "@esbuild/android-arm64": "0.18.20", + "@esbuild/android-x64": "0.18.20", + "@esbuild/darwin-arm64": "0.18.20", + "@esbuild/darwin-x64": "0.18.20", + "@esbuild/freebsd-arm64": "0.18.20", + "@esbuild/freebsd-x64": "0.18.20", + "@esbuild/linux-arm": "0.18.20", + "@esbuild/linux-arm64": "0.18.20", + "@esbuild/linux-ia32": "0.18.20", + "@esbuild/linux-loong64": "0.18.20", + "@esbuild/linux-mips64el": "0.18.20", + "@esbuild/linux-ppc64": "0.18.20", + "@esbuild/linux-riscv64": "0.18.20", + "@esbuild/linux-s390x": "0.18.20", + "@esbuild/linux-x64": "0.18.20", + "@esbuild/netbsd-x64": "0.18.20", + "@esbuild/openbsd-x64": "0.18.20", + "@esbuild/sunos-x64": "0.18.20", + "@esbuild/win32-arm64": "0.18.20", + "@esbuild/win32-ia32": "0.18.20", + "@esbuild/win32-x64": "0.18.20" + } + }, "node_modules/escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", @@ -4431,15 +4784,6 @@ "node": "*" } }, - "node_modules/esm": { - "version": "3.2.25", - "resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz", - "integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==", - "optional": true, - "engines": { - "node": ">=6" - } - }, "node_modules/espree": { "version": "9.6.1", "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", @@ -4579,9 +4923,9 @@ } }, "node_modules/fast-check": { - "version": "3.13.1", - "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.13.1.tgz", - "integrity": "sha512-Xp00tFuWd83i8rbG/4wU54qU+yINjQha7bXH2N4ARNTkyOimzHtUBJ5+htpdXk7RMaCOD/j2jxSjEt9u9ZPNeQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.0.1.tgz", + "integrity": "sha512-Z91jcH02ySQBQlKrCIs3tKTEHdkzOqQhHW5Mg4aZRo4lbI39a28jrFlik6FaRUNzm823VDDTtAi5AEV6lZZprQ==", "dev": true, "funding": [ { @@ -4594,12 +4938,28 @@ } ], "dependencies": { - "pure-rand": "^6.0.0" + "pure-rand": "^7.0.0" }, "engines": { - "node": ">=8.0.0" + "node": ">=12.17.0" } }, + "node_modules/fast-check/node_modules/pure-rand": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-7.0.1.tgz", + "integrity": "sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ] + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -4890,6 +5250,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-tsconfig": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.10.0.tgz", + "integrity": "sha512-kGzZ3LWWQcGIAmg6iWvXn0ei6WDtV26wzHRMwDSzmAbcXrTEXxHy6IehI6/4eT6VRKyMP1eF1VqwrVUmE/LR7A==", + "dev": true, + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, "node_modules/glob": { "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", @@ -5420,17 +5792,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-observable": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-observable/-/is-observable-2.1.0.tgz", - "integrity": "sha512-DailKdLb0WU+xX8K5w7VsJhapwHLZ9jjmazqCJq4X12CTgqq73TKnbRcnSLuXYPOoLQgV5IrD7ePiX/h1vnkBw==", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/is-path-inside": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", @@ -5658,20 +6019,6 @@ "node": ">=8" } }, - "node_modules/ix": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/ix/-/ix-5.0.0.tgz", - "integrity": "sha512-6LyyrHnvNrSy5pKtW/KA+KKusHrB223aBJCJlIGPN7QBfDkEEtNrAkAz9lLLShIcdJntq6BiPCHuKaCM/9wwXw==", - "dependencies": { - "@types/node": "^13.7.4", - "tslib": "^2.3.0" - } - }, - "node_modules/ix/node_modules/@types/node": { - "version": "13.13.52", - "resolved": "https://registry.npmjs.org/@types/node/-/node-13.13.52.tgz", - "integrity": "sha512-s3nugnZumCC//n4moGGe6tkNMyYEdaDBitVjwPxXmR5lnMG5dHePinH2EdxkG3Rh1ghFHHixAG4NJhpJW1rthQ==" - }, "node_modules/jest": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", @@ -6468,12 +6815,6 @@ "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", "dev": true }, - "node_modules/lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", - "dev": true - }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -6531,8 +6872,7 @@ "node_modules/make-error": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" }, "node_modules/makeerror": { "version": "1.0.12", @@ -6648,12 +6988,13 @@ "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true }, "node_modules/multiformats": { - "version": "9.9.0", - "resolved": "https://registry.npmjs.org/multiformats/-/multiformats-9.9.0.tgz", - "integrity": "sha512-HoMUjhH9T8DDBNT+6xzkrd9ga/XiBI4xLr58LJACwK6G3HTOPeMz4nB4KJs33L2BelrIJa7P0VuNaVF3hMYfjg==" + "version": "13.3.2", + "resolved": "https://registry.npmjs.org/multiformats/-/multiformats-13.3.2.tgz", + "integrity": "sha512-qbB0CQDt3QKfiAzZ5ZYjLFOs+zW43vA4uyM8g27PeEuXZybUOFyjrVdP93HPBHMoglibwfkdVwbzfUq8qGcH6g==" }, "node_modules/napi-macros": { "version": "2.2.2", @@ -6850,11 +7191,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/observable-fns": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/observable-fns/-/observable-fns-0.6.1.tgz", - "integrity": "sha512-9gRK4+sRWzeN6AOewNBTLXir7Zl/i3GB6Yl26gK4flxz8BXVpD3kt8amREmWNb0mxYOGDotvE5a4N+PtGGKdkg==" - }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -7416,6 +7752,15 @@ "node": ">=4" } }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, "node_modules/resolve.exports": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz", @@ -7513,6 +7858,14 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "dependencies": { + "tslib": "^2.1.0" + } + }, "node_modules/safe-array-concat": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.0.1.tgz", @@ -8064,37 +8417,11 @@ "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", "dev": true }, - "node_modules/threads": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/threads/-/threads-1.7.0.tgz", - "integrity": "sha512-Mx5NBSHX3sQYR6iI9VYbgHKBLisyB+xROCBGjjWm1O9wb9vfLxdaGtmT/KCjUqMsSNW6nERzCW3T6H43LqjDZQ==", - "dependencies": { - "callsites": "^3.1.0", - "debug": "^4.2.0", - "is-observable": "^2.1.0", - "observable-fns": "^0.6.1" - }, - "funding": { - "url": "https://github.com/andywer/threads.js?sponsor=1" - }, - "optionalDependencies": { - "tiny-worker": ">= 2" - } - }, "node_modules/tiny-inflate": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==" }, - "node_modules/tiny-worker": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tiny-worker/-/tiny-worker-2.3.0.tgz", - "integrity": "sha512-pJ70wq5EAqTAEl9IkGzA+fN0836rycEuz2Cn6yeZ6FRzlVS5IDOkFHpIoEsksPRQV34GDqXm65+OlnZqUSyK2g==", - "optional": true, - "dependencies": { - "esm": "^3.2.25" - } - }, "node_modules/titleize": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/titleize/-/titleize-3.0.0.tgz", @@ -8147,54 +8474,10 @@ "node": ">=14.0.0" } }, - "node_modules/ts-jest": { - "version": "29.1.1", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.1.tgz", - "integrity": "sha512-D6xjnnbP17cC85nliwGiL+tpoKN0StpgE0TeOjXQTU6MVCfsB4v7aW05CgQ/1OywGb0x/oy9hHFnN+sczTiRaA==", - "dev": true, - "dependencies": { - "bs-logger": "0.x", - "fast-json-stable-stringify": "2.x", - "jest-util": "^29.0.0", - "json5": "^2.2.3", - "lodash.memoize": "4.x", - "make-error": "1.x", - "semver": "^7.5.3", - "yargs-parser": "^21.0.1" - }, - "bin": { - "ts-jest": "cli.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": ">=7.0.0-beta.0 <8", - "@jest/types": "^29.0.0", - "babel-jest": "^29.0.0", - "jest": "^29.0.0", - "typescript": ">=4.3 <6" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "@jest/types": { - "optional": true - }, - "babel-jest": { - "optional": true - }, - "esbuild": { - "optional": true - } - } - }, "node_modules/ts-node": { "version": "10.9.1", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", - "dev": true, "dependencies": { "@cspotcode/source-map-support": "^0.8.0", "@tsconfig/node10": "^1.0.7", @@ -8292,6 +8575,33 @@ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", "dev": true }, + "node_modules/tsx": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-3.14.0.tgz", + "integrity": "sha512-xHtFaKtHxM9LOklMmJdI3BEnQq/D5F73Of2E1GDrITi9sgoVkvIsrQUTY1G8FlmGtA+awCI4EBlTRRYxkL2sRg==", + "dev": true, + "dependencies": { + "esbuild": "~0.18.20", + "get-tsconfig": "^4.7.2", + "source-map-support": "^0.5.21" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/tsx/node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, "node_modules/tsyringe": { "version": "4.8.0", "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.8.0.tgz", @@ -8442,7 +8752,6 @@ "version": "5.1.6", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz", "integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==", - "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -8468,8 +8777,7 @@ "node_modules/undici-types": { "version": "5.25.3", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.25.3.tgz", - "integrity": "sha512-Ga1jfYwRn7+cP9v8auvEXN1rX3sWqlayd4HP7OKk4mZWylEmu3KzXDUGrQUN6Ol7qo1gPvB2e5gX6udnyEPgdA==", - "dev": true + "integrity": "sha512-Ga1jfYwRn7+cP9v8auvEXN1rX3sWqlayd4HP7OKk4mZWylEmu3KzXDUGrQUN6Ol7qo1gPvB2e5gX6udnyEPgdA==" }, "node_modules/unicode-trie": { "version": "2.0.0", @@ -8565,8 +8873,7 @@ "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", - "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", - "dev": true + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==" }, "node_modules/v8-to-istanbul": { "version": "9.1.3", @@ -8780,7 +9087,6 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", - "dev": true, "engines": { "node": ">=6" } diff --git a/package.json b/package.json index 4dfd95cea3..0fbec124b0 100644 --- a/package.json +++ b/package.json @@ -51,39 +51,52 @@ "type": "git", "url": "https://github.com/MatrixAI/Polykey.git" }, - "main": "dist/index.js", - "types": "dist/index.d.ts", + "type": "module", + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./*.js": { + "types": "./dist/*.d.ts", + "import": "./dist/*.js" + }, + "./*": "./dist/*" + }, + "imports": { + "#*": "./dist/*" + }, "scripts": { "prepare": "tsc -p ./tsconfig.build.json", "build": "shx rm -rf ./dist && tsc -p ./tsconfig.build.json", "postbuild": "shx cp -f src/status/*.json dist/status/ && shx cp -f src/tokens/schemas/*.json dist/tokens/schemas/", "postversion": "npm install --package-lock-only --ignore-scripts --silent", - "ts-node": "ts-node", - "ts-node-inspect": "node --require ts-node/register --inspect", - "test": "jest", - "lint": "eslint '{src,tests,scripts}/**/*.{js,ts,json}' 'benches/**/*.{js,ts}'", - "lintfix": "eslint '{src,tests,scripts}/**/*.{js,ts,json}' 'benches/**/*.{js,ts}' --fix", + "tsx": "tsx", + "test": "node ./scripts/test.mjs", + "lint": "eslint '{src,tests,scripts,benches}/**/*.{js,mjs,ts,mts,jsx,tsx}'", + "lintfix": "eslint '{src,tests,scripts,benches}/**/*.{js,mjs,ts,mts,jsx,tsx}' --fix", "lint-shell": "find ./src ./tests ./scripts -type f -regextype posix-extended -regex '.*\\.(sh)' -exec shellcheck {} +", "docs": "shx rm -rf ./docs && typedoc --gitRevision master --tsconfig ./tsconfig.build.json --out ./docs src", - "bench": "shx rm -rf ./benches/results && ts-node ./benches" + "bench": "tsc -p ./tsconfig.build.json && shx rm -rf ./benches/results && tsx ./benches/index.ts" }, "dependencies": { - "@matrixai/async-cancellable": "^1.1.1", - "@matrixai/async-init": "^1.10.0", - "@matrixai/async-locks": "^4.0.0", - "@matrixai/contexts": "^1.1.0", - "@matrixai/db": "^5.3.0", - "@matrixai/errors": "^1.2.0", - "@matrixai/events": "^3.2.3", - "@matrixai/id": "^3.3.6", - "@matrixai/logger": "^3.1.2", - "@matrixai/mdns": "^1.2.6", - "@matrixai/quic": "^1.3.13", - "@matrixai/resources": "^1.1.5", - "@matrixai/rpc": "^0.6.2", - "@matrixai/timer": "^1.1.3", - "@matrixai/workers": "^1.3.7", - "@matrixai/ws": "^1.1.7", + "@matrixai/async-cancellable": "^2.0.1", + "@matrixai/async-init": "^2.1.2", + "@matrixai/async-locks": "^5.0.2", + "@matrixai/contexts": "^2.0.2", + "@matrixai/db": "^6.0.20", + "@matrixai/errors": "^2.1.3", + "@matrixai/events": "^4.0.1", + "@matrixai/id": "^4.0.0", + "@matrixai/logger": "^4.0.3", + "@matrixai/mdns": "^2.0.7", + "@matrixai/quic": "^2.0.9", + "@matrixai/resources": "^2.0.1", + "@matrixai/rpc": "^1.0.0", + "@matrixai/timer": "^2.1.1", + "@matrixai/workers": "^2.0.0", + "@matrixai/ws": "^2.0.5", "@peculiar/asn1-pkcs8": "^2.3.0", "@peculiar/asn1-schema": "^2.3.0", "@peculiar/asn1-x509": "^2.3.0", @@ -95,23 +108,21 @@ "cheerio": "^1.0.0-rc.5", "cross-fetch": "^3.0.6", "cross-spawn": "^7.0.3", - "encryptedfs": "^3.5.6", + "encryptedfs": "^4.0.2", "fast-fuzzy": "^1.10.8", "fd-lock": "^1.2.0", "ip-num": "^1.3.3-0", "isomorphic-git": "^1.8.1", - "ix": "^5.0.0", "lexicographic-integer": "^1.1.0", - "multiformats": "^9.4.8", + "multiformats": "^13.3.2", "pako": "^1.0.11", "prompts": "^2.4.1", "resource-counter": "^1.2.4", "sodium-native": "^3.4.1", - "threads": "^1.6.5", "minimatch": "^10.0.1" }, "devDependencies": { - "@fast-check/jest": "^1.1.0", + "@fast-check/jest": "^2.1.1", "@swc/core": "1.3.82", "@swc/jest": "^0.2.29", "@types/cross-spawn": "^6.0.2", @@ -129,7 +140,7 @@ "eslint-config-prettier": "^8.8.0", "eslint-plugin-import": "^2.27.5", "eslint-plugin-prettier": "^5.0.0-alpha.2", - "fast-check": "^3.0.1", + "fast-check": "^4.0.1", "jest": "^29.6.2", "jest-extended": "^4.0.0", "jest-junit": "^16.0.0", @@ -137,9 +148,8 @@ "prettier": "^3.0.0", "shx": "^0.3.4", "systeminformation": "^5.18.5", - "ts-jest": "^29.1.1", "ts-node": "^10.9.1", - "tsconfig-paths": "^3.9.0", + "tsx": "^3.12.7", "typedoc": "^0.24.8", "typescript": "^5.1.6" } diff --git a/scripts/test.mjs b/scripts/test.mjs new file mode 100644 index 0000000000..35db564522 --- /dev/null +++ b/scripts/test.mjs @@ -0,0 +1,48 @@ +#!/usr/bin/env node + +import os from 'node:os'; +import path from 'node:path'; +import url from 'node:url'; +import process from 'node:process'; +import childProcess from 'node:child_process'; + +const projectPath = path.dirname( + path.dirname(url.fileURLToPath(import.meta.url)), +); + +const platform = os.platform(); + +/* eslint-disable no-console */ +async function main(argv = process.argv) { + argv = argv.slice(2); + const tscArgs = [`-p`, path.join(projectPath, 'tsconfig.build.json')]; + console.error('Running tsc:'); + console.error(['tsc', ...tscArgs].join(' ')); + childProcess.execFileSync('tsc', tscArgs, { + stdio: ['inherit', 'inherit', 'inherit'], + windowsHide: true, + encoding: 'utf-8', + shell: platform === 'win32' ? true : false, + }); + const jestArgs = [...argv]; + console.error('Running jest:'); + console.error(['jest', ...jestArgs].join(' ')); + childProcess.execFileSync('jest', jestArgs, { + env: { + ...process.env, + NODE_OPTIONS: '--experimental-vm-modules', + }, + stdio: ['inherit', 'inherit', 'inherit'], + windowsHide: true, + encoding: 'utf-8', + shell: platform === 'win32' ? true : false, + }); +} +/* eslint-enable no-console */ + +if (import.meta.url.startsWith('file:')) { + const modulePath = url.fileURLToPath(import.meta.url); + if (process.argv[1] === modulePath) { + void main(); + } +} diff --git a/src/ErrorPolykey.ts b/src/ErrorPolykey.ts index 05e217729b..85ee67d766 100644 --- a/src/ErrorPolykey.ts +++ b/src/ErrorPolykey.ts @@ -1,6 +1,6 @@ import type { Class } from '@matrixai/errors'; import { AbstractError } from '@matrixai/errors'; -import sysexits from './utils/sysexits'; +import sysexits from './utils/sysexits.js'; class ErrorPolykey extends AbstractError { static description: string = 'Polykey error'; diff --git a/src/PolykeyAgent.ts b/src/PolykeyAgent.ts index c810f638e3..f552ad540b 100644 --- a/src/PolykeyAgent.ts +++ b/src/PolykeyAgent.ts @@ -4,54 +4,51 @@ import type { JSONRPCResponse, MiddlewareFactory, } from '@matrixai/rpc'; -import type { DeepPartial, FileSystem, ObjectEmpty, POJO } from './types'; -import type { PolykeyWorkerManagerInterface } from './workers/types'; -import type { TLSConfig } from './network/types'; -import type { NodeAddress, NodeId, SeedNodes } from './nodes/types'; -import type { Key, PasswordOpsLimit, PasswordMemLimit } from './keys/types'; +import type { DeepPartial, FileSystem, ObjectEmpty, POJO } from './types.js'; +import type { PolykeyWorkerManager } from './workers/types.js'; +import type { TLSConfig } from './network/types.js'; +import type { NodeAddress, NodeId, SeedNodes } from './nodes/types.js'; +import type { PasswordOpsLimit, PasswordMemLimit } from './keys/types.js'; import type { ClientRPCRequestParams, ClientRPCResponseResult, -} from './client/types'; -import path from 'path'; +} from './client/types.js'; +import path from 'node:path'; import process from 'process'; import Logger from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; -import { WorkerManager } from './workers'; -import Audit from './audit/Audit'; -import KeyRing from './keys/KeyRing'; -import CertManager from './keys/CertManager'; -import Status from './status/Status'; -import Schema from './schema/Schema'; -import VaultManager from './vaults/VaultManager'; -import ACL from './acl/ACL'; -import NodeManager from './nodes/NodeManager'; -import NodeGraph from './nodes/NodeGraph'; -import NodeConnectionManager from './nodes/NodeConnectionManager'; -import NotificationsManager from './notifications/NotificationsManager'; -import GestaltGraph from './gestalts/GestaltGraph'; -import Sigchain from './sigchain/Sigchain'; -import Discovery from './discovery/Discovery'; -import SessionManager from './sessions/SessionManager'; -import IdentitiesManager from './identities/IdentitiesManager'; -import * as identityProviders from './identities/providers'; -import TaskManager from './tasks/TaskManager'; -import ClientService from './client/ClientService'; -import config from './config'; -import * as errors from './errors'; -import * as events from './events'; -import * as utils from './utils'; -import * as keysUtils from './keys/utils'; -import * as keysEvents from './keys/events'; -import * as nodesUtils from './nodes/utils'; -import * as workersUtils from './workers/utils'; -import * as clientMiddleware from './client/middleware'; -import clientServerManifest from './client/handlers'; -import agentServerManifest from './nodes/agent/handlers'; +import { createDestroyStartStop } from '@matrixai/async-init'; +import { WorkerManager, polykeyWorkerManifest } from './workers/index.js'; +import Audit from './audit/Audit.js'; +import KeyRing from './keys/KeyRing.js'; +import CertManager from './keys/CertManager.js'; +import Status from './status/Status.js'; +import Schema from './schema/Schema.js'; +import VaultManager from './vaults/VaultManager.js'; +import ACL from './acl/ACL.js'; +import NodeManager from './nodes/NodeManager.js'; +import NodeGraph from './nodes/NodeGraph.js'; +import NodeConnectionManager from './nodes/NodeConnectionManager.js'; +import NotificationsManager from './notifications/NotificationsManager.js'; +import GestaltGraph from './gestalts/GestaltGraph.js'; +import Sigchain from './sigchain/Sigchain.js'; +import Discovery from './discovery/Discovery.js'; +import SessionManager from './sessions/SessionManager.js'; +import IdentitiesManager from './identities/IdentitiesManager.js'; +import * as identityProviders from './identities/providers/index.js'; +import TaskManager from './tasks/TaskManager.js'; +import ClientService from './client/ClientService.js'; +import config from './config.js'; +import * as errors from './errors.js'; +import * as events from './events.js'; +import * as utils from './utils/index.js'; +import * as keysUtils from './keys/utils/index.js'; +import * as keysEvents from './keys/events.js'; +import * as nodesUtils from './nodes/utils.js'; +import * as workersUtils from './workers/utils.js'; +import * as clientMiddleware from './client/middleware.js'; +import clientServerManifest from './client/handlers/index.js'; +import agentServerManifest from './nodes/agent/handlers/index.js'; /** * Optional configuration for `PolykeyAgent`. @@ -112,8 +109,8 @@ type PolykeyAgentOptions = { versionMetadata: POJO; }; -interface PolykeyAgent extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface PolykeyAgent extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new errors.ErrorPolykeyAgentRunning(), new errors.ErrorPolykeyAgentDestroyed(), { @@ -144,7 +141,7 @@ class PolykeyAgent { options = {}, fresh = false, // Optional dependencies - fs = require('fs'), + fs, logger = new Logger(this.name), }: { password: string; @@ -215,6 +212,7 @@ class PolykeyAgent { throw new errors.ErrorUtilsNodePath(); } logger.info(`Setting node path to ${optionsDefaulted.nodePath}`); + fs = await utils.importFS(fs); await utils.mkdirExists(fs, optionsDefaulted.nodePath); const statusPath = path.join( optionsDefaulted.nodePath, @@ -282,20 +280,7 @@ class PolykeyAgent { dbPath, crypto: { key: keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, fs, logger: logger.getChild(DB.name), @@ -556,7 +541,7 @@ class PolykeyAgent { public readonly fs: FileSystem; public readonly logger: Logger; public readonly clientService: ClientService; - protected workerManager: PolykeyWorkerManagerInterface | undefined; + protected workerManager: PolykeyWorkerManager | undefined; protected _startTime: number = 0; protected _versionMetadata: JSONObject; @@ -654,22 +639,22 @@ class PolykeyAgent { this._versionMetadata = versionMetadata; } - @ready(new errors.ErrorPolykeyAgentNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyAgentNotRunning()) get clientServiceHost() { return this.clientService.host; } - @ready(new errors.ErrorPolykeyAgentNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyAgentNotRunning()) get clientServicePort() { return this.clientService.port; } - @ready(new errors.ErrorPolykeyAgentNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyAgentNotRunning()) get agentServiceHost() { return this.nodeConnectionManager.host; } - @ready(new errors.ErrorPolykeyAgentNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyAgentNotRunning()) get agentServicePort() { return this.nodeConnectionManager.port; } @@ -681,7 +666,7 @@ class PolykeyAgent { /** * Returns the time the `PolykeyAgent` was started at in milliseconds since Unix epoch */ - @ready(new errors.ErrorPolykeyAgentNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyAgentNotRunning()) get startTime(): number { return this._startTime; } @@ -748,20 +733,7 @@ class PolykeyAgent { await this.db.start({ crypto: { key: this.keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, fresh, }); @@ -976,20 +948,7 @@ class PolykeyAgent { await this.db.start({ crypto: { key: this.keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); // TaskManager needs to be running for dependent domains to clear state. diff --git a/src/PolykeyClient.ts b/src/PolykeyClient.ts index d6d5f526af..a5ae69d647 100644 --- a/src/PolykeyClient.ts +++ b/src/PolykeyClient.ts @@ -5,33 +5,30 @@ import type { } from '@matrixai/rpc'; import type { PromiseCancellable } from '@matrixai/async-cancellable'; import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts'; -import type { DeepPartial, FileSystem } from './types'; +import type { DeepPartial, FileSystem } from './types.js'; import type { ClientRPCRequestParams, ClientRPCResponseResult, OverrideRPClientType, -} from './client/types'; -import type { NodeId } from './ids/types'; -import path from 'path'; +} from './client/types.js'; +import type { NodeId } from './ids/types.js'; +import path from 'node:path'; import Logger from '@matrixai/logger'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; -import { timedCancellable, context } from '@matrixai/contexts/dist/decorators'; +import { createDestroyStartStop } from '@matrixai/async-init'; +import { decorators } from '@matrixai/contexts'; import { WebSocketClient, events as webSocketEvents } from '@matrixai/ws'; import { RPCClient, middleware as rpcMiddleware } from '@matrixai/rpc'; -import { Session } from './sessions'; -import * as ids from './ids'; -import * as utils from './utils'; -import * as errors from './errors'; -import * as events from './events'; -import * as networkUtils from './network/utils'; -import * as validationErrors from './validation/errors'; -import * as clientUtils from './client/utils'; -import * as clientMiddleware from './client/middleware'; -import clientClientManifest from './client/callers'; -import config from './config'; +import { Session } from './sessions/index.js'; +import * as ids from './ids/index.js'; +import * as utils from './utils/index.js'; +import * as errors from './errors.js'; +import * as events from './events.js'; +import * as networkUtils from './network/utils.js'; +import * as validationErrors from './validation/errors.js'; +import * as clientUtils from './client/utils.js'; +import * as clientMiddleware from './client/middleware.js'; +import clientClientManifest from './client/callers/index.js'; +import config from './config.js'; /** * Optional configuration for`PolykeyClient`. @@ -50,8 +47,8 @@ type PolykeyClientOptions = { >; }; -interface PolykeyClient extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface PolykeyClient extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new errors.ErrorPolykeyClientRunning(), new errors.ErrorPolykeyClientDestroyed(), { @@ -85,7 +82,7 @@ class PolykeyClient { }, ctx?: Partial, ): PromiseCancellable; - @timedCancellable( + @decorators.timedCancellable( true, config.defaultsSystem.clientConnectTimeoutTime, errors.ErrorPolykeyClientCreateTimeout, @@ -100,7 +97,7 @@ class PolykeyClient { options = {}, fresh = false, // Optional dependencies - fs = require('fs'), + fs, logger = new Logger(this.name), }: { nodeId: string | NodeId; @@ -111,7 +108,7 @@ class PolykeyClient { fs?: FileSystem; logger?: Logger; }, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { logger.info(`Creating ${this.name}`); const optionsDefaulted = utils.mergeObjects(options, { @@ -125,6 +122,7 @@ class PolykeyClient { if (optionsDefaulted.nodePath == null) { throw new errors.ErrorUtilsNodePath(); } + fs = await utils.importFS(fs); await utils.mkdirExists(fs, optionsDefaulted.nodePath); const sessionTokenPath = path.join( optionsDefaulted.nodePath, @@ -192,37 +190,37 @@ class PolykeyClient { this.fs = fs; } - @ready(new errors.ErrorPolykeyClientNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyClientNotRunning()) public get nodeId() { return this._nodeId; } - @ready(new errors.ErrorPolykeyClientNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyClientNotRunning()) public get webSocketClient() { return this._webSocketClient; } - @ready(new errors.ErrorPolykeyClientNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyClientNotRunning()) public get rpcClient() { return this._rpcClient; } - @ready(new errors.ErrorPolykeyClientNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyClientNotRunning()) public get host() { return this._webSocketClient.connection.remoteHost; } - @ready(new errors.ErrorPolykeyClientNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyClientNotRunning()) public get port() { return this._webSocketClient.connection.remotePort; } - @ready(new errors.ErrorPolykeyClientNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyClientNotRunning()) public get localHost() { return this._webSocketClient.connection.localHost; } - @ready(new errors.ErrorPolykeyClientNotRunning()) + @createDestroyStartStop.ready(new errors.ErrorPolykeyClientNotRunning()) public get localPort() { return this._webSocketClient.connection.localPort; } @@ -242,7 +240,7 @@ class PolykeyClient { }, ctx?: Partial, ): PromiseCancellable; - @timedCancellable( + @decorators.timedCancellable( true, config.defaultsSystem.clientConnectTimeoutTime, errors.ErrorPolykeyClientCreateTimeout, @@ -266,7 +264,7 @@ class PolykeyClient { }>; fresh?: boolean; }, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { this.logger.info(`Starting ${this.constructor.name}`); const optionsDefaulted = utils.mergeObjects(options, { diff --git a/src/acl/ACL.ts b/src/acl/ACL.ts index cf4d4d5431..c81db8473f 100644 --- a/src/acl/ACL.ts +++ b/src/acl/ACL.ts @@ -4,23 +4,20 @@ import type { PermissionIdString, Permission, VaultActions, -} from './types'; -import type { NodeId } from '../ids/types'; -import type { GestaltAction } from '../gestalts/types'; -import type { VaultAction, VaultId } from '../vaults/types'; -import type { Ref } from '../types'; +} from './types.js'; +import type { NodeId } from '../ids/types.js'; +import type { GestaltAction } from '../gestalts/types.js'; +import type { VaultAction, VaultId } from '../vaults/types.js'; +import type { Ref } from '../types.js'; import Logger from '@matrixai/logger'; import { IdInternal } from '@matrixai/id'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; -import * as aclUtils from './utils'; -import * as aclErrors from './errors'; -import * as events from './events'; +import { createDestroyStartStop } from '@matrixai/async-init'; +import * as aclUtils from './utils.js'; +import * as aclErrors from './errors.js'; +import * as events from './events.js'; -interface ACL extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface ACL extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new aclErrors.ErrorACLRunning(), new aclErrors.ErrorACLDestroyed(), { @@ -99,7 +96,7 @@ class ACL { this.logger.info(`Destroyed ${this.constructor.name}`); } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async sameNodePerm( nodeId1: NodeId, nodeId2: NodeId, @@ -126,7 +123,7 @@ class ACL { return false; } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async getNodePerms( tran?: DBTransaction, ): Promise>> { @@ -163,7 +160,7 @@ class ACL { return nodePerms_; } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async getVaultPerms( tran?: DBTransaction, ): Promise>> { @@ -217,7 +214,7 @@ class ACL { * Gets the permission record for a given node id * Any node id is acceptable */ - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async getNodePerm( nodeId: NodeId, tran?: DBTransaction, @@ -244,7 +241,7 @@ class ACL { * The node ids in the record each represent a unique gestalt * If there are no permissions, then an empty record is returned */ - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async getVaultPerm( vaultId: VaultId, tran?: DBTransaction, @@ -299,7 +296,7 @@ class ACL { return perms; } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async setNodeAction( nodeId: NodeId, action: GestaltAction, @@ -345,7 +342,7 @@ class ACL { } } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async unsetNodeAction( nodeId: NodeId, action: GestaltAction, @@ -371,7 +368,7 @@ class ACL { await tran.put([...this.aclPermsDbPath, permId], permRef, false); } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async setVaultAction( vaultId: VaultId, nodeId: NodeId, @@ -415,7 +412,7 @@ class ACL { ); } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async unsetVaultAction( vaultId: VaultId, nodeId: NodeId, @@ -458,7 +455,7 @@ class ACL { * This is intended for completely new gestalts * Or for gestalt splitting. */ - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async setNodesPerm( nodeIds: Array, perm: Permission, @@ -513,7 +510,7 @@ class ACL { } } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async setNodePerm( nodeId: NodeId, perm: Permission, @@ -555,7 +552,7 @@ class ACL { } } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async unsetNodePerm( nodeId: NodeId, tran?: DBTransaction, @@ -587,7 +584,7 @@ class ACL { // they can be removed later upon inspection } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async unsetVaultPerms( vaultId: VaultId, tran?: DBTransaction, @@ -625,7 +622,7 @@ class ACL { await tran.del([...this.aclVaultsDbPath, vaultId.toBuffer()]); } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async joinNodePerm( nodeId: NodeId, nodeIdsJoin: Array, @@ -682,7 +679,7 @@ class ACL { await tran.put([...this.aclPermsDbPath, permId], permRef, false); } - @ready(new aclErrors.ErrorACLNotRunning()) + @createDestroyStartStop.ready(new aclErrors.ErrorACLNotRunning()) public async joinVaultPerms( vaultId: VaultId, vaultIdsJoin: Array, diff --git a/src/acl/errors.ts b/src/acl/errors.ts index 18d29cb407..c0c605e290 100644 --- a/src/acl/errors.ts +++ b/src/acl/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorACL extends ErrorPolykey {} diff --git a/src/acl/events.ts b/src/acl/events.ts index 3282b4a1ce..65f0ed2baa 100644 --- a/src/acl/events.ts +++ b/src/acl/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventACL extends EventPolykey {} diff --git a/src/acl/index.ts b/src/acl/index.ts index adbff6e07e..7db633b47d 100644 --- a/src/acl/index.ts +++ b/src/acl/index.ts @@ -1,5 +1,5 @@ -export { default as ACL } from './ACL'; -export * as types from './types'; -export * as utils from './utils'; -export * as errors from './errors'; -export * as events from './events'; +export { default as ACL } from './ACL.js'; +export * as types from './types.js'; +export * as utils from './utils.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; diff --git a/src/acl/types.ts b/src/acl/types.ts index a75573b73e..26abb3e04b 100644 --- a/src/acl/types.ts +++ b/src/acl/types.ts @@ -1,6 +1,6 @@ -import type { PermissionId, PermissionIdString } from '../ids/types'; -import type { GestaltActions } from '../gestalts/types'; -import type { VaultActions, VaultIdString } from '../vaults/types'; +import type { PermissionId, PermissionIdString } from '../ids/types.js'; +import type { GestaltActions } from '../gestalts/types.js'; +import type { VaultActions, VaultIdString } from '../vaults/types.js'; type Permission = { gestalt: GestaltActions; diff --git a/src/acl/utils.ts b/src/acl/utils.ts index 1ab02aa2de..43ed81eac7 100644 --- a/src/acl/utils.ts +++ b/src/acl/utils.ts @@ -1,5 +1,5 @@ -import type { Permission } from './types'; -import { createPermIdGenerator } from '../ids'; +import type { Permission } from './types.js'; +import { createPermIdGenerator } from '../ids/index.js'; function permUnion(perm1: Permission, perm2: Permission): Permission { const vaults = { diff --git a/src/audit/Audit.ts b/src/audit/Audit.ts index 4ec611ab05..0a8e3d0125 100644 --- a/src/audit/Audit.ts +++ b/src/audit/Audit.ts @@ -7,27 +7,24 @@ import type { MetricPathToAuditMetric, AuditMetricNodeConnection, AuditEventToAuditEventDB, -} from './types'; -import type { AuditEventId } from '../ids/types'; -import type NodeConnectionManager from '../nodes/NodeConnectionManager'; -import type Discovery from '../discovery/Discovery'; +} from './types.js'; +import type { AuditEventId } from '../ids/types.js'; +import type NodeConnectionManager from '../nodes/NodeConnectionManager.js'; +import type Discovery from '../discovery/Discovery.js'; import type { AbstractEvent } from '@matrixai/events'; import Logger from '@matrixai/logger'; import { IdInternal } from '@matrixai/id'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; -import * as sortableIdUtils from '@matrixai/id/dist/IdSortable'; +import { createDestroyStartStop } from '@matrixai/async-init'; +import { idSortable } from '@matrixai/id'; import { PromiseCancellable } from '@matrixai/async-cancellable'; -import * as auditErrors from './errors'; -import * as auditEvents from './events'; -import * as auditUtils from './utils'; -import * as nodesEvents from '../nodes/events'; -import * as discoveryEvents from '../discovery/events'; +import * as auditErrors from './errors.js'; +import * as auditEvents from './events.js'; +import * as auditUtils from './utils.js'; +import * as nodesEvents from '../nodes/events.js'; +import * as discoveryEvents from '../discovery/events.js'; -interface Audit extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface Audit extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new auditErrors.ErrorAuditRunning(), new auditErrors.ErrorAuditDestroyed(), { @@ -187,7 +184,9 @@ class Audit { this.logger.info(`Destroyed ${this.constructor.name}`); } - @ready(new auditErrors.ErrorAuditNotRunning(), false, ['starting']) + @createDestroyStartStop.ready(new auditErrors.ErrorAuditNotRunning(), false, [ + 'starting', + ]) public async getLastAuditEventId( tran?: DBTransaction, ): Promise { @@ -199,7 +198,9 @@ class Audit { return IdInternal.fromBuffer(lastAuditEventIdBuffer); } - @ready(new auditErrors.ErrorAuditNotRunning(), false, ['starting']) + @createDestroyStartStop.ready(new auditErrors.ErrorAuditNotRunning(), false, [ + 'starting', + ]) protected setEventHandler< T extends typeof AbstractEvent, P extends TopicPath, @@ -228,7 +229,7 @@ class Audit { this.eventHandlerMap.set(event, { target, handler: handler as any }); } - @ready(new auditErrors.ErrorAuditNotRunning()) + @createDestroyStartStop.ready(new auditErrors.ErrorAuditNotRunning()) protected async setAuditEvent( topicPath: TopicPath, auditEvent: TopicSubPathToAuditEvent, @@ -270,7 +271,7 @@ class Audit { }); } - @ready(new auditErrors.ErrorAuditNotRunning()) + @createDestroyStartStop.ready(new auditErrors.ErrorAuditNotRunning()) public async *getAuditEventsLongRunning( topicPath: T, { @@ -371,7 +372,7 @@ class Audit { } } - @ready(new auditErrors.ErrorAuditNotRunning()) + @createDestroyStartStop.ready(new auditErrors.ErrorAuditNotRunning()) public async *getAuditEvents( topicPath: T, { @@ -478,7 +479,7 @@ class Audit { } } - @ready(new auditErrors.ErrorAuditNotRunning()) + @createDestroyStartStop.ready(new auditErrors.ErrorAuditNotRunning()) public async getAuditMetric( metricPath: T, options: { @@ -543,7 +544,7 @@ class Audit { )) { const key = keyPath.at(-1)! as Buffer; if (metric.data.total === 0) { - seekTimestamp = sortableIdUtils.extractTs(key) * 1000; + seekTimestamp = idSortable.extractTs(key) * 1000; } else { lastKey = key; } @@ -551,7 +552,7 @@ class Audit { } if (seekTimestamp != null) { if (lastKey != null) { - seekEndTimestamp = sortableIdUtils.extractTs(lastKey) * 1000; + seekEndTimestamp = idSortable.extractTs(lastKey) * 1000; } else { seekEndTimestamp = Date.now(); } diff --git a/src/audit/errors.ts b/src/audit/errors.ts index 94db98f18b..a6596fc23d 100644 --- a/src/audit/errors.ts +++ b/src/audit/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorAudit extends ErrorPolykey {} diff --git a/src/audit/events.ts b/src/audit/events.ts index b10214f687..f2593da91f 100644 --- a/src/audit/events.ts +++ b/src/audit/events.ts @@ -1,5 +1,5 @@ -import type { TopicPath, TopicSubPathToAuditEvent } from './types'; -import EventPolykey from '../EventPolykey'; +import type { TopicPath, TopicSubPathToAuditEvent } from './types.js'; +import EventPolykey from '../EventPolykey.js'; abstract class EventAudit extends EventPolykey {} diff --git a/src/audit/index.ts b/src/audit/index.ts index 5f4fded00f..c8ae1124a5 100644 --- a/src/audit/index.ts +++ b/src/audit/index.ts @@ -1,5 +1,5 @@ -export { default as Audit } from './Audit'; -export * as types from './types'; -export * as utils from './utils'; -export * as errors from './errors'; -export * as events from './events'; +export { default as Audit } from './Audit.js'; +export * as types from './types.js'; +export * as utils from './utils.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; diff --git a/src/audit/types.ts b/src/audit/types.ts index 0918bc9036..22e21ef9b2 100644 --- a/src/audit/types.ts +++ b/src/audit/types.ts @@ -1,5 +1,5 @@ -import type { AuditEventId, AuditEventIdEncoded } from '../ids'; -import type { ObjectEmpty, POJO } from '../types'; +import type { AuditEventId, AuditEventIdEncoded } from '../ids/index.js'; +import type { ObjectEmpty, POJO } from '../types.js'; import type { nodeConnectionInboundMetricPath, nodeConnectionReverseTopicPath, @@ -14,11 +14,11 @@ import type { nodeConnectionMetricPath, topicPaths, metricPaths, -} from './utils'; +} from './utils.js'; import type { VertexEventError, VertexEventIdentifier, -} from '../discovery/types'; +} from '../discovery/types.js'; // Events diff --git a/src/audit/utils.ts b/src/audit/utils.ts index 8cba7da690..5e6cdea3e0 100644 --- a/src/audit/utils.ts +++ b/src/audit/utils.ts @@ -9,20 +9,20 @@ import type { AuditEventDiscoveryCheckRediscovery, TopicPathTreeNode, TopicSubPath, -} from './types'; -import type * as nodesEvents from '../nodes/events'; -import type * as discoveryEvents from '../discovery/events'; -import type { AuditEventId } from '../ids'; -import type { TopicPath } from './types'; +} from './types.js'; +import type * as nodesEvents from '../nodes/events.js'; +import type * as discoveryEvents from '../discovery/events.js'; +import type { AuditEventId } from '../ids/index.js'; +import type { TopicPath } from './types.js'; import { IdInternal } from '@matrixai/id'; -import * as sortableIdUtils from '@matrixai/id/dist/IdSortable'; -import * as nodesUtils from '../nodes/utils'; +import { idSortable } from '@matrixai/id'; +import * as nodesUtils from '../nodes/utils.js'; import { createAuditEventIdGenerator, encodeAuditEventId, decodeAuditEventId, generateAuditEventIdFromTimestamp, -} from '../ids'; +} from '../ids/index.js'; // Events @@ -37,7 +37,7 @@ function extractFromSeek( let timestamp: number | undefined; if (seek instanceof IdInternal) { auditEventId = seek; - timestamp = sortableIdUtils.extractTs(seek.toBuffer()) * 1000; + timestamp = idSortable.extractTs(seek.toBuffer()) * 1000; } else if (typeof seek === 'number') { timestamp = seek; auditEventId = generateAuditEventIdFromTimestamp(seek, randomSource); diff --git a/src/bootstrap/errors.ts b/src/bootstrap/errors.ts index ca0c385949..d7a64fb857 100644 --- a/src/bootstrap/errors.ts +++ b/src/bootstrap/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorBootstrap extends ErrorPolykey {} diff --git a/src/bootstrap/index.ts b/src/bootstrap/index.ts index 5b5826d2c2..6c875bee08 100644 --- a/src/bootstrap/index.ts +++ b/src/bootstrap/index.ts @@ -1,2 +1,2 @@ -export * as utils from './utils'; -export * as errors from './errors'; +export * as utils from './utils.js'; +export * as errors from './errors.js'; diff --git a/src/bootstrap/utils.ts b/src/bootstrap/utils.ts index d6cd2e66a7..a56b280b90 100644 --- a/src/bootstrap/utils.ts +++ b/src/bootstrap/utils.ts @@ -1,33 +1,32 @@ -import type { FileSystem } from '../types'; +import type { FileSystem } from '../types.js'; import type { RecoveryCode, - Key, PrivateKey, PasswordOpsLimit, PasswordMemLimit, -} from '../keys/types'; -import path from 'path'; +} from '../keys/types.js'; +import path from 'node:path'; import Logger from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import * as bootstrapErrors from './errors'; -import TaskManager from '../tasks/TaskManager'; -import IdentitiesManager from '../identities/IdentitiesManager'; -import SessionManager from '../sessions/SessionManager'; -import Status from '../status/Status'; -import Schema from '../schema/Schema'; -import Sigchain from '../sigchain/Sigchain'; -import ACL from '../acl/ACL'; -import GestaltGraph from '../gestalts/GestaltGraph'; -import KeyRing from '../keys/KeyRing'; -import CertManager from '../keys/CertManager'; -import * as keysUtils from '../keys/utils'; -import NodeGraph from '../nodes/NodeGraph'; -import NodeManager from '../nodes/NodeManager'; -import VaultManager from '../vaults/VaultManager'; -import NotificationsManager from '../notifications/NotificationsManager'; -import config from '../config'; -import * as utils from '../utils'; -import * as errors from '../errors'; +import * as bootstrapErrors from './errors.js'; +import TaskManager from '../tasks/TaskManager.js'; +import IdentitiesManager from '../identities/IdentitiesManager.js'; +import SessionManager from '../sessions/SessionManager.js'; +import Status from '../status/Status.js'; +import Schema from '../schema/Schema.js'; +import Sigchain from '../sigchain/Sigchain.js'; +import ACL from '../acl/ACL.js'; +import GestaltGraph from '../gestalts/GestaltGraph.js'; +import KeyRing from '../keys/KeyRing.js'; +import CertManager from '../keys/CertManager.js'; +import NodeGraph from '../nodes/NodeGraph.js'; +import NodeManager from '../nodes/NodeManager.js'; +import VaultManager from '../vaults/VaultManager.js'; +import NotificationsManager from '../notifications/NotificationsManager.js'; +import { polykeyWorkerManifest } from '../workers/index.js'; +import config from '../config.js'; +import * as utils from '../utils/index.js'; +import * as errors from '../errors.js'; /** * Bootstraps the Node Path` @@ -45,7 +44,7 @@ async function bootstrapState({ certDuration = config.defaultsUser.certDuration, fresh = false, // Optional dependencies - fs = require('fs'), + fs, logger = new Logger(bootstrapState.name), }: { password: string; @@ -68,6 +67,7 @@ async function bootstrapState({ if (nodePath == null) { throw new errors.ErrorUtilsNodePath(); } + fs = await utils.importFS(fs); await utils.mkdirExists(fs, nodePath); // Setup node path and sub paths const statusPath = path.join(nodePath, config.paths.statusBase); @@ -119,20 +119,7 @@ async function bootstrapState({ logger: logger.getChild(DB.name), crypto: { key: keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, fresh, }); diff --git a/src/claims/errors.ts b/src/claims/errors.ts index dffdc336b8..6d89348130 100644 --- a/src/claims/errors.ts +++ b/src/claims/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorClaims extends ErrorPolykey {} diff --git a/src/claims/index.ts b/src/claims/index.ts index dd8ea1afea..1174bf868c 100644 --- a/src/claims/index.ts +++ b/src/claims/index.ts @@ -3,7 +3,7 @@ * The claims are used by `sigchain` and `identities`. * @module */ -export * as payloads from './payloads'; -export * as utils from './utils'; -export * as types from './types'; -export * as errors from './errors'; +export * as payloads from './payloads/index.js'; +export * as utils from './utils.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; diff --git a/src/claims/payloads/claimLinkIdentity.ts b/src/claims/payloads/claimLinkIdentity.ts index 095f197249..3c99a01993 100644 --- a/src/claims/payloads/claimLinkIdentity.ts +++ b/src/claims/payloads/claimLinkIdentity.ts @@ -1,14 +1,14 @@ -import type { Claim, SignedClaim } from '../types'; +import type { Claim, SignedClaim } from '../types.js'; import type { NodeIdEncoded, ProviderIdentityClaimId, ProviderIdentityIdEncoded, -} from '../../ids/types'; -import * as ids from '../../ids'; -import * as claimsUtils from '../utils'; -import * as tokensUtils from '../../tokens/utils'; -import * as validationErrors from '../../validation/errors'; -import * as utils from '../../utils'; +} from '../../ids/types.js'; +import * as ids from '../../ids/index.js'; +import * as claimsUtils from '../utils.js'; +import * as tokensUtils from '../../tokens/utils.js'; +import * as validationErrors from '../../validation/errors.js'; +import * as utils from '../../utils/index.js'; /** * Linking node and digital identity together diff --git a/src/claims/payloads/claimLinkNode.ts b/src/claims/payloads/claimLinkNode.ts index 8d56de9d18..644d649171 100644 --- a/src/claims/payloads/claimLinkNode.ts +++ b/src/claims/payloads/claimLinkNode.ts @@ -1,10 +1,10 @@ -import type { Claim, SignedClaim } from '../types'; -import type { NodeIdEncoded } from '../../ids/types'; -import * as ids from '../../ids'; -import * as claimsUtils from '../utils'; -import * as tokensUtils from '../../tokens/utils'; -import * as validationErrors from '../../validation/errors'; -import * as utils from '../../utils'; +import type { Claim, SignedClaim } from '../types.js'; +import type { NodeIdEncoded } from '../../ids/types.js'; +import * as ids from '../../ids/index.js'; +import * as claimsUtils from '../utils.js'; +import * as tokensUtils from '../../tokens/utils.js'; +import * as validationErrors from '../../validation/errors.js'; +import * as utils from '../../utils/index.js'; /** * Linking 2 nodes together diff --git a/src/claims/payloads/claimNetworkAccess.ts b/src/claims/payloads/claimNetworkAccess.ts index 0be8a340e4..8b7eb34e4a 100644 --- a/src/claims/payloads/claimNetworkAccess.ts +++ b/src/claims/payloads/claimNetworkAccess.ts @@ -1,12 +1,12 @@ -import type { Claim, SignedClaim } from '../types'; -import type { NodeIdEncoded } from '../../ids/types'; -import type { SignedTokenEncoded } from '../../tokens/types'; -import * as tokensSchema from '../../tokens/schemas'; -import * as ids from '../../ids'; -import * as claimsUtils from '../utils'; -import * as tokensUtils from '../../tokens/utils'; -import * as validationErrors from '../../validation/errors'; -import * as utils from '../../utils'; +import type { Claim, SignedClaim } from '../types.js'; +import type { NodeIdEncoded } from '../../ids/types.js'; +import type { SignedTokenEncoded } from '../../tokens/types.js'; +import * as tokensSchema from '../../tokens/schemas/index.js'; +import * as ids from '../../ids/index.js'; +import * as claimsUtils from '../utils.js'; +import * as tokensUtils from '../../tokens/utils.js'; +import * as validationErrors from '../../validation/errors.js'; +import * as utils from '../../utils/index.js'; /** * Asserts that a node is apart of a network diff --git a/src/claims/payloads/claimNetworkAuthority.ts b/src/claims/payloads/claimNetworkAuthority.ts index 71a59fa6cf..82baaae4ff 100644 --- a/src/claims/payloads/claimNetworkAuthority.ts +++ b/src/claims/payloads/claimNetworkAuthority.ts @@ -1,10 +1,10 @@ -import type { Claim, SignedClaim } from '../types'; -import type { NodeIdEncoded } from '../../ids/types'; -import * as ids from '../../ids'; -import * as claimsUtils from '../utils'; -import * as tokensUtils from '../../tokens/utils'; -import * as validationErrors from '../../validation/errors'; -import * as utils from '../../utils'; +import type { Claim, SignedClaim } from '../types.js'; +import type { NodeIdEncoded } from '../../ids/types.js'; +import * as ids from '../../ids/index.js'; +import * as claimsUtils from '../utils.js'; +import * as tokensUtils from '../../tokens/utils.js'; +import * as validationErrors from '../../validation/errors.js'; +import * as utils from '../../utils/index.js'; /** * Asserts that a node is apart of a network diff --git a/src/claims/payloads/index.ts b/src/claims/payloads/index.ts index 52c955be6f..37edbe0e5b 100644 --- a/src/claims/payloads/index.ts +++ b/src/claims/payloads/index.ts @@ -1,3 +1,3 @@ -export * from './claimLinkIdentity'; -export * from './claimLinkNode'; -export * from './claimNetworkAccess'; +export * from './claimLinkIdentity.js'; +export * from './claimLinkNode.js'; +export * from './claimNetworkAccess.js'; diff --git a/src/claims/types.ts b/src/claims/types.ts index ba7a1b28e3..7ccf3c7dbf 100644 --- a/src/claims/types.ts +++ b/src/claims/types.ts @@ -1,4 +1,4 @@ -import type { Opaque } from '../types'; +import type { Opaque } from '../types.js'; import type { TokenPayload, TokenHeaderSignature, @@ -6,8 +6,8 @@ import type { SignedTokenJSON, SignedTokenEncoded, TokenPayloadEncoded, -} from '../tokens/types'; -import type { ClaimIdEncoded } from '../ids/types'; +} from '../tokens/types.js'; +import type { ClaimIdEncoded } from '../ids/types.js'; /** * Claim is structured data based on TokenPayload @@ -61,4 +61,4 @@ export type { SignedClaimDigestEncoded, }; -export type { ClaimId, ClaimIdString, ClaimIdEncoded } from '../ids/types'; +export type { ClaimId, ClaimIdString, ClaimIdEncoded } from '../ids/types.js'; diff --git a/src/claims/utils.ts b/src/claims/utils.ts index 86a1daa9c9..9c2c609e28 100644 --- a/src/claims/utils.ts +++ b/src/claims/utils.ts @@ -4,15 +4,15 @@ import type { SignedClaim, SignedClaimEncoded, SignedClaimDigestEncoded, -} from './types'; -import type { Digest, DigestFormats } from '../keys/types'; +} from './types.js'; +import type { Digest, DigestFormats } from '../keys/types.js'; import canonicalize from 'canonicalize'; -import * as ids from '../ids'; -import * as tokensUtils from '../tokens/utils'; -import * as keysUtils from '../keys/utils'; -import * as keysTypes from '../keys/types'; -import * as validationErrors from '../validation/errors'; -import * as utils from '../utils'; +import * as ids from '../ids/index.js'; +import * as tokensUtils from '../tokens/utils.js'; +import * as keysUtils from '../keys/utils/index.js'; +import * as keysTypes from '../keys/types.js'; +import * as validationErrors from '../validation/errors.js'; +import * as utils from '../utils/index.js'; function generateClaim(claim: Claim): ClaimEncoded { return tokensUtils.generateTokenPayload(claim); @@ -76,6 +76,7 @@ function hashSignedClaim( claim: SignedClaim, format: F, ): Digest { + // @ts-ignore: canonicalize exports is function improperly for ESM const claimJSON = canonicalize(claim)!; const claimData = Buffer.from(claimJSON, 'utf-8'); const claimDigest = keysUtils.hash(claimData, format); @@ -130,4 +131,8 @@ export { decodeSignedClaimDigest, }; -export { createClaimIdGenerator, encodeClaimId, decodeClaimId } from '../ids'; +export { + createClaimIdGenerator, + encodeClaimId, + decodeClaimId, +} from '../ids/index.js'; diff --git a/src/client/ClientService.ts b/src/client/ClientService.ts index a75b432514..2045e9d3d0 100644 --- a/src/client/ClientService.ts +++ b/src/client/ClientService.ts @@ -5,19 +5,19 @@ import type { MiddlewareFactory, ServerManifest, } from '@matrixai/rpc'; -import type { TLSConfig } from '../network/types'; +import type { TLSConfig } from '../network/types.js'; import Logger from '@matrixai/logger'; -import { StartStop, ready } from '@matrixai/async-init/dist/StartStop'; +import { startStop } from '@matrixai/async-init'; import { running, status } from '@matrixai/async-init'; import { WebSocketServer, events as wsEvents } from '@matrixai/ws'; import { RPCServer, middleware as rpcMiddleware } from '@matrixai/rpc'; -import * as events from './events'; -import * as errors from './errors'; -import * as networkUtils from '../network/utils'; -import config from '../config'; +import * as events from './events.js'; +import * as errors from './errors.js'; +import * as networkUtils from '../network/utils.js'; +import config from '../config.js'; -interface ClientService extends StartStop {} -@StartStop({ +interface ClientService extends startStop.StartStop {} +@startStop.StartStop({ eventStart: events.EventClientServiceStart, eventStarted: events.EventClientServiceStarted, eventStop: events.EventClientServiceStop, @@ -103,12 +103,12 @@ class ClientService { }); } - @ready(new errors.ErrorClientServiceNotRunning()) + @startStop.ready(new errors.ErrorClientServiceNotRunning()) public get host() { return this.webSocketServer.host; } - @ready(new errors.ErrorClientServiceNotRunning()) + @startStop.ready(new errors.ErrorClientServiceNotRunning()) public get port() { return this.webSocketServer.port; } @@ -148,7 +148,7 @@ class ClientService { this.logger.info(`Stopped ${this.constructor.name}`); } - @ready(new errors.ErrorClientServiceNotRunning()) + @startStop.ready(new errors.ErrorClientServiceNotRunning()) public setTlsConfig(tlsConfig: TLSConfig): void { this.webSocketServer.updateConfig({ key: tlsConfig.keyPrivatePem, diff --git a/src/client/authenticationMiddleware.ts b/src/client/authenticationMiddleware.ts index cbce3d485f..17da275f1d 100644 --- a/src/client/authenticationMiddleware.ts +++ b/src/client/authenticationMiddleware.ts @@ -3,19 +3,22 @@ import type { JSONRPCResponse, MiddlewareFactory, } from '@matrixai/rpc'; -import type { ClientRPCRequestParams, ClientRPCResponseResult } from './types'; -import type { Session } from '../sessions'; -import type SessionManager from '../sessions/SessionManager'; -import type KeyRing from '../keys/KeyRing'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from './types.js'; +import type { Session } from '../sessions/index.js'; +import type SessionManager from '../sessions/SessionManager.js'; +import type KeyRing from '../keys/KeyRing.js'; import type { JSONRPCResponseError, JSONRPCResponseFailed, } from '@matrixai/rpc'; import { TransformStream } from 'stream/web'; -import { authenticate, decodeAuth } from './utils'; -import { sysexits } from '../errors'; -import * as utils from '../utils'; -import * as networkUtils from '../network/utils'; +import { authenticate, decodeAuth } from './utils.js'; +import { sysexits } from '../errors.js'; +import * as utils from '../utils/index.js'; +import * as networkUtils from '../network/utils.js'; function authenticationMiddlewareServer( sessionManager: SessionManager, diff --git a/src/client/callers/agentLockAll.ts b/src/client/callers/agentLockAll.ts index dad0823c4f..a1a206af80 100644 --- a/src/client/callers/agentLockAll.ts +++ b/src/client/callers/agentLockAll.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type AgentLockAll from '../handlers/AgentLockAll'; +import type AgentLockAll from '../handlers/AgentLockAll.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/agentStatus.ts b/src/client/callers/agentStatus.ts index c3a1db287e..a6a7e0d220 100644 --- a/src/client/callers/agentStatus.ts +++ b/src/client/callers/agentStatus.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type AgentStatus from '../handlers/AgentStatus'; +import type AgentStatus from '../handlers/AgentStatus.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/agentStop.ts b/src/client/callers/agentStop.ts index 5ba9144d36..ef42a306c5 100644 --- a/src/client/callers/agentStop.ts +++ b/src/client/callers/agentStop.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type AgentStop from '../handlers/AgentStop'; +import type AgentStop from '../handlers/AgentStop.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/agentUnlock.ts b/src/client/callers/agentUnlock.ts index d47dbe5344..fae138b0d1 100644 --- a/src/client/callers/agentUnlock.ts +++ b/src/client/callers/agentUnlock.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type AgentUnlock from '../handlers/AgentUnlock'; +import type AgentUnlock from '../handlers/AgentUnlock.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/auditEventsGet.ts b/src/client/callers/auditEventsGet.ts index 4931fa2d08..43b9afa76d 100644 --- a/src/client/callers/auditEventsGet.ts +++ b/src/client/callers/auditEventsGet.ts @@ -1,14 +1,17 @@ import type { ReadableStream } from 'stream/web'; import type { HandlerTypes } from '@matrixai/rpc'; import type { ContextTimedInput } from '@matrixai/contexts'; -import type { AuditEventIdEncoded } from '../../ids'; +import type { AuditEventIdEncoded } from '../../ids/index.js'; import type { AuditEventToAuditEventSerialized, TopicSubPath, TopicSubPathToAuditEvent, -} from '../../audit/types'; -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; -import type AuditEventsGet from '../handlers/AuditEventsGet'; +} from '../../audit/types.js'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; +import type AuditEventsGet from '../handlers/AuditEventsGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/auditMetricGet.ts b/src/client/callers/auditMetricGet.ts index 4515edffe8..c9e99c1db5 100644 --- a/src/client/callers/auditMetricGet.ts +++ b/src/client/callers/auditMetricGet.ts @@ -1,9 +1,12 @@ import type { HandlerTypes } from '@matrixai/rpc'; import type { ContextTimedInput } from '@matrixai/contexts'; -import type { AuditEventIdEncoded } from '../../ids'; -import type { MetricPath, MetricPathToAuditMetric } from '../../audit/types'; -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; -import type AuditMetricGet from '../handlers/AuditMetricGet'; +import type { AuditEventIdEncoded } from '../../ids/index.js'; +import type { MetricPath, MetricPathToAuditMetric } from '../../audit/types.js'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; +import type AuditMetricGet from '../handlers/AuditMetricGet.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsActionsGetByIdentity.ts b/src/client/callers/gestaltsActionsGetByIdentity.ts index 0d918986d5..df07c6b2c8 100644 --- a/src/client/callers/gestaltsActionsGetByIdentity.ts +++ b/src/client/callers/gestaltsActionsGetByIdentity.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsActionsGetByIdentity from '../handlers/GestaltsActionsGetByIdentity'; +import type GestaltsActionsGetByIdentity from '../handlers/GestaltsActionsGetByIdentity.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsActionsGetByNode.ts b/src/client/callers/gestaltsActionsGetByNode.ts index 3a17eedebe..0f65c6b812 100644 --- a/src/client/callers/gestaltsActionsGetByNode.ts +++ b/src/client/callers/gestaltsActionsGetByNode.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsActionsGetByNode from '../handlers/GestaltsActionsGetByNode'; +import type GestaltsActionsGetByNode from '../handlers/GestaltsActionsGetByNode.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsActionsSetByIdentity.ts b/src/client/callers/gestaltsActionsSetByIdentity.ts index f4eb977dc7..2616f598b9 100644 --- a/src/client/callers/gestaltsActionsSetByIdentity.ts +++ b/src/client/callers/gestaltsActionsSetByIdentity.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsActionsSetByIdentity from '../handlers/GestaltsActionsSetByIdentity'; +import type GestaltsActionsSetByIdentity from '../handlers/GestaltsActionsSetByIdentity.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsActionsSetByNode.ts b/src/client/callers/gestaltsActionsSetByNode.ts index adbaf625e9..a3b9983857 100644 --- a/src/client/callers/gestaltsActionsSetByNode.ts +++ b/src/client/callers/gestaltsActionsSetByNode.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsActionsSetByNode from '../handlers/GestaltsActionsSetByNode'; +import type GestaltsActionsSetByNode from '../handlers/GestaltsActionsSetByNode.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsActionsUnsetByIdentity.ts b/src/client/callers/gestaltsActionsUnsetByIdentity.ts index 2f2c97e428..0ff96a8559 100644 --- a/src/client/callers/gestaltsActionsUnsetByIdentity.ts +++ b/src/client/callers/gestaltsActionsUnsetByIdentity.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsActionsUnsetByIdentity from '../handlers/GestaltsActionsUnsetByIdentity'; +import type GestaltsActionsUnsetByIdentity from '../handlers/GestaltsActionsUnsetByIdentity.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsActionsUnsetByNode.ts b/src/client/callers/gestaltsActionsUnsetByNode.ts index 15b22b29eb..795d45afc1 100644 --- a/src/client/callers/gestaltsActionsUnsetByNode.ts +++ b/src/client/callers/gestaltsActionsUnsetByNode.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsActionsUnsetByNode from '../handlers/GestaltsActionsUnsetByNode'; +import type GestaltsActionsUnsetByNode from '../handlers/GestaltsActionsUnsetByNode.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsDiscoveryByIdentity.ts b/src/client/callers/gestaltsDiscoveryByIdentity.ts index 46913d0600..f9e3515ad6 100644 --- a/src/client/callers/gestaltsDiscoveryByIdentity.ts +++ b/src/client/callers/gestaltsDiscoveryByIdentity.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsDiscoveryByIdentity from '../handlers/GestaltsDiscoveryByIdentity'; +import type GestaltsDiscoveryByIdentity from '../handlers/GestaltsDiscoveryByIdentity.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsDiscoveryByNode.ts b/src/client/callers/gestaltsDiscoveryByNode.ts index dad4d45063..8115505b93 100644 --- a/src/client/callers/gestaltsDiscoveryByNode.ts +++ b/src/client/callers/gestaltsDiscoveryByNode.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsDiscoveryByNode from '../handlers/GestaltsDiscoveryByNode'; +import type GestaltsDiscoveryByNode from '../handlers/GestaltsDiscoveryByNode.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsDiscoveryQueue.ts b/src/client/callers/gestaltsDiscoveryQueue.ts index 7301dae297..0cc68c688b 100644 --- a/src/client/callers/gestaltsDiscoveryQueue.ts +++ b/src/client/callers/gestaltsDiscoveryQueue.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsDiscoveryQueue from '../handlers/GestaltsDiscoveryQueue'; +import type GestaltsDiscoveryQueue from '../handlers/GestaltsDiscoveryQueue.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsGestaltGetByIdentity.ts b/src/client/callers/gestaltsGestaltGetByIdentity.ts index 9366670b4d..bf7adc7023 100644 --- a/src/client/callers/gestaltsGestaltGetByIdentity.ts +++ b/src/client/callers/gestaltsGestaltGetByIdentity.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsGestaltGetByIdentity from '../handlers/GestaltsGestaltGetByIdentity'; +import type GestaltsGestaltGetByIdentity from '../handlers/GestaltsGestaltGetByIdentity.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsGestaltGetByNode.ts b/src/client/callers/gestaltsGestaltGetByNode.ts index 4afc101cfa..2fdb75800f 100644 --- a/src/client/callers/gestaltsGestaltGetByNode.ts +++ b/src/client/callers/gestaltsGestaltGetByNode.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsGestaltGetByNode from '../handlers/GestaltsGestaltGetByNode'; +import type GestaltsGestaltGetByNode from '../handlers/GestaltsGestaltGetByNode.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsGestaltList.ts b/src/client/callers/gestaltsGestaltList.ts index 8fe33551c4..754979d48c 100644 --- a/src/client/callers/gestaltsGestaltList.ts +++ b/src/client/callers/gestaltsGestaltList.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsGestaltList from '../handlers/GestaltsGestaltList'; +import type GestaltsGestaltList from '../handlers/GestaltsGestaltList.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsGestaltTrustByIdentity.ts b/src/client/callers/gestaltsGestaltTrustByIdentity.ts index a8eb59a443..30e8880fb7 100644 --- a/src/client/callers/gestaltsGestaltTrustByIdentity.ts +++ b/src/client/callers/gestaltsGestaltTrustByIdentity.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsGestaltTrustByIdentity from '../handlers/GestaltsGestaltTrustByIdentity'; +import type GestaltsGestaltTrustByIdentity from '../handlers/GestaltsGestaltTrustByIdentity.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/gestaltsGestaltTrustByNode.ts b/src/client/callers/gestaltsGestaltTrustByNode.ts index dcde4eba80..2045fb2889 100644 --- a/src/client/callers/gestaltsGestaltTrustByNode.ts +++ b/src/client/callers/gestaltsGestaltTrustByNode.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type GestaltsGestaltTrustByNode from '../handlers/GestaltsGestaltTrustByNode'; +import type GestaltsGestaltTrustByNode from '../handlers/GestaltsGestaltTrustByNode.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesAuthenticate.ts b/src/client/callers/identitiesAuthenticate.ts index 82b4201ba4..502cd4003e 100644 --- a/src/client/callers/identitiesAuthenticate.ts +++ b/src/client/callers/identitiesAuthenticate.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesAuthenticate from '../handlers/IdentitiesAuthenticate'; +import type IdentitiesAuthenticate from '../handlers/IdentitiesAuthenticate.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesAuthenticatedGet.ts b/src/client/callers/identitiesAuthenticatedGet.ts index 638a057c61..c8caca5fbb 100644 --- a/src/client/callers/identitiesAuthenticatedGet.ts +++ b/src/client/callers/identitiesAuthenticatedGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesAuthenticatedGet from '../handlers/IdentitiesAuthenticatedGet'; +import type IdentitiesAuthenticatedGet from '../handlers/IdentitiesAuthenticatedGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesClaim.ts b/src/client/callers/identitiesClaim.ts index 3517f1a889..2af5a302f4 100644 --- a/src/client/callers/identitiesClaim.ts +++ b/src/client/callers/identitiesClaim.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesClaim from '../handlers/IdentitiesClaim'; +import type IdentitiesClaim from '../handlers/IdentitiesClaim.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesInfoConnectedGet.ts b/src/client/callers/identitiesInfoConnectedGet.ts index c9227b7bab..653e215481 100644 --- a/src/client/callers/identitiesInfoConnectedGet.ts +++ b/src/client/callers/identitiesInfoConnectedGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesInfoConnectedGet from '../handlers/IdentitiesInfoConnectedGet'; +import type IdentitiesInfoConnectedGet from '../handlers/IdentitiesInfoConnectedGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesInfoGet.ts b/src/client/callers/identitiesInfoGet.ts index 35d984b642..38769f88de 100644 --- a/src/client/callers/identitiesInfoGet.ts +++ b/src/client/callers/identitiesInfoGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesInfoGet from '../handlers/IdentitiesInfoGet'; +import type IdentitiesInfoGet from '../handlers/IdentitiesInfoGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesInvite.ts b/src/client/callers/identitiesInvite.ts index 8ccf179d43..6b50595ffd 100644 --- a/src/client/callers/identitiesInvite.ts +++ b/src/client/callers/identitiesInvite.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesInvite from '../handlers/IdentitiesInvite'; +import type IdentitiesInvite from '../handlers/IdentitiesInvite.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesProvidersList.ts b/src/client/callers/identitiesProvidersList.ts index 5db63eb8dc..c29b67a30e 100644 --- a/src/client/callers/identitiesProvidersList.ts +++ b/src/client/callers/identitiesProvidersList.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesProvidersList from '../handlers/IdentitiesProvidersList'; +import type IdentitiesProvidersList from '../handlers/IdentitiesProvidersList.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesTokenDelete.ts b/src/client/callers/identitiesTokenDelete.ts index 878dcdd36f..75790d40be 100644 --- a/src/client/callers/identitiesTokenDelete.ts +++ b/src/client/callers/identitiesTokenDelete.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesTokenDelete from '../handlers/IdentitiesTokenDelete'; +import type IdentitiesTokenDelete from '../handlers/IdentitiesTokenDelete.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesTokenGet.ts b/src/client/callers/identitiesTokenGet.ts index 2bf564eec0..2752b88a34 100644 --- a/src/client/callers/identitiesTokenGet.ts +++ b/src/client/callers/identitiesTokenGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesTokenGet from '../handlers/IdentitiesTokenGet'; +import type IdentitiesTokenGet from '../handlers/IdentitiesTokenGet.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/identitiesTokenPut.ts b/src/client/callers/identitiesTokenPut.ts index 94e29029c3..6d53de2899 100644 --- a/src/client/callers/identitiesTokenPut.ts +++ b/src/client/callers/identitiesTokenPut.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type IdentitiesTokenPut from '../handlers/IdentitiesTokenPut'; +import type IdentitiesTokenPut from '../handlers/IdentitiesTokenPut.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/index.ts b/src/client/callers/index.ts index 21b77d9af7..560b3a4eb4 100644 --- a/src/client/callers/index.ts +++ b/src/client/callers/index.ts @@ -1,79 +1,79 @@ -import agentLockAll from './agentLockAll'; -import agentStatus from './agentStatus'; -import agentStop from './agentStop'; -import agentUnlock from './agentUnlock'; -import auditEventsGet from './auditEventsGet'; -import auditMetricGet from './auditMetricGet'; -import gestaltsActionsGetByIdentity from './gestaltsActionsGetByIdentity'; -import gestaltsActionsGetByNode from './gestaltsActionsGetByNode'; -import gestaltsActionsSetByIdentity from './gestaltsActionsSetByIdentity'; -import gestaltsActionsSetByNode from './gestaltsActionsSetByNode'; -import gestaltsActionsUnsetByIdentity from './gestaltsActionsUnsetByIdentity'; -import gestaltsActionsUnsetByNode from './gestaltsActionsUnsetByNode'; -import gestaltsDiscoveryByIdentity from './gestaltsDiscoveryByIdentity'; -import gestaltsDiscoveryByNode from './gestaltsDiscoveryByNode'; -import gestaltsGestaltGetByIdentity from './gestaltsGestaltGetByIdentity'; -import gestaltsGestaltGetByNode from './gestaltsGestaltGetByNode'; -import gestaltsDiscoveryQueue from './gestaltsDiscoveryQueue'; -import gestaltsGestaltList from './gestaltsGestaltList'; -import gestaltsGestaltTrustByIdentity from './gestaltsGestaltTrustByIdentity'; -import gestaltsGestaltTrustByNode from './gestaltsGestaltTrustByNode'; -import identitiesAuthenticate from './identitiesAuthenticate'; -import identitiesAuthenticatedGet from './identitiesAuthenticatedGet'; -import identitiesClaim from './identitiesClaim'; -import identitiesInfoConnectedGet from './identitiesInfoConnectedGet'; -import identitiesInfoGet from './identitiesInfoGet'; -import identitiesInvite from './identitiesInvite'; -import identitiesProvidersList from './identitiesProvidersList'; -import identitiesTokenDelete from './identitiesTokenDelete'; -import identitiesTokenGet from './identitiesTokenGet'; -import identitiesTokenPut from './identitiesTokenPut'; -import keysCertsChainGet from './keysCertsChainGet'; -import keysCertsGet from './keysCertsGet'; -import keysDecrypt from './keysDecrypt'; -import keysEncrypt from './keysEncrypt'; -import keysKeyPair from './keysKeyPair'; -import keysKeyPairRenew from './keysKeyPairRenew'; -import keysKeyPairReset from './keysKeyPairReset'; -import keysPasswordChange from './keysPasswordChange'; -import keysPublicKey from './keysPublicKey'; -import keysSign from './keysSign'; -import keysVerify from './keysVerify'; -import nodesAdd from './nodesAdd'; -import nodesClaim from './nodesClaim'; -import nodesFind from './nodesFind'; -import nodesGetAll from './nodesGetAll'; -import nodesListConnections from './nodesListConnections'; -import nodesPing from './nodesPing'; -import notificationsInboxClear from './notificationsInboxClear'; -import notificationsInboxRead from './notificationsInboxRead'; -import notificationsInboxRemove from './notificationsInboxRemove'; -import notificationsOutboxClear from './notificationsOutboxClear'; -import notificationsOutboxRead from './notificationsOutboxRead'; -import notificationsOutboxRemove from './notificationsOutboxRemove'; -import notificationsSend from './notificationsSend'; -import vaultsClone from './vaultsClone'; -import vaultsCreate from './vaultsCreate'; -import vaultsDelete from './vaultsDelete'; -import vaultsList from './vaultsList'; -import vaultsLog from './vaultsLog'; -import vaultsPermissionGet from './vaultsPermissionGet'; -import vaultsPermissionSet from './vaultsPermissionSet'; -import vaultsPermissionUnset from './vaultsPermissionUnset'; -import vaultsPull from './vaultsPull'; -import vaultsRename from './vaultsRename'; -import vaultsScan from './vaultsScan'; -import vaultsSecretsCat from './vaultsSecretsCat'; -import vaultsSecretsEnv from './vaultsSecretsEnv'; -import vaultsSecretsList from './vaultsSecretsList'; -import vaultsSecretsMkdir from './vaultsSecretsMkdir'; -import vaultsSecretsNewDir from './vaultsSecretsNewDir'; -import vaultsSecretsRename from './vaultsSecretsRename'; -import vaultsSecretsRemove from './vaultsSecretsRemove'; -import vaultsSecretsStat from './vaultsSecretsStat'; -import vaultsSecretsTouch from './vaultsSecretsTouch'; -import vaultsSecretsWriteFile from './vaultsSecretsWriteFile'; -import vaultsVersion from './vaultsVersion'; +import agentLockAll from './agentLockAll.js'; +import agentStatus from './agentStatus.js'; +import agentStop from './agentStop.js'; +import agentUnlock from './agentUnlock.js'; +import auditEventsGet from './auditEventsGet.js'; +import auditMetricGet from './auditMetricGet.js'; +import gestaltsActionsGetByIdentity from './gestaltsActionsGetByIdentity.js'; +import gestaltsActionsGetByNode from './gestaltsActionsGetByNode.js'; +import gestaltsActionsSetByIdentity from './gestaltsActionsSetByIdentity.js'; +import gestaltsActionsSetByNode from './gestaltsActionsSetByNode.js'; +import gestaltsActionsUnsetByIdentity from './gestaltsActionsUnsetByIdentity.js'; +import gestaltsActionsUnsetByNode from './gestaltsActionsUnsetByNode.js'; +import gestaltsDiscoveryByIdentity from './gestaltsDiscoveryByIdentity.js'; +import gestaltsDiscoveryByNode from './gestaltsDiscoveryByNode.js'; +import gestaltsGestaltGetByIdentity from './gestaltsGestaltGetByIdentity.js'; +import gestaltsGestaltGetByNode from './gestaltsGestaltGetByNode.js'; +import gestaltsDiscoveryQueue from './gestaltsDiscoveryQueue.js'; +import gestaltsGestaltList from './gestaltsGestaltList.js'; +import gestaltsGestaltTrustByIdentity from './gestaltsGestaltTrustByIdentity.js'; +import gestaltsGestaltTrustByNode from './gestaltsGestaltTrustByNode.js'; +import identitiesAuthenticate from './identitiesAuthenticate.js'; +import identitiesAuthenticatedGet from './identitiesAuthenticatedGet.js'; +import identitiesClaim from './identitiesClaim.js'; +import identitiesInfoConnectedGet from './identitiesInfoConnectedGet.js'; +import identitiesInfoGet from './identitiesInfoGet.js'; +import identitiesInvite from './identitiesInvite.js'; +import identitiesProvidersList from './identitiesProvidersList.js'; +import identitiesTokenDelete from './identitiesTokenDelete.js'; +import identitiesTokenGet from './identitiesTokenGet.js'; +import identitiesTokenPut from './identitiesTokenPut.js'; +import keysCertsChainGet from './keysCertsChainGet.js'; +import keysCertsGet from './keysCertsGet.js'; +import keysDecrypt from './keysDecrypt.js'; +import keysEncrypt from './keysEncrypt.js'; +import keysKeyPair from './keysKeyPair.js'; +import keysKeyPairRenew from './keysKeyPairRenew.js'; +import keysKeyPairReset from './keysKeyPairReset.js'; +import keysPasswordChange from './keysPasswordChange.js'; +import keysPublicKey from './keysPublicKey.js'; +import keysSign from './keysSign.js'; +import keysVerify from './keysVerify.js'; +import nodesAdd from './nodesAdd.js'; +import nodesClaim from './nodesClaim.js'; +import nodesFind from './nodesFind.js'; +import nodesGetAll from './nodesGetAll.js'; +import nodesListConnections from './nodesListConnections.js'; +import nodesPing from './nodesPing.js'; +import notificationsInboxClear from './notificationsInboxClear.js'; +import notificationsInboxRead from './notificationsInboxRead.js'; +import notificationsInboxRemove from './notificationsInboxRemove.js'; +import notificationsOutboxClear from './notificationsOutboxClear.js'; +import notificationsOutboxRead from './notificationsOutboxRead.js'; +import notificationsOutboxRemove from './notificationsOutboxRemove.js'; +import notificationsSend from './notificationsSend.js'; +import vaultsClone from './vaultsClone.js'; +import vaultsCreate from './vaultsCreate.js'; +import vaultsDelete from './vaultsDelete.js'; +import vaultsList from './vaultsList.js'; +import vaultsLog from './vaultsLog.js'; +import vaultsPermissionGet from './vaultsPermissionGet.js'; +import vaultsPermissionSet from './vaultsPermissionSet.js'; +import vaultsPermissionUnset from './vaultsPermissionUnset.js'; +import vaultsPull from './vaultsPull.js'; +import vaultsRename from './vaultsRename.js'; +import vaultsScan from './vaultsScan.js'; +import vaultsSecretsCat from './vaultsSecretsCat.js'; +import vaultsSecretsEnv from './vaultsSecretsEnv.js'; +import vaultsSecretsList from './vaultsSecretsList.js'; +import vaultsSecretsMkdir from './vaultsSecretsMkdir.js'; +import vaultsSecretsNewDir from './vaultsSecretsNewDir.js'; +import vaultsSecretsRename from './vaultsSecretsRename.js'; +import vaultsSecretsRemove from './vaultsSecretsRemove.js'; +import vaultsSecretsStat from './vaultsSecretsStat.js'; +import vaultsSecretsTouch from './vaultsSecretsTouch.js'; +import vaultsSecretsWriteFile from './vaultsSecretsWriteFile.js'; +import vaultsVersion from './vaultsVersion.js'; /** * Client manifest diff --git a/src/client/callers/keysCertsChainGet.ts b/src/client/callers/keysCertsChainGet.ts index 966f1a3964..702da26cd7 100644 --- a/src/client/callers/keysCertsChainGet.ts +++ b/src/client/callers/keysCertsChainGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysCertsChainGet from '../handlers/KeysCertsChainGet'; +import type KeysCertsChainGet from '../handlers/KeysCertsChainGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysCertsGet.ts b/src/client/callers/keysCertsGet.ts index 8a1914a1d9..4293652a0e 100644 --- a/src/client/callers/keysCertsGet.ts +++ b/src/client/callers/keysCertsGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysCertsGet from '../handlers/KeysCertsGet'; +import type KeysCertsGet from '../handlers/KeysCertsGet.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysDecrypt.ts b/src/client/callers/keysDecrypt.ts index 3f5bb4875a..b954267ea9 100644 --- a/src/client/callers/keysDecrypt.ts +++ b/src/client/callers/keysDecrypt.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysDecrypt from '../handlers/KeysDecrypt'; +import type KeysDecrypt from '../handlers/KeysDecrypt.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysEncrypt.ts b/src/client/callers/keysEncrypt.ts index ae2fa60980..f576ebb9a1 100644 --- a/src/client/callers/keysEncrypt.ts +++ b/src/client/callers/keysEncrypt.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysEncrypt from '../handlers/KeysEncrypt'; +import type KeysEncrypt from '../handlers/KeysEncrypt.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysKeyPair.ts b/src/client/callers/keysKeyPair.ts index 5c1493123b..27d3db0075 100644 --- a/src/client/callers/keysKeyPair.ts +++ b/src/client/callers/keysKeyPair.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysKeyPair from '../handlers/KeysKeyPair'; +import type KeysKeyPair from '../handlers/KeysKeyPair.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysKeyPairRenew.ts b/src/client/callers/keysKeyPairRenew.ts index 00e6034a03..c16504f1b6 100644 --- a/src/client/callers/keysKeyPairRenew.ts +++ b/src/client/callers/keysKeyPairRenew.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysKeyPairRenew from '../handlers/KeysKeyPairRenew'; +import type KeysKeyPairRenew from '../handlers/KeysKeyPairRenew.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysKeyPairReset.ts b/src/client/callers/keysKeyPairReset.ts index 97221d5198..fd02a5e0e6 100644 --- a/src/client/callers/keysKeyPairReset.ts +++ b/src/client/callers/keysKeyPairReset.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysKeyPairReset from '../handlers/KeysKeyPairReset'; +import type KeysKeyPairReset from '../handlers/KeysKeyPairReset.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysPasswordChange.ts b/src/client/callers/keysPasswordChange.ts index 40ac575b96..ad16b7f904 100644 --- a/src/client/callers/keysPasswordChange.ts +++ b/src/client/callers/keysPasswordChange.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysPasswordChange from '../handlers/KeysPasswordChange'; +import type KeysPasswordChange from '../handlers/KeysPasswordChange.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysPublicKey.ts b/src/client/callers/keysPublicKey.ts index 99da93d722..968ab14834 100644 --- a/src/client/callers/keysPublicKey.ts +++ b/src/client/callers/keysPublicKey.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysPublicKey from '../handlers/KeysPublicKey'; +import type KeysPublicKey from '../handlers/KeysPublicKey.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysSign.ts b/src/client/callers/keysSign.ts index 086dad6fce..a6bb3bf508 100644 --- a/src/client/callers/keysSign.ts +++ b/src/client/callers/keysSign.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysSign from '../handlers/KeysSign'; +import type KeysSign from '../handlers/KeysSign.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/keysVerify.ts b/src/client/callers/keysVerify.ts index 21b4747442..c978eac006 100644 --- a/src/client/callers/keysVerify.ts +++ b/src/client/callers/keysVerify.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type KeysVerify from '../handlers/KeysVerify'; +import type KeysVerify from '../handlers/KeysVerify.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/nodesAdd.ts b/src/client/callers/nodesAdd.ts index 663c6049a5..926a00c289 100644 --- a/src/client/callers/nodesAdd.ts +++ b/src/client/callers/nodesAdd.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesAdd from '../handlers/NodesAdd'; +import type NodesAdd from '../handlers/NodesAdd.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/nodesClaim.ts b/src/client/callers/nodesClaim.ts index 40bef13632..3073f19b10 100644 --- a/src/client/callers/nodesClaim.ts +++ b/src/client/callers/nodesClaim.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesClaim from '../handlers/NodesClaim'; +import type NodesClaim from '../handlers/NodesClaim.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/nodesFind.ts b/src/client/callers/nodesFind.ts index 98c04a4ecf..882ef1545e 100644 --- a/src/client/callers/nodesFind.ts +++ b/src/client/callers/nodesFind.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesFind from '../handlers/NodesFind'; +import type NodesFind from '../handlers/NodesFind.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/nodesGetAll.ts b/src/client/callers/nodesGetAll.ts index 33fb681778..a8ac6d7dac 100644 --- a/src/client/callers/nodesGetAll.ts +++ b/src/client/callers/nodesGetAll.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesGetAll from '../handlers/NodesGetAll'; +import type NodesGetAll from '../handlers/NodesGetAll.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/nodesListConnections.ts b/src/client/callers/nodesListConnections.ts index 75426d5adb..0769fc490e 100644 --- a/src/client/callers/nodesListConnections.ts +++ b/src/client/callers/nodesListConnections.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesListConnections from '../handlers/NodesListConnections'; +import type NodesListConnections from '../handlers/NodesListConnections.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/nodesPing.ts b/src/client/callers/nodesPing.ts index 766cdf3959..a7d315abf3 100644 --- a/src/client/callers/nodesPing.ts +++ b/src/client/callers/nodesPing.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesPing from '../handlers/NodesPing'; +import type NodesPing from '../handlers/NodesPing.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/notificationsInboxClear.ts b/src/client/callers/notificationsInboxClear.ts index e6bb40bbed..5f7f46a7d7 100644 --- a/src/client/callers/notificationsInboxClear.ts +++ b/src/client/callers/notificationsInboxClear.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NotificationsInboxClear from '../handlers/NotificationsInboxClear'; +import type NotificationsInboxClear from '../handlers/NotificationsInboxClear.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/notificationsInboxRead.ts b/src/client/callers/notificationsInboxRead.ts index d4e575389b..acd4ff1a07 100644 --- a/src/client/callers/notificationsInboxRead.ts +++ b/src/client/callers/notificationsInboxRead.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NotificationsInboxRead from '../handlers/NotificationsInboxRead'; +import type NotificationsInboxRead from '../handlers/NotificationsInboxRead.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/notificationsInboxRemove.ts b/src/client/callers/notificationsInboxRemove.ts index fd5f51b685..c99bde12b6 100644 --- a/src/client/callers/notificationsInboxRemove.ts +++ b/src/client/callers/notificationsInboxRemove.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NotificationsInboxRemove from '../handlers/NotificationsInboxRemove'; +import type NotificationsInboxRemove from '../handlers/NotificationsInboxRemove.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/notificationsOutboxClear.ts b/src/client/callers/notificationsOutboxClear.ts index aef138f2a9..df93075590 100644 --- a/src/client/callers/notificationsOutboxClear.ts +++ b/src/client/callers/notificationsOutboxClear.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NotificationsOutboxClear from '../handlers/NotificationsOutboxClear'; +import type NotificationsOutboxClear from '../handlers/NotificationsOutboxClear.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/notificationsOutboxRead.ts b/src/client/callers/notificationsOutboxRead.ts index 23f55b7a1a..56a54e08a2 100644 --- a/src/client/callers/notificationsOutboxRead.ts +++ b/src/client/callers/notificationsOutboxRead.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NotificationsOutboxRead from '../handlers/NotificationsOutboxRead'; +import type NotificationsOutboxRead from '../handlers/NotificationsOutboxRead.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/notificationsOutboxRemove.ts b/src/client/callers/notificationsOutboxRemove.ts index 43c770bb85..95d8ba08b2 100644 --- a/src/client/callers/notificationsOutboxRemove.ts +++ b/src/client/callers/notificationsOutboxRemove.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NotificationsOutboxRemove from '../handlers/NotificationsOutboxRemove'; +import type NotificationsOutboxRemove from '../handlers/NotificationsOutboxRemove.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/notificationsSend.ts b/src/client/callers/notificationsSend.ts index d4f6dd182b..4457189f49 100644 --- a/src/client/callers/notificationsSend.ts +++ b/src/client/callers/notificationsSend.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NotificationsSend from '../handlers/NotificationsSend'; +import type NotificationsSend from '../handlers/NotificationsSend.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsClone.ts b/src/client/callers/vaultsClone.ts index ddec40fcbd..2a77e6e931 100644 --- a/src/client/callers/vaultsClone.ts +++ b/src/client/callers/vaultsClone.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsClone from '../handlers/VaultsClone'; +import type VaultsClone from '../handlers/VaultsClone.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsCreate.ts b/src/client/callers/vaultsCreate.ts index e4023a6b7b..08a80f1ef6 100644 --- a/src/client/callers/vaultsCreate.ts +++ b/src/client/callers/vaultsCreate.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsCreate from '../handlers/VaultsCreate'; +import type VaultsCreate from '../handlers/VaultsCreate.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsDelete.ts b/src/client/callers/vaultsDelete.ts index 83596ea1c9..0a2a7d9a5b 100644 --- a/src/client/callers/vaultsDelete.ts +++ b/src/client/callers/vaultsDelete.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsDelete from '../handlers/VaultsDelete'; +import type VaultsDelete from '../handlers/VaultsDelete.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsList.ts b/src/client/callers/vaultsList.ts index afaed25817..d467b37f0c 100644 --- a/src/client/callers/vaultsList.ts +++ b/src/client/callers/vaultsList.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsList from '../handlers/VaultsList'; +import type VaultsList from '../handlers/VaultsList.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsLog.ts b/src/client/callers/vaultsLog.ts index 8bd6d8c316..e0a618a304 100644 --- a/src/client/callers/vaultsLog.ts +++ b/src/client/callers/vaultsLog.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsLog from '../handlers/VaultsLog'; +import type VaultsLog from '../handlers/VaultsLog.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsPermissionGet.ts b/src/client/callers/vaultsPermissionGet.ts index 43e373a039..60272f4e6b 100644 --- a/src/client/callers/vaultsPermissionGet.ts +++ b/src/client/callers/vaultsPermissionGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsPermissionGet from '../handlers/VaultsPermissionGet'; +import type VaultsPermissionGet from '../handlers/VaultsPermissionGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsPermissionSet.ts b/src/client/callers/vaultsPermissionSet.ts index 3966263c6d..5c65bb04fe 100644 --- a/src/client/callers/vaultsPermissionSet.ts +++ b/src/client/callers/vaultsPermissionSet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsPermissionSet from '../handlers/VaultsPermissionSet'; +import type VaultsPermissionSet from '../handlers/VaultsPermissionSet.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsPermissionUnset.ts b/src/client/callers/vaultsPermissionUnset.ts index 0685ec021e..9e8fa721f4 100644 --- a/src/client/callers/vaultsPermissionUnset.ts +++ b/src/client/callers/vaultsPermissionUnset.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsPermissionUnset from '../handlers/VaultsPermissionUnset'; +import type VaultsPermissionUnset from '../handlers/VaultsPermissionUnset.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsPull.ts b/src/client/callers/vaultsPull.ts index db4f14d04f..91befa5681 100644 --- a/src/client/callers/vaultsPull.ts +++ b/src/client/callers/vaultsPull.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsPull from '../handlers/VaultsPull'; +import type VaultsPull from '../handlers/VaultsPull.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsRename.ts b/src/client/callers/vaultsRename.ts index ace8e7f759..f3da696d26 100644 --- a/src/client/callers/vaultsRename.ts +++ b/src/client/callers/vaultsRename.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsRename from '../handlers/VaultsRename'; +import type VaultsRename from '../handlers/VaultsRename.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsScan.ts b/src/client/callers/vaultsScan.ts index b24e94673a..811ef47959 100644 --- a/src/client/callers/vaultsScan.ts +++ b/src/client/callers/vaultsScan.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsScan from '../handlers/VaultsScan'; +import type VaultsScan from '../handlers/VaultsScan.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsCat.ts b/src/client/callers/vaultsSecretsCat.ts index 1671a79667..cef9d6ae14 100644 --- a/src/client/callers/vaultsSecretsCat.ts +++ b/src/client/callers/vaultsSecretsCat.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsCat from '../handlers/VaultsSecretsCat'; +import type VaultsSecretsCat from '../handlers/VaultsSecretsCat.js'; import { DuplexCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsEnv.ts b/src/client/callers/vaultsSecretsEnv.ts index ba6e07d1ba..358f760ec9 100644 --- a/src/client/callers/vaultsSecretsEnv.ts +++ b/src/client/callers/vaultsSecretsEnv.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsEnv from '../handlers/VaultsSecretsEnv'; +import type VaultsSecretsEnv from '../handlers/VaultsSecretsEnv.js'; import { DuplexCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsList.ts b/src/client/callers/vaultsSecretsList.ts index c8bba49ae6..9829256dbe 100644 --- a/src/client/callers/vaultsSecretsList.ts +++ b/src/client/callers/vaultsSecretsList.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsList from '../handlers/VaultsSecretsList'; +import type VaultsSecretsList from '../handlers/VaultsSecretsList.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsMkdir.ts b/src/client/callers/vaultsSecretsMkdir.ts index 71a19c7f20..b7e7e54531 100644 --- a/src/client/callers/vaultsSecretsMkdir.ts +++ b/src/client/callers/vaultsSecretsMkdir.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsMkdir from '../handlers/VaultsSecretsMkdir'; +import type VaultsSecretsMkdir from '../handlers/VaultsSecretsMkdir.js'; import { DuplexCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsNewDir.ts b/src/client/callers/vaultsSecretsNewDir.ts index 2c840228e6..b1faf75c36 100644 --- a/src/client/callers/vaultsSecretsNewDir.ts +++ b/src/client/callers/vaultsSecretsNewDir.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsNewDir from '../handlers/VaultsSecretsNewDir'; +import type VaultsSecretsNewDir from '../handlers/VaultsSecretsNewDir.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsRemove.ts b/src/client/callers/vaultsSecretsRemove.ts index 8362ce46a5..53b6be1484 100644 --- a/src/client/callers/vaultsSecretsRemove.ts +++ b/src/client/callers/vaultsSecretsRemove.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsRemove from '../handlers/VaultsSecretsRemove'; +import type VaultsSecretsRemove from '../handlers/VaultsSecretsRemove.js'; import { DuplexCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsRename.ts b/src/client/callers/vaultsSecretsRename.ts index 1bc07ce1d5..40bcca6b7c 100644 --- a/src/client/callers/vaultsSecretsRename.ts +++ b/src/client/callers/vaultsSecretsRename.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsRename from '../handlers/VaultsSecretsRename'; +import type VaultsSecretsRename from '../handlers/VaultsSecretsRename.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsStat.ts b/src/client/callers/vaultsSecretsStat.ts index 5070863432..cd0df5a39f 100644 --- a/src/client/callers/vaultsSecretsStat.ts +++ b/src/client/callers/vaultsSecretsStat.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsStat from '../handlers/VaultsSecretsStat'; +import type VaultsSecretsStat from '../handlers/VaultsSecretsStat.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsTouch.ts b/src/client/callers/vaultsSecretsTouch.ts index c45a830e73..f899396eff 100644 --- a/src/client/callers/vaultsSecretsTouch.ts +++ b/src/client/callers/vaultsSecretsTouch.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsTouch from '../handlers/VaultsSecretsTouch'; +import type VaultsSecretsTouch from '../handlers/VaultsSecretsTouch.js'; import { DuplexCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsSecretsWriteFile.ts b/src/client/callers/vaultsSecretsWriteFile.ts index 1a71aceb39..74dba1e452 100644 --- a/src/client/callers/vaultsSecretsWriteFile.ts +++ b/src/client/callers/vaultsSecretsWriteFile.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsSecretsWriteFile from '../handlers/VaultsSecretsWriteFile'; +import type VaultsSecretsWriteFile from '../handlers/VaultsSecretsWriteFile.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/callers/vaultsVersion.ts b/src/client/callers/vaultsVersion.ts index c6e7bfdb8e..59152a0bd3 100644 --- a/src/client/callers/vaultsVersion.ts +++ b/src/client/callers/vaultsVersion.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsVersion from '../handlers/VaultsVersion'; +import type VaultsVersion from '../handlers/VaultsVersion.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/client/errors.ts b/src/client/errors.ts index 618f4cd1da..24cee22b75 100644 --- a/src/client/errors.ts +++ b/src/client/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorClient extends ErrorPolykey {} diff --git a/src/client/handlers/AgentLockAll.ts b/src/client/handlers/AgentLockAll.ts index 6e7c4b0b77..63b3a14361 100644 --- a/src/client/handlers/AgentLockAll.ts +++ b/src/client/handlers/AgentLockAll.ts @@ -1,6 +1,9 @@ import type { DB } from '@matrixai/db'; -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; -import type SessionManager from '../../sessions/SessionManager'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; +import type SessionManager from '../../sessions/SessionManager.js'; import { UnaryHandler } from '@matrixai/rpc'; class AgentLockAll extends UnaryHandler< diff --git a/src/client/handlers/AgentStatus.ts b/src/client/handlers/AgentStatus.ts index 4ee6017a29..1942d1d433 100644 --- a/src/client/handlers/AgentStatus.ts +++ b/src/client/handlers/AgentStatus.ts @@ -2,11 +2,11 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, StatusResultMessage, -} from '../types'; -import type PolykeyAgent from '../../PolykeyAgent'; +} from '../types.js'; +import type PolykeyAgent from '../../PolykeyAgent.js'; import { UnaryHandler } from '@matrixai/rpc'; -import config from '../../config'; -import * as nodesUtils from '../../nodes/utils'; +import config from '../../config.js'; +import * as nodesUtils from '../../nodes/utils.js'; class AgentStatus extends UnaryHandler< { diff --git a/src/client/handlers/AgentStop.ts b/src/client/handlers/AgentStop.ts index 2ebf2f5706..eae161d018 100644 --- a/src/client/handlers/AgentStop.ts +++ b/src/client/handlers/AgentStop.ts @@ -1,5 +1,8 @@ -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; -import type PolykeyAgent from '../../PolykeyAgent'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; +import type PolykeyAgent from '../../PolykeyAgent.js'; import { running, status } from '@matrixai/async-init'; import { UnaryHandler } from '@matrixai/rpc'; diff --git a/src/client/handlers/AgentUnlock.ts b/src/client/handlers/AgentUnlock.ts index 79a9b0eb6f..eb89837fc1 100644 --- a/src/client/handlers/AgentUnlock.ts +++ b/src/client/handlers/AgentUnlock.ts @@ -1,4 +1,7 @@ -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; import type { ContainerType } from '@matrixai/rpc'; import { UnaryHandler } from '@matrixai/rpc'; diff --git a/src/client/handlers/AuditEventsGet.ts b/src/client/handlers/AuditEventsGet.ts index 308bb05c7d..08b08182ea 100644 --- a/src/client/handlers/AuditEventsGet.ts +++ b/src/client/handlers/AuditEventsGet.ts @@ -1,16 +1,19 @@ import type { ContextTimed } from '@matrixai/contexts'; import type { JSONValue } from '@matrixai/rpc'; -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; import type { AuditEvent, AuditEventSerialized, TopicPath, TopicSubPath, -} from '../../audit/types'; -import type { Audit } from '../../audit'; -import type { AuditEventId, AuditEventIdEncoded } from '../../ids'; +} from '../../audit/types.js'; +import type { Audit } from '../../audit/index.js'; +import type { AuditEventId, AuditEventIdEncoded } from '../../ids/index.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as auditUtils from '../../audit/utils'; +import * as auditUtils from '../../audit/utils.js'; class AuditEventsGet extends ServerHandler< { diff --git a/src/client/handlers/AuditMetricGet.ts b/src/client/handlers/AuditMetricGet.ts index 5a99e7d0f4..0e7058ad73 100644 --- a/src/client/handlers/AuditMetricGet.ts +++ b/src/client/handlers/AuditMetricGet.ts @@ -1,13 +1,16 @@ -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; import type { AuditMetric, MetricPath, MetricPathToAuditMetric, -} from '../../audit/types'; -import type { Audit } from '../../audit'; -import type { AuditEventId, AuditEventIdEncoded } from '../../ids'; +} from '../../audit/types.js'; +import type { Audit } from '../../audit/index.js'; +import type { AuditEventId, AuditEventIdEncoded } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as auditUtils from '../../audit/utils'; +import * as auditUtils from '../../audit/utils.js'; class AuditMetricGet extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsActionsGetByIdentity.ts b/src/client/handlers/GestaltsActionsGetByIdentity.ts index 33d118e043..58ad0ea287 100644 --- a/src/client/handlers/GestaltsActionsGetByIdentity.ts +++ b/src/client/handlers/GestaltsActionsGetByIdentity.ts @@ -3,14 +3,14 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, IdentityMessage, -} from '../types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type { GestaltAction } from '../../gestalts/types'; -import type { IdentityId, ProviderId } from '../../ids'; +} from '../types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type { GestaltAction } from '../../gestalts/types.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; -import * as ids from '../../ids'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; +import * as ids from '../../ids/index.js'; class GestaltsActionsGetByIdentity extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsActionsGetByNode.ts b/src/client/handlers/GestaltsActionsGetByNode.ts index 56e5dda3b3..03e4bb32f8 100644 --- a/src/client/handlers/GestaltsActionsGetByNode.ts +++ b/src/client/handlers/GestaltsActionsGetByNode.ts @@ -4,14 +4,14 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NodeIdMessage, -} from '../types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type { GestaltAction } from '../../gestalts/types'; -import type { NodeId } from '../../ids'; +} from '../types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type { GestaltAction } from '../../gestalts/types.js'; +import type { NodeId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsActionsGetByNode extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsActionsSetByIdentity.ts b/src/client/handlers/GestaltsActionsSetByIdentity.ts index e1ca128067..45221af60d 100644 --- a/src/client/handlers/GestaltsActionsSetByIdentity.ts +++ b/src/client/handlers/GestaltsActionsSetByIdentity.ts @@ -3,15 +3,15 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, SetIdentityActionMessage, -} from '../types'; -import type { IdentityId, ProviderId } from '../../ids'; -import type { GestaltAction } from '../../gestalts/types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; +} from '../types.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; +import type { GestaltAction } from '../../gestalts/types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import * as gestaltsUtils from '../../gestalts/utils'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import * as gestaltsUtils from '../../gestalts/utils.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsActionsSetByIdentityHandler extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsActionsSetByNode.ts b/src/client/handlers/GestaltsActionsSetByNode.ts index dd8803d6f1..34d9be56e7 100644 --- a/src/client/handlers/GestaltsActionsSetByNode.ts +++ b/src/client/handlers/GestaltsActionsSetByNode.ts @@ -3,15 +3,15 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, SetNodeActionMessage, -} from '../types'; -import type { GestaltAction } from '../../gestalts/types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type { NodeId } from '../../ids'; +} from '../types.js'; +import type { GestaltAction } from '../../gestalts/types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type { NodeId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import * as gestaltsUtils from '../../gestalts/utils'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import * as gestaltsUtils from '../../gestalts/utils.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsActionsSetByNode extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsActionsUnsetByIdentity.ts b/src/client/handlers/GestaltsActionsUnsetByIdentity.ts index a36d53624a..7819a0203b 100644 --- a/src/client/handlers/GestaltsActionsUnsetByIdentity.ts +++ b/src/client/handlers/GestaltsActionsUnsetByIdentity.ts @@ -3,15 +3,15 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, SetIdentityActionMessage, -} from '../types'; -import type { IdentityId, ProviderId } from '../../ids'; -import type { GestaltAction } from '../../gestalts/types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; +} from '../types.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; +import type { GestaltAction } from '../../gestalts/types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import * as gestaltsUtils from '../../gestalts/utils'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import * as gestaltsUtils from '../../gestalts/utils.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsActionsUnsetByIdentity extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsActionsUnsetByNode.ts b/src/client/handlers/GestaltsActionsUnsetByNode.ts index 732dfb3955..7a4f52604f 100644 --- a/src/client/handlers/GestaltsActionsUnsetByNode.ts +++ b/src/client/handlers/GestaltsActionsUnsetByNode.ts @@ -3,15 +3,15 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, SetNodeActionMessage, -} from '../types'; -import type { GestaltAction } from '../../gestalts/types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type { NodeId } from '../../ids'; +} from '../types.js'; +import type { GestaltAction } from '../../gestalts/types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type { NodeId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import * as gestaltsUtils from '../../gestalts/utils'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import * as gestaltsUtils from '../../gestalts/utils.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsActionsUnsetByNode extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsDiscoveryByIdentity.ts b/src/client/handlers/GestaltsDiscoveryByIdentity.ts index 5ff692cbfe..0385fe9ae4 100644 --- a/src/client/handlers/GestaltsDiscoveryByIdentity.ts +++ b/src/client/handlers/GestaltsDiscoveryByIdentity.ts @@ -2,13 +2,13 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, IdentityMessage, -} from '../types'; -import type { IdentityId, ProviderId } from '../../ids'; -import type Discovery from '../../discovery/Discovery'; +} from '../types.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; +import type Discovery from '../../discovery/Discovery.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsDiscoveryByIdentity extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsDiscoveryByNode.ts b/src/client/handlers/GestaltsDiscoveryByNode.ts index 06ba9974e1..f570388e7e 100644 --- a/src/client/handlers/GestaltsDiscoveryByNode.ts +++ b/src/client/handlers/GestaltsDiscoveryByNode.ts @@ -2,13 +2,13 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NodeIdMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type Discovery from '../../discovery/Discovery'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type Discovery from '../../discovery/Discovery.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsDiscoveryByNode extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsDiscoveryQueue.ts b/src/client/handlers/GestaltsDiscoveryQueue.ts index 511a267f97..40e5fc25de 100644 --- a/src/client/handlers/GestaltsDiscoveryQueue.ts +++ b/src/client/handlers/GestaltsDiscoveryQueue.ts @@ -1,6 +1,9 @@ -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; -import type Discovery from '../../discovery/Discovery'; -import type { DiscoveryQueueInfo } from '../../discovery/types'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; +import type Discovery from '../../discovery/Discovery.js'; +import type { DiscoveryQueueInfo } from '../../discovery/types.js'; import type { ContextTimed } from '@matrixai/contexts'; import { ServerHandler } from '@matrixai/rpc'; diff --git a/src/client/handlers/GestaltsGestaltGetByIdentity.ts b/src/client/handlers/GestaltsGestaltGetByIdentity.ts index a2797c936a..10e8041fb8 100644 --- a/src/client/handlers/GestaltsGestaltGetByIdentity.ts +++ b/src/client/handlers/GestaltsGestaltGetByIdentity.ts @@ -4,14 +4,14 @@ import type { ClientRPCResponseResult, GestaltMessage, IdentityMessage, -} from '../types'; -import type { IdentityId, ProviderId } from '../../ids'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; +} from '../types.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as nodesUtils from '../../nodes/utils'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as nodesUtils from '../../nodes/utils.js'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsGestaltGetByIdentity extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsGestaltGetByNode.ts b/src/client/handlers/GestaltsGestaltGetByNode.ts index 30b19d3ee7..80ac445c92 100644 --- a/src/client/handlers/GestaltsGestaltGetByNode.ts +++ b/src/client/handlers/GestaltsGestaltGetByNode.ts @@ -4,14 +4,14 @@ import type { ClientRPCResponseResult, GestaltMessage, NodeIdMessage, -} from '../types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type { NodeId } from '../../ids'; +} from '../types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type { NodeId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as nodesUtils from '../../nodes/utils'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as nodesUtils from '../../nodes/utils.js'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsGestaltGetByNode extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsGestaltList.ts b/src/client/handlers/GestaltsGestaltList.ts index 11ba2819a0..5dd90a1aa0 100644 --- a/src/client/handlers/GestaltsGestaltList.ts +++ b/src/client/handlers/GestaltsGestaltList.ts @@ -3,10 +3,10 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, GestaltMessage, -} from '../types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; +} from '../types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as nodesUtils from '../../nodes/utils'; +import * as nodesUtils from '../../nodes/utils.js'; class GestaltsGestaltList extends ServerHandler< { diff --git a/src/client/handlers/GestaltsGestaltTrustByIdentity.ts b/src/client/handlers/GestaltsGestaltTrustByIdentity.ts index 67c2504d49..35f5cd9aa3 100644 --- a/src/client/handlers/GestaltsGestaltTrustByIdentity.ts +++ b/src/client/handlers/GestaltsGestaltTrustByIdentity.ts @@ -3,14 +3,14 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, IdentityMessage, -} from '../types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type { IdentityId, ProviderId } from '../../ids'; -import type Discovery from '../../discovery/Discovery'; +} from '../types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; +import type Discovery from '../../discovery/Discovery.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsGestaltTrustByIdentity extends UnaryHandler< { diff --git a/src/client/handlers/GestaltsGestaltTrustByNode.ts b/src/client/handlers/GestaltsGestaltTrustByNode.ts index 3b3e0aa349..dafb756ef2 100644 --- a/src/client/handlers/GestaltsGestaltTrustByNode.ts +++ b/src/client/handlers/GestaltsGestaltTrustByNode.ts @@ -3,14 +3,14 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NodeIdMessage, -} from '../types'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type { NodeId } from '../../ids'; -import type Discovery from '../../discovery/Discovery'; +} from '../types.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type { NodeId } from '../../ids/index.js'; +import type Discovery from '../../discovery/Discovery.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class GestaltsGestaltTrustByNode extends UnaryHandler< { diff --git a/src/client/handlers/IdentitiesAuthenticate.ts b/src/client/handlers/IdentitiesAuthenticate.ts index 8db5cc553a..9d337d57d6 100644 --- a/src/client/handlers/IdentitiesAuthenticate.ts +++ b/src/client/handlers/IdentitiesAuthenticate.ts @@ -4,14 +4,14 @@ import type { AuthProcessMessage, ClientRPCRequestParams, ClientRPCResponseResult, -} from '../types'; -import type { ProviderId } from '../../ids'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; +} from '../types.js'; +import type { ProviderId } from '../../ids/index.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import * as identitiesErrors from '../../identities/errors'; -import { validateSync } from '../../validation'; -import { matchSync, never } from '../../utils'; +import * as ids from '../../ids/index.js'; +import * as identitiesErrors from '../../identities/errors.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync, never } from '../../utils/index.js'; class IdentitiesAuthenticate extends ServerHandler< { diff --git a/src/client/handlers/IdentitiesAuthenticatedGet.ts b/src/client/handlers/IdentitiesAuthenticatedGet.ts index 3792923663..ff23544543 100644 --- a/src/client/handlers/IdentitiesAuthenticatedGet.ts +++ b/src/client/handlers/IdentitiesAuthenticatedGet.ts @@ -4,13 +4,13 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, IdentityMessage, -} from '../types'; -import type { ProviderId } from '../../ids'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; +} from '../types.js'; +import type { ProviderId } from '../../ids/index.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class IdentitiesAuthenticatedGet extends ServerHandler< { diff --git a/src/client/handlers/IdentitiesClaim.ts b/src/client/handlers/IdentitiesClaim.ts index 14cbcc40e0..b88167df79 100644 --- a/src/client/handlers/IdentitiesClaim.ts +++ b/src/client/handlers/IdentitiesClaim.ts @@ -3,13 +3,13 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, IdentityMessage, -} from '../types'; -import type { IdentityId, ProviderId } from '../../ids'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; +} from '../types.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class IdentitiesClaim extends UnaryHandler< { diff --git a/src/client/handlers/IdentitiesInfoConnectedGet.ts b/src/client/handlers/IdentitiesInfoConnectedGet.ts index 632f493bad..27bea46bf9 100644 --- a/src/client/handlers/IdentitiesInfoConnectedGet.ts +++ b/src/client/handlers/IdentitiesInfoConnectedGet.ts @@ -5,15 +5,15 @@ import type { ClientRPCResponseResult, IdentityInfoMessage, ProviderSearchMessage, -} from '../types'; -import type { IdentityId, ProviderId } from '../../ids'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; -import type { IdentityData } from '../../identities/types'; +} from '../types.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; +import type { IdentityData } from '../../identities/types.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import * as identitiesErrors from '../../identities/errors'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import * as identitiesErrors from '../../identities/errors.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class IdentitiesInfoConnectedGet extends ServerHandler< { diff --git a/src/client/handlers/IdentitiesInfoGet.ts b/src/client/handlers/IdentitiesInfoGet.ts index 80ded3ee80..9730ad0bff 100644 --- a/src/client/handlers/IdentitiesInfoGet.ts +++ b/src/client/handlers/IdentitiesInfoGet.ts @@ -5,16 +5,16 @@ import type { ClientRPCResponseResult, IdentityInfoMessage, ProviderSearchMessage, -} from '../types'; -import type { IdentityId, ProviderId } from '../../ids'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; -import type { IdentityData } from '../../identities/types'; +} from '../types.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; +import type { IdentityData } from '../../identities/types.js'; import { ServerHandler } from '@matrixai/rpc'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; -import * as ids from '../../ids'; -import * as identitiesErrors from '../../identities/errors'; -import * as identitiesUtils from '../../identities/utils'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; +import * as ids from '../../ids/index.js'; +import * as identitiesErrors from '../../identities/errors.js'; +import * as identitiesUtils from '../../identities/utils.js'; class IdentitiesInfoGet extends ServerHandler< { diff --git a/src/client/handlers/IdentitiesInvite.ts b/src/client/handlers/IdentitiesInvite.ts index b2c1ebaab8..94821379a3 100644 --- a/src/client/handlers/IdentitiesInvite.ts +++ b/src/client/handlers/IdentitiesInvite.ts @@ -3,14 +3,14 @@ import type { ClaimNodeMessage, ClientRPCRequestParams, ClientRPCResponseResult, -} from '../types'; -import type { NodeId } from '../../ids'; -import type NotificationsManager from '../../notifications/NotificationsManager'; -import type ACL from '../../acl/ACL'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; +import type ACL from '../../acl/ACL.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class IdentitiesInvite extends UnaryHandler< { diff --git a/src/client/handlers/IdentitiesProvidersList.ts b/src/client/handlers/IdentitiesProvidersList.ts index b4ffde9331..f95034483d 100644 --- a/src/client/handlers/IdentitiesProvidersList.ts +++ b/src/client/handlers/IdentitiesProvidersList.ts @@ -1,5 +1,8 @@ -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; import { UnaryHandler } from '@matrixai/rpc'; class IdentitiesProvidersList extends UnaryHandler< diff --git a/src/client/handlers/IdentitiesTokenDelete.ts b/src/client/handlers/IdentitiesTokenDelete.ts index b770f56fe1..138f375d43 100644 --- a/src/client/handlers/IdentitiesTokenDelete.ts +++ b/src/client/handlers/IdentitiesTokenDelete.ts @@ -3,13 +3,13 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, IdentityMessage, -} from '../types'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; -import type { IdentityId, ProviderId } from '../../ids'; +} from '../types.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class IdentitiesTokenDeleteHandler extends UnaryHandler< { diff --git a/src/client/handlers/IdentitiesTokenGet.ts b/src/client/handlers/IdentitiesTokenGet.ts index 3c569f6754..cf0b46bbda 100644 --- a/src/client/handlers/IdentitiesTokenGet.ts +++ b/src/client/handlers/IdentitiesTokenGet.ts @@ -4,13 +4,13 @@ import type { ClientRPCResponseResult, IdentityMessage, TokenMessage, -} from '../types'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; -import type { IdentityId, ProviderId } from '../../ids'; +} from '../types.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class IdentitiesTokenGet extends UnaryHandler< { diff --git a/src/client/handlers/IdentitiesTokenPut.ts b/src/client/handlers/IdentitiesTokenPut.ts index 0f6a4d1a04..4fd1642e59 100644 --- a/src/client/handlers/IdentitiesTokenPut.ts +++ b/src/client/handlers/IdentitiesTokenPut.ts @@ -4,13 +4,13 @@ import type { ClientRPCResponseResult, IdentityMessage, TokenMessage, -} from '../types'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; -import type { IdentityId, ProviderId } from '../../ids'; +} from '../types.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; +import type { IdentityId, ProviderId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class IdentitiesTokenPut extends UnaryHandler< { diff --git a/src/client/handlers/KeysCertsChainGet.ts b/src/client/handlers/KeysCertsChainGet.ts index ef3ca5ff59..e70f9048f3 100644 --- a/src/client/handlers/KeysCertsChainGet.ts +++ b/src/client/handlers/KeysCertsChainGet.ts @@ -4,8 +4,8 @@ import type { CertMessage, ClientRPCRequestParams, ClientRPCResponseResult, -} from '../types'; -import type CertManager from '../../keys/CertManager'; +} from '../types.js'; +import type CertManager from '../../keys/CertManager.js'; import { ServerHandler } from '@matrixai/rpc'; class KeysCertsChainGet extends ServerHandler< diff --git a/src/client/handlers/KeysCertsGet.ts b/src/client/handlers/KeysCertsGet.ts index f699f45273..14485bb643 100644 --- a/src/client/handlers/KeysCertsGet.ts +++ b/src/client/handlers/KeysCertsGet.ts @@ -2,8 +2,8 @@ import type { CertMessage, ClientRPCRequestParams, ClientRPCResponseResult, -} from '../types'; -import type CertManager from '../../keys/CertManager'; +} from '../types.js'; +import type CertManager from '../../keys/CertManager.js'; import { UnaryHandler } from '@matrixai/rpc'; class KeysCertsGet extends UnaryHandler< diff --git a/src/client/handlers/KeysDecrypt.ts b/src/client/handlers/KeysDecrypt.ts index 5303c7b0fc..e882a2b053 100644 --- a/src/client/handlers/KeysDecrypt.ts +++ b/src/client/handlers/KeysDecrypt.ts @@ -2,10 +2,10 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, DataMessage, -} from '../types'; -import type KeyRing from '../../keys/KeyRing'; +} from '../types.js'; +import type KeyRing from '../../keys/KeyRing.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { never } from '../../utils'; +import { never } from '../../utils/index.js'; class KeysDecrypt extends UnaryHandler< { diff --git a/src/client/handlers/KeysEncrypt.ts b/src/client/handlers/KeysEncrypt.ts index 11598460ca..bafcc4d868 100644 --- a/src/client/handlers/KeysEncrypt.ts +++ b/src/client/handlers/KeysEncrypt.ts @@ -3,13 +3,13 @@ import type { ClientRPCResponseResult, DataMessage, DecryptMessage, -} from '../types'; -import type KeyRing from '../../keys/KeyRing'; -import type { PublicKey } from '../../keys/types'; +} from '../types.js'; +import type KeyRing from '../../keys/KeyRing.js'; +import type { PublicKey } from '../../keys/types.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { never } from '../../utils'; -import * as keysUtils from '../../keys/utils'; -import * as keysErrors from '../../keys/errors'; +import { never } from '../../utils/index.js'; +import * as keysUtils from '../../keys/utils/index.js'; +import * as keysErrors from '../../keys/errors.js'; class KeysEncrypt extends UnaryHandler< { diff --git a/src/client/handlers/KeysKeyPair.ts b/src/client/handlers/KeysKeyPair.ts index cd85e26765..6ebb918418 100644 --- a/src/client/handlers/KeysKeyPair.ts +++ b/src/client/handlers/KeysKeyPair.ts @@ -3,10 +3,10 @@ import type { ClientRPCResponseResult, KeyPairMessage, PasswordMessage, -} from '../types'; -import type KeyRing from '../../keys/KeyRing'; +} from '../types.js'; +import type KeyRing from '../../keys/KeyRing.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as keysUtils from '../../keys/utils'; +import * as keysUtils from '../../keys/utils/index.js'; class KeysKeyPair extends UnaryHandler< { diff --git a/src/client/handlers/KeysKeyPairRenew.ts b/src/client/handlers/KeysKeyPairRenew.ts index 3e22f9602e..8ff3b1477d 100644 --- a/src/client/handlers/KeysKeyPairRenew.ts +++ b/src/client/handlers/KeysKeyPairRenew.ts @@ -2,8 +2,8 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, PasswordMessage, -} from '../types'; -import type CertManager from '../../keys/CertManager'; +} from '../types.js'; +import type CertManager from '../../keys/CertManager.js'; import { UnaryHandler } from '@matrixai/rpc'; class KeysKeyPairRenew extends UnaryHandler< diff --git a/src/client/handlers/KeysKeyPairReset.ts b/src/client/handlers/KeysKeyPairReset.ts index 3ab41360c5..a03cc9526f 100644 --- a/src/client/handlers/KeysKeyPairReset.ts +++ b/src/client/handlers/KeysKeyPairReset.ts @@ -2,8 +2,8 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, PasswordMessage, -} from '../types'; -import type CertManager from '../../keys/CertManager'; +} from '../types.js'; +import type CertManager from '../../keys/CertManager.js'; import { UnaryHandler } from '@matrixai/rpc'; class KeysKeyPairReset extends UnaryHandler< diff --git a/src/client/handlers/KeysPasswordChange.ts b/src/client/handlers/KeysPasswordChange.ts index f1db2af8d7..f825fbfceb 100644 --- a/src/client/handlers/KeysPasswordChange.ts +++ b/src/client/handlers/KeysPasswordChange.ts @@ -2,8 +2,8 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, PasswordMessage, -} from '../types'; -import type KeyRing from '../../keys/KeyRing'; +} from '../types.js'; +import type KeyRing from '../../keys/KeyRing.js'; import { UnaryHandler } from '@matrixai/rpc'; class KeysPasswordChange extends UnaryHandler< diff --git a/src/client/handlers/KeysPublicKey.ts b/src/client/handlers/KeysPublicKey.ts index 398a958a2a..7435ff8f3e 100644 --- a/src/client/handlers/KeysPublicKey.ts +++ b/src/client/handlers/KeysPublicKey.ts @@ -2,10 +2,10 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, PublicKeyMessage, -} from '../types'; -import type KeyRing from '../../keys/KeyRing'; +} from '../types.js'; +import type KeyRing from '../../keys/KeyRing.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as keysUtils from '../../keys/utils'; +import * as keysUtils from '../../keys/utils/index.js'; class KeysPublicKey extends UnaryHandler< { diff --git a/src/client/handlers/KeysSign.ts b/src/client/handlers/KeysSign.ts index da629b1621..b588cc071c 100644 --- a/src/client/handlers/KeysSign.ts +++ b/src/client/handlers/KeysSign.ts @@ -3,8 +3,8 @@ import type { ClientRPCResponseResult, DataMessage, SignatureMessage, -} from '../types'; -import type KeyRing from '../../keys/KeyRing'; +} from '../types.js'; +import type KeyRing from '../../keys/KeyRing.js'; import { UnaryHandler } from '@matrixai/rpc'; class KeysSign extends UnaryHandler< diff --git a/src/client/handlers/KeysVerify.ts b/src/client/handlers/KeysVerify.ts index 0609f897f6..83c81a8d49 100644 --- a/src/client/handlers/KeysVerify.ts +++ b/src/client/handlers/KeysVerify.ts @@ -3,13 +3,13 @@ import type { ClientRPCResponseResult, SuccessMessage, VerifySignatureMessage, -} from '../types'; -import type KeyRing from '../../keys/KeyRing'; -import type { PublicKey, Signature } from '../../keys/types'; +} from '../types.js'; +import type KeyRing from '../../keys/KeyRing.js'; +import type { PublicKey, Signature } from '../../keys/types.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as keysUtils from '../../keys/utils'; -import { never } from '../../utils'; -import * as keysErrors from '../../keys/errors'; +import * as keysUtils from '../../keys/utils/index.js'; +import { never } from '../../utils/index.js'; +import * as keysErrors from '../../keys/errors.js'; class KeysVerify extends UnaryHandler< { diff --git a/src/client/handlers/NodesAdd.ts b/src/client/handlers/NodesAdd.ts index 84991763b4..a937579614 100644 --- a/src/client/handlers/NodesAdd.ts +++ b/src/client/handlers/NodesAdd.ts @@ -5,16 +5,16 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NodesAddMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type { Host, Port } from '../../network/types'; -import type NodeManager from '../../nodes/NodeManager'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type { Host, Port } from '../../network/types.js'; +import type NodeManager from '../../nodes/NodeManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { matchSync } from '../../utils'; -import { validateSync } from '../../validation'; -import * as ids from '../../ids'; -import * as networkUtils from '../../network/utils'; -import * as nodeErrors from '../../nodes/errors'; +import { matchSync } from '../../utils/index.js'; +import { validateSync } from '../../validation/index.js'; +import * as ids from '../../ids/index.js'; +import * as networkUtils from '../../network/utils.js'; +import * as nodeErrors from '../../nodes/errors.js'; class NodesAdd extends UnaryHandler< { diff --git a/src/client/handlers/NodesClaim.ts b/src/client/handlers/NodesClaim.ts index deed7352c0..eb7babf39f 100644 --- a/src/client/handlers/NodesClaim.ts +++ b/src/client/handlers/NodesClaim.ts @@ -4,13 +4,13 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, SuccessMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type NodeManager from '../../nodes/NodeManager'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type NodeManager from '../../nodes/NodeManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { matchSync } from '../../utils'; -import { validateSync } from '../../validation'; +import * as ids from '../../ids/index.js'; +import { matchSync } from '../../utils/index.js'; +import { validateSync } from '../../validation/index.js'; class NodesClaim extends UnaryHandler< { diff --git a/src/client/handlers/NodesFind.ts b/src/client/handlers/NodesFind.ts index 904ed71379..690927d407 100644 --- a/src/client/handlers/NodesFind.ts +++ b/src/client/handlers/NodesFind.ts @@ -5,14 +5,14 @@ import type { ClientRPCResponseResult, NodeIdMessage, NodesFindMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type NodeManager from '../../nodes/NodeManager'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type NodeManager from '../../nodes/NodeManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; -import * as ids from '../../ids'; -import * as nodesErrors from '../../nodes/errors'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; +import * as ids from '../../ids/index.js'; +import * as nodesErrors from '../../nodes/errors.js'; class NodesFind extends UnaryHandler< { diff --git a/src/client/handlers/NodesGetAll.ts b/src/client/handlers/NodesGetAll.ts index 467ef99847..46ca5ba80c 100644 --- a/src/client/handlers/NodesGetAll.ts +++ b/src/client/handlers/NodesGetAll.ts @@ -4,10 +4,10 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NodesGetMessage, -} from '../types'; -import type NodeGraph from '../../nodes/NodeGraph'; +} from '../types.js'; +import type NodeGraph from '../../nodes/NodeGraph.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as nodesUtils from '../../nodes/utils'; +import * as nodesUtils from '../../nodes/utils.js'; class NodesGetAll extends ServerHandler< { diff --git a/src/client/handlers/NodesListConnections.ts b/src/client/handlers/NodesListConnections.ts index ce86fce503..a816852f33 100644 --- a/src/client/handlers/NodesListConnections.ts +++ b/src/client/handlers/NodesListConnections.ts @@ -2,12 +2,12 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NodeConnectionMessage, -} from '../types'; -import type NodeConnectionManager from '../../nodes/NodeConnectionManager'; +} from '../types.js'; +import type NodeConnectionManager from '../../nodes/NodeConnectionManager.js'; import type { ContextTimed } from '@matrixai/contexts'; import type { JSONValue } from '@matrixai/rpc'; import { ServerHandler } from '@matrixai/rpc'; -import * as nodesUtils from '../../nodes/utils'; +import * as nodesUtils from '../../nodes/utils.js'; class NodesListConnections extends ServerHandler< { diff --git a/src/client/handlers/NodesPing.ts b/src/client/handlers/NodesPing.ts index e89b910562..ed69140953 100644 --- a/src/client/handlers/NodesPing.ts +++ b/src/client/handlers/NodesPing.ts @@ -3,13 +3,13 @@ import type { ClientRPCResponseResult, NodeIdMessage, SuccessMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type NodeManager from '../../nodes/NodeManager'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type NodeManager from '../../nodes/NodeManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class NodesPing extends UnaryHandler< { diff --git a/src/client/handlers/NotificationsInboxClear.ts b/src/client/handlers/NotificationsInboxClear.ts index 38f0d4c269..a592a75536 100644 --- a/src/client/handlers/NotificationsInboxClear.ts +++ b/src/client/handlers/NotificationsInboxClear.ts @@ -1,6 +1,9 @@ import type { DB } from '@matrixai/db'; -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; -import type NotificationsManager from '../../notifications/NotificationsManager'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; import { UnaryHandler } from '@matrixai/rpc'; class NotificationsInboxClear extends UnaryHandler< diff --git a/src/client/handlers/NotificationsInboxRead.ts b/src/client/handlers/NotificationsInboxRead.ts index 6da53fc292..a7398451d7 100644 --- a/src/client/handlers/NotificationsInboxRead.ts +++ b/src/client/handlers/NotificationsInboxRead.ts @@ -6,11 +6,11 @@ import type { ClientRPCResponseResult, NotificationInboxMessage, NotificationReadMessage, -} from '../types'; -import type { NotificationId } from '../../ids/types'; -import type NotificationsManager from '../../notifications/NotificationsManager'; +} from '../types.js'; +import type { NotificationId } from '../../ids/types.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as notificationsUtils from '../../notifications/utils'; +import * as notificationsUtils from '../../notifications/utils.js'; class NotificationsInboxRead extends ServerHandler< { diff --git a/src/client/handlers/NotificationsInboxRemove.ts b/src/client/handlers/NotificationsInboxRemove.ts index ae061132f6..8a798e5021 100644 --- a/src/client/handlers/NotificationsInboxRemove.ts +++ b/src/client/handlers/NotificationsInboxRemove.ts @@ -3,11 +3,11 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NotificationRemoveMessage, -} from '../types'; -import type NotificationsManager from '../../notifications/NotificationsManager'; +} from '../types.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as notificationsUtils from '../../notifications/utils'; -import * as validationErrors from '../../validation/errors'; +import * as notificationsUtils from '../../notifications/utils.js'; +import * as validationErrors from '../../validation/errors.js'; class NotificationsInboxRemove extends UnaryHandler< { diff --git a/src/client/handlers/NotificationsOutboxClear.ts b/src/client/handlers/NotificationsOutboxClear.ts index 3bbe1b5b1b..38af92a876 100644 --- a/src/client/handlers/NotificationsOutboxClear.ts +++ b/src/client/handlers/NotificationsOutboxClear.ts @@ -1,6 +1,9 @@ import type { DB } from '@matrixai/db'; -import type { ClientRPCRequestParams, ClientRPCResponseResult } from '../types'; -import type NotificationsManager from '../../notifications/NotificationsManager'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from '../types.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; import { UnaryHandler } from '@matrixai/rpc'; class NotificationsOutboxClear extends UnaryHandler< diff --git a/src/client/handlers/NotificationsOutboxRead.ts b/src/client/handlers/NotificationsOutboxRead.ts index 2f07433784..c76223b9e2 100644 --- a/src/client/handlers/NotificationsOutboxRead.ts +++ b/src/client/handlers/NotificationsOutboxRead.ts @@ -6,11 +6,11 @@ import type { ClientRPCResponseResult, NotificationOutboxMessage, NotificationOutboxReadMessage, -} from '../types'; -import type { NotificationId } from '../../ids/types'; -import type NotificationsManager from '../../notifications/NotificationsManager'; +} from '../types.js'; +import type { NotificationId } from '../../ids/types.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as notificationsUtils from '../../notifications/utils'; +import * as notificationsUtils from '../../notifications/utils.js'; class NotificationsOutboxRead extends ServerHandler< { diff --git a/src/client/handlers/NotificationsOutboxRemove.ts b/src/client/handlers/NotificationsOutboxRemove.ts index 10412a4f78..b5c7adbb79 100644 --- a/src/client/handlers/NotificationsOutboxRemove.ts +++ b/src/client/handlers/NotificationsOutboxRemove.ts @@ -3,11 +3,11 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NotificationRemoveMessage, -} from '../types'; -import type NotificationsManager from '../../notifications/NotificationsManager'; +} from '../types.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as notificationsUtils from '../../notifications/utils'; -import * as validationErrors from '../../validation/errors'; +import * as notificationsUtils from '../../notifications/utils.js'; +import * as validationErrors from '../../validation/errors.js'; class NotificationsOutboxRemove extends UnaryHandler< { diff --git a/src/client/handlers/NotificationsSend.ts b/src/client/handlers/NotificationsSend.ts index 6628c6a22f..374098e05e 100644 --- a/src/client/handlers/NotificationsSend.ts +++ b/src/client/handlers/NotificationsSend.ts @@ -2,14 +2,14 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, NotificationSendMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type { General } from '../../notifications/types'; -import type NotificationsManager from '../../notifications/NotificationsManager'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type { General } from '../../notifications/types.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class NotificationsSend extends UnaryHandler< { diff --git a/src/client/handlers/VaultsClone.ts b/src/client/handlers/VaultsClone.ts index 069b2ddf46..5f47d4a8b2 100644 --- a/src/client/handlers/VaultsClone.ts +++ b/src/client/handlers/VaultsClone.ts @@ -6,13 +6,13 @@ import type { ClientRPCResponseResult, CloneMessage, SuccessMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; -import * as ids from '../../ids'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; +import * as ids from '../../ids/index.js'; class VaultsClone extends UnaryHandler< { diff --git a/src/client/handlers/VaultsCreate.ts b/src/client/handlers/VaultsCreate.ts index fb4518fc7a..39c2380589 100644 --- a/src/client/handlers/VaultsCreate.ts +++ b/src/client/handlers/VaultsCreate.ts @@ -6,10 +6,10 @@ import type { ClientRPCResponseResult, VaultIdMessage, VaultNameMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; +import * as vaultsUtils from '../../vaults/utils.js'; class VaultsCreate extends UnaryHandler< { diff --git a/src/client/handlers/VaultsDelete.ts b/src/client/handlers/VaultsDelete.ts index 714410c6dc..b1b1968aea 100644 --- a/src/client/handlers/VaultsDelete.ts +++ b/src/client/handlers/VaultsDelete.ts @@ -6,11 +6,11 @@ import type { ClientRPCResponseResult, SuccessMessage, VaultIdentifierMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as vaultsErrors from '../../vaults/errors'; -import * as vaultsUtils from '../../vaults/utils'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as vaultsUtils from '../../vaults/utils.js'; class VaultsDelete extends UnaryHandler< { diff --git a/src/client/handlers/VaultsList.ts b/src/client/handlers/VaultsList.ts index 9eac012d48..aea177cf9a 100644 --- a/src/client/handlers/VaultsList.ts +++ b/src/client/handlers/VaultsList.ts @@ -4,11 +4,11 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, VaultListMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import type { JSONValue } from '@matrixai/rpc'; import { ServerHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; +import * as vaultsUtils from '../../vaults/utils.js'; class VaultsList extends ServerHandler< { diff --git a/src/client/handlers/VaultsLog.ts b/src/client/handlers/VaultsLog.ts index 67e58fe9d1..d00079816f 100644 --- a/src/client/handlers/VaultsLog.ts +++ b/src/client/handlers/VaultsLog.ts @@ -6,11 +6,11 @@ import type { ClientRPCResponseResult, LogEntryMessage, VaultsLogMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; class VaultsLog extends ServerHandler< { diff --git a/src/client/handlers/VaultsPermissionGet.ts b/src/client/handlers/VaultsPermissionGet.ts index c51d8c8584..9196194125 100644 --- a/src/client/handlers/VaultsPermissionGet.ts +++ b/src/client/handlers/VaultsPermissionGet.ts @@ -6,16 +6,16 @@ import type { ClientRPCResponseResult, VaultIdentifierMessage, VaultPermissionMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; -import type ACL from '../../acl/ACL'; -import type { VaultAction, VaultActions } from '../../vaults/types'; -import type { NodeId, NodeIdEncoded } from '../../ids'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; +import type ACL from '../../acl/ACL.js'; +import type { VaultAction, VaultActions } from '../../vaults/types.js'; +import type { NodeId, NodeIdEncoded } from '../../ids/index.js'; import { IdInternal } from '@matrixai/id'; import { ServerHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as nodesUtils from '../../nodes/utils'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as nodesUtils from '../../nodes/utils.js'; class VaultsPermissionGet extends ServerHandler< { diff --git a/src/client/handlers/VaultsPermissionSet.ts b/src/client/handlers/VaultsPermissionSet.ts index 9614ccb3f5..02cdac6cbf 100644 --- a/src/client/handlers/VaultsPermissionSet.ts +++ b/src/client/handlers/VaultsPermissionSet.ts @@ -4,19 +4,19 @@ import type { ClientRPCResponseResult, PermissionSetMessage, SuccessMessage, -} from '../types'; -import type ACL from '../../acl/ACL'; -import type { VaultAction, VaultActions } from '../../vaults/types'; -import type VaultManager from '../../vaults/VaultManager'; -import type NotificationsManager from '../../notifications/NotificationsManager'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type { NodeId } from '../../ids'; +} from '../types.js'; +import type ACL from '../../acl/ACL.js'; +import type { VaultAction, VaultActions } from '../../vaults/types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type { NodeId } from '../../ids/index.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; -import * as ids from '../../ids'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; +import * as ids from '../../ids/index.js'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; class VaultsPermissionSet extends UnaryHandler< { diff --git a/src/client/handlers/VaultsPermissionUnset.ts b/src/client/handlers/VaultsPermissionUnset.ts index 6f1668181c..c6650cb468 100644 --- a/src/client/handlers/VaultsPermissionUnset.ts +++ b/src/client/handlers/VaultsPermissionUnset.ts @@ -4,18 +4,18 @@ import type { ClientRPCResponseResult, PermissionSetMessage, SuccessMessage, -} from '../types'; -import type { VaultAction } from '../../vaults/types'; -import type { NodeId } from '../../ids'; -import type VaultManager from '../../vaults/VaultManager'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type ACL from '../../acl/ACL'; +} from '../types.js'; +import type { VaultAction } from '../../vaults/types.js'; +import type { NodeId } from '../../ids/index.js'; +import type VaultManager from '../../vaults/VaultManager.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type ACL from '../../acl/ACL.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as ids from '../../ids'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; +import * as ids from '../../ids/index.js'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; class VaultsPermissionUnset extends UnaryHandler< { diff --git a/src/client/handlers/VaultsPull.ts b/src/client/handlers/VaultsPull.ts index 917a79bab6..eb71893702 100644 --- a/src/client/handlers/VaultsPull.ts +++ b/src/client/handlers/VaultsPull.ts @@ -6,15 +6,15 @@ import type { ClientRPCResponseResult, SuccessMessage, VaultsPullMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; -import * as ids from '../../ids'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; +import * as ids from '../../ids/index.js'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; class VaultsPull extends UnaryHandler< { diff --git a/src/client/handlers/VaultsRename.ts b/src/client/handlers/VaultsRename.ts index 48b3905142..10b40fbfb1 100644 --- a/src/client/handlers/VaultsRename.ts +++ b/src/client/handlers/VaultsRename.ts @@ -4,11 +4,11 @@ import type { ClientRPCResponseResult, VaultIdMessage, VaultsRenameMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; class VaultsRename extends UnaryHandler< { diff --git a/src/client/handlers/VaultsScan.ts b/src/client/handlers/VaultsScan.ts index dfeb277738..11aa362db8 100644 --- a/src/client/handlers/VaultsScan.ts +++ b/src/client/handlers/VaultsScan.ts @@ -5,13 +5,13 @@ import type { ClientRPCResponseResult, NodeIdMessage, VaultsScanMessage, -} from '../types'; -import type { NodeId } from '../../ids'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type { NodeId } from '../../ids/index.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { ServerHandler } from '@matrixai/rpc'; -import { validateSync } from '../../validation'; -import { matchSync } from '../../utils'; -import * as ids from '../../ids'; +import { validateSync } from '../../validation/index.js'; +import { matchSync } from '../../utils/index.js'; +import * as ids from '../../ids/index.js'; class VaultsScan extends ServerHandler< { diff --git a/src/client/handlers/VaultsSecretsCat.ts b/src/client/handlers/VaultsSecretsCat.ts index c5038cd9fb..cb8dc1be3b 100644 --- a/src/client/handlers/VaultsSecretsCat.ts +++ b/src/client/handlers/VaultsSecretsCat.ts @@ -6,12 +6,12 @@ import type { ClientRPCResponseResult, ContentOrErrorMessage, SecretIdentifierMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { DuplexHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as vaultOps from '../../vaults/VaultOps'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as vaultOps from '../../vaults/VaultOps.js'; class VaultsSecretsCat extends DuplexHandler< { diff --git a/src/client/handlers/VaultsSecretsEnv.ts b/src/client/handlers/VaultsSecretsEnv.ts index 409eb522e6..0f89da5ac0 100644 --- a/src/client/handlers/VaultsSecretsEnv.ts +++ b/src/client/handlers/VaultsSecretsEnv.ts @@ -6,11 +6,11 @@ import type { ClientRPCResponseResult, SecretIdentifierMessage, SecretContentMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { DuplexHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; class VaultsSecretsEnv extends DuplexHandler< { diff --git a/src/client/handlers/VaultsSecretsList.ts b/src/client/handlers/VaultsSecretsList.ts index c2e194f254..6fddc24864 100644 --- a/src/client/handlers/VaultsSecretsList.ts +++ b/src/client/handlers/VaultsSecretsList.ts @@ -6,12 +6,12 @@ import type { ClientRPCResponseResult, SecretFilesMessage, SecretIdentifierMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; -import path from 'path'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; +import path from 'node:path'; import { ServerHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; class VaultsSecretsList extends ServerHandler< { diff --git a/src/client/handlers/VaultsSecretsMkdir.ts b/src/client/handlers/VaultsSecretsMkdir.ts index 22dee5aed4..e180322918 100644 --- a/src/client/handlers/VaultsSecretsMkdir.ts +++ b/src/client/handlers/VaultsSecretsMkdir.ts @@ -6,13 +6,13 @@ import type { ClientRPCResponseResult, SecretDirMessage, SuccessOrErrorMessageTagged, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; -import type { POJO } from '../../types'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; +import type { POJO } from '../../types.js'; import { DuplexHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as vaultOps from '../../vaults/VaultOps'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as vaultOps from '../../vaults/VaultOps.js'; class VaultsSecretsMkdir extends DuplexHandler< { diff --git a/src/client/handlers/VaultsSecretsNewDir.ts b/src/client/handlers/VaultsSecretsNewDir.ts index 1287fa077e..0854111ba8 100644 --- a/src/client/handlers/VaultsSecretsNewDir.ts +++ b/src/client/handlers/VaultsSecretsNewDir.ts @@ -1,4 +1,4 @@ -import type { FileSystem } from 'types'; +import type { FileSystem } from 'types.js'; import type { ContextTimed } from '@matrixai/contexts'; import type { DB } from '@matrixai/db'; import type { JSONValue } from '@matrixai/rpc'; @@ -7,12 +7,12 @@ import type { ClientRPCResponseResult, SecretDirMessage, SuccessMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as vaultOps from '../../vaults/VaultOps'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as vaultOps from '../../vaults/VaultOps.js'; class VaultsSecretsNewDir extends UnaryHandler< { diff --git a/src/client/handlers/VaultsSecretsRemove.ts b/src/client/handlers/VaultsSecretsRemove.ts index 9fd7ad787c..605f7135fa 100644 --- a/src/client/handlers/VaultsSecretsRemove.ts +++ b/src/client/handlers/VaultsSecretsRemove.ts @@ -8,14 +8,14 @@ import type { SecretsRemoveHeaderMessage, SecretIdentifierMessageTagged, SuccessOrErrorMessageTagged, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; -import type { FileSystemWritable } from '../../vaults/types'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; +import type { FileSystemWritable } from '../../vaults/types.js'; import { withG } from '@matrixai/resources'; import { DuplexHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as clientErrors from '../errors'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as clientErrors from '../errors.js'; class VaultsSecretsRemove extends DuplexHandler< { diff --git a/src/client/handlers/VaultsSecretsRename.ts b/src/client/handlers/VaultsSecretsRename.ts index dea09fbaeb..7bebb855a2 100644 --- a/src/client/handlers/VaultsSecretsRename.ts +++ b/src/client/handlers/VaultsSecretsRename.ts @@ -6,12 +6,12 @@ import type { ClientRPCResponseResult, SecretRenameMessage, SuccessMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as vaultOps from '../../vaults/VaultOps'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as vaultOps from '../../vaults/VaultOps.js'; class VaultsSecretsRename extends UnaryHandler< { diff --git a/src/client/handlers/VaultsSecretsStat.ts b/src/client/handlers/VaultsSecretsStat.ts index a808c74e70..ae69b34aed 100644 --- a/src/client/handlers/VaultsSecretsStat.ts +++ b/src/client/handlers/VaultsSecretsStat.ts @@ -4,12 +4,12 @@ import type { ClientRPCResponseResult, SecretIdentifierMessage, SecretStatMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as vaultOps from '../../vaults/VaultOps'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as vaultOps from '../../vaults/VaultOps.js'; class VaultsSecretsStat extends UnaryHandler< { diff --git a/src/client/handlers/VaultsSecretsTouch.ts b/src/client/handlers/VaultsSecretsTouch.ts index 27b9b7cc8c..fa0b0348ce 100644 --- a/src/client/handlers/VaultsSecretsTouch.ts +++ b/src/client/handlers/VaultsSecretsTouch.ts @@ -8,14 +8,14 @@ import type { SecretIdentifierMessageTagged, SuccessOrErrorMessageTagged, VaultNamesHeaderMessageTagged, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; -import type { FileSystemWritable } from '../../vaults/types'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; +import type { FileSystemWritable } from '../../vaults/types.js'; import { withG } from '@matrixai/resources'; import { DuplexHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as clientErrors from '../errors'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as clientErrors from '../errors.js'; class VaultsSecretsTouch extends DuplexHandler< { diff --git a/src/client/handlers/VaultsSecretsWriteFile.ts b/src/client/handlers/VaultsSecretsWriteFile.ts index 1d6a30863d..f973e9c694 100644 --- a/src/client/handlers/VaultsSecretsWriteFile.ts +++ b/src/client/handlers/VaultsSecretsWriteFile.ts @@ -6,12 +6,12 @@ import type { ClientRPCResponseResult, SecretContentMessage, SuccessMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; -import * as vaultOps from '../../vaults/VaultOps'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; +import * as vaultOps from '../../vaults/VaultOps.js'; class VaultsSecretsWriteFile extends UnaryHandler< { diff --git a/src/client/handlers/VaultsVersion.ts b/src/client/handlers/VaultsVersion.ts index d560c9163f..5752fd1064 100644 --- a/src/client/handlers/VaultsVersion.ts +++ b/src/client/handlers/VaultsVersion.ts @@ -4,11 +4,11 @@ import type { ClientRPCResponseResult, VaultsLatestVersionMessage, VaultsVersionMessage, -} from '../types'; -import type VaultManager from '../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../vaults/VaultManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as vaultsUtils from '../../vaults/utils'; -import * as vaultsErrors from '../../vaults/errors'; +import * as vaultsUtils from '../../vaults/utils.js'; +import * as vaultsErrors from '../../vaults/errors.js'; class VaultsVersion extends UnaryHandler< { diff --git a/src/client/handlers/index.ts b/src/client/handlers/index.ts index 472bdcb7d0..cd9be79e32 100644 --- a/src/client/handlers/index.ts +++ b/src/client/handlers/index.ts @@ -1,96 +1,96 @@ import type { DB } from '@matrixai/db'; import type Logger from '@matrixai/logger'; -import type ACL from '../../acl/ACL'; -import type Audit from '../../audit/Audit'; -import type KeyRing from '../../keys/KeyRing'; -import type CertManager from '../../keys/CertManager'; -import type SessionManager from '../../sessions/SessionManager'; -import type GestaltGraph from '../../gestalts/GestaltGraph'; -import type IdentitiesManager from '../../identities/IdentitiesManager'; -import type Discovery from '../../discovery/Discovery'; -import type NotificationsManager from '../../notifications/NotificationsManager'; -import type NodeManager from '../../nodes/NodeManager'; -import type NodeConnectionManager from '../../nodes/NodeConnectionManager'; -import type NodeGraph from '../../nodes/NodeGraph'; -import type VaultManager from '../../vaults/VaultManager'; -import type PolykeyAgent from '../../PolykeyAgent'; -import type { FileSystem } from '../../types'; -import AgentLockAll from './AgentLockAll'; -import AgentStatus from './AgentStatus'; -import AgentStop from './AgentStop'; -import AgentUnlock from './AgentUnlock'; -import AuditEventsGet from './AuditEventsGet'; -import AuditMetricGet from './AuditMetricGet'; -import GestaltsActionsGetByIdentity from './GestaltsActionsGetByIdentity'; -import GestaltsActionsGetByNode from './GestaltsActionsGetByNode'; -import GestaltsActionsSetByIdentity from './GestaltsActionsSetByIdentity'; -import GestaltsActionsSetByNode from './GestaltsActionsSetByNode'; -import GestaltsActionsUnsetByIdentity from './GestaltsActionsUnsetByIdentity'; -import GestaltsActionsUnsetByNode from './GestaltsActionsUnsetByNode'; -import GestaltsDiscoveryByIdentity from './GestaltsDiscoveryByIdentity'; -import GestaltsDiscoveryByNode from './GestaltsDiscoveryByNode'; -import GestaltsGestaltGetByIdentity from './GestaltsGestaltGetByIdentity'; -import GestaltsGestaltGetByNode from './GestaltsGestaltGetByNode'; -import GestaltsGestaltList from './GestaltsGestaltList'; -import GestaltsGestaltTrustByIdentity from './GestaltsGestaltTrustByIdentity'; -import GestaltsGestaltTrustByNode from './GestaltsGestaltTrustByNode'; -import GestaltsDiscoveryQueue from './GestaltsDiscoveryQueue'; -import IdentitiesAuthenticate from './IdentitiesAuthenticate'; -import IdentitiesAuthenticatedGet from './IdentitiesAuthenticatedGet'; -import IdentitiesClaim from './IdentitiesClaim'; -import IdentitiesInfoConnectedGet from './IdentitiesInfoConnectedGet'; -import IdentitiesInfoGet from './IdentitiesInfoGet'; -import IdentitiesInvite from './IdentitiesInvite'; -import IdentitiesProvidersList from './IdentitiesProvidersList'; -import IdentitiesTokenDelete from './IdentitiesTokenDelete'; -import IdentitiesTokenGet from './IdentitiesTokenGet'; -import IdentitiesTokenPut from './IdentitiesTokenPut'; -import KeysCertsChainGet from './KeysCertsChainGet'; -import KeysCertsGet from './KeysCertsGet'; -import KeysDecrypt from './KeysDecrypt'; -import KeysEncrypt from './KeysEncrypt'; -import KeysKeyPair from './KeysKeyPair'; -import KeysKeyPairRenew from './KeysKeyPairRenew'; -import KeysKeyPairReset from './KeysKeyPairReset'; -import KeysPasswordChange from './KeysPasswordChange'; -import KeysPublicKey from './KeysPublicKey'; -import KeysSign from './KeysSign'; -import KeysVerify from './KeysVerify'; -import NodesAdd from './NodesAdd'; -import NodesClaim from './NodesClaim'; -import NodesFind from './NodesFind'; -import NodesGetAll from './NodesGetAll'; -import NodesListConnections from './NodesListConnections'; -import NodesPing from './NodesPing'; -import NotificationsInboxClear from './NotificationsInboxClear'; -import NotificationsInboxRead from './NotificationsInboxRead'; -import NotificationsInboxRemove from './NotificationsInboxRemove'; -import NotificationsOutboxClear from './NotificationsOutboxClear'; -import NotificationsOutboxRead from './NotificationsOutboxRead'; -import NotificationsOutboxRemove from './NotificationsOutboxRemove'; -import NotificationsSend from './NotificationsSend'; -import VaultsClone from './VaultsClone'; -import VaultsCreate from './VaultsCreate'; -import VaultsDelete from './VaultsDelete'; -import VaultsList from './VaultsList'; -import VaultsLog from './VaultsLog'; -import VaultsPermissionGet from './VaultsPermissionGet'; -import VaultsPermissionSet from './VaultsPermissionSet'; -import VaultsPermissionUnset from './VaultsPermissionUnset'; -import VaultsPull from './VaultsPull'; -import VaultsRename from './VaultsRename'; -import VaultsScan from './VaultsScan'; -import VaultsSecretsCat from './VaultsSecretsCat'; -import VaultsSecretsEnv from './VaultsSecretsEnv'; -import VaultsSecretsList from './VaultsSecretsList'; -import VaultsSecretsMkdir from './VaultsSecretsMkdir'; -import VaultsSecretsNewDir from './VaultsSecretsNewDir'; -import VaultsSecretsRename from './VaultsSecretsRename'; -import VaultsSecretsRemove from './VaultsSecretsRemove'; -import VaultsSecretsStat from './VaultsSecretsStat'; -import VaultsSecretsTouch from './VaultsSecretsTouch'; -import VaultsSecretsWriteFile from './VaultsSecretsWriteFile'; -import VaultsVersion from './VaultsVersion'; +import type ACL from '../../acl/ACL.js'; +import type Audit from '../../audit/Audit.js'; +import type KeyRing from '../../keys/KeyRing.js'; +import type CertManager from '../../keys/CertManager.js'; +import type SessionManager from '../../sessions/SessionManager.js'; +import type GestaltGraph from '../../gestalts/GestaltGraph.js'; +import type IdentitiesManager from '../../identities/IdentitiesManager.js'; +import type Discovery from '../../discovery/Discovery.js'; +import type NotificationsManager from '../../notifications/NotificationsManager.js'; +import type NodeManager from '../../nodes/NodeManager.js'; +import type NodeConnectionManager from '../../nodes/NodeConnectionManager.js'; +import type NodeGraph from '../../nodes/NodeGraph.js'; +import type VaultManager from '../../vaults/VaultManager.js'; +import type PolykeyAgent from '../../PolykeyAgent.js'; +import type { FileSystem } from '../../types.js'; +import AgentLockAll from './AgentLockAll.js'; +import AgentStatus from './AgentStatus.js'; +import AgentStop from './AgentStop.js'; +import AgentUnlock from './AgentUnlock.js'; +import AuditEventsGet from './AuditEventsGet.js'; +import AuditMetricGet from './AuditMetricGet.js'; +import GestaltsActionsGetByIdentity from './GestaltsActionsGetByIdentity.js'; +import GestaltsActionsGetByNode from './GestaltsActionsGetByNode.js'; +import GestaltsActionsSetByIdentity from './GestaltsActionsSetByIdentity.js'; +import GestaltsActionsSetByNode from './GestaltsActionsSetByNode.js'; +import GestaltsActionsUnsetByIdentity from './GestaltsActionsUnsetByIdentity.js'; +import GestaltsActionsUnsetByNode from './GestaltsActionsUnsetByNode.js'; +import GestaltsDiscoveryByIdentity from './GestaltsDiscoveryByIdentity.js'; +import GestaltsDiscoveryByNode from './GestaltsDiscoveryByNode.js'; +import GestaltsGestaltGetByIdentity from './GestaltsGestaltGetByIdentity.js'; +import GestaltsGestaltGetByNode from './GestaltsGestaltGetByNode.js'; +import GestaltsGestaltList from './GestaltsGestaltList.js'; +import GestaltsGestaltTrustByIdentity from './GestaltsGestaltTrustByIdentity.js'; +import GestaltsGestaltTrustByNode from './GestaltsGestaltTrustByNode.js'; +import GestaltsDiscoveryQueue from './GestaltsDiscoveryQueue.js'; +import IdentitiesAuthenticate from './IdentitiesAuthenticate.js'; +import IdentitiesAuthenticatedGet from './IdentitiesAuthenticatedGet.js'; +import IdentitiesClaim from './IdentitiesClaim.js'; +import IdentitiesInfoConnectedGet from './IdentitiesInfoConnectedGet.js'; +import IdentitiesInfoGet from './IdentitiesInfoGet.js'; +import IdentitiesInvite from './IdentitiesInvite.js'; +import IdentitiesProvidersList from './IdentitiesProvidersList.js'; +import IdentitiesTokenDelete from './IdentitiesTokenDelete.js'; +import IdentitiesTokenGet from './IdentitiesTokenGet.js'; +import IdentitiesTokenPut from './IdentitiesTokenPut.js'; +import KeysCertsChainGet from './KeysCertsChainGet.js'; +import KeysCertsGet from './KeysCertsGet.js'; +import KeysDecrypt from './KeysDecrypt.js'; +import KeysEncrypt from './KeysEncrypt.js'; +import KeysKeyPair from './KeysKeyPair.js'; +import KeysKeyPairRenew from './KeysKeyPairRenew.js'; +import KeysKeyPairReset from './KeysKeyPairReset.js'; +import KeysPasswordChange from './KeysPasswordChange.js'; +import KeysPublicKey from './KeysPublicKey.js'; +import KeysSign from './KeysSign.js'; +import KeysVerify from './KeysVerify.js'; +import NodesAdd from './NodesAdd.js'; +import NodesClaim from './NodesClaim.js'; +import NodesFind from './NodesFind.js'; +import NodesGetAll from './NodesGetAll.js'; +import NodesListConnections from './NodesListConnections.js'; +import NodesPing from './NodesPing.js'; +import NotificationsInboxClear from './NotificationsInboxClear.js'; +import NotificationsInboxRead from './NotificationsInboxRead.js'; +import NotificationsInboxRemove from './NotificationsInboxRemove.js'; +import NotificationsOutboxClear from './NotificationsOutboxClear.js'; +import NotificationsOutboxRead from './NotificationsOutboxRead.js'; +import NotificationsOutboxRemove from './NotificationsOutboxRemove.js'; +import NotificationsSend from './NotificationsSend.js'; +import VaultsClone from './VaultsClone.js'; +import VaultsCreate from './VaultsCreate.js'; +import VaultsDelete from './VaultsDelete.js'; +import VaultsList from './VaultsList.js'; +import VaultsLog from './VaultsLog.js'; +import VaultsPermissionGet from './VaultsPermissionGet.js'; +import VaultsPermissionSet from './VaultsPermissionSet.js'; +import VaultsPermissionUnset from './VaultsPermissionUnset.js'; +import VaultsPull from './VaultsPull.js'; +import VaultsRename from './VaultsRename.js'; +import VaultsScan from './VaultsScan.js'; +import VaultsSecretsCat from './VaultsSecretsCat.js'; +import VaultsSecretsEnv from './VaultsSecretsEnv.js'; +import VaultsSecretsList from './VaultsSecretsList.js'; +import VaultsSecretsMkdir from './VaultsSecretsMkdir.js'; +import VaultsSecretsNewDir from './VaultsSecretsNewDir.js'; +import VaultsSecretsRename from './VaultsSecretsRename.js'; +import VaultsSecretsRemove from './VaultsSecretsRemove.js'; +import VaultsSecretsStat from './VaultsSecretsStat.js'; +import VaultsSecretsTouch from './VaultsSecretsTouch.js'; +import VaultsSecretsWriteFile from './VaultsSecretsWriteFile.js'; +import VaultsVersion from './VaultsVersion.js'; /** * Server manifest factory. diff --git a/src/client/index.ts b/src/client/index.ts index c339d6e97e..158dc7f533 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -1,9 +1,9 @@ -export { default as manifestClient } from './callers'; -export { default as manifestServer } from './handlers'; -export * as callers from './callers'; -export * as handlers from './handlers'; -export * as utils from './utils'; -export * as middleware from './middleware'; -export * as authenticationMiddleware from './authenticationMiddleware'; -export * as errors from './errors'; -export * as types from './types'; +export { default as manifestClient } from './callers/index.js'; +export { default as manifestServer } from './handlers/index.js'; +export * as callers from './callers/index.js'; +export * as handlers from './handlers/index.js'; +export * as utils from './utils.js'; +export * as middleware from './middleware.js'; +export * as authenticationMiddleware from './authenticationMiddleware.js'; +export * as errors from './errors.js'; +export * as types from './types.js'; diff --git a/src/client/middleware.ts b/src/client/middleware.ts index d6b3690579..226c692071 100644 --- a/src/client/middleware.ts +++ b/src/client/middleware.ts @@ -1,13 +1,16 @@ -import type { ClientRPCRequestParams, ClientRPCResponseResult } from './types'; -import type { Session } from '../sessions'; +import type { + ClientRPCRequestParams, + ClientRPCResponseResult, +} from './types.js'; +import type { Session } from '../sessions/index.js'; import type { JSONRPCRequest, JSONRPCResponse, MiddlewareFactory, } from '@matrixai/rpc'; -import type SessionManager from '../sessions/SessionManager'; -import type KeyRing from '../keys/KeyRing'; -import * as authenticationMiddlewareUtils from './authenticationMiddleware'; +import type SessionManager from '../sessions/SessionManager.js'; +import type KeyRing from '../keys/KeyRing.js'; +import * as authenticationMiddlewareUtils from './authenticationMiddleware.js'; function middlewareServer( sessionManager: SessionManager, diff --git a/src/client/types.ts b/src/client/types.ts index fa8a44f308..8e08254fe8 100644 --- a/src/client/types.ts +++ b/src/client/types.ts @@ -11,19 +11,23 @@ import type { NotificationIdEncoded, ProviderId, VaultIdEncoded, -} from '../ids'; -import type { GestaltAction } from '../gestalts/types'; -import type { CommitId, VaultAction, VaultName } from '../vaults/types'; -import type { CertificatePEM, JWKEncrypted, PublicKeyJWK } from '../keys/types'; -import type { Notification } from '../notifications/types'; -import type { ProviderToken } from '../identities/types'; -import type { AuditMetricGetTypeOverride } from './callers/auditMetricGet'; +} from '../ids/index.js'; +import type { GestaltAction } from '../gestalts/types.js'; +import type { CommitId, VaultAction, VaultName } from '../vaults/types.js'; +import type { + CertificatePEM, + JWKEncrypted, + PublicKeyJWK, +} from '../keys/types.js'; +import type { Notification } from '../notifications/types.js'; +import type { ProviderToken } from '../identities/types.js'; +import type { AuditMetricGetTypeOverride } from './callers/auditMetricGet.js'; import type { NodeContact, NodeAddress, NodeContactAddressData, -} from '../nodes/types'; -import type { AuditEventsGetTypeOverride } from './callers/auditEventsGet'; +} from '../nodes/types.js'; +import type { AuditEventsGetTypeOverride } from './callers/auditEventsGet.js'; type ClientRPCRequestParams = JSONRPCResponseResult< diff --git a/src/client/utils.ts b/src/client/utils.ts index 2836d6f749..9de8e4b8fe 100644 --- a/src/client/utils.ts +++ b/src/client/utils.ts @@ -1,13 +1,13 @@ import type { JSONRPCRequest } from '@matrixai/rpc'; -import type { ClientRPCRequestParams } from './types'; -import type SessionManager from '../sessions/SessionManager'; -import type { SessionToken } from '../sessions/types'; -import type KeyRing from '../keys/KeyRing'; -import type { Certificate, CertificatePEM } from '../keys/types'; -import type { NodeId } from '../ids'; -import { utils as wsUtils } from '@matrixai/ws'; -import * as clientErrors from './errors'; -import * as keysUtils from '../keys/utils'; +import type { ClientRPCRequestParams } from './types.js'; +import type SessionManager from '../sessions/SessionManager.js'; +import type { SessionToken } from '../sessions/types.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type { Certificate, CertificatePEM } from '../keys/types.js'; +import type { NodeId } from '../ids/index.js'; +import { utils as wsUtils } from '@matrixai/ws/index.js'; +import * as clientErrors from './errors.js'; +import * as keysUtils from '../keys/utils/index.js'; async function authenticate( sessionManager: SessionManager, diff --git a/src/config.ts b/src/config.ts index 310ef5d7e9..a837e930a8 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,7 +1,7 @@ -import type { PasswordMemLimit, PasswordOpsLimit } from './keys/types'; -import { getDefaultNodePath } from './utils'; +import type { PasswordMemLimit, PasswordOpsLimit } from './keys/types.js'; +import { getDefaultNodePath } from './utils/index.js'; // @ts-ignore package.json is outside rootDir -import { version } from '../package.json'; +import packageJSON from '../package.json' assert { type: 'json' }; /** * Polykey static configuration @@ -21,7 +21,7 @@ const config = { * Version of source code * This must match the package.json */ - sourceVersion: version, + sourceVersion: packageJSON.version, /** * Version of the state, persisted into the node state * It is only incremented on breaking changes diff --git a/src/discovery/Discovery.ts b/src/discovery/Discovery.ts index d5f3865bdf..c9cc2d3490 100644 --- a/src/discovery/Discovery.ts +++ b/src/discovery/Discovery.ts @@ -1,15 +1,15 @@ import type { DB, DBTransaction } from '@matrixai/db'; import type { PromiseCancellable } from '@matrixai/async-cancellable'; import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts'; -import type { NodeId } from '../nodes/types'; -import type NodeManager from '../nodes/NodeManager'; -import type GestaltGraph from '../gestalts/GestaltGraph'; +import type { NodeId } from '../nodes/types.js'; +import type NodeManager from '../nodes/NodeManager.js'; +import type GestaltGraph from '../gestalts/GestaltGraph.js'; import type { GestaltId, GestaltIdEncoded, GestaltNodeInfo, -} from '../gestalts/types'; -import type IdentitiesManager from '../identities/IdentitiesManager'; +} from '../gestalts/types.js'; +import type IdentitiesManager from '../identities/IdentitiesManager.js'; import type { IdentityData, IdentityId, @@ -18,29 +18,29 @@ import type { ProviderIdentityClaimId, ProviderIdentityId, ProviderPaginationToken, -} from '../identities/types'; -import type KeyRing from '../keys/KeyRing'; -import type { ClaimIdEncoded, SignedClaim } from '../claims/types'; -import type TaskManager from '../tasks/TaskManager'; -import type { Task, TaskHandler, TaskHandlerId } from '../tasks/types'; -import type { ClaimLinkIdentity, ClaimLinkNode } from '../claims/payloads'; -import type { DiscoveryQueueInfo } from './types'; +} from '../identities/types.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type { ClaimIdEncoded, SignedClaim } from '../claims/types.js'; +import type TaskManager from '../tasks/TaskManager.js'; +import type { Task, TaskHandler, TaskHandlerId } from '../tasks/types.js'; +import type { + ClaimLinkIdentity, + ClaimLinkNode, +} from '../claims/payloads/index.js'; +import type { DiscoveryQueueInfo } from './types.js'; import Logger from '@matrixai/logger'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; -import { context, timedCancellable } from '@matrixai/contexts/dist/decorators'; -import * as discoveryErrors from './errors'; -import * as discoveryEvents from './events'; -import * as tasksErrors from '../tasks/errors'; -import * as tasksUtils from '../tasks/utils'; -import * as gestaltsUtils from '../gestalts/utils'; -import * as nodesUtils from '../nodes/utils'; -import * as keysUtils from '../keys/utils'; -import { never } from '../utils'; -import Token from '../tokens/Token'; -import { decodeClaimId } from '../ids'; +import { createDestroyStartStop } from '@matrixai/async-init'; +import { decorators } from '@matrixai/contexts'; +import * as discoveryErrors from './errors.js'; +import * as discoveryEvents from './events.js'; +import * as tasksErrors from '../tasks/errors.js'; +import * as tasksUtils from '../tasks/utils.js'; +import * as gestaltsUtils from '../gestalts/utils.js'; +import * as nodesUtils from '../nodes/utils.js'; +import * as keysUtils from '../keys/utils/index.js'; +import { never } from '../utils/index.js'; +import Token from '../tokens/Token.js'; +import { decodeClaimId } from '../ids/index.js'; /** * This is the reason used to cancel duplicate tasks for vertices @@ -57,8 +57,8 @@ const discoveryStoppingTaskReason = Symbol('discovery stopping task reason'); */ const discoveryDestroyedTaskReason = Symbol('discovery destroyed task reason'); -interface Discovery extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface Discovery extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new discoveryErrors.ErrorDiscoveryRunning(), new discoveryErrors.ErrorDiscoveryDestroyed(), { @@ -332,7 +332,7 @@ class Discovery { /** * Queues a node for discovery. Internally calls `pushKeyToDiscoveryQueue`. */ - @ready(new discoveryErrors.ErrorDiscoveryNotRunning()) + @createDestroyStartStop.ready(new discoveryErrors.ErrorDiscoveryNotRunning()) public async queueDiscoveryByNode( nodeId: NodeId, lastProcessedCutoffTime?: number, @@ -348,7 +348,7 @@ class Discovery { * Queues an identity for discovery. Internally calls * `pushKeyToDiscoveryQueue`. */ - @ready(new discoveryErrors.ErrorDiscoveryNotRunning()) + @createDestroyStartStop.ready(new discoveryErrors.ErrorDiscoveryNotRunning()) public async queueDiscoveryByIdentity( providerId: ProviderId, identityId: IdentityId, @@ -364,7 +364,7 @@ class Discovery { /** * This returns the discovery queue */ - @ready(new discoveryErrors.ErrorDiscoveryNotRunning()) + @createDestroyStartStop.ready(new discoveryErrors.ErrorDiscoveryNotRunning()) public async *getDiscoveryQueue( tran?: DBTransaction, ): AsyncGenerator { @@ -397,11 +397,11 @@ class Discovery { lastProcessedCutoffTime?: number, ctx?: Partial, ): PromiseCancellable; - @timedCancellable(true) + @decorators.timedCancellable(true) protected async processVertex( vertex: GestaltIdEncoded, lastProcessedCutoffTime: number | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { this.logger.debug(`Processing vertex: ${vertex}`); const vertexId = gestaltsUtils.decodeGestaltId(vertex); @@ -882,11 +882,11 @@ class Discovery { identityId: IdentityId, ctx: Partial, ): Promise; - @timedCancellable(true, 20000) + @decorators.timedCancellable(true, 20000) protected async getIdentityInfo( providerId: ProviderId, identityId: IdentityId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { const provider = this.identitiesManager.getProvider(providerId); // If we don't have this provider, no identity info to find @@ -1039,11 +1039,11 @@ class Discovery { tran?: DBTransaction, ctx?: Partial, ): Promise; - @timedCancellable(true) + @decorators.timedCancellable(true) public async checkRediscovery( lastProcessedCutoffTime: number, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => diff --git a/src/discovery/errors.ts b/src/discovery/errors.ts index 3fa021a161..be1ac4e2dc 100644 --- a/src/discovery/errors.ts +++ b/src/discovery/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorDiscovery extends ErrorPolykey {} diff --git a/src/discovery/events.ts b/src/discovery/events.ts index 204f454053..3c75728ff5 100644 --- a/src/discovery/events.ts +++ b/src/discovery/events.ts @@ -1,5 +1,5 @@ -import type { VertexEventIdentifier, VertexEventError } from './types'; -import EventPolykey from '../EventPolykey'; +import type { VertexEventIdentifier, VertexEventError } from './types.js'; +import EventPolykey from '../EventPolykey.js'; abstract class EventDiscovery extends EventPolykey {} diff --git a/src/discovery/index.ts b/src/discovery/index.ts index 62cb4914d7..bdcd56b922 100644 --- a/src/discovery/index.ts +++ b/src/discovery/index.ts @@ -1,4 +1,4 @@ -export { default as Discovery } from './Discovery'; -export * as errors from './errors'; -export * as events from './events'; -export type * as types from './types'; +export { default as Discovery } from './Discovery.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; +export type * as types from './types.js'; diff --git a/src/discovery/types.ts b/src/discovery/types.ts index b7c56d6c31..6493c1c640 100644 --- a/src/discovery/types.ts +++ b/src/discovery/types.ts @@ -1,6 +1,6 @@ -import type { GestaltIdEncoded } from '../ids'; -import type { TaskIdEncoded } from '../ids'; -import type { TaskParameters, TaskStatus } from '../tasks/types'; +import type { GestaltIdEncoded } from '../ids/index.js'; +import type { TaskIdEncoded } from '../ids/index.js'; +import type { TaskParameters, TaskStatus } from '../tasks/types.js'; type VertexEventIdentifier = { vertex: GestaltIdEncoded; diff --git a/src/errors.ts b/src/errors.ts index 0b8f663ef5..408f450e9d 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from './ErrorPolykey'; -import sysexits from './utils/sysexits'; +import ErrorPolykey from './ErrorPolykey.js'; +import sysexits from './utils/sysexits.js'; class ErrorPolykeyUnimplemented extends ErrorPolykey { static description = 'This is an unimplemented functionality'; @@ -78,25 +78,25 @@ export { * reference all Polykey errors. * This is used by RPC to serialize errors from agent to client. */ -export * from './audit/errors'; -export * from './sessions/errors'; -export * from './keys/errors'; -export * from './vaults/errors'; -export * from './git/errors'; -export * from './discovery/errors'; -export * from './gestalts/errors'; -export * from './identities/errors'; -export * from './client/errors'; -export * from './network/errors'; -export * from './nodes/errors'; -export * from './claims/errors'; -export * from './sigchain/errors'; -export * from './bootstrap/errors'; -export * from './notifications/errors'; -export * from './schema/errors'; -export * from './status/errors'; -export * from './tasks/errors'; -export * from './tokens/errors'; -export * from './validation/errors'; -export * from './utils/errors'; -export * from './workers/errors'; +export * from './audit/errors.js'; +export * from './sessions/errors.js'; +export * from './keys/errors.js'; +export * from './vaults/errors.js'; +export * from './git/errors.js'; +export * from './discovery/errors.js'; +export * from './gestalts/errors.js'; +export * from './identities/errors.js'; +export * from './client/errors.js'; +export * from './network/errors.js'; +export * from './nodes/errors.js'; +export * from './claims/errors.js'; +export * from './sigchain/errors.js'; +export * from './bootstrap/errors.js'; +export * from './notifications/errors.js'; +export * from './schema/errors.js'; +export * from './status/errors.js'; +export * from './tasks/errors.js'; +export * from './tokens/errors.js'; +export * from './validation/errors.js'; +export * from './utils/errors.js'; +export * from './workers/errors.js'; diff --git a/src/events.ts b/src/events.ts index 9d8dbf1ae6..ffb694f941 100644 --- a/src/events.ts +++ b/src/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from './EventPolykey'; +import EventPolykey from './EventPolykey.js'; abstract class EventPolykeyAgent extends EventPolykey {} @@ -50,16 +50,16 @@ export { * This ensures that we have one place to construct and * reference all Polykey events. */ -export * from './acl/events'; -export * from './discovery/events'; -export * from './sessions/events'; -export * from './keys/events'; -export * from './vaults/events'; -export * from './gestalts/events'; -export * from './identities/events'; -export * from './nodes/events'; -export * from './sigchain/events'; -export * from './notifications/events'; -export * from './schema/events'; -export * from './status/events'; -export * from './tasks/events'; +export * from './acl/events.js'; +export * from './discovery/events.js'; +export * from './sessions/events.js'; +export * from './keys/events.js'; +export * from './vaults/events.js'; +export * from './gestalts/events.js'; +export * from './identities/events.js'; +export * from './nodes/events.js'; +export * from './sigchain/events.js'; +export * from './notifications/events.js'; +export * from './schema/events.js'; +export * from './status/events.js'; +export * from './tasks/events.js'; diff --git a/src/gestalts/GestaltGraph.ts b/src/gestalts/GestaltGraph.ts index efe1298766..7ad6f066df 100644 --- a/src/gestalts/GestaltGraph.ts +++ b/src/gestalts/GestaltGraph.ts @@ -14,25 +14,22 @@ import type { GestaltLinkIdentity, GestaltId, GestaltIdEncoded, -} from './types'; -import type { ClaimId, NodeId, ProviderIdentityId } from '../ids/types'; -import type ACL from '../acl/ACL'; -import type { GestaltLinkJSON } from './types'; +} from './types.js'; +import type { ClaimId, NodeId, ProviderIdentityId } from '../ids/types.js'; +import type ACL from '../acl/ACL.js'; +import type { GestaltLinkJSON } from './types.js'; import Logger from '@matrixai/logger'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { IdInternal } from '@matrixai/id'; -import * as gestaltsUtils from './utils'; -import * as gestaltsErrors from './errors'; -import * as gestaltsEvents from './events'; -import * as aclUtils from '../acl/utils'; -import { never } from '../utils'; -import * as utils from '../utils'; - -interface GestaltGraph extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +import * as gestaltsUtils from './utils.js'; +import * as gestaltsErrors from './errors.js'; +import * as gestaltsEvents from './events.js'; +import * as aclUtils from '../acl/utils.js'; +import { never } from '../utils/index.js'; +import * as utils from '../utils/index.js'; + +interface GestaltGraph extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new gestaltsErrors.ErrorGestaltsGraphRunning(), new gestaltsErrors.ErrorGestaltsGraphDestroyed(), { @@ -167,7 +164,9 @@ class GestaltGraph { * If this is a new node, it will set a new node pointer * to a new gestalt permission in the acl */ - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async setNode( nodeInfo: GestaltNodeInfo, tran?: DBTransaction, @@ -200,7 +199,9 @@ class GestaltGraph { return gestaltNodeId; } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async setIdentity( identityInfo: GestaltIdentityInfo, tran?: DBTransaction, @@ -233,7 +234,9 @@ class GestaltGraph { return gestaltIdentityId; } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async unsetNode(nodeId: NodeId, tran?: DBTransaction): Promise { if (tran == null) { return this.db.withTransactionF((tran) => this.unsetNode(nodeId, tran)); @@ -264,7 +267,9 @@ class GestaltGraph { await this.acl.unsetNodePerm(nodeId, tran); } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async unsetIdentity( providerIdentityId: ProviderIdentityId, tran?: DBTransaction, @@ -306,7 +311,9 @@ class GestaltGraph { } // Calls one of `setNode` or `setIdentity` - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public setVertex( gestaltInfo: GestaltInfo, tran?: DBTransaction, @@ -323,7 +330,9 @@ class GestaltGraph { } // Calls one of `unsetNode` or `unsetIdentity` - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public unsetVertex( gestaltId: GestaltId, tran?: DBTransaction, @@ -342,7 +351,9 @@ class GestaltGraph { /** * Updates the last processed time in the database for the given vertex */ - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async setVertexProcessedTime( vertex: GestaltId, processedTime: number, @@ -376,7 +387,9 @@ class GestaltGraph { /** * Removes the last processed time for a vertex */ - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async unsetVertexProcessedTime( vertex: GestaltId, tran?: DBTransaction, @@ -408,7 +421,9 @@ class GestaltGraph { /** * Gets the last processed time for a vertex */ - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getVertexProcessedTime( vertex: GestaltId, tran?: DBTransaction, @@ -429,7 +444,9 @@ class GestaltGraph { /** * Gets the last processed time for a vertex */ - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async *getVertexProcessedTimes( { order = 'asc', @@ -478,7 +495,9 @@ class GestaltGraph { /** * Updates the newest `ClaimId` for a node if it's newer than the current id stored */ - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async setClaimIdNewest( nodeId: NodeId, claimId: ClaimId, @@ -510,7 +529,9 @@ class GestaltGraph { ); } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getClaimIdNewest( nodeId: NodeId, tran?: DBTransaction, @@ -536,7 +557,9 @@ class GestaltGraph { * It does not however verify the signatures. * Verifying signatures should be done before linking the nodes in the GG */ - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async linkNodeAndNode( nodeInfo1: GestaltNodeInfo, nodeInfo2: GestaltNodeInfo, @@ -682,7 +705,9 @@ class GestaltGraph { return gestaltLinkIdNew; } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async linkNodeAndIdentity( nodeInfo: GestaltNodeInfo, identityInfo: GestaltIdentityInfo, @@ -845,7 +870,9 @@ class GestaltGraph { link: ['identity', Omit], tran?: DBTransaction, ): Promise; - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public linkVertexAndVertex( gestaltInfo1: GestaltInfo, gestaltInfo2: GestaltInfo, @@ -880,7 +907,9 @@ class GestaltGraph { } } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async unlinkNodeAndNode( nodeId1: NodeId, nodeId2: NodeId, @@ -950,7 +979,9 @@ class GestaltGraph { await this.acl.setNodesPerm(nodeIds, perm, tran); } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async unlinkNodeAndIdentity( nodeId: NodeId, providerIdentityId: ProviderIdentityId, @@ -1046,7 +1077,9 @@ class GestaltGraph { gestaltId2: ['node', NodeId], tran?: DBTransaction, ): Promise; - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public unlinkVertexAndVertex( gestaltId1: GestaltId, gestaltId2: GestaltId, @@ -1075,7 +1108,9 @@ class GestaltGraph { } } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getGestaltActions( gestaltId: GestaltId, tran?: DBTransaction, @@ -1114,7 +1149,9 @@ class GestaltGraph { } } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async setGestaltAction( gestaltId: GestaltId, action: GestaltAction, @@ -1153,7 +1190,9 @@ class GestaltGraph { } } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async unsetGestaltAction( gestaltId: GestaltId, action: GestaltAction, @@ -1195,7 +1234,9 @@ class GestaltGraph { // GETTERS - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async *getGestalts(tran?: DBTransaction): AsyncGenerator { if (tran == null) { return yield* this.db.withTransactionG((tran) => this.getGestalts(tran)); @@ -1241,7 +1282,9 @@ class GestaltGraph { } } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getGestaltByNode( nodeId: NodeId, tran?: DBTransaction, @@ -1255,7 +1298,9 @@ class GestaltGraph { return this.getGestaltByKey(nodeKey, undefined, tran); } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getGestaltByIdentity( providerIdentityId: ProviderIdentityId, tran?: DBTransaction, @@ -1272,7 +1317,9 @@ class GestaltGraph { return this.getGestaltByKey(identityKey, undefined, tran); } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getNode( nodeId: NodeId, tran?: DBTransaction, @@ -1289,7 +1336,9 @@ class GestaltGraph { return gestaltsUtils.fromGestaltNodeInfoJSON(gestaltNodeInfoJSON); } - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getIdentity( providerIdentityId: ProviderIdentityId, tran?: DBTransaction, @@ -1323,7 +1372,9 @@ class GestaltGraph { gestaltId: GestaltId, tran?: DBTransaction, ): Promise; - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getVertex( gestaltId: GestaltId, tran?: DBTransaction, @@ -1375,7 +1426,9 @@ class GestaltGraph { gestaltId2: ['identity', ProviderIdentityId], tran?: DBTransaction, ): Promise<['identity', GestaltLinkIdentity] | undefined>; - @ready(new gestaltsErrors.ErrorGestaltsGraphNotRunning()) + @createDestroyStartStop.ready( + new gestaltsErrors.ErrorGestaltsGraphNotRunning(), + ) public async getLink( gestaltId1: GestaltId, gestaltId2: GestaltId, diff --git a/src/gestalts/errors.ts b/src/gestalts/errors.ts index b43f09e25a..79e8ad00eb 100644 --- a/src/gestalts/errors.ts +++ b/src/gestalts/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorGestalts extends ErrorPolykey {} diff --git a/src/gestalts/events.ts b/src/gestalts/events.ts index 63efa30f4a..81ee49ff54 100644 --- a/src/gestalts/events.ts +++ b/src/gestalts/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventGestalts extends EventPolykey {} diff --git a/src/gestalts/index.ts b/src/gestalts/index.ts index 8444b2131b..c4fe2cfbe7 100644 --- a/src/gestalts/index.ts +++ b/src/gestalts/index.ts @@ -1,5 +1,5 @@ -export { default as GestaltGraph } from './GestaltGraph'; -export * as utils from './utils'; -export * as types from './types'; -export * as errors from './errors'; -export * as events from './events'; +export { default as GestaltGraph } from './GestaltGraph.js'; +export * as utils from './utils.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; diff --git a/src/gestalts/types.ts b/src/gestalts/types.ts index 1cfb039f24..c7f302986d 100644 --- a/src/gestalts/types.ts +++ b/src/gestalts/types.ts @@ -1,4 +1,4 @@ -import type { JSONValue, Opaque } from '../types'; +import type { JSONValue, Opaque } from '../types.js'; import type { IdentityId, ProviderId, @@ -6,10 +6,13 @@ import type { ProviderIdentityClaimId, NodeId, GestaltLinkId, -} from '../ids/types'; -import type { SignedClaim, SignedClaimJSON } from '../claims/types'; -import type { ClaimLinkIdentity, ClaimLinkNode } from '../claims/payloads'; -import type { ProviderPaginationToken } from '../identities/types'; +} from '../ids/types.js'; +import type { SignedClaim, SignedClaimJSON } from '../claims/types.js'; +import type { + ClaimLinkIdentity, + ClaimLinkNode, +} from '../claims/payloads/index.js'; +import type { ProviderPaginationToken } from '../identities/types.js'; const gestaltActions = ['notify', 'scan', 'claim'] as const; @@ -153,4 +156,4 @@ export type { GestaltIdEncoded, GestaltLinkId, GestaltLinkIdString, -} from '../ids/types'; +} from '../ids/types.js'; diff --git a/src/gestalts/utils.ts b/src/gestalts/utils.ts index ecbcaf9fb8..dcfa046e44 100644 --- a/src/gestalts/utils.ts +++ b/src/gestalts/utils.ts @@ -1,5 +1,9 @@ -import type { GestaltLinkId, NodeId, ProviderIdentityId } from '../ids/types'; -import type { TokenSignature } from '../tokens/types'; +import type { + GestaltLinkId, + NodeId, + ProviderIdentityId, +} from '../ids/types.js'; +import type { TokenSignature } from '../tokens/types.js'; import type { GestaltId, GestaltKey, @@ -8,12 +12,15 @@ import type { GestaltNodeInfoJSON, GestaltLink, GestaltLinkJSON, -} from './types'; -import type { ClaimLinkNode, ClaimLinkIdentity } from '../claims/payloads'; +} from './types.js'; +import type { + ClaimLinkNode, + ClaimLinkIdentity, +} from '../claims/payloads/index.js'; import { IdInternal } from '@matrixai/id'; -import { gestaltActions } from './types'; -import * as ids from '../ids'; -import * as validationErrors from '../validation/errors'; +import { gestaltActions } from './types.js'; +import * as ids from '../ids/index.js'; +import * as validationErrors from '../validation/errors.js'; function toGestaltKey(gestaltId: GestaltId): GestaltKey { switch (gestaltId[0]) { @@ -195,4 +202,4 @@ export { decodeGestaltNodeId, decodeGestaltIdentityId, createGestaltLinkIdGenerator, -} from '../ids'; +} from '../ids/index.js'; diff --git a/src/git/errors.ts b/src/git/errors.ts index cc8ac20416..be57e82074 100644 --- a/src/git/errors.ts +++ b/src/git/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorGit extends ErrorPolykey {} diff --git a/src/git/http.ts b/src/git/http.ts index c84371e962..52f83f68fc 100644 --- a/src/git/http.ts +++ b/src/git/http.ts @@ -4,13 +4,13 @@ import type { Reference, ObjectId, ObjectIdList, -} from './types'; +} from './types.js'; import type { EncryptedFS } from 'encryptedfs'; import type { PackObjectsResult } from 'isomorphic-git'; import { Buffer } from 'buffer'; import git from 'isomorphic-git'; -import * as gitUtils from './utils'; -import * as utils from '../utils'; +import * as gitUtils from './utils.js'; +import * as utils from '../utils/index.js'; /** * Reference discovery diff --git a/src/git/index.ts b/src/git/index.ts index 4d43235592..861285638e 100644 --- a/src/git/index.ts +++ b/src/git/index.ts @@ -1,4 +1,4 @@ -export * as http from './http'; -export * as utils from './utils'; -export * as types from './types'; -export * as errors from './errors'; +export * as http from './http.js'; +export * as utils from './utils.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; diff --git a/src/git/utils.ts b/src/git/utils.ts index b127b4cfe4..fd70a52138 100644 --- a/src/git/utils.ts +++ b/src/git/utils.ts @@ -7,13 +7,13 @@ import type { ObjectType, Reference, RequestType, -} from './types'; +} from './types.js'; import type { EncryptedFS } from 'encryptedfs'; -import path from 'path'; +import path from 'node:path'; import git from 'isomorphic-git'; -import { requestTypes } from './types'; -import * as utils from '../utils'; -import * as validationErrors from '../validation/errors'; +import { requestTypes } from './types.js'; +import * as utils from '../utils/index.js'; +import * as validationErrors from '../validation/errors.js'; // Constants // Total number of bytes per pack line minus the 4 size bytes and 1 channel byte diff --git a/src/http/index.ts b/src/http/index.ts index 7ad4b67b9b..1737171501 100644 --- a/src/http/index.ts +++ b/src/http/index.ts @@ -1 +1 @@ -export * as utils from './utils'; +export * as utils from './utils.js'; diff --git a/src/http/utils.ts b/src/http/utils.ts index a83e5dc211..0e3213ed30 100644 --- a/src/http/utils.ts +++ b/src/http/utils.ts @@ -2,7 +2,7 @@ import type tls from 'tls'; import type https from 'https'; import net from 'net'; import http from 'http'; -import * as utils from '../utils'; +import * as utils from '../utils/index.js'; function terminatingHttpServer( server: http.Server | https.Server, diff --git a/src/identities/IdentitiesManager.ts b/src/identities/IdentitiesManager.ts index 831c14d695..bbaf16c9d9 100644 --- a/src/identities/IdentitiesManager.ts +++ b/src/identities/IdentitiesManager.ts @@ -4,27 +4,25 @@ import type { ProviderTokens, ProviderToken, IdentitySignedClaim, -} from './types'; +} from './types.js'; import type { DB, DBTransaction, KeyPath, LevelPath } from '@matrixai/db'; -import type Provider from './Provider'; -import type { ClaimLinkIdentity } from '../claims/payloads'; -import type KeyRing from '../keys/KeyRing'; -import type Sigchain from '../sigchain/Sigchain'; -import type GestaltGraph from '../gestalts/GestaltGraph'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import type Provider from './Provider.js'; +import type { ClaimLinkIdentity } from '../claims/payloads/index.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type Sigchain from '../sigchain/Sigchain.js'; +import type GestaltGraph from '../gestalts/GestaltGraph.js'; +import { createDestroyStartStop } from '@matrixai/async-init'; import Logger from '@matrixai/logger'; -import * as identitiesErrors from './errors'; -import * as identitiesEvents from './events'; -import Token from '../tokens/Token'; -import * as nodesUtils from '../nodes/utils'; -import { promise } from '../utils'; -import { encodeProviderIdentityId } from '../ids'; +import * as identitiesErrors from './errors.js'; +import * as identitiesEvents from './events.js'; +import Token from '../tokens/Token.js'; +import * as nodesUtils from '../nodes/utils.js'; +import { promise } from '../utils/index.js'; +import { encodeProviderIdentityId } from '../ids/index.js'; -interface IdentitiesManager extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface IdentitiesManager + extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new identitiesErrors.ErrorIdentitiesManagerRunning(), new identitiesErrors.ErrorIdentitiesManagerDestroyed(), { @@ -121,17 +119,23 @@ class IdentitiesManager { this.logger.info(`Destroyed ${this.constructor.name}`); } - @ready(new identitiesErrors.ErrorIdentitiesManagerNotRunning()) + @createDestroyStartStop.ready( + new identitiesErrors.ErrorIdentitiesManagerNotRunning(), + ) public getProviders(): Record { return Object.fromEntries(this.providers); } - @ready(new identitiesErrors.ErrorIdentitiesManagerNotRunning()) + @createDestroyStartStop.ready( + new identitiesErrors.ErrorIdentitiesManagerNotRunning(), + ) public getProvider(pId: ProviderId): Provider | undefined { return this.providers.get(pId); } - @ready(new identitiesErrors.ErrorIdentitiesManagerNotRunning()) + @createDestroyStartStop.ready( + new identitiesErrors.ErrorIdentitiesManagerNotRunning(), + ) public registerProvider(p: Provider): void { if (this.providers.has(p.id)) { throw new identitiesErrors.ErrorProviderDuplicate(); @@ -145,12 +149,16 @@ class IdentitiesManager { this.providers.set(p.id, p); } - @ready(new identitiesErrors.ErrorIdentitiesManagerNotRunning()) + @createDestroyStartStop.ready( + new identitiesErrors.ErrorIdentitiesManagerNotRunning(), + ) public unregisterProvider(pId: ProviderId): void { this.providers.delete(pId); } - @ready(new identitiesErrors.ErrorIdentitiesManagerNotRunning()) + @createDestroyStartStop.ready( + new identitiesErrors.ErrorIdentitiesManagerNotRunning(), + ) public async getTokens( providerId: ProviderId, tran?: DBTransaction, @@ -171,7 +179,9 @@ class IdentitiesManager { return providerTokens; } - @ready(new identitiesErrors.ErrorIdentitiesManagerNotRunning()) + @createDestroyStartStop.ready( + new identitiesErrors.ErrorIdentitiesManagerNotRunning(), + ) public async getToken( providerId: ProviderId, identityId: IdentityId, @@ -193,7 +203,9 @@ class IdentitiesManager { return providerTokens[identityId]; } - @ready(new identitiesErrors.ErrorIdentitiesManagerNotRunning()) + @createDestroyStartStop.ready( + new identitiesErrors.ErrorIdentitiesManagerNotRunning(), + ) public async putToken( providerId: ProviderId, identityId: IdentityId, @@ -222,7 +234,9 @@ class IdentitiesManager { await tran.put(providerIdPath, providerTokens); } - @ready(new identitiesErrors.ErrorIdentitiesManagerNotRunning()) + @createDestroyStartStop.ready( + new identitiesErrors.ErrorIdentitiesManagerNotRunning(), + ) public async delToken( providerId: ProviderId, identityId: IdentityId, diff --git a/src/identities/Provider.ts b/src/identities/Provider.ts index be0dbec6ff..e7a733fb45 100644 --- a/src/identities/Provider.ts +++ b/src/identities/Provider.ts @@ -8,12 +8,12 @@ import type { ProviderAuthenticateRequest, ProviderIdentityClaimId, ProviderPaginationToken, -} from './types'; -import type { SignedClaim } from '../claims/types'; -import type { ClaimLinkIdentity } from '../claims/payloads/claimLinkIdentity'; -import * as identitiesErrors from './errors'; -import * as tokensSchema from '../tokens/schemas'; -import * as claimLinkIdentity from '../claims/payloads/claimLinkIdentity'; +} from './types.js'; +import type { SignedClaim } from '../claims/types.js'; +import type { ClaimLinkIdentity } from '../claims/payloads/claimLinkIdentity.js'; +import * as identitiesErrors from './errors.js'; +import * as tokensSchema from '../tokens/schemas/index.js'; +import * as claimLinkIdentity from '../claims/payloads/claimLinkIdentity.js'; type GetTokens = () => Promise; type GetToken = (identityId: IdentityId) => Promise; diff --git a/src/identities/errors.ts b/src/identities/errors.ts index 3a2d8ff647..a32dd79b2e 100644 --- a/src/identities/errors.ts +++ b/src/identities/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorIdentities extends ErrorPolykey {} diff --git a/src/identities/events.ts b/src/identities/events.ts index b5068bacbf..049aee8138 100644 --- a/src/identities/events.ts +++ b/src/identities/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventIdentitiesManager extends EventPolykey {} diff --git a/src/identities/index.ts b/src/identities/index.ts index 1cdbc8d265..84c7e9babb 100644 --- a/src/identities/index.ts +++ b/src/identities/index.ts @@ -1,7 +1,7 @@ -export { default as IdentitiesManager } from './IdentitiesManager'; -export { default as Provider } from './Provider'; -export * as utils from './utils'; -export * as types from './types'; -export * as errors from './errors'; -export * as events from './events'; -export * as providers from './providers'; +export { default as IdentitiesManager } from './IdentitiesManager.js'; +export { default as Provider } from './Provider.js'; +export * as utils from './utils.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; +export * as providers from './providers/index.js'; diff --git a/src/identities/providers/github/GitHubProvider.ts b/src/identities/providers/github/GitHubProvider.ts index c40e87fd2c..ad018856a1 100644 --- a/src/identities/providers/github/GitHubProvider.ts +++ b/src/identities/providers/github/GitHubProvider.ts @@ -7,17 +7,17 @@ import type { ProviderIdentityClaimId, ProviderAuthenticateRequest, ProviderPaginationToken, -} from '../../types'; -import type { SignedClaim } from '../../../claims/types'; -import type { ClaimLinkIdentity } from '../../../claims/payloads/claimLinkIdentity'; +} from '../../types.js'; +import type { SignedClaim } from '../../../claims/types.js'; +import type { ClaimLinkIdentity } from '../../../claims/payloads/claimLinkIdentity.js'; import { fetch, Request, Headers } from 'cross-fetch'; import * as cheerio from 'cheerio'; import Logger from '@matrixai/logger'; -import Provider from '../../Provider'; -import * as identitiesErrors from '../../errors'; -import * as identitiesUtils from '../../utils'; -import * as tokensUtils from '../../../tokens/utils'; -import * as utils from '../../../utils'; +import Provider from '../../Provider.js'; +import * as identitiesErrors from '../../errors.js'; +import * as identitiesUtils from '../../utils.js'; +import * as tokensUtils from '../../../tokens/utils.js'; +import * as utils from '../../../utils/index.js'; class GitHubProvider extends Provider { public readonly id = 'github.com' as ProviderId; diff --git a/src/identities/providers/github/index.ts b/src/identities/providers/github/index.ts index fd294f6786..e9a08eab71 100644 --- a/src/identities/providers/github/index.ts +++ b/src/identities/providers/github/index.ts @@ -1 +1 @@ -export { default } from './GitHubProvider'; +export { default } from './GitHubProvider.js'; diff --git a/src/identities/providers/index.ts b/src/identities/providers/index.ts index a47d3e5a9a..9bd8f92ec6 100644 --- a/src/identities/providers/index.ts +++ b/src/identities/providers/index.ts @@ -1 +1 @@ -export { default as GithubProvider } from './github'; +export { default as GithubProvider } from './github/index.js'; diff --git a/src/identities/types.ts b/src/identities/types.ts index f96133f7b8..f2390d49c0 100644 --- a/src/identities/types.ts +++ b/src/identities/types.ts @@ -1,11 +1,11 @@ -import type { POJO, Opaque } from '../types'; +import type { POJO, Opaque } from '../types.js'; import type { ProviderId, IdentityId, ProviderIdentityClaimId, -} from '../ids/types'; -import type { SignedClaim } from '../claims/types'; -import type { ClaimLinkIdentity } from '../claims/payloads'; +} from '../ids/types.js'; +import type { SignedClaim } from '../claims/types.js'; +import type { ClaimLinkIdentity } from '../claims/payloads/index.js'; /** * Identity data contains key details about the @@ -77,4 +77,4 @@ export type { ProviderIdentityId, ProviderIdentityIdEncoded, ProviderIdentityClaimId, -} from '../ids/types'; +} from '../ids/types.js'; diff --git a/src/identities/utils.ts b/src/identities/utils.ts index 6a18fccab6..7224279cc8 100644 --- a/src/identities/utils.ts +++ b/src/identities/utils.ts @@ -1,6 +1,6 @@ import type childProcess from 'child_process'; -import type { IdentityData } from './types'; -import os from 'os'; +import type { IdentityData } from './types.js'; +import os from 'node:os'; import process from 'process'; import spawn from 'cross-spawn'; import { Searcher } from 'fast-fuzzy'; @@ -96,4 +96,7 @@ function matchIdentityData( export { browser, matchIdentityData }; -export { encodeProviderIdentityId, decodeProviderIdentityId } from '../ids'; +export { + encodeProviderIdentityId, + decodeProviderIdentityId, +} from '../ids/index.js'; diff --git a/src/ids/index.ts b/src/ids/index.ts index 26c21bd0d8..869eb6ffd8 100644 --- a/src/ids/index.ts +++ b/src/ids/index.ts @@ -22,10 +22,10 @@ import type { NotificationIdEncoded, AuditEventId, AuditEventIdEncoded, -} from './types'; +} from './types.js'; import { IdInternal, IdSortable, IdRandom } from '@matrixai/id'; -import * as keysUtilsRandom from '../keys/utils/random'; -import * as validationErrors from '../validation/errors'; +import * as keysUtilsRandom from '../keys/utils/random.js'; +import * as validationErrors from '../validation/errors.js'; /** * Generates an auditId from an epoch timestamp. @@ -605,4 +605,4 @@ export { generateNotificationIdFromTimestamp, }; -export * from './types'; +export * from './types.js'; diff --git a/src/ids/types.ts b/src/ids/types.ts index 394e7505cb..7b95a2138f 100644 --- a/src/ids/types.ts +++ b/src/ids/types.ts @@ -1,5 +1,5 @@ import type { Id } from '@matrixai/id'; -import type { Opaque } from '../types'; +import type { Opaque } from '../types.js'; // ACL diff --git a/src/index.ts b/src/index.ts index c888e08f25..643a1c3ddc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,37 +1,38 @@ -export { default as PolykeyAgent } from './PolykeyAgent'; -export { default as PolykeyClient } from './PolykeyClient'; -export { default as EventPolykey } from './EventPolykey'; -export { default as ErrorPolykey } from './ErrorPolykey'; -export { default as config } from './config'; -export * as utils from './utils'; -export * as events from './events'; -export * as errors from './errors'; -export * from './types'; +export { default as PolykeyAgent } from './PolykeyAgent.js'; +export { default as PolykeyClient } from './PolykeyClient.js'; +export { default as EventPolykey } from './EventPolykey.js'; +export { default as ErrorPolykey } from './ErrorPolykey.js'; +export { default as config } from './config.js'; +export * as utils from './utils/index.js'; +export * as events from './events.js'; +export * as errors from './errors.js'; +export * from './types.js'; // Subdomains for Polykey // Users should prefer importing them directly to avoid importing the entire // kitchen sink here -export * as acl from './acl'; -export * as bootstrap from './bootstrap'; -export * as claims from './claims'; -export * as client from './client'; -export * as discovery from './discovery'; -export * as gestalts from './gestalts'; -export * as git from './git'; -export * as http from './http'; -export * as identities from './identities'; -export * as ids from './ids'; -export * as keys from './keys'; -export * as network from './network'; -export * as nodes from './nodes'; -export * as notifications from './notifications'; -export * as schema from './schema'; -export * as sessions from './sessions'; -export * as sigchain from './sigchain'; -export * as status from './status'; -export * as tasks from './tasks'; -export * as tokens from './tokens'; -export * as validation from './validation'; -export * as vaults from './vaults'; -export * as workers from './workers'; +export * as acl from './acl/index.js'; +export * as audit from './audit/index.js'; +export * as bootstrap from './bootstrap/index.js'; +export * as claims from './claims/index.js'; +export * as client from './client/index.js'; +export * as discovery from './discovery/index.js'; +export * as gestalts from './gestalts/index.js'; +export * as git from './git/index.js'; +export * as http from './http/index.js'; +export * as identities from './identities/index.js'; +export * as ids from './ids/index.js'; +export * as keys from './keys/index.js'; +export * as network from './network/index.js'; +export * as nodes from './nodes/index.js'; +export * as notifications from './notifications/index.js'; +export * as schema from './schema/index.js'; +export * as sessions from './sessions/index.js'; +export * as sigchain from './sigchain/index.js'; +export * as status from './status/index.js'; +export * as tasks from './tasks/index.js'; +export * as tokens from './tokens/index.js'; +export * as validation from './validation/index.js'; +export * as vaults from './vaults/index.js'; +export * as workers from './workers/index.js'; diff --git a/src/keys/CertManager.ts b/src/keys/CertManager.ts index 0baee4a194..07a3a60a27 100644 --- a/src/keys/CertManager.ts +++ b/src/keys/CertManager.ts @@ -8,24 +8,22 @@ import type { KeyPair, RecoveryCode, CertificatePEMChain, -} from './types'; -import type KeyRing from './KeyRing'; -import type TaskManager from '../tasks/TaskManager'; -import type { CertId, TaskHandlerId, TaskId } from '../ids/types'; -import type { Task, TaskHandler } from '../tasks/types'; -import type { PolykeyWorkerManagerInterface } from '../workers/types'; +} from './types.js'; +import type KeyRing from './KeyRing.js'; +import type TaskManager from '../tasks/TaskManager.js'; +import type { CertId, TaskHandlerId, TaskId } from '../ids/types.js'; +import type { Task, TaskHandler } from '../tasks/types.js'; +import type { PolykeyWorkerManager } from '../workers/types.js'; import Logger from '@matrixai/logger'; import { IdInternal } from '@matrixai/id'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { Lock } from '@matrixai/async-locks'; -import * as keysUtils from './utils'; -import * as keysErrors from './errors'; -import * as keysEvents from './events'; -import * as ids from '../ids'; -import config from '../config'; +import * as keysUtils from './utils/index.js'; +import * as keysErrors from './errors.js'; +import * as keysEvents from './events.js'; +import * as ids from '../ids/index.js'; +import * as workerUtils from '../workers/utils.js'; +import config from '../config.js'; /** * This signal reason indicates we want to stop the renewal @@ -34,8 +32,8 @@ const abortRenewCertTaskReason = Symbol( 'abort automatic certificate task renewal', ); -interface CertManager extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface CertManager extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new keysErrors.ErrorCertManagerRunning(), new keysErrors.ErrorCertManagerDestroyed(), { @@ -80,7 +78,7 @@ class CertManager { taskManager: TaskManager; certDuration?: number; certRenewLeadTime?: number; - workerManager?: PolykeyWorkerManagerInterface; + workerManager?: PolykeyWorkerManager; logger?: Logger; subjectAttrsExtra?: Array<{ [key: string]: Array }>; issuerAttrsExtra?: Array<{ [key: string]: Array }>; @@ -118,7 +116,7 @@ class CertManager { protected db: DB; protected keyRing: KeyRing; protected taskManager: TaskManager; - protected workerManager?: PolykeyWorkerManagerInterface; + protected workerManager?: PolykeyWorkerManager; protected generateCertId: () => CertId; protected dbPath: LevelPath = [this.constructor.name]; /** @@ -160,7 +158,7 @@ class CertManager { taskManager: TaskManager; certDuration: number; certRenewLeadTime: number; - workerManager?: PolykeyWorkerManagerInterface; + workerManager?: PolykeyWorkerManager; logger: Logger; }) { this.logger = logger; @@ -172,7 +170,7 @@ class CertManager { this.workerManager = workerManager; } - public setWorkerManager(workerManager: PolykeyWorkerManagerInterface) { + public setWorkerManager(workerManager: PolykeyWorkerManager) { this.workerManager = workerManager; } @@ -229,7 +227,11 @@ class CertManager { * Start background tasks. * This is idempotent. */ - @ready(new keysErrors.ErrorCertManagerNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new keysErrors.ErrorCertManagerNotRunning(), + false, + ['starting'], + ) public async startTasks(now: Date = new Date()): Promise { this.tasksRunning = true; await this.setupRenewCurrentCertTask(now); @@ -265,7 +267,11 @@ class CertManager { this.tasksRunning = false; } - @ready(new keysErrors.ErrorCertManagerNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new keysErrors.ErrorCertManagerNotRunning(), + false, + ['starting'], + ) public async getLastCertId( tran?: DBTransaction, ): Promise { @@ -280,7 +286,11 @@ class CertManager { /** * Get a certificate according to the `CertID` */ - @ready(new keysErrors.ErrorCertManagerNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new keysErrors.ErrorCertManagerNotRunning(), + false, + ['starting'], + ) public async getCert( certId: CertId, tran?: DBTransaction, @@ -298,7 +308,11 @@ class CertManager { /** * Get `Certificate` from leaf to root */ - @ready(new keysErrors.ErrorCertManagerNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new keysErrors.ErrorCertManagerNotRunning(), + false, + ['starting'], + ) public async *getCerts(tran?: DBTransaction): AsyncGenerator { if (tran == null) { return yield* this.db.withTransactionG((tran) => this.getCerts(tran)); @@ -314,7 +328,7 @@ class CertManager { /** * Gets an array of `Certificate` in order of leaf to root */ - @ready(new keysErrors.ErrorCertManagerNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorCertManagerNotRunning()) public async getCertsChain( tran?: DBTransaction, ): Promise> { @@ -328,7 +342,7 @@ class CertManager { /** * Get `CertificatePEM` from leaf to root */ - @ready(new keysErrors.ErrorCertManagerNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorCertManagerNotRunning()) public async *getCertPEMs( tran?: DBTransaction, ): AsyncGenerator { @@ -340,7 +354,7 @@ class CertManager { /** * Gets an array of `CertificatePEM` in order of leaf to root */ - @ready(new keysErrors.ErrorCertManagerNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorCertManagerNotRunning()) public async getCertPEMsChain( tran?: DBTransaction, ): Promise> { @@ -354,7 +368,7 @@ class CertManager { /** * Gets a concatenated `CertificatePEM` ordered from leaf to root */ - @ready(new keysErrors.ErrorCertManagerNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorCertManagerNotRunning()) public async getCertPEMsChainPEM( tran?: DBTransaction, ): Promise { @@ -368,7 +382,11 @@ class CertManager { /** * Get the current (leaf) certificate */ - @ready(new keysErrors.ErrorCertManagerNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new keysErrors.ErrorCertManagerNotRunning(), + false, + ['starting'], + ) public async getCurrentCert(tran?: DBTransaction): Promise { let cert: Certificate; for await (const cert_ of this.getCerts(tran)) { @@ -381,7 +399,7 @@ class CertManager { /** * Get the current (leaf) certificate in PEM */ - @ready(new keysErrors.ErrorCertManagerNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorCertManagerNotRunning()) public async getCurrentCertPEM( tran?: DBTransaction, ): Promise { @@ -404,7 +422,7 @@ class CertManager { * It will reference the same timestamp that was used to generate the new * certificate. */ - @ready(new keysErrors.ErrorCertManagerNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorCertManagerNotRunning()) public async renewCertWithNewKeyPair( password: string, duration: number = this.certDuration, @@ -486,7 +504,11 @@ class CertManager { * It will reference the same timestamp that was used to generate the new * certificate. */ - @ready(new keysErrors.ErrorCertManagerNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new keysErrors.ErrorCertManagerNotRunning(), + false, + ['starting'], + ) public async renewCertWithCurrentKeyPair( duration: number = this.certDuration, now: Date = new Date(), @@ -547,7 +569,7 @@ class CertManager { * It will reference the same timestamp that was used to generate the new * certificate. */ - @ready(new keysErrors.ErrorCertManagerNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorCertManagerNotRunning()) public async resetCertWithNewKeyPair( password: string, duration: number = this.certDuration, @@ -620,7 +642,7 @@ class CertManager { * It will reference the same timestamp that was used to generate the new * certificate. */ - @ready(new keysErrors.ErrorCertManagerNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorCertManagerNotRunning()) public async resetCertWithCurrentKeyPair( duration: number = this.certDuration, now: Date = new Date(), @@ -757,7 +779,7 @@ class CertManager { } // Only if the task does not already exist, do we setup a new task if (task == null) { - task = await this.taskManager.scheduleTask( + const taskNew = await this.taskManager.scheduleTask( { handlerId: this.renewCurrentCertHandlerId, delay, @@ -766,7 +788,8 @@ class CertManager { }, tran, ); - this.renewCurrentCertTaskId = task.id; + this.renewCurrentCertTaskId = taskNew.id; + task = taskNew; } }); } @@ -801,21 +824,34 @@ class CertManager { now, }); } else { - cert = await this.workerManager.call(async (w) => { - const result = await w.generateCertificate({ - certId: this.generateCertId().buffer, - subjectKeyPair: { - publicKey: subjectKeyPair.publicKey.buffer, - privateKey: subjectKeyPair.privateKey.buffer, + const certId = this.generateCertId(); + const certIdAB = workerUtils.toArrayBuffer(certId.toBuffer()); + const publicKeyAB = workerUtils.toArrayBuffer( + Buffer.from(subjectKeyPair.publicKey), + ); + const privateKeyAB = workerUtils.toArrayBuffer( + Buffer.from(subjectKeyPair.privateKey), + ); + const issuerPrivateKeyAB = workerUtils.toArrayBuffer( + Buffer.from(issuerPrivateKey), + ); + const { data: certAB } = + await this.workerManager.methods.generateCertificate( + { + certId: certIdAB, + subjectKeyPair: { + publicKey: publicKeyAB, + privateKey: privateKeyAB, + }, + issuerPrivateKey: issuerPrivateKeyAB, + duration, + subjectAttrsExtra, + issuerAttrsExtra, + now, }, - issuerPrivateKey: issuerPrivateKey.buffer, - duration, - subjectAttrsExtra, - issuerAttrsExtra, - now, - }); - return keysUtils.certFromASN1(Buffer.from(result) as CertificateASN1)!; - }); + [certIdAB, publicKeyAB, privateKeyAB, issuerPrivateKeyAB], + ); + cert = keysUtils.certFromASN1(Buffer.from(certAB) as CertificateASN1)!; } return cert; } diff --git a/src/keys/KeyRing.ts b/src/keys/KeyRing.ts index 5b9bcd27fd..0df7d45b3e 100644 --- a/src/keys/KeyRing.ts +++ b/src/keys/KeyRing.ts @@ -12,24 +12,23 @@ import type { RecoveryCodeLocked, PasswordOpsLimit, PasswordMemLimit, -} from './types'; -import type { NodeId } from '../ids/types'; -import type { PolykeyWorkerManagerInterface } from '../workers/types'; -import type { FileSystem, ObjectEmpty } from '../types'; -import path from 'path'; +} from './types.js'; +import type { NodeId } from '../ids/types.js'; +import type { PolykeyWorkerManager } from '../workers/types.js'; +import type { FileSystem, ObjectEmpty } from '../types.js'; +import path from 'node:path'; import Logger from '@matrixai/logger'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { Lock } from '@matrixai/async-locks'; -import * as keysUtils from './utils'; -import * as keysErrors from './errors'; -import * as keysEvents from './events'; -import { bufferLock, bufferUnlock } from './utils/memory'; - -interface KeyRing extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +import * as keysUtils from './utils/index.js'; +import * as keysErrors from './errors.js'; +import * as keysEvents from './events.js'; +import { bufferLock, bufferUnlock } from './utils/memory.js'; +import * as utils from '../utils/index.js'; +import * as workersUtils from '../workers/utils.js'; + +interface KeyRing extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new keysErrors.ErrorKeyRingRunning(), new keysErrors.ErrorKeyRingDestroyed(), { @@ -48,7 +47,7 @@ class KeyRing { passwordMemLimit, strictMemoryLock = true, workerManager, - fs = require('fs'), + fs, logger = new Logger(this.name), ...startOptions }: { @@ -57,7 +56,7 @@ class KeyRing { passwordOpsLimit?: PasswordOpsLimit; passwordMemLimit?: PasswordMemLimit; strictMemoryLock?: boolean; - workerManager?: PolykeyWorkerManagerInterface; + workerManager?: PolykeyWorkerManager; fs?: FileSystem; logger?: Logger; fresh?: boolean; @@ -75,6 +74,7 @@ class KeyRing { )): Promise { logger.info(`Creating ${this.name}`); logger.info(`Setting keys path to ${keysPath}`); + fs = await utils.importFS(fs); const keyRing = new this({ keysPath, passwordOpsLimit, @@ -98,7 +98,7 @@ class KeyRing { protected logger: Logger; protected fs: FileSystem; - protected workerManager?: PolykeyWorkerManagerInterface; + protected workerManager?: PolykeyWorkerManager; protected _keyPair?: KeyPairLocked; protected _dbKey?: BufferLocked; protected passwordHash?: Readonly<{ @@ -120,7 +120,7 @@ class KeyRing { logger, }: { keysPath: string; - workerManager?: PolykeyWorkerManagerInterface; + workerManager?: PolykeyWorkerManager; passwordOpsLimit?: PasswordOpsLimit; passwordMemLimit?: PasswordMemLimit; strictMemoryLock: boolean; @@ -139,7 +139,7 @@ class KeyRing { this.dbKeyPath = path.join(keysPath, 'db.jwk'); } - public setWorkerManager(workerManager: PolykeyWorkerManagerInterface) { + public setWorkerManager(workerManager: PolykeyWorkerManager) { this.workerManager = workerManager; } @@ -227,22 +227,22 @@ class KeyRing { this.logger.info(`Destroyed ${this.constructor.name}`); } - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) get keyPair(): KeyPairLocked { return this._keyPair!; } - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) get dbKey(): BufferLocked { return this._dbKey!; } - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) get recoveryCode(): RecoveryCode | undefined { return this._recoveryCodeData?.toString('utf-8') as RecoveryCode; } - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) public getNodeId(): NodeId { return keysUtils.publicKeyToNodeId(this._keyPair!.publicKey); } @@ -251,7 +251,7 @@ class KeyRing { * Warning: this is intended to be a slow operation to prevent brute force * attacks */ - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) public async checkPassword(password: string): Promise { if (this.workerManager == null) { return keysUtils.checkPassword( @@ -262,15 +262,20 @@ class KeyRing { this.passwordMemLimit, ); } else { - return await this.workerManager.call(async (w) => { - return await w.checkPassword( - password, - this.passwordHash!.hash.buffer, - this.passwordHash!.salt.buffer, - this.passwordOpsLimit, - this.passwordMemLimit, - ); + const passwordHashAB = workersUtils.toArrayBuffer( + this.passwordHash!.hash, + ); + const passwordSaltAB = workersUtils.toArrayBuffer( + this.passwordHash!.salt, + ); + const { data: result } = await this.workerManager.methods.checkPassword({ + password: password, + hash: passwordHashAB, + salt: passwordSaltAB, + opsLimit: this.passwordOpsLimit, + memLimit: this.passwordMemLimit, }); + return result; } } @@ -284,7 +289,7 @@ class KeyRing { * If an external client intends to change the password, * they must be authenticated first. */ - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) public async changePassword(password: string): Promise { await this.rotateLock.withF(async () => { this.logger.info('Changing root key pair password'); @@ -309,7 +314,7 @@ class KeyRing { * The DB key is not rotated, it is just re-encrypted with the new key pair. * The key pair is wrapped with the new password. */ - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) public async rotateKeyPair( password: string, rotateHook?: ( @@ -429,7 +434,7 @@ class KeyRing { * If it is important that the receiver can authenticate the sender, consider doing * `sign-then-encrypt`, by adding a signature into the plain text being sent. */ - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) public encrypt( receiverPublicKey: PublicKey, plainText: Buffer, @@ -446,17 +451,17 @@ class KeyRing { * Decrypt data sent to this key pair * Note that this does not automatically authenticate the sender. */ - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) public decrypt(cipherText: Buffer): Buffer | undefined { return keysUtils.decryptWithPrivateKey(this._keyPair!, cipherText); } - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) public sign(data: Buffer): Signature { return keysUtils.signWithPrivateKey(this._keyPair!, data); } - @ready(new keysErrors.ErrorKeyRingNotRunning()) + @createDestroyStartStop.ready(new keysErrors.ErrorKeyRingNotRunning()) public verify( publicKey: PublicKey, data: Buffer, @@ -800,13 +805,15 @@ class KeyRing { if (this.workerManager == null) { keyPair = await keysUtils.generateDeterministicKeyPair(recoveryCode); } else { - keyPair = await this.workerManager.call(async (w) => { - const result = await w.generateDeterministicKeyPair(recoveryCode); - result.publicKey = Buffer.from(result.publicKey); - result.privateKey = Buffer.from(result.privateKey); - result.secretKey = Buffer.from(result.secretKey); - return result as KeyPair; - }); + const { data: _keyPair } = + await this.workerManager.methods.generateDeterministicKeyPair({ + recoveryCode, + }); + keyPair = { + publicKey: Buffer.from(_keyPair.publicKey), + privateKey: Buffer.from(_keyPair.privateKey), + secretKey: Buffer.from(_keyPair.secretKey), + } as KeyPair; } } else { keyPair = keysUtils.generateKeyPair(); @@ -976,17 +983,16 @@ class KeyRing { this.passwordMemLimit, ); } else { - [hash, salt] = await this.workerManager.call(async (w) => { - const result = await w.hashPassword( - password, - undefined, - this.passwordOpsLimit, - this.passwordMemLimit, - ); - result[0] = Buffer.from(result[0]); - result[1] = Buffer.from(result[1]); - return result as [PasswordHash, PasswordSalt]; + const { + data: [hashAB, saltAB], + } = await this.workerManager.methods.hashPassword({ + password, + salt: undefined, + opsLimit: this.passwordOpsLimit, + memLimit: this.passwordMemLimit, }); + hash = Buffer.from(hashAB) as PasswordHash; + salt = Buffer.from(saltAB) as PasswordSalt; } return [hash, salt]; } diff --git a/src/keys/errors.ts b/src/keys/errors.ts index 3a20d9e868..8151583f61 100644 --- a/src/keys/errors.ts +++ b/src/keys/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorKeys extends ErrorPolykey {} diff --git a/src/keys/events.ts b/src/keys/events.ts index 53a1aa0c10..2813e0b7dc 100644 --- a/src/keys/events.ts +++ b/src/keys/events.ts @@ -1,5 +1,5 @@ -import type { CertManagerChangeData } from './types'; -import EventPolykey from '../EventPolykey'; +import type { CertManagerChangeData } from './types.js'; +import EventPolykey from '../EventPolykey.js'; abstract class EventKeys extends EventPolykey {} diff --git a/src/keys/index.ts b/src/keys/index.ts index 47b2aba464..5c05ac56a8 100644 --- a/src/keys/index.ts +++ b/src/keys/index.ts @@ -1,6 +1,6 @@ -export { default as KeyRing } from './KeyRing'; -export { default as CertManager } from './CertManager'; -export * as utils from './utils'; -export * as types from './types'; -export * as errors from './errors'; -export * as events from './events'; +export { default as KeyRing } from './KeyRing.js'; +export { default as CertManager } from './CertManager.js'; +export * as utils from './utils/index.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; diff --git a/src/keys/types.ts b/src/keys/types.ts index de920b19d1..da1210b010 100644 --- a/src/keys/types.ts +++ b/src/keys/types.ts @@ -1,6 +1,6 @@ import type { X509Certificate } from '@peculiar/x509'; -import type { NodeId } from '../ids/types'; -import type { Opaque, InverseRecord } from '../types'; +import type { NodeId } from '../ids/types.js'; +import type { Opaque, InverseRecord } from '../types.js'; /** * Locked buffer wrapper type for sensitive in-memory data. @@ -316,6 +316,6 @@ export type { CertManagerChangeData, }; -export type { CertId, CertIdString, CertIdEncoded } from '../ids/types'; +export type { CertId, CertIdString, CertIdEncoded } from '../ids/types.js'; export { multihashCodes, multihashCodesI }; diff --git a/src/keys/utils/asymmetric.ts b/src/keys/utils/asymmetric.ts index 2435756dbe..3f80ef9a0e 100644 --- a/src/keys/utils/asymmetric.ts +++ b/src/keys/utils/asymmetric.ts @@ -8,14 +8,14 @@ import type { Signature, JWK, JWKEncrypted, -} from '../types'; -import type { NodeId } from '../../ids/types'; +} from '../types.js'; +import type { NodeId } from '../../ids/types.js'; import sodium from 'sodium-native'; import canonicalize from 'canonicalize'; import { IdInternal } from '@matrixai/id'; -import { getRandomBytes } from './random'; -import * as validationErrors from '../../validation/errors'; -import * as utils from '../../utils'; +import { getRandomBytes } from './random.js'; +import * as validationErrors from '../../validation/errors.js'; +import * as utils from '../../utils/index.js'; /** * Use this to make a key pair if you only have public key and private key @@ -379,6 +379,7 @@ function encapsulateWithPublicKey( // Which does in fact require a nonce, are they re-using the same nonce somehow? const nonce = getRandomBytes(sodium.crypto_box_NONCEBYTES); const mac = Buffer.allocUnsafe(sodium.crypto_box_MACBYTES); + // @ts-ignore: canonicalize exports is function improperly for ESM const plainText = Buffer.from(canonicalize(keyJWK)!, 'utf-8'); const cipherText = Buffer.allocUnsafe(plainText.byteLength); sodium.crypto_box_detached( @@ -417,6 +418,7 @@ function encapsulateWithPublicKey( return keyJWE; } else { // ECDH-ES and ECDH-EE + // @ts-ignore: canonicalize exports is function improperly for ESM const plainText = Buffer.from(canonicalize(keyJWK)!, 'utf-8'); const publicKeyAndMacAndCipherText = Buffer.allocUnsafe( sodium.crypto_box_SEALBYTES + plainText.byteLength, diff --git a/src/keys/utils/generate.ts b/src/keys/utils/generate.ts index 60df706bb5..6bda3dabca 100644 --- a/src/keys/utils/generate.ts +++ b/src/keys/utils/generate.ts @@ -1,7 +1,7 @@ -import type { Key, KeyPair, RecoveryCode } from '../types'; +import type { Key, KeyPair, RecoveryCode } from '../types.js'; import sodium from 'sodium-native'; import * as bip39 from '@scure/bip39'; -import * as utils from '../../utils'; +import * as utils from '../../utils/index.js'; /** * Generates a Key. diff --git a/src/keys/utils/hash.ts b/src/keys/utils/hash.ts index a9dc21b832..7d0e1c640c 100644 --- a/src/keys/utils/hash.ts +++ b/src/keys/utils/hash.ts @@ -1,10 +1,10 @@ import type { MultihashDigest } from 'multiformats/hashes/interface'; -import type { Digest, DigestCode, DigestFormats } from '../types'; +import type { Digest, DigestCode, DigestFormats } from '../types.js'; import sodium from 'sodium-native'; import * as multiformats from 'multiformats'; -import * as keysTypes from '../types'; -import * as utils from '../../utils'; -import * as errors from '../../errors'; +import * as keysTypes from '../types.js'; +import * as utils from '../../utils/index.js'; +import * as errors from '../../errors.js'; function sha2256(data: BufferSource): Digest<'sha2-256'> { const digest = Buffer.allocUnsafeSlow(sodium.crypto_hash_sha256_BYTES); diff --git a/src/keys/utils/index.ts b/src/keys/utils/index.ts index 0f40590fa0..dd121e4c58 100644 --- a/src/keys/utils/index.ts +++ b/src/keys/utils/index.ts @@ -4,15 +4,15 @@ * @module */ -export * from './webcrypto'; -export * from './asymmetric'; -export * from './generate'; -export * from './hash'; -export * from './jwk'; -export * from './memory'; -export * from './password'; -export * from './pem'; -export * from './random'; -export * from './recoveryCode'; -export * from './symmetric'; -export * from './x509'; +export * from './webcrypto.js'; +export * from './asymmetric.js'; +export * from './generate.js'; +export * from './hash.js'; +export * from './jwk.js'; +export * from './memory.js'; +export * from './password.js'; +export * from './pem.js'; +export * from './random.js'; +export * from './recoveryCode.js'; +export * from './symmetric.js'; +export * from './x509.js'; diff --git a/src/keys/utils/jwk.ts b/src/keys/utils/jwk.ts index 76eb138788..427e4113ef 100644 --- a/src/keys/utils/jwk.ts +++ b/src/keys/utils/jwk.ts @@ -8,12 +8,12 @@ import type { PrivateKeyJWK, KeyPairJWK, JWK, -} from '../types'; +} from '../types.js'; import sodium from 'sodium-native'; import { validatePublicKey, publicKeyFromPrivateKeyEd25519, -} from './asymmetric'; +} from './asymmetric.js'; function keyToJWK(key: Key): KeyJWK { return { diff --git a/src/keys/utils/memory.ts b/src/keys/utils/memory.ts index 371a27cbf9..29aa3b6f5a 100644 --- a/src/keys/utils/memory.ts +++ b/src/keys/utils/memory.ts @@ -1,6 +1,6 @@ -import type { BufferLocked } from '../types'; +import type { BufferLocked } from '../types.js'; import sodium from 'sodium-native'; -import * as keysErrors from '../errors'; +import * as keysErrors from '../errors.js'; /** * Locks a buffer so that it cannot be swapped. diff --git a/src/keys/utils/password.ts b/src/keys/utils/password.ts index 8e9f920ed3..7ee0c8e206 100644 --- a/src/keys/utils/password.ts +++ b/src/keys/utils/password.ts @@ -5,10 +5,10 @@ import type { PasswordOpsLimit, PasswordMemLimitChoice, PasswordMemLimit, -} from '../types'; +} from '../types.js'; import sodium from 'sodium-native'; -import { getRandomBytes } from './random'; -import * as keysErrors from '../errors'; +import { getRandomBytes } from './random.js'; +import * as keysErrors from '../errors.js'; /** * Use the `min` limit during testing to improve performance. diff --git a/src/keys/utils/pem.ts b/src/keys/utils/pem.ts index 2a6efa7805..7b4af7523d 100644 --- a/src/keys/utils/pem.ts +++ b/src/keys/utils/pem.ts @@ -5,12 +5,12 @@ import type { PublicKeyPEM, PrivateKeyPEM, KeyPairPEM, -} from '../types'; +} from '../types.js'; import * as x509 from '@peculiar/x509'; import * as asn1 from '@peculiar/asn1-schema'; import * as asn1X509 from '@peculiar/asn1-x509'; import * as asn1Pkcs8 from '@peculiar/asn1-pkcs8'; -import { validatePublicKey } from './asymmetric'; +import { validatePublicKey } from './asymmetric.js'; /** * Converts PublicKey to SPKI PEM format. diff --git a/src/keys/utils/recoveryCode.ts b/src/keys/utils/recoveryCode.ts index 663ac2fea7..dad6e47b75 100644 --- a/src/keys/utils/recoveryCode.ts +++ b/src/keys/utils/recoveryCode.ts @@ -1,7 +1,7 @@ -import type { RecoveryCode } from '../types'; +import type { RecoveryCode } from '../types.js'; import * as bip39 from '@scure/bip39'; import { wordlist as bip39Wordlist } from '@scure/bip39/wordlists/english'; -import * as validationErrors from '../../validation/errors'; +import * as validationErrors from '../../validation/errors.js'; function generateRecoveryCode(size: 12 | 24 = 24): RecoveryCode { if (size === 12) { diff --git a/src/keys/utils/symmetric.ts b/src/keys/utils/symmetric.ts index 5020e8c267..d2a3ef1d6b 100644 --- a/src/keys/utils/symmetric.ts +++ b/src/keys/utils/symmetric.ts @@ -7,18 +7,18 @@ import type { PasswordOpsLimit, PasswordMemLimit, Digest, -} from '../types'; +} from '../types.js'; import sodium from 'sodium-native'; import canonicalize from 'canonicalize'; -import { getRandomBytes } from './random'; +import { getRandomBytes } from './random.js'; import { passwordOpsLimits, passwordMemLimits, passwordOpsLimitDefault, passwordMemLimitDefault, hashPassword, -} from './password'; -import * as utils from '../../utils'; +} from './password.js'; +import * as utils from '../../utils/index.js'; const nonceSize = sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES; const macSize = sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES; @@ -191,9 +191,11 @@ function wrapWithPassword( salt: salt.toString('base64url'), }; const protectedHeaderEncoded = Buffer.from( + // @ts-ignore: canonicalize exports is function improperly for ESM canonicalize(protectedHeader)!, 'utf-8', ).toString('base64url'); + // @ts-ignore: canonicalize exports is function improperly for ESM const plainText = Buffer.from(canonicalize(keyJWK)!, 'utf-8'); const additionalData = Buffer.from(protectedHeaderEncoded, 'utf-8'); const nonce = getRandomBytes(nonceSize); @@ -302,9 +304,11 @@ function wrapWithKey(key: Key, keyJWK: JWK): JWKEncrypted { cty: 'jwk+json', }; const protectedHeaderEncoded = Buffer.from( + // @ts-ignore: canonicalize exports is function improperly for ESM canonicalize(protectedHeader)!, 'utf-8', ).toString('base64url'); + // @ts-ignore: canonicalize exports is function improperly for ESM const plainText = Buffer.from(canonicalize(keyJWK)!, 'utf-8'); const additionalData = Buffer.from(protectedHeaderEncoded, 'utf-8'); const nonce = getRandomBytes(nonceSize); diff --git a/src/keys/utils/webcrypto.ts b/src/keys/utils/webcrypto.ts index cc193c2c64..bbeeae519a 100644 --- a/src/keys/utils/webcrypto.ts +++ b/src/keys/utils/webcrypto.ts @@ -1,7 +1,7 @@ -import type { PublicKey, PrivateKey, KeyPair } from '../types'; +import type { PublicKey, PrivateKey, KeyPair } from '../types.js'; import sodium from 'sodium-native'; import * as peculiarWebcrypto from '@peculiar/webcrypto'; -import * as utils from '../../utils'; +import * as utils from '../../utils/index.js'; /** * WebCrypto polyfill from @peculiar/webcrypto diff --git a/src/keys/utils/x509.ts b/src/keys/utils/x509.ts index 695b2c59b7..0e3dba93b5 100644 --- a/src/keys/utils/x509.ts +++ b/src/keys/utils/x509.ts @@ -4,19 +4,19 @@ import type { Certificate, CertificateASN1, CertificatePEM, -} from '../types'; -import type { CertId, NodeId } from '../../ids/types'; +} from '../types.js'; +import type { CertId, NodeId } from '../../ids/types.js'; import * as x509 from '@peculiar/x509'; import * as asn1 from '@peculiar/asn1-schema'; import * as asn1X509 from '@peculiar/asn1-x509'; -import webcrypto, { importPrivateKey, importPublicKey } from './webcrypto'; +import webcrypto, { importPrivateKey, importPublicKey } from './webcrypto.js'; import { publicKeyToNodeId, publicKeyFromPrivateKeyEd25519, validatePublicKey, -} from './asymmetric'; -import * as ids from '../../ids'; -import config from '../../config'; +} from './asymmetric.js'; +import * as ids from '../../ids/index.js'; +import config from '../../config.js'; x509.cryptoProvider.set(webcrypto); @@ -473,4 +473,8 @@ export { certFromPEM, }; -export { createCertIdGenerator, encodeCertId, decodeCertId } from '../../ids'; +export { + createCertIdGenerator, + encodeCertId, + decodeCertId, +} from '../../ids/index.js'; diff --git a/src/network/errors.ts b/src/network/errors.ts index 8a9dfbdd17..b6d41e8517 100644 --- a/src/network/errors.ts +++ b/src/network/errors.ts @@ -1,7 +1,7 @@ -import type { JSONValue } from '../types'; +import type { JSONValue } from '../types.js'; import type { Class } from '@matrixai/errors'; -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorNetwork extends ErrorPolykey {} diff --git a/src/network/index.ts b/src/network/index.ts index 0060192136..5257c52619 100644 --- a/src/network/index.ts +++ b/src/network/index.ts @@ -1,3 +1,3 @@ -export * as utils from './utils'; -export * as types from './types'; -export * as errors from './errors'; +export * as utils from './utils.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; diff --git a/src/network/types.ts b/src/network/types.ts index 32f2d568a0..7223d4d6c0 100644 --- a/src/network/types.ts +++ b/src/network/types.ts @@ -1,6 +1,6 @@ -import type { NodeId } from '../ids/types'; -import type { CertificatePEMChain, PrivateKeyPEM } from '../keys/types'; -import type { Opaque } from '../types'; +import type { NodeId } from '../ids/types.js'; +import type { CertificatePEMChain, PrivateKeyPEM } from '../keys/types.js'; +import type { Opaque } from '../types.js'; /** * Host is always an IP address diff --git a/src/network/utils.ts b/src/network/utils.ts index 6f03f69293..253d2bcb5d 100644 --- a/src/network/utils.ts +++ b/src/network/utils.ts @@ -1,17 +1,17 @@ import type { PromiseCancellable } from '@matrixai/async-cancellable'; import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts'; -import type { Address, Host, Hostname, Port } from './types'; -import type { NodeAddress } from '../nodes/types'; -import type { JSONValue } from '../types'; +import type { Address, Host, Hostname, Port } from './types.js'; +import type { NodeAddress } from '../nodes/types.js'; +import type { JSONValue } from '../types.js'; import dns from 'dns'; import { IPv4, IPv6, Validator } from 'ip-num'; -import { timedCancellable } from '@matrixai/contexts/dist/functions'; +import { functions } from '@matrixai/contexts'; import { AbstractError } from '@matrixai/errors'; -import * as networkErrors from './errors'; -import * as validationUtils from '../validation/utils'; -import * as validationErrors from '../validation/errors'; -import * as errors from '../errors'; -import ErrorPolykey from '../ErrorPolykey'; +import * as networkErrors from './errors.js'; +import * as validationUtils from '../validation/utils.js'; +import * as validationErrors from '../validation/errors.js'; +import * as errors from '../errors.js'; +import ErrorPolykey from '../ErrorPolykey.js'; /** * Is it an IPv4 address? @@ -377,7 +377,7 @@ function resolveHostname( } return hosts; }; - return timedCancellable(f, true)(ctx); + return functions.timedCancellable(f, true)(ctx); } /** diff --git a/src/nodes/NodeConnection.ts b/src/nodes/NodeConnection.ts index 090eaa9742..d977dde0cd 100644 --- a/src/nodes/NodeConnection.ts +++ b/src/nodes/NodeConnection.ts @@ -2,14 +2,14 @@ import type { X509Certificate } from '@peculiar/x509'; import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts'; import type { PromiseCancellable } from '@matrixai/async-cancellable'; import type { QUICSocket, QUICConnection } from '@matrixai/quic'; -import type { Host, Hostname, Port, TLSConfig } from '../network/types'; -import type { Certificate } from '../keys/types'; -import type { NodeId } from './types'; -import type agentClientManifest from './agent/callers'; +import type { Host, Hostname, Port, TLSConfig } from '../network/types.js'; +import type { Certificate } from '../keys/types.js'; +import type { NodeId } from './types.js'; +import type agentClientManifest from './agent/callers/index.js'; import Logger from '@matrixai/logger'; -import { CreateDestroy } from '@matrixai/async-init/dist/CreateDestroy'; +import { createDestroy } from '@matrixai/async-init'; import { status } from '@matrixai/async-init'; -import { timedCancellable, context } from '@matrixai/contexts/dist/decorators'; +import { decorators } from '@matrixai/contexts'; import { errors as contextErrors } from '@matrixai/contexts'; import { AbstractEvent, EventAll } from '@matrixai/events'; import { @@ -18,21 +18,21 @@ import { errors as quicErrors, } from '@matrixai/quic'; import { RPCClient, middleware as rpcUtilsMiddleware } from '@matrixai/rpc'; -import { ConnectionErrorReason, ConnectionErrorCode } from './types'; -import * as nodesErrors from './errors'; -import * as nodesEvents from './events'; -import * as nodesUtils from '../nodes/utils'; -import { never } from '../utils'; -import config from '../config'; -import * as networkUtils from '../network/utils'; +import { ConnectionErrorReason, ConnectionErrorCode } from './types.js'; +import * as nodesErrors from './errors.js'; +import * as nodesEvents from './events.js'; +import * as nodesUtils from '../nodes/utils.js'; +import { never } from '../utils/index.js'; +import config from '../config.js'; +import * as networkUtils from '../network/utils.js'; type AgentClientManifest = typeof agentClientManifest; /** * Encapsulates the unidirectional client-side connection of one node to another. */ -interface NodeConnection extends CreateDestroy {} -@CreateDestroy({ +interface NodeConnection extends createDestroy.CreateDestroy {} +@createDestroy.CreateDestroy({ eventDestroy: nodesEvents.EventNodeConnectionDestroy, eventDestroyed: nodesEvents.EventNodeConnectionDestroyed, }) @@ -194,7 +194,7 @@ class NodeConnection { }, ctx?: Partial, ): PromiseCancellable; - @timedCancellable( + @decorators.timedCancellable( true, config.defaultsSystem.nodesConnectionConnectTimeoutTime, ) @@ -229,7 +229,7 @@ class NodeConnection { quicSocket: QUICSocket; logger?: Logger; }, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { logger.info(`Creating forward ${this.name}`); // Checking if attempting to connect to a wildcard IP diff --git a/src/nodes/NodeConnectionManager.ts b/src/nodes/NodeConnectionManager.ts index 2d426009a0..333dfbed05 100644 --- a/src/nodes/NodeConnectionManager.ts +++ b/src/nodes/NodeConnectionManager.ts @@ -7,19 +7,19 @@ import type { AuthenticateNetworkReverseCallback, NodeId, NodeIdString, -} from './types'; -import type { NodesAuthenticateConnectionMessage } from './agent/types'; -import type { AgentServerManifest } from './agent/handlers'; -import type KeyRing from '../keys/KeyRing'; -import type { CertificatePEM } from '../keys/types'; +} from './types.js'; +import type { NodesAuthenticateConnectionMessage } from './agent/types.js'; +import type { AgentServerManifest } from './agent/handlers/index.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type { CertificatePEM } from '../keys/types.js'; import type { ConnectionData, Host, Hostname, Port, TLSConfig, -} from '../network/types'; -import type { JSONValue } from '../types'; +} from '../network/types.js'; +import type { JSONValue } from '../types.js'; import { TransformStream } from 'stream/web'; import { events as quicEvents, @@ -36,31 +36,22 @@ import { import Logger from '@matrixai/logger'; import { Timer } from '@matrixai/timer'; import { IdInternal } from '@matrixai/id'; -import { - ready, - running, - StartStop, - status, -} from '@matrixai/async-init/dist/StartStop'; +import { startStop } from '@matrixai/async-init'; import { AbstractEvent, EventAll } from '@matrixai/events'; -import { - context, - timed, - timedCancellable, -} from '@matrixai/contexts/dist/decorators'; +import { decorators } from '@matrixai/contexts'; import { Semaphore } from '@matrixai/async-locks'; import { PromiseCancellable } from '@matrixai/async-cancellable'; -import NodeConnection from './NodeConnection'; -import agentClientManifest from './agent/callers'; -import * as nodesUtils from './utils'; -import * as nodesErrors from './errors'; -import * as nodesEvents from './events'; -import * as agentUtils from './agent/utils'; -import * as keysUtils from '../keys/utils'; -import * as networkUtils from '../network/utils'; -import * as utils from '../utils'; -import RateLimiter from '../utils/ratelimiter/RateLimiter'; -import config from '../config'; +import NodeConnection from './NodeConnection.js'; +import agentClientManifest from './agent/callers/index.js'; +import * as nodesUtils from './utils.js'; +import * as nodesErrors from './errors.js'; +import * as nodesEvents from './events.js'; +import * as agentUtils from './agent/utils.js'; +import * as keysUtils from '../keys/utils/index.js'; +import * as networkUtils from '../network/utils.js'; +import * as utils from '../utils/index.js'; +import RateLimiter from '../utils/ratelimiter/RateLimiter.js'; +import config from '../config.js'; type ConnectionAndTimer = { connection: NodeConnection; @@ -127,8 +118,8 @@ const rpcMethodsWhitelist = ['nodesAuthenticateConnection']; * The NodeConnectionManager encapsulates `QUICServer`. * While the NodeConnection encapsulates `QUICClient`. */ -interface NodeConnectionManager extends StartStop {} -@StartStop({ +interface NodeConnectionManager extends startStop.StartStop {} +@startStop.StartStop({ eventStart: nodesEvents.EventNodeConnectionManagerStart, eventStarted: nodesEvents.EventNodeConnectionManagerStarted, eventStop: nodesEvents.EventNodeConnectionManagerStop, @@ -290,7 +281,7 @@ class NodeConnectionManager { _evt: nodesEvents.EventNodeConnectionManagerClose, ) => { this.logger.debug(`close event triggering NodeConnectionManager.stop`); - if (this[running] && this[status] !== 'stopping') { + if (this[startStop.running] && this[startStop.status] !== 'stopping') { await this.stop(); } }; @@ -531,7 +522,7 @@ class NodeConnectionManager { /** * Get the host that node connection manager is bound to. */ - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) public get host(): Host { return this.quicSocket.host as unknown as Host; } @@ -539,12 +530,12 @@ class NodeConnectionManager { /** * Get the port that node connection manager is bound to. */ - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) public get port(): Port { return this.quicSocket.port as unknown as Port; } - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) public get type(): 'ipv4' | 'ipv6' | 'ipv4&ipv6' { return this.quicSocket.type; } @@ -797,10 +788,10 @@ class NodeConnectionManager { ctx: Partial | undefined, f: (conn: NodeConnection) => Promise, ): Promise; - @timedCancellable(true) + @decorators.timedCancellable(true) public async withConnF( targetNodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, f: (conn: NodeConnection) => Promise, ): Promise { return await withF( @@ -825,11 +816,11 @@ class NodeConnectionManager { ctx: Partial | undefined, g: (conn: NodeConnection) => AsyncGenerator, ): AsyncGenerator; - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) - @timed() + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @decorators.timed() public async *withConnG( targetNodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, g: (conn: NodeConnection) => AsyncGenerator, ): AsyncGenerator { const acquire = this.acquireConnection(targetNodeId, ctx); @@ -856,8 +847,8 @@ class NodeConnectionManager { port: Port, ctx?: Partial, ): PromiseCancellable; - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) - @timedCancellable( + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, @@ -866,7 +857,7 @@ class NodeConnectionManager { nodeIds: Array, host: Host, port: Port, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { const nodeConnection = await NodeConnection.createNodeConnection( { @@ -923,8 +914,8 @@ class NodeConnectionManager { addresses: Array<[Host, Port]>, ctx?: Partial, ): PromiseCancellable; - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) - @timedCancellable( + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, @@ -932,7 +923,7 @@ class NodeConnectionManager { public async createConnectionMultiple( nodeIds: Array, addresses: Array<[Host, Port]>, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { // Setting up intermediate signal const abortControllerMultiConn = new AbortController(); @@ -978,8 +969,8 @@ class NodeConnectionManager { nodeIdSignaller: NodeId, ctx?: Partial, ): PromiseCancellable; - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) - @timedCancellable( + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, @@ -987,7 +978,7 @@ class NodeConnectionManager { public async createConnectionPunch( nodeIdTarget: NodeId, nodeIdSignaller: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { // Get the signaller node from the existing connections if (!this.hasConnection(nodeIdSignaller)) { @@ -1240,7 +1231,7 @@ class NodeConnectionManager { * This takes a reverse initiated QUICConnection, wraps it as a * NodeConnection and adds it to the connection map. */ - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) protected handleConnectionReverse(quicConnection: QUICConnection) { // Checking NodeId // No specific error here, validation is handled by the QUICServer @@ -1313,8 +1304,8 @@ class NodeConnectionManager { port: Port, ctx?: Partial, ): PromiseCancellable; - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) - @timedCancellable( + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, @@ -1322,7 +1313,7 @@ class NodeConnectionManager { public async holePunch( host: Host, port: Port, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { // We need to send a random data packet to the target until the process times out or a connection is established let ended = false; @@ -1357,12 +1348,12 @@ class NodeConnectionManager { } } - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) public hasConnection(nodeId: NodeId): boolean { return this.connections.has(nodeId.toString() as NodeIdString); } - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) public listConnections(): Array<{ nodeId: NodeId; connectionId: string; @@ -1438,7 +1429,7 @@ class NodeConnectionManager { * Active attempts are tracked inside the `activeHolePunchPs` set and are cancelled and awaited when the * `NodeConnectionManager` stops. */ - @ready(new nodesErrors.ErrorNodeManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning()) public handleNodesConnectionSignalFinal(host: Host, port: Port) { const id = `${host}:${port}`; if (this.activeHolePunchPs.has(id)) return; @@ -1504,8 +1495,8 @@ class NodeConnectionManager { host: Host; port: Port; }>; - @ready(new nodesErrors.ErrorNodeManagerNotRunning()) - @timedCancellable( + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning()) + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, @@ -1518,7 +1509,7 @@ class NodeConnectionManager { port: Port; }, requestSignature: string, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise<{ host: Host; port: Port; @@ -1604,7 +1595,7 @@ class NodeConnectionManager { /** * Returns a list of active connections and their address information. */ - @ready(new nodesErrors.ErrorNodeManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning()) public getClosestConnections( targetNodeId: NodeId, limit: number = this.connectionGetClosestLimit, @@ -1653,14 +1644,14 @@ class NodeConnectionManager { nodeId: NodeId, ctx?: Partial, ): PromiseCancellable; - @timedCancellable( + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, ) public async forwardAuthenticate( nodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { const targetNodeIdString = nodeId.toString() as NodeIdString; const connectionsEntry = this.connections.get(targetNodeIdString); @@ -1706,7 +1697,7 @@ class NodeConnectionManager { message: NodesAuthenticateConnectionMessage, ctx?: Partial, ): PromiseCancellable; - @timedCancellable( + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, @@ -1714,7 +1705,7 @@ class NodeConnectionManager { public async handleReverseAuthenticate( nodeId: NodeId, message: NodesAuthenticateConnectionMessage, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { const targetNodeIdString = nodeId.toString() as NodeIdString; const connectionsEntry = this.connections.get(targetNodeIdString); @@ -1808,14 +1799,14 @@ class NodeConnectionManager { nodeId: NodeId, ctx?: Partial, ): Promise; - @timedCancellable( + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, ) public async isAuthenticatedP( nodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { ctx.signal.throwIfAborted(); const targetNodeIdString = nodeId.toString() as NodeIdString; diff --git a/src/nodes/NodeConnectionQueue.ts b/src/nodes/NodeConnectionQueue.ts index d82fb137f1..fe9a2e36e9 100644 --- a/src/nodes/NodeConnectionQueue.ts +++ b/src/nodes/NodeConnectionQueue.ts @@ -1,9 +1,9 @@ -import type { NodeIdString, NodeId } from '../ids/types'; -import type { NodeContact } from './types'; +import type { NodeIdString, NodeId } from '../ids/types.js'; +import type { NodeContact } from './types.js'; import type { Semaphore } from '@matrixai/async-locks'; import type { ContextCancellable } from '@matrixai/contexts'; -import * as nodesUtils from './utils'; -import * as utils from '../utils'; +import * as nodesUtils from './utils.js'; +import * as utils from '../utils/index.js'; // Temp utility class for tracking shared queue export class NodeConnectionQueue { diff --git a/src/nodes/NodeGraph.ts b/src/nodes/NodeGraph.ts index 4af01f14f6..e3cfdc45ca 100644 --- a/src/nodes/NodeGraph.ts +++ b/src/nodes/NodeGraph.ts @@ -10,21 +10,17 @@ import type { NodeBucketMeta, NodeBucketIndex, NodeGraphSpace, -} from './types'; -import type KeyRing from '../keys/KeyRing'; +} from './types.js'; +import type KeyRing from '../keys/KeyRing.js'; import Logger from '@matrixai/logger'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { IdInternal } from '@matrixai/id'; -import { timedCancellable } from '@matrixai/contexts/dist/decorators'; -import { context } from '@matrixai/contexts/dist/decorators'; -import * as nodesUtils from './utils'; -import * as nodesErrors from './errors'; -import * as nodesEvents from './events'; -import * as utils from '../utils'; -import config from '../config'; +import { decorators } from '@matrixai/contexts'; +import * as nodesUtils from './utils.js'; +import * as nodesErrors from './errors.js'; +import * as nodesEvents from './events.js'; +import * as utils from '../utils/index.js'; +import config from '../config.js'; /** * NodeGraph is an implementation of Kademlia for maintaining peer to peer @@ -41,8 +37,8 @@ import config from '../config'; * When the node ID changes, either due to key renewal or reset, we remap all * existing records to the other space, and then we swap the active space key. */ -interface NodeGraph extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface NodeGraph extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new nodesErrors.ErrorNodeGraphRunning(), new nodesErrors.ErrorNodeGraphDestroyed(), { @@ -226,7 +222,7 @@ class NodeGraph { * Locks the bucket index for exclusive operations. * This allows you to sequence operations for any bucket. */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async lockBucket( bucketIndex: number, tran: DBTransaction, @@ -248,12 +244,12 @@ class NodeGraph { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @decorators.timedCancellable(true) public async getNodeContact( nodeId: NodeId, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return await this.db.withTransactionF( @@ -292,7 +288,7 @@ class NodeGraph { * NodeBucketIndex asc, NodeID asc, NodeContactAddress asc * NodeBucketIndex desc, NodeId desc, NodeContactAddress desc */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async *getNodeContacts( order: 'asc' | 'desc' = 'asc', tran?: DBTransaction, @@ -314,7 +310,7 @@ class NodeGraph { /** * Get a single `NodeContactAddressData`. */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async getNodeContactAddressData( nodeId: NodeId, nodeAddress: NodeAddress | NodeContactAddress, @@ -347,7 +343,7 @@ class NodeGraph { * * @throws {nodesErrors.ErrorNodeGraphBucketLimit} If the bucket is full. */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async setNodeContact( nodeId: NodeId, nodeContact: NodeContact, @@ -397,7 +393,7 @@ class NodeGraph { * * @throws {nodesErrors.ErrorNodeGraphBucketLimit} If the bucket is full. */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async setNodeContactAddressData( nodeId: NodeId, nodeAddress: NodeAddress | NodeContactAddress, @@ -451,7 +447,7 @@ class NodeGraph { * Unsets a `NodeId` record. * It will decrement the bucket count if it existed. */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async unsetNodeContact( nodeId: NodeId, tran?: DBTransaction, @@ -478,7 +474,7 @@ class NodeGraph { await this.delConnectedTime(nodeId, tran); } - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async unsetNodeContactAddress( nodeId: NodeId, nodeAddress: NodeAddress | NodeContactAddress, @@ -635,15 +631,15 @@ class NodeGraph { tran?: DBTransaction, ctx?: Partial, ): Promise; - @timedCancellable(true) - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @decorators.timedCancellable(true) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async getBucket( bucketIndex: NodeBucketIndex, sort: 'nodeId' | 'distance' | 'connected' = 'nodeId', order: 'asc' | 'desc' = 'asc', limit: number | undefined, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return await this.db.withTransactionF( @@ -710,7 +706,7 @@ class NodeGraph { * NodeBucketIndex asc, connected asc * NodeBucketIndex desc, connected desc */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async *getBuckets( sort: 'nodeId' | 'distance' | 'connected' = 'nodeId', order: 'asc' | 'desc' = 'asc', @@ -740,7 +736,7 @@ class NodeGraph { * Resets the bucket according to the new node ID. * Run this after new node ID is generated via renewal or reset. */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async resetBuckets(tran?: DBTransaction): Promise { if (tran == null) { return this.db.withTransactionF((tran) => this.resetBuckets(tran)); @@ -833,7 +829,7 @@ class NodeGraph { * Get a bucket meta POJO. * This will provide default values for missing properties. */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async getBucketMeta( bucketIndex: NodeBucketIndex, tran?: DBTransaction, @@ -867,7 +863,7 @@ class NodeGraph { * Get a single bucket meta property. * This will provide default values for missing properties. */ - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async getBucketMetaProp( bucketIndex: NodeBucketIndex, key: Key, @@ -903,7 +899,10 @@ class NodeGraph { * ascending order. If the given node ID already exists in the node graph, * then it will be the first result. * + * @param nodeId * @param limit - Defaults to the bucket limit. + * @param tran + * @param ctx * @returns The `NodeBucket` which could have less than `limit` nodes if the * node graph has less than the requested limit. */ @@ -913,13 +912,13 @@ class NodeGraph { tran?: DBTransaction, ctx?: Partial, ): Promise; - @timedCancellable(true) - @ready(new nodesErrors.ErrorNodeGraphNotRunning()) + @decorators.timedCancellable(true) + @createDestroyStartStop.ready(new nodesErrors.ErrorNodeGraphNotRunning()) public async getClosestNodes( nodeId: NodeId, limit: number = this.nodeBucketLimit, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return await this.db.withTransactionF( diff --git a/src/nodes/NodeManager.ts b/src/nodes/NodeManager.ts index c527104c79..ff0ebccd59 100644 --- a/src/nodes/NodeManager.ts +++ b/src/nodes/NodeManager.ts @@ -2,31 +2,31 @@ import type { DB, DBTransaction } from '@matrixai/db'; import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts'; import type { PromiseCancellable } from '@matrixai/async-cancellable'; import type { ResourceAcquire } from '@matrixai/resources'; -import type KeyRing from '../keys/KeyRing'; -import type Sigchain from '../sigchain/Sigchain'; -import type TaskManager from '../tasks/TaskManager'; -import type GestaltGraph from '../gestalts/GestaltGraph'; +import type KeyRing from '../keys/KeyRing.js'; +import type Sigchain from '../sigchain/Sigchain.js'; +import type TaskManager from '../tasks/TaskManager.js'; +import type GestaltGraph from '../gestalts/GestaltGraph.js'; import type { Task, TaskHandler, TaskHandlerId, TaskInfo, -} from '../tasks/types'; -import type { SignedTokenEncoded } from '../tokens/types'; -import type { Host, Port } from '../network/types'; +} from '../tasks/types.js'; +import type { SignedTokenEncoded } from '../tokens/types.js'; +import type { Host, Port } from '../network/types.js'; import type { Claim, ClaimId, // ClaimIdEncoded, SignedClaim, -} from '../claims/types'; -import type { ClaimLinkNode } from '../claims/payloads'; -import type NodeConnection from '../nodes/NodeConnection'; +} from '../claims/types.js'; +import type { ClaimLinkNode } from '../claims/payloads/index.js'; +import type NodeConnection from '../nodes/NodeConnection.js'; import type { AgentClaimMessage, AgentRPCRequestParams, AgentRPCResponseResult, -} from './agent/types'; +} from './agent/types.js'; import type { NodeAddress, NodeBucket, @@ -34,36 +34,32 @@ import type { NodeContactAddressData, NodeId, NodeIdEncoded, -} from './types'; -import type NodeConnectionManager from './NodeConnectionManager'; -import type NodeGraph from './NodeGraph'; +} from './types.js'; +import type NodeConnectionManager from './NodeConnectionManager.js'; +import type NodeGraph from './NodeGraph.js'; import type { ServicePOJO } from '@matrixai/mdns'; import { withF } from '@matrixai/resources'; import { events as mdnsEvents, MDNS, utils as mdnsUtils } from '@matrixai/mdns'; import Logger from '@matrixai/logger'; -import { ready, StartStop } from '@matrixai/async-init/dist/StartStop'; +import { startStop } from '@matrixai/async-init'; import { Lock, LockBox, Semaphore } from '@matrixai/async-locks'; import { IdInternal } from '@matrixai/id'; -import { - context, - timed, - timedCancellable, -} from '@matrixai/contexts/dist/decorators'; -import * as nodesUtils from './utils'; -import * as nodesEvents from './events'; -import * as nodesErrors from './errors'; -import * as agentErrors from './agent/errors'; -import NodeConnectionQueue from './NodeConnectionQueue'; -import { assertClaimNetworkAuthority } from '../claims/payloads/claimNetworkAuthority'; -import { assertClaimNetworkAccess } from '../claims/payloads/claimNetworkAccess'; -import Token from '../tokens/Token'; -import * as keysUtils from '../keys/utils'; -import * as tasksErrors from '../tasks/errors'; -import * as claimsUtils from '../claims/utils'; -import * as claimsErrors from '../claims/errors'; -import * as utils from '../utils/utils'; -import config from '../config'; -import * as networkUtils from '../network/utils'; +import { decorators } from '@matrixai/contexts'; +import * as nodesUtils from './utils.js'; +import * as nodesEvents from './events.js'; +import * as nodesErrors from './errors.js'; +import * as agentErrors from './agent/errors.js'; +import NodeConnectionQueue from './NodeConnectionQueue.js'; +import { assertClaimNetworkAuthority } from '../claims/payloads/claimNetworkAuthority.js'; +import { assertClaimNetworkAccess } from '../claims/payloads/claimNetworkAccess.js'; +import Token from '../tokens/Token.js'; +import * as keysUtils from '../keys/utils/index.js'; +import * as tasksErrors from '../tasks/errors.js'; +import * as claimsUtils from '../claims/utils.js'; +import * as claimsErrors from '../claims/errors.js'; +import * as utils from '../utils/utils.js'; +import config from '../config.js'; +import * as networkUtils from '../network/utils.js'; const abortEphemeralTaskReason = Symbol('abort ephemeral task reason'); const abortSingletonTaskReason = Symbol('abort singleton task reason'); @@ -76,8 +72,8 @@ const abortPendingConnectionsReason = Symbol( * It encapsulates mutations to the NodeGraph. * It listens to the NodeConnectionManager events. */ -interface NodeManager extends StartStop {} -@StartStop({ +interface NodeManager extends startStop.StartStop {} +@startStop.StartStop({ eventStart: nodesEvents.EventNodeManagerStart, eventStarted: nodesEvents.EventNodeManagerStarted, eventStop: nodesEvents.EventNodeManagerStop, @@ -517,10 +513,10 @@ class NodeManager { ctx: Partial | undefined, f: (conn: NodeConnection) => Promise, ): Promise; - @ready(new nodesErrors.ErrorNodeManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning()) public async withConnF( nodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, f: (conn: NodeConnection) => Promise, ): Promise { return await withF( @@ -545,11 +541,11 @@ class NodeManager { ctx: Partial | undefined, g: (conn: NodeConnection) => AsyncGenerator, ): AsyncGenerator; - @ready(new nodesErrors.ErrorNodeManagerNotRunning()) - @timed() + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning()) + @decorators.timed() public async *withConnG( nodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, g: (conn: NodeConnection) => AsyncGenerator, ): AsyncGenerator { const acquire = this.acquireConnection(nodeId, ctx); @@ -594,7 +590,7 @@ class NodeManager { }, ctx?: Partial, ): PromiseCancellable<[NodeAddress, NodeContactAddressData] | undefined>; - @timedCancellable(true) + @decorators.timedCancellable(true) public async findNode( { nodeId, @@ -609,7 +605,7 @@ class NodeManager { concurrencyLimit: number; limit: number; }, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise<[NodeAddress, NodeContactAddressData] | undefined> { // Setting up intermediate signal const abortController = new AbortController(); @@ -688,12 +684,12 @@ class NodeManager { connectionConnectTimeoutTime?: number, ctx?: Partial, ): PromiseCancellable<[[Host, Port], NodeContactAddressData]>; - @timedCancellable(true) + @decorators.timedCancellable(true) public async findNodeBySignal( nodeId: NodeId, nodeConnectionsQueue: NodeConnectionQueue, connectionConnectTimeoutTime: number = this.connectionConnectTimeoutTime, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise<[[Host, Port], NodeContactAddressData]> { // Setting up intermediate signal const abortController = new AbortController(); @@ -824,12 +820,12 @@ class NodeManager { connectionConnectTimeoutTime?: number, ctx?: Partial, ): PromiseCancellable<[[Host, Port], NodeContactAddressData]>; - @timedCancellable(true) + @decorators.timedCancellable(true) public async findNodeByDirect( nodeId: NodeId, nodeConnectionsQueue: NodeConnectionQueue, connectionConnectTimeoutTime: number = this.connectionConnectTimeoutTime, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise<[[Host, Port], NodeContactAddressData]> { // Setting up intermediate signal const abortController = new AbortController(); @@ -967,13 +963,13 @@ class NodeManager { nodeId: NodeId, ctx?: Partial, ): PromiseCancellable>; - @timedCancellable( + @decorators.timedCancellable( true, (nodeManager: NodeManager) => nodeManager.connectionConnectTimeoutTime, ) public async queryMDNS( nodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise> { const addresses: Array<[Host, Port]> = []; if (this.mdns == null) return addresses; @@ -1064,13 +1060,13 @@ class NodeManager { nodeId: NodeId, ctx?: Partial, ): PromiseCancellable<[[Host, Port], NodeContactAddressData]>; - @timedCancellable( + @decorators.timedCancellable( true, (nodeManager: NodeManager) => nodeManager.connectionFindMDNSTimeoutTime, ) public async findNodeByMDNS( nodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise<[[Host, Port], NodeContactAddressData]> { try { if (this.mdns == null) { @@ -1173,15 +1169,15 @@ class NodeManager { nodeId: NodeId, ctx?: Partial, ): PromiseCancellable<[NodeAddress, NodeContactAddressData] | undefined>; - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) - @timedCancellable( + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, ) public async pingNode( nodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise<[NodeAddress, NodeContactAddressData] | undefined> { return await this.findNode( { @@ -1205,8 +1201,8 @@ class NodeManager { port: Port, ctx?: Partial, ): PromiseCancellable; - @ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) - @timedCancellable( + @startStop.ready(new nodesErrors.ErrorNodeConnectionManagerNotRunning()) + @decorators.timedCancellable( true, (nodeConnectionManager: NodeConnectionManager) => nodeConnectionManager.connectionConnectTimeoutTime, @@ -1215,7 +1211,7 @@ class NodeManager { nodeId: NodeId, host: Host, port: Port, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (this.nodeConnectionManager.hasConnection(nodeId)) return true; try { @@ -1247,11 +1243,11 @@ class NodeManager { claimId?: ClaimId, ctx?: Partial, ): PromiseCancellable>; - @timedCancellable(true) + @decorators.timedCancellable(true) public async requestChainData( targetNodeId: NodeId, claimId: ClaimId | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise> { // Verify the node's chain with its own public key return await this.withConnF(targetNodeId, ctx, async (connection) => { @@ -1314,11 +1310,11 @@ class NodeManager { tran?: DBTransaction, ctx?: Partial, ): PromiseCancellable; - @ready(new nodesErrors.ErrorNodeManagerNotRunning()) + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning()) public async claimNode( targetNodeId: NodeId, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => { @@ -1668,8 +1664,10 @@ class NodeManager { tran?: DBTransaction, ctx?: Partial, ): PromiseCancellable; - @ready(new nodesErrors.ErrorNodeManagerNotRunning(), true, ['stopping']) - @timedCancellable(true) + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning(), true, [ + 'stopping', + ]) + @decorators.timedCancellable(true) public async setNode( nodeId: NodeId, nodeAddress: NodeAddress, @@ -1678,7 +1676,7 @@ class NodeManager { force: boolean = false, connectionConnectTimeoutTime: number = this.connectionConnectTimeoutTime, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { // We don't want to add our own node if (nodeId.equals(this.keyRing.getNodeId())) { @@ -1823,11 +1821,11 @@ class NodeManager { ctx?: Partial, tran?: DBTransaction, ): PromiseCancellable; - @timedCancellable(true) + @decorators.timedCancellable(true) protected async garbageCollectBucket( bucketIndex: number, connectionConnectTimeoutTime: number = this.connectionConnectTimeoutTime, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, tran?: DBTransaction, ): Promise { if (tran == null) { @@ -2023,12 +2021,12 @@ class NodeManager { connectionConnectTimeoutTime?: number, ctx?: Partial, ): PromiseCancellable; - @timedCancellable(true) + @decorators.timedCancellable(true) public async refreshBucket( bucketIndex: NodeBucketIndex, connectionConnectTimeoutTime: number | undefined = this .connectionConnectTimeoutTime, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { // We need to generate a random nodeId for this bucket const nodeId = this.keyRing.getNodeId(); @@ -2144,14 +2142,16 @@ class NodeManager { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new nodesErrors.ErrorNodeManagerNotRunning(), true, ['stopping']) - @timedCancellable(true) + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning(), true, [ + 'stopping', + ]) + @decorators.timedCancellable(true) public async updateRefreshBucketDelay( bucketIndex: number, delay: number = this.refreshBucketDelayTime, lazy: boolean = true, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => @@ -2246,13 +2246,13 @@ class NodeManager { blocking?: boolean, ctx?: Partial, ): PromiseCancellable; - @ready(new nodesErrors.ErrorNodeManagerNotRunning()) - @timedCancellable(true) + @startStop.ready(new nodesErrors.ErrorNodeManagerNotRunning()) + @decorators.timedCancellable(true) public async syncNodeGraph( initialNodes: Array<[NodeId, NodeAddress]>, connectionConnectTimeoutTime: number = this.connectionConnectTimeoutTime, blocking: boolean = false, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { const logger = this.logger.getChild('syncNodeGraph'); logger.info('Synchronizing NodeGraph'); diff --git a/src/nodes/agent/callers/index.ts b/src/nodes/agent/callers/index.ts index 990142a341..af2001fc45 100644 --- a/src/nodes/agent/callers/index.ts +++ b/src/nodes/agent/callers/index.ts @@ -1,17 +1,17 @@ -import nodesAuthenticateConnection from './nodesAuthenticateConnection'; -import nodesAuditEventsGet from './nodesAuditEventsGet'; -import nodesClaimsGet from './nodesClaimsGet'; -import nodesClosestActiveConnectionsGet from './nodesClosestActiveConnectionsGet'; -import nodesClosestLocalNodesGet from './nodesClosestLocalNodesGet'; -import nodesConnectionSignalFinal from './nodesConnectionSignalFinal'; -import nodesConnectionSignalInitial from './nodesConnectionSignalInitial'; -import nodesCrossSignClaim from './nodesCrossSignClaim'; -import nodesClaimNetworkSign from './nodesClaimNetworkSign'; -import nodesClaimNetworkVerify from './nodesClaimNetworkVerify'; -import notificationsSend from './notificationsSend'; -import vaultsGitInfoGet from './vaultsGitInfoGet'; -import vaultsGitPackGet from './vaultsGitPackGet'; -import vaultsScan from './vaultsScan'; +import nodesAuthenticateConnection from './nodesAuthenticateConnection.js'; +import nodesAuditEventsGet from './nodesAuditEventsGet.js'; +import nodesClaimsGet from './nodesClaimsGet.js'; +import nodesClosestActiveConnectionsGet from './nodesClosestActiveConnectionsGet.js'; +import nodesClosestLocalNodesGet from './nodesClosestLocalNodesGet.js'; +import nodesConnectionSignalFinal from './nodesConnectionSignalFinal.js'; +import nodesConnectionSignalInitial from './nodesConnectionSignalInitial.js'; +import nodesCrossSignClaim from './nodesCrossSignClaim.js'; +import nodesClaimNetworkSign from './nodesClaimNetworkSign.js'; +import nodesClaimNetworkVerify from './nodesClaimNetworkVerify.js'; +import notificationsSend from './notificationsSend.js'; +import vaultsGitInfoGet from './vaultsGitInfoGet.js'; +import vaultsGitPackGet from './vaultsGitPackGet.js'; +import vaultsScan from './vaultsScan.js'; /** * Client manifest diff --git a/src/nodes/agent/callers/nodesAuditEventsGet.ts b/src/nodes/agent/callers/nodesAuditEventsGet.ts index eccbd5ac9f..7dc4b1b4cb 100644 --- a/src/nodes/agent/callers/nodesAuditEventsGet.ts +++ b/src/nodes/agent/callers/nodesAuditEventsGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesAuditEventsGet from '../handlers/NodesAuditEventsGet'; +import type NodesAuditEventsGet from '../handlers/NodesAuditEventsGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesAuthenticateConnection.ts b/src/nodes/agent/callers/nodesAuthenticateConnection.ts index d8814a60cb..9409914852 100644 --- a/src/nodes/agent/callers/nodesAuthenticateConnection.ts +++ b/src/nodes/agent/callers/nodesAuthenticateConnection.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesAuthenticateConnection from '../handlers/NodesAuthenticateConnection'; +import type NodesAuthenticateConnection from '../handlers/NodesAuthenticateConnection.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesClaimNetworkSign.ts b/src/nodes/agent/callers/nodesClaimNetworkSign.ts index afbf833b2e..07d877b79b 100644 --- a/src/nodes/agent/callers/nodesClaimNetworkSign.ts +++ b/src/nodes/agent/callers/nodesClaimNetworkSign.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesClaimNetworkSign from '../handlers/NodesClaimNetworkSign'; +import type NodesClaimNetworkSign from '../handlers/NodesClaimNetworkSign.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesClaimNetworkVerify.ts b/src/nodes/agent/callers/nodesClaimNetworkVerify.ts index 32b659beb2..2b8c553fa4 100644 --- a/src/nodes/agent/callers/nodesClaimNetworkVerify.ts +++ b/src/nodes/agent/callers/nodesClaimNetworkVerify.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesClaimNetworkVerify from '../handlers/NodesClaimNetworkVerify'; +import type NodesClaimNetworkVerify from '../handlers/NodesClaimNetworkVerify.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesClaimsGet.ts b/src/nodes/agent/callers/nodesClaimsGet.ts index 4d32cb110a..87e6c643b1 100644 --- a/src/nodes/agent/callers/nodesClaimsGet.ts +++ b/src/nodes/agent/callers/nodesClaimsGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesClaimsGet from '../handlers/NodesClaimsGet'; +import type NodesClaimsGet from '../handlers/NodesClaimsGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesClosestActiveConnectionsGet.ts b/src/nodes/agent/callers/nodesClosestActiveConnectionsGet.ts index dcce923213..1b719413ff 100644 --- a/src/nodes/agent/callers/nodesClosestActiveConnectionsGet.ts +++ b/src/nodes/agent/callers/nodesClosestActiveConnectionsGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesClosestActiveConnectionsGet from '../handlers/NodesClosestActiveConnectionsGet'; +import type NodesClosestActiveConnectionsGet from '../handlers/NodesClosestActiveConnectionsGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesClosestLocalNodesGet.ts b/src/nodes/agent/callers/nodesClosestLocalNodesGet.ts index 9de8e6417d..2be1380ce6 100644 --- a/src/nodes/agent/callers/nodesClosestLocalNodesGet.ts +++ b/src/nodes/agent/callers/nodesClosestLocalNodesGet.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesClosestLocalNodesGet from '../handlers/NodesClosestLocalNodesGet'; +import type NodesClosestLocalNodesGet from '../handlers/NodesClosestLocalNodesGet.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesConnectionSignalFinal.ts b/src/nodes/agent/callers/nodesConnectionSignalFinal.ts index 2d341f2d46..a9eea2bb9c 100644 --- a/src/nodes/agent/callers/nodesConnectionSignalFinal.ts +++ b/src/nodes/agent/callers/nodesConnectionSignalFinal.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesConnectionSignalFinal from '../handlers/NodesConnectionSignalFinal'; +import type NodesConnectionSignalFinal from '../handlers/NodesConnectionSignalFinal.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesConnectionSignalInitial.ts b/src/nodes/agent/callers/nodesConnectionSignalInitial.ts index eef756e4e3..b5ad5687f9 100644 --- a/src/nodes/agent/callers/nodesConnectionSignalInitial.ts +++ b/src/nodes/agent/callers/nodesConnectionSignalInitial.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesConnectionSignalInitial from '../handlers/NodesConnectionSignalInitial'; +import type NodesConnectionSignalInitial from '../handlers/NodesConnectionSignalInitial.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/nodesCrossSignClaim.ts b/src/nodes/agent/callers/nodesCrossSignClaim.ts index f94684ff09..89afb7726b 100644 --- a/src/nodes/agent/callers/nodesCrossSignClaim.ts +++ b/src/nodes/agent/callers/nodesCrossSignClaim.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NodesCrossSignClaim from '../handlers/NodesCrossSignClaim'; +import type NodesCrossSignClaim from '../handlers/NodesCrossSignClaim.js'; import { DuplexCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/notificationsSend.ts b/src/nodes/agent/callers/notificationsSend.ts index d4f6dd182b..4457189f49 100644 --- a/src/nodes/agent/callers/notificationsSend.ts +++ b/src/nodes/agent/callers/notificationsSend.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type NotificationsSend from '../handlers/NotificationsSend'; +import type NotificationsSend from '../handlers/NotificationsSend.js'; import { UnaryCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/callers/vaultsScan.ts b/src/nodes/agent/callers/vaultsScan.ts index b24e94673a..811ef47959 100644 --- a/src/nodes/agent/callers/vaultsScan.ts +++ b/src/nodes/agent/callers/vaultsScan.ts @@ -1,5 +1,5 @@ import type { HandlerTypes } from '@matrixai/rpc'; -import type VaultsScan from '../handlers/VaultsScan'; +import type VaultsScan from '../handlers/VaultsScan.js'; import { ServerCaller } from '@matrixai/rpc'; type CallerTypes = HandlerTypes; diff --git a/src/nodes/agent/errors.ts b/src/nodes/agent/errors.ts index 7ff9bba44b..c60bb368a0 100644 --- a/src/nodes/agent/errors.ts +++ b/src/nodes/agent/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../../ErrorPolykey'; -import sysexits from '../../utils/sysexits'; +import ErrorPolykey from '../../ErrorPolykey.js'; +import sysexits from '../../utils/sysexits.js'; class ErrorAgent extends ErrorPolykey {} diff --git a/src/nodes/agent/handlers/NodesAuditEventsGet.ts b/src/nodes/agent/handlers/NodesAuditEventsGet.ts index 7fc77e8886..664a601d19 100644 --- a/src/nodes/agent/handlers/NodesAuditEventsGet.ts +++ b/src/nodes/agent/handlers/NodesAuditEventsGet.ts @@ -6,12 +6,12 @@ import type { AgentRPCResponseResult, AuditIdMessage, AgentAuditMessage, -} from '../types'; -import type Audit from '../../../audit/Audit'; -import type { AuditEvent } from '../../../audit/types'; -import type { AuditEventId } from '../../../ids'; +} from '../types.js'; +import type Audit from '../../../audit/Audit.js'; +import type { AuditEvent } from '../../../audit/types.js'; +import type { AuditEventId } from '../../../ids/index.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as auditUtils from '../../../audit/utils'; +import * as auditUtils from '../../../audit/utils.js'; /** * Gets audit events from a node diff --git a/src/nodes/agent/handlers/NodesAuthenticateConnection.ts b/src/nodes/agent/handlers/NodesAuthenticateConnection.ts index a4fbedfdeb..a20ee66316 100644 --- a/src/nodes/agent/handlers/NodesAuthenticateConnection.ts +++ b/src/nodes/agent/handlers/NodesAuthenticateConnection.ts @@ -3,13 +3,13 @@ import type { AgentRPCResponseResult, NodesAuthenticateConnectionMessage, SuccessMessage, -} from '../types'; -import type NodeConnectionManager from '../../../nodes/NodeConnectionManager'; -import type { JSONValue } from '../../../types'; +} from '../types.js'; +import type NodeConnectionManager from '../../../nodes/NodeConnectionManager.js'; +import type { JSONValue } from '../../../types.js'; import type { ContextTimed } from '@matrixai/contexts'; import { UnaryHandler } from '@matrixai/rpc'; -import * as agentErrors from '../errors'; -import * as agentUtils from '../utils'; +import * as agentErrors from '../errors.js'; +import * as agentUtils from '../utils.js'; class NodesAuthenticateConnection extends UnaryHandler< { diff --git a/src/nodes/agent/handlers/NodesClaimNetworkSign.ts b/src/nodes/agent/handlers/NodesClaimNetworkSign.ts index 470885c82e..3e137066fd 100644 --- a/src/nodes/agent/handlers/NodesClaimNetworkSign.ts +++ b/src/nodes/agent/handlers/NodesClaimNetworkSign.ts @@ -2,12 +2,12 @@ import type { AgentRPCRequestParams, AgentRPCResponseResult, AgentClaimMessage, -} from '../types'; -import type NodeManager from '../../../nodes/NodeManager'; -import type { JSONValue } from '../../../types'; +} from '../types.js'; +import type NodeManager from '../../../nodes/NodeManager.js'; +import type { JSONValue } from '../../../types.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as agentErrors from '../errors'; -import * as agentUtils from '../utils'; +import * as agentErrors from '../errors.js'; +import * as agentUtils from '../utils.js'; class NodesClaimNetworkSign extends UnaryHandler< { diff --git a/src/nodes/agent/handlers/NodesClaimNetworkVerify.ts b/src/nodes/agent/handlers/NodesClaimNetworkVerify.ts index fb786f5e79..f22d425c80 100644 --- a/src/nodes/agent/handlers/NodesClaimNetworkVerify.ts +++ b/src/nodes/agent/handlers/NodesClaimNetworkVerify.ts @@ -2,12 +2,12 @@ import type { AgentClaimMessage, AgentRPCRequestParams, AgentRPCResponseResult, -} from '../types'; -import type NodeManager from '../../../nodes/NodeManager'; -import type { JSONValue } from '../../../types'; +} from '../types.js'; +import type NodeManager from '../../../nodes/NodeManager.js'; +import type { JSONValue } from '../../../types.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as agentErrors from '../errors'; -import * as agentUtils from '../utils'; +import * as agentErrors from '../errors.js'; +import * as agentUtils from '../utils.js'; class NodesClaimNetworkVerify extends UnaryHandler< { diff --git a/src/nodes/agent/handlers/NodesClaimsGet.ts b/src/nodes/agent/handlers/NodesClaimsGet.ts index a149ed2177..5f7fc22505 100644 --- a/src/nodes/agent/handlers/NodesClaimsGet.ts +++ b/src/nodes/agent/handlers/NodesClaimsGet.ts @@ -1,16 +1,16 @@ import type { ContextTimed } from '@matrixai/contexts'; import type { DB } from '@matrixai/db'; import type { JSONValue } from '@matrixai/rpc'; -import type Sigchain from '../../../sigchain/Sigchain'; +import type Sigchain from '../../../sigchain/Sigchain.js'; import type { AgentRPCRequestParams, AgentRPCResponseResult, AgentClaimMessage, NodesClaimsGetMessage, -} from '../types'; +} from '../types.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as claimsUtils from '../../../claims/utils'; -import * as ids from '../../../ids'; +import * as claimsUtils from '../../../claims/utils.js'; +import * as ids from '../../../ids/index.js'; /** * Gets the sigchain claims of a node diff --git a/src/nodes/agent/handlers/NodesClosestActiveConnectionsGet.ts b/src/nodes/agent/handlers/NodesClosestActiveConnectionsGet.ts index e6f699fd4a..f1573748c9 100644 --- a/src/nodes/agent/handlers/NodesClosestActiveConnectionsGet.ts +++ b/src/nodes/agent/handlers/NodesClosestActiveConnectionsGet.ts @@ -4,15 +4,15 @@ import type { AgentRPCRequestParams, AgentRPCResponseResult, NodeIdMessage, -} from '../types'; -import type NodeConnectionManager from '../../NodeConnectionManager'; -import type { NodeId } from '../../../ids'; -import type { ActiveConnectionDataMessage } from '../types'; +} from '../types.js'; +import type NodeConnectionManager from '../../NodeConnectionManager.js'; +import type { NodeId } from '../../../ids/index.js'; +import type { ActiveConnectionDataMessage } from '../types.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as utils from '../../../utils'; -import * as ids from '../../../ids'; -import * as validation from '../../../validation'; -import * as nodesUtils from '../../utils'; +import * as utils from '../../../utils/index.js'; +import * as ids from '../../../ids/index.js'; +import * as validation from '../../../validation/index.js'; +import * as nodesUtils from '../../utils.js'; /** * Gets the closest local nodes to a target node diff --git a/src/nodes/agent/handlers/NodesClosestLocalNodesGet.ts b/src/nodes/agent/handlers/NodesClosestLocalNodesGet.ts index b6a5cd0889..4fc5615f14 100644 --- a/src/nodes/agent/handlers/NodesClosestLocalNodesGet.ts +++ b/src/nodes/agent/handlers/NodesClosestLocalNodesGet.ts @@ -6,19 +6,19 @@ import type { AgentRPCResponseResult, NodeContactMessage, NodeIdMessage, -} from '../types'; -import type NodeGraph from '../../NodeGraph'; -import type { NodeId } from '../../../ids'; +} from '../types.js'; +import type NodeGraph from '../../NodeGraph.js'; +import type { NodeId } from '../../../ids/index.js'; import type { NodeBucket, NodeContact, NodeContactAddressData, -} from '../../types'; +} from '../../types.js'; import { ServerHandler } from '@matrixai/rpc'; -import * as ids from '../../../ids'; -import * as validation from '../../../validation'; -import * as nodesUtils from '../../utils'; -import * as utils from '../../../utils'; +import * as ids from '../../../ids/index.js'; +import * as validation from '../../../validation/index.js'; +import * as nodesUtils from '../../utils.js'; +import * as utils from '../../../utils/index.js'; /** * Gets the closest local nodes to a target node diff --git a/src/nodes/agent/handlers/NodesConnectionSignalFinal.ts b/src/nodes/agent/handlers/NodesConnectionSignalFinal.ts index 1d9f185060..d96fc460bd 100644 --- a/src/nodes/agent/handlers/NodesConnectionSignalFinal.ts +++ b/src/nodes/agent/handlers/NodesConnectionSignalFinal.ts @@ -4,17 +4,17 @@ import type { AgentRPCRequestParams, AgentRPCResponseResult, HolePunchRequestMessage, -} from '../types'; -import type { NodeId } from '../../../ids'; -import type NodeConnectionManager from '../../NodeConnectionManager'; -import type { Host, Port } from '../../../network/types'; +} from '../types.js'; +import type { NodeId } from '../../../ids/index.js'; +import type NodeConnectionManager from '../../NodeConnectionManager.js'; +import type { Host, Port } from '../../../network/types.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { validateSync } from '../../../validation'; -import { matchSync } from '../../../utils'; -import * as keysUtils from '../../../keys/utils'; -import * as ids from '../../../ids'; -import * as agentErrors from '../errors'; -import * as agentUtils from '../utils'; +import { validateSync } from '../../../validation/index.js'; +import { matchSync } from '../../../utils/index.js'; +import * as keysUtils from '../../../keys/utils/index.js'; +import * as ids from '../../../ids/index.js'; +import * as agentErrors from '../errors.js'; +import * as agentUtils from '../utils.js'; class NodesConnectionSignalFinal extends UnaryHandler< { diff --git a/src/nodes/agent/handlers/NodesConnectionSignalInitial.ts b/src/nodes/agent/handlers/NodesConnectionSignalInitial.ts index b586dc280a..cd3b56dd6d 100644 --- a/src/nodes/agent/handlers/NodesConnectionSignalInitial.ts +++ b/src/nodes/agent/handlers/NodesConnectionSignalInitial.ts @@ -3,19 +3,19 @@ import type { AgentRPCResponseResult, HolePunchSignalMessage, AddressMessage, -} from '../types'; -import type { NodeId } from '../../../ids'; -import type NodeConnectionManager from '../../../nodes/NodeConnectionManager'; -import type { Host, Port } from '../../../network/types'; -import type { JSONValue } from '../../../types'; +} from '../types.js'; +import type { NodeId } from '../../../ids/index.js'; +import type NodeConnectionManager from '../../../nodes/NodeConnectionManager.js'; +import type { Host, Port } from '../../../network/types.js'; +import type { JSONValue } from '../../../types.js'; import { UnaryHandler } from '@matrixai/rpc'; -import { validateSync } from '../../../validation'; -import { matchSync } from '../../../utils'; -import { never } from '../../../utils'; -import * as agentErrors from '../errors'; -import * as agentUtils from '../utils'; -import * as keysUtils from '../../../keys/utils'; -import * as ids from '../../../ids'; +import { validateSync } from '../../../validation/index.js'; +import { matchSync } from '../../../utils/index.js'; +import { never } from '../../../utils/index.js'; +import * as agentErrors from '../errors.js'; +import * as agentUtils from '../utils.js'; +import * as keysUtils from '../../../keys/utils/index.js'; +import * as ids from '../../../ids/index.js'; class NodesConnectionSignalInitial extends UnaryHandler< { diff --git a/src/nodes/agent/handlers/NodesCrossSignClaim.ts b/src/nodes/agent/handlers/NodesCrossSignClaim.ts index 6b669e5267..dd089a9714 100644 --- a/src/nodes/agent/handlers/NodesCrossSignClaim.ts +++ b/src/nodes/agent/handlers/NodesCrossSignClaim.ts @@ -3,13 +3,13 @@ import type { AgentRPCRequestParams, AgentRPCResponseResult, AgentClaimMessage, -} from '../types'; -import type NodeManager from '../../NodeManager'; -import type ACL from '../../../acl/ACL'; +} from '../types.js'; +import type NodeManager from '../../NodeManager.js'; +import type ACL from '../../../acl/ACL.js'; import { DuplexHandler } from '@matrixai/rpc'; -import * as agentErrors from '../errors'; -import * as agentUtils from '../utils'; -import * as nodesErrors from '../../errors'; +import * as agentErrors from '../errors.js'; +import * as agentUtils from '../utils.js'; +import * as nodesErrors from '../../errors.js'; /** * Claims a node diff --git a/src/nodes/agent/handlers/NotificationsSend.ts b/src/nodes/agent/handlers/NotificationsSend.ts index 33c2363023..1a0bcdc1f6 100644 --- a/src/nodes/agent/handlers/NotificationsSend.ts +++ b/src/nodes/agent/handlers/NotificationsSend.ts @@ -3,11 +3,11 @@ import type { AgentRPCRequestParams, AgentRPCResponseResult, SignedNotificationEncoded, -} from '../types'; -import type KeyRing from '../../../keys/KeyRing'; -import type NotificationsManager from '../../../notifications/NotificationsManager'; +} from '../types.js'; +import type KeyRing from '../../../keys/KeyRing.js'; +import type NotificationsManager from '../../../notifications/NotificationsManager.js'; import { UnaryHandler } from '@matrixai/rpc'; -import * as notificationsUtils from '../../../notifications/utils'; +import * as notificationsUtils from '../../../notifications/utils.js'; /** * Sends a notification to a node diff --git a/src/nodes/agent/handlers/VaultsGitInfoGet.ts b/src/nodes/agent/handlers/VaultsGitInfoGet.ts index b13fa48ac5..6dc6d3ce6c 100644 --- a/src/nodes/agent/handlers/VaultsGitInfoGet.ts +++ b/src/nodes/agent/handlers/VaultsGitInfoGet.ts @@ -2,17 +2,17 @@ import type { DB } from '@matrixai/db'; import type Logger from '@matrixai/logger'; import type { JSONObject, JSONRPCRequest } from '@matrixai/rpc'; import type { ContextTimed } from '@matrixai/contexts'; -import type ACL from '../../../acl/ACL'; -import type VaultManager from '../../../vaults/VaultManager'; -import type { JSONValue } from '../../../types'; +import type ACL from '../../../acl/ACL.js'; +import type VaultManager from '../../../vaults/VaultManager.js'; +import type { JSONValue } from '../../../types.js'; import { ReadableStream } from 'stream/web'; import { RawHandler } from '@matrixai/rpc'; -import * as agentErrors from '../errors'; -import * as vaultsUtils from '../../../vaults/utils'; -import * as vaultsErrors from '../../../vaults/errors'; -import * as nodesUtils from '../../utils'; -import * as agentUtils from '../utils'; -import * as utils from '../../../utils'; +import * as agentErrors from '../errors.js'; +import * as vaultsUtils from '../../../vaults/utils.js'; +import * as vaultsErrors from '../../../vaults/errors.js'; +import * as nodesUtils from '../../utils.js'; +import * as agentUtils from '../utils.js'; +import * as utils from '../../../utils/index.js'; /** * Gets the git info of a vault. diff --git a/src/nodes/agent/handlers/VaultsGitPackGet.ts b/src/nodes/agent/handlers/VaultsGitPackGet.ts index 2f006b8cdc..492e3ee084 100644 --- a/src/nodes/agent/handlers/VaultsGitPackGet.ts +++ b/src/nodes/agent/handlers/VaultsGitPackGet.ts @@ -1,17 +1,17 @@ import type { DB } from '@matrixai/db'; import type { JSONObject, JSONRPCRequest, JSONValue } from '@matrixai/rpc'; import type { ContextTimed } from '@matrixai/contexts'; -import type { VaultName } from '../../../vaults/types'; -import type ACL from '../../../acl/ACL'; -import type VaultManager from '../../../vaults/VaultManager'; +import type { VaultName } from '../../../vaults/types.js'; +import type ACL from '../../../acl/ACL.js'; +import type VaultManager from '../../../vaults/VaultManager.js'; import { ReadableStream } from 'stream/web'; import { RawHandler } from '@matrixai/rpc'; -import * as agentErrors from '../errors'; -import * as agentUtils from '../utils'; -import * as nodesUtils from '../../utils'; -import * as vaultsUtils from '../../../vaults/utils'; -import * as vaultsErrors from '../../../vaults/errors'; -import * as utils from '../../../utils'; +import * as agentErrors from '../errors.js'; +import * as agentUtils from '../utils.js'; +import * as nodesUtils from '../../utils.js'; +import * as vaultsUtils from '../../../vaults/utils.js'; +import * as vaultsErrors from '../../../vaults/errors.js'; +import * as utils from '../../../utils/index.js'; /** * Gets the git pack of a vault. diff --git a/src/nodes/agent/handlers/VaultsScan.ts b/src/nodes/agent/handlers/VaultsScan.ts index 72a4705bc8..a4e950d04d 100644 --- a/src/nodes/agent/handlers/VaultsScan.ts +++ b/src/nodes/agent/handlers/VaultsScan.ts @@ -4,13 +4,13 @@ import type { AgentRPCRequestParams, AgentRPCResponseResult, VaultsScanMessage, -} from '../types'; -import type VaultManager from '../../../vaults/VaultManager'; +} from '../types.js'; +import type VaultManager from '../../../vaults/VaultManager.js'; import type { JSONValue } from '@matrixai/rpc'; import { ServerHandler } from '@matrixai/rpc'; -import * as agentErrors from '../errors'; -import * as agentUtils from '../utils'; -import * as vaultsUtils from '../../../vaults/utils'; +import * as agentErrors from '../errors.js'; +import * as agentUtils from '../utils.js'; +import * as vaultsUtils from '../../../vaults/utils.js'; /** * Scan vaults. diff --git a/src/nodes/agent/handlers/index.ts b/src/nodes/agent/handlers/index.ts index 28ffc3c1d9..cb6c24d3d6 100644 --- a/src/nodes/agent/handlers/index.ts +++ b/src/nodes/agent/handlers/index.ts @@ -1,27 +1,27 @@ import type { DB } from '@matrixai/db'; import type Logger from '@matrixai/logger'; -import type KeyRing from '../../../keys/KeyRing'; -import type Audit from '../../../audit/Audit'; -import type Sigchain from '../../../sigchain/Sigchain'; -import type ACL from '../../../acl/ACL'; -import type NodeGraph from '../../../nodes/NodeGraph'; -import type NodeManager from '../../../nodes/NodeManager'; -import type NodeConnectionManager from '../../../nodes/NodeConnectionManager'; -import type NotificationsManager from '../../../notifications/NotificationsManager'; -import type VaultManager from '../../../vaults/VaultManager'; -import NodesAuthenticateConnection from './NodesAuthenticateConnection'; -import NodesAuditEventsGet from './NodesAuditEventsGet'; -import NodesClaimsGet from './NodesClaimsGet'; -import NodesClosestActiveConnectionsGet from './NodesClosestActiveConnectionsGet'; -import NodesClosestLocalNodesGet from './NodesClosestLocalNodesGet'; -import NodesConnectionSignalFinal from './NodesConnectionSignalFinal'; -import NodesConnectionSignalInitial from './NodesConnectionSignalInitial'; -import NodesCrossSignClaim from './NodesCrossSignClaim'; -import NodesClaimNetworkSign from './NodesClaimNetworkSign'; -import NotificationsSend from './NotificationsSend'; -import VaultsGitInfoGet from './VaultsGitInfoGet'; -import VaultsGitPackGet from './VaultsGitPackGet'; -import VaultsScan from './VaultsScan'; +import type KeyRing from '../../../keys/KeyRing.js'; +import type Audit from '../../../audit/Audit.js'; +import type Sigchain from '../../../sigchain/Sigchain.js'; +import type ACL from '../../../acl/ACL.js'; +import type NodeGraph from '../../../nodes/NodeGraph.js'; +import type NodeManager from '../../../nodes/NodeManager.js'; +import type NodeConnectionManager from '../../../nodes/NodeConnectionManager.js'; +import type NotificationsManager from '../../../notifications/NotificationsManager.js'; +import type VaultManager from '../../../vaults/VaultManager.js'; +import NodesAuthenticateConnection from './NodesAuthenticateConnection.js'; +import NodesAuditEventsGet from './NodesAuditEventsGet.js'; +import NodesClaimsGet from './NodesClaimsGet.js'; +import NodesClosestActiveConnectionsGet from './NodesClosestActiveConnectionsGet.js'; +import NodesClosestLocalNodesGet from './NodesClosestLocalNodesGet.js'; +import NodesConnectionSignalFinal from './NodesConnectionSignalFinal.js'; +import NodesConnectionSignalInitial from './NodesConnectionSignalInitial.js'; +import NodesCrossSignClaim from './NodesCrossSignClaim.js'; +import NodesClaimNetworkSign from './NodesClaimNetworkSign.js'; +import NotificationsSend from './NotificationsSend.js'; +import VaultsGitInfoGet from './VaultsGitInfoGet.js'; +import VaultsGitPackGet from './VaultsGitPackGet.js'; +import VaultsScan from './VaultsScan.js'; /** * Server manifest factory. diff --git a/src/nodes/agent/index.ts b/src/nodes/agent/index.ts index a26442f67b..cae058d26e 100644 --- a/src/nodes/agent/index.ts +++ b/src/nodes/agent/index.ts @@ -1,7 +1,7 @@ -export { default as manifestClient } from './callers'; -export { default as manifestServer } from './handlers'; -export * as callers from './callers'; -export * as handlers from './handlers'; -export * as utils from './utils'; -export * as errors from './errors'; -export * as types from './types'; +export { default as manifestClient } from './callers/index.js'; +export { default as manifestServer } from './handlers/index.js'; +export * as callers from './callers/index.js'; +export * as handlers from './handlers/index.js'; +export * as utils from './utils.js'; +export * as errors from './errors.js'; +export * as types from './types.js'; diff --git a/src/nodes/agent/types.ts b/src/nodes/agent/types.ts index 1318bc2be4..0d3ca17642 100644 --- a/src/nodes/agent/types.ts +++ b/src/nodes/agent/types.ts @@ -3,18 +3,18 @@ import type { JSONRPCRequestParams, JSONRPCResponseResult, } from '@matrixai/rpc'; -import type { SignedTokenEncoded } from '../../tokens/types'; +import type { SignedTokenEncoded } from '../../tokens/types.js'; import type { AuditEventIdEncoded, ClaimIdEncoded, NodeIdEncoded, VaultIdEncoded, -} from '../../ids'; -import type { VaultAction, VaultName } from '../../vaults/types'; -import type { SignedNotification } from '../../notifications/types'; -import type { Host, Hostname, Port } from '../../network/types'; -import type { NetworkId, NodeContact } from '../../nodes/types'; -import type { AuditEvent } from '../../audit/types'; +} from '../../ids/index.js'; +import type { VaultAction, VaultName } from '../../vaults/types.js'; +import type { SignedNotification } from '../../notifications/types.js'; +import type { Host, Hostname, Port } from '../../network/types.js'; +import type { NetworkId, NodeContact } from '../../nodes/types.js'; +import type { AuditEvent } from '../../audit/types.js'; type AgentRPCRequestParams = JSONRPCRequestParams; diff --git a/src/nodes/agent/utils.ts b/src/nodes/agent/utils.ts index a12120c098..8ab67b6c69 100644 --- a/src/nodes/agent/utils.ts +++ b/src/nodes/agent/utils.ts @@ -1,7 +1,7 @@ -import type { NodeId } from '../../ids/types'; -import type { CertificatePEM } from '../../keys/types'; +import type { NodeId } from '../../ids/types.js'; +import type { CertificatePEM } from '../../keys/types.js'; import { utils as quicUtils } from '@matrixai/quic'; -import * as keysUtils from '../../keys/utils'; +import * as keysUtils from '../../keys/utils/index.js'; /** * Used to extract the NodeId from the connection metadata. diff --git a/src/nodes/errors.ts b/src/nodes/errors.ts index 76dbbcc737..1eaee43406 100644 --- a/src/nodes/errors.ts +++ b/src/nodes/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorNodes extends ErrorPolykey {} diff --git a/src/nodes/events.ts b/src/nodes/events.ts index 93cccd0a47..1fd2133035 100644 --- a/src/nodes/events.ts +++ b/src/nodes/events.ts @@ -1,7 +1,7 @@ import type { QUICStream } from '@matrixai/quic'; -import type { ConnectionData } from '../network/types'; -import type { NodeId } from '../ids/types'; -import EventPolykey from '../EventPolykey'; +import type { ConnectionData } from '../network/types.js'; +import type { NodeId } from '../ids/types.js'; +import EventPolykey from '../EventPolykey.js'; abstract class EventNode extends EventPolykey {} diff --git a/src/nodes/index.ts b/src/nodes/index.ts index 09265ea674..3f81ef3494 100644 --- a/src/nodes/index.ts +++ b/src/nodes/index.ts @@ -1,9 +1,9 @@ -export { default as NodeManager } from './NodeManager'; -export { default as NodeGraph } from './NodeGraph'; -export { default as NodeConnectionManager } from './NodeConnectionManager'; -export { default as NodeConnection } from './NodeConnection'; -export * as agent from './agent'; -export * as utils from './utils'; -export * as events from './events'; -export * as errors from './errors'; -export * as types from './types'; +export { default as NodeManager } from './NodeManager.js'; +export { default as NodeGraph } from './NodeGraph.js'; +export { default as NodeConnectionManager } from './NodeConnectionManager.js'; +export { default as NodeConnection } from './NodeConnection.js'; +export * as agent from './agent/index.js'; +export * as utils from './utils.js'; +export * as events from './events.js'; +export * as errors from './errors.js'; +export * as types from './types.js'; diff --git a/src/nodes/types.ts b/src/nodes/types.ts index ac08a6ffd2..d2ecaef79f 100644 --- a/src/nodes/types.ts +++ b/src/nodes/types.ts @@ -1,8 +1,8 @@ import type { ContextTimed } from '@matrixai/contexts'; -import type { NodeId, NodeIdString, NodeIdEncoded } from '../ids/types'; -import type { Host, Hostname, Port } from '../network/types'; -import type { NodesAuthenticateConnectionMessage } from '../nodes/agent/types'; -import type { Opaque } from '../types'; +import type { NodeId, NodeIdString, NodeIdEncoded } from '../ids/types.js'; +import type { Host, Hostname, Port } from '../network/types.js'; +import type { NodesAuthenticateConnectionMessage } from '../nodes/agent/types.js'; +import type { Opaque } from '../types.js'; /** * Key indicating which space the NodeGraph is in diff --git a/src/nodes/utils.ts b/src/nodes/utils.ts index 72a0a3fbe2..f7b45909ed 100644 --- a/src/nodes/utils.ts +++ b/src/nodes/utils.ts @@ -1,8 +1,8 @@ import type { DBTransaction, KeyPath, LevelPath } from '@matrixai/db'; import type { X509Certificate } from '@peculiar/x509'; import type { QUICClientCrypto, QUICServerCrypto } from '@matrixai/quic'; -import type { Key, Certificate, CertificatePEM } from '../keys/types'; -import type { Hostname, Port } from '../network/types'; +import type { Key, Certificate, CertificatePEM } from '../keys/types.js'; +import type { Hostname, Port } from '../network/types.js'; import type { NodeAddress, NodeContact, @@ -12,26 +12,26 @@ import type { NodeBucketIndex, NodeId, SeedNodes, -} from './types'; +} from './types.js'; import type { NodesAuthenticateConnectionMessage, NodesAuthenticateConnectionMessageBasicPublic, NodesAuthenticateConnectionMessageNone, -} from './agent/types'; +} from './agent/types.js'; import dns from 'dns'; import { utils as dbUtils } from '@matrixai/db'; import { IdInternal } from '@matrixai/id'; -import { CryptoError } from '@matrixai/quic/dist/native'; +import { native } from '@matrixai/quic'; import { utils as quicUtils, errors as quicErrors } from '@matrixai/quic'; import { errors as rpcErrors } from '@matrixai/rpc'; import lexi from 'lexicographic-integer'; -import * as nodesErrors from './errors'; -import * as ids from '../ids'; -import * as keysUtils from '../keys/utils'; -import * as networkUtils from '../network/utils'; -import * as validationErrors from '../validation/errors'; -import config from '../config'; -import * as utils from '../utils'; +import * as nodesErrors from './errors.js'; +import * as ids from '../ids/index.js'; +import * as keysUtils from '../keys/utils/index.js'; +import * as networkUtils from '../network/utils.js'; +import * as validationErrors from '../validation/errors.js'; +import config from '../config.js'; +import * as utils from '../utils/index.js'; const sepBuffer = dbUtils.sep; @@ -155,7 +155,12 @@ function parseBucketsDbKey(keyPath: KeyPath): { } const bucketKey = bucketKeyPath.toString(); const bucketIndex = lexi.unpack(bucketKey); - const nodeId = IdInternal.fromBuffer(Buffer.from(nodeIdKey)); + let nodeId: NodeId; + if (typeof nodeIdKey === 'string') { + nodeId = IdInternal.fromBuffer(Buffer.from(nodeIdKey)); + } else { + nodeId = IdInternal.fromBuffer(Buffer.from(nodeIdKey)); + } return { bucketIndex, bucketKey, @@ -219,7 +224,12 @@ function parseLastUpdatedBucketDbKey(keyPath: KeyPath): { if (lastUpdated == null) { throw new TypeError('Buffer is not an NodeGraph index bucket key'); } - const nodeId = IdInternal.fromBuffer(Buffer.from(nodeIdKey)); + let nodeId: NodeId; + if (typeof nodeIdKey === 'string') { + nodeId = IdInternal.fromBuffer(Buffer.from(nodeIdKey)); + } else { + nodeId = IdInternal.fromBuffer(Buffer.from(nodeIdKey)); + } return { lastUpdated, nodeId, @@ -544,14 +554,14 @@ async function verifyServerCertificateChain( } | { result: 'fail'; - value: CryptoError; + value: native.CryptoError; } > { const certPEMChain = certs.map((v) => quicUtils.derToPEM(v)); if (certPEMChain.length === 0) { return { result: 'fail', - value: CryptoError.CertificateRequired, + value: native.CryptoError.CertificateRequired, }; } if (nodeIds.length === 0) { @@ -563,7 +573,7 @@ async function verifyServerCertificateChain( if (cert == null) { return { result: 'fail', - value: CryptoError.BadCertificate, + value: native.CryptoError.BadCertificate, }; } certChain.push(cert); @@ -577,27 +587,27 @@ async function verifyServerCertificateChain( if (now < cert.notBefore || now > cert.notAfter) { return { result: 'fail', - value: CryptoError.CertificateExpired, + value: native.CryptoError.CertificateExpired, }; } const certNodeId = keysUtils.certNodeId(cert); if (certNodeId == null) { return { result: 'fail', - value: CryptoError.BadCertificate, + value: native.CryptoError.BadCertificate, }; } const certPublicKey = keysUtils.certPublicKey(cert); if (certPublicKey == null) { return { result: 'fail', - value: CryptoError.BadCertificate, + value: native.CryptoError.BadCertificate, }; } if (!(await keysUtils.certNodeSigned(cert))) { return { result: 'fail', - value: CryptoError.BadCertificate, + value: native.CryptoError.BadCertificate, }; } for (const nodeId of nodeIds) { @@ -614,7 +624,7 @@ async function verifyServerCertificateChain( if (certClaimIndex == null || certClaim == null || verifiedNodeId == null) { return { result: 'fail', - value: CryptoError.BadCertificate, + value: native.CryptoError.BadCertificate, }; } if (certClaimIndex > 0) { @@ -632,7 +642,7 @@ async function verifyServerCertificateChain( ) { return { result: 'fail', - value: CryptoError.BadCertificate, + value: native.CryptoError.BadCertificate, }; } } @@ -649,15 +659,15 @@ async function verifyServerCertificateChain( */ async function verifyClientCertificateChain( certs: Array, -): Promise { +): Promise { const certPEMChain = certs.map((v) => quicUtils.derToPEM(v)); if (certPEMChain.length === 0) { - return CryptoError.CertificateRequired; + return native.CryptoError.CertificateRequired; } const certChain: Array> = []; for (const certPEM of certPEMChain) { const cert = keysUtils.certFromPEM(certPEM as CertificatePEM); - if (cert == null) return CryptoError.BadCertificate; + if (cert == null) return native.CryptoError.BadCertificate; certChain.push(cert); } const now = new Date(); @@ -666,18 +676,18 @@ async function verifyClientCertificateChain( const cert = certChain[certIndex]; const certNext = certChain[certIndex + 1]; if (leafCert && (now < cert.notBefore || now > cert.notAfter)) { - return CryptoError.CertificateExpired; + return native.CryptoError.CertificateExpired; } const certNodeId = keysUtils.certNodeId(cert); if (certNodeId == null) { - return CryptoError.BadCertificate; + return native.CryptoError.BadCertificate; } const certPublicKey = keysUtils.certPublicKey(cert); if (certPublicKey == null) { - return CryptoError.BadCertificate; + return native.CryptoError.BadCertificate; } if (!(await keysUtils.certNodeSigned(cert))) { - return CryptoError.BadCertificate; + return native.CryptoError.BadCertificate; } if (certNext != null) { if ( @@ -687,7 +697,7 @@ async function verifyClientCertificateChain( keysUtils.certPublicKey(certNext)!, )) ) { - return CryptoError.BadCertificate; + return native.CryptoError.BadCertificate; } } leafCert = false; @@ -868,4 +878,4 @@ export { nodesAuthenticateConnectionReverseDeny, }; -export { encodeNodeId, decodeNodeId } from '../ids'; +export { encodeNodeId, decodeNodeId } from '../ids/index.js'; diff --git a/src/notifications/NotificationsManager.ts b/src/notifications/NotificationsManager.ts index c6fb547505..23d4adaaaf 100644 --- a/src/notifications/NotificationsManager.ts +++ b/src/notifications/NotificationsManager.ts @@ -4,31 +4,28 @@ import type { Notification, NotificationData, NotificationDB, -} from './types'; -import type ACL from '../acl/ACL'; -import type KeyRing from '../keys/KeyRing'; -import type NodeManager from '../nodes/NodeManager'; +} from './types.js'; +import type ACL from '../acl/ACL.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type NodeManager from '../nodes/NodeManager.js'; import type { NodeId, NodeIdEncoded, NotificationIdEncoded, TaskHandlerId, -} from '../ids/types'; -import type { Task, TaskHandler, TaskInfo } from '../tasks/types'; -import type { TaskManager } from '../tasks'; +} from '../ids/types.js'; +import type { Task, TaskHandler, TaskInfo } from '../tasks/types.js'; +import type { TaskManager } from '../tasks/index.js'; import Logger from '@matrixai/logger'; import { IdInternal } from '@matrixai/id'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; -import * as notificationsUtils from './utils'; -import * as notificationsErrors from './errors'; -import * as notificationsEvents from './events'; -import config from '../config'; -import { ErrorPolykeyRemote } from '../network/errors'; -import * as nodesUtils from '../nodes/utils'; -import { never } from '../utils/utils'; +import { createDestroyStartStop } from '@matrixai/async-init'; +import * as notificationsUtils from './utils.js'; +import * as notificationsErrors from './errors.js'; +import * as notificationsEvents from './events.js'; +import config from '../config.js'; +import { ErrorPolykeyRemote } from '../network/errors.js'; +import * as nodesUtils from '../nodes/utils.js'; +import { never } from '../utils/utils.js'; const abortSendNotificationTaskReason = Symbol( 'abort send notification task reason', @@ -37,8 +34,9 @@ const abortSendNotificationTaskReason = Symbol( /** * Manage Node Notifications between Gestalts */ -interface NotificationsManager extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface NotificationsManager + extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new notificationsErrors.ErrorNotificationsRunning(), new notificationsErrors.ErrorNotificationsDestroyed(), { @@ -315,7 +313,9 @@ class NotificationsManager { * Send a notification to another node * The `data` parameter must match one of the NotificationData types outlined in ./types */ - @ready(new notificationsErrors.ErrorNotificationsNotRunning()) + @createDestroyStartStop.ready( + new notificationsErrors.ErrorNotificationsNotRunning(), + ) public async sendNotification( { nodeId, @@ -484,7 +484,9 @@ class NotificationsManager { /** * Read pending notifications in the outbox. */ - @ready(new notificationsErrors.ErrorNotificationsNotRunning()) + @createDestroyStartStop.ready( + new notificationsErrors.ErrorNotificationsNotRunning(), + ) public async *readOutboxNotifications({ seek, seekEnd, @@ -523,7 +525,9 @@ class NotificationsManager { } } - @ready(new notificationsErrors.ErrorNotificationsNotRunning()) + @createDestroyStartStop.ready( + new notificationsErrors.ErrorNotificationsNotRunning(), + ) public async getOutboxNotificationTaskInfoById( notificationId: NotificationId, tran?: DBTransaction, @@ -570,7 +574,9 @@ class NotificationsManager { /** * Clears the pending outbox notifications */ - @ready(new notificationsErrors.ErrorNotificationsNotRunning()) + @createDestroyStartStop.ready( + new notificationsErrors.ErrorNotificationsNotRunning(), + ) public async clearOutboxNotifications(tran?: DBTransaction): Promise { if (tran == null) { return this.db.withTransactionF((tran) => @@ -615,7 +621,9 @@ class NotificationsManager { /** * Receive a notification */ - @ready(new notificationsErrors.ErrorNotificationsNotRunning()) + @createDestroyStartStop.ready( + new notificationsErrors.ErrorNotificationsNotRunning(), + ) public async receiveNotification( notification: Notification, tran?: DBTransaction, @@ -676,7 +684,9 @@ class NotificationsManager { /** * Read a notification */ - @ready(new notificationsErrors.ErrorNotificationsNotRunning()) + @createDestroyStartStop.ready( + new notificationsErrors.ErrorNotificationsNotRunning(), + ) public async *readInboxNotifications({ seek, seekEnd, @@ -727,7 +737,9 @@ class NotificationsManager { * Linearly searches for a GestaltInvite notification from the supplied NodeId. * Returns the notification if found. */ - @ready(new notificationsErrors.ErrorNotificationsNotRunning()) + @createDestroyStartStop.ready( + new notificationsErrors.ErrorNotificationsNotRunning(), + ) public async findGestaltInvite( fromNode: NodeId, tran?: DBTransaction, @@ -751,7 +763,9 @@ class NotificationsManager { /** * Removes all notifications */ - @ready(new notificationsErrors.ErrorNotificationsNotRunning()) + @createDestroyStartStop.ready( + new notificationsErrors.ErrorNotificationsNotRunning(), + ) public async clearInboxNotifications(tran?: DBTransaction): Promise { if (tran == null) { return this.db.withTransactionF((tran) => diff --git a/src/notifications/errors.ts b/src/notifications/errors.ts index d4e66b213f..b5bc30d3f0 100644 --- a/src/notifications/errors.ts +++ b/src/notifications/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorNotifications extends ErrorPolykey {} diff --git a/src/notifications/events.ts b/src/notifications/events.ts index cf01121cda..9d593d9876 100644 --- a/src/notifications/events.ts +++ b/src/notifications/events.ts @@ -1,5 +1,5 @@ -import type { Notification } from './types'; -import EventPolykey from '../EventPolykey'; +import type { Notification } from './types.js'; +import EventPolykey from '../EventPolykey.js'; abstract class EventNotificationsManager extends EventPolykey {} diff --git a/src/notifications/index.ts b/src/notifications/index.ts index 9fd78f3d23..4116878905 100644 --- a/src/notifications/index.ts +++ b/src/notifications/index.ts @@ -1,5 +1,5 @@ -export { default as NotificationsManager } from './NotificationsManager'; -export * as utils from './utils'; -export * as types from './types'; -export * as errors from './errors'; -export * as events from './events'; +export { default as NotificationsManager } from './NotificationsManager.js'; +export * as utils from './utils.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; diff --git a/src/notifications/types.ts b/src/notifications/types.ts index 2bd2508298..66da089c69 100644 --- a/src/notifications/types.ts +++ b/src/notifications/types.ts @@ -1,6 +1,10 @@ -import type { Opaque } from '../types'; -import type { NotificationId, NotificationIdEncoded } from '../ids/types'; -import type { VaultName, VaultActions, VaultIdEncoded } from '../vaults/types'; +import type { Opaque } from '../types.js'; +import type { NotificationId, NotificationIdEncoded } from '../ids/types.js'; +import type { + VaultName, + VaultActions, + VaultIdEncoded, +} from '../vaults/types.js'; type GestaltInvite = { type: 'GestaltInvite'; diff --git a/src/notifications/utils.ts b/src/notifications/utils.ts index 8c94eb1b22..457696c46f 100644 --- a/src/notifications/utils.ts +++ b/src/notifications/utils.ts @@ -4,21 +4,21 @@ import type { VaultShare, Notification, SignedNotification, -} from './types'; -import type { NodeId, VaultId, NotificationId } from '../ids/types'; -import type { KeyPairLocked } from '../keys/types'; +} from './types.js'; +import type { NodeId, VaultId, NotificationId } from '../ids/types.js'; +import type { KeyPairLocked } from '../keys/types.js'; import { IdInternal } from '@matrixai/id'; -import * as sortableIdUtils from '@matrixai/id/dist/IdSortable'; -import * as notificationsErrors from './errors'; -import { createNotificationIdGenerator } from '../ids'; -import { vaultActions } from '../vaults/types'; -import { never } from '../utils'; -import Token from '../tokens/Token'; -import * as nodesUtils from '../nodes/utils'; -import * as keysUtils from '../keys/utils'; -import * as validationErrors from '../validation/errors'; -import * as utils from '../utils'; -import * as ids from '../ids'; +import { idSortable } from '@matrixai/id'; +import * as notificationsErrors from './errors.js'; +import { createNotificationIdGenerator } from '../ids/index.js'; +import { vaultActions } from '../vaults/types.js'; +import { never } from '../utils/index.js'; +import Token from '../tokens/Token.js'; +import * as nodesUtils from '../nodes/utils.js'; +import * as keysUtils from '../keys/utils/index.js'; +import * as validationErrors from '../validation/errors.js'; +import * as utils from '../utils/index.js'; +import * as ids from '../ids/index.js'; function constructGestaltInviteMessage(nodeId: NodeId): string { return `Keynode with ID ${nodeId} has invited this Keynode to join their Gestalt. Accept this invitation by typing the command: xxx`; @@ -221,7 +221,7 @@ function extractFromSeek( let timestamp: number | undefined; if (seek instanceof IdInternal) { notificationId = seek; - timestamp = sortableIdUtils.extractTs(seek.toBuffer()) * 1000; + timestamp = idSortable.extractTs(seek.toBuffer()) * 1000; } else if (typeof seek === 'number') { timestamp = seek; notificationId = ids.generateNotificationIdFromTimestamp( @@ -255,4 +255,4 @@ export { extractFromSeek, }; -export { encodeNotificationId, decodeNotificationId } from '../ids'; +export { encodeNotificationId, decodeNotificationId } from '../ids/index.js'; diff --git a/src/schema/Schema.ts b/src/schema/Schema.ts index 10ffaeff38..4d767696fd 100644 --- a/src/schema/Schema.ts +++ b/src/schema/Schema.ts @@ -1,16 +1,16 @@ -import type { StateVersion } from './types'; -import type { FileSystem } from '../types'; -import path from 'path'; +import type { StateVersion } from './types.js'; +import type { FileSystem } from '../types.js'; +import path from 'node:path'; import Logger from '@matrixai/logger'; -import { CreateDestroyStartStop } from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { RWLockWriter } from '@matrixai/async-locks'; -import * as schemaErrors from './errors'; -import * as schemaEvents from './events'; -import * as utils from '../utils'; -import config from '../config'; +import * as schemaErrors from './errors.js'; +import * as schemaEvents from './events.js'; +import * as utils from '../utils/index.js'; +import config from '../config.js'; -interface Schema extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface Schema extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new schemaErrors.ErrorSchemaRunning(), new schemaErrors.ErrorSchemaDestroyed(), { @@ -24,7 +24,7 @@ class Schema { public static async createSchema({ statePath, stateVersion = config.stateVersion as StateVersion, - fs = require('fs'), + fs, logger = new Logger(this.name), fresh = false, }: { @@ -35,6 +35,7 @@ class Schema { fresh?: boolean; }): Promise { logger.info(`Creating ${this.name}`); + fs = await utils.importFS(fs); const schema = new this({ statePath, stateVersion, @@ -56,12 +57,12 @@ class Schema { public constructor({ statePath, stateVersion = config.stateVersion as StateVersion, - fs = require('fs'), + fs, logger, }: { statePath: string; stateVersion?: StateVersion; - fs?: FileSystem; + fs: FileSystem; logger?: Logger; }) { this.logger = logger ?? new Logger(this.constructor.name); diff --git a/src/schema/errors.ts b/src/schema/errors.ts index c1d9e9ca91..ab45375d88 100644 --- a/src/schema/errors.ts +++ b/src/schema/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorSchema extends ErrorPolykey {} diff --git a/src/schema/events.ts b/src/schema/events.ts index 7e04ee914b..0b9cbafa08 100644 --- a/src/schema/events.ts +++ b/src/schema/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventSchema extends EventPolykey {} diff --git a/src/schema/index.ts b/src/schema/index.ts index a76e576c26..a5867b1275 100644 --- a/src/schema/index.ts +++ b/src/schema/index.ts @@ -1,4 +1,4 @@ -export { default as Schema } from './Schema'; -export * as errors from './errors'; -export * as types from './types'; -export * as events from './events'; +export { default as Schema } from './Schema.js'; +export * as errors from './errors.js'; +export * as types from './types.js'; +export * as events from './events.js'; diff --git a/src/schema/migrations/index.ts b/src/schema/migrations/index.ts index 678ccb3feb..24f9207a1e 100644 --- a/src/schema/migrations/index.ts +++ b/src/schema/migrations/index.ts @@ -13,7 +13,7 @@ * be copied back * @module */ -import type { StateVersion, Migration } from '../types'; +import type { StateVersion, Migration } from '../types.js'; const migrations: Map = new Map(); diff --git a/src/schema/types.ts b/src/schema/types.ts index f96bf783a0..799fbd037d 100644 --- a/src/schema/types.ts +++ b/src/schema/types.ts @@ -1,4 +1,4 @@ -import type { Opaque } from '../types'; +import type { Opaque } from '../types.js'; type StateVersion = Opaque<'StateVersion', number>; diff --git a/src/sessions/Session.ts b/src/sessions/Session.ts index c185945f9d..9e68b08ba3 100644 --- a/src/sessions/Session.ts +++ b/src/sessions/Session.ts @@ -1,14 +1,14 @@ -import type { SessionToken } from './types'; -import type { FileSystem } from '../types'; +import type { SessionToken } from './types.js'; +import type { FileHandle, FileSystem } from '../types.js'; import Logger from '@matrixai/logger'; -import { CreateDestroyStartStop } from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import lock from 'fd-lock'; -import * as sessionErrors from './errors'; -import * as events from './events'; -import * as utils from '../utils'; +import * as sessionErrors from './errors.js'; +import * as events from './events.js'; +import * as utils from '../utils/index.js'; -interface Session extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface Session extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new sessionErrors.ErrorSessionRunning(), new sessionErrors.ErrorSessionDestroyed(), { @@ -23,7 +23,7 @@ interface Session extends CreateDestroyStartStop {} class Session { static async createSession({ sessionTokenPath, - fs = require('fs'), + fs, logger = new Logger(this.name), sessionToken, fresh = false, @@ -36,6 +36,7 @@ class Session { }): Promise { logger.info(`Creating ${this.name}`); logger.info(`Setting session token path to ${sessionTokenPath}`); + fs = await utils.importFS(fs); const session = new this({ sessionTokenPath, fs, @@ -100,7 +101,7 @@ class Session { } public async readToken(): Promise { - let sessionTokenFile; + let sessionTokenFile: FileHandle | undefined; try { sessionTokenFile = await this.fs.promises.open( this.sessionTokenPath, @@ -131,7 +132,7 @@ class Session { } public async writeToken(sessionToken: SessionToken): Promise { - let sessionTokenFile; + let sessionTokenFile: FileHandle | undefined; try { // Cannot use 'w', it truncates immediately // should truncate only while holding the lock diff --git a/src/sessions/SessionManager.ts b/src/sessions/SessionManager.ts index 59ec967aab..f8a15098da 100644 --- a/src/sessions/SessionManager.ts +++ b/src/sessions/SessionManager.ts @@ -1,21 +1,19 @@ import type { DB, DBTransaction, LevelPath } from '@matrixai/db'; -import type { SessionToken } from './types'; -import type KeyRing from '../keys/KeyRing'; -import type { Key } from '../keys/types'; +import type { SessionToken } from './types.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type { Key } from '../keys/types.js'; import Logger from '@matrixai/logger'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { withF } from '@matrixai/resources'; -import * as sessionsUtils from './utils'; -import * as sessionsErrors from './errors'; -import * as sessionsEvents from './events'; -import * as keysUtils from '../keys/utils'; -import * as nodesUtils from '../nodes/utils'; +import * as sessionsUtils from './utils.js'; +import * as sessionsErrors from './errors.js'; +import * as sessionsEvents from './events.js'; +import * as keysUtils from '../keys/utils/index.js'; +import * as nodesUtils from '../nodes/utils.js'; -interface SessionManager extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface SessionManager + extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new sessionsErrors.ErrorSessionManagerRunning(), new sessionsErrors.ErrorSessionManagerDestroyed(), { @@ -101,7 +99,9 @@ class SessionManager { this.logger.info(`Destroyed ${this.constructor.name}`); } - @ready(new sessionsErrors.ErrorSessionManagerNotRunning()) + @createDestroyStartStop.ready( + new sessionsErrors.ErrorSessionManagerNotRunning(), + ) public async resetKey(tran?: DBTransaction): Promise { const tranOrDb = tran ?? this.db; const key = keysUtils.generateKey(); @@ -114,7 +114,9 @@ class SessionManager { * @param expiry Seconds from now or default * @param tran */ - @ready(new sessionsErrors.ErrorSessionManagerNotRunning()) + @createDestroyStartStop.ready( + new sessionsErrors.ErrorSessionManagerNotRunning(), + ) public async createToken( expiry: number | undefined = this.expiry, tran?: DBTransaction, @@ -131,7 +133,9 @@ class SessionManager { return await sessionsUtils.createSessionToken(payload, key!, expiry); } - @ready(new sessionsErrors.ErrorSessionManagerNotRunning()) + @createDestroyStartStop.ready( + new sessionsErrors.ErrorSessionManagerNotRunning(), + ) public async verifyToken( token: SessionToken, tran?: DBTransaction, diff --git a/src/sessions/errors.ts b/src/sessions/errors.ts index a09d06a362..11e3fe91f8 100644 --- a/src/sessions/errors.ts +++ b/src/sessions/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorSessions extends ErrorPolykey {} diff --git a/src/sessions/events.ts b/src/sessions/events.ts index f2625cd6b9..f1b09ee9ed 100644 --- a/src/sessions/events.ts +++ b/src/sessions/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventSessions extends EventPolykey {} diff --git a/src/sessions/index.ts b/src/sessions/index.ts index e027a4bef0..aa69e660a5 100644 --- a/src/sessions/index.ts +++ b/src/sessions/index.ts @@ -1,6 +1,6 @@ -export { default as SessionManager } from './SessionManager'; -export { default as Session } from './Session'; -export * as errors from './errors'; -export * as types from './types'; -export * as utils from './utils'; -export * as events from './events'; +export { default as SessionManager } from './SessionManager.js'; +export { default as Session } from './Session.js'; +export * as errors from './errors.js'; +export * as types from './types.js'; +export * as utils from './utils.js'; +export * as events from './events.js'; diff --git a/src/sessions/types.ts b/src/sessions/types.ts index e3a17ee1f2..5f6d9e8d5d 100644 --- a/src/sessions/types.ts +++ b/src/sessions/types.ts @@ -1,4 +1,4 @@ -import type { Opaque } from '../types'; +import type { Opaque } from '../types.js'; type SessionToken = Opaque<'SessionToken', string>; diff --git a/src/sessions/utils.ts b/src/sessions/utils.ts index 6c93f6e425..8bb535d116 100644 --- a/src/sessions/utils.ts +++ b/src/sessions/utils.ts @@ -1,7 +1,7 @@ -import type { SessionToken } from './types'; -import type { TokenPayload } from '../tokens/types'; -import type { Key } from '../keys/types'; -import Token from '../tokens/Token'; +import type { SessionToken } from './types.js'; +import type { TokenPayload } from '../tokens/types.js'; +import type { Key } from '../keys/types.js'; +import Token from '../tokens/Token.js'; /** * Create session token diff --git a/src/sigchain/Sigchain.ts b/src/sigchain/Sigchain.ts index 7e95a729be..1762a5f93f 100644 --- a/src/sigchain/Sigchain.ts +++ b/src/sigchain/Sigchain.ts @@ -1,27 +1,27 @@ import type { DB, DBTransaction, LevelPath, KeyPath } from '@matrixai/db'; -import type { ClaimInput } from './types'; -import type KeyRing from '../keys/KeyRing'; -import type { TokenSignature, TokenHeaderSignatureJSON } from '../tokens/types'; +import type { ClaimInput } from './types.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type { + TokenSignature, + TokenHeaderSignatureJSON, +} from '../tokens/types.js'; import type { ClaimId, Claim, ClaimHeaderSignature, SignedClaim, -} from '../claims/types'; +} from '../claims/types.js'; import Logger from '@matrixai/logger'; import { IdInternal } from '@matrixai/id'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; -import * as sigchainErrors from './errors'; -import * as sigchainEvents from './events'; -import Token from '../tokens/Token'; -import * as claimsUtils from '../claims/utils'; -import * as utils from '../utils'; +import { createDestroyStartStop } from '@matrixai/async-init'; +import * as sigchainErrors from './errors.js'; +import * as sigchainEvents from './events.js'; +import Token from '../tokens/Token.js'; +import * as claimsUtils from '../claims/utils.js'; +import * as utils from '../utils/index.js'; -interface Sigchain extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface Sigchain extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new sigchainErrors.ErrorSigchainRunning(), new sigchainErrors.ErrorSigchainDestroyed(), { @@ -133,7 +133,11 @@ class Sigchain { /** * Gets the last claim ID for preserving monotonicity over restarts */ - @ready(new sigchainErrors.ErrorSigchainNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new sigchainErrors.ErrorSigchainNotRunning(), + false, + ['starting'], + ) public async getLastClaimId( tran?: DBTransaction, ): Promise { @@ -148,7 +152,11 @@ class Sigchain { /** * Gets the last sequence number for preserving monotonicity over restarts */ - @ready(new sigchainErrors.ErrorSigchainNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new sigchainErrors.ErrorSigchainNotRunning(), + false, + ['starting'], + ) public async getLastSequenceNumber( tran?: DBTransaction, ): Promise { @@ -162,7 +170,7 @@ class Sigchain { * Call this method when the `KeyRing` changes * This should be replaced with rxjs later */ - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async onKeyRingChange() { const lastClaimId = await this.getLastClaimId(); this.generateClaimId = claimsUtils.createClaimIdGenerator( @@ -171,7 +179,7 @@ class Sigchain { ); } - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async getLastClaim( tran?: DBTransaction, ): Promise<[ClaimId, Claim] | undefined> { @@ -184,7 +192,7 @@ class Sigchain { return; } - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async getLastSignedClaim( tran?: DBTransaction, ): Promise<[ClaimId, SignedClaim] | undefined> { @@ -203,7 +211,7 @@ class Sigchain { /** * Get a claim according to the `ClaimId` */ - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async getClaim( claimId: ClaimId, tran?: DBTransaction, @@ -217,7 +225,7 @@ class Sigchain { /** * Get a signed claim according to the `ClaimId` */ - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async getSignedClaim( claimId: ClaimId, tran?: DBTransaction, @@ -244,7 +252,7 @@ class Sigchain { /** * Get a claim signatures according to the `ClaimId` */ - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async getSignatures( claimId: ClaimId, tran?: DBTransaction, @@ -278,7 +286,7 @@ class Sigchain { /** * Get claims */ - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async *getClaims( { order = 'asc', @@ -326,7 +334,7 @@ class Sigchain { /** * Get signed claims */ - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async *getSignedClaims( { order = 'asc', @@ -384,7 +392,7 @@ class Sigchain { * Remember that `undefined` properties are deleted. * While `undefined` values in arrays are converted to `null`. */ - @ready(new sigchainErrors.ErrorSigchainNotRunning()) + @createDestroyStartStop.ready(new sigchainErrors.ErrorSigchainNotRunning()) public async addClaim( data: ClaimInput, date: Date = new Date(), diff --git a/src/sigchain/errors.ts b/src/sigchain/errors.ts index 2277bc93bb..ae6c45e769 100644 --- a/src/sigchain/errors.ts +++ b/src/sigchain/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorSigchain extends ErrorPolykey {} diff --git a/src/sigchain/events.ts b/src/sigchain/events.ts index 55ed4e27fe..e342c3e63b 100644 --- a/src/sigchain/events.ts +++ b/src/sigchain/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventSigchain extends EventPolykey {} diff --git a/src/sigchain/index.ts b/src/sigchain/index.ts index 5a0a2f74f7..12625d6d4e 100644 --- a/src/sigchain/index.ts +++ b/src/sigchain/index.ts @@ -1,4 +1,4 @@ -export { default as Sigchain } from './Sigchain'; -export * as types from './types'; -export * as errors from './errors'; -export * as events from './events'; +export { default as Sigchain } from './Sigchain.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; diff --git a/src/sigchain/types.ts b/src/sigchain/types.ts index e062cac0f9..a83a6fea5f 100644 --- a/src/sigchain/types.ts +++ b/src/sigchain/types.ts @@ -1,5 +1,5 @@ -import type { TokenPayload } from '../tokens/types'; -import type { ClaimDefault } from '../claims/types'; +import type { TokenPayload } from '../tokens/types.js'; +import type { ClaimDefault } from '../claims/types.js'; /** * During the creation of `Claim`, only properties that are not automatically diff --git a/src/status/Status.ts b/src/status/Status.ts index c4d7671e25..5510a830af 100644 --- a/src/status/Status.ts +++ b/src/status/Status.ts @@ -4,23 +4,23 @@ import type { StatusLive, StatusStopping, StatusDead, -} from './types'; -import type { FileSystem, FileHandle } from '../types'; +} from './types.js'; +import type { FileSystem, FileHandle } from '../types.js'; import type { PromiseCancellable } from '@matrixai/async-cancellable'; import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts'; import Logger from '@matrixai/logger'; import lock from 'fd-lock'; -import { StartStop, ready } from '@matrixai/async-init/dist/StartStop'; -import { context, timedCancellable } from '@matrixai/contexts/dist/decorators'; -import * as statusUtils from './utils'; -import * as statusErrors from './errors'; -import * as statusEvents from './events'; -import { sleep, poll } from '../utils'; -import * as errors from '../errors'; -import { utils as nodesUtils } from '../nodes'; +import { startStop } from '@matrixai/async-init'; +import { decorators } from '@matrixai/contexts'; +import * as statusUtils from './utils.js'; +import * as statusErrors from './errors.js'; +import * as statusEvents from './events.js'; +import { sleep, poll } from '../utils/index.js'; +import * as errors from '../errors.js'; +import { utils as nodesUtils } from '../nodes/index.js'; -interface Status extends StartStop {} -@StartStop({ +interface Status extends startStop.StartStop {} +@startStop.StartStop({ eventStart: statusEvents.EventStatusStart, eventStarted: statusEvents.EventStatusStarted, eventStop: statusEvents.EventStatusStop, @@ -37,12 +37,12 @@ class Status { public constructor({ statusPath, statusLockPath, - fs = require('fs'), + fs, logger, }: { statusPath: string; statusLockPath: string; - fs?: FileSystem; + fs: FileSystem; logger?: Logger; }) { this.logger = logger ?? new Logger(this.constructor.name); @@ -75,7 +75,7 @@ class Status { this.logger.info(`${this.constructor.name} is STARTING`); } - @ready(new statusErrors.ErrorStatusNotRunning(), true) + @startStop.ready(new statusErrors.ErrorStatusNotRunning(), true) public async finishStart(data: StatusLive['data']): Promise { this.logger.info(`Finish ${this.constructor.name} STARTING`); await this.writeStatus({ @@ -85,7 +85,7 @@ class Status { this.logger.info(`${this.constructor.name} is LIVE`); } - @ready(new statusErrors.ErrorStatusNotRunning(), true) + @startStop.ready(new statusErrors.ErrorStatusNotRunning(), true) public async beginStop(data: StatusStopping['data']): Promise { this.logger.info(`Begin ${this.constructor.name} STOPPING`); await this.writeStatus({ @@ -112,7 +112,7 @@ class Status { * This can be used without running Status */ public async readStatus(): Promise { - let statusFile; + let statusFile: FileHandle | undefined; try { try { statusFile = await this.fs.promises.open(this.statusPath, 'r'); @@ -133,7 +133,7 @@ class Status { while (!lock(statusFile.fd)) { await sleep(2); } - let statusData; + let statusData: string; try { statusData = (await statusFile.readFile('utf-8')).trim(); } catch (e) { @@ -150,7 +150,7 @@ class Status { if (statusData === '') { return; } - let statusInfo; + let statusInfo: StatusInfo | undefined; try { statusInfo = JSON.parse(statusData, this.statusReviver); } catch (e) { @@ -177,7 +177,7 @@ class Status { protected async writeStatus(statusInfo: StatusInfo): Promise { this.logger.info(`Writing ${this.constructor.name} to ${this.statusPath}`); - let statusFile; + let statusFile: FileHandle | undefined; try { // Cannot use 'w', it truncates immediately // should truncate only while holding the lock @@ -216,12 +216,12 @@ class Status { } } - @ready(new statusErrors.ErrorStatusNotRunning()) + @startStop.ready(new statusErrors.ErrorStatusNotRunning()) public async updateStatusLive( data: Partial, ): Promise { this.logger.info(`Updating ${this.constructor.name} LIVE`); - let statusFile; + let statusFile: FileHandle | undefined; try { try { statusFile = await this.fs.promises.open(this.statusPath, 'r+'); @@ -239,7 +239,7 @@ class Status { while (!lock(statusFile.fd)) { await sleep(2); } - let statusData; + let statusData: string; try { statusData = (await statusFile.readFile('utf-8')).trim(); } catch (e) { @@ -253,7 +253,7 @@ class Status { cause: e, }); } - let statusInfo; + let statusInfo: StatusInfo | undefined; try { statusInfo = JSON.parse(statusData, this.statusReviver); } catch (e) { @@ -306,12 +306,12 @@ class Status { status: StatusInfo['status'], ctx?: Partial, ): PromiseCancellable; - @timedCancellable(true) + @decorators.timedCancellable(true) public async waitFor( status: StatusInfo['status'], - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { - let statusInfo; + let statusInfo: StatusInfo | undefined; try { statusInfo = await poll( async () => { @@ -327,8 +327,7 @@ class Status { ) { return true; } - if (statusInfo?.status === status) return true; - return false; + return statusInfo?.status === status; }, 50, ctx, diff --git a/src/status/errors.ts b/src/status/errors.ts index 746f493b69..2c427cf3fe 100644 --- a/src/status/errors.ts +++ b/src/status/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorStatus extends ErrorPolykey {} diff --git a/src/status/events.ts b/src/status/events.ts index ec36ba92bf..cbe921706f 100644 --- a/src/status/events.ts +++ b/src/status/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventStatus extends EventPolykey {} diff --git a/src/status/index.ts b/src/status/index.ts index 9797c95937..7e9f9913b9 100644 --- a/src/status/index.ts +++ b/src/status/index.ts @@ -1,5 +1,5 @@ -export { default as Status } from './Status'; -export * as types from './types'; -export * as errors from './errors'; -export * as utils from './utils'; -export * as events from './events'; +export { default as Status } from './Status.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; +export * as utils from './utils.js'; +export * as events from './events.js'; diff --git a/src/status/types.ts b/src/status/types.ts index 633acdd893..7b985aac3d 100644 --- a/src/status/types.ts +++ b/src/status/types.ts @@ -1,4 +1,4 @@ -import type { NodeId } from '../ids/types'; +import type { NodeId } from '../ids/types.js'; type StatusStarting = { status: 'STARTING'; diff --git a/src/status/utils.ts b/src/status/utils.ts index ab6e820ce3..a037953e43 100644 --- a/src/status/utils.ts +++ b/src/status/utils.ts @@ -1,9 +1,10 @@ import type { JSONSchemaType, ValidateFunction } from 'ajv'; -import type { StatusInfo } from './types'; +import type { StatusInfo } from './types.js'; import Ajv from 'ajv'; import StatusSchema from './StatusSchema.json'; -const ajv = new Ajv(); +// @ts-ignore Ajv is improperly exported for ESM +const ajv = new Ajv.default(); const statusSchema = StatusSchema as JSONSchemaType; const statusValidate: ValidateFunction = ajv.compile(statusSchema); diff --git a/src/tasks/TaskEvent.ts b/src/tasks/TaskEvent.ts index 54439c1f9a..01e1f09066 100644 --- a/src/tasks/TaskEvent.ts +++ b/src/tasks/TaskEvent.ts @@ -1,4 +1,4 @@ -import type { TaskIdEncoded } from './types'; +import type { TaskIdEncoded } from './types.js'; class TaskEvent extends Event { public detail: diff --git a/src/tasks/TaskManager.ts b/src/tasks/TaskManager.ts index 435f04db2f..907f654889 100644 --- a/src/tasks/TaskManager.ts +++ b/src/tasks/TaskManager.ts @@ -12,29 +12,26 @@ import type { TaskParameters, TaskTimestamp, TaskPath, -} from './types'; +} from './types.js'; import Logger from '@matrixai/logger'; import { IdInternal } from '@matrixai/id'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { Lock } from '@matrixai/async-locks'; import { PromiseCancellable } from '@matrixai/async-cancellable'; -import { extractTs } from '@matrixai/id/dist/IdSortable'; +import { idSortable } from '@matrixai/id'; import { Timer } from '@matrixai/timer'; -import TaskEvent from './TaskEvent'; -import * as tasksUtils from './utils'; -import * as tasksErrors from './errors'; -import * as tasksEvents from './events'; -import * as utils from '../utils'; +import TaskEvent from './TaskEvent.js'; +import * as tasksUtils from './utils.js'; +import * as tasksErrors from './errors.js'; +import * as tasksEvents from './events.js'; +import * as utils from '../utils/index.js'; const abortSchedulingLoopReason = Symbol('abort scheduling loop reason'); const abortQueuingLoopReason = Symbol('abort queuing loop reason'); const cancelTimerReason = Symbol('cancel timer reason'); -interface TaskManager extends CreateDestroyStartStop {} -@CreateDestroyStartStop( +interface TaskManager extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new tasksErrors.ErrorTaskManagerRunning(), new tasksErrors.ErrorTaskManagerDestroyed(), { @@ -244,7 +241,11 @@ class TaskManager { * This call is idempotent * Use this when `Tasks` is started in lazy mode */ - @ready(new tasksErrors.ErrorTaskManagerNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new tasksErrors.ErrorTaskManagerNotRunning(), + false, + ['starting'], + ) public async startProcessing(): Promise { await Promise.all([this.startScheduling(), this.startQueueing()]); } @@ -312,7 +313,11 @@ class TaskManager { this.handlers.delete(handlerId); } - @ready(new tasksErrors.ErrorTaskManagerNotRunning(), false, ['starting']) + @createDestroyStartStop.ready( + new tasksErrors.ErrorTaskManagerNotRunning(), + false, + ['starting'], + ) public async getLastTaskId( tran?: DBTransaction, ): Promise { @@ -324,7 +329,7 @@ class TaskManager { return IdInternal.fromBuffer(lastTaskIdBuffer); } - @ready(new tasksErrors.ErrorTaskManagerNotRunning()) + @createDestroyStartStop.ready(new tasksErrors.ErrorTaskManagerNotRunning()) public async getTask( taskId: TaskId, lazy: boolean = false, @@ -395,7 +400,7 @@ class TaskManager { }; } - @ready(new tasksErrors.ErrorTaskManagerNotRunning()) + @createDestroyStartStop.ready(new tasksErrors.ErrorTaskManagerNotRunning()) public async *getTasks( order: 'asc' | 'desc' = 'asc', lazy: boolean = false, @@ -429,7 +434,7 @@ class TaskManager { } } - @ready(new tasksErrors.ErrorTaskManagerNotRunning()) + @createDestroyStartStop.ready(new tasksErrors.ErrorTaskManagerNotRunning()) public getTaskPromise( taskId: TaskId, tran?: DBTransaction, @@ -500,7 +505,7 @@ class TaskManager { * If `this.schedulingLoop` isn't running, then this will not * attempt to reset the `this.schedulingTimer` */ - @ready(new tasksErrors.ErrorTaskManagerNotRunning()) + @createDestroyStartStop.ready(new tasksErrors.ErrorTaskManagerNotRunning()) public async scheduleTask( { handlerId, @@ -546,7 +551,9 @@ class TaskManager { const taskIdBuffer = taskId.toBuffer(); // Timestamp extracted from `IdSortable` is a floating point in seconds // with subsecond fractionals, multiply it by 1000 gives us milliseconds - const taskTimestamp = Math.trunc(extractTs(taskId) * 1000) as TaskTimestamp; + const taskTimestamp = Math.trunc( + idSortable.extractTs(taskId) * 1000, + ) as TaskTimestamp; const taskPriority = tasksUtils.toPriority(priority); const taskDelay = tasksUtils.toDelay(delay); const taskDeadline = tasksUtils.toDeadline(deadline); @@ -614,7 +621,7 @@ class TaskManager { }; } - @ready(new tasksErrors.ErrorTaskManagerNotRunning()) + @createDestroyStartStop.ready(new tasksErrors.ErrorTaskManagerNotRunning()) public async updateTask( taskId: TaskId, taskPatch: Partial<{ diff --git a/src/tasks/errors.ts b/src/tasks/errors.ts index 3e011a7fbb..a60e748d4e 100644 --- a/src/tasks/errors.ts +++ b/src/tasks/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorTasks extends ErrorPolykey {} diff --git a/src/tasks/events.ts b/src/tasks/events.ts index 7658fc105f..e323736a59 100644 --- a/src/tasks/events.ts +++ b/src/tasks/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventTasks extends EventPolykey {} diff --git a/src/tasks/index.ts b/src/tasks/index.ts index 78fb255da1..97b2eb464e 100644 --- a/src/tasks/index.ts +++ b/src/tasks/index.ts @@ -1,5 +1,5 @@ -export { default as TaskManager } from './TaskManager'; -export * as types from './types'; -export * as utils from './utils'; -export * as errors from './errors'; -export * as events from './events'; +export { default as TaskManager } from './TaskManager.js'; +export * as types from './types.js'; +export * as utils from './utils.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; diff --git a/src/tasks/types.ts b/src/tasks/types.ts index a58dd30106..b6ef034b93 100644 --- a/src/tasks/types.ts +++ b/src/tasks/types.ts @@ -3,10 +3,10 @@ import type { TaskId, TaskIdString, TaskIdEncoded, -} from '../ids/types'; +} from '../ids/types.js'; import type { PromiseCancellable } from '@matrixai/async-cancellable'; import type { ContextTimed } from '@matrixai/contexts'; -import type { Opaque } from '../types'; +import type { Opaque } from '../types.js'; type TaskHandler = ( ctx: ContextTimed, diff --git a/src/tasks/utils.ts b/src/tasks/utils.ts index c6b3ebe4ca..fe5b6a5e46 100644 --- a/src/tasks/utils.ts +++ b/src/tasks/utils.ts @@ -1,5 +1,9 @@ -import type { TaskPriority, TaskDelay, TaskDeadline } from './types'; -import { createTaskIdGenerator, encodeTaskId, decodeTaskId } from '../ids'; +import type { TaskPriority, TaskDelay, TaskDeadline } from './types.js'; +import { + createTaskIdGenerator, + encodeTaskId, + decodeTaskId, +} from '../ids/index.js'; /** * Encodes delay milliseconds diff --git a/src/tokens/Token.ts b/src/tokens/Token.ts index 82c9f61e7d..f11ad1e1d3 100644 --- a/src/tokens/Token.ts +++ b/src/tokens/Token.ts @@ -6,15 +6,15 @@ import type { TokenHeaderSignatureEncoded, SignedToken, SignedTokenEncoded, -} from './types'; -import type { Key, PublicKey, PrivateKey, KeyPair } from '../keys/types'; -import type { POJO } from '../types'; -import type { Signature } from '../keys/types'; -import * as tokensUtils from './utils'; -import * as tokensErrors from './errors'; -import * as ids from '../ids'; -import * as keysUtils from '../keys/utils'; -import * as validationErrors from '../validation/errors'; +} from './types.js'; +import type { Key, PublicKey, PrivateKey, KeyPair } from '../keys/types.js'; +import type { POJO } from '../types.js'; +import type { Signature } from '../keys/types.js'; +import * as tokensUtils from './utils.js'; +import * as tokensErrors from './errors.js'; +import * as ids from '../ids/index.js'; +import * as keysUtils from '../keys/utils/index.js'; +import * as validationErrors from '../validation/errors.js'; /** * Token represents a single token with methods to sign and verify. diff --git a/src/tokens/errors.ts b/src/tokens/errors.ts index 8578543572..d8424888d7 100644 --- a/src/tokens/errors.ts +++ b/src/tokens/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorTokens extends ErrorPolykey {} diff --git a/src/tokens/index.ts b/src/tokens/index.ts index 94e565c5a8..0457acdcce 100644 --- a/src/tokens/index.ts +++ b/src/tokens/index.ts @@ -4,8 +4,8 @@ * It does not cover non-JWT JWS nor JWE nor JWK. * @module */ -export { default as Token } from './Token'; -export * as utils from './utils'; -export * as errors from './errors'; -export * as types from './types'; -export * as schemas from './schemas'; +export { default as Token } from './Token.js'; +export * as utils from './utils.js'; +export * as errors from './errors.js'; +export * as types from './types.js'; +export * as schemas from './schemas/index.js'; diff --git a/src/tokens/schemas/index.ts b/src/tokens/schemas/index.ts index 1b13c2b383..69848d6aac 100644 --- a/src/tokens/schemas/index.ts +++ b/src/tokens/schemas/index.ts @@ -1,9 +1,10 @@ import type { ValidateFunction } from 'ajv'; -import type { SignedTokenEncoded } from '../types'; +import type { SignedTokenEncoded } from '../types.js'; import Ajv from 'ajv'; import SignedTokenEncodedSchema from './SignedTokenEncodedSchema.json'; -const ajv = new Ajv(); +// @ts-ignore: Ajv exports is function improperly for ESM +const ajv = new Ajv.default(); const validateSignedTokenEncoded: ValidateFunction = ajv.compile(SignedTokenEncodedSchema); diff --git a/src/tokens/types.ts b/src/tokens/types.ts index a0b6ef8bfb..75452a3b8f 100644 --- a/src/tokens/types.ts +++ b/src/tokens/types.ts @@ -1,6 +1,6 @@ -import type { Opaque, JSONValue } from '../types'; -import type { Signature, MAC } from '../keys/types'; -import type { NodeIdEncoded } from '../ids/types'; +import type { Opaque, JSONValue } from '../types.js'; +import type { Signature, MAC } from '../keys/types.js'; +import type { NodeIdEncoded } from '../ids/types.js'; /** * Token based on JWT specification. diff --git a/src/tokens/utils.ts b/src/tokens/utils.ts index c19d0dec49..30308dd73b 100644 --- a/src/tokens/utils.ts +++ b/src/tokens/utils.ts @@ -9,15 +9,16 @@ import type { SignedToken, SignedTokenEncoded, TokenHeaderSignatureEncoded, -} from './types'; +} from './types.js'; import { Buffer } from 'buffer'; import canonicalize from 'canonicalize'; -import * as ids from '../ids'; -import * as validationErrors from '../validation/errors'; -import * as keysUtils from '../keys/utils'; -import * as utils from '../utils'; +import * as ids from '../ids/index.js'; +import * as validationErrors from '../validation/errors.js'; +import * as keysUtils from '../keys/utils/index.js'; +import * as utils from '../utils/index.js'; function generateTokenPayload(payload: TokenPayload): TokenPayloadEncoded { + // @ts-ignore: canonicalize exports is function improperly for ESM const payloadJSON = canonicalize(payload)!; const payloadData = Buffer.from(payloadJSON, 'utf-8'); return payloadData.toString('base64url') as TokenPayloadEncoded; @@ -26,6 +27,7 @@ function generateTokenPayload(payload: TokenPayload): TokenPayloadEncoded { function generateTokenProtectedHeader( header: TokenProtectedHeader, ): TokenProtectedHeaderEncoded { + // @ts-ignore: canonicalize exports is function improperly for ESM const headerJSON = canonicalize(header)!; const headerData = Buffer.from(headerJSON, 'utf-8'); return headerData.toString('base64url') as TokenProtectedHeaderEncoded; diff --git a/src/types.ts b/src/types.ts index 810a35352c..997b5d8180 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,5 +1,5 @@ // eslint-disable-next-line no-restricted-imports -- Interim types for FileSystem -import type fs from 'fs'; +import type fs from 'node:fs'; /** * Plain data dictionary @@ -171,6 +171,7 @@ export type { POJO, JSONValue, Opaque, + brand, Callback, NonEmptyArray, AbstractConstructorParameters, diff --git a/src/utils/base.ts b/src/utils/base.ts index 3598032d8a..114ddf967a 100644 --- a/src/utils/base.ts +++ b/src/utils/base.ts @@ -1,10 +1,11 @@ -import type { Codec } from 'multiformats/bases/base'; +// Import type { Codec } from 'multiformats/bases/base'; import { bases } from 'multiformats/basics'; -import { bufferWrap } from './utils'; +import { bufferWrap } from './utils.js'; type MultibaseFormats = keyof typeof bases; +type Codec = (typeof bases)[MultibaseFormats]; -const basesByPrefix: Record> = {}; +const basesByPrefix: Record = {}; for (const k in bases) { const codec = bases[k]; basesByPrefix[codec.prefix] = codec; diff --git a/src/utils/errors.ts b/src/utils/errors.ts index 49de513986..d715d74b6a 100644 --- a/src/utils/errors.ts +++ b/src/utils/errors.ts @@ -1,6 +1,6 @@ -import sysexits from './sysexits'; -import ErrorPolykey from '../ErrorPolykey'; -export * from './ratelimiter/errors'; +import sysexits from './sysexits.js'; +import ErrorPolykey from '../ErrorPolykey.js'; +export * from './ratelimiter/errors.js'; class ErrorUtils extends ErrorPolykey {} diff --git a/src/utils/index.ts b/src/utils/index.ts index dbff459afd..35a3fe5905 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,7 +1,7 @@ -export { default as sysexits } from './sysexits'; -export * from './utils'; -export * from './matchers'; -export * from './binary'; -export * from './random'; -export * from './base'; -export * as errors from './errors'; +export { default as sysexits } from './sysexits.js'; +export * from './utils.js'; +export * from './matchers.js'; +export * from './binary.js'; +export * from './random.js'; +export * from './base.js'; +export * as errors from './errors.js'; diff --git a/src/utils/matchers.ts b/src/utils/matchers.ts index 89d8a4482e..1076191e4e 100644 --- a/src/utils/matchers.ts +++ b/src/utils/matchers.ts @@ -1,4 +1,4 @@ -import { isDeepStrictEqual } from 'util'; +import { isDeepStrictEqual } from 'node:util'; type Proc = (data: any) => Promise | T; type Case = [...patterns: [any, ...Array], proc: Proc]; diff --git a/src/utils/ratelimiter/RateLimiter.ts b/src/utils/ratelimiter/RateLimiter.ts index 4e310b5bdd..38803f24d4 100644 --- a/src/utils/ratelimiter/RateLimiter.ts +++ b/src/utils/ratelimiter/RateLimiter.ts @@ -1,5 +1,5 @@ import { Timer } from '@matrixai/timer'; -import * as rateLimiterErrors from './errors'; +import * as rateLimiterErrors from './errors.js'; /** * Internal data structure used to track a buckets' information. diff --git a/src/utils/ratelimiter/errors.ts b/src/utils/ratelimiter/errors.ts index 531a7693d7..d12530ac52 100644 --- a/src/utils/ratelimiter/errors.ts +++ b/src/utils/ratelimiter/errors.ts @@ -1,4 +1,4 @@ -import { ErrorPolykey, sysexits } from '../../errors'; +import { ErrorPolykey, sysexits } from '../../errors.js'; class ErrorRateLimiter extends ErrorPolykey {} diff --git a/src/utils/ratelimiter/index.ts b/src/utils/ratelimiter/index.ts index 12e24d3316..c6a0068aff 100644 --- a/src/utils/ratelimiter/index.ts +++ b/src/utils/ratelimiter/index.ts @@ -1,2 +1,2 @@ -export { default as RateLimiter } from './RateLimiter'; -export * as errors from './errors'; +export { default as RateLimiter } from './RateLimiter.js'; +export * as errors from './errors.js'; diff --git a/src/utils/utils.ts b/src/utils/utils.ts index d14329739c..3c28acd31a 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -4,16 +4,16 @@ import type { Timer, PromiseDeconstructed, Callback, -} from '../types'; +} from '../types.js'; import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts'; -import os from 'os'; +import os from 'node:os'; import process from 'process'; -import path from 'path'; -import nodesEvents from 'events'; +import path from 'node:path'; +import nodesEvents from 'node:events'; import lexi from 'lexicographic-integer'; import { PromiseCancellable } from '@matrixai/async-cancellable'; -import { timedCancellable } from '@matrixai/contexts/dist/functions'; -import * as utilsErrors from './errors'; +import { functions } from '@matrixai/contexts'; +import * as utilsErrors from './errors.js'; const AsyncFunction = (async () => {}).constructor; const GeneratorFunction = function* () {}.constructor; @@ -222,7 +222,7 @@ async function poll_( } } -const pollCancellable = timedCancellable( +const pollCancellable = functions.timedCancellable( poll_, true, undefined, @@ -541,6 +541,12 @@ function setMaxListeners( nodesEvents.setMaxListeners(limit, target); } +async function importFS(fs?: FileSystem): Promise { + if (fs != null) return fs; + const { default: fsImported } = await import('node:fs'); + return fsImported; +} + export { AsyncFunction, GeneratorFunction, @@ -581,4 +587,5 @@ export { isBufferSource, yieldMicro, setMaxListeners, + importFS, }; diff --git a/src/validation/errors.ts b/src/validation/errors.ts index 498f41e14b..4c776529e3 100644 --- a/src/validation/errors.ts +++ b/src/validation/errors.ts @@ -1,6 +1,6 @@ import { AbstractError } from '@matrixai/errors'; -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; /** * Generic error containing all parsing errors that occurred during diff --git a/src/validation/index.ts b/src/validation/index.ts index 2d29ef407a..14e05fe76b 100644 --- a/src/validation/index.ts +++ b/src/validation/index.ts @@ -1,5 +1,5 @@ -import * as validationErrors from './errors'; -import * as validationUtils from './utils'; +import * as validationErrors from './errors.js'; +import * as validationUtils from './utils.js'; async function validate( parser: (keyPath: Array, value: any) => Promise, diff --git a/src/validation/utils.ts b/src/validation/utils.ts index 59a6272180..203a51f858 100644 --- a/src/validation/utils.ts +++ b/src/validation/utils.ts @@ -5,7 +5,7 @@ * The parse error message must focus on why the validation failed * @module */ -import * as validationErrors from './errors'; +import * as validationErrors from './errors.js'; function parseInteger(data: any): number { data = parseInt(data); diff --git a/src/vaults/Vault.ts b/src/vaults/Vault.ts index dbcf74bcd7..76f1e3ba8c 100644 --- a/src/vaults/Vault.ts +++ b/src/vaults/Vault.ts @@ -1,4 +1,4 @@ -import type VaultInternal from './VaultInternal'; +import type VaultInternal from './VaultInternal.js'; interface Vault { vaultDataDir: VaultInternal['vaultDataDir']; diff --git a/src/vaults/VaultInternal.ts b/src/vaults/VaultInternal.ts index b5d5c6747c..be229e0d88 100644 --- a/src/vaults/VaultInternal.ts +++ b/src/vaults/VaultInternal.ts @@ -14,43 +14,35 @@ import type { VaultIdEncoded, VaultName, VaultRef, -} from './types'; -import type { POJO } from '../types'; -import type { NodeId, NodeIdEncoded } from '../ids/types'; -import type KeyRing from '../keys/KeyRing'; -import type NodeManager from '../nodes/NodeManager'; -import type agentClientManifest from '../nodes/agent/callers'; -import path from 'path'; +} from './types.js'; +import type { POJO } from '../types.js'; +import type { NodeId, NodeIdEncoded } from '../ids/types.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type NodeManager from '../nodes/NodeManager.js'; +import type agentClientManifest from '../nodes/agent/callers/index.js'; +import path from 'node:path'; import git from 'isomorphic-git'; import Logger from '@matrixai/logger'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { RWLockWriter } from '@matrixai/async-locks'; -import { - context, - timed, - timedCancellable, -} from '@matrixai/contexts/dist/decorators'; +import { decorators } from '@matrixai/contexts'; import { withF, withG } from '@matrixai/resources'; -import { tagLast } from './types'; -import * as vaultsErrors from './errors'; -import * as vaultsEvents from './events'; -import * as vaultsUtils from './utils'; -import * as ids from '../ids'; -import * as utils from '../utils'; -import * as nodesUtils from '../nodes/utils'; -import * as gitUtils from '../git/utils'; +import { tagLast } from './types.js'; +import * as vaultsErrors from './errors.js'; +import * as vaultsEvents from './events.js'; +import * as vaultsUtils from './utils.js'; +import * as ids from '../ids/index.js'; +import * as utils from '../utils/index.js'; +import * as nodesUtils from '../nodes/utils.js'; +import * as gitUtils from '../git/utils.js'; type RemoteInfo = { remoteNode: NodeIdEncoded; remoteVault: VaultIdEncoded; }; -interface VaultInternal extends CreateDestroyStartStop {} - -@CreateDestroyStartStop( +interface VaultInternal extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new vaultsErrors.ErrorVaultRunning(), new vaultsErrors.ErrorVaultDestroyed(), { @@ -92,7 +84,7 @@ class VaultInternal { tran?: DBTransaction, ctx?: Partial, ): Promise; - @timedCancellable(true) + @decorators.timedCancellable(true) public static async createVaultInternal( { vaultId, @@ -114,7 +106,7 @@ class VaultInternal { logger?: Logger; }, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return await db.withTransactionF((tran) => @@ -178,7 +170,7 @@ class VaultInternal { tran?: DBTransaction, ctx?: Partial, ): Promise; - @timedCancellable(true) + @decorators.timedCancellable(true) public static async cloneVaultInternal( { targetNodeId, @@ -202,7 +194,7 @@ class VaultInternal { logger?: Logger; }, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return await db.withTransactionF((tran) => @@ -361,7 +353,7 @@ class VaultInternal { tran: DBTransaction, ctx?: Partial, ): Promise; - @timedCancellable(true) + @decorators.timedCancellable(true) protected async start_( { vaultName, @@ -371,7 +363,7 @@ class VaultInternal { fresh: boolean; }, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { this.logger.info( `Starting ${this.constructor.name} - ${this.vaultIdEncoded}`, @@ -442,7 +434,7 @@ class VaultInternal { ref?: string | VaultRef, limit?: number, ): Promise>; - @ready(new vaultsErrors.ErrorVaultNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) public async log( ref: string | VaultRef = 'HEAD', limit: number, @@ -479,7 +471,7 @@ class VaultInternal { * Checks out the vault repository to specific commit ID or special tags. * This changes the working directory and updates the HEAD reference. */ - @ready(new vaultsErrors.ErrorVaultNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) public async version(ref: string | VaultRef = tagLast): Promise { vaultsUtils.assertRef(ref); if (ref === vaultsUtils.tagLast) { @@ -509,7 +501,7 @@ class VaultInternal { /** * With context handler for using a vault in a read-only context. */ - @ready(new vaultsErrors.ErrorVaultNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) public async readF(f: (fs: FileSystemReadable) => Promise): Promise { return withF([this.lock.read()], async () => { return await f(this.efsVault); @@ -520,7 +512,7 @@ class VaultInternal { * With context handler for using a vault in a read-only context for a * generator. */ - @ready(new vaultsErrors.ErrorVaultNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) public readG( g: (fs: FileSystemReadable) => AsyncGenerator, ): AsyncGenerator { @@ -538,12 +530,12 @@ class VaultInternal { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new vaultsErrors.ErrorVaultNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) + @decorators.timedCancellable(true) public async writeF( f: (fs: FileSystemWritable) => Promise, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => this.writeF(f, tran, ctx)); @@ -594,12 +586,12 @@ class VaultInternal { tran?: DBTransaction, ctx?: Partial, ): AsyncGenerator; - @ready(new vaultsErrors.ErrorVaultNotRunning()) - @timed() + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) + @decorators.timed() public writeG( g: (fs: FileSystemWritable) => AsyncGenerator, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): AsyncGenerator { if (tran == null) { return this.db.withTransactionG((tran) => this.writeG(g, tran, ctx)); @@ -643,7 +635,7 @@ class VaultInternal { /** * Acquire a read-only lock on this vault. */ - @ready(new vaultsErrors.ErrorVaultNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) public acquireRead(): ResourceAcquire { return async () => { const acquire = this.lock.read(); @@ -660,7 +652,7 @@ class VaultInternal { /** * Acquire a read-write lock on this vault. */ - @ready(new vaultsErrors.ErrorVaultNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) public acquireWrite( tran: DBTransaction | undefined, ctx: ContextTimed, @@ -736,8 +728,8 @@ class VaultInternal { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new vaultsErrors.ErrorVaultNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultNotRunning()) + @decorators.timedCancellable(true) public async pullVault( { nodeManager, @@ -749,7 +741,7 @@ class VaultInternal { pullVaultNameOrId?: VaultId | VaultName; }, tran: DBTransaction | undefined, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => diff --git a/src/vaults/VaultManager.ts b/src/vaults/VaultManager.ts index b1c7faf8c9..5f9f7019a2 100644 --- a/src/vaults/VaultManager.ts +++ b/src/vaults/VaultManager.ts @@ -7,45 +7,38 @@ import type { VaultActions, VaultIdString, VaultIdEncoded, -} from './types'; -import type { Vault } from './Vault'; -import type { FileSystem } from '../types'; -import type { PolykeyWorkerManagerInterface } from '../workers/types'; -import type { NodeId } from '../ids/types'; -import type KeyRing from '../keys/KeyRing'; -import type NodeManager from '../nodes/NodeManager'; -import type GestaltGraph from '../gestalts/GestaltGraph'; -import type NotificationsManager from '../notifications/NotificationsManager'; -import type ACL from '../acl/ACL'; -import type { RemoteInfo } from './VaultInternal'; -import type { VaultAction } from './types'; -import type { Key } from '../keys/types'; -import path from 'path'; +} from './types.js'; +import type { Vault } from './Vault.js'; +import type { FileSystem } from '../types.js'; +import type { NodeId } from '../ids/types.js'; +import type KeyRing from '../keys/KeyRing.js'; +import type NodeManager from '../nodes/NodeManager.js'; +import type GestaltGraph from '../gestalts/GestaltGraph.js'; +import type NotificationsManager from '../notifications/NotificationsManager.js'; +import type ACL from '../acl/ACL.js'; +import type { PolykeyWorkerManager } from '../workers/types.js'; +import type { RemoteInfo } from './VaultInternal.js'; +import type { VaultAction } from './types.js'; +import path from 'node:path'; import { DB } from '@matrixai/db'; import { EncryptedFS, errors as encryptedFsErrors } from 'encryptedfs'; -import { - CreateDestroyStartStop, - ready, -} from '@matrixai/async-init/dist/CreateDestroyStartStop'; +import { createDestroyStartStop } from '@matrixai/async-init'; import { IdInternal } from '@matrixai/id'; import { withF, withG } from '@matrixai/resources'; import { LockBox, RWLockWriter } from '@matrixai/async-locks'; -import { - context, - timedCancellable, - timed, -} from '@matrixai/contexts/dist/decorators'; +import { decorators } from '@matrixai/contexts'; import Logger from '@matrixai/logger'; -import VaultInternal from './VaultInternal'; -import * as vaultsEvents from './events'; -import * as vaultsUtils from './utils'; -import * as vaultsErrors from './errors'; -import config from '../config'; -import { mkdirExists } from '../utils/utils'; -import * as utils from '../utils'; -import * as gitHttp from '../git/http'; -import * as nodesUtils from '../nodes/utils'; -import * as keysUtils from '../keys/utils'; +import VaultInternal from './VaultInternal.js'; +import * as vaultsEvents from './events.js'; +import * as vaultsUtils from './utils.js'; +import * as vaultsErrors from './errors.js'; +import config from '../config.js'; +import { mkdirExists } from '../utils/utils.js'; +import * as gitHttp from '../git/http.js'; +import * as nodesUtils from '../nodes/utils.js'; +import * as keysUtils from '../keys/utils/index.js'; +import { polykeyWorkerManifest } from '../workers/index.js'; +import * as utils from '#utils/index.js'; /** * Object map pattern for each vault. @@ -59,9 +52,8 @@ type VaultMetadata = { remoteInfo?: RemoteInfo; }; -interface VaultManager extends CreateDestroyStartStop {} - -@CreateDestroyStartStop( +interface VaultManager extends createDestroyStartStop.CreateDestroyStartStop {} +@createDestroyStartStop.CreateDestroyStartStop( new vaultsErrors.ErrorVaultManagerRunning(), new vaultsErrors.ErrorVaultManagerDestroyed(), { @@ -82,7 +74,7 @@ class VaultManager { nodeManager, gestaltGraph, notificationsManager, - fs = require('fs'), + fs, logger = new Logger(this.name), fresh = false, }: { @@ -99,6 +91,7 @@ class VaultManager { }): Promise { logger.info(`Creating ${this.name}`); logger.info(`Setting vaults path to ${vaultsPath}`); + fs = await utils.importFS(fs); const vaultManager = new this({ vaultsPath, db, @@ -192,20 +185,7 @@ class VaultManager { efsDb = await DB.createDB({ crypto: { key: vaultKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, dbPath: this.efsPath, logger: this.logger.getChild('EFS Database'), @@ -276,20 +256,7 @@ class VaultManager { await this.efsDb.start({ crypto: { key: this.vaultKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, fresh: false, }); @@ -306,7 +273,7 @@ class VaultManager { this.logger.info(`Destroyed ${this.constructor.name}`); } - public setWorkerManager(workerManager: PolykeyWorkerManagerInterface) { + public setWorkerManager(workerManager: PolykeyWorkerManager) { this.efs.setWorkerManager(workerManager); } @@ -322,12 +289,12 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timedCancellable(true) public async createVault( vaultName: VaultName, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => @@ -380,7 +347,7 @@ class VaultManager { * Retrieves the vault metadata using the VaultId and parses it to return the * associated vault name. */ - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) public async getVaultMeta( vaultId: VaultId, tran?: DBTransaction, @@ -424,12 +391,12 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timedCancellable(true) public async destroyVault( vaultId: VaultId, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => @@ -475,12 +442,12 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timedCancellable(true) public async closeVault( vaultId: VaultId, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => @@ -510,10 +477,10 @@ class VaultManager { ctx?: Partial, tran?: DBTransaction, ): Promise; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timedCancellable(true) public async listVaults( - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, tran?: DBTransaction, ): Promise { if (tran == null) { @@ -536,7 +503,7 @@ class VaultManager { /** * Changes the vault name metadata of a VaultId. */ - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) public async renameVault( vaultId: VaultId, newVaultName: VaultName, @@ -596,7 +563,7 @@ class VaultManager { /** * Retrieves the VaultId associated with a vault name. */ - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) public async getVaultId( vaultName: VaultName, tran?: DBTransaction, @@ -619,7 +586,7 @@ class VaultManager { /** * Retrieves the vault name associated with a VaultId. */ - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) public async getVaultName( vaultId: VaultId, tran?: DBTransaction, @@ -636,7 +603,7 @@ class VaultManager { /** * Returns a dictionary of VaultActions for each node */ - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) public async getVaultPermission( vaultId: VaultId, tran?: DBTransaction, @@ -660,7 +627,7 @@ class VaultManager { * Sets clone, pull and scan permissions of a vault for a gestalt and send a * notification to this gestalt. */ - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) public async shareVault( vaultId: VaultId, nodeId: NodeId, @@ -695,7 +662,7 @@ class VaultManager { /** * Unsets clone, pull and scan permissions of a vault for a gestalt. */ - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) public async unshareVault( vaultId: VaultId, nodeId: NodeId, @@ -724,13 +691,13 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timedCancellable(true) public async cloneVault( nodeId: NodeId, vaultNameOrId: VaultId | VaultName, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => @@ -823,7 +790,7 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): Promise; - @timedCancellable(true) + @decorators.timedCancellable(true) public async pullVault( { vaultId, @@ -835,7 +802,7 @@ class VaultManager { pullVaultNameOrId?: VaultId | VaultName; }, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => @@ -870,12 +837,12 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): AsyncGenerator; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timed() + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timed() public async *handleInfoRequest( vaultId: VaultId, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): AsyncGenerator { if (tran == null) { const handleInfoRequest = (tran: DBTransaction) => @@ -916,16 +883,16 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): AsyncGenerator; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timed() + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timed() public async *handlePackRequest( vaultId: VaultId, body: Array, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): AsyncGenerator { if (tran == null) { - // Lambda to maintain `this` context + // Lambda to maintain `this` decorators.context const handlePackRequest = (tran: DBTransaction) => this.handlePackRequest(vaultId, body, tran, ctx); return yield* this.db.withTransactionG(async function* (tran) { @@ -966,10 +933,10 @@ class VaultManager { vaultIdEncoded: VaultIdEncoded; vaultPermissions: VaultAction[]; }>; - @timed() + @decorators.timed() public async *scanVaults( targetNodeId: NodeId, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): AsyncGenerator<{ vaultName: VaultName; vaultIdEncoded: VaultIdEncoded; @@ -1010,18 +977,18 @@ class VaultManager { vaultName: VaultName; vaultPermissions: VaultAction[]; }>; - @timed() + @decorators.timed() public async *handleScanVaults( nodeId: NodeId, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): AsyncGenerator<{ vaultId: VaultId; vaultName: VaultName; vaultPermissions: VaultAction[]; }> { if (tran == null) { - // Lambda to maintain `this` context + // Lambda to maintain `this` decorators.context const handleScanVaults = (tran: DBTransaction) => this.handleScanVaults(nodeId, tran, ctx); return yield* this.db.withTransactionG(async function* (tran) { @@ -1064,7 +1031,7 @@ class VaultManager { } } - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) protected async generateVaultId(): Promise { let vaultId = this.vaultIdGenerator(); let i = 0; @@ -1080,7 +1047,7 @@ class VaultManager { return vaultId; } - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) protected async getVault( vaultId: VaultId, tran: DBTransaction, @@ -1133,13 +1100,13 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): Promise; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timedCancellable(true) + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timedCancellable(true) public async withVaults( vaultIds: VaultId[], f: (...args: Vault[]) => Promise, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): Promise { if (tran == null) { return this.db.withTransactionF((tran) => @@ -1179,13 +1146,13 @@ class VaultManager { tran?: DBTransaction, ctx?: Partial, ): AsyncGenerator; - @ready(new vaultsErrors.ErrorVaultManagerNotRunning()) - @timed() + @createDestroyStartStop.ready(new vaultsErrors.ErrorVaultManagerNotRunning()) + @decorators.timed() public async *withVaultsG( vaultIds: Array, g: (...args: Array) => AsyncGenerator, tran: DBTransaction, - @context ctx: ContextTimed, + @decorators.context ctx: ContextTimed, ): AsyncGenerator { if (tran == null) { return yield* this.db.withTransactionG((tran) => diff --git a/src/vaults/VaultOps.ts b/src/vaults/VaultOps.ts index a8dbdc8051..511d5d1ecb 100644 --- a/src/vaults/VaultOps.ts +++ b/src/vaults/VaultOps.ts @@ -1,10 +1,12 @@ import type Logger from '@matrixai/logger'; import type { ContextTimed } from '@matrixai/contexts'; import type { Stat } from 'encryptedfs'; -import type { Vault } from './Vault'; -import path from 'path'; -import * as vaultsErrors from './errors'; -import * as vaultsUtils from './utils'; +import type { Vault } from './Vault.js'; +import type { FileSystem } from '../types.js'; +import path from 'node:path'; +import * as vaultsErrors from './errors.js'; +import * as vaultsUtils from './utils.js'; +import * as utils from '../utils/index.js'; type FileOptions = { recursive?: boolean; @@ -201,13 +203,14 @@ async function mkdir( async function addSecretDirectory( vault: Vault, secretDirectory: string, - fs = require('fs'), + fs?: FileSystem, logger?: Logger, ctx?: ContextTimed, ): Promise { const absoluteDirPath = path.resolve(secretDirectory); await vault.writeF( async (efs) => { + fs = await utils.importFS(fs); for await (const secretPath of vaultsUtils.readDirRecursively( fs, absoluteDirPath, diff --git a/src/vaults/errors.ts b/src/vaults/errors.ts index a6874fe66f..a6a63e09ee 100644 --- a/src/vaults/errors.ts +++ b/src/vaults/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorVaults extends ErrorPolykey {} diff --git a/src/vaults/events.ts b/src/vaults/events.ts index d7ee9a817b..88d924608c 100644 --- a/src/vaults/events.ts +++ b/src/vaults/events.ts @@ -1,4 +1,4 @@ -import EventPolykey from '../EventPolykey'; +import EventPolykey from '../EventPolykey.js'; abstract class EventVaults extends EventPolykey {} diff --git a/src/vaults/fileTree.ts b/src/vaults/fileTree.ts index 31bc05f358..d513c83127 100644 --- a/src/vaults/fileTree.ts +++ b/src/vaults/fileTree.ts @@ -1,5 +1,5 @@ import type { Stat } from 'encryptedfs'; -import type { FileSystem } from '../types'; +import type { FileSystem } from '../types.js'; import type { ContentNode, DoneMessage, @@ -10,16 +10,17 @@ import type { Parsed, HeaderGeneric, HeaderContent, -} from './types'; -import path from 'path'; +} from './types.js'; +import type { FdIndex } from 'encryptedfs'; +import path from 'node:path'; import { ReadableStream, TransformStream } from 'stream/web'; import { minimatch } from 'minimatch'; import { JSONParser, TokenizerError } from '@streamparser/json'; -import * as vaultsUtils from './utils'; -import { HeaderSize, HeaderType, HeaderMagic } from './types'; -import * as utils from '../utils'; -import * as utilsErrors from '../utils/errors'; -import * as validationErrors from '../validation/errors'; +import * as vaultsUtils from './utils.js'; +import { HeaderSize, HeaderType, HeaderMagic } from './types.js'; +import * as utils from '../utils/index.js'; +import * as utilsErrors from '../utils/errors.js'; +import * as validationErrors from '../validation/errors.js'; /** * Generates a serializable format of file stats @@ -290,7 +291,7 @@ async function* encodeContent( // Handle as an EFS fd const fsr = fs as FileSystemReadable; const bytesRead = await fsr.promises.read( - fd, + fd as FdIndex, buffer, undefined, buffer.byteLength, @@ -305,7 +306,7 @@ async function* encodeContent( if (typeof fd === 'number') { // Handle as an EFS fd const fsr = fs as FileSystemReadable; - return await fsr.close(fd); + return await fsr.close(fd as FdIndex); } else { // Handle as an FS fd return await fd.close(); diff --git a/src/vaults/index.ts b/src/vaults/index.ts index b03de1f7c8..4ad2f5a9c3 100644 --- a/src/vaults/index.ts +++ b/src/vaults/index.ts @@ -1,9 +1,9 @@ -export { default as VaultManager } from './VaultManager'; -export { default as VaultInternal } from './VaultInternal'; -export type { Vault } from './Vault'; -export * as utils from './utils'; -export * as types from './types'; -export * as errors from './errors'; -export * as events from './events'; -export * as vaultOps from './VaultOps'; -export * as fileTree from './fileTree'; +export { default as VaultManager } from './VaultManager.js'; +export { default as VaultInternal } from './VaultInternal.js'; +export type { Vault } from './Vault.js'; +export * as utils from './utils.js'; +export * as types from './types.js'; +export * as errors from './errors.js'; +export * as events from './events.js'; +export * as vaultOps from './VaultOps.js'; +export * as fileTree from './fileTree.js'; diff --git a/src/vaults/types.ts b/src/vaults/types.ts index a4609718c5..1537de7f3d 100644 --- a/src/vaults/types.ts +++ b/src/vaults/types.ts @@ -1,8 +1,8 @@ -import type { VaultId, VaultIdString, VaultIdEncoded } from '../ids/types'; +import type { VaultId, VaultIdString, VaultIdEncoded } from '../ids/types.js'; import type { EncryptedFS } from 'encryptedfs'; -import type { Callback, Path } from 'encryptedfs/dist/types'; -import type { FdIndex } from 'encryptedfs/dist/fd/types'; -import type { Opaque } from '../types'; +import type { Callback, Path } from 'encryptedfs'; +import type { FdIndex } from 'encryptedfs'; +import type { Opaque } from '../types.js'; const vaultActions = ['clone', 'pull'] as const; diff --git a/src/vaults/utils.ts b/src/vaults/utils.ts index 7dd0de7023..33d1891878 100644 --- a/src/vaults/utils.ts +++ b/src/vaults/utils.ts @@ -5,15 +5,15 @@ import type { CommitId, FileSystemReadable, FileSystemWritable, -} from './types'; -import type { NodeId } from '../ids/types'; -import type { Path } from 'encryptedfs/dist/types'; -import path from 'path'; -import { pathJoin } from 'encryptedfs/dist/utils'; -import * as vaultsErrors from './errors'; -import { tagLast, refs, vaultActions } from './types'; -import * as nodesUtils from '../nodes/utils'; -import * as validationErrors from '../validation/errors'; +} from './types.js'; +import type { NodeId } from '../ids/types.js'; +import type { Path } from 'encryptedfs'; +import path from 'node:path'; +import { utils as encryptedFsUtils } from 'encryptedfs'; +import * as vaultsErrors from './errors.js'; +import { tagLast, refs, vaultActions } from './types.js'; +import * as nodesUtils from '../nodes/utils.js'; +import * as validationErrors from '../validation/errors.js'; /** * Vault history is designed for linear-history. @@ -80,7 +80,9 @@ async function* walkFs( // Push contents to shortlist const newPaths = await efs.readdir(path_); shortList.push( - ...newPaths.map((v) => pathJoin(path_!.toString(), v.toString())), + ...newPaths.map((v) => + encryptedFsUtils.pathJoin(path_!.toString(), v.toString()), + ), ); } else { // Is a file so we yield the path @@ -170,4 +172,8 @@ export { uint8ArrayConcat, }; -export { createVaultIdGenerator, encodeVaultId, decodeVaultId } from '../ids'; +export { + createVaultIdGenerator, + encodeVaultId, + decodeVaultId, +} from '../ids/index.js'; diff --git a/src/workers/errors.ts b/src/workers/errors.ts index 880e943566..1882553e44 100644 --- a/src/workers/errors.ts +++ b/src/workers/errors.ts @@ -1,5 +1,5 @@ -import ErrorPolykey from '../ErrorPolykey'; -import sysexits from '../utils/sysexits'; +import ErrorPolykey from '../ErrorPolykey.js'; +import sysexits from '../utils/sysexits.js'; class ErrorWorkers extends ErrorPolykey {} diff --git a/src/workers/index.ts b/src/workers/index.ts index 7ff9ca454e..93a5a09407 100644 --- a/src/workers/index.ts +++ b/src/workers/index.ts @@ -1,5 +1,4 @@ export { WorkerManager } from '@matrixai/workers'; -export { default as polykeyWorker } from './polykeyWorkerModule'; -export * as utils from './utils'; -export type { PolykeyWorkerModule } from './polykeyWorkerModule'; -export type { PolykeyWorkerManagerInterface } from './types'; +export { default as polykeyWorkerManifest } from './polykeyWorkerManifest.js'; +export * as utils from './utils.js'; +export type * from './types.js'; diff --git a/src/workers/polykeyWorker.ts b/src/workers/polykeyWorker.ts deleted file mode 100644 index 5706b012ea..0000000000 --- a/src/workers/polykeyWorker.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { PolykeyWorkerModule } from './polykeyWorkerModule'; -import { expose } from 'threads/worker'; -import polykeyWorker from './polykeyWorkerModule'; - -expose(polykeyWorker); - -export type { PolykeyWorkerModule }; diff --git a/src/workers/polykeyWorkerManifest.ts b/src/workers/polykeyWorkerManifest.ts new file mode 100644 index 0000000000..63fb2de15f --- /dev/null +++ b/src/workers/polykeyWorkerManifest.ts @@ -0,0 +1,307 @@ +import type { WorkerManifest } from '@matrixai/workers'; +import type { + Key, + KeyPair, + PrivateKey, + RecoveryCode, + PasswordHash, + PasswordSalt, + PasswordMemLimit, + PasswordOpsLimit, + CertId, +} from '../keys/types.js'; +import { expose } from '@matrixai/workers'; +import { IdInternal } from '@matrixai/id'; +import * as keysUtils from '../keys/utils/index.js'; + +type PolykeyWorkerManifest = { + sleep({ delay }: { delay: number }): Promise<{ data: undefined }>; + hashPassword( + { + password, + salt, + opsLimit, + memLimit, + }: { + password: string; + salt?: ArrayBuffer; + opsLimit?: PasswordOpsLimit; + memLimit?: PasswordMemLimit; + }, + transferList?: Array, + ): Promise<{ + data: [ArrayBuffer, ArrayBuffer]; + transferList: [ArrayBuffer, ArrayBuffer]; + }>; + checkPassword( + { + password, + hash, + salt, + opsLimit, + memLimit, + }: { + password: string; + hash: ArrayBuffer; + salt: ArrayBuffer; + opsLimit?: PasswordOpsLimit; + memLimit?: PasswordMemLimit; + }, + transferList?: Array, + ): Promise<{ data: boolean }>; + generateDeterministicKeyPair({ + recoveryCode, + }: { + recoveryCode: RecoveryCode; + }): Promise<{ + data: { + publicKey: ArrayBuffer; + privateKey: ArrayBuffer; + secretKey: ArrayBuffer; + }; + transferList: [ArrayBuffer, ArrayBuffer, ArrayBuffer]; + }>; + generateCertificate( + { + certId, + subjectKeyPair, + issuerPrivateKey, + duration, + subjectAttrsExtra, + issuerAttrsExtra, + now, + }: { + certId: ArrayBuffer; + subjectKeyPair: { + publicKey: ArrayBuffer; + privateKey: ArrayBuffer; + }; + issuerPrivateKey: ArrayBuffer; + duration: number; + subjectAttrsExtra?: Array<{ [key: string]: Array }>; + issuerAttrsExtra?: Array<{ [key: string]: Array }>; + now?: Date; + }, + transferList?: Array, + ): Promise<{ + data: ArrayBuffer; + transferList: [ArrayBuffer]; + }>; + encrypt( + data: { key: ArrayBuffer; plainText: ArrayBuffer }, + transferList: Array, + ): Promise<{ data: ArrayBuffer; transferList: [ArrayBuffer] }>; + decrypt( + data: { + key: ArrayBuffer; + cipherText: ArrayBuffer; + }, + transferList: Array, + ): Promise< + | { data: ArrayBuffer; transferList: [ArrayBuffer] } + | { data: undefined; transferList: [] } + >; +}; + +/** + * Worker object that contains all functions that will be executed in parallel. + * Functions should be using CPU-parallelism not IO-parallelism. + * Most functions should be synchronous, not asynchronous. + * Making them asynchronous does not make a difference to the caller. + * The caller must always await because the fucntions will run on the pool. + * + * When passing in `Buffer`, it is coerced into an `Uint8Array`. To avoid + * confusion, do not pass in `Buffer` and instead use `ArrayBuffer`. + * + * If you are passing the underlying `ArrayBuffer`, ensure that the containing + * `Buffer` is unpooled, or make a slice copy of the underlying `ArrayBuffer` + * with the `Buffer.byteOffset` and `Buffer.byteLength`. + * + * Remember the subtyping relationship of buffers: + * Buffers < Uint8Array < ArrayBuffer < BufferSource + * + * Only the `ArrayBuffer` is "transferrable" which means they can be zero-copy + * transferred. When transferring a structure that contains `ArrayBuffer`, you + * must pass the array of transferrable objects as the second parameter to + * `Transfer`. + * + * Only transfer things that you don't expect to be using in the sending thread. + * + * Note that `Buffer.from(ArrayBuffer)` is a zero-copy wrapper. + */ +const polykeyWorkerManifest: PolykeyWorkerManifest = { + async sleep({ delay }: { delay: number }): Promise<{ data: undefined }> { + await new Promise((resolve) => setTimeout(resolve, delay)); + return { data: undefined }; + }, + // Keys functions + async hashPassword( + { + password, + salt, + opsLimit, + memLimit, + }: { + password: string; + salt?: ArrayBuffer; + opsLimit?: PasswordOpsLimit; + memLimit?: PasswordMemLimit; + }, + transferList?: Array, // eslint-disable-line @typescript-eslint/no-unused-vars + ): Promise<{ + data: [ArrayBuffer, ArrayBuffer]; + transferList: [ArrayBuffer, ArrayBuffer]; + }> { + if (salt != null) salt = Buffer.from(salt); + // It is guaranteed that `keysUtils.hashPassword` returns non-pooled buffers + const hashAndSalt = keysUtils.hashPassword( + password, + salt as PasswordSalt | undefined, + opsLimit, + memLimit, + ); + // Result is a tuple of [hash, salt] using transferable `ArrayBuffer` + const result: [ArrayBuffer, ArrayBuffer] = [ + hashAndSalt[0].buffer, + hashAndSalt[1].buffer, + ]; + return { data: result, transferList: result }; + }, + async checkPassword( + { + password, + hash, + salt, + opsLimit, + memLimit, + }: { + password: string; + hash: ArrayBuffer; + salt: ArrayBuffer; + opsLimit?: PasswordOpsLimit; + memLimit?: PasswordMemLimit; + }, + transferList: Array, // eslint-disable-line @typescript-eslint/no-unused-vars + ): Promise<{ data: boolean }> { + hash = Buffer.from(hash); + salt = Buffer.from(salt); + const result = keysUtils.checkPassword( + password, + hash as PasswordHash, + salt as PasswordSalt, + opsLimit, + memLimit, + ); + return { data: result }; + }, + async generateDeterministicKeyPair({ + recoveryCode, + }: { + recoveryCode: RecoveryCode; + }): Promise<{ + data: { + publicKey: ArrayBuffer; + privateKey: ArrayBuffer; + secretKey: ArrayBuffer; + }; + transferList: [ArrayBuffer, ArrayBuffer, ArrayBuffer]; + }> { + const keyPair = await keysUtils.generateDeterministicKeyPair(recoveryCode); + // Result is a record of {publicKey, privateKey, secretKey} using transferable `ArrayBuffer` + const result = { + publicKey: keyPair.publicKey.buffer, + privateKey: keyPair.privateKey.buffer, + secretKey: keyPair.secretKey.buffer, + }; + return { + data: { + publicKey: result.publicKey, + privateKey: result.privateKey, + secretKey: result.secretKey, + }, + transferList: [result.publicKey, result.privateKey, result.secretKey], + }; + }, + async generateCertificate({ + certId, + subjectKeyPair, + issuerPrivateKey, + duration, + subjectAttrsExtra, + issuerAttrsExtra, + now = new Date(), + }: { + certId: ArrayBuffer; + subjectKeyPair: { + publicKey: ArrayBuffer; + privateKey: ArrayBuffer; + }; + issuerPrivateKey: ArrayBuffer; + duration: number; + subjectAttrsExtra?: Array<{ [key: string]: Array }>; + issuerAttrsExtra?: Array<{ [key: string]: Array }>; + now?: Date; + }): Promise<{ + data: ArrayBuffer; + transferList: [ArrayBuffer]; + }> { + certId = IdInternal.create(certId); + subjectKeyPair.publicKey = Buffer.from(subjectKeyPair.publicKey); + subjectKeyPair.privateKey = Buffer.from(subjectKeyPair.privateKey); + issuerPrivateKey = Buffer.from(issuerPrivateKey); + const cert = await keysUtils.generateCertificate({ + certId: certId as CertId, + subjectKeyPair: subjectKeyPair as KeyPair, + issuerPrivateKey: issuerPrivateKey as PrivateKey, + duration, + subjectAttrsExtra, + issuerAttrsExtra, + now, + }); + return { data: cert.rawData, transferList: [cert.rawData] }; + }, + + // EFS functions + + async encrypt({ + key, + plainText, + }: { + key: ArrayBuffer; + plainText: ArrayBuffer; + }): Promise<{ data: ArrayBuffer; transferList: [ArrayBuffer] }> { + const cipherText = keysUtils.encryptWithKey( + Buffer.from(key) as Key, + Buffer.from(plainText), + ); + const cipherTextAB = cipherText.buffer; + return { data: cipherTextAB, transferList: [cipherTextAB] }; + }, + async decrypt({ + key, + cipherText, + }: { + key: ArrayBuffer; + cipherText: ArrayBuffer; + }): Promise< + | { data: ArrayBuffer; transferList: [ArrayBuffer] } + | { data: undefined; transferList: [] } + > { + const plainText = keysUtils.decryptWithKey( + Buffer.from(key) as Key, + Buffer.from(cipherText), + ); + if (plainText != null) { + const plainTextAB = plainText.buffer; + return { data: plainTextAB, transferList: [plainTextAB] }; + } else { + return { data: undefined, transferList: [] }; + } + }, +} satisfies WorkerManifest; + +expose(polykeyWorkerManifest); + +export type { PolykeyWorkerManifest }; + +export default polykeyWorkerManifest; diff --git a/src/workers/polykeyWorkerModule.ts b/src/workers/polykeyWorkerModule.ts deleted file mode 100644 index 75a3c14b9a..0000000000 --- a/src/workers/polykeyWorkerModule.ts +++ /dev/null @@ -1,192 +0,0 @@ -import type { TransferDescriptor } from 'threads'; -import type { - Key, - KeyPair, - PrivateKey, - RecoveryCode, - PasswordHash, - PasswordSalt, - PasswordMemLimit, - PasswordOpsLimit, - CertId, -} from '../keys/types'; -import { isWorkerRuntime } from 'threads'; -import { Transfer } from 'threads/worker'; -import { IdInternal } from '@matrixai/id'; -import * as keysUtils from '../keys/utils'; - -/** - * Worker object that contains all functions that will be executed in parallel. - * Functions should be using CPU-parallelism not IO-parallelism. - * Most functions should be synchronous, not asynchronous. - * Making them asynchronous does not make a difference to the caller. - * The caller must always await because the fucntions will run on the pool. - * - * When passing in `Buffer`, it is coerced into an `Uint8Array`. To avoid - * confusion, do not pass in `Buffer` and instead use `ArrayBuffer`. - * - * If you are passing the underlying `ArrayBuffer`, ensure that the containing - * `Buffer` is unpooled, or make a slice copy of the underlying `ArrayBuffer` - * with the `Buffer.byteOffset` and `Buffer.byteLength`. - * - * Remember the subtyping relationship of buffers: - * Buffers < Uint8Array < ArrayBuffer < BufferSource - * - * Only the `ArrayBuffer` is "transferrable" which means they can be zero-copy - * transferred. When transferring a structure that contains `ArrayBuffer`, you - * must pass the array of transferrable objects as the second parameter to - * `Transfer`. - * - * Only transfer things that you don't expect to be using in the sending thread. - * - * Note that `Buffer.from(ArrayBuffer)` is a zero-copy wrapper. - */ -const polykeyWorker = { - // Diagnostic functions - - /** - * Check if we are running in the worker. - * Only used for testing - */ - isRunningInWorker(): boolean { - return isWorkerRuntime(); - }, - /** - * Sleep synchronously - * This blocks the entire event loop - * Only used for testing - */ - sleep(ms: number): void { - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); - return; - }, - - // Keys functions - - hashPassword( - password: string, - salt?: ArrayBuffer, - opsLimit?: PasswordOpsLimit, - memLimit?: PasswordMemLimit, - ): TransferDescriptor<[ArrayBuffer, ArrayBuffer]> { - if (salt != null) salt = Buffer.from(salt); - // It is guaranteed that `keysUtils.hashPassword` returns non-pooled buffers - const hashAndSalt = keysUtils.hashPassword( - password, - salt as PasswordSalt | undefined, - opsLimit, - memLimit, - ); - // Result is a tuple of [hash, salt] using transferable `ArrayBuffer` - const result: [ArrayBuffer, ArrayBuffer] = [ - hashAndSalt[0].buffer, - hashAndSalt[1].buffer, - ]; - return Transfer(result, [result[0], result[1]]); - }, - checkPassword( - password: string, - hash: ArrayBuffer, - salt: ArrayBuffer, - opsLimit?: PasswordOpsLimit, - memLimit?: PasswordMemLimit, - ): boolean { - hash = Buffer.from(hash); - salt = Buffer.from(salt); - return keysUtils.checkPassword( - password, - hash as PasswordHash, - salt as PasswordSalt, - opsLimit, - memLimit, - ); - }, - async generateDeterministicKeyPair(recoveryCode: RecoveryCode): Promise< - TransferDescriptor<{ - publicKey: ArrayBuffer; - privateKey: ArrayBuffer; - secretKey: ArrayBuffer; - }> - > { - const keyPair = await keysUtils.generateDeterministicKeyPair(recoveryCode); - // Result is a record of {publicKey, privateKey, secretKey} using transferable `ArrayBuffer` - const result = { - publicKey: keyPair.publicKey.buffer, - privateKey: keyPair.privateKey.buffer, - secretKey: keyPair.secretKey.buffer, - }; - return Transfer(result, [ - result.publicKey, - result.privateKey, - result.secretKey, - ]); - }, - async generateCertificate({ - certId, - subjectKeyPair, - issuerPrivateKey, - duration, - subjectAttrsExtra, - issuerAttrsExtra, - now = new Date(), - }: { - certId: ArrayBuffer; - subjectKeyPair: { - publicKey: ArrayBuffer; - privateKey: ArrayBuffer; - }; - issuerPrivateKey: ArrayBuffer; - duration: number; - subjectAttrsExtra?: Array<{ [key: string]: Array }>; - issuerAttrsExtra?: Array<{ [key: string]: Array }>; - now?: Date; - }): Promise> { - certId = IdInternal.create(certId); - subjectKeyPair.publicKey = Buffer.from(subjectKeyPair.publicKey); - subjectKeyPair.privateKey = Buffer.from(subjectKeyPair.privateKey); - issuerPrivateKey = Buffer.from(issuerPrivateKey); - const cert = await keysUtils.generateCertificate({ - certId: certId as CertId, - subjectKeyPair: subjectKeyPair as KeyPair, - issuerPrivateKey: issuerPrivateKey as PrivateKey, - duration, - subjectAttrsExtra, - issuerAttrsExtra, - now, - }); - return Transfer(cert.rawData); - }, - - // EFS functions - - encrypt( - key: ArrayBuffer, - plainText: ArrayBuffer, - ): TransferDescriptor { - const cipherText = keysUtils.encryptWithKey( - Buffer.from(key) as Key, - Buffer.from(plainText), - ); - return Transfer(cipherText.buffer); - }, - decrypt( - key: ArrayBuffer, - cipherText: ArrayBuffer, - ): TransferDescriptor | undefined { - const plainText = keysUtils.decryptWithKey( - Buffer.from(key) as Key, - Buffer.from(cipherText), - ); - if (plainText != null) { - return Transfer(plainText.buffer); - } else { - return; - } - }, -}; - -type PolykeyWorkerModule = typeof polykeyWorker; - -export type { PolykeyWorkerModule }; - -export default polykeyWorker; diff --git a/src/workers/types.ts b/src/workers/types.ts index 293232ca38..a310d571ab 100644 --- a/src/workers/types.ts +++ b/src/workers/types.ts @@ -1,7 +1,4 @@ -import type { WorkerManagerInterface } from '@matrixai/workers'; -import type { PolykeyWorkerModule } from './polykeyWorkerModule'; - -type PolykeyWorkerManagerInterface = - WorkerManagerInterface; - -export type { PolykeyWorkerManagerInterface }; +import type { PolykeyWorkerManifest } from './polykeyWorkerManifest.js'; +import type { WorkerManager } from '@matrixai/workers'; +type PolykeyWorkerManager = WorkerManager; +export type { PolykeyWorkerManifest, PolykeyWorkerManager }; diff --git a/src/workers/utils.ts b/src/workers/utils.ts index 1e8ba3fc32..38c07fe05a 100644 --- a/src/workers/utils.ts +++ b/src/workers/utils.ts @@ -1,9 +1,20 @@ -import type { PolykeyWorkerModule } from './polykeyWorkerModule'; -import type { PolykeyWorkerManagerInterface } from './types'; +import type { + PolykeyWorkerManager, + PolykeyWorkerManifest, +} from '../workers/index.js'; import type Logger from '@matrixai/logger'; +import path from 'node:path'; +import url from 'node:url'; +import { Worker } from 'node:worker_threads'; import { WorkerManager } from '@matrixai/workers'; -import { spawn, Worker } from 'threads'; -import * as workerErrors from './errors'; +import * as workerErrors from './errors.js'; +import { polykeyWorkerManifest } from '../workers/index.js'; + +const dirname = url.fileURLToPath(new URL('.', import.meta.url)); +const workerPath = path.join( + dirname, + '../../dist/workers/polykeyWorkerManifest.js', +); async function createWorkerManager({ cores, @@ -11,15 +22,34 @@ async function createWorkerManager({ }: { cores?: number; logger?: Logger; -}): Promise { +}): Promise { if (cores != null && (cores < 0 || isNaN(cores))) { throw new workerErrors.ErrorWorkersInvalidCores(); } - return await WorkerManager.createWorkerManager({ - workerFactory: () => spawn(new Worker('./polykeyWorker')), + return await WorkerManager.createWorkerManager({ + workerFactory: () => new Worker(workerPath), + manifest: polykeyWorkerManifest, cores, logger, }); } -export { createWorkerManager }; +/** + * Slice-copies the Node Buffer to a new ArrayBuffer + */ +function toArrayBuffer(b: Buffer): ArrayBuffer { + return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); +} + +/** + * Wraps ArrayBuffer in Node Buffer with zero copy + */ +function fromArrayBuffer( + b: ArrayBuffer, + offset?: number, + length?: number, +): Buffer { + return Buffer.from(b, offset, length); +} + +export { createWorkerManager, toArrayBuffer, fromArrayBuffer }; diff --git a/tests/PolykeyAgent.test.ts b/tests/PolykeyAgent.test.ts index b7031f0390..0d736175e8 100644 --- a/tests/PolykeyAgent.test.ts +++ b/tests/PolykeyAgent.test.ts @@ -1,18 +1,18 @@ -import type { StateVersion } from '@/schema/types'; -import type { CertManagerChangeData } from '@/keys/types'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +import type { StateVersion } from '#schema/types.js'; +import type { CertManagerChangeData } from '#keys/types.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import PolykeyAgent from '@/PolykeyAgent'; -import { Status } from '@/status'; -import { Schema } from '@/schema'; -import * as errors from '@/errors'; -import config from '@/config'; -import { promise } from '@/utils'; -import * as keysUtils from '@/keys/utils'; -import * as keysEvents from '@/keys/events'; -import * as testsUtils from './utils'; +import * as testsUtils from './utils/index.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import { Status } from '#status/index.js'; +import { Schema } from '#schema/index.js'; +import * as errors from '#errors.js'; +import config from '#config.js'; +import { promise } from '#utils/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as keysEvents from '#keys/events.js'; describe('PolykeyAgent', () => { const password = 'password'; @@ -145,6 +145,7 @@ describe('PolykeyAgent', () => { const nodePath = path.join(dataDir, 'polykey'); const statePath = path.join(nodePath, config.paths.stateBase); const schema = new Schema({ + fs, statePath, }); const pkAgent = await PolykeyAgent.createPolykeyAgent({ diff --git a/tests/PolykeyClient.test.ts b/tests/PolykeyClient.test.ts index 537ecab06f..9db9f15c6f 100644 --- a/tests/PolykeyClient.test.ts +++ b/tests/PolykeyClient.test.ts @@ -1,25 +1,25 @@ -import type { SessionToken } from '@/sessions/types'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +import type { SessionToken } from '#sessions/types.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; import net from 'net'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { utils as webSocketUtils, errors as webSocketErrors, } from '@matrixai/ws'; -import { running } from '@matrixai/async-init/dist/CreateDestroyStartStop'; -import PolykeyAgent from '@/PolykeyAgent'; -import PolykeyClient from '@/PolykeyClient'; -import Session from '@/sessions/Session'; -import config from '@/config'; -import * as ids from '@/ids'; -import * as clientUtils from '@/client/utils'; -import * as keysUtils from '@/keys/utils'; -import * as errors from '@/errors'; -import * as events from '@/events'; -import * as utils from '@/utils'; -import * as testsUtils from './utils'; +import { createDestroyStartStop } from '@matrixai/async-init'; +import * as testsUtils from './utils/index.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import PolykeyClient from '#PolykeyClient.js'; +import Session from '#sessions/Session.js'; +import config from '#config.js'; +import * as ids from '#ids/index.js'; +import * as clientUtils from '#client/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as errors from '#errors.js'; +import * as events from '#events.js'; +import * as utils from '#utils/index.js'; describe(PolykeyClient.name, () => { const logger = new Logger(`${PolykeyClient.name} Test`, LogLevel.WARN, [ @@ -230,7 +230,7 @@ describe(PolykeyClient.name, () => { // Promise that resolves when status changes await pkClient.webSocketClient.destroy({ force: true }); await expect(stoppedP).toResolve(); - expect(pkClient[running]).toBe(false); + expect(pkClient[createDestroyStartStop.running]).toBe(false); }); }); }); diff --git a/tests/acl/ACL.test.ts b/tests/acl/ACL.test.ts index 68c079be9a..1b5604bf03 100644 --- a/tests/acl/ACL.test.ts +++ b/tests/acl/ACL.test.ts @@ -1,19 +1,18 @@ -import type { Permission } from '@/acl/types'; -import type { NodeId } from '@/ids/types'; -import type { VaultAction, VaultId } from '@/vaults/types'; -import type { GestaltAction } from '@/gestalts/types'; -import type { Key } from '@/keys/types'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +import type { Permission } from '#acl/types.js'; +import type { NodeId } from '#ids/types.js'; +import type { VaultAction, VaultId } from '#vaults/types.js'; +import type { GestaltAction } from '#gestalts/types.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import ACL from '@/acl/ACL'; -import * as utils from '@/utils'; -import * as aclErrors from '@/acl/errors'; -import * as keysUtils from '@/keys/utils'; -import * as vaultsUtils from '@/vaults/utils'; -import * as testNodesUtils from '../nodes/utils'; +import * as testNodesUtils from '../nodes/utils.js'; +import ACL from '#acl/ACL.js'; +import * as aclErrors from '#acl/errors.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe(ACL.name, () => { const logger = new Logger(`${ACL.name} test`, LogLevel.WARN, [ @@ -49,20 +48,7 @@ describe(ACL.name, () => { logger, crypto: { key: dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); vaultId1 = vaultIdGenerator(); diff --git a/tests/acl/utils.test.ts b/tests/acl/utils.test.ts index c001ac6958..b8ab77e285 100644 --- a/tests/acl/utils.test.ts +++ b/tests/acl/utils.test.ts @@ -1,4 +1,4 @@ -import * as aclUtils from '@/acl/utils'; +import * as aclUtils from '#acl/utils.js'; describe('acl/utils', () => { test('merging permissions', async () => { diff --git a/tests/acl/utils.ts b/tests/acl/utils.ts index c435d9cfbe..0b4788b1d2 100644 --- a/tests/acl/utils.ts +++ b/tests/acl/utils.ts @@ -1,38 +1,46 @@ import type { DB } from '@matrixai/db'; -import type { Permission } from '@/acl/types'; -import type { NodeId, VaultId } from '@/ids/types'; +import type { Permission } from '#acl/types.js'; +import type { NodeId, VaultId } from '#ids/types.js'; import fc from 'fast-check'; import Logger, { LogLevel } from '@matrixai/logger'; import { IdInternal } from '@matrixai/id'; -import ACL from '@/acl/ACL'; -import * as testsGestaltsUtils from '../gestalts/utils'; -import * as testsVaultsUtils from '../vaults/utils'; -import * as testsIdsUtils from '../ids/utils'; +import * as testsGestaltsUtils from '../gestalts/utils.js'; +import * as testsVaultsUtils from '../vaults/utils.js'; +import * as testsIdsUtils from '../ids/utils.js'; +import ACL from '#acl/ACL.js'; const permissionArb = (vaultIds: Array = []) => - fc.record({ - gestalt: testsGestaltsUtils.gestaltActionsArb(), - vaults: - vaultIds.length < 1 - ? fc.constant({}) - : fc.dictionary( - fc.constantFrom(...vaultIds.map((id) => id.toString())), - testsVaultsUtils.vaultActionsArb, - { - minKeys: vaultIds.length, - maxKeys: vaultIds.length, - }, - ), - }) as fc.Arbitrary; + fc.record( + { + gestalt: testsGestaltsUtils.gestaltActionsArb(), + vaults: + vaultIds.length < 1 + ? fc.constant({}) + : fc.dictionary( + fc.constantFrom(...vaultIds.map((id) => id.toString())), + testsVaultsUtils.vaultActionsArb, + { + minKeys: vaultIds.length, + maxKeys: vaultIds.length, + noNullPrototype: true, + }, + ), + }, + { noNullPrototype: true }, + ) as fc.Arbitrary; const aclFactoryArb = (vaultIds: Array = []) => { return fc - .record({ - nodes: fc.dictionary( - testsIdsUtils.nodeIdStringArb, - permissionArb(vaultIds), - ), - }) + .record( + { + nodes: fc.dictionary( + testsIdsUtils.nodeIdStringArb, + permissionArb(vaultIds), + { noNullPrototype: true }, + ), + }, + { noNullPrototype: true }, + ) .map(({ nodes }) => { const logger = new Logger(undefined, LogLevel.SILENT); return async (db: DB) => { diff --git a/tests/audit/Audit.test.ts b/tests/audit/Audit.test.ts index e46a83ac5e..75a3f61b20 100644 --- a/tests/audit/Audit.test.ts +++ b/tests/audit/Audit.test.ts @@ -1,20 +1,20 @@ -import type { Key } from '@/keys/types'; -import type { ConnectionData, Host, Port } from '@/network/types'; -import type NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +import type { ConnectionData, Host, Port } from '#network/types.js'; +import type NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import Audit from '@/audit/Audit'; -import * as utils from '@/utils'; -import * as auditErrors from '@/audit/errors'; -import * as auditEvents from '@/audit/events'; -import * as keysUtils from '@/keys/utils'; -import * as nodeEvents from '@/nodes/events'; -import * as nodeUtils from '@/nodes/utils'; -import * as ids from '@/ids'; -import * as testNodesUtils from '../nodes/utils'; +import * as testNodesUtils from '../nodes/utils.js'; +import Audit from '#audit/Audit.js'; +import * as utils from '#utils/index.js'; +import * as auditErrors from '#audit/errors.js'; +import * as auditEvents from '#audit/events.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodeEvents from '#nodes/events.js'; +import * as nodeUtils from '#nodes/utils.js'; +import * as ids from '#ids/index.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe(Audit.name, () => { const logger = new Logger(`${Audit.name} test`, LogLevel.WARN, [ @@ -35,20 +35,7 @@ describe(Audit.name, () => { logger, crypto: { key: dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); mockNodeConnectionManager = new EventTarget() as NodeConnectionManager; diff --git a/tests/audit/utils.test.ts b/tests/audit/utils.test.ts index 6555b334d5..040e4d48e9 100644 --- a/tests/audit/utils.test.ts +++ b/tests/audit/utils.test.ts @@ -1,6 +1,6 @@ import fc from 'fast-check'; import { test } from '@fast-check/jest'; -import * as auditUtils from '@/audit/utils'; +import * as auditUtils from '#audit/utils.js'; describe('Audit Utils', () => { const sortFn = (a: number, b: number): number => { @@ -59,7 +59,7 @@ describe('Audit Utils', () => { expect(filtered).not.toInclude('e.f'); expect(filtered).not.toInclude('e.g'); }); - test.prop([fc.array(orderedNumberArrayArb).noShrink()])( + test.prop([fc.noShrink(fc.array(orderedNumberArrayArb))])( 'can combine strictly ordered iterators', async (generatorData) => { async function* gen( diff --git a/tests/bootstrap/utils.test.ts b/tests/bootstrap/utils.test.ts index e3a6b332ad..b03e72e2b8 100644 --- a/tests/bootstrap/utils.test.ts +++ b/tests/bootstrap/utils.test.ts @@ -1,11 +1,11 @@ -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import * as bootstrapUtils from '@/bootstrap/utils'; -import * as bootstrapErrors from '@/bootstrap/errors'; -import { errors as statusErrors } from '@/status'; -import config from '@/config'; +import * as bootstrapUtils from '#bootstrap/utils.js'; +import * as bootstrapErrors from '#bootstrap/errors.js'; +import { errors as statusErrors } from '#status/index.js'; +import config from '#config.js'; describe('bootstrap/utils', () => { const logger = new Logger('bootstrap/utils test', LogLevel.WARN, [ diff --git a/tests/claims/payloads/claimLinkIdentity.test.ts b/tests/claims/payloads/claimLinkIdentity.test.ts index 8836491669..71c7c5432b 100644 --- a/tests/claims/payloads/claimLinkIdentity.test.ts +++ b/tests/claims/payloads/claimLinkIdentity.test.ts @@ -1,6 +1,6 @@ import { test, fc } from '@fast-check/jest'; -import * as claimsPayloadsClaimLinkIdentity from '@/claims/payloads/claimLinkIdentity'; -import * as testsClaimsPayloadsUtils from './utils'; +import * as testsClaimsPayloadsUtils from './utils.js'; +import * as claimsPayloadsClaimLinkIdentity from '#claims/payloads/claimLinkIdentity.js'; describe('claims/payloads/claimLinkIdentity', () => { test.prop([ @@ -25,10 +25,13 @@ describe('claims/payloads/claimLinkIdentity', () => { testsClaimsPayloadsUtils.signedClaimEncodedArb( testsClaimsPayloadsUtils.claimLinkIdentityArb, ), - fc.record({ - payload: fc.string(), - signatures: fc.array(fc.string()), - }), + fc.record( + { + payload: fc.string(), + signatures: fc.array(fc.string()), + }, + { noNullPrototype: true }, + ), ])( 'parse signed claim link identity', ( diff --git a/tests/claims/payloads/claimLinkNode.test.ts b/tests/claims/payloads/claimLinkNode.test.ts index 07d4f9d407..404a0966e3 100644 --- a/tests/claims/payloads/claimLinkNode.test.ts +++ b/tests/claims/payloads/claimLinkNode.test.ts @@ -1,6 +1,6 @@ import { test, fc } from '@fast-check/jest'; -import * as claimsPayloadsClaimLinkNode from '@/claims/payloads/claimLinkNode'; -import * as testsClaimsPayloadsUtils from './utils'; +import * as testsClaimsPayloadsUtils from './utils.js'; +import * as claimsPayloadsClaimLinkNode from '#claims/payloads/claimLinkNode.js'; describe('claims/payloads/claimLinkNode', () => { test.prop([testsClaimsPayloadsUtils.claimLinkNodeEncodedArb, fc.string()])( @@ -22,10 +22,13 @@ describe('claims/payloads/claimLinkNode', () => { testsClaimsPayloadsUtils.signedClaimEncodedArb( testsClaimsPayloadsUtils.claimLinkNodeArb, ), - fc.record({ - payload: fc.string(), - signatures: fc.array(fc.string()), - }), + fc.record( + { + payload: fc.string(), + signatures: fc.array(fc.string()), + }, + { noNullPrototype: true }, + ), ])( 'parse signed claim link node', ( diff --git a/tests/claims/payloads/utils.ts b/tests/claims/payloads/utils.ts index 6810a24a56..1b1678b358 100644 --- a/tests/claims/payloads/utils.ts +++ b/tests/claims/payloads/utils.ts @@ -1,17 +1,23 @@ -import type { Claim, SignedClaim } from '@/claims/types'; -import type { ClaimLinkNode, ClaimLinkIdentity } from '@/claims/payloads'; +import type { Claim, SignedClaim } from '#claims/types.js'; +import type { + ClaimLinkNode, + ClaimLinkIdentity, +} from '#claims/payloads/index.js'; import fc from 'fast-check'; -import * as claimsUtils from '@/claims/utils'; -import * as testsClaimsUtils from '../utils'; -import * as testsTokensUtils from '../../tokens/utils'; -import * as testsIdsUtils from '../../ids/utils'; +import * as testsClaimsUtils from '../utils.js'; +import * as testsTokensUtils from '../../tokens/utils.js'; +import * as testsIdsUtils from '../../ids/utils.js'; +import * as claimsUtils from '#claims/utils.js'; const claimLinkIdentityArb = testsClaimsUtils.claimArb.chain((claim) => { return fc - .record({ - iss: testsIdsUtils.nodeIdEncodedArb, - sub: testsIdsUtils.providerIdentityIdEncodedArb, - }) + .record( + { + iss: testsIdsUtils.nodeIdEncodedArb, + sub: testsIdsUtils.providerIdentityIdEncodedArb, + }, + { noNullPrototype: true }, + ) .chain((value) => { return fc.constant({ typ: 'ClaimLinkIdentity', @@ -27,10 +33,13 @@ const claimLinkIdentityEncodedArb = claimLinkIdentityArb.map( const claimLinkNodeArb = testsClaimsUtils.claimArb.chain((claim) => { return fc - .record({ - iss: testsIdsUtils.nodeIdEncodedArb, - sub: testsIdsUtils.nodeIdEncodedArb, - }) + .record( + { + iss: testsIdsUtils.nodeIdEncodedArb, + sub: testsIdsUtils.nodeIdEncodedArb, + }, + { noNullPrototype: true }, + ) .chain((value) => { return fc.constant({ typ: 'ClaimLinkNode', @@ -45,10 +54,13 @@ const claimLinkNodeEncodedArb = claimLinkNodeArb.map(claimsUtils.generateClaim); const signedClaimArb =

( payloadArb: fc.Arbitrary

, ): fc.Arbitrary> => { - return fc.record({ - payload: payloadArb, - signatures: fc.array(testsTokensUtils.tokenHeaderSignatureArb), - }); + return fc.record( + { + payload: payloadArb, + signatures: fc.array(testsTokensUtils.tokenHeaderSignatureArb), + }, + { noNullPrototype: true }, + ); }; const signedClaimEncodedArb = (payloadArb: fc.Arbitrary) => diff --git a/tests/claims/utils.test.ts b/tests/claims/utils.test.ts index ae8e8dc296..44771fff56 100644 --- a/tests/claims/utils.test.ts +++ b/tests/claims/utils.test.ts @@ -1,7 +1,7 @@ import { test, fc } from '@fast-check/jest'; -import * as claimsUtils from '@/claims/utils'; -import * as validationErrors from '@/validation/errors'; -import * as testsClaimsUtils from './utils'; +import * as testsClaimsUtils from './utils.js'; +import * as claimsUtils from '#claims/utils.js'; +import * as validationErrors from '#validation/errors.js'; describe('claims/utils', () => { test.prop([testsClaimsUtils.claimEncodedArb, fc.string()])( @@ -17,10 +17,13 @@ describe('claims/utils', () => { ); test.prop([ testsClaimsUtils.signedClaimEncodedArb, - fc.record({ - payload: fc.string(), - signatures: fc.array(fc.string()), - }), + fc.record( + { + payload: fc.string(), + signatures: fc.array(fc.string()), + }, + { noNullPrototype: true }, + ), ])( 'parse signed claim', (signedClaimEncodedCorrect, signedClaimEncodedIncorrect) => { diff --git a/tests/claims/utils.ts b/tests/claims/utils.ts index 8561bccd69..59f5745950 100644 --- a/tests/claims/utils.ts +++ b/tests/claims/utils.ts @@ -1,22 +1,39 @@ -import type { SignedClaim } from '@/claims/types'; +import type { + ClaimIdEncoded, + SignedClaim, + SignedClaimDigestEncoded, +} from '#claims/types.js'; import { fc } from '@fast-check/jest'; -import * as claimsUtils from '@/claims/utils'; -import * as testsTokensUtils from '../tokens/utils'; -import * as testsIdsUtils from '../ids/utils'; +import * as testsTokensUtils from '../tokens/utils.js'; +import * as testsIdsUtils from '../ids/utils.js'; +import * as claimsUtils from '#claims/utils.js'; -const claimInitialArb = fc.record({ - jti: testsIdsUtils.claimIdEncodedArb, - iat: fc.nat(), - nbf: fc.nat(), - seq: fc.constant(1), - prevClaimId: fc.constant(null), - prevDigest: fc.constant(null), -}); +const claimInitialArb: fc.Arbitrary<{ + jti: ClaimIdEncoded; + iat: number; + nbf: number; + seq: 1; + prevClaimId: null; + prevDigest: null; +}> = fc.record( + { + jti: testsIdsUtils.claimIdEncodedArb, + iat: fc.nat(), + nbf: fc.nat(), + seq: fc.constant(1), + prevClaimId: fc.constant(null), + prevDigest: fc.constant(null), + }, + { noNullPrototype: true }, +); -const signedClaimInitialArb = fc.record({ - payload: claimInitialArb, - signatures: fc.array(testsTokensUtils.tokenHeaderSignatureArb), -}) as fc.Arbitrary; +const signedClaimInitialArb = fc.record( + { + payload: claimInitialArb, + signatures: fc.array(testsTokensUtils.tokenHeaderSignatureArb), + }, + { noNullPrototype: true }, +) as fc.Arbitrary; const signedClaimDigestArb = signedClaimInitialArb.map((signedClaimInitial) => { return claimsUtils.hashSignedClaim(signedClaimInitial, 'blake2b-256'); @@ -31,24 +48,47 @@ const signedClaimDigestEncodedArb = signedClaimDigestArb.map( }, ); -const claimArb = fc.oneof( +const claimArb: fc.Arbitrary< + | { + jti: ClaimIdEncoded; + iat: number; + nbf: number; + seq: 1; + prevClaimId: null; + prevDigest: null; + } + | { + jti: ClaimIdEncoded; + iat: number; + nbf: number; + seq: number; + prevClaimId: ClaimIdEncoded; + prevDigest: SignedClaimDigestEncoded; + } +> = fc.oneof( claimInitialArb, - fc.record({ - jti: testsIdsUtils.claimIdEncodedArb, - iat: fc.nat(), - nbf: fc.nat(), - seq: fc.nat(), - prevClaimId: testsIdsUtils.claimIdEncodedArb, - prevDigest: signedClaimDigestEncodedArb, - }), + fc.record( + { + jti: testsIdsUtils.claimIdEncodedArb, + iat: fc.nat(), + nbf: fc.nat(), + seq: fc.nat(), + prevClaimId: testsIdsUtils.claimIdEncodedArb, + prevDigest: signedClaimDigestEncodedArb, + }, + { noNullPrototype: true }, + ), ); const claimEncodedArb = claimArb.map(claimsUtils.generateClaim); -const signedClaimArb = fc.record({ - payload: claimArb, - signatures: fc.array(testsTokensUtils.tokenHeaderSignatureArb), -}) as fc.Arbitrary; +const signedClaimArb = fc.record( + { + payload: claimArb, + signatures: fc.array(testsTokensUtils.tokenHeaderSignatureArb), + }, + { noNullPrototype: true }, +) as fc.Arbitrary; const signedClaimEncodedArb = signedClaimArb.map( claimsUtils.generateSignedClaim, diff --git a/tests/client/ClientService.test.ts b/tests/client/ClientService.test.ts index 4d01ccf41c..14e1b8ffe5 100644 --- a/tests/client/ClientService.test.ts +++ b/tests/client/ClientService.test.ts @@ -1,8 +1,8 @@ -import type { TLSConfig } from '@/network/types'; +import type { TLSConfig } from '#network/types.js'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; -import ClientService from '@/client/ClientService'; -import * as keysUtils from '@/keys/utils'; -import * as testsUtils from '../utils'; +import * as testsUtils from '../utils/index.js'; +import ClientService from '#client/ClientService.js'; +import * as keysUtils from '#keys/utils/index.js'; describe(`ClientService tests`, () => { const logger = new Logger(`${ClientService.name} test`, LogLevel.WARN, [ diff --git a/tests/client/authenticationMiddleware.test.ts b/tests/client/authenticationMiddleware.test.ts index ca0d89b05b..93bde809af 100644 --- a/tests/client/authenticationMiddleware.test.ts +++ b/tests/client/authenticationMiddleware.test.ts @@ -1,11 +1,11 @@ import type { ClientRPCRequestParams, ClientRPCResponseResult, -} from '@/client/types'; -import type { TLSConfig } from '../../src/network/types'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +} from '#client/types.js'; +import type { TLSConfig } from '#network/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { @@ -15,16 +15,16 @@ import { middleware as rpcUtilsMiddleware, } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import KeyRing from '@/keys/KeyRing'; -import TaskManager from '@/tasks/TaskManager'; -import CertManager from '@/keys/CertManager'; -import ClientService from '@/client/ClientService'; -import { Session, SessionManager } from '@/sessions'; -import * as authMiddleware from '@/client/authenticationMiddleware'; -import * as keysUtils from '@/keys/utils'; -import * as clientUtils from '@/client/utils'; -import * as networkUtils from '@/network/utils'; -import * as testsUtils from '../utils'; +import * as testsUtils from '../utils/index.js'; +import KeyRing from '#keys/KeyRing.js'; +import TaskManager from '#tasks/TaskManager.js'; +import CertManager from '#keys/CertManager.js'; +import ClientService from '#client/ClientService.js'; +import { Session, SessionManager } from '#sessions/index.js'; +import * as authMiddleware from '#client/authenticationMiddleware.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as clientUtils from '#client/utils.js'; +import * as networkUtils from '#network/utils.js'; describe('authenticationMiddleware', () => { const logger = new Logger('agentUnlock test', LogLevel.WARN, [ diff --git a/tests/client/handlers/agent.test.ts b/tests/client/handlers/agent.test.ts index a88b680877..ec48b26941 100644 --- a/tests/client/handlers/agent.test.ts +++ b/tests/client/handlers/agent.test.ts @@ -1,39 +1,39 @@ -import type { TLSConfig } from '@/network/types'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type { TLSConfig } from '#network/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { running } from '@matrixai/async-init'; import { RPCClient, middleware as rpcUtilsMiddleware } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import KeyRing from '@/keys/KeyRing'; -import CertManager from '@/keys/CertManager'; -import TaskManager from '@/tasks/TaskManager'; -import PolykeyAgent from '@/PolykeyAgent'; -import Status from '@/status/Status'; -import ClientService from '@/client/ClientService'; -import Session from '@/sessions/Session'; -import SessionManager from '@/sessions/SessionManager'; -import config from '@/config'; +import * as testsUtils from '../../utils/index.js'; +import KeyRing from '#keys/KeyRing.js'; +import CertManager from '#keys/CertManager.js'; +import TaskManager from '#tasks/TaskManager.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import Status from '#status/Status.js'; +import ClientService from '#client/ClientService.js'; +import Session from '#sessions/Session.js'; +import SessionManager from '#sessions/SessionManager.js'; +import config from '#config.js'; import { AgentLockAll, AgentStatus, AgentStop, AgentUnlock, -} from '@/client/handlers'; +} from '#client/handlers/index.js'; import { agentLockAll, agentStatus, agentStop, agentUnlock, -} from '@/client/callers'; -import * as clientUtils from '@/client/utils'; -import * as clientUtilsAuthMiddleware from '@/client/authenticationMiddleware'; -import * as keysUtils from '@/keys/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as networkUtils from '@/network/utils'; -import * as testsUtils from '../../utils'; +} from '#client/callers/index.js'; +import * as clientUtils from '#client/utils.js'; +import * as clientUtilsAuthMiddleware from '#client/authenticationMiddleware.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as networkUtils from '#network/utils.js'; describe('agentLockAll', () => { const logger = new Logger('agentLockAll test', LogLevel.WARN, [ diff --git a/tests/client/handlers/audit.test.ts b/tests/client/handlers/audit.test.ts index 3cc432d317..1e39aedd8d 100644 --- a/tests/client/handlers/audit.test.ts +++ b/tests/client/handlers/audit.test.ts @@ -1,30 +1,30 @@ -import type { ConnectionData, Host, Port, TLSConfig } from '@/network/types'; -import type { OverrideRPClientType } from '@/client/types'; -import type NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import type Discovery from '@/discovery/Discovery'; -import type { GestaltIdEncoded } from '@/ids'; -import type { POJO } from '@'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type { ConnectionData, Host, Port, TLSConfig } from '#network/types.js'; +import type { OverrideRPClientType } from '#client/types.js'; +import type NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import type Discovery from '#discovery/Discovery.js'; +import type { GestaltIdEncoded } from '#ids/index.js'; +import type { POJO } from '#index.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { RPCClient } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import KeyRing from '@/keys/KeyRing'; -import ClientService from '@/client/ClientService'; -import * as keysUtils from '@/keys/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as nodesEvents from '@/nodes/events'; -import * as discoveryEvents from '@/discovery/events'; -import * as networkUtils from '@/network/utils'; -import { Audit } from '@/audit'; -import AuditMetricGet from '@/client/handlers/AuditMetricGet'; -import AuditEventsGet from '@/client/handlers/AuditEventsGet'; -import auditMetricGet from '@/client/callers/auditMetricGet'; -import auditEventsGet from '@/client/callers/auditEventsGet'; -import * as testsUtils from '../../utils'; -import * as testNodesUtils from '../../nodes/utils'; +import * as testsUtils from '../../utils/index.js'; +import * as testNodesUtils from '../../nodes/utils.js'; +import KeyRing from '#keys/KeyRing.js'; +import ClientService from '#client/ClientService.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as nodesEvents from '#nodes/events.js'; +import * as discoveryEvents from '#discovery/events.js'; +import * as networkUtils from '#network/utils.js'; +import { Audit } from '#audit/index.js'; +import AuditMetricGet from '#client/handlers/AuditMetricGet.js'; +import AuditEventsGet from '#client/handlers/AuditEventsGet.js'; +import auditMetricGet from '#client/callers/auditMetricGet.js'; +import auditEventsGet from '#client/callers/auditEventsGet.js'; describe('auditEventGet', () => { const logger = new Logger('auditEventsGet test', LogLevel.WARN, [ diff --git a/tests/client/handlers/gestalts.test.ts b/tests/client/handlers/gestalts.test.ts index cdbefcec42..bac25fa742 100644 --- a/tests/client/handlers/gestalts.test.ts +++ b/tests/client/handlers/gestalts.test.ts @@ -6,38 +6,42 @@ import type { ClaimId, NodeId, NodeIdEncoded, -} from '@/ids'; -import type { TLSConfig } from '@/network/types'; +} from '#ids/index.js'; +import type { TLSConfig } from '#network/types.js'; import type { Gestalt, GestaltIdentityInfo, GestaltNodeInfo, -} from '@/gestalts/types'; -import type { SignedClaim } from '@/claims/types'; -import type { Host } from '@/network/types'; -import type { ClaimLinkIdentity } from '@/claims/payloads'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import type { DiscoveryQueueInfo } from '@/discovery/types'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +} from '#gestalts/types.js'; +import type { SignedClaim } from '#claims/types.js'; +import type { Host } from '#network/types.js'; +import type { ClaimLinkIdentity } from '#claims/payloads/index.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import type { DiscoveryQueueInfo } from '#discovery/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { jest } from '@jest/globals'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { RPCClient } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import KeyRing from '@/keys/KeyRing'; -import TaskManager from '@/tasks/TaskManager'; -import ACL from '@/acl/ACL'; -import GestaltGraph from '@/gestalts/GestaltGraph'; -import PolykeyAgent from '@/PolykeyAgent'; -import Token from '@/tokens/Token'; -import IdentitiesManager from '@/identities/IdentitiesManager'; -import NodeGraph from '@/nodes/NodeGraph'; -import NodeManager from '@/nodes/NodeManager'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import Sigchain from '@/sigchain/Sigchain'; -import Discovery from '@/discovery/Discovery'; -import ClientService from '@/client/ClientService'; +import * as testsUtils from '../../utils/index.js'; +import * as testNodesUtils from '../../nodes/utils.js'; +import TestProvider from '../../identities/TestProvider.js'; +import KeyRing from '#keys/KeyRing.js'; +import TaskManager from '#tasks/TaskManager.js'; +import ACL from '#acl/ACL.js'; +import GestaltGraph from '#gestalts/GestaltGraph.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import Token from '#tokens/Token.js'; +import IdentitiesManager from '#identities/IdentitiesManager.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import NodeManager from '#nodes/NodeManager.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import Discovery from '#discovery/Discovery.js'; +import ClientService from '#client/ClientService.js'; import { GestaltsActionsGetByIdentity, GestaltsActionsSetByIdentity, @@ -53,7 +57,7 @@ import { GestaltsGestaltList, GestaltsGestaltTrustByIdentity, GestaltsGestaltTrustByNode, -} from '@/client/handlers'; +} from '#client/handlers/index.js'; import { gestaltsActionsGetByIdentity, gestaltsActionsGetByNode, @@ -69,17 +73,14 @@ import { gestaltsGestaltList, gestaltsGestaltTrustByIdentity, gestaltsGestaltTrustByNode, -} from '@/client/callers'; -import { encodeProviderIdentityId } from '@/ids'; -import * as nodesUtils from '@/nodes/utils'; -import * as gestaltUtils from '@/gestalts/utils'; -import * as gestaltsErrors from '@/gestalts/errors'; -import * as networkUtils from '@/network/utils'; -import * as keysUtils from '@/keys/utils'; -import * as utils from '@/utils'; -import * as testsUtils from '../../utils'; -import * as testNodesUtils from '../../nodes/utils'; -import TestProvider from '../../identities/TestProvider'; +} from '#client/callers/index.js'; +import { encodeProviderIdentityId } from '#ids/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as gestaltUtils from '#gestalts/utils.js'; +import * as gestaltsErrors from '#gestalts/errors.js'; +import * as networkUtils from '#network/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as utils from '#utils/index.js'; describe('gestaltsActionsByIdentity', () => { const logger = new Logger('gestaltsActionsByIdentity test', LogLevel.WARN, [ @@ -1754,7 +1755,9 @@ describe('gestaltsGestaltTrustByNode', () => { let nodeIdRemote: NodeId; let nodeIdEncodedRemote: NodeIdEncoded; let node: PolykeyAgent; - let mockedRequestChainData: jest.SpyInstance; + let mockedRequestChainData: jest.SpiedFunction< + typeof NodeManager.prototype.requestChainData + >; let nodeDataDir: string; beforeEach(async () => { testProvider = new TestProvider(); diff --git a/tests/client/handlers/identities.test.ts b/tests/client/handlers/identities.test.ts index 6b54c62db2..812345f4a7 100644 --- a/tests/client/handlers/identities.test.ts +++ b/tests/client/handlers/identities.test.ts @@ -1,27 +1,30 @@ -import type GestaltGraph from '@/gestalts/GestaltGraph'; -import type { IdentityId, ProviderId } from '@/ids'; +import type GestaltGraph from '#gestalts/GestaltGraph.js'; +import type { IdentityId, ProviderId } from '#ids/index.js'; import type { ClientRPCResponseResult, IdentityInfoMessage, IdentityMessage, -} from '@/client/types'; -import type { TLSConfig } from '@/network/types'; -import type { Claim } from '@/claims/types'; -import type { ClaimLinkIdentity } from '@/claims/payloads'; -import type ACL from '@/acl/ACL'; -import type NotificationsManager from '@/notifications/NotificationsManager'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +} from '#client/types.js'; +import type { TLSConfig } from '#network/types.js'; +import type { Claim } from '#claims/types.js'; +import type { ClaimLinkIdentity } from '#claims/payloads/index.js'; +import type ACL from '#acl/ACL.js'; +import type NotificationsManager from '#notifications/NotificationsManager.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { jest } from '@jest/globals'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { RPCClient } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import Token from '@/tokens/Token'; -import Sigchain from '@/sigchain/Sigchain'; -import KeyRing from '@/keys/KeyRing'; -import IdentitiesManager from '@/identities/IdentitiesManager'; -import ClientService from '@/client/ClientService'; +import * as testsUtils from '../../utils/index.js'; +import TestProvider from '../../identities/TestProvider.js'; +import Token from '#tokens/Token.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import KeyRing from '#keys/KeyRing.js'; +import IdentitiesManager from '#identities/IdentitiesManager.js'; +import ClientService from '#client/ClientService.js'; import { IdentitiesAuthenticate, IdentitiesAuthenticatedGet, @@ -33,7 +36,7 @@ import { IdentitiesTokenDelete, IdentitiesTokenGet, IdentitiesTokenPut, -} from '@/client/handlers'; +} from '#client/handlers/index.js'; import { identitiesAuthenticate, identitiesAuthenticatedGet, @@ -45,17 +48,14 @@ import { identitiesTokenDelete, identitiesTokenGet, identitiesTokenPut, -} from '@/client/callers'; -import { encodeProviderIdentityId } from '@/ids'; -import * as keysUtils from '@/keys/utils'; -import * as validationErrors from '@/validation/errors'; -import * as claimsUtils from '@/claims/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as identitiesErrors from '@/identities/errors'; -import * as networkUtils from '@/network/utils'; -import * as testUtils from '../../utils'; -import * as testsUtils from '../../utils'; -import TestProvider from '../../identities/TestProvider'; +} from '#client/callers/index.js'; +import { encodeProviderIdentityId } from '#ids/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as validationErrors from '#validation/errors.js'; +import * as claimsUtils from '#claims/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as identitiesErrors from '#identities/errors.js'; +import * as networkUtils from '#network/utils.js'; describe('identitiesAuthenticate', () => { const logger = new Logger('identitiesAuthenticate test', LogLevel.WARN, [ @@ -191,7 +191,7 @@ describe('identitiesAuthenticate', () => { }; const response = await rpcClient.methods.identitiesAuthenticate(request); const reader = response.getReader(); - await testUtils.expectRemoteError( + await testsUtils.expectRemoteError( reader.read(), validationErrors.ErrorValidation, ); @@ -440,7 +440,7 @@ describe('identitiesClaim', () => { }>; let tlsConfig: TLSConfig; let identitiesManager: IdentitiesManager; - let mockedAddClaim: jest.SpyInstance; + let mockedAddClaim: jest.SpiedFunction; let testProvider: TestProvider; let sigchain: Sigchain; const testToken = { @@ -575,21 +575,21 @@ describe('identitiesClaim', () => { }); test('cannot claim invalid identity', async () => { // Setup provider - await testUtils.expectRemoteError( + await testsUtils.expectRemoteError( rpcClient.methods.identitiesClaim({ providerId: testToken.providerId, identityId: '', }), validationErrors.ErrorValidation, ); - await testUtils.expectRemoteError( + await testsUtils.expectRemoteError( rpcClient.methods.identitiesClaim({ providerId: '', identityId: testToken.identityId, }), validationErrors.ErrorValidation, ); - await testUtils.expectRemoteError( + await testsUtils.expectRemoteError( rpcClient.methods.identitiesClaim({ providerId: '', identityId: '', @@ -1276,7 +1276,7 @@ describe('identitiesInfoConnectedGet', () => { providerIdList: [], }); const reader = response.getReader(); - await testUtils.expectRemoteError( + await testsUtils.expectRemoteError( reader.read(), identitiesErrors.ErrorProviderUnimplemented, ); @@ -1713,7 +1713,7 @@ describe('identitiesInvite', () => { }>; let tlsConfig: TLSConfig; let identitiesManager: IdentitiesManager; - let mockedAddClaim: jest.SpyInstance; + let mockedAddClaim: jest.SpiedFunction; let testProvider: TestProvider; let sigchain: Sigchain; let acl: ACL; @@ -1876,7 +1876,9 @@ describe('identitiesProvidersList', () => { const providers = {}; providers[id1] = new TestProvider(); providers[id2] = new TestProvider(); - let mockedGetProviders: jest.SpyInstance; + let mockedGetProviders: jest.SpiedFunction< + typeof IdentitiesManager.prototype.getProviders + >; beforeEach(async () => { mockedGetProviders = jest .spyOn(IdentitiesManager.prototype, 'getProviders') diff --git a/tests/client/handlers/keys.test.ts b/tests/client/handlers/keys.test.ts index 32ab50d639..af57e65593 100644 --- a/tests/client/handlers/keys.test.ts +++ b/tests/client/handlers/keys.test.ts @@ -1,21 +1,23 @@ -import type GestaltGraph from '@/gestalts/GestaltGraph'; -import type Sigchain from '@/sigchain/Sigchain'; -import type { TLSConfig } from '@/network/types'; -import type { CertificatePEM } from '@/keys/types'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type GestaltGraph from '#gestalts/GestaltGraph.js'; +import type Sigchain from '#sigchain/Sigchain.js'; +import type { TLSConfig } from '#network/types.js'; +import type { CertificatePEM } from '#keys/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { jest } from '@jest/globals'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { RPCClient } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import PolykeyAgent from '@/PolykeyAgent'; -import KeyRing from '@/keys/KeyRing'; -import CertManager from '@/keys/CertManager'; -import TaskManager from '@/tasks/TaskManager'; -import NodeManager from '@/nodes/NodeManager'; -import IdentitiesManager from '@/identities/IdentitiesManager'; -import ClientService from '@/client/ClientService'; +import * as testsUtils from '../../utils/index.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import KeyRing from '#keys/KeyRing.js'; +import CertManager from '#keys/CertManager.js'; +import TaskManager from '#tasks/TaskManager.js'; +import NodeManager from '#nodes/NodeManager.js'; +import IdentitiesManager from '#identities/IdentitiesManager.js'; +import ClientService from '#client/ClientService.js'; import { KeysCertsChainGet, KeysCertsGet, @@ -28,7 +30,7 @@ import { KeysPublicKey, KeysSign, KeysVerify, -} from '@/client/handlers'; +} from '#client/handlers/index.js'; import { keysCertsChainGet, keysCertsGet, @@ -41,12 +43,11 @@ import { keysPublicKey, keysSign, keysVerify, -} from '@/client/callers'; -import * as keysUtils from '@/keys/utils'; -import * as keysEvents from '@/keys/events'; -import * as networkUtils from '@/network/utils'; -import * as utils from '@/utils'; -import * as testsUtils from '../../utils'; +} from '#client/callers/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as keysEvents from '#keys/events.js'; +import * as networkUtils from '#network/utils.js'; +import * as utils from '#utils/index.js'; describe('keysCertsChainGet', () => { const logger = new Logger('keysCertsChainGet test', LogLevel.WARN, [ @@ -69,7 +70,9 @@ describe('keysCertsChainGet', () => { let identitiesManager: IdentitiesManager; let taskManager: TaskManager; let certManager: CertManager; - let mockedGetRootCertChainPems: jest.SpyInstance; + let mockedGetRootCertChainPems: jest.SpiedFunction< + typeof CertManager.prototype.getCertPEMsChain + >; beforeEach(async () => { mockedGetRootCertChainPems = jest .spyOn(CertManager.prototype, 'getCertPEMsChain') @@ -181,7 +184,9 @@ describe('keysCertsGet', () => { let identitiesManager: IdentitiesManager; let taskManager: TaskManager; let certManager: CertManager; - let mockedGetRootCertPem: jest.SpyInstance; + let mockedGetRootCertPem: jest.SpiedFunction< + typeof CertManager.prototype.getCurrentCertPEM + >; beforeEach(async () => { mockedGetRootCertPem = jest .spyOn(CertManager.prototype, 'getCurrentCertPEM') @@ -489,7 +494,9 @@ describe('keysKeyPairRenew', () => { let rpcClient: RPCClient<{ keysKeyPairRenew: typeof keysKeyPairRenew; }>; - let mockedRefreshBuckets: jest.SpyInstance; + let mockedRefreshBuckets: jest.SpiedFunction< + typeof NodeManager.prototype.resetBuckets + >; beforeEach(async () => { mockedRefreshBuckets = jest.spyOn(NodeManager.prototype, 'resetBuckets'); dataDir = await fs.promises.mkdtemp( @@ -618,7 +625,9 @@ describe('keysKeyPairReset', () => { }>; let pkAgent: PolykeyAgent; let tlsConfig: TLSConfig; - let mockedRefreshBuckets: jest.SpyInstance; + let mockedRefreshBuckets: jest.SpiedFunction< + typeof NodeManager.prototype.resetBuckets + >; beforeEach(async () => { mockedRefreshBuckets = jest.spyOn(NodeManager.prototype, 'resetBuckets'); dataDir = await fs.promises.mkdtemp( diff --git a/tests/client/handlers/nodes.test.ts b/tests/client/handlers/nodes.test.ts index 7a084039ae..90d099e8f6 100644 --- a/tests/client/handlers/nodes.test.ts +++ b/tests/client/handlers/nodes.test.ts @@ -1,24 +1,27 @@ -import type GestaltGraph from '@/gestalts/GestaltGraph'; -import type { NodeIdEncoded } from '@/ids/types'; -import type { TLSConfig, Host, Port } from '@/network/types'; -import type { Notification } from '@/notifications/types'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type GestaltGraph from '#gestalts/GestaltGraph.js'; +import type { NodeIdEncoded } from '#ids/types.js'; +import type { TLSConfig, Host, Port } from '#network/types.js'; +import type { Notification } from '#notifications/types.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import type { NodeAddress, NodeContactAddressData } from '#nodes/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { jest } from '@jest/globals'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { RPCClient } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import ACL from '@/acl/ACL'; -import KeyRing from '@/keys/KeyRing'; -import NodeManager from '@/nodes/NodeManager'; -import NodeGraph from '@/nodes/NodeGraph'; -import TaskManager from '@/tasks/TaskManager'; -import Sigchain from '@/sigchain/Sigchain'; -import NotificationsManager from '@/notifications/NotificationsManager'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import ClientService from '@/client/ClientService'; +import * as testsUtils from '../../utils/index.js'; +import ACL from '#acl/ACL.js'; +import KeyRing from '#keys/KeyRing.js'; +import NodeManager from '#nodes/NodeManager.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import TaskManager from '#tasks/TaskManager.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import NotificationsManager from '#notifications/NotificationsManager.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import ClientService from '#client/ClientService.js'; import { NodesAdd, NodesClaim, @@ -26,7 +29,7 @@ import { NodesPing, NodesGetAll, NodesListConnections, -} from '@/client/handlers'; +} from '#client/handlers/index.js'; import { nodesAdd, nodesClaim, @@ -34,14 +37,13 @@ import { nodesPing, nodesGetAll, nodesListConnections, -} from '@/client/callers'; -import * as keysUtils from '@/keys/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as networkUtils from '@/network/utils'; -import * as notificationsUtils from '@/notifications/utils'; -import * as validationErrors from '@/validation/errors'; -import { parseNodeId } from '@/ids'; -import * as testsUtils from '../../utils'; +} from '#client/callers/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as networkUtils from '#network/utils.js'; +import * as notificationsUtils from '#notifications/utils.js'; +import * as validationErrors from '#validation/errors.js'; +import { parseNodeId } from '#ids/index.js'; describe('nodesAdd', () => { const logger = new Logger('nodesAdd test', LogLevel.WARN, [ @@ -269,9 +271,15 @@ describe('nodesClaim', () => { let notificationsManager: NotificationsManager; let acl: ACL; let sigchain: Sigchain; - let mockedFindGestaltInvite: jest.SpyInstance; - let mockedSendNotification: jest.SpyInstance; - let mockedClaimNode: jest.SpyInstance; + let mockedFindGestaltInvite: jest.SpiedFunction< + typeof NotificationsManager.prototype.findGestaltInvite + >; + let mockedSendNotification: jest.SpiedFunction< + typeof NotificationsManager.prototype.sendNotification + >; + let mockedClaimNode: jest.SpiedFunction< + typeof NodeManager.prototype.claimNode + >; beforeEach(async () => { mockedFindGestaltInvite = jest .spyOn(NotificationsManager.prototype, 'findGestaltInvite') @@ -449,7 +457,7 @@ describe('nodesFind', () => { let nodeConnectionManager: NodeConnectionManager; let nodeManager: NodeManager; let sigchain: Sigchain; - let mockedFindNode: jest.SpyInstance; + let mockedFindNode: jest.SpiedFunction; beforeEach(async () => { mockedFindNode = jest .spyOn(NodeManager.prototype, 'findNode') @@ -605,7 +613,7 @@ describe('nodesPing', () => { let nodeConnectionManager: NodeConnectionManager; let nodeManager: NodeManager; let sigchain: Sigchain; - let mockedPingNode: jest.SpyInstance; + let mockedPingNode: jest.SpiedFunction; beforeEach(async () => { mockedPingNode = jest.spyOn(NodeManager.prototype, 'pingNode'); dataDir = await fs.promises.mkdtemp( @@ -720,7 +728,10 @@ describe('nodesPing', () => { expect(response.success).toBeFalsy(); }); test('pings a node (online)', async () => { - mockedPingNode.mockResolvedValue([]); + mockedPingNode.mockResolvedValue([['', 0], {}] as [ + NodeAddress, + NodeContactAddressData, + ]); const response = await rpcClient.methods.nodesPing({ nodeIdEncoded: 'vrsc24a1er424epq77dtoveo93meij0pc8ig4uvs9jbeld78n9nl0' as NodeIdEncoded, @@ -906,7 +917,9 @@ describe('nodesListConnections', () => { let nodeConnectionManager: NodeConnectionManager; let nodeManager: NodeManager; let sigchain: Sigchain; - let mockedConnection: jest.SpyInstance; + let mockedConnection: jest.SpiedFunction< + typeof NodeConnectionManager.prototype.listConnections + >; beforeEach(async () => { mockedConnection = jest.spyOn( NodeConnectionManager.prototype, @@ -1023,12 +1036,13 @@ describe('nodesListConnections', () => { connectionId: 'someId', primary: true, address: { - host: '127.0.0.1', - port: 11111, + host: '127.0.0.1' as Host, + port: 11111 as Port, hostname: undefined, }, usageCount: 1, timeout: undefined, + authenticated: true, }, ]); diff --git a/tests/client/handlers/notifications.test.ts b/tests/client/handlers/notifications.test.ts index 8142955493..fd84d259d5 100644 --- a/tests/client/handlers/notifications.test.ts +++ b/tests/client/handlers/notifications.test.ts @@ -1,29 +1,36 @@ -import type GestaltGraph from '@/gestalts/GestaltGraph'; -import type { Host, TLSConfig } from '@/network/types'; -import type { General, Notification, VaultShare } from '@/notifications/types'; +import type GestaltGraph from '#gestalts/GestaltGraph.js'; +import type { Host, TLSConfig } from '#network/types.js'; +import type { + General, + Notification, + VaultShare, +} from '#notifications/types.js'; import type { VaultIdEncoded, NodeIdEncoded, NotificationIdEncoded, -} from '@/ids/types'; -import type { VaultName } from '@/vaults/types'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +} from '#ids/types.js'; +import type { VaultName } from '#vaults/types.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { jest } from '@jest/globals'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { RPCClient } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import KeyRing from '@/keys/KeyRing'; -import ClientService from '@/client/ClientService'; -import ACL from '@/acl/ACL'; -import Sigchain from '@/sigchain/Sigchain'; -import NodeGraph from '@/nodes/NodeGraph'; -import TaskManager from '@/tasks/TaskManager'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import NodeManager from '@/nodes/NodeManager'; -import NotificationsManager from '@/notifications/NotificationsManager'; +import * as testsNodesUtils from '../../nodes/utils.js'; +import * as testsUtils from '../../utils/index.js'; +import KeyRing from '#keys/KeyRing.js'; +import ClientService from '#client/ClientService.js'; +import ACL from '#acl/ACL.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import TaskManager from '#tasks/TaskManager.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import NodeManager from '#nodes/NodeManager.js'; +import NotificationsManager from '#notifications/NotificationsManager.js'; import { NotificationsInboxClear, NotificationsOutboxClear, @@ -32,7 +39,7 @@ import { NotificationsInboxRead, NotificationsInboxRemove, NotificationsSend, -} from '@/client/handlers'; +} from '#client/handlers/index.js'; import { notificationsInboxClear, notificationsInboxRead, @@ -41,13 +48,19 @@ import { notificationsOutboxRead, notificationsOutboxRemove, notificationsInboxRemove, -} from '@/client/callers'; -import * as nodesUtils from '@/nodes/utils'; -import * as keysUtils from '@/keys/utils'; -import * as networkUtils from '@/network/utils'; -import * as notificationsUtils from '@/notifications/utils'; -import * as testsNodesUtils from '../../nodes/utils'; -import * as testsUtils from '../../utils'; +} from '#client/callers/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as networkUtils from '#network/utils.js'; +import * as notificationsUtils from '#notifications/utils.js'; + +async function* arrayToGenerator( + array: Array, +): AsyncGenerator { + for (const value of array) { + yield value; + } +} describe('notificationsInboxClear', () => { const logger = new Logger('notificationsInboxClear test', LogLevel.WARN, [ @@ -73,7 +86,9 @@ describe('notificationsInboxClear', () => { let notificationsManager: NotificationsManager; let acl: ACL; let sigchain: Sigchain; - let mockedClearNotifications: jest.SpyInstance; + let mockedClearNotifications: jest.SpiedFunction< + typeof NotificationsManager.prototype.clearInboxNotifications + >; beforeEach(async () => { mockedClearNotifications = jest .spyOn(NotificationsManager.prototype, 'clearInboxNotifications') @@ -240,7 +255,9 @@ describe('notificationsInboxRead', () => { let notificationsManager: NotificationsManager; let acl: ACL; let sigchain: Sigchain; - let mockedReadNotifications: jest.SpyInstance; + let mockedReadNotifications: jest.SpiedFunction< + typeof NotificationsManager.prototype.readInboxNotifications + >; beforeEach(async () => { mockedReadNotifications = jest.spyOn( NotificationsManager.prototype, @@ -376,21 +393,23 @@ describe('notificationsInboxRead', () => { }); }); test('reads a single notification', async () => { - mockedReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'General', - message: 'test', + mockedReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'General', + message: 'test', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsInboxRead({ order: 'desc', limit: 1, @@ -409,36 +428,41 @@ describe('notificationsInboxRead', () => { expect(notification.sub).toBe(nodeIdReceiverEncoded); expect(notification.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedReadNotifications.mock.calls[0][0].limit).toBe(1); - expect(mockedReadNotifications.mock.calls[0][0].order).toBe('desc'); + expect(mockedReadNotifications.mock.calls[0][0]!.unread).toBeFalsy(); + expect(mockedReadNotifications.mock.calls[0][0]!.limit).toBe(1); + expect(mockedReadNotifications.mock.calls[0][0]!.order).toBe('desc'); }); test('reads unread notifications', async () => { - mockedReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'General', - message: 'test1', + mockedReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'General', + message: 'test1', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - { - typ: 'notification', - data: { - type: 'General', - message: 'test2', + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'General', + message: 'test2', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsInboxRead({ unread: true, limit: Infinity, @@ -464,36 +488,41 @@ describe('notificationsInboxRead', () => { expect(notification2.sub).toBe(nodeIdReceiverEncoded); expect(notification2.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedReadNotifications.mock.calls[0][0].unread).toBeTruthy(); - expect(mockedReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedReadNotifications.mock.calls[0][0].order).toBe('desc'); + expect(mockedReadNotifications.mock.calls[0][0]!.unread).toBeTruthy(); + expect(mockedReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedReadNotifications.mock.calls[0][0]!.order).toBe('desc'); }); test('reads notifications in reverse order', async () => { - mockedReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'General', - message: 'test2', + mockedReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'General', + message: 'test2', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - { - typ: 'notification', - data: { - type: 'General', - message: 'test1', + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'General', + message: 'test1', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsInboxRead({ unread: false, limit: Infinity, @@ -519,25 +548,27 @@ describe('notificationsInboxRead', () => { expect(notification2.sub).toBe(nodeIdReceiverEncoded); expect(notification2.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedReadNotifications.mock.calls[0][0].order).toBe('asc'); + expect(mockedReadNotifications.mock.calls[0][0]!.unread).toBeFalsy(); + expect(mockedReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedReadNotifications.mock.calls[0][0]!.order).toBe('asc'); }); test('reads gestalt invite notifications', async () => { - mockedReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'GestaltInvite', + mockedReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'GestaltInvite', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsInboxRead({ unread: false, limit: Infinity, @@ -554,31 +585,33 @@ describe('notificationsInboxRead', () => { expect(notification.sub).toBe(nodeIdReceiverEncoded); expect(notification.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedReadNotifications.mock.calls[0][0].order).toBe('asc'); + expect(mockedReadNotifications.mock.calls[0][0]!.unread).toBeFalsy(); + expect(mockedReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedReadNotifications.mock.calls[0][0]!.order).toBe('asc'); }); test('reads vault share notifications', async () => { - mockedReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'VaultShare', - vaultId: 'vault' as VaultIdEncoded, - vaultName: 'vault' as VaultName, - actions: { - clone: null, - pull: null, + mockedReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'VaultShare', + vaultId: 'vault' as VaultIdEncoded, + vaultName: 'vault' as VaultName, + actions: { + clone: null, + pull: null, + }, }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsInboxRead({ unread: false, limit: Infinity, @@ -602,12 +635,14 @@ describe('notificationsInboxRead', () => { expect(notification.sub).toBe(nodeIdReceiverEncoded); expect(notification.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedReadNotifications.mock.calls[0][0].order).toBe('desc'); + expect(mockedReadNotifications.mock.calls[0][0]!.unread).toBeFalsy(); + expect(mockedReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedReadNotifications.mock.calls[0][0]!.order).toBe('desc'); }); test('reads no notifications', async () => { - mockedReadNotifications.mockReturnValueOnce([]); + mockedReadNotifications.mockReturnValueOnce( + arrayToGenerator([]), + ); const response = await rpcClient.methods.notificationsInboxRead({ unread: false, limit: Infinity, @@ -619,9 +654,9 @@ describe('notificationsInboxRead', () => { } expect(notificationList).toHaveLength(0); // Check request was parsed correctly - expect(mockedReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedReadNotifications.mock.calls[0][0].order).toBe('desc'); + expect(mockedReadNotifications.mock.calls[0][0]!.unread).toBeFalsy(); + expect(mockedReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedReadNotifications.mock.calls[0][0]!.order).toBe('desc'); }); }); describe('notificationsInboxRemove', () => { @@ -648,7 +683,9 @@ describe('notificationsInboxRemove', () => { let notificationsManager: NotificationsManager; let acl: ACL; let sigchain: Sigchain; - let mockedRemoveNotification: jest.SpyInstance; + let mockedRemoveNotification: jest.SpiedFunction< + typeof NotificationsManager.prototype.removeInboxNotification + >; beforeEach(async () => { mockedRemoveNotification = jest.spyOn( NotificationsManager.prototype, @@ -783,7 +820,7 @@ describe('notificationsInboxRemove', () => { }); }); test('removes a notification', async () => { - mockedRemoveNotification.mockImplementation(); + mockedRemoveNotification.mockImplementation(async () => {}); const receiverNotificationIdEncoded = 'v0ph20eva21o0197dk3ovbl3l2o' as NotificationIdEncoded; await rpcClient.methods.notificationsInboxRemove({ @@ -791,7 +828,9 @@ describe('notificationsInboxRemove', () => { }); expect(mockedRemoveNotification.mock.calls.length).toBe(1); expect( - nodesUtils.encodeNodeId(mockedRemoveNotification.mock.calls[0][0]), + notificationsUtils.encodeNotificationId( + mockedRemoveNotification.mock.calls[0][0]!, + ), ).toEqual(receiverNotificationIdEncoded); }); }); @@ -819,7 +858,9 @@ describe('notificationsOutboxClear', () => { let notificationsManager: NotificationsManager; let acl: ACL; let sigchain: Sigchain; - let mockedOutboxClearNotifications: jest.SpyInstance; + let mockedOutboxClearNotifications: jest.SpiedFunction< + typeof NotificationsManager.prototype.clearOutboxNotifications + >; beforeEach(async () => { mockedOutboxClearNotifications = jest .spyOn(NotificationsManager.prototype, 'clearOutboxNotifications') @@ -986,7 +1027,9 @@ describe('notificationsOutboxRead', () => { let notificationsManager: NotificationsManager; let acl: ACL; let sigchain: Sigchain; - let mockedOutboxReadNotifications: jest.SpyInstance; + let mockedOutboxReadNotifications: jest.SpiedFunction< + typeof NotificationsManager.prototype.readOutboxNotifications + >; beforeEach(async () => { mockedOutboxReadNotifications = jest.spyOn( NotificationsManager.prototype, @@ -1122,21 +1165,23 @@ describe('notificationsOutboxRead', () => { }); }); test('reads a single notification', async () => { - mockedOutboxReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'General', - message: 'test', + mockedOutboxReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'General', + message: 'test', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsOutboxRead({ order: 'desc', limit: 1, @@ -1154,39 +1199,40 @@ describe('notificationsOutboxRead', () => { expect(notification.sub).toBe(nodeIdReceiverEncoded); expect(notification.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedOutboxReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedOutboxReadNotifications.mock.calls[0][0].limit).toBe(1); - expect(mockedOutboxReadNotifications.mock.calls[0][0].order).toBe('desc'); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.limit).toBe(1); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.order).toBe('desc'); }); test('reads notifications in reverse order', async () => { - mockedOutboxReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'General', - message: 'test2', + mockedOutboxReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'General', + message: 'test2', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'General', - message: 'test1', + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'General', + message: 'test1', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsOutboxRead({ limit: Infinity, order: 'asc', @@ -1211,25 +1257,26 @@ describe('notificationsOutboxRead', () => { expect(notification2.sub).toBe(nodeIdReceiverEncoded); expect(notification2.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedOutboxReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedOutboxReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedOutboxReadNotifications.mock.calls[0][0].order).toBe('asc'); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.order).toBe('asc'); }); test('reads gestalt invite notifications', async () => { - mockedOutboxReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'GestaltInvite', + mockedOutboxReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'GestaltInvite', + }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsOutboxRead({ limit: Infinity, order: 'desc', @@ -1245,31 +1292,32 @@ describe('notificationsOutboxRead', () => { expect(notification.sub).toBe(nodeIdReceiverEncoded); expect(notification.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedOutboxReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedOutboxReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedOutboxReadNotifications.mock.calls[0][0].order).toBe('desc'); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.order).toBe('desc'); }); test('reads vault share notifications', async () => { - mockedOutboxReadNotifications.mockReturnValueOnce([ - { - notificationIdEncoded: notificationsUtils.encodeNotificationId( - generateNotificationId(), - ), - typ: 'notification', - data: { - type: 'VaultShare', - vaultId: 'vault' as VaultIdEncoded, - vaultName: 'vault' as VaultName, - actions: { - clone: null, - pull: null, + mockedOutboxReadNotifications.mockReturnValueOnce( + arrayToGenerator([ + { + notificationIdEncoded: notificationsUtils.encodeNotificationId( + generateNotificationId(), + ), + typ: 'notification', + data: { + type: 'VaultShare', + vaultId: 'vault' as VaultIdEncoded, + vaultName: 'vault' as VaultName, + actions: { + clone: null, + pull: null, + }, }, + iss: nodeIdSenderEncoded, + sub: nodeIdReceiverEncoded, + isRead: true, }, - iss: nodeIdSenderEncoded, - sub: nodeIdReceiverEncoded, - isRead: true, - }, - ]); + ]), + ); const response = await rpcClient.methods.notificationsOutboxRead({ limit: Infinity, order: 'desc', @@ -1292,12 +1340,13 @@ describe('notificationsOutboxRead', () => { expect(notification.sub).toBe(nodeIdReceiverEncoded); expect(notification.isRead).toBeTruthy(); // Check request was parsed correctly - expect(mockedOutboxReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedOutboxReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedOutboxReadNotifications.mock.calls[0][0].order).toBe('desc'); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.order).toBe('desc'); }); test('reads no notifications', async () => { - mockedOutboxReadNotifications.mockReturnValueOnce([]); + mockedOutboxReadNotifications.mockReturnValueOnce( + arrayToGenerator([]), + ); const response = await rpcClient.methods.notificationsOutboxRead({ limit: Infinity, order: 'desc', @@ -1308,9 +1357,8 @@ describe('notificationsOutboxRead', () => { } expect(notificationList).toHaveLength(0); // Check request was parsed correctly - expect(mockedOutboxReadNotifications.mock.calls[0][0].unread).toBeFalsy(); - expect(mockedOutboxReadNotifications.mock.calls[0][0].limit).toBe(null); - expect(mockedOutboxReadNotifications.mock.calls[0][0].order).toBe('desc'); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.limit).toBe(null); + expect(mockedOutboxReadNotifications.mock.calls[0][0]!.order).toBe('desc'); }); }); describe('notificationsOutboxRemove', () => { @@ -1337,7 +1385,9 @@ describe('notificationsOutboxRemove', () => { let notificationsManager: NotificationsManager; let acl: ACL; let sigchain: Sigchain; - let mockedRemoveOutboxNotification: jest.SpyInstance; + let mockedRemoveOutboxNotification: jest.SpiedFunction< + typeof NotificationsManager.prototype.removeOutboxNotification + >; beforeEach(async () => { mockedRemoveOutboxNotification = jest.spyOn( NotificationsManager.prototype, @@ -1472,7 +1522,7 @@ describe('notificationsOutboxRemove', () => { }); }); test('removes a notification', async () => { - mockedRemoveOutboxNotification.mockImplementation(); + mockedRemoveOutboxNotification.mockImplementation(async () => {}); const receiverNotificationIdEncoded = 'v0ph20eva21o0197dk3ovbl3l2o' as NotificationIdEncoded; await rpcClient.methods.notificationsOutboxRemove({ @@ -1480,7 +1530,9 @@ describe('notificationsOutboxRemove', () => { }); expect(mockedRemoveOutboxNotification.mock.calls.length).toBe(1); expect( - nodesUtils.encodeNodeId(mockedRemoveOutboxNotification.mock.calls[0][0]), + notificationsUtils.encodeNotificationId( + mockedRemoveOutboxNotification.mock.calls[0][0], + ), ).toEqual(receiverNotificationIdEncoded); }); }); @@ -1508,7 +1560,9 @@ describe('notificationsSend', () => { let notificationsManager: NotificationsManager; let acl: ACL; let sigchain: Sigchain; - let mockedSendNotification: jest.SpyInstance; + let mockedSendNotification: jest.SpiedFunction< + typeof NodeManager.prototype.withConnF + >; beforeEach(async () => { mockedSendNotification = jest.spyOn(NodeManager.prototype, 'withConnF'); dataDir = await fs.promises.mkdtemp( @@ -1639,7 +1693,7 @@ describe('notificationsSend', () => { }); }); test('sends a notification', async () => { - mockedSendNotification.mockImplementation(); + mockedSendNotification.mockImplementation(async () => {}); const receiverNodeIdEncoded = 'vrsc24a1er424epq77dtoveo93meij0pc8ig4uvs9jbeld78n9nl0' as NodeIdEncoded; await rpcClient.methods.notificationsSend({ diff --git a/tests/client/handlers/vaults.test.ts b/tests/client/handlers/vaults.test.ts index f69b365a12..abe1c9687e 100644 --- a/tests/client/handlers/vaults.test.ts +++ b/tests/client/handlers/vaults.test.ts @@ -1,8 +1,8 @@ import type { ContextTimed } from '@matrixai/contexts'; -import type { TLSConfig } from '@/network/types'; -import type { FileSystem } from '@/types'; -import type { VaultId } from '@/ids'; -import type NodeManager from '@/nodes/NodeManager'; +import type { TLSConfig } from '#network/types.js'; +import type { FileSystem } from '#types.js'; +import type { VaultId } from '#ids/index.js'; +import type NodeManager from '#nodes/NodeManager.js'; import type { LogEntryMessage, SecretContentMessage, @@ -15,23 +15,25 @@ import type { VaultNamesHeaderMessageTagged, VaultPermissionMessage, VaultsLogMessage, -} from '@/client/types'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +} from '#client/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import fc from 'fast-check'; import { test } from '@fast-check/jest'; +import { jest } from '@jest/globals'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { RPCClient } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import TaskManager from '@/tasks/TaskManager'; -import ACL from '@/acl/ACL'; -import KeyRing from '@/keys/KeyRing'; -import VaultManager from '@/vaults/VaultManager'; -import GestaltGraph from '@/gestalts/GestaltGraph'; -import NotificationsManager from '@/notifications/NotificationsManager'; -import ClientService from '@/client/ClientService'; +import * as testsUtils from '../../utils/index.js'; +import TaskManager from '#tasks/TaskManager.js'; +import ACL from '#acl/ACL.js'; +import KeyRing from '#keys/KeyRing.js'; +import VaultManager from '#vaults/VaultManager.js'; +import GestaltGraph from '#gestalts/GestaltGraph.js'; +import NotificationsManager from '#notifications/NotificationsManager.js'; +import ClientService from '#client/ClientService.js'; import { VaultsCreate, VaultsDelete, @@ -52,7 +54,7 @@ import { VaultsSecretsStat, VaultsSecretsTouch, VaultsVersion, -} from '@/client/handlers'; +} from '#client/handlers/index.js'; import { vaultsCreate, vaultsDelete, @@ -73,14 +75,13 @@ import { vaultsSecretsStat, vaultsSecretsTouch, vaultsVersion, -} from '@/client/callers'; -import * as keysUtils from '@/keys/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as vaultsUtils from '@/vaults/utils'; -import * as vaultsErrors from '@/vaults/errors'; -import * as clientErrors from '@/client/errors'; -import * as networkUtils from '@/network/utils'; -import * as testsUtils from '../../utils'; +} from '#client/callers/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as clientErrors from '#client/errors.js'; +import * as networkUtils from '#network/utils.js'; describe('vaultsClone', () => { const logger = new Logger('vaultsClone test', LogLevel.WARN, [ @@ -507,11 +508,14 @@ describe('vaultsPermissionSet and vaultsPermissionUnset and vaultsPermissionGet' let acl: ACL; let gestaltGraph: GestaltGraph; let notificationsManager: NotificationsManager; - let mockedSendNotification: jest.SpyInstance; + let mockedSendNotification: jest.SpiedFunction< + typeof NotificationsManager.prototype.sendNotification + >; beforeEach(async () => { mockedSendNotification = jest .spyOn(NotificationsManager.prototype, 'sendNotification') - .mockImplementation(); + // @ts-ignore: overriding types + .mockImplementation(async () => {}); dataDir = await fs.promises.mkdtemp( path.join(os.tmpdir(), 'polykey-test-'), ); @@ -2845,7 +2849,7 @@ describe('vaultsSecretsNewDir', () => { ]); const password = 'helloWorld'; const localhost = '127.0.0.1'; - const fs: FileSystem = require('fs'); + let fs: FileSystem; let dataDir: string; let db: DB; let keyRing: KeyRing; @@ -2857,6 +2861,7 @@ describe('vaultsSecretsNewDir', () => { }>; let vaultManager: VaultManager; beforeEach(async () => { + fs = await import('node:fs'); dataDir = await fs.promises.mkdtemp( path.join(os.tmpdir(), 'polykey-test-'), ); @@ -2973,7 +2978,7 @@ describe('vaultsSecretsList', () => { ]); const password = 'helloWorld'; const localhost = '127.0.0.1'; - const fs: FileSystem = require('fs'); + let fs: FileSystem; let dataDir: string; let db: DB; let keyRing: KeyRing; @@ -2985,6 +2990,7 @@ describe('vaultsSecretsList', () => { }>; let vaultManager: VaultManager; beforeEach(async () => { + fs = await import('node:fs'); dataDir = await fs.promises.mkdtemp( path.join(os.tmpdir(), 'polykey-test-'), ); @@ -3291,7 +3297,7 @@ describe('vaultsSecretsRename', () => { ]); const password = 'helloWorld'; const localhost = '127.0.0.1'; - const fs: FileSystem = require('fs'); + let fs: FileSystem; let dataDir: string; let db: DB; let keyRing: KeyRing; @@ -3303,6 +3309,7 @@ describe('vaultsSecretsRename', () => { }>; let vaultManager: VaultManager; beforeEach(async () => { + fs = await import('node:fs'); dataDir = await fs.promises.mkdtemp( path.join(os.tmpdir(), 'polykey-test-'), ); @@ -3441,7 +3448,7 @@ describe('vaultsSecretsStat', () => { ]); const password = 'helloWorld'; const localhost = '127.0.0.1'; - const fs: FileSystem = require('fs'); + let fs: FileSystem; let dataDir: string; let db: DB; let keyRing: KeyRing; @@ -3453,6 +3460,7 @@ describe('vaultsSecretsStat', () => { }>; let vaultManager: VaultManager; beforeEach(async () => { + fs = await import('node:fs'); dataDir = await fs.promises.mkdtemp( path.join(os.tmpdir(), 'polykey-test-'), ); @@ -4220,7 +4228,7 @@ describe('vaultsVersion', () => { ]); const password = 'helloWorld'; const localhost = '127.0.0.1'; - const fs: FileSystem = require('fs'); + let fs: FileSystem; let dataDir: string; let db: DB; let keyRing: KeyRing; @@ -4242,6 +4250,7 @@ describe('vaultsVersion', () => { }; const vaultName = 'test-vault'; beforeEach(async () => { + fs = await import('node:fs'); dataDir = await fs.promises.mkdtemp( path.join(os.tmpdir(), 'polykey-test-'), ); diff --git a/tests/client/middleware.test.ts b/tests/client/middleware.test.ts index 1eb77e03c8..c4a03a15a7 100644 --- a/tests/client/middleware.test.ts +++ b/tests/client/middleware.test.ts @@ -2,12 +2,12 @@ import type { JSONRPCRequest, JSONRPCResponse } from '@matrixai/rpc'; import type { ClientRPCRequestParams, ClientRPCResponseResult, -} from '@/client/types'; -import type { TLSConfig } from '../../src/network/types'; +} from '#client/types.js'; +import type { TLSConfig } from '#network/types.js'; import { TransformStream } from 'stream/web'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { @@ -17,16 +17,16 @@ import { middleware as rpcUtilsMiddleware, } from '@matrixai/rpc'; import { WebSocketClient } from '@matrixai/ws'; -import KeyRing from '@/keys/KeyRing'; -import TaskManager from '@/tasks/TaskManager'; -import CertManager from '@/keys/CertManager'; -import ClientService from '@/client/ClientService'; -import { Session, SessionManager } from '@/sessions'; -import * as middleware from '@/client/middleware'; -import * as keysUtils from '@/keys/utils'; -import * as clientUtils from '@/client/utils'; -import * as networkUtils from '@/network/utils'; -import * as testsUtils from '../utils'; +import * as testsUtils from '../utils/index.js'; +import KeyRing from '#keys/KeyRing.js'; +import TaskManager from '#tasks/TaskManager.js'; +import CertManager from '#keys/CertManager.js'; +import ClientService from '#client/ClientService.js'; +import { Session, SessionManager } from '#sessions/index.js'; +import * as middleware from '#client/middleware.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as clientUtils from '#client/utils.js'; +import * as networkUtils from '#network/utils.js'; describe('middleware', () => { const logger = new Logger('middleware test', LogLevel.WARN, [ diff --git a/tests/client/utils.test.ts b/tests/client/utils.test.ts index 283c4dbf65..9ed854c85c 100644 --- a/tests/client/utils.test.ts +++ b/tests/client/utils.test.ts @@ -1,8 +1,8 @@ -import type { CertificatePEM, PrivateKeyPEM } from '@/keys/types'; +import type { CertificatePEM, PrivateKeyPEM } from '#keys/types.js'; import { utils as wsUtils } from '@matrixai/ws'; -import * as clientUtils from '@/client/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testTlsUtils from '../utils/tls'; +import * as testTlsUtils from '../utils/tls.js'; +import * as clientUtils from '#client/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('client/utils', () => { const keyPairRoot = keysUtils.generateKeyPair(); diff --git a/tests/discovery/Discovery.test.ts b/tests/discovery/Discovery.test.ts index 857f9e4065..0b9657ea7b 100644 --- a/tests/discovery/Discovery.test.ts +++ b/tests/discovery/Discovery.test.ts @@ -1,43 +1,41 @@ -import type { IdentityId, ProviderId } from '@/identities/types'; -import type { Host } from '@/network/types'; -import type { Key } from '@/keys/types'; -import type { NodeId } from '@/ids'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import type { DiscoveryQueueInfo } from '@/discovery/types'; -import type { ClaimLinkIdentity } from '@/claims/payloads/claimLinkIdentity'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type { IdentityId, ProviderId } from '#identities/types.js'; +import type { Host } from '#network/types.js'; +import type { NodeId } from '#ids/index.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import type { DiscoveryQueueInfo } from '#discovery/types.js'; +import type { ClaimLinkIdentity } from '#claims/payloads/claimLinkIdentity.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { jest } from '@jest/globals'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { PromiseCancellable } from '@matrixai/async-cancellable'; import { EventAll } from '@matrixai/events'; -import { AsyncIterableX as AsyncIterable } from 'ix/asynciterable'; -import { Token } from '@/tokens'; -import TaskManager from '@/tasks/TaskManager'; -import PolykeyAgent from '@/PolykeyAgent'; -import Discovery from '@/discovery/Discovery'; -import * as discoveryEvents from '@/discovery/events'; -import GestaltGraph from '@/gestalts/GestaltGraph'; -import IdentitiesManager from '@/identities/IdentitiesManager'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import NodeGraph from '@/nodes/NodeGraph'; -import NodeManager from '@/nodes/NodeManager'; -import NodesAuthenticateConnection from '@/nodes/agent/handlers/NodesAuthenticateConnection'; -import KeyRing from '@/keys/KeyRing'; -import ACL from '@/acl/ACL'; -import Sigchain from '@/sigchain/Sigchain'; -import * as utils from '@/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as discoveryErrors from '@/discovery/errors'; -import * as keysUtils from '@/keys/utils'; -import * as gestaltsUtils from '@/gestalts/utils'; -import { encodeProviderIdentityId } from '@/ids'; -import * as testNodesUtils from '../nodes/utils'; -import TestProvider from '../identities/TestProvider'; -import 'ix/add/asynciterable-operators/toarray'; -import { createTLSConfig } from '../utils/tls'; -import * as testsUtils from '../utils'; +import * as testNodesUtils from '../nodes/utils.js'; +import TestProvider from '../identities/TestProvider.js'; +import * as testsUtils from '../utils/index.js'; +import { Token } from '#tokens/index.js'; +import TaskManager from '#tasks/TaskManager.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import Discovery from '#discovery/Discovery.js'; +import * as discoveryEvents from '#discovery/events.js'; +import GestaltGraph from '#gestalts/GestaltGraph.js'; +import IdentitiesManager from '#identities/IdentitiesManager.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import NodeManager from '#nodes/NodeManager.js'; +import NodesAuthenticateConnection from '#nodes/agent/handlers/NodesAuthenticateConnection.js'; +import KeyRing from '#keys/KeyRing.js'; +import ACL from '#acl/ACL.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import * as utils from '#utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as discoveryErrors from '#discovery/errors.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as gestaltsUtils from '#gestalts/utils.js'; +import { encodeProviderIdentityId } from '#ids/index.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe('Discovery', () => { const password = 'password'; @@ -108,20 +106,7 @@ describe('Discovery', () => { logger: logger.getChild('db'), crypto: { key: keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, fresh: true, }); @@ -163,7 +148,7 @@ describe('Discovery', () => { logger, lazy: true, }); - const tlsConfig = await createTLSConfig(keyRing.keyPair); + const tlsConfig = await testsUtils.createTLSConfig(keyRing.keyPair); nodeConnectionManager = new NodeConnectionManager({ keyRing, tlsConfig, @@ -320,9 +305,9 @@ describe('Discovery', () => { await taskManager.startProcessing(); await discovery.queueDiscoveryByNode(nodeA.keyRing.getNodeId()); await waitForAllDiscoveryTasks(discovery); - const gestalts = await AsyncIterable.as( + const gestalts = await testsUtils.generatorToArray( gestaltGraph.getGestalts(), - ).toArray(); + ); const gestalt = gestalts[0]; const gestaltMatrix = gestalt.matrix; const gestaltNodes = gestalt.nodes; @@ -355,9 +340,9 @@ describe('Discovery', () => { await taskManager.startProcessing(); await discovery.queueDiscoveryByIdentity(testToken.providerId, identityId); await waitForAllDiscoveryTasks(discovery); - const gestalts = await AsyncIterable.as( + const gestalts = await testsUtils.generatorToArray( gestaltGraph.getGestalts(), - ).toArray(); + ); const gestalt = gestalts[0]; const gestaltMatrix = gestalt.matrix; const gestaltNodes = gestalt.nodes; @@ -390,9 +375,9 @@ describe('Discovery', () => { await taskManager.startProcessing(); await discovery.queueDiscoveryByNode(nodeA.keyRing.getNodeId()); await waitForAllDiscoveryTasks(discovery); - const gestalts1 = await AsyncIterable.as( + const gestalts1 = await testsUtils.generatorToArray( gestaltGraph.getGestalts(), - ).toArray(); + ); const gestalt1 = gestalts1[0]; const gestaltMatrix1 = gestalt1.matrix; const gestaltNodes1 = gestalt1.nodes; @@ -443,9 +428,9 @@ describe('Discovery', () => { // already discovered vertices, however for now we must do this manually. await discovery.queueDiscoveryByNode(nodeA.keyRing.getNodeId()); await waitForAllDiscoveryTasks(discovery); - const gestalts2 = await AsyncIterable.as( + const gestalts2 = await testsUtils.generatorToArray( gestaltGraph.getGestalts(), - ).toArray(); + ); const gestalt2 = gestalts2[0]; const gestaltMatrix2 = gestalt2.matrix; const gestaltNodes2 = gestalt2.nodes; @@ -484,9 +469,9 @@ describe('Discovery', () => { await discovery.start(); await taskManager.startProcessing(); await waitForAllDiscoveryTasks(discovery); - const gestalts = await AsyncIterable.as( + const gestalts = await testsUtils.generatorToArray( gestaltGraph.getGestalts(), - ).toArray(); + ); const gestalt = gestalts[0]; const gestaltMatrix = gestalt.matrix; const gestaltNodes = gestalt.nodes; @@ -627,9 +612,9 @@ describe('Discovery', () => { ); await discovery.queueDiscoveryByIdentity(testToken.providerId, identityId2); await discovery.waitForDiscoveryTasks(true); - const gestalts = await AsyncIterable.as( + const gestalts = await testsUtils.generatorToArray( gestaltGraph.getGestalts(), - ).toArray(); + ); expect(gestalts.length).toBe(1); const gestalt = gestalts[0]; const nodeMatrix = diff --git a/tests/gestalts/GestaltGraph.test.ts b/tests/gestalts/GestaltGraph.test.ts index a60a469773..422aebc99b 100644 --- a/tests/gestalts/GestaltGraph.test.ts +++ b/tests/gestalts/GestaltGraph.test.ts @@ -1,11 +1,10 @@ -import type { NodeId } from '@/nodes/types'; -import type { ProviderIdentityId } from '@/identities/types'; -import type { SignedClaim } from '@/claims/types'; -import type { Key } from '@/keys/types'; +import type { NodeId } from '#nodes/types.js'; +import type { ProviderIdentityId } from '#identities/types.js'; +import type { SignedClaim } from '#claims/types.js'; import type { ClaimLinkNode, ClaimLinkIdentity, -} from '../../src/claims/payloads'; +} from '#claims/payloads/index.js'; import type { GestaltIdentityInfo, GestaltInfo, @@ -15,31 +14,32 @@ import type { GestaltLinkId, GestaltLinkNode, GestaltLinkIdentity, -} from '../../src/gestalts/types'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +} from '#gestalts/types.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { fc, test } from '@fast-check/jest'; -import { AsyncIterableX as AsyncIterable } from 'ix/asynciterable'; -import GestaltGraph from '@/gestalts/GestaltGraph'; -import ACL from '@/acl/ACL'; -import * as gestaltsErrors from '@/gestalts/errors'; -import * as gestaltsUtils from '@/gestalts/utils'; -import * as utils from '@/utils'; -import * as keysUtils from '@/keys/utils'; -import Token from '@/tokens/Token'; -import { encodeGestaltNodeId, encodeGestaltIdentityId } from '@/gestalts/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as claimsUtils from '@/claims/utils'; -import * as testsGestaltsUtils from './utils'; -import * as testsUtils from '../utils'; -import * as testsIdentitiesUtils from '../identities/utils'; -import * as testsKeysUtils from '../keys/utils'; -import * as ids from '../../src/ids'; -import * as testsIdsUtils from '../ids/utils'; -import 'ix/add/asynciterable-operators/toarray'; +import * as testsGestaltsUtils from './utils.js'; +import * as testsUtils from '../utils/index.js'; +import * as testsIdentitiesUtils from '../identities/utils.js'; +import * as testsKeysUtils from '../keys/utils.js'; +import * as ids from '../../src/ids/index.js'; +import * as testsIdsUtils from '../ids/utils.js'; +import GestaltGraph from '#gestalts/GestaltGraph.js'; +import ACL from '#acl/ACL.js'; +import * as gestaltsErrors from '#gestalts/errors.js'; +import * as gestaltsUtils from '#gestalts/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import Token from '#tokens/Token.js'; +import { + encodeGestaltNodeId, + encodeGestaltIdentityId, +} from '#gestalts/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as claimsUtils from '#claims/utils.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe('GestaltGraph', () => { const logger = new Logger('GestaltGraph Test', LogLevel.WARN, [ @@ -53,90 +53,100 @@ describe('GestaltGraph', () => { const gestaltNodeInfoComposedArb = testsIdsUtils.nodeIdArb.chain( testsGestaltsUtils.gestaltNodeInfoArb, ); - const linkNodeComposedArb = fc - .tuple(testsKeysUtils.keyPairArb, testsKeysUtils.keyPairArb) - .chain(([keyPair1, keyPair2]) => { - const nodeId1 = keysUtils.publicKeyToNodeId(keyPair1.publicKey); - const nodeId2 = keysUtils.publicKeyToNodeId(keyPair2.publicKey); - return fc.record({ - gestaltNodeInfo1: testsGestaltsUtils.gestaltNodeInfoArb(nodeId1), - gestaltNodeInfo2: testsGestaltsUtils.gestaltNodeInfoArb(nodeId2), - linkNode: testsGestaltsUtils.linkNodeArb(keyPair1, keyPair2), - }); - }) - .noShrink(); - const gestaltIdentityInfoComposedArb = fc - .tuple( - testsIdentitiesUtils.providerIdArb, - testsIdentitiesUtils.identitiyIdArb, - ) - .chain((item) => testsGestaltsUtils.gestaltIdentityInfoArb(...item)) - .noShrink(); - const linkIdentityComposedArb = fc - .tuple( - testsKeysUtils.keyPairArb, - testsIdentitiesUtils.providerIdArb, - testsIdentitiesUtils.identitiyIdArb, - ) - .chain(([keyPair, providerId, identityId]) => { - const nodeId = keysUtils.publicKeyToNodeId(keyPair.publicKey); - return fc.record({ - gestaltNodeInfo: testsGestaltsUtils.gestaltNodeInfoArb(nodeId), - gestaltIdentityInfo: testsGestaltsUtils.gestaltIdentityInfoArb( - providerId, - identityId, - ), - linkIdentity: testsGestaltsUtils.linkIdentityArb( - keyPair, - providerId, - identityId, - ), - }); - }) - .noShrink(); + const linkNodeComposedArb = fc.noShrink( + fc + .tuple(testsKeysUtils.keyPairArb, testsKeysUtils.keyPairArb) + .chain(([keyPair1, keyPair2]) => { + const nodeId1 = keysUtils.publicKeyToNodeId(keyPair1.publicKey); + const nodeId2 = keysUtils.publicKeyToNodeId(keyPair2.publicKey); + return fc.record( + { + gestaltNodeInfo1: testsGestaltsUtils.gestaltNodeInfoArb(nodeId1), + gestaltNodeInfo2: testsGestaltsUtils.gestaltNodeInfoArb(nodeId2), + linkNode: testsGestaltsUtils.linkNodeArb(keyPair1, keyPair2), + }, + { noNullPrototype: true }, + ); + }), + ); + const gestaltIdentityInfoComposedArb = fc.noShrink( + fc + .tuple( + testsIdentitiesUtils.providerIdArb, + testsIdentitiesUtils.identitiyIdArb, + ) + .chain((item) => testsGestaltsUtils.gestaltIdentityInfoArb(...item)), + ); + const linkIdentityComposedArb = fc.noShrink( + fc + .tuple( + testsKeysUtils.keyPairArb, + testsIdentitiesUtils.providerIdArb, + testsIdentitiesUtils.identitiyIdArb, + ) + .chain(([keyPair, providerId, identityId]) => { + const nodeId = keysUtils.publicKeyToNodeId(keyPair.publicKey); + return fc.record( + { + gestaltNodeInfo: testsGestaltsUtils.gestaltNodeInfoArb(nodeId), + gestaltIdentityInfo: testsGestaltsUtils.gestaltIdentityInfoArb( + providerId, + identityId, + ), + linkIdentity: testsGestaltsUtils.linkIdentityArb( + keyPair, + providerId, + identityId, + ), + }, + { noNullPrototype: true }, + ); + }), + ); const gestaltInfoComposedArb = fc.oneof( fc.tuple(fc.constant('node'), gestaltNodeInfoComposedArb), fc.tuple(fc.constant('identity'), gestaltIdentityInfoComposedArb), ) as fc.Arbitrary< ['node', GestaltNodeInfo] | ['identity', GestaltIdentityInfo] >; - const linkVertexComposedArb = fc - .oneof( - fc.tuple(fc.constant('node'), linkNodeComposedArb), - fc.tuple(fc.constant('identity'), linkIdentityComposedArb), - ) - .map((item) => { - const [type, linkData] = item as any; - switch (type) { - case 'node': - return { - gestaltVertexInfo1: ['node', linkData.gestaltNodeInfo1] as [ - 'node', - GestaltNodeInfo, - ], - gestaltVertexInfo2: [ - 'node', - linkData.gestaltNodeInfo2, - ] as GestaltInfo, - gestaltLink: ['node', linkData.linkNode] as GestaltLink, - }; - case 'identity': - return { - gestaltVertexInfo1: ['node', linkData.gestaltNodeInfo] as [ - 'node', - GestaltNodeInfo, - ], - gestaltVertexInfo2: [ - 'identity', - linkData.gestaltIdentityInfo, - ] as GestaltInfo, - gestaltLink: ['identity', linkData.linkIdentity] as GestaltLink, - }; - default: - } - throw Error(); - }) - .noShrink(); + const linkVertexComposedArb = fc.noShrink( + fc + .oneof( + fc.tuple(fc.constant('node'), linkNodeComposedArb), + fc.tuple(fc.constant('identity'), linkIdentityComposedArb), + ) + .map((item) => { + const [type, linkData] = item as any; + switch (type) { + case 'node': + return { + gestaltVertexInfo1: ['node', linkData.gestaltNodeInfo1] as [ + 'node', + GestaltNodeInfo, + ], + gestaltVertexInfo2: [ + 'node', + linkData.gestaltNodeInfo2, + ] as GestaltInfo, + gestaltLink: ['node', linkData.linkNode] as GestaltLink, + }; + case 'identity': + return { + gestaltVertexInfo1: ['node', linkData.gestaltNodeInfo] as [ + 'node', + GestaltNodeInfo, + ], + gestaltVertexInfo2: [ + 'identity', + linkData.gestaltIdentityInfo, + ] as GestaltInfo, + gestaltLink: ['identity', linkData.linkIdentity] as GestaltLink, + }; + default: + } + throw Error(); + }), + ); beforeEach(async () => { dataDir = await fs.promises.mkdtemp( @@ -148,20 +158,7 @@ describe('GestaltGraph', () => { logger, crypto: { key: keysUtils.generateKey(), - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); acl = await ACL.createACL({ db, logger }); @@ -758,9 +755,9 @@ describe('GestaltGraph', () => { for (const gestaltNodeInfo of gestaltNodeInfos) { await gestaltGraph.setNode(gestaltNodeInfo); } - const gestalts = await AsyncIterable.as( + const gestalts = await testsUtils.generatorToArray( gestaltGraph.getGestalts(), - ).toArray(); + ); expect(gestalts).toHaveLength(gestaltNodeInfos.length); for (const gestalt of gestalts) { const gestaltId = Object.keys(gestalt.nodes)[0]; @@ -777,52 +774,46 @@ describe('GestaltGraph', () => { } }); test.prop([ - fc - .array(gestaltIdentityInfoComposedArb, { minLength: 2, maxLength: 10 }) - .noShrink(), - ])( - 'getGestalts with identities', - - async (gestaltIdentityInfos) => { - const ids = new Set(); - for (const gestaltIdentityInfo of gestaltIdentityInfos) { - ids.add( - gestaltIdentityInfo.providerId + gestaltIdentityInfo.identityId, - ); - } - fc.pre(ids.size === gestaltIdentityInfos.length); - const gestaltGraph = await GestaltGraph.createGestaltGraph({ - db, - acl, - logger, - fresh: true, - }); - for (const gestaltIdentityInfo of gestaltIdentityInfos) { - await gestaltGraph.setIdentity(gestaltIdentityInfo); - } - const gestalts = await AsyncIterable.as( - gestaltGraph.getGestalts(), - ).toArray(); - expect(gestalts).toHaveLength(gestaltIdentityInfos.length); - for (const gestalt of gestalts) { - const gestaltId = Object.keys(gestalt.identities)[0]; - const [, providerIdentityId] = - gestaltsUtils.decodeGestaltIdentityId(gestaltId)!; - expect(gestalt).toMatchObject({ - matrix: { - [gestaltId]: {}, - }, - nodes: {}, - identities: { - [gestaltId]: { - providerId: providerIdentityId[0], - identityId: providerIdentityId[1], - }, + fc.noShrink( + fc.array(gestaltIdentityInfoComposedArb, { minLength: 2, maxLength: 10 }), + ), + ])('getGestalts with identities', async (gestaltIdentityInfos) => { + const ids = new Set(); + for (const gestaltIdentityInfo of gestaltIdentityInfos) { + ids.add(gestaltIdentityInfo.providerId + gestaltIdentityInfo.identityId); + } + fc.pre(ids.size === gestaltIdentityInfos.length); + const gestaltGraph = await GestaltGraph.createGestaltGraph({ + db, + acl, + logger, + fresh: true, + }); + for (const gestaltIdentityInfo of gestaltIdentityInfos) { + await gestaltGraph.setIdentity(gestaltIdentityInfo); + } + const gestalts = await testsUtils.generatorToArray( + gestaltGraph.getGestalts(), + ); + expect(gestalts).toHaveLength(gestaltIdentityInfos.length); + for (const gestalt of gestalts) { + const gestaltId = Object.keys(gestalt.identities)[0]; + const [, providerIdentityId] = + gestaltsUtils.decodeGestaltIdentityId(gestaltId)!; + expect(gestalt).toMatchObject({ + matrix: { + [gestaltId]: {}, + }, + nodes: {}, + identities: { + [gestaltId]: { + providerId: providerIdentityId[0], + identityId: providerIdentityId[1], }, - }); - } - }, - ); + }, + }); + } + }); test.prop([ fc.array(gestaltInfoComposedArb, { minLength: 2, maxLength: 10 }), ])('getGestalts with nodes and identities', async (gestaltInfos) => { @@ -850,9 +841,9 @@ describe('GestaltGraph', () => { for (const gestaltinfo of gestaltInfos) { await gestaltGraph.setVertex(gestaltinfo); } - const gestalts = await AsyncIterable.as( + const gestalts = await testsUtils.generatorToArray( gestaltGraph.getGestalts(), - ).toArray(); + ); expect(gestalts).toHaveLength(gestaltInfos.length); for (const gestalt of gestalts) { const gestaltId = Object.keys(gestalt.matrix)[0]; @@ -1150,201 +1141,208 @@ describe('GestaltGraph', () => { describe('Model based testing', () => { const altCommandsArb = // Use a record to generate a constrained set of vertices - fc - .record({ - keyPairs: fc.array(testsKeysUtils.keyPairArb, { - minLength: 2, - maxLength: 10, - }), - identityInfos: fc - .array(gestaltIdentityInfoComposedArb, { - minLength: 1, - maxLength: 2, - }) - .filter((v) => { - const ids = new Set(); - for (const identityInfo of v) { - ids.add(identityInfo.providerId + identityInfo.identityId); - } - return ids.size === v.length; - }), - }) - .chain((verticies) => { - const { keyPairs, identityInfos } = verticies; - const nodeInfos = keyPairs.map((keyPair) => { - const nodeId = keysUtils.publicKeyToNodeId(keyPair.publicKey); - const nodeInfo: GestaltNodeInfo = { nodeId }; - return nodeInfo; - }); - const vertexInfos = [ - ...nodeInfos.map((nodeInfo) => ['node', nodeInfo]), - ...identityInfos.map((identityInfo) => ['identity', identityInfo]), - ] as Array; - - // Random selection arbs - const randomNodeInfoArb = fc.constantFrom(...nodeInfos); - const randomNodeIdArb = randomNodeInfoArb.map( - (nodeInfo) => nodeInfo.nodeId, - ); - const randomIdentityInfoArb = fc.constantFrom(...identityInfos); - const randomProviderIdentityIdArb = randomIdentityInfoArb.map( - (identityInfo) => - [ - identityInfo.providerId, - identityInfo.identityId, - ] as ProviderIdentityId, - ); - const randomVertexInfo = fc.constantFrom(...vertexInfos); - const randomVertexId = fc.oneof( - fc.tuple(fc.constant('node'), randomNodeIdArb), - fc.tuple(fc.constant('identity'), randomProviderIdentityIdArb), - ) as fc.Arbitrary; - const randomKeyPair = fc.constantFrom(...keyPairs); - - const setVertexCommandArb = fc - .tuple(randomVertexInfo, testsGestaltsUtils.gestaltActionsArb(1)) - .map((args) => new testsGestaltsUtils.SetVertexCommand(...args)); - const unsetVertexCommandArb = randomVertexId.map( - (args) => new testsGestaltsUtils.UnsetVertexCommand(args), - ); - const linkNodesParamsArb = fc - .tuple(randomKeyPair, randomKeyPair) - .filter(([a, b]) => !a.privateKey.equals(b.privateKey)) - .chain(([keyPair1, keyPair2]) => { - const nodeInfo1 = { - nodeId: keysUtils.publicKeyToNodeId(keyPair1.publicKey), - }; - const nodeInfo2 = { - nodeId: keysUtils.publicKeyToNodeId(keyPair2.publicKey), - }; - return fc.tuple( - fc.constant(nodeInfo1), - fc.constant(nodeInfo2), - testsGestaltsUtils.gestaltLinkNodeArb(keyPair1, keyPair2), - ); + fc.noShrink( + fc + .record( + { + keyPairs: fc.array(testsKeysUtils.keyPairArb, { + minLength: 2, + maxLength: 10, + }), + identityInfos: fc + .array(gestaltIdentityInfoComposedArb, { + minLength: 1, + maxLength: 2, + }) + .filter((v) => { + const ids = new Set(); + for (const identityInfo of v) { + ids.add(identityInfo.providerId + identityInfo.identityId); + } + return ids.size === v.length; + }), + }, + { noNullPrototype: true }, + ) + .chain((verticies) => { + const { keyPairs, identityInfos } = verticies; + const nodeInfos = keyPairs.map((keyPair) => { + const nodeId = keysUtils.publicKeyToNodeId(keyPair.publicKey); + const nodeInfo: GestaltNodeInfo = { nodeId }; + return nodeInfo; }); - const linkNodesCommandArb = linkNodesParamsArb.map( - ([nodeInfo1, nodeInfo2, linkNode]) => - new testsGestaltsUtils.LinkNodeAndNodeCommand( - nodeInfo1, - nodeInfo2, - linkNode, - ), - ); + const vertexInfos = [ + ...nodeInfos.map((nodeInfo) => ['node', nodeInfo]), + ...identityInfos.map((identityInfo) => [ + 'identity', + identityInfo, + ]), + ] as Array; - const linkIdentitiesParamsArb = fc - .tuple(randomKeyPair, randomIdentityInfoArb) - .chain(([keyPair, identityInfo]) => { - const nodeInfo = { - nodeId: keysUtils.publicKeyToNodeId(keyPair.publicKey), - }; - return fc.tuple( - fc.constant(nodeInfo), - fc.constant(identityInfo), - testsGestaltsUtils.gestaltLinkIdentityArb( - keyPair, + // Random selection arbs + const randomNodeInfoArb = fc.constantFrom(...nodeInfos); + const randomNodeIdArb = randomNodeInfoArb.map( + (nodeInfo) => nodeInfo.nodeId, + ); + const randomIdentityInfoArb = fc.constantFrom(...identityInfos); + const randomProviderIdentityIdArb = randomIdentityInfoArb.map( + (identityInfo) => + [ identityInfo.providerId, identityInfo.identityId, - ), - ); - }); - const linkIdentitiiesCommandArb = linkIdentitiesParamsArb.map( - ([nodeInfo, identitiyInfo, linkIdentity]) => - new testsGestaltsUtils.LinkNodeAndIdentityCommand( - nodeInfo, - identitiyInfo, - linkIdentity, - ), - ); + ] as ProviderIdentityId, + ); + const randomVertexInfo = fc.constantFrom(...vertexInfos); + const randomVertexId = fc.oneof( + fc.tuple(fc.constant('node'), randomNodeIdArb), + fc.tuple(fc.constant('identity'), randomProviderIdentityIdArb), + ) as fc.Arbitrary; + const randomKeyPair = fc.constantFrom(...keyPairs); - const linkVertexCommandArb = fc - .oneof( - linkNodesParamsArb.map( - ([info1, info2, link]) => - [ - ['node', info1], - ['node', info2], - ['node', link], - ] as [GestaltInfo, GestaltInfo, GestaltLink], - ), - linkIdentitiesParamsArb.map( - ([info1, info2, link]) => - [ - ['node', info1], - ['identity', info2], - ['identity', link], - ] as [GestaltInfo, GestaltInfo, GestaltLink], - ), - ) - .map( - ([gestaltInfo1, gestaltInfo2, gestaltLink]) => - new testsGestaltsUtils.LinkVertexAndVertexCommand( - gestaltInfo1 as ['node', GestaltNodeInfo], - gestaltInfo2, - gestaltLink, + const setVertexCommandArb = fc + .tuple(randomVertexInfo, testsGestaltsUtils.gestaltActionsArb(1)) + .map((args) => new testsGestaltsUtils.SetVertexCommand(...args)); + const unsetVertexCommandArb = randomVertexId.map( + (args) => new testsGestaltsUtils.UnsetVertexCommand(args), + ); + const linkNodesParamsArb = fc + .tuple(randomKeyPair, randomKeyPair) + .filter(([a, b]) => !a.privateKey.equals(b.privateKey)) + .chain(([keyPair1, keyPair2]) => { + const nodeInfo1 = { + nodeId: keysUtils.publicKeyToNodeId(keyPair1.publicKey), + }; + const nodeInfo2 = { + nodeId: keysUtils.publicKeyToNodeId(keyPair2.publicKey), + }; + return fc.tuple( + fc.constant(nodeInfo1), + fc.constant(nodeInfo2), + testsGestaltsUtils.gestaltLinkNodeArb(keyPair1, keyPair2), + ); + }); + const linkNodesCommandArb = linkNodesParamsArb.map( + ([nodeInfo1, nodeInfo2, linkNode]) => + new testsGestaltsUtils.LinkNodeAndNodeCommand( + nodeInfo1, + nodeInfo2, + linkNode, ), ); - const unlinkNodeCommandArb = fc - .tuple(randomNodeIdArb, randomNodeIdArb) - .map( - ([nodeId1, nodeId2]) => - new testsGestaltsUtils.UnlinkNodeAndNodeCommand( - nodeId1, - nodeId2, + const linkIdentitiesParamsArb = fc + .tuple(randomKeyPair, randomIdentityInfoArb) + .chain(([keyPair, identityInfo]) => { + const nodeInfo = { + nodeId: keysUtils.publicKeyToNodeId(keyPair.publicKey), + }; + return fc.tuple( + fc.constant(nodeInfo), + fc.constant(identityInfo), + testsGestaltsUtils.gestaltLinkIdentityArb( + keyPair, + identityInfo.providerId, + identityInfo.identityId, + ), + ); + }); + const linkIdentitiiesCommandArb = linkIdentitiesParamsArb.map( + ([nodeInfo, identitiyInfo, linkIdentity]) => + new testsGestaltsUtils.LinkNodeAndIdentityCommand( + nodeInfo, + identitiyInfo, + linkIdentity, ), ); - const unlinkIdentityCommandArb = fc - .tuple(randomNodeIdArb, randomProviderIdentityIdArb) - .map( - ([nodeId, identityId]) => - new testsGestaltsUtils.UnlinkNodeAndIdentityCommand( - nodeId, - identityId, + const linkVertexCommandArb = fc + .oneof( + linkNodesParamsArb.map( + ([info1, info2, link]) => + [ + ['node', info1], + ['node', info2], + ['node', link], + ] as [GestaltInfo, GestaltInfo, GestaltLink], ), - ); + linkIdentitiesParamsArb.map( + ([info1, info2, link]) => + [ + ['node', info1], + ['identity', info2], + ['identity', link], + ] as [GestaltInfo, GestaltInfo, GestaltLink], + ), + ) + .map( + ([gestaltInfo1, gestaltInfo2, gestaltLink]) => + new testsGestaltsUtils.LinkVertexAndVertexCommand( + gestaltInfo1 as ['node', GestaltNodeInfo], + gestaltInfo2, + gestaltLink, + ), + ); - const unlinkVertexCommandArb = fc - .tuple( - randomNodeIdArb.map( - (nodeId) => ['node', nodeId] as ['node', NodeId], - ), - randomVertexId, - ) - .map( - ([gestaltId1, gestaltId2]) => - new testsGestaltsUtils.UnlinkVertexAndVertexCommand( - gestaltId1, - gestaltId2, + const unlinkNodeCommandArb = fc + .tuple(randomNodeIdArb, randomNodeIdArb) + .map( + ([nodeId1, nodeId2]) => + new testsGestaltsUtils.UnlinkNodeAndNodeCommand( + nodeId1, + nodeId2, + ), + ); + + const unlinkIdentityCommandArb = fc + .tuple(randomNodeIdArb, randomProviderIdentityIdArb) + .map( + ([nodeId, identityId]) => + new testsGestaltsUtils.UnlinkNodeAndIdentityCommand( + nodeId, + identityId, + ), + ); + + const unlinkVertexCommandArb = fc + .tuple( + randomNodeIdArb.map( + (nodeId) => ['node', nodeId] as ['node', NodeId], ), - ); + randomVertexId, + ) + .map( + ([gestaltId1, gestaltId2]) => + new testsGestaltsUtils.UnlinkVertexAndVertexCommand( + gestaltId1, + gestaltId2, + ), + ); - const commandsUnlink = fc.commands( - [ - unsetVertexCommandArb, - unlinkNodeCommandArb, - unlinkIdentityCommandArb, - unlinkVertexCommandArb, - ], - { size: '+1' }, - ); + const commandsUnlink = fc.commands( + [ + unsetVertexCommandArb, + unlinkNodeCommandArb, + unlinkIdentityCommandArb, + unlinkVertexCommandArb, + ], + { size: '+1' }, + ); - const commandsLink = fc.commands( - [ - setVertexCommandArb, - linkNodesCommandArb, - linkIdentitiiesCommandArb, - linkVertexCommandArb, - ], - { size: '=' }, - ); - return fc.tuple(commandsLink, commandsUnlink); - }) - .map(([commandsLink, commandsUnlink]) => { - return [...commandsLink, ...commandsUnlink]; - }) - .noShrink(); + const commandsLink = fc.commands( + [ + setVertexCommandArb, + linkNodesCommandArb, + linkIdentitiiesCommandArb, + linkVertexCommandArb, + ], + { size: '=' }, + ); + return fc.tuple(commandsLink, commandsUnlink); + }) + .map(([commandsLink, commandsUnlink]) => { + return [...commandsLink, ...commandsUnlink]; + }), + ); test.prop([altCommandsArb], { numRuns: 20 })('model', async (cmds) => { await acl.start({ fresh: true }); diff --git a/tests/gestalts/utils.ts b/tests/gestalts/utils.ts index 78df7ad932..92c854e481 100644 --- a/tests/gestalts/utils.ts +++ b/tests/gestalts/utils.ts @@ -4,10 +4,13 @@ import type { IdentityId, GestaltId, ProviderIdentityId, -} from '@/ids/types'; -import type { KeyPair } from '@/keys/types'; -import type { ClaimLinkNode, ClaimLinkIdentity } from '@/claims/payloads'; -import type { SignedClaim } from '@/claims/types'; +} from '#ids/types.js'; +import type { KeyPair } from '#keys/types.js'; +import type { + ClaimLinkNode, + ClaimLinkIdentity, +} from '#claims/payloads/index.js'; +import type { SignedClaim } from '#claims/types.js'; import type { GestaltNodeInfo, GestaltIdentityInfo, @@ -18,24 +21,27 @@ import type { GestaltInfo, GestaltLink, GestaltActions, -} from '@/gestalts/types'; -import type { GestaltIdEncoded } from '@/ids/types'; -import type { GestaltGraph } from '../../src/gestalts'; +} from '#gestalts/types.js'; +import type { GestaltIdEncoded } from '#ids/types.js'; +import type { GestaltGraph } from '#gestalts/index.js'; import fc from 'fast-check'; -import * as ids from '@/ids'; -import { gestaltActions } from '@/gestalts/types'; -import Token from '@/tokens/Token'; -import * as keysUtils from '@/keys/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as gestaltsUtils from '@/gestalts/utils'; -import { never } from '@/utils'; -import * as testsIdsUtils from '../ids/utils'; -import * as testsClaimsUtils from '../claims/utils'; +import * as testsIdsUtils from '../ids/utils.js'; +import * as testsClaimsUtils from '../claims/utils.js'; +import * as ids from '#ids/index.js'; +import { gestaltActions } from '#gestalts/types.js'; +import Token from '#tokens/Token.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as gestaltsUtils from '#gestalts/utils.js'; +import { never } from '#utils/index.js'; const gestaltNodeInfoArb = (nodeId: NodeId): fc.Arbitrary => - fc.record({ - nodeId: fc.constant(nodeId), - }); + fc.record( + { + nodeId: fc.constant(nodeId), + }, + { noNullPrototype: true }, + ); const gestaltIdentityInfoArb = ( providerId: ProviderId, @@ -51,6 +57,7 @@ const gestaltIdentityInfoArb = ( }, { requiredKeys: ['identityId', 'providerId'], + noNullPrototype: true, }, ); @@ -73,11 +80,14 @@ const gestaltLinkNodeArb = ( token.signWithPrivateKey(keyPair2); return token.toSigned(); }) as fc.Arbitrary>; - return fc.record({ - id: testsIdsUtils.gestaltLinkIdArb, - claim: signedClaimLinkNode, - meta: fc.constant({}), - }); + return fc.record( + { + id: testsIdsUtils.gestaltLinkIdArb, + claim: signedClaimLinkNode, + meta: fc.constant({}), + }, + { noNullPrototype: true }, + ); }; const linkNodeArb = (keyPair1: KeyPair, keyPair2: KeyPair) => @@ -105,13 +115,19 @@ const gestaltLinkIdentityArb = ( token.signWithPrivateKey(keyPair); return token.toSigned(); }) as fc.Arbitrary>; - return fc.record({ - id: testsIdsUtils.gestaltLinkIdArb, - claim: signedClaimLinkIdentity, - meta: fc.record({ - providerIdentityClaimId: testsIdsUtils.providerIdentityClaimIdArb, - }), - }); + return fc.record( + { + id: testsIdsUtils.gestaltLinkIdArb, + claim: signedClaimLinkIdentity, + meta: fc.record( + { + providerIdentityClaimId: testsIdsUtils.providerIdentityClaimIdArb, + }, + { noNullPrototype: true }, + ), + }, + { noNullPrototype: true }, + ); }; const linkIdentityArb = ( @@ -130,7 +146,11 @@ const gestaltActionsArb = (max?: number) => fc.dictionary( fc.oneof(...gestaltActions.map((action) => fc.constant(action))), fc.constant(null), - { minKeys: 1, maxKeys: max ?? gestaltActions.length }, + { + minKeys: 1, + maxKeys: max ?? gestaltActions.length, + noNullPrototype: true, + }, ); type GestaltGraphModel = { diff --git a/tests/git/http.test.ts b/tests/git/http.test.ts index d7daf55e0b..001a2cacd4 100644 --- a/tests/git/http.test.ts +++ b/tests/git/http.test.ts @@ -1,14 +1,14 @@ import type { ContextTimed } from '@matrixai/contexts'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import git from 'isomorphic-git'; import { test } from '@fast-check/jest'; import fc from 'fast-check'; -import * as gitHttp from '@/git/http'; -import * as gitUtils from '@/git/utils'; -import * as validationErrors from '@/validation/errors'; -import * as gitTestUtils from './utils'; +import * as gitTestUtils from './utils.js'; +import * as gitHttp from '#git/http.js'; +import * as gitUtils from '#git/utils.js'; +import * as validationErrors from '#validation/errors.js'; describe('Git Http', () => { let dataDir: string; @@ -153,7 +153,7 @@ describe('Git Http', () => { 'agent=git/isomorphic-git@1.24.5', ]); }); - test.prop([fc.uint8Array({ minLength: 100 }).noShrink()])( + test.prop([fc.noShrink(fc.uint8Array({ minLength: 100 }))])( 'parsePackRequest handles random data', async (data) => { const bufferData = Buffer.from(data); diff --git a/tests/git/utils.test.ts b/tests/git/utils.test.ts index e813959fd6..cf613a903d 100644 --- a/tests/git/utils.test.ts +++ b/tests/git/utils.test.ts @@ -1,13 +1,13 @@ import type { ContextTimed } from '@matrixai/contexts'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import git from 'isomorphic-git'; import fc from 'fast-check'; import { test } from '@fast-check/jest'; -import * as gitUtils from '@/git/utils'; -import * as validationErrors from '@/validation/errors'; -import * as gitTestUtils from './utils'; +import * as gitTestUtils from './utils.js'; +import * as gitUtils from '#git/utils.js'; +import * as validationErrors from '#validation/errors.js'; describe('Git utils', () => { let dataDir: string; @@ -199,8 +199,8 @@ describe('Git utils', () => { expect(objectList).toIncludeAllMembers(expectedObjectIds); }); test.prop([ - gitTestUtils.gitRequestDataArb, - fc.uint8Array({ size: 'medium' }), + fc.noShrink(gitTestUtils.gitRequestDataArb), + fc.noShrink(fc.uint8Array({ size: 'medium' })), ])('parseRequestLine', async (lineData, rest) => { const data = gitTestUtils.generateGitNegotiationLine( lineData, @@ -246,7 +246,7 @@ describe('Git utils', () => { break; } }); - test.prop([fc.uint8Array({ size: 'medium', minLength: 1 }).noShrink()])( + test.prop([fc.noShrink(fc.uint8Array({ size: 'medium', minLength: 1 }))])( 'parseRequestLine handles bad data', async (randomData) => { const bufferData = Buffer.from(randomData); diff --git a/tests/git/utils.ts b/tests/git/utils.ts index 3f8ef2d52b..885b146ea1 100644 --- a/tests/git/utils.ts +++ b/tests/git/utils.ts @@ -1,14 +1,14 @@ import type { ContextTimed } from '@matrixai/contexts'; -import type { POJO } from '@'; -import type { CapabilityList } from '@/git/types'; +import type { POJO } from '#index.js'; +import type { CapabilityList } from '#git/types.js'; import type { Arbitrary } from 'fast-check'; import type { EncryptedFS } from 'encryptedfs'; -import path from 'path'; +import path from 'node:path'; import git from 'isomorphic-git'; import fc from 'fast-check'; -import * as gitUtils from '@/git/utils'; -import * as gitHttp from '@/git/http'; -import * as utils from '@/utils'; +import * as gitUtils from '#git/utils.js'; +import * as gitHttp from '#git/http.js'; +import * as utils from '#utils/index.js'; /** * Utility for quickly creating a git repo with history @@ -193,43 +193,56 @@ function request({ }; } +const hexCharArb = fc.constantFrom(...`1234567890abcdef`.split('')); + // Generates a git objectId in the form of a 40-digit hex number -const gitObjectIdArb = fc.hexaString({ +const gitObjectIdArb = fc.string({ + unit: hexCharArb, maxLength: 40, minLength: 40, }); // Generates a list of capabilities, theses are just random valid strings const gitCapabilityListArb = fc.array( - fc.stringOf( - fc.constantFrom(...`abcdefghijklmnopqrstuvwxyz-1234567890`.split('')), - { minLength: 5 }, - ), + fc.string({ + unit: fc.constantFrom(...`abcdefghijklmnopqrstuvwxyz-1234567890`.split('')), + minLength: 5, + }), { size: 'small' }, ); // Generates git request data used for testing `parseRequestLine` const gitRequestDataArb = fc.oneof( - fc.record({ - type: fc.constant('want') as Arbitrary<'want'>, - objectId: gitObjectIdArb, - capabilityList: gitCapabilityListArb, - }), - fc.record({ - type: fc.constant('have') as Arbitrary<'have'>, - objectId: gitObjectIdArb, - }), - fc.record({ - type: fc.constantFrom<'SEPARATOR' | 'done' | 'none'>( - 'SEPARATOR', - 'done', - 'none', - ), - }), + fc.record( + { + type: fc.constant('want') as Arbitrary<'want'>, + objectId: gitObjectIdArb, + capabilityList: gitCapabilityListArb, + }, + { noNullPrototype: true }, + ), + fc.record( + { + type: fc.constant('have') as Arbitrary<'have'>, + objectId: gitObjectIdArb, + }, + { noNullPrototype: true }, + ), + fc.record( + { + type: fc.constantFrom<'SEPARATOR' | 'done' | 'none'>( + 'SEPARATOR', + 'done', + 'none', + ), + }, + { noNullPrototype: true }, + ), ); export { createGitRepo, generateGitNegotiationLine, request, + hexCharArb, gitObjectIdArb, gitCapabilityListArb, gitRequestDataArb, diff --git a/tests/http/utils.test.ts b/tests/http/utils.test.ts index 7b535cbf02..1119b1e1cb 100644 --- a/tests/http/utils.test.ts +++ b/tests/http/utils.test.ts @@ -1,6 +1,6 @@ import type { AddressInfo } from 'net'; import http from 'http'; -import * as httpUtils from '@/http/utils'; +import * as httpUtils from '#http/utils.js'; describe('Http utils', () => { test('termination of http server', async () => { diff --git a/tests/identities/IdentitiesManager.test.ts b/tests/identities/IdentitiesManager.test.ts index 390eeb986d..668e0b1694 100644 --- a/tests/identities/IdentitiesManager.test.ts +++ b/tests/identities/IdentitiesManager.test.ts @@ -4,30 +4,30 @@ import type { ProviderToken, IdentityData, IdentitySignedClaim, -} from '@/identities/types'; -import type { Key } from '@/keys/types'; -import type GestaltGraph from '@/gestalts/GestaltGraph'; -import type { ClaimLinkIdentity } from '@/claims/payloads'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +} from '#identities/types.js'; +import type GestaltGraph from '#gestalts/GestaltGraph.js'; +import type { ClaimLinkIdentity } from '#claims/payloads/index.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; +import { jest } from '@jest/globals'; import { test } from '@fast-check/jest'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import { IdentitiesManager, providers } from '@/identities'; -import * as identitiesErrors from '@/identities/errors'; -import * as keysUtils from '@/keys/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as utils from '@/utils'; -import KeyRing from '@/keys/KeyRing'; -import Sigchain from '@/sigchain/Sigchain'; -import { encodeProviderIdentityId } from '@/ids'; -import Token from '@/tokens/Token'; -import * as identitiesTestUtils from './utils'; -import TestProvider from './TestProvider'; -import * as claimsTestUtils from '../claims/utils'; -import * as keysTestUtils from '../keys/utils'; -import * as testNodesUtils from '../nodes/utils'; +import * as identitiesTestUtils from './utils.js'; +import TestProvider from './TestProvider.js'; +import * as claimsTestUtils from '../claims/utils.js'; +import * as keysTestUtils from '../keys/utils.js'; +import * as testNodesUtils from '../nodes/utils.js'; +import { IdentitiesManager, providers } from '#identities/index.js'; +import * as identitiesErrors from '#identities/errors.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import KeyRing from '#keys/KeyRing.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import { encodeProviderIdentityId } from '#ids/index.js'; +import Token from '#tokens/Token.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe('IdentitiesManager', () => { const logger = new Logger('IdentitiesManager Test', LogLevel.WARN, [ @@ -48,20 +48,7 @@ describe('IdentitiesManager', () => { logger, crypto: { key: keysUtils.generateKey(), - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); }); @@ -99,7 +86,7 @@ describe('IdentitiesManager', () => { await identitiesManager.getTokens('abc' as ProviderId); }).rejects.toThrow(identitiesErrors.ErrorIdentitiesManagerNotRunning); }); - test.prop([ + test.only.prop([ identitiesTestUtils.identitiyIdArb, identitiesTestUtils.providerTokenArb, ])('get, set and unset tokens', async (identityId, providerToken) => { diff --git a/tests/identities/TestProvider.ts b/tests/identities/TestProvider.ts index 45130a1480..ad174a39ed 100644 --- a/tests/identities/TestProvider.ts +++ b/tests/identities/TestProvider.ts @@ -1,4 +1,4 @@ -import type { POJO } from '@/types'; +import type { POJO } from '#types.js'; import type { ProviderId, IdentityId, @@ -6,17 +6,17 @@ import type { IdentityData, ProviderAuthenticateRequest, ProviderPaginationToken, -} from '@/identities/types'; +} from '#identities/types.js'; import type { IdentitySignedClaim, ProviderIdentityClaimId, -} from '@/identities/types'; -import type { SignedClaim } from '@/claims/types'; -import type { ClaimLinkIdentity } from '@/claims/payloads'; -import { Provider } from '@/identities'; -import * as identitiesUtils from '@/identities/utils'; -import * as identitiesErrors from '@/identities/errors'; -import * as tokenUtils from '@/tokens/utils'; +} from '#identities/types.js'; +import type { SignedClaim } from '#claims/types.js'; +import type { ClaimLinkIdentity } from '#claims/payloads/index.js'; +import { Provider } from '#identities/index.js'; +import * as identitiesUtils from '#identities/utils.js'; +import * as identitiesErrors from '#identities/errors.js'; +import * as tokenUtils from '#tokens/utils.js'; class TestProvider extends Provider { public readonly id: ProviderId; diff --git a/tests/identities/utils.ts b/tests/identities/utils.ts index c9db50d2f1..710387a8d0 100644 --- a/tests/identities/utils.ts +++ b/tests/identities/utils.ts @@ -1,14 +1,17 @@ -import type { IdentityId, ProviderId } from '@/ids'; -import type { ProviderToken } from '@/identities/types'; +import type { IdentityId, ProviderId } from '#ids/index.js'; +import type { ProviderToken } from '#identities/types.js'; import { fc } from '@fast-check/jest'; const providerTokenArb = fc - .record({ - accessToken: fc.string({ minLength: 10, maxLength: 32 }), - refreshToken: fc.string({ minLength: 0, maxLength: 32 }), - accessTokenExpiresIn: fc.integer(), - refreshTokenExpiresIn: fc.integer(), - }) + .record( + { + accessToken: fc.string({ minLength: 10, maxLength: 32 }), + refreshToken: fc.string({ minLength: 0, maxLength: 32 }), + accessTokenExpiresIn: fc.integer(), + refreshTokenExpiresIn: fc.integer(), + }, + { noNullPrototype: true }, + ) .map((item) => item as ProviderToken); const identitiyIdArb = fc.string().map((item) => item as IdentityId); diff --git a/tests/ids/index.test.ts b/tests/ids/index.test.ts index 3461b4fa6d..58eaee2d07 100644 --- a/tests/ids/index.test.ts +++ b/tests/ids/index.test.ts @@ -1,4 +1,4 @@ -import * as ids from '@/ids'; +import * as ids from '#ids/index.js'; describe('ids/index', () => { test('node ids', () => { diff --git a/tests/ids/utils.ts b/tests/ids/utils.ts index 042b573858..b94386f01c 100644 --- a/tests/ids/utils.ts +++ b/tests/ids/utils.ts @@ -7,10 +7,10 @@ import type { VaultId, GestaltLinkId, ProviderIdentityClaimId, -} from '@/ids/types'; +} from '#ids/types.js'; import { fc } from '@fast-check/jest'; import { IdInternal } from '@matrixai/id'; -import * as ids from '@/ids'; +import * as ids from '#ids/index.js'; const nodeIdArb = fc .uint8Array({ minLength: 32, maxLength: 32 }) diff --git a/tests/index.test.ts b/tests/index.test.ts index b8be30718c..6175aafbce 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,4 +1,4 @@ -import * as polykey from '@'; +import * as polykey from '#index.js'; describe('index', () => { test('exports PolykeyAgent, PolykeyClient and errors', async () => { diff --git a/tests/keys/CertManager.test.ts b/tests/keys/CertManager.test.ts index 3846c12873..b246e8f77e 100644 --- a/tests/keys/CertManager.test.ts +++ b/tests/keys/CertManager.test.ts @@ -1,24 +1,24 @@ import type { - Key, Certificate, CertificatePEM, CertificatePEMChain, -} from '@/keys/types'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +} from '#keys/types.js'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import { test, fc } from '@fast-check/jest'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import * as asynciterable from 'ix/asynciterable'; -import KeyRing from '@/keys/KeyRing'; -import CertManager from '@/keys/CertManager'; -import TaskManager from '@/tasks/TaskManager'; -import * as keysUtils from '@/keys/utils'; -import * as keysErrors from '@/keys/errors'; -import * as utils from '@/utils'; -import * as testsKeysUtils from './utils'; -import * as testsUtilsFastCheck from '../utils/fastCheck'; +import * as testsKeysUtils from './utils.js'; +import * as testsUtilsFastCheck from '../utils/fastCheck.js'; +import * as testsUtils from '../utils/index.js'; +import KeyRing from '#keys/KeyRing.js'; +import CertManager from '#keys/CertManager.js'; +import TaskManager from '#tasks/TaskManager.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as keysErrors from '#keys/errors.js'; +import * as utils from '#utils/index.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe(CertManager.name, () => { const password = keysUtils.getRandomBytes(10).toString('utf-8'); @@ -51,20 +51,7 @@ describe(CertManager.name, () => { logger, crypto: { key: keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - Buffer.from(key) as Key, - Buffer.from(plainText), - ).buffer; - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - Buffer.from(key) as Key, - Buffer.from(cipherText), - )?.buffer; - }, - }, + ops: polykeyWorkerManifest, }, }); taskManager = await TaskManager.createTaskManager({ db, logger }); @@ -211,7 +198,7 @@ describe(CertManager.name, () => { let certs: Array; let certPEMs: Array; let currentCert: Certificate; - certs = await asynciterable.toArray(certManager.getCerts()); + certs = await testsUtils.generatorToArray(certManager.getCerts()); currentCert = certs[0]; expect(certs).toHaveLength(1); expect(keysUtils.certNodeId(currentCert)).toStrictEqual( @@ -226,13 +213,13 @@ describe(CertManager.name, () => { expect(keysUtils.certIssuedBy(currentCert, currentCert)).toBe(true); expect(keysUtils.certNotExpiredBy(currentCert, new Date())).toBe(true); expect(await keysUtils.certNodeSigned(currentCert)).toBe(true); - certPEMs = await asynciterable.toArray(certManager.getCertPEMs()); + certPEMs = await testsUtils.generatorToArray(certManager.getCertPEMs()); expect(certPEMs).toHaveLength(1); expect(certPEMs[0]).toStrictEqual(keysUtils.certToPEM(currentCert!)); // After renewal there will be 2 certificates await certManager.renewCertWithNewKeyPair(password, 1000); - certs = await asynciterable.toArray(certManager.getCerts()); - certPEMs = await asynciterable.toArray(certManager.getCertPEMs()); + certs = await testsUtils.generatorToArray(certManager.getCerts()); + certPEMs = await testsUtils.generatorToArray(certManager.getCertPEMs()); expect(certs).toHaveLength(2); currentCert = certs[0]; expect(certPEMs).toHaveLength(2); @@ -406,23 +393,25 @@ describe(CertManager.name, () => { }); test.prop( [ - fc.commands([ - // Sleep command - fc - .integer({ min: 250, max: 250 }) - .map((ms) => new testsUtilsFastCheck.SleepCommand(ms)), - fc - .integer({ min: 0, max: 2 }) - .map( - (d) => new testsKeysUtils.RenewCertWithCurrentKeyPairCommand(d), - ), - fc - .tuple(testsKeysUtils.passwordArb, fc.integer({ min: 0, max: 2 })) - .map( - ([p, d]) => - new testsKeysUtils.RenewCertWithNewKeyPairCommand(p, d), - ), - ]), + fc.noShrink( + fc.commands([ + // Sleep command + fc + .integer({ min: 250, max: 250 }) + .map((ms) => new testsUtilsFastCheck.SleepCommand(ms)), + fc + .integer({ min: 0, max: 2 }) + .map( + (d) => new testsKeysUtils.RenewCertWithCurrentKeyPairCommand(d), + ), + fc + .tuple(testsKeysUtils.passwordArb, fc.integer({ min: 0, max: 2 })) + .map( + ([p, d]) => + new testsKeysUtils.RenewCertWithNewKeyPairCommand(p, d), + ), + ]), + ), ], { numRuns: 10 }, )('renewing with current and new key pair', async (cmds) => { diff --git a/tests/keys/KeyRing.test.ts b/tests/keys/KeyRing.test.ts index 470d63c144..9f6d0d44e5 100644 --- a/tests/keys/KeyRing.test.ts +++ b/tests/keys/KeyRing.test.ts @@ -1,12 +1,12 @@ -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import { test } from '@fast-check/jest'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import KeyRing from '@/keys/KeyRing'; -import * as keysUtils from '@/keys/utils'; -import * as keysErrors from '@/keys/errors'; -import * as testsKeysUtils from './utils'; +import * as testsKeysUtils from './utils.js'; +import KeyRing from '#keys/KeyRing.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as keysErrors from '#keys/errors.js'; describe(KeyRing.name, () => { const password = keysUtils.getRandomBytes(10).toString('utf-8'); diff --git a/tests/keys/utils.ts b/tests/keys/utils.ts index 1f2ef3f912..c3275875f4 100644 --- a/tests/keys/utils.ts +++ b/tests/keys/utils.ts @@ -8,22 +8,17 @@ import type { PrivateKeyJWK, Signature, MAC, -} from '@/keys/types'; -import type CertManager from '@/keys/CertManager'; -import type { KeyRing } from '@/keys'; +} from '#keys/types.js'; +import type CertManager from '#keys/CertManager.js'; +import type { KeyRing } from '#keys/index.js'; import { fc } from '@fast-check/jest'; -import { IterableX as Iterable } from 'ix/iterable'; -import { AsyncIterableX as AsyncIterable } from 'ix/asynciterable'; -import 'ix/add/iterable-operators/takewhile'; -import 'ix/add/iterable-operators/toarray'; -import 'ix/add/asynciterable-operators/toarray'; -import 'ix/add/asynciterable-operators/take'; -import * as asymmetric from '@/keys/utils/asymmetric'; -import * as jwk from '@/keys/utils/jwk'; -import * as x509 from '@/keys/utils/x509'; -import * as utils from '@/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testsIdsUtils from '../ids/utils'; +import * as testsIdsUtils from '../ids/utils.js'; +import * as testsUtils from '../utils/index.js'; +import * as asymmetric from '#keys/utils/asymmetric.js'; +import * as jwk from '#keys/utils/jwk.js'; +import * as x509 from '#keys/utils/x509.js'; +import * as utils from '#utils/index.js'; +import * as keysUtils from '#keys/utils/index.js'; const bufferArb = (constraints?: fc.IntArrayConstraints) => { return fc.uint8Array(constraints).map(utils.bufferWrap); @@ -32,81 +27,81 @@ const bufferArb = (constraints?: fc.IntArrayConstraints) => { /** * 256 bit symmetric key */ -const keyArb = fc - .uint8Array({ minLength: 32, maxLength: 32 }) - .map(utils.bufferWrap) - .noShrink() as fc.Arbitrary; +const keyArb = fc.noShrink( + fc.uint8Array({ minLength: 32, maxLength: 32 }).map(utils.bufferWrap), +) as fc.Arbitrary; -const keyJWKArb = keyArb - .map((key) => jwk.keyToJWK(key)) - .noShrink() as fc.Arbitrary; +const keyJWKArb = fc.noShrink( + keyArb.map((key) => jwk.keyToJWK(key)), +) as fc.Arbitrary; /** * Ed25519 Private Key */ -const privateKeyArb = fc - .uint8Array({ minLength: 32, maxLength: 32 }) - .map(utils.bufferWrap) - .noShrink() as fc.Arbitrary; +const privateKeyArb = fc.noShrink( + fc.uint8Array({ minLength: 32, maxLength: 32 }).map(utils.bufferWrap), +) as fc.Arbitrary; /** * Ed25519 Public Key */ -const publicKeyArb = privateKeyArb - .map(asymmetric.publicKeyFromPrivateKeyEd25519) - .noShrink(); +const publicKeyArb = fc.noShrink( + privateKeyArb.map(asymmetric.publicKeyFromPrivateKeyEd25519), +); /** * Keypair of public and private key */ -const keyPairArb = privateKeyArb - .map((privateKey) => { +const keyPairArb = fc.noShrink( + privateKeyArb.map((privateKey) => { const publicKey = asymmetric.publicKeyFromPrivateKeyEd25519(privateKey); return { publicKey, privateKey, secretKey: Buffer.concat([privateKey, publicKey]), }; - }) - .noShrink() as fc.Arbitrary; - -const publicKeyJWKArb = publicKeyArb - .map((publicKey) => jwk.publicKeyToJWK(publicKey)) - .noShrink() as fc.Arbitrary; - -const privateKeyJWKArb = privateKeyArb - .map((privateKey) => jwk.privateKeyToJWK(privateKey)) - .noShrink() as fc.Arbitrary; - -const certPArb = fc - .record({ - subjectKeyPair: keyPairArb, - issuerKeyPair: keyPairArb, - certId: testsIdsUtils.certIdArb, - duration: fc.integer({ min: 1, max: 1000 }), - }) - .map(async ({ subjectKeyPair, issuerKeyPair, certId, duration }) => { - const cert = await x509.generateCertificate({ - certId, - subjectKeyPair: subjectKeyPair, - issuerPrivateKey: issuerKeyPair.privateKey, - duration, - }); - return cert; - }) - .noShrink(); - -const signatureArb = fc - .uint8Array({ minLength: 64, maxLength: 64 }) - .map(utils.bufferWrap) - .noShrink() as fc.Arbitrary; - -const macArb = fc - .uint8Array({ minLength: 32, maxLength: 32 }) - .map(utils.bufferWrap) - .noShrink() as fc.Arbitrary; - -const passwordArb = fc.string({ minLength: 0, maxLength: 20 }).noShrink(); + }), +) as fc.Arbitrary; + +const publicKeyJWKArb = fc.noShrink( + publicKeyArb.map((publicKey) => jwk.publicKeyToJWK(publicKey)), +) as fc.Arbitrary; + +const privateKeyJWKArb = fc.noShrink( + privateKeyArb.map((privateKey) => jwk.privateKeyToJWK(privateKey)), +) as fc.Arbitrary; + +const certPArb = fc.noShrink( + fc + .record( + { + subjectKeyPair: keyPairArb, + issuerKeyPair: keyPairArb, + certId: testsIdsUtils.certIdArb, + duration: fc.integer({ min: 1, max: 1000 }), + }, + { noNullPrototype: true }, + ) + .map(async ({ subjectKeyPair, issuerKeyPair, certId, duration }) => { + const cert = await x509.generateCertificate({ + certId, + subjectKeyPair: subjectKeyPair, + issuerPrivateKey: issuerKeyPair.privateKey, + duration, + }); + return cert; + }), +); + +const signatureArb = fc.noShrink( + fc.uint8Array({ minLength: 64, maxLength: 64 }).map(utils.bufferWrap), +) as fc.Arbitrary; + +const macArb = fc.noShrink( + fc.uint8Array({ minLength: 32, maxLength: 32 }).map(utils.bufferWrap), +) as fc.Arbitrary; + +const passwordArb = fc.noShrink(fc.string({ minLength: 0, maxLength: 20 })); type CertManagerModel = { certs: Array; @@ -133,20 +128,18 @@ class RenewCertWithCurrentKeyPairCommand implements CertManagerCommand { const firstExpiredCert = model.certs.find((cert) => { return !x509.certNotExpiredBy(cert, now); }); - model.certs = [certNew].concat( - Iterable.as(model.certs) - .takeWhile((cert) => { - return x509.certNotExpiredBy(cert, now); - }) - .toArray(), - ); + const newCerts = [certNew]; + for (const cert of model.certs) { + if (!x509.certNotExpiredBy(cert, now)) break; + newCerts.push(cert); + } + model.certs = newCerts; if (firstExpiredCert != null) { model.certs.push(firstExpiredCert); } // Check consistency - const [certNew_, certOld_] = await AsyncIterable.as(real.getCerts()) - .take(2) - .toArray(); + const certList = await testsUtils.generatorToArray(real.getCerts()); + const [certNew_, certOld_] = certList.slice(0, 2); // New certificate with have a greater `CertId` expect(x509.certCertId(certNew)! > x509.certCertId(certOld)!).toBe(true); // Same key pair preserves the NodeId @@ -201,20 +194,18 @@ class RenewCertWithNewKeyPairCommand implements CertManagerCommand { const firstExpiredCert = model.certs.find((cert) => { return !x509.certNotExpiredBy(cert, now); }); - model.certs = [certNew].concat( - Iterable.as(model.certs) - .takeWhile((cert) => { - return x509.certNotExpiredBy(cert, now); - }) - .toArray(), - ); + const newCerts = [certNew]; + for (const cert of model.certs) { + if (!x509.certNotExpiredBy(cert, now)) break; + newCerts.push(cert); + } + model.certs = newCerts; if (firstExpiredCert != null) { model.certs.push(firstExpiredCert); } // Check consistency - const [certNew_, certOld_] = await AsyncIterable.as(real.getCerts()) - .take(2) - .toArray(); + const certList = await testsUtils.generatorToArray(real.getCerts()); + const [certNew_, certOld_] = certList.slice(0, 2); // New certificate with have a greater `CertId` expect(x509.certCertId(certNew)! > x509.certCertId(certOld)!).toBe(true); // Different key pair changes the the NodeId @@ -264,12 +255,11 @@ class ResetCertWithCurrentKeyPairCommand implements CertManagerCommand { const certOld = model.certs[0]; const certNew = await real.getCurrentCert(); model.certs = [certNew]; - const [certNew_, certOld_] = await AsyncIterable.as(real.getCerts()) - .take(2) - .toArray(); + const certList = await testsUtils.generatorToArray(real.getCerts()); + const [certNew_, certOld_] = certList.slice(0, 2); // New certificate with have a greater `CertId` expect(x509.certCertId(certNew)! > x509.certCertId(certOld)!).toBe(true); - // Different key pair changes the the NodeId + // Different key pair changes the NodeId expect(x509.certNodeId(certNew)).toStrictEqual(x509.certNodeId(certOld)); // New certificates should match expect(x509.certEqual(certNew_, certNew)).toBe(true); @@ -317,12 +307,11 @@ class ResetCertWithNewKeyPairCommand implements CertManagerCommand { const certOld = model.certs[0]; const certNew = await real.getCurrentCert(); model.certs = [certNew]; - const [certNew_, certOld_] = await AsyncIterable.as(real.getCerts()) - .take(2) - .toArray(); + const certList = await testsUtils.generatorToArray(real.getCerts()); + const [certNew_, certOld_] = certList.slice(0, 2); // New certificate with have a greater `CertId` expect(x509.certCertId(certNew)! > x509.certCertId(certOld)!).toBe(true); - // Different key pair changes the the NodeId + // Different key pair changes the NodeId expect(x509.certNodeId(certNew)).not.toStrictEqual( x509.certNodeId(certOld), ); diff --git a/tests/keys/utils/asymmetric.test.ts b/tests/keys/utils/asymmetric.test.ts index 3f8e66033c..31b40d6cbe 100644 --- a/tests/keys/utils/asymmetric.test.ts +++ b/tests/keys/utils/asymmetric.test.ts @@ -1,8 +1,8 @@ import { test, fc } from '@fast-check/jest'; -import * as asymmetric from '@/keys/utils/asymmetric'; -import * as ids from '@/ids'; -import * as utils from '@/utils'; -import * as testsKeysUtils from '../utils'; +import * as testsKeysUtils from '../utils.js'; +import * as asymmetric from '#keys/utils/asymmetric.js'; +import * as ids from '#ids/index.js'; +import * as utils from '#utils/index.js'; describe('keys/utils/asymmetric', () => { test.prop([ diff --git a/tests/keys/utils/generate.test.ts b/tests/keys/utils/generate.test.ts index 64706bc8c7..1ee148e3a6 100644 --- a/tests/keys/utils/generate.test.ts +++ b/tests/keys/utils/generate.test.ts @@ -1,6 +1,6 @@ import sodium from 'sodium-native'; -import * as generate from '@/keys/utils/generate'; -import * as recoveryCode from '@/keys/utils/recoveryCode'; +import * as generate from '#keys/utils/generate.js'; +import * as recoveryCode from '#keys/utils/recoveryCode.js'; describe('keys/utils/generate', () => { test('generate keys', () => { diff --git a/tests/keys/utils/hash.test.ts b/tests/keys/utils/hash.test.ts index 759e67de95..955db7c793 100644 --- a/tests/keys/utils/hash.test.ts +++ b/tests/keys/utils/hash.test.ts @@ -1,6 +1,6 @@ import { test, fc } from '@fast-check/jest'; -import * as hash from '@/keys/utils/hash'; -import * as utils from '@/utils'; +import * as hash from '#keys/utils/hash.js'; +import * as utils from '#utils/index.js'; describe('keys/utils/hash', () => { test.prop([fc.uint8Array({ minLength: 0, maxLength: 1024 })])( diff --git a/tests/keys/utils/jwk.test.ts b/tests/keys/utils/jwk.test.ts index b4805b8e80..65dd82fbf3 100644 --- a/tests/keys/utils/jwk.test.ts +++ b/tests/keys/utils/jwk.test.ts @@ -1,6 +1,8 @@ import { test, fc } from '@fast-check/jest'; -import * as jwk from '@/keys/utils/jwk'; -import * as testsKeysUtils from '../utils'; +import * as testsKeysUtils from '../utils.js'; +import * as jwk from '#keys/utils/jwk.js'; + +const hexCharArb = fc.constantFrom(...`1234567890ABCDEF`.split('')); describe('keys/utils/jwk', () => { test.prop([testsKeysUtils.keyArb])('key convert to and from JWK', (key) => { @@ -54,7 +56,7 @@ describe('keys/utils/jwk', () => { testsKeysUtils.keyJWKArb.map((keyJWK) => { return { ...keyJWK, - k: fc.sample(fc.hexaString(), 1)[0], + k: fc.sample(fc.string({ unit: hexCharArb }), 1)[0], }; }), ])('conversion from bad JWK key returns `undefined`', (badJWK) => { @@ -64,7 +66,7 @@ describe('keys/utils/jwk', () => { testsKeysUtils.publicKeyJWKArb.map((publicKeyJWK) => { return { ...publicKeyJWK, - x: fc.sample(fc.hexaString(), 1)[0], + x: fc.sample(fc.string({ unit: hexCharArb }), 1)[0], }; }), ])('conversion from bad JWK public key returns `undefined`', (badJWK) => { @@ -74,8 +76,8 @@ describe('keys/utils/jwk', () => { testsKeysUtils.privateKeyJWKArb.map((privateKeyJWK) => { return { ...privateKeyJWK, - x: fc.sample(fc.hexaString(), 1)[0], - d: fc.sample(fc.hexaString(), 1)[0], + x: fc.sample(fc.string({ unit: hexCharArb }), 1)[0], + d: fc.sample(fc.string({ unit: hexCharArb }), 1)[0], }; }), ])('conversion from bad JWK private key returns `undefined`', (badJWK) => { diff --git a/tests/keys/utils/password.test.ts b/tests/keys/utils/password.test.ts index 7f13c4bc88..b858bf1389 100644 --- a/tests/keys/utils/password.test.ts +++ b/tests/keys/utils/password.test.ts @@ -1,4 +1,4 @@ -import * as password from '@/keys/utils/password'; +import * as password from '#keys/utils/password.js'; describe('keys/utils/password', () => { test('password hashing ops limits raw numbers', () => { diff --git a/tests/keys/utils/pem.test.ts b/tests/keys/utils/pem.test.ts index 69de4d4d84..23d87aa3c9 100644 --- a/tests/keys/utils/pem.test.ts +++ b/tests/keys/utils/pem.test.ts @@ -1,8 +1,8 @@ import { test } from '@fast-check/jest'; -import webcrypto, { importKeyPair } from '@/keys/utils/webcrypto'; -import * as pem from '@/keys/utils/pem'; -import * as utils from '@/utils'; -import * as testsKeysUtils from '../utils'; +import * as testsKeysUtils from '../utils.js'; +import webcrypto, { importKeyPair } from '#keys/utils/webcrypto.js'; +import * as pem from '#keys/utils/pem.js'; +import * as utils from '#utils/index.js'; describe('keys/utils/pem', () => { test.prop([testsKeysUtils.keyPairArb])( diff --git a/tests/keys/utils/random.test.ts b/tests/keys/utils/random.test.ts index 52bfe05f63..e0eac30e8c 100644 --- a/tests/keys/utils/random.test.ts +++ b/tests/keys/utils/random.test.ts @@ -1,5 +1,5 @@ import { test, fc } from '@fast-check/jest'; -import * as random from '@/keys/utils/random'; +import * as random from '#keys/utils/random.js'; describe('keys/utils/random', () => { test('get random bytes less than 65536', () => { diff --git a/tests/keys/utils/recoveryCode.test.ts b/tests/keys/utils/recoveryCode.test.ts index 4da311d614..4fdd92a7af 100644 --- a/tests/keys/utils/recoveryCode.test.ts +++ b/tests/keys/utils/recoveryCode.test.ts @@ -1,7 +1,7 @@ import { generateRecoveryCode, validateRecoveryCode, -} from '@/keys/utils/recoveryCode'; +} from '#keys/utils/recoveryCode.js'; describe('keys/utils/recoveryCode', () => { test('generates recovery code', () => { diff --git a/tests/keys/utils/symmetric.test.ts b/tests/keys/utils/symmetric.test.ts index 935c0a6325..669b105731 100644 --- a/tests/keys/utils/symmetric.test.ts +++ b/tests/keys/utils/symmetric.test.ts @@ -1,7 +1,7 @@ import { test, fc } from '@fast-check/jest'; -import * as symmetric from '@/keys/utils/symmetric'; -import * as utils from '@/utils'; -import * as testsKeysUtils from '../utils'; +import * as testsKeysUtils from '../utils.js'; +import * as symmetric from '#keys/utils/symmetric.js'; +import * as utils from '#utils/index.js'; describe('keys/utils/symmetric', () => { test.prop([ diff --git a/tests/keys/utils/webcrypto.test.ts b/tests/keys/utils/webcrypto.test.ts index e92af41cf0..2bd6ef217d 100644 --- a/tests/keys/utils/webcrypto.test.ts +++ b/tests/keys/utils/webcrypto.test.ts @@ -1,6 +1,6 @@ import { test } from '@fast-check/jest'; -import { importKeyPair, exportKeyPair } from '@/keys/utils/webcrypto'; -import * as testsKeysUtils from '../utils'; +import * as testsKeysUtils from '../utils.js'; +import { importKeyPair, exportKeyPair } from '#keys/utils/webcrypto.js'; describe('keys/utils/webcrypto', () => { test.prop([testsKeysUtils.keyPairArb])( diff --git a/tests/keys/utils/x509.test.ts b/tests/keys/utils/x509.test.ts index c39fbb53cb..2f790ee549 100644 --- a/tests/keys/utils/x509.test.ts +++ b/tests/keys/utils/x509.test.ts @@ -1,9 +1,10 @@ +import { jest } from '@jest/globals'; import { test, fc } from '@fast-check/jest'; -import * as generate from '@/keys/utils/generate'; -import * as x509 from '@/keys/utils/x509'; -import * as asymmetric from '@/keys/utils/asymmetric'; -import * as ids from '@/ids'; -import * as testsKeysUtils from '../utils'; +import * as testsKeysUtils from '../utils.js'; +import * as generate from '#keys/utils/generate.js'; +import * as x509 from '#keys/utils/x509.js'; +import * as asymmetric from '#keys/utils/asymmetric.js'; +import * as ids from '#ids/index.js'; describe('keys/utils/x509', () => { const certIdGenerator = ids.createCertIdGenerator(); diff --git a/tests/network/utils.test.ts b/tests/network/utils.test.ts index 2813909feb..65fce9f4b9 100644 --- a/tests/network/utils.test.ts +++ b/tests/network/utils.test.ts @@ -1,5 +1,5 @@ -import type { Host, Hostname, Port } from '@/network/types'; -import * as networkUtils from '@/network/utils'; +import type { Host, Hostname, Port } from '#network/types.js'; +import * as networkUtils from '#network/utils.js'; describe('utils', () => { test('validating hosts', () => { diff --git a/tests/network/utils.ts b/tests/network/utils.ts index 17ae2ea53d..8afb8ecede 100644 --- a/tests/network/utils.ts +++ b/tests/network/utils.ts @@ -1,4 +1,4 @@ -import type { Host, Hostname, Port } from '@/network/types'; +import type { Host, Hostname, Port } from '#network/types.js'; import { fc } from '@fast-check/jest'; const hostArb = fc.oneof(fc.ipV4(), fc.ipV6()) as fc.Arbitrary; diff --git a/tests/nodes/NodeConnection.test.ts b/tests/nodes/NodeConnection.test.ts index 91d7528c01..7925d002b5 100644 --- a/tests/nodes/NodeConnection.test.ts +++ b/tests/nodes/NodeConnection.test.ts @@ -1,22 +1,22 @@ -import type { Host, Port, TLSConfig } from '@/network/types'; -import type { NodeId, NodeIdEncoded } from '@/ids'; +import type { Host, Port, TLSConfig } from '#network/types.js'; +import type { NodeId, NodeIdEncoded } from '#ids/index.js'; import type { RPCStream } from '@matrixai/rpc'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import type { AgentClientManifest } from '@/nodes/agent/callers'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import type { AgentClientManifest } from '#nodes/agent/callers/index.js'; import type { QUICConnection } from '@matrixai/quic'; import { QUICServer, QUICSocket, events as quicEvents } from '@matrixai/quic'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { errors as quicErrors } from '@matrixai/quic'; import { RPCServer } from '@matrixai/rpc'; -import * as nodesUtils from '@/nodes/utils'; -import * as nodesEvents from '@/nodes/events'; -import * as nodesErrors from '@/nodes/errors'; -import * as keysUtils from '@/keys/utils'; -import NodeConnection from '@/nodes/NodeConnection'; -import { promise } from '@/utils'; -import * as networkUtils from '@/network/utils'; -import * as tlsTestUtils from '../utils/tls'; -import * as testsUtils from '../utils/utils'; +import * as tlsTestUtils from '../utils/tls.js'; +import * as testsUtils from '../utils/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as nodesEvents from '#nodes/events.js'; +import * as nodesErrors from '#nodes/errors.js'; +import * as keysUtils from '#keys/utils/index.js'; +import NodeConnection from '#nodes/NodeConnection.js'; +import { promise } from '#utils/index.js'; +import * as networkUtils from '#network/utils.js'; describe(`${NodeConnection.name}`, () => { const logger = new Logger(`${NodeConnection.name} test`, LogLevel.WARN, [ diff --git a/tests/nodes/NodeConnectionManager.test.ts b/tests/nodes/NodeConnectionManager.test.ts index 7334ce2c5d..b798379c66 100644 --- a/tests/nodes/NodeConnectionManager.test.ts +++ b/tests/nodes/NodeConnectionManager.test.ts @@ -1,32 +1,33 @@ -import type { Host, Port } from '@/network/types'; -import type NodeConnection from '@/nodes/NodeConnection'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import type { KeyRing } from '@/keys'; -import type { NCMState } from './utils'; -import type { JSONValue, ObjectEmpty } from '@'; +import type { Host, Port } from '#network/types.js'; +import type NodeConnection from '#nodes/NodeConnection.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import type { KeyRing } from '#keys/index.js'; +import type { NCMState } from './utils.js'; +import type { JSONValue, ObjectEmpty } from '#index.js'; import type { AgentRPCRequestParams, AgentRPCResponseResult, NodesAuthenticateConnectionMessage, SuccessMessage, -} from '@/nodes/agent/types'; +} from '#nodes/agent/types.js'; import type { ContextTimed } from '@matrixai/contexts'; +import { jest } from '@jest/globals'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { Timer } from '@matrixai/timer'; import { destroyed } from '@matrixai/async-init'; import { UnaryHandler } from '@matrixai/rpc'; -import * as keysUtils from '@/keys/utils'; -import * as nodesEvents from '@/nodes/events'; -import * as nodesErrors from '@/nodes/errors'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import NodesAuthenticateConnection from '@/nodes/agent/handlers/NodesAuthenticateConnection'; -import NodesConnectionSignalFinal from '@/nodes/agent/handlers/NodesConnectionSignalFinal'; -import NodesConnectionSignalInitial from '@/nodes/agent/handlers/NodesConnectionSignalInitial'; -import * as utils from '@/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as nodesTestUtils from './utils'; -import * as keysTestUtils from '../keys/utils'; -import * as testsUtils from '../utils'; +import * as nodesTestUtils from './utils.js'; +import * as keysTestUtils from '../keys/utils.js'; +import * as testsUtils from '../utils/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesEvents from '#nodes/events.js'; +import * as nodesErrors from '#nodes/errors.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import NodesAuthenticateConnection from '#nodes/agent/handlers/NodesAuthenticateConnection.js'; +import NodesConnectionSignalFinal from '#nodes/agent/handlers/NodesConnectionSignalFinal.js'; +import NodesConnectionSignalInitial from '#nodes/agent/handlers/NodesConnectionSignalInitial.js'; +import * as utils from '#utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; class DummyNodesAuthenticateConnection extends UnaryHandler< ObjectEmpty, diff --git a/tests/nodes/NodeGraph.test.ts b/tests/nodes/NodeGraph.test.ts index 593cb9a0fa..43e24afebe 100644 --- a/tests/nodes/NodeGraph.test.ts +++ b/tests/nodes/NodeGraph.test.ts @@ -4,22 +4,22 @@ import type { NodeContactAddressData, NodeId, NodeBucket, -} from '@/nodes/types'; -import type { Key } from '@/keys/types'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +} from '#nodes/types.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; +import { jest } from '@jest/globals'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { test, fc } from '@fast-check/jest'; -import NodeGraph from '@/nodes/NodeGraph'; -import KeyRing from '@/keys/KeyRing'; -import * as keysUtils from '@/keys/utils'; -import * as nodesErrors from '@/nodes/errors'; -import * as nodesUtils from '@/nodes/utils'; -import * as utils from '@/utils'; -import { encodeNodeId } from '@/ids'; -import * as testNodesUtils from './utils'; +import * as testNodesUtils from './utils.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import KeyRing from '#keys/KeyRing.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesErrors from '#nodes/errors.js'; +import * as nodesUtils from '#nodes/utils.js'; +import { encodeNodeId } from '#ids/index.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe(`${NodeGraph.name} test`, () => { const password = 'password'; @@ -53,20 +53,7 @@ describe(`${NodeGraph.name} test`, () => { logger: logger.getChild(DB.name), crypto: { key: dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); nodeGraph = await NodeGraph.createNodeGraph({ @@ -576,13 +563,9 @@ describe(`${NodeGraph.name} test`, () => { ); }); describe('unsetNodeContact', () => { - test.prop( - [ - testNodesUtils.nodeIdArb.noShrink(), - testNodesUtils.nodeContactPairArb.noShrink(), - ], - { numRuns: 20 }, - )( + test.prop([testNodesUtils.nodeIdArb, testNodesUtils.nodeContactPairArb], { + numRuns: 20, + })( 'can unsetNodeContact with single address', async (nodeId, nodeContactPair) => { const nodeContact = { @@ -652,13 +635,9 @@ describe(`${NodeGraph.name} test`, () => { await nodeGraph.unsetNodeContact(nodeId2); expect(await nodeGraph.getBucketMetaProp(100, 'count')).toBe(0); }); - test.prop( - [ - testNodesUtils.nodeIdArb.noShrink(), - testNodesUtils.nodeContactPairArb.noShrink(), - ], - { numRuns: 20 }, - )('should delete lastUpdatedTime', async (nodeId, nodeContactPair) => { + test.prop([testNodesUtils.nodeIdArb, testNodesUtils.nodeContactPairArb], { + numRuns: 20, + })('should delete lastUpdatedTime', async (nodeId, nodeContactPair) => { const nodeContact = { [nodeContactPair.nodeContactAddress]: nodeContactPair.nodeContactAddressData, @@ -833,10 +812,11 @@ describe(`${NodeGraph.name} test`, () => { describe('getBucket', () => { test.prop( [ - fc.integer({ min: 20, max: 254 }).noShrink(), - fc - .array(testNodesUtils.nodeContactArb, { minLength: 1, maxLength: 20 }) - .noShrink(), + fc.integer({ min: 20, max: 254 }), + fc.array(testNodesUtils.nodeContactArb, { + minLength: 1, + maxLength: 20, + }), ], { numRuns: 1 }, )('can get a bucket', async (bucketIndex, nodeContacts) => { @@ -861,10 +841,11 @@ describe(`${NodeGraph.name} test`, () => { }); test.prop( [ - fc.integer({ min: 20, max: 254 }).noShrink(), - fc - .array(testNodesUtils.nodeContactArb, { minLength: 1, maxLength: 20 }) - .noShrink(), + fc.integer({ min: 20, max: 254 }), + fc.array(testNodesUtils.nodeContactArb, { + minLength: 1, + maxLength: 20, + }), ], { numRuns: 1 }, )( @@ -917,10 +898,11 @@ describe(`${NodeGraph.name} test`, () => { ); test.prop( [ - fc.integer({ min: 20, max: 254 }).noShrink(), - fc - .array(testNodesUtils.nodeContactArb, { minLength: 1, maxLength: 20 }) - .noShrink(), + fc.integer({ min: 20, max: 254 }), + fc.array(testNodesUtils.nodeContactArb, { + minLength: 1, + maxLength: 20, + }), ], { numRuns: 1 }, )( @@ -985,9 +967,7 @@ describe(`${NodeGraph.name} test`, () => { describe('getBuckets', () => { test.prop( [ - fc - .uniqueArray(fc.integer({ min: 0, max: 255 }), { minLength: 1 }) - .noShrink(), + fc.uniqueArray(fc.integer({ min: 0, max: 255 }), { minLength: 1 }), testNodesUtils.nodeContactArb, ], { numRuns: 1 }, @@ -1012,7 +992,7 @@ describe(`${NodeGraph.name} test`, () => { }); }); describe('resetBuckets', () => { - let getNodeIdMock: jest.SpyInstance; + let getNodeIdMock: jest.SpiedFunction; beforeEach(() => { getNodeIdMock = jest.spyOn(keyRing, 'getNodeId'); @@ -1308,11 +1288,7 @@ describe(`${NodeGraph.name} test`, () => { }); describe('nodesTotal', () => { test.prop( - [ - fc - .array(testNodesUtils.nodeIdContactPairArb, { maxLength: 20 }) - .noShrink(), - ], + [fc.array(testNodesUtils.nodeIdContactPairArb, { maxLength: 20 })], { numRuns: 1, }, diff --git a/tests/nodes/NodeManager.test.ts b/tests/nodes/NodeManager.test.ts index a7394731f2..95bfde9b93 100644 --- a/tests/nodes/NodeManager.test.ts +++ b/tests/nodes/NodeManager.test.ts @@ -1,50 +1,51 @@ -import type { Host, Port } from '@/network/types'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import type nodeGraph from '@/nodes/NodeGraph'; -import type { NCMState } from './utils'; -import type { NodeAddress, NodeContactAddressData } from '@/nodes/types'; +import type { Host, Port } from '#network/types.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import type nodeGraph from '#nodes/NodeGraph.js'; +import type { NCMState } from './utils.js'; +import type { NodeAddress, NodeContactAddressData } from '#nodes/types.js'; import type { AgentRPCRequestParams, AgentRPCResponseResult, NodesAuthenticateConnectionMessage, SuccessMessage, -} from '@/nodes/agent/types'; -import type { JSONValue, ObjectEmpty } from '@'; +} from '#nodes/agent/types.js'; +import type { JSONValue, ObjectEmpty } from '#index.js'; import type { ContextTimed } from '@matrixai/contexts'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { jest } from '@jest/globals'; import Logger, { formatting, LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { Semaphore } from '@matrixai/async-locks'; import { PromiseCancellable } from '@matrixai/async-cancellable'; import { UnaryHandler } from '@matrixai/rpc'; -import ACL from '@/acl/ACL'; -import NodeGraph from '@/nodes/NodeGraph'; +import { generateNodeIdForBucket } from './utils.js'; +import * as nodesTestUtils from './utils.js'; +import * as testsUtils from '../utils/index.js'; +import ACL from '#acl/ACL.js'; +import NodeGraph from '#nodes/NodeGraph.js'; import { NodesClaimsGet, NodesClosestActiveConnectionsGet, NodesClosestLocalNodesGet, -} from '@/nodes/agent/handlers'; -import * as keysUtils from '@/keys/utils'; -import * as nodesErrors from '@/nodes/errors'; -import * as nodesEvents from '@/nodes/events'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import NodesCrossSignClaim from '@/nodes/agent/handlers/NodesCrossSignClaim'; -import NodesConnectionSignalFinal from '@/nodes/agent/handlers/NodesConnectionSignalFinal'; -import NodesConnectionSignalInitial from '@/nodes/agent/handlers/NodesConnectionSignalInitial'; -import NodesAuthenticateConnection from '@/nodes/agent/handlers/NodesAuthenticateConnection'; -import * as nodesUtils from '@/nodes/utils'; -import { TaskManager } from '@/tasks'; -import { NodeConnection, NodeManager } from '@/nodes'; -import { GestaltGraph } from '@/gestalts'; -import { Sigchain } from '@/sigchain'; -import { KeyRing } from '@/keys'; -import NodeConnectionQueue from '@/nodes/NodeConnectionQueue'; -import * as utils from '@/utils'; -import { generateNodeIdForBucket } from './utils'; -import * as nodesTestUtils from './utils'; -import * as testsUtils from '../utils'; +} from '#nodes/agent/handlers/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesErrors from '#nodes/errors.js'; +import * as nodesEvents from '#nodes/events.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import NodesCrossSignClaim from '#nodes/agent/handlers/NodesCrossSignClaim.js'; +import NodesConnectionSignalFinal from '#nodes/agent/handlers/NodesConnectionSignalFinal.js'; +import NodesConnectionSignalInitial from '#nodes/agent/handlers/NodesConnectionSignalInitial.js'; +import NodesAuthenticateConnection from '#nodes/agent/handlers/NodesAuthenticateConnection.js'; +import * as nodesUtils from '#nodes/utils.js'; +import { TaskManager } from '#tasks/index.js'; +import { NodeConnection, NodeManager } from '#nodes/index.js'; +import { GestaltGraph } from '#gestalts/index.js'; +import { Sigchain } from '#sigchain/index.js'; +import { KeyRing } from '#keys/index.js'; +import NodeConnectionQueue from '#nodes/NodeConnectionQueue.js'; +import * as utils from '#utils/index.js'; class DummyNodesAuthenticateConnection extends UnaryHandler< ObjectEmpty, @@ -1141,6 +1142,8 @@ describe(`${NodeManager.name}`, () => { }); test('findNodeByMdns', async () => { + // Allow time for DNS to propagate + await utils.sleep(100); const result = await nodeManager.findNodeByMDNS(keyRingPeer.getNodeId()); expect(result).toBeDefined(); const [[host, port]] = result; @@ -1148,6 +1151,8 @@ describe(`${NodeManager.name}`, () => { expect(port).toBe(nodeConnectionManagerPeer.port); }); test('findNode with mdns', async () => { + // Allow time for DNS to propagate + await utils.sleep(100); const result = await nodeManager.findNode({ nodeId: keyRingPeer.getNodeId(), }); diff --git a/tests/nodes/agent/handlers/nodesAuditsGet.test.ts b/tests/nodes/agent/handlers/nodesAuditsGet.test.ts index 0bfeffe5f8..34070727d4 100644 --- a/tests/nodes/agent/handlers/nodesAuditsGet.test.ts +++ b/tests/nodes/agent/handlers/nodesAuditsGet.test.ts @@ -1,25 +1,25 @@ -import type { AuditEventId } from '@/ids'; -import type NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import type Discovery from '@/discovery/Discovery'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type { AuditEventId } from '#ids/index.js'; +import type NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import type Discovery from '#discovery/Discovery.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { test } from '@fast-check/jest'; import fc from 'fast-check'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { QUICClient, QUICServer, events as quicEvents } from '@matrixai/quic'; import { DB } from '@matrixai/db'; import { RPCClient, RPCServer } from '@matrixai/rpc'; -import NodesAuditEventsGet from '@/nodes/agent/handlers/NodesAuditEventsGet'; -import { nodesAuditEventsGet } from '@/nodes/agent/callers'; -import * as nodesUtils from '@/nodes/utils'; -import KeyRing from '@/keys/KeyRing'; -import Audit from '@/audit/Audit'; -import * as keysUtils from '@/keys/utils'; -import * as networkUtils from '@/network/utils'; -import * as auditUtils from '@/audit/utils'; -import * as tlsTestsUtils from '../../../utils/tls'; -import * as testNodesUtils from '../../../nodes/utils'; +import * as tlsTestsUtils from '../../../utils/tls.js'; +import * as testNodesUtils from '../../../nodes/utils.js'; +import NodesAuditEventsGet from '#nodes/agent/handlers/NodesAuditEventsGet.js'; +import { nodesAuditEventsGet } from '#nodes/agent/callers/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import KeyRing from '#keys/KeyRing.js'; +import Audit from '#audit/Audit.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as networkUtils from '#network/utils.js'; +import * as auditUtils from '#audit/utils.js'; describe('nodesAuditEventsGet', () => { const logger = new Logger('nodesAuditEventsGet test', LogLevel.WARN, [ @@ -251,10 +251,13 @@ describe('nodesAuditEventsGet', () => { testNodesUtils .randomAuditEventsArb(2, 100) // At least 2 so there's a valid seek index .chain((events) => - fc.record({ - events: fc.constant(events), - seekIndex: fc.integer({ min: 0, max: events.length - 1 }), - }), + fc.record( + { + events: fc.constant(events), + seekIndex: fc.integer({ min: 0, max: events.length - 1 }), + }, + { noNullPrototype: true }, + ), ), ])( 'should get audit events with a random seek index (property-based)', diff --git a/tests/nodes/agent/handlers/nodesClaimNetworkVerify.test.ts b/tests/nodes/agent/handlers/nodesClaimNetworkVerify.test.ts index 4859ed36f5..8035209cdf 100644 --- a/tests/nodes/agent/handlers/nodesClaimNetworkVerify.test.ts +++ b/tests/nodes/agent/handlers/nodesClaimNetworkVerify.test.ts @@ -1,31 +1,31 @@ -import type NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import type { NodeId } from '@/ids'; -import type { KeyPair } from '@/keys/types'; -import type { SignedTokenEncoded } from '@/tokens/types'; -import type { ClaimNetworkAuthority } from '@/claims/payloads/claimNetworkAuthority'; -import type { ClaimNetworkAccess } from '@/claims/payloads/claimNetworkAccess'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import type { NodeId } from '#ids/index.js'; +import type { KeyPair } from '#keys/types.js'; +import type { SignedTokenEncoded } from '#tokens/types.js'; +import type { ClaimNetworkAuthority } from '#claims/payloads/claimNetworkAuthority.js'; +import type { ClaimNetworkAccess } from '#claims/payloads/claimNetworkAccess.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { QUICClient, QUICServer, events as quicEvents } from '@matrixai/quic'; import { DB } from '@matrixai/db'; import { RPCClient, RPCServer } from '@matrixai/rpc'; -import { nodesClaimNetworkVerify } from '@/nodes/agent/callers'; -import { Token } from '@/tokens'; -import Sigchain from '@/sigchain/Sigchain'; -import KeyRing from '@/keys/KeyRing'; -import NodeGraph from '@/nodes/NodeGraph'; -import NodesClaimNetworkVerify from '@/nodes/agent/handlers/NodesClaimNetworkVerify'; -import ACL from '@/acl/ACL'; -import NodeManager from '@/nodes/NodeManager'; -import GestaltGraph from '@/gestalts/GestaltGraph'; -import TaskManager from '@/tasks/TaskManager'; -import * as keysUtils from '@/keys/utils'; -import * as claimsUtils from '@/claims/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as networkUtils from '@/network/utils'; -import * as tlsTestsUtils from '../../../utils/tls'; +import * as tlsTestsUtils from '../../../utils/tls.js'; +import { nodesClaimNetworkVerify } from '#nodes/agent/callers/index.js'; +import { Token } from '#tokens/index.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import KeyRing from '#keys/KeyRing.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import NodesClaimNetworkVerify from '#nodes/agent/handlers/NodesClaimNetworkVerify.js'; +import ACL from '#acl/ACL.js'; +import NodeManager from '#nodes/NodeManager.js'; +import GestaltGraph from '#gestalts/GestaltGraph.js'; +import TaskManager from '#tasks/TaskManager.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as claimsUtils from '#claims/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as networkUtils from '#network/utils.js'; describe('nodesClaimNetworkVerify', () => { const logger = new Logger('nodesClaimNetworkVerify test', LogLevel.WARN, [ diff --git a/tests/nodes/agent/handlers/nodesClaimsGet.test.ts b/tests/nodes/agent/handlers/nodesClaimsGet.test.ts index 9a6a826ac0..7fc4991272 100644 --- a/tests/nodes/agent/handlers/nodesClaimsGet.test.ts +++ b/tests/nodes/agent/handlers/nodesClaimsGet.test.ts @@ -1,22 +1,22 @@ -import type { IdentityId, ProviderId } from '@/identities/types'; -import type { ClaimIdEncoded } from '@/ids'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type { IdentityId, ProviderId } from '#identities/types.js'; +import type { ClaimIdEncoded } from '#ids/index.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { QUICClient, QUICServer, events as quicEvents } from '@matrixai/quic'; import { DB } from '@matrixai/db'; import { RPCClient, RPCServer } from '@matrixai/rpc'; -import * as nodesUtils from '@/nodes/utils'; -import { encodeProviderIdentityId } from '@/identities/utils'; -import NodesClaimsGet from '@/nodes/agent/handlers/NodesClaimsGet'; -import { nodesClaimsGet } from '@/nodes/agent/callers'; -import KeyRing from '@/keys/KeyRing'; -import Sigchain from '@/sigchain/Sigchain'; -import * as keysUtils from '@/keys/utils'; -import * as networkUtils from '@/network/utils'; -import * as tlsTestsUtils from '../../../utils/tls'; -import * as testNodesUtils from '../../../nodes/utils'; +import * as tlsTestsUtils from '../../../utils/tls.js'; +import * as testNodesUtils from '../../../nodes/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; +import { encodeProviderIdentityId } from '#identities/utils.js'; +import NodesClaimsGet from '#nodes/agent/handlers/NodesClaimsGet.js'; +import { nodesClaimsGet } from '#nodes/agent/callers/index.js'; +import KeyRing from '#keys/KeyRing.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as networkUtils from '#network/utils.js'; describe('nodesClaimsGet', () => { const logger = new Logger('nodesClaimsGet test', LogLevel.WARN, [ diff --git a/tests/nodes/agent/handlers/nodesClosestActiveConnectionsGet.test.ts b/tests/nodes/agent/handlers/nodesClosestActiveConnectionsGet.test.ts index 8054bb8422..338838a274 100644 --- a/tests/nodes/agent/handlers/nodesClosestActiveConnectionsGet.test.ts +++ b/tests/nodes/agent/handlers/nodesClosestActiveConnectionsGet.test.ts @@ -1,20 +1,20 @@ -import type { Host, Port } from '@/network/types'; +import type { Host, Port } from '#network/types.js'; import type { Timer } from '@matrixai/timer'; -import type KeyRing from '@/keys/KeyRing'; -import type { NodeId, NodeIdString } from '@/ids'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import type { NodeConnection } from '@/nodes'; -import type { ActiveConnectionDataMessage } from '@/nodes/agent/types'; +import type KeyRing from '#keys/KeyRing.js'; +import type { NodeId, NodeIdString } from '#ids/index.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import type { NodeConnection } from '#nodes/index.js'; +import type { ActiveConnectionDataMessage } from '#nodes/agent/types.js'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import * as keysUtils from '@/keys/utils'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import NodesAuthenticateConnection from '@/nodes/agent/handlers/NodesAuthenticateConnection'; -import NodesClosestActiveConnectionsGet from '@/nodes/agent/handlers/NodesClosestActiveConnectionsGet'; -import * as nodesUtils from '@/nodes/utils'; -import * as testsUtils from '../../../utils'; +import * as testsUtils from '../../../utils/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import NodesAuthenticateConnection from '#nodes/agent/handlers/NodesAuthenticateConnection.js'; +import NodesClosestActiveConnectionsGet from '#nodes/agent/handlers/NodesClosestActiveConnectionsGet.js'; +import * as nodesUtils from '#nodes/utils.js'; describe('nodesClosestLocalNode', () => { - const logger = new Logger('nodesClosestLocalNode test', LogLevel.INFO, [ + const logger = new Logger('nodesClosestLocalNode test', LogLevel.WARN, [ new StreamHandler(), ]); const localHost = '127.0.0.1' as Host; diff --git a/tests/nodes/agent/handlers/nodesClosestLocalNode.test.ts b/tests/nodes/agent/handlers/nodesClosestLocalNode.test.ts index 65eee95c90..ab394b6c3c 100644 --- a/tests/nodes/agent/handlers/nodesClosestLocalNode.test.ts +++ b/tests/nodes/agent/handlers/nodesClosestLocalNode.test.ts @@ -1,21 +1,21 @@ -import type { NodeIdEncoded } from '@/ids'; -import type { Host, Port } from '@/network/types'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type { NodeIdEncoded } from '#ids/index.js'; +import type { Host, Port } from '#network/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { QUICClient, QUICServer, events as quicEvents } from '@matrixai/quic'; import { DB } from '@matrixai/db'; import { RPCClient, RPCServer } from '@matrixai/rpc'; -import KeyRing from '@/keys/KeyRing'; -import * as nodesUtils from '@/nodes/utils'; -import { nodesClosestLocalNodesGet } from '@/nodes/agent/callers'; -import NodesClosestLocalNodesGet from '@/nodes/agent/handlers/NodesClosestLocalNodesGet'; -import NodeGraph from '@/nodes/NodeGraph'; -import * as keysUtils from '@/keys/utils'; -import * as networkUtils from '@/network/utils'; -import * as testNodesUtils from '../../../nodes/utils'; -import * as tlsTestsUtils from '../../../utils/tls'; +import * as testNodesUtils from '../../../nodes/utils.js'; +import * as tlsTestsUtils from '../../../utils/tls.js'; +import KeyRing from '#keys/KeyRing.js'; +import * as nodesUtils from '#nodes/utils.js'; +import { nodesClosestLocalNodesGet } from '#nodes/agent/callers/index.js'; +import NodesClosestLocalNodesGet from '#nodes/agent/handlers/NodesClosestLocalNodesGet.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as networkUtils from '#network/utils.js'; describe('nodesClosestLocalNode', () => { const logger = new Logger('nodesClosestLocalNode test', LogLevel.WARN, [ diff --git a/tests/nodes/agent/handlers/nodesConnectionSignalFinal.test.ts b/tests/nodes/agent/handlers/nodesConnectionSignalFinal.test.ts index d8e861a375..e2fe5da3a1 100644 --- a/tests/nodes/agent/handlers/nodesConnectionSignalFinal.test.ts +++ b/tests/nodes/agent/handlers/nodesConnectionSignalFinal.test.ts @@ -1,14 +1,15 @@ -import type { KeyPair } from '@/keys/types'; +import type { KeyPair } from '#keys/types.js'; +import { jest } from '@jest/globals'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { QUICClient, QUICServer, events as quicEvents } from '@matrixai/quic'; import { RPCClient, RPCServer } from '@matrixai/rpc'; -import { nodesConnectionSignalFinal } from '@/nodes/agent/callers'; -import { NodesConnectionSignalFinal } from '@/nodes/agent/handlers'; -import * as keysUtils from '@/keys/utils/index'; -import * as networkUtils from '@/network/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as tlsTestsUtils from '../../../utils/tls'; -import * as testsNodesUtils from '../../utils'; +import * as tlsTestsUtils from '../../../utils/tls.js'; +import * as testsNodesUtils from '../../utils.js'; +import { nodesConnectionSignalFinal } from '#nodes/agent/callers/index.js'; +import { NodesConnectionSignalFinal } from '#nodes/agent/handlers/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as networkUtils from '#network/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; describe('nodesHolePunchRequest', () => { const logger = new Logger('nodesHolePunchRequest test', LogLevel.WARN, [ diff --git a/tests/nodes/agent/handlers/nodesConnectionSignalInitial.test.ts b/tests/nodes/agent/handlers/nodesConnectionSignalInitial.test.ts index d3880af2d9..879f02172b 100644 --- a/tests/nodes/agent/handlers/nodesConnectionSignalInitial.test.ts +++ b/tests/nodes/agent/handlers/nodesConnectionSignalInitial.test.ts @@ -1,14 +1,17 @@ -import type { KeyPair } from '@/keys/types'; +import type { KeyPair } from '#keys/types.js'; +import type NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import type { Host, Port } from '#network/types.js'; +import { jest } from '@jest/globals'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { QUICClient, QUICServer, events as quicEvents } from '@matrixai/quic'; import { RPCClient, RPCServer } from '@matrixai/rpc'; -import { nodesConnectionSignalInitial } from '@/nodes/agent/callers'; -import { NodesConnectionSignalInitial } from '@/nodes/agent/handlers'; -import * as keysUtils from '@/keys/utils/index'; -import * as nodesUtils from '@/nodes/utils'; -import * as networkUtils from '@/network/utils'; -import * as tlsTestsUtils from '../../../utils/tls'; -import * as testsNodesUtils from '../../../nodes/utils'; +import * as tlsTestsUtils from '../../../utils/tls.js'; +import * as testsNodesUtils from '../../../nodes/utils.js'; +import { nodesConnectionSignalInitial } from '#nodes/agent/callers/index.js'; +import { NodesConnectionSignalInitial } from '#nodes/agent/handlers/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as networkUtils from '#network/utils.js'; describe('nodesHolePunchSignal', () => { const logger = new Logger('nodesHolePunchSignal test', LogLevel.WARN, [ @@ -27,7 +30,10 @@ describe('nodesHolePunchSignal', () => { let rpcClient: RPCClient; let quicClient: QUICClient; const dummyNodeConnectionManager = { - handleNodesConnectionSignalInitial: jest.fn(), + handleNodesConnectionSignalInitial: + jest.fn< + typeof NodeConnectionManager.prototype.handleNodesConnectionSignalInitial + >(), }; beforeEach(async () => { @@ -143,9 +149,8 @@ describe('nodesHolePunchSignal', () => { const signature = keysUtils.signWithPrivateKey(keyPair, data); dummyNodeConnectionManager.handleNodesConnectionSignalInitial.mockResolvedValue( { - host: '127.0.0.1', - port: 55555, - scopes: ['global'], + host: '127.0.0.1' as Host, + port: 55555 as Port, }, ); await rpcClient.methods.nodesConnectionSignalInitial({ diff --git a/tests/nodes/agent/handlers/nodesCrossSignClaim.test.ts b/tests/nodes/agent/handlers/nodesCrossSignClaim.test.ts index 5fb01045bc..d0c544e2e5 100644 --- a/tests/nodes/agent/handlers/nodesCrossSignClaim.test.ts +++ b/tests/nodes/agent/handlers/nodesCrossSignClaim.test.ts @@ -1,31 +1,31 @@ -import type NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import type { AgentClaimMessage } from '@/nodes/agent/types'; -import type { NodeId } from '@/ids'; -import type { ClaimLinkNode } from '@/claims/payloads'; -import type { KeyPair } from '@/keys/types'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import type { AgentClaimMessage } from '#nodes/agent/types.js'; +import type { NodeId } from '#ids/index.js'; +import type { ClaimLinkNode } from '#claims/payloads/index.js'; +import type { KeyPair } from '#keys/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { QUICClient, QUICServer, events as quicEvents } from '@matrixai/quic'; import { DB } from '@matrixai/db'; import { RPCClient, RPCServer } from '@matrixai/rpc'; -import Sigchain from '@/sigchain/Sigchain'; -import KeyRing from '@/keys/KeyRing'; -import NodeGraph from '@/nodes/NodeGraph'; -import { nodesCrossSignClaim } from '@/nodes/agent/callers'; -import NodesCrossSignClaim from '@/nodes/agent/handlers/NodesCrossSignClaim'; -import ACL from '@/acl/ACL'; -import NodeManager from '@/nodes/NodeManager'; -import GestaltGraph from '@/gestalts/GestaltGraph'; -import TaskManager from '@/tasks/TaskManager'; -import * as keysUtils from '@/keys/utils'; -import * as claimsUtils from '@/claims/utils'; -import { Token } from '@/tokens'; -import * as nodesUtils from '@/nodes/utils'; -import { generateKeyPair } from '@/keys/utils/generate'; -import * as networkUtils from '@/network/utils'; -import * as tlsTestsUtils from '../../../utils/tls'; +import * as tlsTestsUtils from '../../../utils/tls.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import KeyRing from '#keys/KeyRing.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import { nodesCrossSignClaim } from '#nodes/agent/callers/index.js'; +import NodesCrossSignClaim from '#nodes/agent/handlers/NodesCrossSignClaim.js'; +import ACL from '#acl/ACL.js'; +import NodeManager from '#nodes/NodeManager.js'; +import GestaltGraph from '#gestalts/GestaltGraph.js'; +import TaskManager from '#tasks/TaskManager.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as claimsUtils from '#claims/utils.js'; +import { Token } from '#tokens/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import { generateKeyPair } from '#keys/utils/generate.js'; +import * as networkUtils from '#network/utils.js'; describe('nodesCrossSignClaim', () => { const logger = new Logger('nodesCrossSignClaim test', LogLevel.WARN, [ diff --git a/tests/nodes/agent/handlers/notificationsSend.test.ts b/tests/nodes/agent/handlers/notificationsSend.test.ts index cc34de832c..c4027d0207 100644 --- a/tests/nodes/agent/handlers/notificationsSend.test.ts +++ b/tests/nodes/agent/handlers/notificationsSend.test.ts @@ -1,36 +1,34 @@ -import type { Notification, SignedNotification } from '@/notifications/types'; -import type { NodeId } from '@/ids'; -import type GestaltGraph from '@/gestalts/GestaltGraph'; -import type { Host } from '@/network/types'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import type { Notification, SignedNotification } from '#notifications/types.js'; +import type { NodeId } from '#ids/index.js'; +import type GestaltGraph from '#gestalts/GestaltGraph.js'; +import type { Host } from '#network/types.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { QUICClient, QUICServer, events as quicEvents } from '@matrixai/quic'; import { DB } from '@matrixai/db'; import { RPCClient, RPCServer } from '@matrixai/rpc'; -import { AsyncIterableX as AsyncIterable } from 'ix/asynciterable'; -import KeyRing from '@/keys/KeyRing'; -import * as nodesUtils from '@/nodes/utils'; -import NodeGraph from '@/nodes/NodeGraph'; -import * as notificationsUtils from '@/notifications/utils'; -import { notificationsSend } from '@/nodes/agent/callers'; -import NotificationsSend from '@/nodes/agent/handlers/NotificationsSend'; -import NotificationsManager from '@/notifications/NotificationsManager'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import NodeManager from '@/nodes/NodeManager'; -import ACL from '@/acl/ACL'; -import { Token } from '@/tokens'; -import * as notificationsErrors from '@/notifications/errors'; -import * as validationErrors from '@/validation/errors'; -import * as keysUtils from '@/keys/utils'; -import * as networkUtils from '@/network/utils'; -import Sigchain from '@/sigchain/Sigchain'; -import TaskManager from '@/tasks/TaskManager'; -import * as testsUtils from '../../../utils/utils'; -import * as tlsTestsUtils from '../../../utils/tls'; -import 'ix/add/asynciterable-operators/toarray'; +import * as testsUtils from '../../../utils/utils.js'; +import * as tlsTestsUtils from '../../../utils/tls.js'; +import KeyRing from '#keys/KeyRing.js'; +import * as nodesUtils from '#nodes/utils.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import * as notificationsUtils from '#notifications/utils.js'; +import { notificationsSend } from '#nodes/agent/callers/index.js'; +import NotificationsSend from '#nodes/agent/handlers/NotificationsSend.js'; +import NotificationsManager from '#notifications/NotificationsManager.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import NodeManager from '#nodes/NodeManager.js'; +import ACL from '#acl/ACL.js'; +import { Token } from '#tokens/index.js'; +import * as notificationsErrors from '#notifications/errors.js'; +import * as validationErrors from '#validation/errors.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as networkUtils from '#network/utils.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import TaskManager from '#tasks/TaskManager.js'; describe('notificationsSend', () => { const logger = new Logger('notificationsSend test', LogLevel.WARN, [ @@ -306,9 +304,9 @@ describe('notificationsSend', () => { signedNotificationEncoded: signedNotification, }); // Check notification was received - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(1); expect(receivedNotifications[0].data).toEqual(notification.data); expect(receivedNotifications[0].iss).toEqual(notification.iss); @@ -348,9 +346,9 @@ describe('notificationsSend', () => { notificationsErrors.ErrorNotificationsVerificationFailed, ); // Check notification was not received - let receivedNotifications = await AsyncIterable.as( + let receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(0); // Improperly typed notification const notification2 = { @@ -372,9 +370,9 @@ describe('notificationsSend', () => { validationErrors.ErrorParse, ); // Check notification was not received - receivedNotifications = await AsyncIterable.as( + receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(0); // Reverse side effects await acl.unsetNodePerm(senderNodeId); @@ -407,9 +405,9 @@ describe('notificationsSend', () => { notificationsErrors.ErrorNotificationsPermissionsNotFound, ); // Check notification was not received - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(0); }); }); diff --git a/tests/nodes/utils.test.ts b/tests/nodes/utils.test.ts index 88258bc90c..bff19f58a8 100644 --- a/tests/nodes/utils.test.ts +++ b/tests/nodes/utils.test.ts @@ -1,21 +1,22 @@ -import type { NodeId } from '@/ids/types'; -import type { Key, CertificatePEM, PrivateKeyPEM } from '@/keys/types'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +import type { NodeId } from '#ids/types.js'; +import type { CertificatePEM, PrivateKeyPEM } from '#keys/types.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import lexi from 'lexicographic-integer'; import { IdInternal } from '@matrixai/id'; import { DB } from '@matrixai/db'; import { errors as rpcErrors } from '@matrixai/rpc'; import { utils as wsUtils } from '@matrixai/ws'; -import { CryptoError } from '@matrixai/quic/dist/native'; -import * as nodesUtils from '@/nodes/utils'; -import * as keysUtils from '@/keys/utils'; -import * as validationErrors from '@/validation/errors'; -import * as utils from '@/utils'; -import * as testNodesUtils from './utils'; -import * as testTlsUtils from '../utils/tls'; +import { native } from '@matrixai/quic'; +import * as testNodesUtils from './utils.js'; +import * as testTlsUtils from '../utils/tls.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as validationErrors from '#validation/errors.js'; +import * as utils from '#utils/index.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe('nodes/utils', () => { const logger = new Logger(`nodes/utils test`, LogLevel.WARN, [ @@ -34,20 +35,7 @@ describe('nodes/utils', () => { logger, crypto: { key: dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); }); @@ -418,7 +406,7 @@ describe('nodes/utils', () => { if (result.result !== 'fail') { utils.never('result.result should be "fail"'); } - expect(result.value).toBe(CryptoError.CertificateExpired); + expect(result.value).toBe(native.CryptoError.CertificateExpired); }); }); describe('server verifyClientCertificateChain', () => { @@ -448,7 +436,7 @@ describe('nodes/utils', () => { const result = await nodesUtils.verifyClientCertificateChain( cert.certChainPem.map((v) => wsUtils.pemToDER(v)), ); - expect(result).toBe(CryptoError.CertificateExpired); + expect(result).toBe(native.CryptoError.CertificateExpired); }); }); }); diff --git a/tests/nodes/utils.ts b/tests/nodes/utils.ts index 46866099e9..6d8c242f87 100644 --- a/tests/nodes/utils.ts +++ b/tests/nodes/utils.ts @@ -1,22 +1,23 @@ import type { NodeAddressScope, + NodeContactAddress, NodeContactAddressData, NodeId, -} from '@/nodes/types'; -import type PolykeyAgent from '@/PolykeyAgent'; +} from '#nodes/types.js'; +import type PolykeyAgent from '#PolykeyAgent.js'; import type Logger from '@matrixai/logger'; -import type { KeyRing } from '@/keys'; -import type { Host, Port } from '@/network/types'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; +import type { KeyRing } from '#keys/index.js'; +import type { Host, Port } from '#network/types.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; import { webcrypto } from 'crypto'; import { IdInternal } from '@matrixai/id'; import * as fc from 'fast-check'; -import * as keysUtils from '@/keys/utils'; -import * as utils from '@/utils'; -import * as nodesUtils from '@/nodes/utils'; -import { hostArb, hostnameArb, portArb } from '../network/utils'; -import NodeConnectionManager from '../../src/nodes/NodeConnectionManager'; -import * as testsUtils from '../utils'; +import { hostArb, hostnameArb, portArb } from '../network/utils.js'; +import * as testsUtils from '../utils/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as utils from '#utils/index.js'; +import * as nodesUtils from '#nodes/utils.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; /** * Generate random `NodeId` @@ -111,26 +112,28 @@ async function nodesConnect(localNode: PolykeyAgent, remoteNode: PolykeyAgent) { ); } -const nodeIdArb = fc - .int8Array({ minLength: 32, maxLength: 32 }) - .map((value) => IdInternal.fromBuffer(Buffer.from(value))) - .noShrink(); +const nodeIdArb = fc.noShrink( + fc + .int8Array({ minLength: 32, maxLength: 32 }) + .map((value) => IdInternal.fromBuffer(Buffer.from(value))), +); const nodeIdArrayArb = (length: number) => - fc.array(nodeIdArb, { maxLength: length, minLength: length }).noShrink(); + fc.noShrink(fc.array(nodeIdArb, { maxLength: length, minLength: length })); const uniqueNodeIdArb = (length: number) => - fc - .array(nodeIdArb, { maxLength: length, minLength: length }) - .noShrink() - .filter((values) => { - for (let i = 0; i < values.length; i++) { - for (let j = i; j < values.length; j++) { - if (values[i].equals(values[j])) return true; + fc.noShrink( + fc + .array(nodeIdArb, { maxLength: length, minLength: length }) + .filter((values) => { + for (let i = 0; i < values.length; i++) { + for (let j = i; j < values.length; j++) { + if (values[i].equals(values[j])) return true; + } } - } - return false; - }); + return false; + }), + ); const nodeAddressArb = fc.tuple(fc.oneof(hostArb, hostnameArb), portArb); @@ -145,30 +148,48 @@ const scopeArb = fc.constantFrom( const scopesArb = fc.uniqueArray(scopeArb); -const nodeContactAddressDataArb = fc.record({ - mode: fc.constantFrom('direct', 'signal', 'relay'), - connectedTime: fc.integer({ min: 0 }), - scopes: scopesArb, -}) as fc.Arbitrary; +const nodeContactAddressDataArb = fc.record( + { + mode: fc.constantFrom('direct', 'signal', 'relay'), + connectedTime: fc.integer({ min: 0 }), + scopes: scopesArb, + }, + { noNullPrototype: true }, +) as fc.Arbitrary; -const nodeContactPairArb = fc.record({ - nodeContactAddress: nodeContactAddressArb, - nodeContactAddressData: nodeContactAddressDataArb, -}); +const nodeContactPairArb: fc.Arbitrary<{ + nodeContactAddress: NodeContactAddress; + nodeContactAddressData: NodeContactAddressData; +}> = fc.noShrink( + fc.record( + { + nodeContactAddress: nodeContactAddressArb, + nodeContactAddressData: nodeContactAddressDataArb, + }, + { noNullPrototype: true }, + ), +); -const nodeContactArb = fc - .dictionary(nodeContactAddressArb, nodeContactAddressDataArb, { +const nodeContactArb = fc.noShrink( + fc.dictionary(nodeContactAddressArb, nodeContactAddressDataArb, { minKeys: 1, maxKeys: 5, - }) - .noShrink(); + noNullPrototype: true, + }), +); -const nodeIdContactPairArb = fc - .record({ - nodeId: nodeIdArb, - nodeContact: nodeContactArb, - }) - .noShrink(); +const nodeIdContactPairArb: fc.Arbitrary<{ + nodeId: NodeId; + nodeContact: Record; +}> = fc.noShrink( + fc.record( + { + nodeId: nodeIdArb, + nodeContact: nodeContactArb, + }, + { noNullPrototype: true }, + ), +); /** * Signs using the 256-bit HMAC key @@ -323,11 +344,14 @@ async function nodeConnectionManagerFactory({ const randomAuditEventsArb = (minLength: number = 1, maxLength: number = 100) => fc.array( - fc.record({ - remoteNodeId: fc.string({ minLength: 1, maxLength: 20 }), - remoteHost: fc.ipV4(), - remotePort: fc.nat({ max: 65535 }), - }), + fc.record( + { + remoteNodeId: fc.string({ minLength: 1, maxLength: 20 }), + remoteHost: fc.ipV4(), + remotePort: fc.nat({ max: 65535 }), + }, + { noNullPrototype: true }, + ), { minLength, maxLength }, ); diff --git a/tests/notifications/NotificationsManager.test.ts b/tests/notifications/NotificationsManager.test.ts index 7f833115cf..170d9dd778 100644 --- a/tests/notifications/NotificationsManager.test.ts +++ b/tests/notifications/NotificationsManager.test.ts @@ -1,38 +1,40 @@ -import type { NodeId, NodeIdEncoded, NotificationIdEncoded } from '@/ids/types'; -import type { Host } from '@/network/types'; -import type { VaultActions, VaultName } from '@/vaults/types'; -import type { Notification, NotificationData } from '@/notifications/types'; -import type { Key } from '@/keys/types'; -import type GestaltGraph from '@/gestalts/GestaltGraph'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import type { + NodeId, + NodeIdEncoded, + NotificationIdEncoded, +} from '#ids/types.js'; +import type { Host } from '#network/types.js'; +import type { VaultActions, VaultName } from '#vaults/types.js'; +import type { Notification, NotificationData } from '#notifications/types.js'; +import type GestaltGraph from '#gestalts/GestaltGraph.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { jest } from '@jest/globals'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; import { IdInternal } from '@matrixai/id'; -import { AsyncIterableX as AsyncIterable } from 'ix/asynciterable'; -import TaskManager from '@/tasks/TaskManager'; -import PolykeyAgent from '@/PolykeyAgent'; -import ACL from '@/acl/ACL'; -import Sigchain from '@/sigchain/Sigchain'; -import KeyRing from '@/keys/KeyRing'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import NodeGraph from '@/nodes/NodeGraph'; -import NodeManager from '@/nodes/NodeManager'; -import NodesAuthenticateConnection from '@/nodes/agent/handlers/NodesAuthenticateConnection'; -import NotificationsManager from '@/notifications/NotificationsManager'; -import * as nodesErrors from '@/nodes/errors'; -import * as notificationsErrors from '@/notifications/errors'; -import * as notificationsEvents from '@/notifications/events'; -import * as notificationsUtils from '@/notifications/utils'; -import * as vaultsUtils from '@/vaults/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as keysUtils from '@/keys/utils'; -import * as utils from '@/utils'; -import * as testsUtils from '../utils'; -import * as tlsTestsUtils from '../utils/tls'; -import 'ix/add/asynciterable-operators/toarray'; +import * as testsUtils from '../utils/index.js'; +import * as tlsTestsUtils from '../utils/tls.js'; +import TaskManager from '#tasks/TaskManager.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import ACL from '#acl/ACL.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import KeyRing from '#keys/KeyRing.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import NodeManager from '#nodes/NodeManager.js'; +import NodesAuthenticateConnection from '#nodes/agent/handlers/NodesAuthenticateConnection.js'; +import NotificationsManager from '#notifications/NotificationsManager.js'; +import * as nodesErrors from '#nodes/errors.js'; +import * as notificationsErrors from '#notifications/errors.js'; +import * as notificationsEvents from '#notifications/events.js'; +import * as notificationsUtils from '#notifications/utils.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe('NotificationsManager', () => { const password = 'password'; @@ -82,20 +84,7 @@ describe('NotificationsManager', () => { logger, crypto: { key: keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); acl = await ACL.createACL({ @@ -280,9 +269,9 @@ describe('NotificationsManager', () => { ), ]) .then((value) => value.map((value) => value.sendP)); - const outboxNotifications = await AsyncIterable.as( + const outboxNotifications = await testsUtils.generatorToArray( notificationsManager.readOutboxNotifications(), - ).toArray(); + ); expect(outboxNotifications).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -307,9 +296,9 @@ describe('NotificationsManager', () => { .next() .then((data) => data.done), ).resolves.toBe(true); - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( receiver.notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(3); expect(receivedNotifications).toEqual( expect.arrayContaining([ @@ -398,9 +387,9 @@ describe('NotificationsManager', () => { .next() .then((data) => data.done), ).resolves.toBe(true); - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( receiver.notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(0); // Reverse side-effects await notificationsManager.stop(); @@ -498,11 +487,11 @@ describe('NotificationsManager', () => { await notificationsManager.receiveNotification(notification1); await notificationsManager.receiveNotification(notification2); await notificationsManager.receiveNotification(notification3); - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ order: 'desc', }), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(3); expect(receivedNotifications[0].data).toEqual(notification3.data); expect(receivedNotifications[0].iss).toEqual(senderIdEncoded); @@ -546,9 +535,9 @@ describe('NotificationsManager', () => { ).rejects.toThrow( notificationsErrors.ErrorNotificationsPermissionsNotFound, ); - let receivedNotifications = await AsyncIterable.as( + let receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(0); // Missing permission await acl.setNodePerm(senderId, { @@ -556,9 +545,9 @@ describe('NotificationsManager', () => { vaults: {}, }); await notificationsManager.receiveNotification(notification); - receivedNotifications = await AsyncIterable.as( + receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(0); // Reverse side-effects await acl.unsetNodePerm(senderId); @@ -596,9 +585,9 @@ describe('NotificationsManager', () => { vaults: {}, }); await notificationsManager.receiveNotification(notification); - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(1); expect(receivedNotifications[0].isRead).toBeTruthy(); // Reverse side-effects @@ -666,11 +655,11 @@ describe('NotificationsManager', () => { await notificationsManager.receiveNotification(notification1); await notificationsManager.receiveNotification(notification2); await notificationsManager.receiveNotification(notification3); - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ order: 'desc', }), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(3); expect(receivedNotifications[0].data['message']).toBe('msg3'); expect(receivedNotifications[1].data['message']).toBe('msg2'); @@ -743,11 +732,11 @@ describe('NotificationsManager', () => { for await (const _ of notificationsManager.readInboxNotifications()) { // Noop } - const unreadNotifications = await AsyncIterable.as( + const unreadNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ unread: true, }), - ).toArray(); + ); expect(unreadNotifications).toHaveLength(0); // Reverse side-effects await notificationsManager.clearInboxNotifications(); @@ -814,11 +803,11 @@ describe('NotificationsManager', () => { await notificationsManager.receiveNotification(notification1); await notificationsManager.receiveNotification(notification2); await notificationsManager.receiveNotification(notification3); - const lastNotification = await AsyncIterable.as( + const lastNotification = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ limit: 1, }), - ).toArray(); + ); expect(lastNotification).toHaveLength(1); // Reverse side-effects await notificationsManager.clearInboxNotifications(); @@ -885,11 +874,11 @@ describe('NotificationsManager', () => { await notificationsManager.receiveNotification(notification1); await notificationsManager.receiveNotification(notification2); await notificationsManager.receiveNotification(notification3); - const reversedNotifications = await AsyncIterable.as( + const reversedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ order: 'asc', }), - ).toArray(); + ); expect(reversedNotifications).toHaveLength(3); expect(reversedNotifications[0].data['message']).toBe('msg1'); expect(reversedNotifications[1].data['message']).toBe('msg2'); @@ -969,29 +958,29 @@ describe('NotificationsManager', () => { await notificationsManager.receiveNotification(notification1); await notificationsManager.receiveNotification(notification2); await notificationsManager.receiveNotification(notification3); - let notifications = await AsyncIterable.as( + let notifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ order: 'asc', seek: notificationsUtils.decodeNotificationId( notificationIdsEncoded[1], ), }), - ).toArray(); + ); expect(notifications).toHaveLength(2); expect(notifications[0].data['message']).toBe('msg2'); expect(notifications[1].data['message']).toBe('msg3'); - notifications = await AsyncIterable.as( + notifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ order: 'asc', seekEnd: notificationsUtils.decodeNotificationId( notificationIdsEncoded[1], ), }), - ).toArray(); + ); expect(notifications).toHaveLength(2); expect(notifications[0].data['message']).toBe('msg1'); expect(notifications[1].data['message']).toBe('msg2'); - notifications = await AsyncIterable.as( + notifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ order: 'asc', seek: notificationsUtils.decodeNotificationId( @@ -1001,7 +990,7 @@ describe('NotificationsManager', () => { notificationIdsEncoded[1], ), }), - ).toArray(); + ); expect(notifications).toHaveLength(1); expect(notifications[0].data['message']).toBe('msg2'); // Reverse side-effects @@ -1074,11 +1063,11 @@ describe('NotificationsManager', () => { await notificationsManager.receiveNotification(notification1); await notificationsManager.receiveNotification(notification2); await notificationsManager.receiveNotification(notification3); - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ order: 'desc', }), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(2); expect(receivedNotifications[0].data['message']).toBe('msg3'); expect(receivedNotifications[1].data['message']).toBe('msg2'); @@ -1164,9 +1153,9 @@ describe('NotificationsManager', () => { }); await notificationsManager.receiveNotification(notification); await notificationsManager.clearInboxNotifications(); - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(0); // Reverse side-effects await acl.unsetNodePerm(senderId); @@ -1196,9 +1185,9 @@ describe('NotificationsManager', () => { }, }); await notificationsManager.clearOutboxNotifications(); - const outboxNotifications = await AsyncIterable.as( + const outboxNotifications = await testsUtils.generatorToArray( notificationsManager.readOutboxNotifications(), - ).toArray(); + ); expect(outboxNotifications).toHaveLength(0); // Reverse side-effects await receiver.notificationsManager.clearInboxNotifications(); @@ -1259,21 +1248,21 @@ describe('NotificationsManager', () => { } await notificationsManager.stop(); await notificationsManager.start(); - const unreadNotifications = await AsyncIterable.as( + const unreadNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ unread: true, order: 'desc', }), - ).toArray(); + ); expect(unreadNotifications).toHaveLength(1); expect(unreadNotifications[0].data).toEqual(notification1.data); expect(unreadNotifications[0].iss).toBe(notification1.iss); - const latestNotification = await AsyncIterable.as( + const latestNotification = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications({ limit: 1, order: 'desc', }), - ).toArray(); + ); expect(latestNotification).toHaveLength(1); expect(latestNotification[0].data).toEqual(notification2.data); expect(latestNotification[0].iss).toBe(notification2.iss); @@ -1329,13 +1318,13 @@ describe('NotificationsManager', () => { }); await notificationsManager.stop(); await notificationsManager.start({ fresh: true }); - const receivedNotifications = await AsyncIterable.as( + const receivedNotifications = await testsUtils.generatorToArray( notificationsManager.readInboxNotifications(), - ).toArray(); + ); expect(receivedNotifications).toHaveLength(0); - const outboxNotifications = await AsyncIterable.as( + const outboxNotifications = await testsUtils.generatorToArray( notificationsManager.readOutboxNotifications(), - ).toArray(); + ); expect(outboxNotifications).toHaveLength(0); // Reverse side-effects await receiver.notificationsManager.clearInboxNotifications(); diff --git a/tests/notifications/utils.test.ts b/tests/notifications/utils.test.ts index 4b42472639..bff06be27b 100644 --- a/tests/notifications/utils.test.ts +++ b/tests/notifications/utils.test.ts @@ -1,12 +1,12 @@ -import type { Notification, NotificationData } from '@/notifications/types'; -import type { VaultActions, VaultName } from '@/vaults/types'; -import type { KeyPairLocked } from '@/keys/types'; -import * as keysUtils from '@/keys/utils'; -import * as notificationsUtils from '@/notifications/utils'; -import * as vaultsUtils from '@/vaults/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as validationErrors from '@/validation/errors'; -import * as testNodesUtils from '../nodes/utils'; +import type { Notification, NotificationData } from '#notifications/types.js'; +import type { VaultActions, VaultName } from '#vaults/types.js'; +import type { KeyPairLocked } from '#keys/types.js'; +import * as testNodesUtils from '../nodes/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as notificationsUtils from '#notifications/utils.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; +import * as validationErrors from '#validation/errors.js'; describe('Notifications utils', () => { const keyPair = keysUtils.generateKeyPair() as KeyPairLocked; diff --git a/tests/polykeyScratch.ts b/tests/polykeyScratch.ts index 7e404e8b1a..2b045c0642 100644 --- a/tests/polykeyScratch.ts +++ b/tests/polykeyScratch.ts @@ -3,14 +3,14 @@ * the need for the CLI. This should allow streamline testing * against networks */ -import type { Hostname } from '../src/network/types'; +import type { Hostname } from '#network/types.js'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; // Import { trackTimers } from './utils'; -import * as testsUtils from './utils'; -import PolykeyAgent from '../src/PolykeyAgent'; -import { sleep } from '../src/utils'; -import { encodeNodeId } from '../src/ids'; -import { resolveSeednodes } from '../src/nodes/utils'; +import * as testsUtils from './utils/index.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import { sleep } from '#utils/index.js'; +import { encodeNodeId } from '#ids/index.js'; +import { resolveSeednodes } from '#nodes/utils.js'; async function main() { const logger = new Logger('PolykeyAgent Test', LogLevel.WARN, [ diff --git a/tests/schema/Schema.test.ts b/tests/schema/Schema.test.ts index b08ce7b6b1..2b6445de40 100644 --- a/tests/schema/Schema.test.ts +++ b/tests/schema/Schema.test.ts @@ -1,11 +1,11 @@ -import type { StateVersion } from '@/schema/types'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import type { StateVersion } from '#schema/types.js'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import Schema from '@/schema/Schema'; -import * as schemaErrors from '@/schema/errors'; -import config from '@/config'; +import Schema from '#schema/Schema.js'; +import * as schemaErrors from '#schema/errors.js'; +import config from '#config.js'; describe('Schema', () => { const logger = new Logger(`${Schema.name} Test`, LogLevel.WARN, [ diff --git a/tests/sessions/Session.test.ts b/tests/sessions/Session.test.ts index f79456b6a3..bc9fc35120 100644 --- a/tests/sessions/Session.test.ts +++ b/tests/sessions/Session.test.ts @@ -1,10 +1,10 @@ -import type { SessionToken } from '@/sessions/types'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import type { SessionToken } from '#sessions/types.js'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import Session from '@/sessions/Session'; -import * as sessionErrors from '@/sessions/errors'; +import Session from '#sessions/Session.js'; +import * as sessionErrors from '#sessions/errors.js'; describe('Session', () => { const logger = new Logger(`${Session.name} Test`, LogLevel.WARN, [ diff --git a/tests/sessions/SessionManager.test.ts b/tests/sessions/SessionManager.test.ts index bd6b5b746d..0ebf685b3f 100644 --- a/tests/sessions/SessionManager.test.ts +++ b/tests/sessions/SessionManager.test.ts @@ -1,15 +1,14 @@ -import type { Key } from '@/keys/types'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import { DB } from '@matrixai/db'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import KeyRing from '@/keys/KeyRing'; -import * as utils from '@/utils'; -import * as keysUtils from '@/keys/utils'; -import SessionManager from '@/sessions/SessionManager'; -import * as sessionsErrors from '@/sessions/errors'; -import { sleep } from '@/utils'; +import KeyRing from '#keys/KeyRing.js'; +import * as keysUtils from '#keys/utils/index.js'; +import SessionManager from '#sessions/SessionManager.js'; +import * as sessionsErrors from '#sessions/errors.js'; +import { sleep } from '#utils/index.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe('SessionManager', () => { const password = 'password'; @@ -41,20 +40,7 @@ describe('SessionManager', () => { logger, crypto: { key: keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, }); }); diff --git a/tests/setupAfterEnv.ts b/tests/setupAfterEnv.ts index 8ea8279e39..ec04822709 100644 --- a/tests/setupAfterEnv.ts +++ b/tests/setupAfterEnv.ts @@ -1,3 +1,5 @@ +import { jest } from '@jest/globals'; + // Default timeout per test // some tests may take longer in which case you should specify the timeout // explicitly for each test by using the third parameter of test function diff --git a/tests/sigchain/Sigchain.test.ts b/tests/sigchain/Sigchain.test.ts index 7893b67320..377ce13a67 100644 --- a/tests/sigchain/Sigchain.test.ts +++ b/tests/sigchain/Sigchain.test.ts @@ -1,21 +1,20 @@ -import type { Key } from '@/keys/types'; -import type { ClaimId, SignedClaim } from '@/claims/types'; -import type { ClaimInput } from '@/sigchain/types'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +import type { ClaimId, SignedClaim } from '#claims/types.js'; +import type { ClaimInput } from '#sigchain/types.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; import { test, fc } from '@fast-check/jest'; -import { AsyncIterableX as AsyncIterable } from 'ix/asynciterable'; -import 'ix/add/asynciterable-operators/toarray'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import KeyRing from '@/keys/KeyRing'; -import Sigchain from '@/sigchain/Sigchain'; -import Token from '@/tokens/Token'; -import * as sigchainErrors from '@/sigchain/errors'; -import * as keysUtils from '@/keys/utils'; -import * as claimsUtils from '@/claims/utils'; -import * as utils from '@/utils'; +import * as testsUtils from '../utils/index.js'; +import KeyRing from '#keys/KeyRing.js'; +import Sigchain from '#sigchain/Sigchain.js'; +import Token from '#tokens/Token.js'; +import * as sigchainErrors from '#sigchain/errors.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as claimsUtils from '#claims/utils.js'; +import * as utils from '#utils/index.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe(Sigchain.name, () => { const password = keysUtils.getRandomBytes(10).toString('utf-8'); @@ -47,20 +46,7 @@ describe(Sigchain.name, () => { logger, crypto: { key: keyRing.dbKey, - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - Buffer.from(key) as Key, - Buffer.from(plainText), - ).buffer; - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - Buffer.from(key) as Key, - Buffer.from(cipherText), - )?.buffer; - }, - }, + ops: polykeyWorkerManifest, }, }); }); @@ -173,11 +159,11 @@ describe(Sigchain.name, () => { expect(result.status).toBe('fulfilled'); } // Get all chain of claims in descending order - const signedClaims = await AsyncIterable.as( + const signedClaims = await testsUtils.generatorToArray( sigchain.getSignedClaims({ order: 'desc', }), - ).toArray(); + ); expect(signedClaims.length).toBe(datas.length); let digest: string | null = null; for (const [, signedClaim] of signedClaims) { @@ -267,11 +253,11 @@ describe(Sigchain.name, () => { const signatures = await sigchain.getSignatures(claimId); expect(signatures).toEqual(signedClaim.signatures); } - const signedClaims = await AsyncIterable.as( + const signedClaims = await testsUtils.generatorToArray( sigchain.getSignedClaims(), - ).toArray(); + ); expect(signedClaims).toEqual(claimIdSignedClaims); - const claims = await AsyncIterable.as(sigchain.getClaims()).toArray(); + const claims = await testsUtils.generatorToArray(sigchain.getClaims()); expect(claims).toEqual( claimIdSignedClaims.map((c) => [c[0], c[1].payload]), ); @@ -321,9 +307,9 @@ describe(Sigchain.name, () => { for (let i = 0; i < 3; i++) { claims.push(await sigchain.addClaim({})); } - const claimsAsc = await AsyncIterable.as( + const claimsAsc = await testsUtils.generatorToArray( sigchain.getClaims({ seek: claims[1][0], order: 'asc' }), - ).toArray(); + ); expect(claimsAsc).toHaveLength(2); // The claim we seeked to is included expect(claimsAsc[0][0].equals(claims[1][0])).toBeTrue(); @@ -341,9 +327,9 @@ describe(Sigchain.name, () => { for (let i = 0; i < 3; i++) { claims.push(await sigchain.addClaim({})); } - const claimsAsc = await AsyncIterable.as( + const claimsAsc = await testsUtils.generatorToArray( sigchain.getClaims({ seek: claims[1][0], order: 'desc' }), - ).toArray(); + ); expect(claimsAsc).toHaveLength(2); // The claim we seeked to is included expect(claimsAsc[0][0].equals(claims[1][0])).toBeTrue(); @@ -361,9 +347,9 @@ describe(Sigchain.name, () => { for (let i = 0; i < 3; i++) { claims.push(await sigchain.addClaim({})); } - const claimsAsc = await AsyncIterable.as( + const claimsAsc = await testsUtils.generatorToArray( sigchain.getClaims({ seek: claims[1][0], limit: 1 }), - ).toArray(); + ); expect(claimsAsc).toHaveLength(1); // The claim we seeked to is included expect(claimsAsc[0][0].equals(claims[1][0])).toBeTrue(); diff --git a/tests/status/Status.test.ts b/tests/status/Status.test.ts index d1ec9da468..fc5a78c8d7 100644 --- a/tests/status/Status.test.ts +++ b/tests/status/Status.test.ts @@ -1,11 +1,11 @@ -import type { StatusLive } from '@/status/types'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import type { StatusLive } from '#status/types.js'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import config from '@/config'; -import { Status, errors as statusErrors } from '@/status'; -import * as testNodesUtils from '../nodes/utils'; +import * as testNodesUtils from '../nodes/utils.js'; +import config from '#config.js'; +import { Status, errors as statusErrors } from '#status/index.js'; describe('Status', () => { const logger = new Logger(`${Status.name} Test`, LogLevel.WARN, [ diff --git a/tests/tasks/TaskManager.test.ts b/tests/tasks/TaskManager.test.ts index e48b6e6ede..f0c17ffc74 100644 --- a/tests/tasks/TaskManager.test.ts +++ b/tests/tasks/TaskManager.test.ts @@ -2,22 +2,24 @@ import type { PromiseCancellable } from '@matrixai/async-cancellable'; import type { ContextTimed } from '@matrixai/contexts'; import type { Task, + TaskHandler, TaskHandlerId, TaskId, TaskPath, TaskStatus, -} from '@/tasks/types'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +} from '#tasks/types.js'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { jest } from '@jest/globals'; import * as fc from 'fast-check'; import { test } from '@fast-check/jest'; import { DB } from '@matrixai/db'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { Lock } from '@matrixai/async-locks'; -import TaskManager from '@/tasks/TaskManager'; -import * as tasksErrors from '@/tasks/errors'; -import * as utils from '@/utils'; +import TaskManager from '#tasks/TaskManager.js'; +import * as tasksErrors from '#tasks/errors.js'; +import * as utils from '#utils/index.js'; describe(TaskManager.name, () => { const logger = new Logger(`${TaskManager.name} test`, LogLevel.WARN, [ @@ -62,7 +64,7 @@ describe(TaskManager.name, () => { logger, }); const handlerId = 'asd' as TaskHandlerId; - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async () => {}); taskManager.registerHandler(handlerId, handler); await taskManager.startProcessing(); @@ -143,7 +145,7 @@ describe(TaskManager.name, () => { logger, }); const handlerId = 'asd' as TaskHandlerId; - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async () => {}); taskManager.registerHandler(handlerId, handler); await taskManager.startProcessing(); @@ -205,26 +207,37 @@ describe(TaskManager.name, () => { await taskManager.stop(); expect(handler).toHaveBeenCalledTimes(3); }); - const scheduleCommandArb = fc - .record({ - handlerId: fc.constant(handlerId), - delay: fc.integer({ min: 10, max: 1000 }), - parameters: fc.constant([]), - priority: fc.integer({ min: -200, max: 200 }), - }) - .map((taskSpec) => async (context: { taskManager: TaskManager }) => { - return await context.taskManager.scheduleTask({ - ...taskSpec, - lazy: false, - }); - }) - .noShrink(); - const sleepCommandArb = fc - .integer({ min: 10, max: 100 }) - .noShrink() - .map((value) => async (_context) => { + const scheduleCommandArb = fc.noShrink( + fc + .record( + { + handlerId: fc.constant(handlerId), + delay: fc.integer({ min: 10, max: 1000 }), + parameters: fc.constant([]), + priority: fc.integer({ min: -200, max: 200 }), + }, + { noNullPrototype: true }, + ) + .map( + (taskSpec: { + handlerId: TaskHandlerId; + delay: number; + parameters: []; + priority: number; + }) => + async (context: { taskManager: TaskManager }) => { + return await context.taskManager.scheduleTask({ + ...taskSpec, + lazy: false, + }); + }, + ), + ); + const sleepCommandArb = fc.noShrink( + fc.integer({ min: 10, max: 100 }).map((value) => async (_context) => { await utils.sleep(value); - }); + }), + ); const commandsArb = fc.array( fc.oneof( @@ -244,7 +257,7 @@ describe(TaskManager.name, () => { fresh: true, logger, }); - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async () => { await utils.sleep(200); }); @@ -275,7 +288,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('tasks are handled exactly once per task', async () => { - const handler = jest.fn(); + const handler = jest.fn(); const pendingLock = new Lock(); const [lockReleaser] = await pendingLock.lock()(); const resolvedTasks = new Map(); @@ -310,7 +323,7 @@ describe(TaskManager.name, () => { expect(handler).toHaveBeenCalledTimes(totalTasks); }); test('awaited taskPromises resolve', async () => { - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async (_ctx, _taskInfo, fail) => { if (!fail) throw Error('three'); return fail; @@ -334,7 +347,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('awaited taskPromises reject', async () => { - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async (_ctx, _taskInfo, fail) => { if (!fail) throw Error('three'); return fail; @@ -358,7 +371,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('awaited taskPromises resolve or reject', async () => { - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async (_ctx, _taskInfo, fail) => { if (!fail) throw Error('three'); return fail; @@ -408,7 +421,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('tasks fail with unregistered handler', async () => { - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async (_ctx, _taskInfo, fail) => { if (!fail) throw Error('three'); return fail; @@ -446,7 +459,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('eager taskPromise resolves when awaited after task completion', async () => { - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async (_ctx, _taskInfo, fail) => { if (!fail) throw Error('three'); return fail; @@ -474,7 +487,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('lazy taskPromise rejects when awaited after task completion', async () => { - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async () => {}); taskManager = await TaskManager.createTaskManager({ db, @@ -552,7 +565,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('can cancel active task, clean up and reject taskPromise', async () => { - const handler = jest.fn(); + const handler = jest.fn(); const { p: pauseP, resolveP: resolvePauseP } = utils.promise(); handler.mockImplementation(async (ctx: ContextTimed) => { const abortP = new Promise((_, reject) => @@ -604,7 +617,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('incomplete active tasks cleaned up during startup', async () => { - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async () => {}); taskManager = await TaskManager.createTaskManager({ db, @@ -654,7 +667,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('stopping should gracefully end active tasks', async () => { - const handler = jest.fn(); + const handler = jest.fn(); const { p: pauseP, resolveP: resolvePauseP } = utils.promise(); handler.mockImplementation(async (ctx: ContextTimed) => { const abortP = new Promise((_, reject) => @@ -708,7 +721,7 @@ describe(TaskManager.name, () => { test('stopped tasks should run again if allowed', async () => { const { p: pauseP, resolveP: resolvePauseP } = utils.promise(); const handlerId1 = 'handler1' as TaskHandlerId; - const handler1 = jest.fn(); + const handler1 = jest.fn(); handler1.mockImplementation(async (ctx: ContextTimed) => { const abortP = new Promise((_, reject) => ctx.signal.addEventListener('abort', () => @@ -722,7 +735,7 @@ describe(TaskManager.name, () => { await Promise.race([pauseP, abortP]); }); const handlerId2 = 'handler2' as TaskHandlerId; - const handler2 = jest.fn(); + const handler2 = jest.fn(); handler2.mockImplementation(async (ctx: ContextTimed) => { const abortP = new Promise((_, reject) => ctx.signal.addEventListener('abort', () => reject(ctx.signal.reason)), @@ -901,8 +914,8 @@ describe(TaskManager.name, () => { test('updating tasks while scheduled', async () => { const handlerId1 = 'handler1' as TaskHandlerId; const handlerId2 = 'handler2' as TaskHandlerId; - const handler1 = jest.fn(); - const handler2 = jest.fn(); + const handler1 = jest.fn(); + const handler2 = jest.fn(); taskManager = await TaskManager.createTaskManager({ db, handlers: { [handlerId1]: handler1, [handlerId2]: handler2 }, @@ -949,7 +962,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('updating tasks while queued or active should fail', async () => { - const handler = jest.fn(); + const handler = jest.fn(); handler.mockImplementation(async (_ctx, _taskInfo, value) => value); taskManager = await TaskManager.createTaskManager({ db, @@ -991,8 +1004,8 @@ describe(TaskManager.name, () => { test('updating tasks delay should update schedule timer', async () => { const handlerId1 = 'handler1' as TaskHandlerId; const handlerId2 = 'handler2' as TaskHandlerId; - const handler1 = jest.fn(); - const handler2 = jest.fn(); + const handler1 = jest.fn(); + const handler2 = jest.fn(); handler1.mockImplementation(async (_ctx, _taskInfo, value) => value); handler2.mockImplementation(async (_ctx, _taskInfo, value) => value); taskManager = await TaskManager.createTaskManager({ @@ -1038,7 +1051,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('task should run after scheduled delay', async () => { - const handler = jest.fn(); + const handler = jest.fn(); taskManager = await TaskManager.createTaskManager({ db, handlers: { [handlerId]: handler }, @@ -1089,7 +1102,7 @@ describe(TaskManager.name, () => { expect(taskInfinite.deadline).toBe(Infinity); }); test('queued tasks should be started in priority order', async () => { - const handler = jest.fn(); + const handler = jest.fn(); const { p: pendingP, resolveP: resolvePendingP } = utils.promise(); const totalTasks = 31; const completedTaskOrder: Array = []; @@ -1140,7 +1153,7 @@ describe(TaskManager.name, () => { await taskManager.stop(); }); test('task exceeding deadline should abort and clean up', async () => { - const handler = jest.fn(); + const handler = jest.fn(); const { p: pauseP, resolveP: resolvePauseP } = utils.promise(); handler.mockImplementation(async (ctx: ContextTimed) => { const abortP = new Promise((_, reject) => diff --git a/tests/tasks/utils.test.ts b/tests/tasks/utils.test.ts index afac0a7795..81e7f618b3 100644 --- a/tests/tasks/utils.test.ts +++ b/tests/tasks/utils.test.ts @@ -3,9 +3,9 @@ import type { TaskDeadline, TaskDelay, TaskId, -} from '@/tasks/types'; +} from '#tasks/types.js'; import { IdInternal } from '@matrixai/id'; -import * as tasksUtils from '@/tasks/utils'; +import * as tasksUtils from '#tasks/utils.js'; describe('tasks/utils', () => { test('encode priority from `int8` to flipped `uint8`', () => { diff --git a/tests/tokens/Token.test.ts b/tests/tokens/Token.test.ts index a5f27e58cd..845805cf6a 100644 --- a/tests/tokens/Token.test.ts +++ b/tests/tokens/Token.test.ts @@ -1,13 +1,13 @@ import type { TokenHeaderSignatureEncoded, TokenPayloadEncoded, -} from '@/tokens/types'; +} from '#tokens/types.js'; import { test, fc } from '@fast-check/jest'; -import Token from '@/tokens/Token'; -import * as tokensUtils from '@/tokens/utils'; -import * as tokensErrors from '@/tokens/errors'; -import * as testsTokensUtils from './utils'; -import * as testsKeysUtils from '../keys/utils'; +import * as testsTokensUtils from './utils.js'; +import * as testsKeysUtils from '../keys/utils.js'; +import Token from '#tokens/Token.js'; +import * as tokensUtils from '#tokens/utils.js'; +import * as tokensErrors from '#tokens/errors.js'; describe(Token.name, () => { test.prop([testsTokensUtils.tokenPayloadArb])( @@ -58,15 +58,21 @@ describe(Token.name, () => { }, ); test.prop([ - fc.record({ - payload: fc.string() as fc.Arbitrary, - signatures: fc.array( - fc.record({ - protected: fc.string(), - signature: fc.string(), - }) as fc.Arbitrary, - ), - }), + fc.record( + { + payload: fc.string() as fc.Arbitrary, + signatures: fc.array( + fc.record( + { + protected: fc.string(), + signature: fc.string(), + }, + { noNullPrototype: true }, + ) as fc.Arbitrary, + ), + }, + { noNullPrototype: true }, + ), ])( 'creating Token from invalid signed token encoded results in parse error', (signedTokenEncodedIncorrect) => { diff --git a/tests/tokens/schemas.test.ts b/tests/tokens/schemas.test.ts index 226b6e75c3..dbc8ca331c 100644 --- a/tests/tokens/schemas.test.ts +++ b/tests/tokens/schemas.test.ts @@ -1,6 +1,6 @@ import { test, fc } from '@fast-check/jest'; -import * as tokensSchemas from '@/tokens/schemas'; -import * as testsTokensUtils from './utils'; +import * as testsTokensUtils from './utils.js'; +import * as tokensSchemas from '#tokens/schemas/index.js'; describe('tokens/schemas', () => { test.prop([testsTokensUtils.signedTokenEncodedArb, fc.object()])( diff --git a/tests/tokens/utils.test.ts b/tests/tokens/utils.test.ts index ed741b7f6e..69a67b8be0 100644 --- a/tests/tokens/utils.test.ts +++ b/tests/tokens/utils.test.ts @@ -1,8 +1,8 @@ import { test, fc } from '@fast-check/jest'; -import * as keysUtils from '@/keys/utils'; -import * as tokensUtils from '@/tokens/utils'; -import * as validationErrors from '@/validation/errors'; -import * as testsTokensUtils from './utils'; +import * as testsTokensUtils from './utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as tokensUtils from '#tokens/utils.js'; +import * as validationErrors from '#validation/errors.js'; describe('tokens/utils', () => { test.prop([testsTokensUtils.tokenSignatureArb])( @@ -127,10 +127,13 @@ describe('tokens/utils', () => { ); test.prop([ testsTokensUtils.signedTokenEncodedArb, - fc.record({ - payload: fc.string(), - signatures: fc.array(fc.string()), - }), + fc.record( + { + payload: fc.string(), + signatures: fc.array(fc.string()), + }, + { noNullPrototype: true }, + ), ])( 'parse signed token', (signedTokenEncodedCorrect, signedTokenEncodedIncorrect) => { diff --git a/tests/tokens/utils.ts b/tests/tokens/utils.ts index 9c07a60e57..0d264b2312 100644 --- a/tests/tokens/utils.ts +++ b/tests/tokens/utils.ts @@ -2,24 +2,27 @@ import type { SignedToken, TokenHeaderSignature, TokenProtectedHeader, -} from '@/tokens/types'; +} from '#tokens/types.js'; import { fc } from '@fast-check/jest'; -import * as tokensUtils from '@/tokens/utils'; -import * as testsKeysUtils from '../keys/utils'; -import * as testsIdsUtils from '../ids/utils'; +import * as testsKeysUtils from '../keys/utils.js'; +import * as testsIdsUtils from '../ids/utils.js'; +import * as tokensUtils from '#tokens/utils.js'; const tokenPayloadArb = fc - .record({ - jti: fc.option(fc.string(), { nil: undefined }), - iat: fc.option(fc.nat(), { nil: undefined }), - nbf: fc.option(fc.nat(), { nil: undefined }), - exp: fc.option(fc.nat(), { nil: undefined }), - iss: fc.option(fc.string(), { nil: undefined }), - sub: fc.option(fc.string(), { nil: undefined }), - aud: fc.option(fc.oneof(fc.string(), fc.array(fc.string())), { - nil: undefined, - }), - }) + .record( + { + jti: fc.option(fc.string(), { nil: undefined }), + iat: fc.option(fc.nat(), { nil: undefined }), + nbf: fc.option(fc.nat(), { nil: undefined }), + exp: fc.option(fc.nat(), { nil: undefined }), + iss: fc.option(fc.string(), { nil: undefined }), + sub: fc.option(fc.string(), { nil: undefined }), + aud: fc.option(fc.oneof(fc.string(), fc.array(fc.string())), { + nil: undefined, + }), + }, + { noNullPrototype: true }, + ) .chain((value) => { return fc.json().chain((json) => { return fc.constant({ @@ -30,13 +33,19 @@ const tokenPayloadArb = fc }); const tokenProtectedHeaderArb = fc .oneof( - fc.record({ - alg: fc.constant('EdDSA'), - kid: testsIdsUtils.nodeIdEncodedArb, - }), - fc.record({ - alg: fc.constant('BLAKE2b'), - }), + fc.record( + { + alg: fc.constant('EdDSA'), + kid: testsIdsUtils.nodeIdEncodedArb, + }, + { noNullPrototype: true }, + ), + fc.record( + { + alg: fc.constant('BLAKE2b'), + }, + { noNullPrototype: true }, + ), ) .chain((value) => { return fc.json().chain((json) => { @@ -52,15 +61,21 @@ const tokenSignatureArb = fc.oneof( testsKeysUtils.macArb, ); -const tokenHeaderSignatureArb = fc.record({ - protected: tokenProtectedHeaderArb, - signature: tokenSignatureArb, -}) as fc.Arbitrary; +const tokenHeaderSignatureArb = fc.record( + { + protected: tokenProtectedHeaderArb, + signature: tokenSignatureArb, + }, + { noNullPrototype: true }, +) as fc.Arbitrary; -const signedTokenArb = fc.record({ - payload: tokenPayloadArb, - signatures: fc.array(tokenHeaderSignatureArb), -}) as fc.Arbitrary; +const signedTokenArb = fc.record( + { + payload: tokenPayloadArb, + signatures: fc.array(tokenHeaderSignatureArb), + }, + { noNullPrototype: true }, +) as fc.Arbitrary; const tokenPayloadEncodedArb = tokenPayloadArb.map( tokensUtils.generateTokenPayload, diff --git a/tests/utils.test.ts b/tests/utils.test.ts index a4de7648b0..f7c6ccb7c6 100644 --- a/tests/utils.test.ts +++ b/tests/utils.test.ts @@ -1,7 +1,7 @@ -import os from 'os'; -import path from 'path'; +import os from 'node:os'; +import path from 'node:path'; import process from 'process'; -import * as utils from '@/utils'; +import * as utils from '#utils/index.js'; describe('utils', () => { test('getting default node path', () => { diff --git a/tests/utils/exec.ts b/tests/utils/exec.ts index d3236f2148..3853d99f6c 100644 --- a/tests/utils/exec.ts +++ b/tests/utils/exec.ts @@ -1,9 +1,9 @@ -import type { ChildProcess } from 'child_process'; -import type ErrorPolykey from '@/ErrorPolykey'; -import childProcess from 'child_process'; -import path from 'path'; -import process from 'process'; -import readline from 'readline'; +import type { ChildProcess } from 'node:child_process'; +import type ErrorPolykey from '#ErrorPolykey.js'; +import childProcess from 'node:child_process'; +import path from 'node:path'; +import process from 'node:process'; +import readline from 'node:readline'; import Logger from '@matrixai/logger'; type ExecOpts = { diff --git a/tests/utils/fastCheck.ts b/tests/utils/fastCheck.ts index c2b6168db0..e2fac06fc7 100644 --- a/tests/utils/fastCheck.ts +++ b/tests/utils/fastCheck.ts @@ -1,6 +1,6 @@ import type { Arbitrary } from 'fast-check'; import { fc } from '@fast-check/jest'; -import * as utils from '@/utils'; +import * as utils from '#utils/index.js'; class SleepCommand implements fc.AsyncCommand { constructor(public readonly ms: number) {} @@ -30,10 +30,11 @@ const scheduleCall = (s: fc.Scheduler, f: () => Promise) => * Creates an ASCII file name */ const fileNameArb = () => - fc - .stringMatching(/^[^<>.:"/\\|?* ]{2,10}$/) - .filter((name) => name.trim().length > 0 && name !== '__proto__') - .noShrink(); + fc.noShrink( + fc + .stringMatching(/^[^<>.:"/\\|?* ]{2,10}$/) + .filter((name) => name.trim().length > 0 && name !== '__proto__'), + ); /** * Creates an array with the file name arbitrary, then returns a tuple @@ -62,10 +63,9 @@ const fileNameLengthSampleArb = ( * Creates a valid ASCII vault name */ const vaultNameArb = () => - fc - .stringMatching(/^[:\\]{6,10}$/) - .map((value) => `vault-${value}`) - .noShrink(); + fc.noShrink( + fc.stringMatching(/^[:\\]{6,10}$/).map((value) => `vault-${value}`), + ); export { SleepCommand, diff --git a/tests/utils/index.ts b/tests/utils/index.ts index 1cf26f1b0e..9760d7b76c 100644 --- a/tests/utils/index.ts +++ b/tests/utils/index.ts @@ -1,4 +1,4 @@ -export * from './utils'; -export * from './exec'; -export * from './fastCheck'; -export * from './tls'; +export * from './utils.js'; +export * from './exec.js'; +export * from './fastCheck.js'; +export * from './tls.js'; diff --git a/tests/utils/ratelimiter/RateLimiter.test.ts b/tests/utils/ratelimiter/RateLimiter.test.ts index c4a01646d0..007fea04df 100644 --- a/tests/utils/ratelimiter/RateLimiter.test.ts +++ b/tests/utils/ratelimiter/RateLimiter.test.ts @@ -1,5 +1,5 @@ -import RateLimiter from '@/utils/ratelimiter/RateLimiter'; -import { sleep } from '@/utils'; +import RateLimiter from '#utils/ratelimiter/RateLimiter.js'; +import { sleep } from '#utils/index.js'; describe(`${RateLimiter.name}`, () => { let rateLimiter: RateLimiter; diff --git a/tests/utils/tls.ts b/tests/utils/tls.ts index 58470655b4..eea2e07058 100644 --- a/tests/utils/tls.ts +++ b/tests/utils/tls.ts @@ -5,9 +5,9 @@ import type { CertificatePEMChain, KeyPair, PrivateKeyPEM, -} from '@/keys/types'; -import type { TLSConfig } from '@/network/types'; -import * as keysUtils from '@/keys/utils'; +} from '#keys/types.js'; +import type { TLSConfig } from '#network/types.js'; +import * as keysUtils from '#keys/utils/index.js'; async function createTLSConfig( keyPair: KeyPair, diff --git a/tests/utils/utils.ts b/tests/utils/utils.ts index 9916a2b1b3..9d243586be 100644 --- a/tests/utils/utils.ts +++ b/tests/utils/utils.ts @@ -1,8 +1,8 @@ -import type { NodeId } from '@/ids/types'; +import type { NodeId } from '#ids/types.js'; import { IdInternal } from '@matrixai/id'; -import * as keysUtils from '@/keys/utils'; -import { promise } from '@/utils'; -import * as networkErrors from '@/network/errors'; +import * as keysUtils from '#keys/utils/index.js'; +import { promise } from '#utils/index.js'; +import * as networkErrors from '#network/errors.js'; function generateRandomNodeId(): NodeId { const random = keysUtils.getRandomBytes(16).toString('hex'); @@ -148,6 +148,16 @@ function promFromEvents< const testNetworkName = 'testNetwork'; +async function generatorToArray( + generator: AsyncGenerator, +): Promise> { + const results: Array = []; + for await (const value of generator) { + results.push(value); + } + return results; +} + export { generateRandomNodeId, expectRemoteError, @@ -157,4 +167,5 @@ export { promFromEvent, promFromEvents, testNetworkName, + generatorToArray, }; diff --git a/tests/validation/index.test.ts b/tests/validation/index.test.ts index 7baed6d5bd..cfd15cf2fa 100644 --- a/tests/validation/index.test.ts +++ b/tests/validation/index.test.ts @@ -2,7 +2,7 @@ import { validate, validateSync, errors as validationErrors, -} from '@/validation'; +} from '#validation/index.js'; describe('validation/index', () => { test('validate primitives', async () => { diff --git a/tests/vaults/VaultInternal.test.ts b/tests/vaults/VaultInternal.test.ts index aacc9c7c9c..ac595e8329 100644 --- a/tests/vaults/VaultInternal.test.ts +++ b/tests/vaults/VaultInternal.test.ts @@ -1,25 +1,24 @@ import type { ContextTimed } from '@matrixai/contexts'; -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; import type { LevelPath } from '@matrixai/db'; -import type { Key } from '@/keys/types'; -import type KeyRing from '@/keys/KeyRing'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; +import type KeyRing from '#keys/KeyRing.js'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs'; import git from 'isomorphic-git'; import { EncryptedFS } from 'encryptedfs'; import { DB } from '@matrixai/db'; import { withF } from '@matrixai/resources'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import { tagLast } from '@/vaults/types'; -import { sleep } from '@/utils'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultsErrors from '@/vaults/errors'; -import * as keysUtils from '@/keys/utils'; -import * as vaultsUtils from '@/vaults/utils'; -import * as utils from '@/utils'; -import * as nodeTestUtils from '../nodes/utils'; +import * as nodeTestUtils from '../nodes/utils.js'; +import { tagLast } from '#vaults/types.js'; +import { sleep } from '#utils/index.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import { polykeyWorkerManifest } from '#workers/index.js'; describe('VaultInternal', () => { const logger = new Logger('Vault', LogLevel.WARN, [new StreamHandler()]); @@ -69,20 +68,7 @@ describe('VaultInternal', () => { db = await DB.createDB({ crypto: { key: keysUtils.generateKey(), - ops: { - encrypt: async (key, plainText) => { - return keysUtils.encryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(plainText), - ); - }, - decrypt: async (key, cipherText) => { - return keysUtils.decryptWithKey( - utils.bufferWrap(key) as Key, - utils.bufferWrap(cipherText), - ); - }, - }, + ops: polykeyWorkerManifest, }, dbPath: path.join(dataDir, 'db'), fs: fs, diff --git a/tests/vaults/VaultManager.test.ts b/tests/vaults/VaultManager.test.ts index fb5645bbd8..5de1800924 100644 --- a/tests/vaults/VaultManager.test.ts +++ b/tests/vaults/VaultManager.test.ts @@ -1,44 +1,45 @@ import type { ContextTimed } from '@matrixai/contexts'; -import type { NodeId } from '@/ids/types'; +import type { NodeId } from '#ids/types.js'; import type { VaultAction, VaultId, VaultIdString, VaultName, -} from '@/vaults/types'; -import type NotificationsManager from '@/notifications/NotificationsManager'; -import type { Host } from '@/network/types'; -import type { Sigchain } from '@/sigchain'; -import type { AgentServerManifest } from '@/nodes/agent/handlers'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +} from '#vaults/types.js'; +import type NotificationsManager from '#notifications/NotificationsManager.js'; +import type { Host } from '#network/types.js'; +import type { Sigchain } from '#sigchain/index.js'; +import type { AgentServerManifest } from '#nodes/agent/handlers/index.js'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { jest } from '@jest/globals'; import git from 'isomorphic-git'; import { IdInternal } from '@matrixai/id'; import { DB } from '@matrixai/db'; import { destroyed, running } from '@matrixai/async-init'; import { RWLockWriter } from '@matrixai/async-locks'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import TaskManager from '@/tasks/TaskManager'; -import ACL from '@/acl/ACL'; -import GestaltGraph from '@/gestalts/GestaltGraph'; -import NodeManager from '@/nodes/NodeManager'; -import NodeConnectionManager from '@/nodes/NodeConnectionManager'; -import NodesAuthenticateConnection from '@/nodes/agent/handlers/NodesAuthenticateConnection'; -import KeyRing from '@/keys/KeyRing'; -import PolykeyAgent from '@/PolykeyAgent'; -import VaultManager from '@/vaults/VaultManager'; -import NodeGraph from '@/nodes/NodeGraph'; -import VaultInternal from '@/vaults/VaultInternal'; -import { sleep } from '@/utils'; -import * as keysUtils from '@/keys/utils'; -import * as vaultsErrors from '@/vaults/errors'; -import * as vaultsUtils from '@/vaults/utils'; -import * as nodesUtils from '@/nodes/utils'; -import * as nodeTestUtils from '../nodes/utils'; -import * as testUtils from '../utils'; -import * as tlsTestsUtils from '../utils/tls'; -import * as testsUtils from '../utils'; +import * as nodeTestUtils from '../nodes/utils.js'; +import * as testUtils from '../utils/index.js'; +import * as tlsTestsUtils from '../utils/tls.js'; +import * as testsUtils from '../utils/index.js'; +import TaskManager from '#tasks/TaskManager.js'; +import ACL from '#acl/ACL.js'; +import GestaltGraph from '#gestalts/GestaltGraph.js'; +import NodeManager from '#nodes/NodeManager.js'; +import NodeConnectionManager from '#nodes/NodeConnectionManager.js'; +import NodesAuthenticateConnection from '#nodes/agent/handlers/NodesAuthenticateConnection.js'; +import KeyRing from '#keys/KeyRing.js'; +import PolykeyAgent from '#PolykeyAgent.js'; +import VaultManager from '#vaults/VaultManager.js'; +import NodeGraph from '#nodes/NodeGraph.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import { sleep } from '#utils/index.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as nodesUtils from '#nodes/utils.js'; describe('VaultManager', () => { const localhost = '127.0.0.1'; diff --git a/tests/vaults/VaultOps/addSecret.test.ts b/tests/vaults/VaultOps/addSecret.test.ts index 462eb6cbc3..e98936f4a8 100644 --- a/tests/vaults/VaultOps/addSecret.test.ts +++ b/tests/vaults/VaultOps/addSecret.test.ts @@ -1,20 +1,20 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsErrors from '@/vaults/errors'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; -import * as testVaultsUtils from '../utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import * as testVaultsUtils from '../utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('addSecret', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/addSecretDirectory.test.ts b/tests/vaults/VaultOps/addSecretDirectory.test.ts index f7a8ff757d..da18747df2 100644 --- a/tests/vaults/VaultOps/addSecretDirectory.test.ts +++ b/tests/vaults/VaultOps/addSecretDirectory.test.ts @@ -1,18 +1,18 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('addSecretDirectory', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/deleteSecret.test.ts b/tests/vaults/VaultOps/deleteSecret.test.ts index f2061ca72e..d9b43932d9 100644 --- a/tests/vaults/VaultOps/deleteSecret.test.ts +++ b/tests/vaults/VaultOps/deleteSecret.test.ts @@ -1,20 +1,20 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsErrors from '@/vaults/errors'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; -import * as testVaultsUtils from '../utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import * as testVaultsUtils from '../utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('deleteSecret', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/getSecret.test.ts b/tests/vaults/VaultOps/getSecret.test.ts index bca1f1fd7e..7be3d16b5f 100644 --- a/tests/vaults/VaultOps/getSecret.test.ts +++ b/tests/vaults/VaultOps/getSecret.test.ts @@ -1,20 +1,20 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsErrors from '@/vaults/errors'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; -import * as testVaultsUtils from '../utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import * as testVaultsUtils from '../utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('getSecret', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/listSecrets.test.ts b/tests/vaults/VaultOps/listSecrets.test.ts index 56f3aff0c4..71eee1f016 100644 --- a/tests/vaults/VaultOps/listSecrets.test.ts +++ b/tests/vaults/VaultOps/listSecrets.test.ts @@ -1,19 +1,19 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; -import * as testVaultsUtils from '../utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import * as testVaultsUtils from '../utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('listSecrets', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/mkdir.test.ts b/tests/vaults/VaultOps/mkdir.test.ts index ea97be4921..289eebda57 100644 --- a/tests/vaults/VaultOps/mkdir.test.ts +++ b/tests/vaults/VaultOps/mkdir.test.ts @@ -1,20 +1,20 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsUtils from '@/vaults/utils'; -import * as vaultsErrors from '@/vaults/errors'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; -import * as testVaultsUtils from '../utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import * as testVaultsUtils from '../utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('mkdir', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/renameSecret.test.ts b/tests/vaults/VaultOps/renameSecret.test.ts index adb8c43bb1..df3c76826f 100644 --- a/tests/vaults/VaultOps/renameSecret.test.ts +++ b/tests/vaults/VaultOps/renameSecret.test.ts @@ -1,20 +1,20 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsErrors from '@/vaults/errors'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; -import * as testVaultsUtils from '../utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import * as testVaultsUtils from '../utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('renameSecret', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/statSecret.test.ts b/tests/vaults/VaultOps/statSecret.test.ts index 89c2165a0f..9b0cd934ba 100644 --- a/tests/vaults/VaultOps/statSecret.test.ts +++ b/tests/vaults/VaultOps/statSecret.test.ts @@ -1,20 +1,20 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS, Stat } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsErrors from '@/vaults/errors'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; -import * as testVaultsUtils from '../utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import * as testVaultsUtils from '../utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('statSecret', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/touchSecret.test.ts b/tests/vaults/VaultOps/touchSecret.test.ts index 79d3c8c696..55cec86065 100644 --- a/tests/vaults/VaultOps/touchSecret.test.ts +++ b/tests/vaults/VaultOps/touchSecret.test.ts @@ -1,20 +1,20 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsErrors from '@/vaults/errors'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; -import * as testVaultsUtils from '../utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import * as testVaultsUtils from '../utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsErrors from '#vaults/errors.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('touchSecret', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/VaultOps/writeSecret.test.ts b/tests/vaults/VaultOps/writeSecret.test.ts index c18f52253b..be14707525 100644 --- a/tests/vaults/VaultOps/writeSecret.test.ts +++ b/tests/vaults/VaultOps/writeSecret.test.ts @@ -1,18 +1,18 @@ -import type { VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults/Vault'; -import type KeyRing from '@/keys/KeyRing'; +import type { VaultId } from '#vaults/types.js'; +import type { Vault } from '#vaults/Vault.js'; +import type KeyRing from '#keys/KeyRing.js'; import type { LevelPath } from '@matrixai/db'; -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { DB } from '@matrixai/db'; -import VaultInternal from '@/vaults/VaultInternal'; -import * as vaultOps from '@/vaults/VaultOps'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as testNodesUtils from '../../nodes/utils'; +import * as testNodesUtils from '../../nodes/utils.js'; +import VaultInternal from '#vaults/VaultInternal.js'; +import * as vaultOps from '#vaults/VaultOps.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('writeSecret', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); diff --git a/tests/vaults/fileTree.test.ts b/tests/vaults/fileTree.test.ts index 62cd2a288c..be1d6f8de4 100644 --- a/tests/vaults/fileTree.test.ts +++ b/tests/vaults/fileTree.test.ts @@ -1,21 +1,26 @@ -import type { ContentNode, FileTree, TreeNode, VaultId } from '@/vaults/types'; -import type { Vault } from '@/vaults'; -import type KeyRing from '../../src/keys/KeyRing'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import type { + ContentNode, + FileTree, + TreeNode, + VaultId, +} from '#vaults/types.js'; +import type { Vault } from '#vaults/index.js'; +import type KeyRing from '#keys/KeyRing.js'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import { ReadableStream } from 'stream/web'; import { test } from '@fast-check/jest'; import fc from 'fast-check'; import { EncryptedFS } from 'encryptedfs'; import { DB, type LevelPath } from '@matrixai/db'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import * as fileTree from '@/vaults/fileTree'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; -import * as vaultsTestUtils from './utils'; -import VaultInternal from '../../src/vaults/VaultInternal'; -import * as testNodesUtils from '../nodes/utils'; +import * as vaultsTestUtils from './utils.js'; +import * as testNodesUtils from '../nodes/utils.js'; +import * as fileTree from '#vaults/fileTree.js'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import VaultInternal from '#vaults/VaultInternal.js'; describe('fileTree', () => { const logger = new Logger('VaultOps', LogLevel.WARN, [new StreamHandler()]); @@ -702,10 +707,9 @@ describe('fileTree', () => { }); test.prop( [ - fc - .uint8Array({ size: 'large' }) - .noShrink() - .map((v) => Buffer.from(v)), + fc.noShrink( + fc.uint8Array({ size: 'large' }).map((v) => Buffer.from(v)), + ), ], { numRuns: 20 }, )('handles invalid data', async (data) => { diff --git a/tests/vaults/utils.test.ts b/tests/vaults/utils.test.ts index e0725455d1..d2c57312ea 100644 --- a/tests/vaults/utils.test.ts +++ b/tests/vaults/utils.test.ts @@ -1,12 +1,12 @@ -import type { VaultId } from '@/vaults/types'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; +import type { VaultId } from '#vaults/types.js'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import { EncryptedFS } from 'encryptedfs'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; import { IdRandom } from '@matrixai/id'; -import * as vaultsUtils from '@/vaults/utils'; -import * as keysUtils from '@/keys/utils'; +import * as vaultsUtils from '#vaults/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; describe('Vaults utils', () => { const logger = new Logger('Vaults utils tests', LogLevel.WARN, [ diff --git a/tests/vaults/utils.ts b/tests/vaults/utils.ts index 717c8215dd..962a7b677d 100644 --- a/tests/vaults/utils.ts +++ b/tests/vaults/utils.ts @@ -1,34 +1,41 @@ -import type { Vault } from '@/vaults'; +import type { Vault } from '#vaults/index.js'; import type { VaultActions, HeaderContent, HeaderGeneric, -} from '@/vaults/types'; +} from '#vaults/types.js'; import { TransformStream } from 'stream/web'; -import path from 'path'; +import path from 'node:path'; import fc from 'fast-check'; -import { vaultActions } from '@/vaults/types'; -import { HeaderType } from '@/vaults/fileTree'; -import * as vaultsUtils from '@/vaults/utils'; +import { vaultActions } from '#vaults/types.js'; +import { HeaderType } from '#vaults/fileTree.js'; +import * as vaultsUtils from '#vaults/utils.js'; const vaultActionArb = fc.constantFrom(...vaultActions); const vaultActionsArb = fc.dictionary(vaultActionArb, fc.constant(null), { minKeys: 0, maxKeys: vaultActions.length, + noNullPrototype: true, }) as fc.Arbitrary; const headerTypeArb: fc.Arbitrary = fc.oneof( fc.constant(HeaderType.CONTENT), fc.constant(HeaderType.TREE), ); -const headerGenericArb = fc.record({ - type: headerTypeArb, -}); -const headerContentArb = fc.record({ - dataSize: fc.bigUint({ max: 2n ** 63n }), - iNode: fc.nat(), -}); +const headerGenericArb = fc.record( + { + type: headerTypeArb, + }, + { noNullPrototype: true }, +); +const headerContentArb = fc.record( + { + dataSize: fc.bigInt({ max: 2n ** 63n, min: BigInt(0) }), + iNode: fc.nat(), + }, + { noNullPrototype: true }, +); /** * This is used to convert regular chunks into randomly sized chunks based on diff --git a/tests/workers/polykeyWorker.test.ts b/tests/workers/polykeyWorker.test.ts index 59bf203d95..cdc3f2e8f3 100644 --- a/tests/workers/polykeyWorker.test.ts +++ b/tests/workers/polykeyWorker.test.ts @@ -1,13 +1,14 @@ -import type { PolykeyWorkerManagerInterface } from '@/workers/types'; +import type { PolykeyWorkerManager } from '#workers/types.js'; import Logger, { LogLevel, StreamHandler } from '@matrixai/logger'; -import { createWorkerManager } from '@/workers/utils'; -import * as keysUtils from '@/keys/utils'; +import { createWorkerManager } from '#workers/utils.js'; +import * as keysUtils from '#keys/utils/index.js'; +import * as workersUtils from '#workers/utils.js'; describe('Polykey worker', () => { const logger = new Logger('PolyKey Worker Test', LogLevel.WARN, [ new StreamHandler(), ]); - let workerManager: PolykeyWorkerManagerInterface; + let workerManager: PolykeyWorkerManager; beforeAll(async () => { workerManager = await createWorkerManager({ cores: 1, @@ -18,41 +19,64 @@ describe('Polykey worker', () => { await workerManager.destroy(); }); test('hashPassword', async () => { - await workerManager.call(async (w) => { - await w.hashPassword('password'); - }); + await workerManager.methods.hashPassword({ password: 'password' }); }); test('checkPassword', async () => { - await workerManager.call(async (w) => { - const [hash, salt] = await w.hashPassword('password'); - expect(await w.checkPassword('password', hash, salt)).toBeTrue(); - }); + const { + data: [hash, salt], + } = await workerManager.methods.hashPassword({ password: 'password' }); + const { data: result } = await workerManager.methods.checkPassword( + { + password: 'password', + hash, + salt, + }, + [hash, salt], + ); + expect(result).toBeTrue(); }); test('generateDeterministicKeyPair', async () => { const recoveryCode = keysUtils.generateRecoveryCode(); - await workerManager.call(async (w) => { - await w.generateDeterministicKeyPair(recoveryCode); - }); + await workerManager.methods.generateDeterministicKeyPair({ recoveryCode }); }); test('generateCertificate', async () => { const keyPair = keysUtils.generateKeyPair(); const certId = keysUtils.createCertIdGenerator()(); - await workerManager.call(async (w) => { - await w.generateCertificate({ - certId, - subjectKeyPair: keyPair, - issuerPrivateKey: keyPair.privateKey, + const certIdAB = workersUtils.toArrayBuffer(certId.toBuffer()); + const privateKeyAB = workersUtils.toArrayBuffer(keyPair.privateKey); + const publicKeyAB = workersUtils.toArrayBuffer(keyPair.publicKey); + await workerManager.methods.generateCertificate( + { + certId: certIdAB, + subjectKeyPair: { + privateKey: privateKeyAB, + publicKey: publicKeyAB, + }, + issuerPrivateKey: privateKeyAB, duration: 0, - }); - }); + }, + [certIdAB, privateKeyAB, publicKeyAB], + ); }); test('encrypt, decrypt', async () => { const key = keysUtils.generateKey(); + const keyAB = workersUtils.toArrayBuffer(key); const message = 'HelloWorld!'; - await workerManager.call(async (w) => { - const encrypted = await w.encrypt(key, Buffer.from(message)); - const decrypted = await w.decrypt(key, encrypted); - expect(Buffer.from(decrypted!).toString()).toBe(message); - }); + const plainTextAB = workersUtils.toArrayBuffer(Buffer.from(message)); + const { data: encryptedAB } = await workerManager.methods.encrypt( + { + key: keyAB, + plainText: plainTextAB, + }, + [plainTextAB], + ); + const { data: decryptedAB } = await workerManager.methods.decrypt( + { + key: keyAB, + cipherText: encryptedAB, + }, + [encryptedAB], + ); + expect(workersUtils.fromArrayBuffer(decryptedAB!).toString()).toBe(message); }); }); diff --git a/tsconfig.json b/tsconfig.json index 3d794c9aac..8a3a5d48b8 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,15 +12,14 @@ "esModuleInterop": true, "allowSyntheticDefaultImports": true, "resolveJsonModule": true, - "skipLibCheck": true, - "moduleResolution": "node", - "module": "CommonJS", + "moduleResolution": "NodeNext", + "module": "ESNext", "target": "ES2022", "baseUrl": "./src", "paths": { - "@": ["index"], - "@/*": ["*"] + "#*": ["*"] }, + "skipLibCheck": true, "noEmit": true }, "include": [ @@ -31,7 +30,7 @@ "./benches/**/*" ], "ts-node": { - "require": ["tsconfig-paths/register"], + "esm": true, "transpileOnly": true, "swc": true }