Files
docx-js/src/patcher/patch-detector.ts
zarwan-translate 962795743c feat: Add ability to detect patches which are present in a file (#2633)
* feat: Add ability to detect patches which are present in a file

* chore: export patchDetector function

* fix: Make sure we don't attempt to call toJson on binary content

---------

Co-authored-by: Christopher Fox <cfox@homebound.com>
2024-05-22 03:05:48 +01:00

31 lines
1.0 KiB
TypeScript

import JSZip from "jszip";
import { toJson } from "./util";
import { traverse } from "./traverser";
import { InputDataType } from "./from-docx";
type PatchDetectorOptions = {
readonly data: InputDataType;
};
/** Detects which patches are needed/present in a template */
export const patchDetector = async ({ data }: PatchDetectorOptions): Promise<readonly string[]> => {
const zipContent = await JSZip.loadAsync(data);
const patches = new Set<string>();
for (const [key, value] of Object.entries(zipContent.files)) {
if (!key.endsWith(".xml") && !key.endsWith(".rels")) {
continue;
}
if (key.startsWith("word/") && !key.endsWith(".xml.rels")) {
const json = toJson(await value.async("text"));
traverse(json).forEach((p) => findPatchKeys(p.text).forEach((patch) => patches.add(patch)));
}
}
return Array.from(patches);
};
const findPatchKeys = (text: string): readonly string[] => {
const pattern = /(?<=\{\{).+?(?=\}\})/gs;
return text.match(pattern) ?? [];
};