Make hash async

This commit is contained in:
Andras Schmelczer 2026-04-01 22:29:57 +01:00
parent 22dfdc069b
commit 0897f7a545
2 changed files with 12 additions and 8 deletions

View file

@ -1,14 +1,14 @@
import type { DocumentRecord } from "../persistence/database"; import type { DocumentRecord, RelativePath } from "../sync-operations/types";
import { EMPTY_HASH } from "./hash"; import { EMPTY_HASH } from "./hash";
// TODO: make this smarter so that offline files can be renamed & edited at the same time // TODO: make this smarter so that offline files can be renamed & edited at the same time
export function findMatchingFile( export async function findMatchingFile(
contentHash: string, contentHash: string,
candidates: DocumentRecord[] candidates: { path: RelativePath; record: DocumentRecord }[]
): DocumentRecord | undefined { ): Promise<{ path: RelativePath; record: DocumentRecord } | undefined> {
if (contentHash === EMPTY_HASH) { if (contentHash === await EMPTY_HASH) {
return undefined; return undefined;
} }
return candidates.find(({ metadata }) => metadata?.hash === contentHash); return candidates.find(({ record }) => record.hash === contentHash);
} }

View file

@ -1,7 +1,11 @@
export async function hash(content: Uint8Array): Promise<string> { export async function hash(content: Uint8Array): Promise<string> {
const digest = await crypto.subtle.digest("SHA-256", content); const digest = await crypto.subtle.digest(
"SHA-256",
content as Uint8Array<ArrayBuffer>
);
const bytes = new Uint8Array(digest); const bytes = new Uint8Array(digest);
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
} }
export const EMPTY_HASH = await hash(new Uint8Array(0)); // SHA-256 of empty content, computed once at import time
export const EMPTY_HASH: Promise<string> = hash(new Uint8Array());