Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix ESLint, fix the issues reported by the linter
Adorian Doran9b53e87de679
diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsxindex 9558defb2a..5d5f9c47cc 100644--- a/apps/client/src/widgets/type_widgets/options/backup.tsx+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx@@ -165,7 +165,7 @@ export function BackupOptions() {}}, []);- useEffect(() => { refreshPassphrase(); }, [refreshPassphrase]);+ useEffect(() => { void refreshPassphrase(); }, [refreshPassphrase]);async function storePassword(password: string) {const result = await window.electronApi?.backupPassphrase.set(password);diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex 76ccc7507d..4e076e6970 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -616,30 +616,32 @@ describe("preload script", () => {it("getStatus invokes the corresponding IPC channel", async () => {await backupPassphrase().getStatus();- expect(ipcRendererInvoked).toContainEqual(- { channel: "backup-passphrase-status",- args: [] }- );+ expect(ipcRendererInvoked).toContainEqual({+ channel: "backup-passphrase-status",+ args: []+ });});it("set invokes the corresponding IPC channel", async () => {await backupPassphrase().set("hunter2");- expect(ipcRendererInvoked).toContainEqual(- { channel: "backup-passphrase-set",- args: ["hunter2"] }- );+ expect(ipcRendererInvoked).toContainEqual({+ channel: "backup-passphrase-set",+ args: [ "hunter2" ]+ });});it("clear invokes the corresponding IPC channel", async () => {await backupPassphrase().clear();- expect(ipcRendererInvoked).toContainEqual(- { channel: "backup-passphrase-clear",- args: [] }- );+ expect(ipcRendererInvoked).toContainEqual({+ channel: "backup-passphrase-clear",+ args: []+ });});it("exposes no way to read the passphrase back", () => {- expect(Object.keys(backupPassphrase()).sort()).toEqual(["clear", "getStatus", "set"]);+ const exposed = Object.keys(backupPassphrase()).sort();++ expect(exposed).toEqual([ "clear", "getStatus", "set" ]);});});diff --git a/apps/desktop/src/services/backup_passphrase.spec.ts b/apps/desktop/src/services/backup_passphrase.spec.tsindex ee2350d7a3..4ad6919672 100644--- a/apps/desktop/src/services/backup_passphrase.spec.ts+++ b/apps/desktop/src/services/backup_passphrase.spec.ts@@ -98,7 +98,7 @@ describe("backup passphrase storage", () => {it("stores a passphrase encrypted, and never in the clear", async () => {expect(await passphrase.storeBackupPassphrase("hunter2")).toBe(true);- const stored = [...h.fileStore.values()];+ const stored = [ ...h.fileStore.values() ];expect(stored).toHaveLength(1);expect(stored[0].toString()).not.toContain("hunter2");expect(h.encrypt).toHaveBeenCalledWith("hunter2");@@ -154,8 +154,8 @@ describe("keyring availability", () => {});it.each([- ["the app is not ready yet", () => { h.isReady = false; }],- ["the platform offers no encryption", () => { h.encryptionAvailable = false; }],+ [ "the app is not ready yet", () => { h.isReady = false; } ],+ [ "the platform offers no encryption", () => { h.encryptionAvailable = false; } ],["Linux falls back to the hardcoded-password backend",() => { h.storageBackend = "basic_text"; }@@ -203,7 +203,7 @@ describe("IPC handlers", () => {});it("registers status, set and clear, and nothing that reads the passphrase back", () => {- expect([...h.handlers.keys()].sort()).toEqual([+ expect([ ...h.handlers.keys() ].sort()).toEqual(["backup-passphrase-clear","backup-passphrase-set","backup-passphrase-status"@@ -220,8 +220,8 @@ describe("IPC handlers", () => {});it.each([- ["set", ["backup-passphrase-set", "hunter2"]],- ["clear", ["backup-passphrase-clear"]]+ [ "set", [ "backup-passphrase-set", "hunter2" ] ],+ [ "clear", [ "backup-passphrase-clear" ] ]] as ConfirmCase[])("asks the OS before it %ss, with no escape from asking", async (_label,calldiff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.tsindex fbe0d14c3e..86f2c0a13b 100644--- a/apps/server/src/backup_provider.spec.ts+++ b/apps/server/src/backup_provider.spec.ts@@ -1,12 +1,11 @@+import { readBackupContainer } from "@triliumnext/backup-container";import type { OptionNames } from "@triliumnext/commons";import { getLog, getSql, ws } from "@triliumnext/core";import fs from "fs";import os from "os";import path from "path";-import { afterAll, afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";--import { readBackupContainer } from "@triliumnext/backup-container";import { Readable, Writable } from "stream";+import { afterAll, afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";import ServerBackupService, { type ServerBackupConfig } from "./backup_provider.js";import dataDir from "./services/data_dir.js";@@ -88,7 +87,7 @@ describe("ServerBackupService: backup location", () => {expect(service.getBackupFolderPath()).toBe(CUSTOM_DIR);expect(await service.backupNow("daily")).toBe(path.join(CUSTOM_DIR, "backup-daily.db"));- expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.db"]);+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([ "backup-daily.db" ]);expect(backupNamesIn(DEFAULT_DIR)).toEqual([]);});@@ -117,7 +116,8 @@ describe("ServerBackupService: backup location", () => {expect(service.getBackupFolderPath()).toBe(DEFAULT_DIR);await service.backupNow("now");// Listed once, not once per configured directory.- expect((await service.getExistingBackups()).map((b) => b.fileName)).toEqual(["backup-now.db"]);+ const listed = await service.getExistingBackups();+ expect(listed.map((b) => b.fileName)).toEqual([ "backup-now.db" ]);});});@@ -135,7 +135,7 @@ describe("ServerBackupService: backup format", () => {}});- await readBackupContainer(Readable.from([fs.readFileSync(filePath)]), sink, {+ await readBackupContainer(Readable.from([ fs.readFileSync(filePath) ]), sink, {passphrase,// The stub standing in for the online backup is not a real database.requireSqliteHeader: false@@ -148,7 +148,7 @@ describe("ServerBackupService: backup format", () => {const backupFile = await desktopService(CUSTOM_DIR).backupNow("now");expect(backupFile).toBe(path.join(CUSTOM_DIR, "backup-now.db"));- expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-now.db"]);+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([ "backup-now.db" ]);});it("writes a compressed container, which unwraps to the database again", async () => {@@ -189,13 +189,13 @@ describe("ServerBackupService: backup format", () => {it("keeps one file per backup name, whichever format it was last written in", async () => {await desktopService(CUSTOM_DIR).backupNow("daily");- expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.db"]);+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([ "backup-daily.db" ]);await desktopService(CUSTOM_DIR, { backupEnableCompression: "true" }).backupNow("daily");- expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.tnbackup"]);+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([ "backup-daily.tnbackup" ]);await desktopService(CUSTOM_DIR).backupNow("daily");- expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.db"]);+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([ "backup-daily.db" ]);});it("leaves no snapshot behind in the data directory", async () => {@@ -228,8 +228,8 @@ describe("ServerBackupService: backup format", () => {const backups = await desktopService("").getExistingBackups();expect(backups.map((b) => b.fileName).sort()).toEqual(- ["backup-daily.tnbackup",- "backup-weekly.db"]+ [ "backup-daily.tnbackup",+ "backup-weekly.db" ]);});@@ -241,16 +241,16 @@ describe("ServerBackupService: backup format", () => {// Listed by a service with both switched off: a backup keeps the shape it was written in.const listed = await desktopService("").getExistingBackups();- const byName = new Map(listed.map((b) => [b.fileName, b]));+ const byName = new Map(listed.map((b) => [ b.fileName, b ]));expect(byName.get("backup-compressed.tnbackup")).toMatchObject({ compressed: true,- encrypted: false,- plaintextSize: "db-bytes".length }+ encrypted: false,+ plaintextSize: "db-bytes".length });expect(byName.get("backup-encrypted.tnbackup")).toMatchObject({ compressed: false,- encrypted: true }+ encrypted: true });// A plain copy states nothing of the sort: its own size is the whole story.expect(byName.get("backup-plain.db")).not.toHaveProperty("compressed");@@ -266,7 +266,7 @@ describe("ServerBackupService: backup format", () => {const backups = await desktopService("").getExistingBackups();- expect(backups.map((b) => b.fileName)).toEqual(["backup-damaged.tnbackup"]);+ expect(backups.map((b) => b.fileName)).toEqual([ "backup-damaged.tnbackup" ]);expect(backups[0]).not.toHaveProperty("compressed");expect(backups[0]).not.toHaveProperty("encrypted");});@@ -292,7 +292,7 @@ describe("ServerBackupService: when the backup passphrase cannot be read", () =>expect(ws.sendMessageToAllClients).toHaveBeenCalledWith(expect.objectContaining({ type: "toast",- message: expect.stringContaining("not encrypted") }+ message: expect.stringContaining("not encrypted") }));});@@ -312,7 +312,7 @@ describe("ServerBackupService: when the backup passphrase cannot be read", () =>it("says nothing and encrypts nothing when encryption was never asked for", async () => {await desktopService(CUSTOM_DIR, {}, noPassphrase).backupNow("daily");- expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.db"]);+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([ "backup-daily.db" ]);expect(ws.sendMessageToAllClients).not.toHaveBeenCalled();});@@ -328,7 +328,7 @@ describe("ServerBackupService: fallback when the custom directory cannot be writcopyDatabase.mockRejectedValueOnce(new Error("ENOSPC: no space left on device"));expect(await desktopService(CUSTOM_DIR).backupNow("daily")).toBe(path.join(DEFAULT_DIR, "backup-daily.db"));- expect(backupNamesIn(DEFAULT_DIR)).toEqual(["backup-daily.db"]);+ expect(backupNamesIn(DEFAULT_DIR)).toEqual([ "backup-daily.db" ]);expect(ws.sendMessageToAllClients).toHaveBeenCalledWith(expect.objectContaining({@@ -358,7 +358,7 @@ describe("ServerBackupService: fallback when the custom directory cannot be writawait desktopService(CUSTOM_DIR).backupNow("daily");expect(backupNamesIn(CUSTOM_DIR)).toEqual([]);- expect(backupNamesIn(DEFAULT_DIR)).toEqual(["backup-daily.db"]);+ expect(backupNamesIn(DEFAULT_DIR)).toEqual([ "backup-daily.db" ]);});it("propagates the failure when the default directory fails too", async () => {@@ -441,7 +441,7 @@ describe("ServerBackupService.getExistingBackups", () => {const backups = await desktopService("").getExistingBackups();- expect(backups.map((b) => b.fileName)).toEqual(["backup-spec-list.db"]);+ expect(backups.map((b) => b.fileName)).toEqual([ "backup-spec-list.db" ]);expect(backups[0].fileSize).toBe("backup-bytes".length);expect(backups[0].filePath).toBe(path.join(DEFAULT_DIR, "backup-spec-list.db"));expect(backups[0].mtime).toBeInstanceOf(Date);@@ -456,7 +456,10 @@ describe("ServerBackupService.getExistingBackups", () => {const backups = await desktopService(CUSTOM_DIR).getExistingBackups();expect(backups.map((b) => b.filePath).sort()).toEqual(- [path.join(CUSTOM_DIR, "backup-daily.db"), path.join(DEFAULT_DIR, "backup-weekly.db")].sort()+ [+ path.join(CUSTOM_DIR, "backup-daily.db"),+ path.join(DEFAULT_DIR, "backup-weekly.db")+ ].sort());});diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.tsindex e1e2829584..d4eb87e1dc 100644--- a/apps/server/src/backup_provider.ts+++ b/apps/server/src/backup_provider.ts@@ -4,7 +4,7 @@ import {writeBackupContainer} from "@triliumnext/backup-container";import type { DatabaseBackup } from "@triliumnext/commons";-import { BackupOptionsService, BackupService, utils as coreUtils, getLog, sync_mutex as syncMutexService, ws } from "@triliumnext/core";+import { BackupOptionsService, BackupService, getLog, sync_mutex as syncMutexService, utils as coreUtils, ws } from "@triliumnext/core";import fs from "fs";import fsp from "fs/promises";import { t } from "i18next";@@ -47,6 +47,7 @@ interface BackupFormat {}export default class ServerBackupService extends BackupService {+constructor(options: BackupOptionsService, private readonly config: ServerBackupConfig = {}) {super(options);}@@ -173,8 +174,9 @@ export default class ServerBackupService extends BackupService {const customDir = this.getCustomBackupDir();const defaultDir = getDefaultBackupDir();- return customDir ? [customDir, defaultDir] : [defaultDir];+ return customDir ? [ customDir, defaultDir ] : [ defaultDir ];}+}function getDefaultBackupDir(): string {@@ -211,10 +213,10 @@ function listBackupsIn(directory: string): DatabaseBackup[] {return [{ fileName,- filePath,- mtime: stat.mtime,- fileSize: stat.size,- ...describeContainer(filePath, fileName) }+ filePath,+ mtime: stat.mtime,+ fileSize: stat.size,+ ...describeContainer(filePath, fileName) }];});}diff --git a/package.json b/package.jsonindex 2a87946587..eb09b97c95 100644--- a/package.json+++ b/package.json@@ -54,6 +54,7 @@"private": true,"devDependencies": {"@fast-csv/parse": "5.0.7",+ "@stylistic/eslint-plugin": "5.10.0","@playwright/test": "1.62.1","@triliumnext/server": "workspace:*","@types/express": "5.0.6",diff --git a/packages/trilium-backup-container/src/byte-reader.ts b/packages/trilium-backup-container/src/byte-reader.tsindex 1ebadab54f..3ccead8c67 100644--- a/packages/trilium-backup-container/src/byte-reader.ts+++ b/packages/trilium-backup-container/src/byte-reader.ts@@ -4,6 +4,7 @@ import { BackupContainerError } from "./errors.js";/** Pull-based view over a readable stream, so the reader can ask for exact byte counts. */export class ByteReader {+readonly #iterator: AsyncIterator<Buffer>;#pending: Buffer[] = [];#pendingBytes = 0;@@ -26,8 +27,7 @@ export class ByteReader {if (this.#pendingBytes < count) {throw new BackupContainerError("truncated",- `Expected ${count} bytes at offset ${this.#consumed},- found ${this.#pendingBytes}.`+ `Expected ${count} bytes at offset ${this.#consumed}, found ${this.#pendingBytes}.`);}@@ -71,10 +71,11 @@ export class ByteReader {const taken = merged.subarray(0, count);const rest = merged.subarray(count);- this.#pending = rest.length > 0 ? [rest] : [];+ this.#pending = rest.length > 0 ? [ rest ] : [];this.#pendingBytes = rest.length;this.#consumed += count;return taken;}+}diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.tsindex 1fa2720718..247384a36e 100644--- a/packages/trilium-backup-container/src/container.spec.ts+++ b/packages/trilium-backup-container/src/container.spec.ts@@ -32,9 +32,9 @@ const FRAME_OVERHEAD = 4 + TAG_BYTES;describe("round trip", () => {const cases: [string, WriteOptions, number][] = [- ["plain", {}, HEADER_BYTES_PLAIN],- ["compressed", { compress: true }, HEADER_BYTES_PLAIN],- ["encrypted", { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }, HEADER_BYTES_ENCRYPTED],+ [ "plain", {}, HEADER_BYTES_PLAIN ],+ [ "compressed", { compress: true }, HEADER_BYTES_PLAIN ],+ [ "encrypted", { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }, HEADER_BYTES_ENCRYPTED ],["compressed and encrypted",{ compress: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT },@@ -50,7 +50,7 @@ describe("round trip", () => {{ ...options, plaintextSize: database.length });expect(written.result.headerLength).toBe(headerLength);- expect(written.patchedAt).toEqual([headerLength - 32]);+ expect(written.patchedAt).toEqual([ headerLength - 32 ]);const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });expect(read.bytes.equals(database)).toBe(true);@@ -253,7 +253,7 @@ describe("damage and tampering", () => {it("rejects bytes appended after the final frame", async () => {const written = await encrypted();- const extended = Buffer.concat([written.bytes, Buffer.from("extra")]);+ const extended = Buffer.concat([ written.bytes, Buffer.from("extra") ]);expect(await failureOf(extended, { passphrase: PASSPHRASE })).toBe("trailing-data");});@@ -290,14 +290,14 @@ describe("damage and tampering", () => {const written = await writeToBuffer(fakeDatabase(50_000), { compress: true });const damaged = flipByte(written.bytes, HEADER_BYTES_PLAIN + 40);- expect(["damaged-payload", "digest-mismatch"]).toContain(await failureOf(damaged));+ expect([ "damaged-payload", "digest-mismatch" ]).toContain(await failureOf(damaged));});});describe("peeking at a container", () => {it.each([- ["plain", {}, { compressed: false, encrypted: false }],- ["compressed", { compress: true }, { compressed: true, encrypted: false }],+ [ "plain", {}, { compressed: false, encrypted: false } ],+ [ "compressed", { compress: true }, { compressed: true, encrypted: false } ],["encrypted",{ passphrase: PASSPHRASE, scrypt: FAST_SCRYPT },@@ -334,10 +334,10 @@ describe("peeking at a container", () => {});it.each([- ["fewer bytes than a header", Buffer.alloc(20)],- ["something that is not a container", Buffer.alloc(64, 9)],- ["a version it does not know", tamper((bytes) => bytes.writeUInt8(2, 20))],- ["a reserved flag bit", tamper((bytes) => bytes.writeUInt8(0b100, 21))]+ [ "fewer bytes than a header", Buffer.alloc(20) ],+ [ "something that is not a container", Buffer.alloc(64, 9) ],+ [ "a version it does not know", tamper((bytes) => bytes.writeUInt8(2, 20)) ],+ [ "a reserved flag bit", tamper((bytes) => bytes.writeUInt8(0b100, 21)) ]])("answers null for %s, so one bad file cannot derail a listing", (_label, bytes) => {expect(peekBackupContainer(bytes)).toBeNull();});@@ -355,8 +355,8 @@ function tamper(mutate: (bytes: Buffer) => void): Buffer {describe("input that is not a container", () => {it.each([- ["random bytes", Buffer.alloc(300, 9), "not-a-container"],- ["an empty file, which identifies itself as nothing", Buffer.alloc(0), "not-a-container"],+ [ "random bytes", Buffer.alloc(300, 9), "not-a-container" ],+ [ "an empty file, which identifies itself as nothing", Buffer.alloc(0), "not-a-container" ],["a short file whose bytes are not the start of the magic",Buffer.from("Trillium"),@@ -432,15 +432,15 @@ describe("SQLite check", () => {describe("option validation", () => {it("requires patchHeader, since the digest is written after the payload", async () => {const reason = await reasonOf(- writeBackupContainer(Readable.from([fakeDatabase()]), new MemorySink(), {} as never)+ writeBackupContainer(Readable.from([ fakeDatabase() ]), new MemorySink(), {} as never));expect(reason).toBe("invalid-options");});it.each([- ["a negative plaintext size", { plaintextSize: -1 }, "invalid-options"],- ["a fractional plaintext size", { plaintextSize: 1.5 }, "invalid-options"],+ [ "a negative plaintext size", { plaintextSize: -1 }, "invalid-options" ],+ [ "a fractional plaintext size", { plaintextSize: 1.5 }, "invalid-options" ],["scrypt parameters out of bounds",{ passphrase: PASSPHRASE, scrypt: { log2N: 30, r: 8, p: 1 } },@@ -486,7 +486,7 @@ describe("errors", () => {failing._write = (_chunk, _encoding, callback) =>callback(new Error("ENOSPC: no space left on device"));- const read = readBackupContainer(Readable.from([written.bytes]), failing);+ const read = readBackupContainer(Readable.from([ written.bytes ]), failing);await expect(read).rejects.toThrow(/ENOSPC/);});diff --git a/packages/trilium-backup-container/src/crypto.ts b/packages/trilium-backup-container/src/crypto.tsindex acc8bb3ff2..7716621761 100644--- a/packages/trilium-backup-container/src/crypto.ts+++ b/packages/trilium-backup-container/src/crypto.ts@@ -65,11 +65,11 @@ export function sealFrame(plaintext: Buffer): Buffer {const cipher = createCipheriv("aes-256-gcm", key, nonceFor(noncePrefix, counter));- cipher.setAAD(Buffer.concat([aad, lengthField]));+ cipher.setAAD(Buffer.concat([ aad, lengthField ]));- const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);+ const ciphertext = Buffer.concat([ cipher.update(plaintext), cipher.final() ]);- return Buffer.concat([lengthField, ciphertext, cipher.getAuthTag()]);+ return Buffer.concat([ lengthField, ciphertext, cipher.getAuthTag() ]);}/** Opens one frame, throwing `damaged-payload` when the tag does not match. */@@ -84,11 +84,11 @@ export function openFrame(offset: number): Buffer {const decipher = createDecipheriv("aes-256-gcm", key, nonceFor(noncePrefix, counter));- decipher.setAAD(Buffer.concat([aad, lengthField]));+ decipher.setAAD(Buffer.concat([ aad, lengthField ]));decipher.setAuthTag(tag);try {- return Buffer.concat([decipher.update(ciphertext), decipher.final()]);+ return Buffer.concat([ decipher.update(ciphertext), decipher.final() ]);} catch {throw new BackupContainerError("damaged-payload",diff --git a/packages/trilium-backup-container/src/errors.ts b/packages/trilium-backup-container/src/errors.tsindex ff5d055d78..10bc28820a 100644--- a/packages/trilium-backup-container/src/errors.ts+++ b/packages/trilium-backup-container/src/errors.ts@@ -47,6 +47,7 @@ export type BackupContainerErrorReason =/** Error thrown by every entry point in this module. */export class BackupContainerError extends Error {+/** Machine-readable cause, for callers that must map failures to their own messages. */readonly reason: BackupContainerErrorReason;@@ -55,6 +56,7 @@ export class BackupContainerError extends Error {this.name = "BackupContainerError";this.reason = reason;}+}/** Narrowing helper for callers that catch errors from this module. */diff --git a/packages/trilium-backup-container/src/format.spec.ts b/packages/trilium-backup-container/src/format.spec.tsindex 5bac177f11..9b63aba98b 100644--- a/packages/trilium-backup-container/src/format.spec.ts+++ b/packages/trilium-backup-container/src/format.spec.ts@@ -83,7 +83,8 @@ describe("header layout", () => {expect(bytes).toHaveLength(108);expect(bytes.readUInt8(21)).toBe(0b10);expect(bytes.readUInt8(32)).toBe(KDF_SCRYPT);- expect([bytes.readUInt8(33), bytes.readUInt8(34), bytes.readUInt8(35)]).toEqual([17, 8, 1]);+ const params = [ bytes.readUInt8(33), bytes.readUInt8(34), bytes.readUInt8(35) ];+ expect(params).toEqual([ 17, 8, 1 ]);expect(authenticatedHeaderEnd(108)).toBe(60);expect(digestOffset(108)).toBe(76);@@ -124,8 +125,8 @@ describe("fixed header validation", () => {(bytes: Buffer) => bytes.write("Trillium Notes Bckp!", 0, "ascii"),"not-a-container"],- ["version 0", (bytes: Buffer) => bytes.writeUInt8(0, 20), "unsupported-version"],- ["a newer version", (bytes: Buffer) => bytes.writeUInt8(2, 20), "unsupported-version"],+ [ "version 0", (bytes: Buffer) => bytes.writeUInt8(0, 20), "unsupported-version" ],+ [ "a newer version", (bytes: Buffer) => bytes.writeUInt8(2, 20), "unsupported-version" ],["a reserved flag bit",(bytes: Buffer) => bytes.writeUInt8(0b100, 21),@@ -173,11 +174,11 @@ describe("scrypt parameter bounds", () => {});it.each([- ["log2N below the floor", { log2N: 9, r: 8, p: 1 }],- ["log2N above the ceiling", { log2N: 21, r: 8, p: 1 }],- ["r out of range", { log2N: 14, r: 17, p: 1 }],- ["p out of range", { log2N: 14, r: 8, p: 9 }],- ["a non-integer", { log2N: 14.5, r: 8, p: 1 }]+ [ "log2N below the floor", { log2N: 9, r: 8, p: 1 } ],+ [ "log2N above the ceiling", { log2N: 21, r: 8, p: 1 } ],+ [ "r out of range", { log2N: 14, r: 17, p: 1 } ],+ [ "p out of range", { log2N: 14, r: 8, p: 9 } ],+ [ "a non-integer", { log2N: 14.5, r: 8, p: 1 } ]])("rejects %s", (_label, params) => {expect(() => validateScryptParams(params, 1024 ** 3)).toThrow(expect.objectContaining({ reason: "invalid-kdf-params" }) as Error@@ -202,10 +203,10 @@ describe("SQLite header check", () => {});it.each([- ["a page size that is not a power of two", sqliteHead(3000)],- ["a page size below the floor", sqliteHead(256)],- ["output that is too short", sqliteHead(4096).subarray(0, 17)],- ["a foreign magic", Buffer.concat([Buffer.from("Not a database!!"), Buffer.alloc(2)])]+ [ "a page size that is not a power of two", sqliteHead(3000) ],+ [ "a page size below the floor", sqliteHead(256) ],+ [ "output that is too short", sqliteHead(4096).subarray(0, 17) ],+ [ "a foreign magic", Buffer.concat([ Buffer.from("Not a database!!"), Buffer.alloc(2) ]) ]])("rejects %s", (_label, head) => {expect(() => validateSqliteHeader(head)).toThrow(expect.objectContaining({ reason: "not-a-database" }) as Error);diff --git a/packages/trilium-backup-container/src/internals.spec.ts b/packages/trilium-backup-container/src/internals.spec.tsindex 53d233f454..458200007e 100644--- a/packages/trilium-backup-container/src/internals.spec.ts+++ b/packages/trilium-backup-container/src/internals.spec.ts@@ -61,7 +61,7 @@ describe("FrameEncryptor", () => {const encryptor = new FrameEncryptor(randomBytes(32), randomBytes(8), Buffer.alloc(60), 0);const reason = await reasonOf(- pipeline(Readable.from([Buffer.alloc(2 * FRAME_SIZE)]), encryptor, new MemorySink())+ pipeline(Readable.from([ Buffer.alloc(2 * FRAME_SIZE) ]), encryptor, new MemorySink()));expect(reason).toBe("payload-too-large");diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.tsindex 187fb41869..e2479abf1e 100644--- a/packages/trilium-backup-container/src/read.ts+++ b/packages/trilium-backup-container/src/read.ts@@ -154,16 +154,14 @@ export async function readBackupContainer(? readFrames(reader, header, header.encryption, key): readPlainPayload(reader, header);- const stages = header.compressed ? [payload, createGunzip(), guard, output] : [- payload,- guard,- output- ];-try {- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- pipeline's overloads do- // not accept a built array.- await pipeline(stages as any);+ // Spelled out rather than built as an array: the source is an async generator, which only+ // the variadic overloads accept.+ if (header.compressed) {+ await pipeline(payload, createGunzip(), guard, output);+ } else {+ await pipeline(payload, guard, output);+ }} catch (error) {throw translatePipelineError(error);}@@ -199,15 +197,14 @@ async function readHeader(reader: ByteReader, maxHeaderBytes: number): Promise<C}throw new BackupContainerError("truncated",- `File ends after ${fixedBytes.length} bytes,- inside the header.`+ `File ends after ${fixedBytes.length} bytes, inside the header.`);}const fixed = decodeFixedHeader(fixedBytes, maxHeaderBytes);const rest = await reader.readExactly(fixed.headerLength - FIXED_HEADER_BYTES);- return decodeHeader(Buffer.concat([fixedBytes, rest]), maxHeaderBytes);+ return decodeHeader(Buffer.concat([ fixedBytes, rest ]), maxHeaderBytes);}/** Re-encodes the header so the authenticated span comes from the same layout the writer used. */diff --git a/packages/trilium-backup-container/src/streams.ts b/packages/trilium-backup-container/src/streams.tsindex 0d87991476..6110823a51 100644--- a/packages/trilium-backup-container/src/streams.ts+++ b/packages/trilium-backup-container/src/streams.ts@@ -14,6 +14,7 @@ import { sealFrame } from "./crypto.js";/** Passes bytes through untouched while hashing them, so the digest costs no extra pass. */export class DigestTap extends Transform {+readonly #hash: Hash = createHash("sha256");#bytes = 0;@@ -35,6 +36,7 @@ export class DigestTap extends Transform {digest(): Buffer {return this.#hash.digest();}+}/**@@ -45,6 +47,7 @@ export class DigestTap extends Transform {* and outside gzip's CRC, so rewriting it is safe.*/export class GzipHeaderNormaliser extends Transform {+#seen = 0;override _transform(@@ -61,6 +64,7 @@ export class GzipHeaderNormaliser extends Transform {this.#seen += chunk.length;callback(null, chunk);}+}/**@@ -72,6 +76,7 @@ export class GzipHeaderNormaliser extends Transform {* follows.*/export class FrameEncryptor extends Transform {+readonly #frame = Buffer.allocUnsafe(FRAME_SIZE);#filled = 0;#counter = 0;@@ -145,6 +150,7 @@ export class FrameEncryptor extends Transform {return frame;}+}/**@@ -152,6 +158,7 @@ export class FrameEncryptor extends Transform {* SQLite header as soon as enough of it has passed, and counts what was written.*/export class OutputGuard extends Transform {+#written = 0;#head: Buffer[] = [];#headBytes = 0;@@ -211,4 +218,5 @@ export class OutputGuard extends Transform {}callback();}+}diff --git a/packages/trilium-backup-container/src/test-helpers.ts b/packages/trilium-backup-container/src/test-helpers.tsindex 345ac29a04..c610cbeddd 100644--- a/packages/trilium-backup-container/src/test-helpers.ts+++ b/packages/trilium-backup-container/src/test-helpers.ts@@ -16,6 +16,7 @@ import {export const FAST_SCRYPT: ScryptParams = { log2N: 10, r: 8, p: 1 };export class MemorySink extends Writable {+readonly chunks: Buffer[] = [];override _write(@@ -30,6 +31,7 @@ export class MemorySink extends Writable {toBuffer(): Buffer {return Buffer.concat(this.chunks);}+}/** A byte pattern that starts with a valid SQLite header and compresses well. */@@ -49,7 +51,7 @@ export function chunked(data: Buffer, chunkSize: number): Readable {chunks.push(data.subarray(offset, offset + chunkSize));}- return Readable.from(chunks.length > 0 ? chunks : [Buffer.alloc(0)]);+ return Readable.from(chunks.length > 0 ? chunks : [ Buffer.alloc(0) ]);}export interface WrittenContainer {@@ -67,7 +69,7 @@ export async function writeToBuffer(const patches: { offset: number; data: Buffer }[] = [];const result = await writeBackupContainer(- Buffer.isBuffer(input) ? Readable.from([input]) : input,+ Buffer.isBuffer(input) ? Readable.from([ input ]) : input,sink,{...options,@@ -93,7 +95,7 @@ export async function readFromBuffer(options: ReadBackupContainerOptions = {}): Promise<ReadContainer> {const sink = new MemorySink();- const result = await readBackupContainer(Readable.from([container]), sink, options);+ const result = await readBackupContainer(Readable.from([ container ]), sink, options);return { bytes: sink.toBuffer(), result };}diff --git a/packages/trilium-backup-container/src/write.ts b/packages/trilium-backup-container/src/write.tsindex 01b7f26e65..453b45c495 100644--- a/packages/trilium-backup-container/src/write.ts+++ b/packages/trilium-backup-container/src/write.ts@@ -24,6 +24,9 @@ import {} from "./format.js";import { DigestTap, FrameEncryptor, GzipHeaderNormaliser } from "./streams.js";+/** The stream shapes `pipeline` accepts, so a built array needs no cast at the call. */+type PipelineStage = NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream;+/*** Writes `data` at an absolute offset in the destination that is already being streamed to.*@@ -87,8 +90,7 @@ export async function writeBackupContainer(if (!Number.isSafeInteger(plaintextSize) || plaintextSize < 0) {throw new BackupContainerError("invalid-options",- `plaintextSize must be a non-negative safe integer,- got ${plaintextSize}.`+ `plaintextSize must be a non-negative safe integer, got ${plaintextSize}.`);}@@ -136,7 +138,8 @@ export async function writeBackupContainer(// input -> gzip -> frames -> digest -> output, with the stages the flags call for.const digestTap = new DigestTap();- const stages: (Readable | Writable)[] = [input];+ // Typed as the streams `pipeline` accepts, so the built array needs no cast at the call.+ const stages: PipelineStage[] = [ input ];if (compressed) {stages.push(createGzip({ level: options.compressionLevel ?? 6 }),@@ -148,9 +151,7 @@ export async function writeBackupContainer(}stages.push(digestTap, output);- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- pipeline's overloads do not- // accept a built array.- await pipeline(stages as any);+ await pipeline(stages);const digest = digestTap.digest();await options.patchHeader(digestOffset(header.headerLength), digest);diff --git a/packages/trilium-backup-container/vite.config.ts b/packages/trilium-backup-container/vite.config.tsindex fbd6b2ba6e..0c8ddf0a69 100644--- a/packages/trilium-backup-container/vite.config.ts+++ b/packages/trilium-backup-container/vite.config.ts@@ -10,10 +10,10 @@ export default defineConfig(() => ({watch: false,globals: true,environment: "node",- include: ["src/**/*.{test,spec}.ts"],+ include: [ "src/**/*.{test,spec}.ts" ],reporters: ["default",- ["junit", { outputFile: "./test-output/vitest/junit.xml", addFileAttribute: true }]+ [ "junit", { outputFile: "./test-output/vitest/junit.xml", addFileAttribute: true } ]],coverage: {thresholds: {@@ -24,9 +24,9 @@ export default defineConfig(() => ({},reportsDirectory: "./test-output/vitest/coverage",provider: "v8" as const,- include: ["src/**/*.ts"],- exclude: ["**/*.spec.ts", "**/*.d.ts", "src/index.ts", "src/test-helpers.ts"],- reporter: ["text", ["lcov", { projectRoot: resolve(__dirname, "../..") }]]+ include: [ "src/**/*.ts" ],+ exclude: [ "**/*.spec.ts", "**/*.d.ts", "src/index.ts", "src/test-helpers.ts" ],+ reporter: [ "text", [ "lcov", { projectRoot: resolve(__dirname, "../..") } ] ]}}}));diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 065306dcf0..83711eb3a4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -94,6 +94,9 @@ importers:'@playwright/test':specifier: 1.62.1version: 1.62.1+ '@stylistic/eslint-plugin':+ specifier: 5.10.0'@triliumnext/server':specifier: workspace:*version: link:apps/server@@ -4774,6 +4777,12 @@ packages:'@standard-schema/[email protected]':resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}+ '@stylistic/[email protected]':+ resolution: {integrity: sha512-nPK52ZHvot8Ju/0A4ucSX1dcPV2/1clx0kLcH5wDmrE4naKso7TUC/voUyU1O9OTKTrR6MYip6LP0ogEMQ9jPQ==}+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ peerDependencies:+ eslint: ^9.0.0 || ^10.0.0+'@szmarczak/[email protected]':resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==}engines: {node: '>=10'}@@ -7712,6 +7721,10 @@ packages:resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==}engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}+ resolution: {integrity: sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==}+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==}engines: {node: ^20.19.0 || ^22.13.0 || >=24}@@ -7726,6 +7739,10 @@ packages:jiti:optional: true+ resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==}+ engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==}engines: {node: ^20.19.0 || ^22.13.0 || >=24}@@ -16445,6 +16462,16 @@ snapshots:'@standard-schema/[email protected]': {}+ dependencies:+ '@typescript-eslint/types': 8.65.0+ eslint: 10.8.0([email protected])([email protected])+ eslint-visitor-keys: 4.2.1+ espree: 10.4.0+ estraverse: 5.3.0+ picomatch: 4.0.5+'@szmarczak/[email protected]':dependencies:defer-to-connect: 2.0.1@@ -20804,6 +20831,8 @@ snapshots:+ [email protected]: {}+@@ -20843,6 +20872,12 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ acorn: 8.17.0+ acorn-jsx: 5.3.2([email protected])+ eslint-visitor-keys: 4.2.1+dependencies:acorn: 8.17.0