26 lines
1.0 KiB
TypeScript
26 lines
1.0 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
|
|
/** Canonicalize wiki link syntax: [[ a | b ]] -> [[a|b]], [[ a ]] -> [[a]]. */
|
|
export function canonicalizeWikilinks(text: string): string {
|
|
return text.replace(/\[\[\s*([^\]|]+?)\s*(?:\|\s*([^\]]+?)\s*)?\]\]/g, (_m, target: string, display: string | undefined) =>
|
|
display !== undefined ? `[[${target}|${display}]]` : `[[${target}]]`,
|
|
);
|
|
}
|
|
|
|
/** Collapse trailing whitespace per line and runs of blank lines. */
|
|
export function canonicalizeWhitespace(text: string): string {
|
|
return text
|
|
.replace(/[ \t]+\n/g, "\n")
|
|
.replace(/\n{3,}/g, "\n\n")
|
|
.replace(/^\s+|\s+$/g, "");
|
|
}
|
|
|
|
/** Full canonical text form used for hashing and comparison. */
|
|
export function canonicalize(text: string): string {
|
|
return canonicalizeWhitespace(canonicalizeWikilinks(text));
|
|
}
|
|
|
|
/** SHA-256 of the canonical form, used in the foundry: block to detect real content change. */
|
|
export function contentHash(text: string): string {
|
|
return createHash("sha256").update(canonicalize(text)).digest("hex");
|
|
} |