@mark1russell7/guidebook-library 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package",
2
3
  "name": "@mark1russell7/guidebook-library",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
4
+ "version": "0.1.1",
5
+ "description": "The library add-on of the guidebook: a catalog of offline bundles (size, license, version, checksum), the copies of each bundle on media, and the gaps of the copies of each level.",
6
+ "keywords": [
7
+ "guidebook",
8
+ "offline",
9
+ "library",
10
+ "kiwix",
11
+ "zim",
12
+ "backup",
13
+ "redundancy",
14
+ "checksum",
15
+ "typescript"
16
+ ],
17
+ "homepage": "https://github.com/mark1russell7/guidebook#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/mark1russell7/guidebook/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/mark1russell7/guidebook.git",
24
+ "directory": "packages/library"
25
+ },
26
+ "license": "MIT",
27
+ "author": "Mark Russell (https://github.com/mark1russell7)",
28
+ "type": "module",
29
+ "sideEffects": false,
30
+ "main": "./build/index.js",
31
+ "types": "./build/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./build/index.d.ts",
35
+ "default": "./build/index.js"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "build",
41
+ "src",
42
+ "!src/**/*.test.ts"
43
+ ],
44
+ "engines": {
45
+ "node": ">=22.12"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "dependencies": {
51
+ "@mark1russell7/guidebook": "0.1.1",
52
+ "@mark1russell7/stack-placement": "^0.1.1",
53
+ "@mark1russell7/stack-risk": "^0.2.1",
54
+ "@mark1russell7/system-stack": "^0.1.6",
55
+ "@mark1russell7/text": "^0.0.17"
56
+ },
57
+ "devDependencies": {
58
+ "@mark1russell7/cue": "^2.0.0",
59
+ "@types/node": "^26.6.5",
60
+ "@vitest/coverage-v8": "^5.0.3",
61
+ "typescript": "^7.0.2",
62
+ "vitest": "^5.0.3",
63
+ "tsdown": "^0.23.7"
64
+ },
65
+ "scripts": {
66
+ "build": "tsdown",
67
+ "test": "vitest run",
68
+ "test:watch": "vitest",
69
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
70
+ }
6
71
  }
package/src/check.ts ADDED
@@ -0,0 +1,105 @@
1
+ // The catalog gate: the checks of the bundles and of their copies.
2
+
3
+ import { LICENSES, isWebAddress, permits, timeOf } from "@mark1russell7/guidebook";
4
+ import type { Finding, License, Source, UseContext } from "@mark1russell7/guidebook";
5
+ import { MEDIUM_KINDS } from "./records.ts";
6
+ import type { Bundle, Copy, CopyRule } from "./records.ts";
7
+
8
+ /** The codes of the findings of the catalog gate. */
9
+ export const LIBRARY_CODES = [
10
+ "duplicate-id",
11
+ "empty-title",
12
+ "bad-bytes",
13
+ "bad-sha256",
14
+ "bad-url",
15
+ "unknown-license",
16
+ "missing-source",
17
+ "unknown-level",
18
+ "use-refused",
19
+ "missing-bundle",
20
+ "bad-kind",
21
+ "bad-date",
22
+ "checked-in-future",
23
+ "duplicate-copy",
24
+ ] as const;
25
+
26
+ /** A code of a finding of the catalog gate. */
27
+ export type LibraryCode = (typeof LIBRARY_CODES)[number];
28
+
29
+ /** A finding of the catalog gate, on a bundle or on a copy. */
30
+ export type LibraryFinding = Finding<LibraryCode, "bundle" | "copy">;
31
+
32
+ /** The options of the catalog gate. */
33
+ export interface CatalogOptions extends UseContext {
34
+ /** The sources of the core. With them, a bundle must name a known source. */
35
+ readonly sources?: readonly Source[];
36
+ /** The copy rules. With them, a bundle must name the level of a rule. */
37
+ readonly rules?: readonly CopyRule[];
38
+ }
39
+
40
+ const SHA256 = /^[0-9a-f]{64}$/;
41
+
42
+ function isLicense(value: unknown): value is License {
43
+ return typeof value === "string" && (LICENSES as readonly string[]).includes(value);
44
+ }
45
+
46
+ /**
47
+ * This function gives the findings of the bundles of a catalog.
48
+ * A bundle must have a unique id, a title, a whole positive size and a license that permits a bundle.
49
+ * Its hash and its address must be correct when it has them.
50
+ */
51
+ export function checkCatalog(bundles: readonly Bundle[], options: CatalogOptions = {}): readonly LibraryFinding[] {
52
+ const out: LibraryFinding[] = [];
53
+ const error = (code: LibraryCode, id: string, message: string): void => {
54
+ out.push({ level: "error", code, record: "bundle", id, message });
55
+ };
56
+ const sources = options.sources === undefined ? undefined : new Set(options.sources.map((source) => source.id));
57
+ const levels = options.rules === undefined ? undefined : new Set(options.rules.map((rule) => rule.level));
58
+ const seen = new Set<string>();
59
+ for (const bundle of bundles) {
60
+ if (seen.has(bundle.id)) error("duplicate-id", bundle.id, `Two bundles have the id "${bundle.id}".`);
61
+ seen.add(bundle.id);
62
+ if (bundle.title.trim() === "") error("empty-title", bundle.id, `The bundle "${bundle.id}" has no title.`);
63
+ if (!Number.isSafeInteger(bundle.bytes) || bundle.bytes <= 0) error("bad-bytes", bundle.id, `The bundle "${bundle.id}" has the size ${bundle.bytes}. It needs a whole number of bytes more than 0.`);
64
+ if (bundle.sha256 !== undefined && !SHA256.test(bundle.sha256)) error("bad-sha256", bundle.id, `The bundle "${bundle.id}" has a SHA-256 that is not 64 lower-case hexadecimal digits.`);
65
+ if (bundle.url !== undefined && !isWebAddress(bundle.url)) error("bad-url", bundle.id, `The bundle "${bundle.id}" has the address "${bundle.url}". It needs an address with https: or http:.`);
66
+ if (!isLicense(bundle.license)) {
67
+ error("unknown-license", bundle.id, `The bundle "${bundle.id}" has the unknown license "${String(bundle.license)}".`);
68
+ } else if (!permits(bundle.license, "bundle", options)) {
69
+ error("use-refused", bundle.id, `The license "${bundle.license}" of the bundle "${bundle.id}" does not permit an offline bundle in this guidebook.`);
70
+ }
71
+ if (sources !== undefined && !sources.has(bundle.source)) error("missing-source", bundle.id, `The bundle "${bundle.id}" names the unknown source "${bundle.source}".`);
72
+ if (levels !== undefined && !levels.has(bundle.level)) error("unknown-level", bundle.id, `The bundle "${bundle.id}" has the level "${bundle.level}", and no copy rule has it.`);
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /** The options of the check of the copies. */
78
+ export interface CopiesOptions {
79
+ /** The date of the check. With it, a copy with a later check date is an error. */
80
+ readonly at?: string;
81
+ }
82
+
83
+ /** This function gives the findings of the copies: an unknown bundle or kind, a bad date, and two records of one copy. */
84
+ export function checkCopies(copies: readonly Copy[], bundles: readonly Bundle[], options: CopiesOptions = {}): readonly LibraryFinding[] {
85
+ const out: LibraryFinding[] = [];
86
+ const at = options.at === undefined ? undefined : timeOf(options.at);
87
+ if (options.at !== undefined && at === undefined) throw new RangeError(`checkCopies: the date "${options.at}" of the check is not a date YYYY-MM-DD.`);
88
+ const known = new Set(bundles.map((bundle) => bundle.id));
89
+ const seen = new Set<string>();
90
+ for (const copy of copies) {
91
+ const id = `${copy.bundle}@${copy.medium}`;
92
+ const error = (code: LibraryCode, message: string): void => {
93
+ out.push({ level: "error", code, record: "copy", id, message });
94
+ };
95
+ if (seen.has(id)) error("duplicate-copy", `Two records give the copy of "${copy.bundle}" on the medium "${copy.medium}".`);
96
+ seen.add(id);
97
+ if (!known.has(copy.bundle)) error("missing-bundle", `The copy "${id}" names the unknown bundle "${copy.bundle}".`);
98
+ if (!(MEDIUM_KINDS as readonly string[]).includes(copy.kind)) error("bad-kind", `The copy "${id}" has the unknown kind "${String(copy.kind)}".`);
99
+ if (copy.sha256 !== undefined && !SHA256.test(copy.sha256)) error("bad-sha256", `The copy "${id}" has a SHA-256 that is not 64 lower-case hexadecimal digits.`);
100
+ const checked = timeOf(copy.checked);
101
+ if (checked === undefined) error("bad-date", `The copy "${id}" has the check date "${copy.checked}". It needs a date YYYY-MM-DD.`);
102
+ else if (at !== undefined && checked > at) error("checked-in-future", `The copy "${id}" has a check date after the date of the check.`);
103
+ }
104
+ return out;
105
+ }
package/src/copies.ts ADDED
@@ -0,0 +1,141 @@
1
+ // The state of the copies of each bundle, against the copy rule of its level, and the checks that are due.
2
+
3
+ import { DAY_MS, timeOf } from "@mark1russell7/guidebook";
4
+ import type { Finding, IsoDate } from "@mark1russell7/guidebook";
5
+ import { addDays } from "./date.ts";
6
+ import type { Bundle, Copy, CopyRule, MediumKind } from "./records.ts";
7
+
8
+ /** The codes of the copy gaps. */
9
+ export const GAP_CODES = ["few-copies", "few-kinds", "few-places", "no-rule", "check-due", "bad-hash", "old-version"] as const;
10
+
11
+ /** A code of a copy gap. */
12
+ export type GapCode = (typeof GAP_CODES)[number];
13
+
14
+ /** A copy gap: an error on a bundle with too few good copies, or a warning on one copy. */
15
+ export type GapFinding = Finding<GapCode, "bundle" | "copy">;
16
+
17
+ /**
18
+ * The status of one copy at a date.
19
+ * - `good`: the copy had a check within the days of its rule, and its hash agrees with the bundle.
20
+ * - `old`: as `good`, but the copy holds an earlier release of the bundle. It counts as a good copy.
21
+ * - `due`: the last check is older than the days of the rule. The copy does not count until a new check.
22
+ * - `bad`: the hash of the copy does not agree with the hash of the same release. Replace the copy.
23
+ */
24
+ export type CopyStatus = "good" | "old" | "due" | "bad";
25
+
26
+ /** The state of the copies of one bundle. */
27
+ export interface CopyState {
28
+ readonly bundle: string;
29
+ readonly level: string;
30
+ /** The rule of the level, or `undefined` when no rule has the level. */
31
+ readonly rule: CopyRule | undefined;
32
+ readonly copies: readonly { readonly copy: Copy; readonly status: CopyStatus }[];
33
+ /** The count of good copies (the status `good` or `old`). */
34
+ readonly good: number;
35
+ /** The different kinds of media of the good copies. */
36
+ readonly kinds: readonly MediumKind[];
37
+ /** The different places of the good copies. */
38
+ readonly places: readonly string[];
39
+ /** This field is true when the good copies obey the rule. */
40
+ readonly ok: boolean;
41
+ }
42
+
43
+ /** The result of `copyStates`. */
44
+ export interface CopyStates {
45
+ readonly states: readonly CopyState[];
46
+ readonly findings: readonly GapFinding[];
47
+ }
48
+
49
+ function statusOf(copy: Copy, bundle: Bundle, rule: CopyRule | undefined, at: number): CopyStatus {
50
+ const sameRelease = bundle.version === undefined || copy.version === undefined || bundle.version === copy.version;
51
+ if (sameRelease && bundle.sha256 !== undefined && copy.sha256 !== undefined && bundle.sha256 !== copy.sha256) return "bad";
52
+ const checked = timeOf(copy.checked);
53
+ if (checked === undefined) return "due";
54
+ if (rule !== undefined && (at - checked) / DAY_MS > rule.everyDays) return "due";
55
+ return sameRelease ? "good" : "old";
56
+ }
57
+
58
+ /**
59
+ * This function gives the state of the copies of each bundle at the date `at`, and the gaps.
60
+ * A bundle with fewer good copies, kinds or places than the rule of its level gets an error.
61
+ * A copy with a check that is due, a bad hash or an earlier release gets a warning.
62
+ */
63
+ export function copyStates(bundles: readonly Bundle[], copies: readonly Copy[], rules: readonly CopyRule[], options: { readonly at: IsoDate }): CopyStates {
64
+ const at = timeOf(options.at);
65
+ if (at === undefined) throw new RangeError(`copyStates: the date "${options.at}" is not a date YYYY-MM-DD.`);
66
+ const ruleOf = new Map(rules.map((rule) => [rule.level, rule]));
67
+ const byBundle = new Map<string, Copy[]>();
68
+ for (const copy of copies) {
69
+ const list = byBundle.get(copy.bundle) ?? [];
70
+ list.push(copy);
71
+ byBundle.set(copy.bundle, list);
72
+ }
73
+ const states: CopyState[] = [];
74
+ const findings: GapFinding[] = [];
75
+ for (const bundle of bundles) {
76
+ const rule = ruleOf.get(bundle.level);
77
+ const rated = (byBundle.get(bundle.id) ?? []).map((copy) => ({ copy, status: statusOf(copy, bundle, rule, at) }));
78
+ const good = rated.filter((item) => item.status === "good" || item.status === "old").map((item) => item.copy);
79
+ const kinds = [...new Set(good.map((copy) => copy.kind))];
80
+ const places = [...new Set(good.map((copy) => copy.place))];
81
+ const bundleError = (code: GapCode, message: string): void => {
82
+ findings.push({ level: "error", code, record: "bundle", id: bundle.id, message });
83
+ };
84
+ if (rule === undefined) {
85
+ bundleError("no-rule", `The bundle "${bundle.id}" has the level "${bundle.level}", and no copy rule has it.`);
86
+ } else {
87
+ if (good.length < rule.copies) bundleError("few-copies", `The bundle "${bundle.id}" has ${good.length} good copies. Its level "${rule.level}" needs ${rule.copies}.`);
88
+ if (kinds.length < rule.kinds) bundleError("few-kinds", `The good copies of "${bundle.id}" are on ${kinds.length} kinds of media. Its level "${rule.level}" needs ${rule.kinds}.`);
89
+ if (places.length < rule.places) bundleError("few-places", `The good copies of "${bundle.id}" are in ${places.length} places. Its level "${rule.level}" needs ${rule.places}.`);
90
+ }
91
+ for (const { copy, status } of rated) {
92
+ const id = `${copy.bundle}@${copy.medium}`;
93
+ if (status === "due") findings.push({ level: "warning", code: "check-due", record: "copy", id, message: `Read the copy "${id}" against its hash. Its last check was on ${copy.checked}.` });
94
+ if (status === "bad") findings.push({ level: "warning", code: "bad-hash", record: "copy", id, message: `The copy "${id}" does not agree with the hash of its release. Replace it.` });
95
+ if (status === "old") findings.push({ level: "warning", code: "old-version", record: "copy", id, message: `The copy "${id}" holds the release "${copy.version ?? ""}". The catalog has "${bundle.version ?? ""}".` });
96
+ }
97
+ const ok = rule !== undefined && good.length >= rule.copies && kinds.length >= rule.kinds && places.length >= rule.places;
98
+ states.push({ bundle: bundle.id, level: bundle.level, rule, copies: rated, good: good.length, kinds, places, ok });
99
+ }
100
+ return { states, findings };
101
+ }
102
+
103
+ /** A check of a copy that a schedule gives to a person or a job. */
104
+ export interface DueCheck {
105
+ readonly bundle: string;
106
+ readonly medium: string;
107
+ readonly place: string;
108
+ /** The last date on which the copy is good with no new check. */
109
+ readonly due: IsoDate;
110
+ }
111
+
112
+ /**
113
+ * This function gives the check of each copy whose due date is on or before `at` plus `withinDays`, the first due first.
114
+ * A copy of a bundle with no rule, or of an unknown bundle, gets no check.
115
+ */
116
+ export function checksDue(bundles: readonly Bundle[], copies: readonly Copy[], rules: readonly CopyRule[], options: { readonly at: IsoDate; readonly withinDays?: number }): readonly DueCheck[] {
117
+ const limit = addDays(options.at, options.withinDays ?? 0);
118
+ const levelOf = new Map(bundles.map((bundle) => [bundle.id, bundle.level]));
119
+ const ruleOf = new Map(rules.map((rule) => [rule.level, rule]));
120
+ const out: DueCheck[] = [];
121
+ for (const copy of copies) {
122
+ const level = levelOf.get(copy.bundle);
123
+ const rule = level === undefined ? undefined : ruleOf.get(level);
124
+ if (rule === undefined) continue;
125
+ const due = timeOf(copy.checked) === undefined ? options.at : addDays(copy.checked, rule.everyDays);
126
+ if (due <= limit) out.push({ bundle: copy.bundle, medium: copy.medium, place: copy.place, due });
127
+ }
128
+ return out.sort((a, b) => (a.due < b.due ? -1 : a.due > b.due ? 1 : a.bundle < b.bundle ? -1 : a.bundle > b.bundle ? 1 : a.medium < b.medium ? -1 : a.medium > b.medium ? 1 : 0));
129
+ }
130
+
131
+ /** This function gives the bytes that are necessary on one medium for each bundle of a list. */
132
+ export function bytesOf(bundles: readonly Bundle[], ids: readonly string[]): number {
133
+ const sizeOf = new Map(bundles.map((bundle) => [bundle.id, bundle.bytes]));
134
+ let total = 0;
135
+ for (const id of new Set(ids)) {
136
+ const bytes = sizeOf.get(id);
137
+ if (bytes === undefined) throw new RangeError(`bytesOf: the bundle "${id}" is not in the catalog.`);
138
+ total += bytes;
139
+ }
140
+ return total;
141
+ }
package/src/date.ts ADDED
@@ -0,0 +1,10 @@
1
+ // The dates of the add-on. A date is `YYYY-MM-DD` in UTC, as in the core.
2
+
3
+ import { DAY_MS, timeOf } from "@mark1russell7/guidebook";
4
+
5
+ /** This function gives the date `YYYY-MM-DD` that is `days` after the date `date`. */
6
+ export function addDays(date: string, days: number): string {
7
+ const time = timeOf(date);
8
+ if (time === undefined) throw new RangeError(`addDays: "${date}" is not a date YYYY-MM-DD.`);
9
+ return new Date(time + days * DAY_MS).toISOString().slice(0, 10);
10
+ }
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ // The library add-on of the guidebook: a catalog of offline bundles, the copies of each bundle on media, and their gaps.
2
+ // The add-on names no topic: the levels, the places and the media are input data of the caller.
3
+
4
+ export { MEDIUM_KINDS } from "./records.ts";
5
+ export type { Bundle, Copy, CopyRule, MediumKind } from "./records.ts";
6
+ export { LIBRARY_CODES, checkCatalog, checkCopies } from "./check.ts";
7
+ export type { CatalogOptions, CopiesOptions, LibraryCode, LibraryFinding } from "./check.ts";
8
+ export { GAP_CODES, bytesOf, checksDue, copyStates } from "./copies.ts";
9
+ export type { CopyState, CopyStates, CopyStatus, DueCheck, GapCode, GapFinding } from "./copies.ts";
10
+ export { KIWIX_CATALOG, RELEASE_CODES, checkReleases, kiwixFeedUrl, kiwixKeyOf, latestReleases, parseKiwixFeed, parseMeta4, withRelease, zimUrlOf } from "./kiwix.ts";
11
+ export type { FeedQuery, KiwixEntry, Meta4, ReleaseCode, ReleaseFinding, ReleaseOptions } from "./kiwix.ts";
12
+ export { copiesLayer, keepChance, libraryPartOf, planCopies } from "./placement.ts";
13
+ export type { CopiesInput, CopiesQuery, CopyPlace, KindLoss, MediumOffer, PlanCopiesOptions } from "./placement.ts";
package/src/kiwix.ts ADDED
@@ -0,0 +1,214 @@
1
+ // The Kiwix catalog: its OPDS feed of ZIM files, the Metalink file (`.meta4`) of each release, and the release gate.
2
+ // The functions are pure. The caller fetches the feed and the `.meta4` files, for example with `polite-crawler/api`.
3
+
4
+ import type { Finding, IsoDate } from "@mark1russell7/guidebook";
5
+ import { DAY_MS, timeOf } from "@mark1russell7/guidebook";
6
+ import { decodeReferences } from "@mark1russell7/text/references";
7
+ import type { Bundle } from "./records.ts";
8
+
9
+ /** The address of the OPDS catalog of Kiwix. */
10
+ export const KIWIX_CATALOG = "https://opds.library.kiwix.org/catalog/v2";
11
+
12
+ /** One ZIM file of the OPDS feed of Kiwix. */
13
+ export interface KiwixEntry {
14
+ /** The key of the file: its name with its flavour, for example `wikipedia_en_medicine_nopic`. */
15
+ readonly key: string;
16
+ readonly name: string;
17
+ /** The flavour of the file, for example `nopic`, or an empty text. */
18
+ readonly flavour: string;
19
+ readonly title: string;
20
+ /** The release of the file, `YYYY-MM`. */
21
+ readonly release: string;
22
+ /** The date of the release. */
23
+ readonly issued: IsoDate;
24
+ /** The address of the `.meta4` file of the release. */
25
+ readonly meta4: string;
26
+ /** The size that the feed gives. The feed rounds it up to whole KiB, so `parseMeta4` gives the exact size. */
27
+ readonly approxBytes: number;
28
+ }
29
+
30
+ /** The facts of one file in a `.meta4` file. */
31
+ export interface Meta4 {
32
+ /** The name of the file, for example `wikipedia_en_medicine_nopic_2026-10.zim`. */
33
+ readonly file: string;
34
+ /** The exact size of the file in bytes. */
35
+ readonly bytes: number;
36
+ /** The SHA-256 of the file, as 64 lower-case hexadecimal digits. */
37
+ readonly sha256: string;
38
+ }
39
+
40
+ /** The options of `kiwixFeedUrl`. */
41
+ export interface FeedQuery {
42
+ /** The ISO 639-3 code of the language, for example `eng`. */
43
+ readonly lang?: string;
44
+ /** The name of a file, for example `wikipedia_en_medicine`. */
45
+ readonly name?: string;
46
+ /** The largest count of entries. The default is 2000. */
47
+ readonly count?: number;
48
+ /** The address of the catalog. The default is `KIWIX_CATALOG`. */
49
+ readonly catalog?: string;
50
+ }
51
+
52
+ /** This function gives the address of the OPDS feed of the entries that agree with the query. */
53
+ export function kiwixFeedUrl(query: FeedQuery = {}): string {
54
+ const params: [string, string][] = [];
55
+ if (query.lang !== undefined) params.push(["lang", query.lang]);
56
+ if (query.name !== undefined) params.push(["name", query.name]);
57
+ params.push(["count", String(query.count ?? 2000)]);
58
+ const search = params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
59
+ return `${query.catalog ?? KIWIX_CATALOG}/entries?${search}`;
60
+ }
61
+
62
+ const FILE = /^([a-z0-9._-]+?)_(\d{4}-\d{2})\.zim$/u;
63
+
64
+ /** This function gives the key and the release of a ZIM file from its name or its address, or `undefined` for another file. */
65
+ export function kiwixKeyOf(fileOrUrl: string): { readonly key: string; readonly release: string } | undefined {
66
+ const file = fileOrUrl.split(/[?#]/u)[0]?.split("/").at(-1)?.replace(/\.meta4$/u, "") ?? "";
67
+ const match = FILE.exec(file);
68
+ return match === null ? undefined : { key: match[1] ?? "", release: match[2] ?? "" };
69
+ }
70
+
71
+ function textOf(xml: string, tag: string): string | undefined {
72
+ const match = new RegExp(`<${tag}(?:\\s[^>]*)?>([^<]*)</${tag}>`, "u").exec(xml);
73
+ return match === null ? undefined : decodeReferences(match[1] ?? "").trim();
74
+ }
75
+
76
+ /** This function gives each start tag of the element `name` in the XML, with a scan that is linear in the length of the XML. */
77
+ function tagsOf(xml: string, name: string): string[] {
78
+ const out: string[] = [];
79
+ for (let start = xml.indexOf(`<${name}`); start >= 0; start = xml.indexOf(`<${name}`, start + 1)) {
80
+ const end = xml.indexOf(">", start);
81
+ if (end < 0) break;
82
+ out.push(xml.slice(start, end + 1));
83
+ }
84
+ return out;
85
+ }
86
+
87
+ const OPEN_ACCESS = 'rel="http://opds-spec.org/acquisition/open-access"';
88
+
89
+ function attributeOf(tag: string, name: string): string | undefined {
90
+ const match = new RegExp(`\\s${name}="([^"]*)"`, "u").exec(tag);
91
+ return match === null ? undefined : decodeReferences(match[1] ?? "");
92
+ }
93
+
94
+ /**
95
+ * This function gives the entries of an OPDS feed of Kiwix.
96
+ * An entry with no open-access link to a `.meta4` file of a ZIM release is not in the result.
97
+ */
98
+ export function parseKiwixFeed(xml: string): readonly KiwixEntry[] {
99
+ const out: KiwixEntry[] = [];
100
+ for (const part of xml.split("<entry>").slice(1)) {
101
+ const entry = part.split("</entry>")[0] ?? "";
102
+ const link = tagsOf(entry, "link ").find((tag) => tag.includes(OPEN_ACCESS));
103
+ const meta4 = link === undefined ? undefined : attributeOf(link, "href");
104
+ const file = meta4 === undefined ? undefined : kiwixKeyOf(meta4);
105
+ if (link === undefined || meta4 === undefined || file === undefined) continue;
106
+ const issued = (textOf(entry, "dc:issued") ?? textOf(entry, "updated") ?? "").slice(0, 10);
107
+ out.push({
108
+ key: file.key,
109
+ name: textOf(entry, "name") ?? "",
110
+ flavour: textOf(entry, "flavour") ?? "",
111
+ title: textOf(entry, "title") ?? "",
112
+ release: file.release,
113
+ issued,
114
+ meta4,
115
+ approxBytes: Number(attributeOf(link, "length") ?? "0"),
116
+ });
117
+ }
118
+ return out;
119
+ }
120
+
121
+ /** This function gives the file, the exact size and the SHA-256 of the first file of a `.meta4` file. It throws a `RangeError` when one is missing. */
122
+ export function parseMeta4(xml: string): Meta4 {
123
+ const tag = tagsOf(xml, "file ")[0];
124
+ const start = tag === undefined ? -1 : xml.indexOf(tag) + tag.length;
125
+ const end = start < 0 ? -1 : xml.indexOf("</file>", start);
126
+ const block = end < 0 ? "" : xml.slice(start, end);
127
+ const file = tag === undefined ? undefined : attributeOf(tag, "name");
128
+ const bytes = Number(textOf(block, "size") ?? Number.NaN);
129
+ const sha256 = /<hash\s+type="sha-256"\s*>([0-9a-fA-F]{64})<\/hash>/u.exec(block)?.[1]?.toLowerCase();
130
+ if (file === undefined || file === "" || !Number.isSafeInteger(bytes) || bytes < 1 || sha256 === undefined) {
131
+ throw new RangeError("parseMeta4: the file has no file name, no size or no SHA-256.");
132
+ }
133
+ return { file, bytes, sha256 };
134
+ }
135
+
136
+ /** This function gives the newest release of each key of the entries. */
137
+ export function latestReleases(entries: readonly KiwixEntry[]): ReadonlyMap<string, KiwixEntry> {
138
+ const out = new Map<string, KiwixEntry>();
139
+ for (const entry of entries) {
140
+ const known = out.get(entry.key);
141
+ if (known === undefined || entry.release > known.release) out.set(entry.key, entry);
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /** The address of the ZIM file of a `.meta4` address: the same address with no `.meta4`. */
147
+ export function zimUrlOf(meta4: string): string {
148
+ return meta4.replace(/\.meta4$/u, "");
149
+ }
150
+
151
+ /**
152
+ * This function gives the bundle with the release of the entry: its version, its exact size, its SHA-256 and its address.
153
+ * It throws a `RangeError` when the `.meta4` file is for a different file.
154
+ */
155
+ export function withRelease(bundle: Bundle, entry: KiwixEntry, meta4: Meta4): Bundle {
156
+ const file = kiwixKeyOf(meta4.file);
157
+ if (file?.key !== entry.key || file.release !== entry.release) {
158
+ throw new RangeError(`withRelease: the .meta4 file is for "${meta4.file}", not for ${entry.key} ${entry.release}.`);
159
+ }
160
+ return { ...bundle, version: entry.release, bytes: meta4.bytes, sha256: meta4.sha256, url: zimUrlOf(entry.meta4) };
161
+ }
162
+
163
+ /** The codes of the release gate. */
164
+ export const RELEASE_CODES = ["not-kiwix", "not-in-feed", "newer-release", "old-release", "no-hash"] as const;
165
+
166
+ /** A code of the release gate. */
167
+ export type ReleaseCode = (typeof RELEASE_CODES)[number];
168
+
169
+ /** A finding of the release gate. */
170
+ export type ReleaseFinding = Finding<ReleaseCode, "bundle">;
171
+
172
+ /** The options of `checkReleases`. */
173
+ export interface ReleaseOptions {
174
+ /** The date of the read of the feed. */
175
+ readonly at: IsoDate;
176
+ /** A newer release is an error when the release of the bundle is older than this count of days. The default is 365. */
177
+ readonly maxAgeDays?: number;
178
+ }
179
+
180
+ /**
181
+ * This function compares each bundle with a Kiwix address to the newest release of the feed.
182
+ * - The feed has no file of the key: the error `not-in-feed`.
183
+ * - The feed has a newer release: the warning `newer-release`, or the error `old-release` when the bundle is older than `maxAgeDays`.
184
+ * - The bundle has no SHA-256: the warning `no-hash`.
185
+ * - A bundle with an address that is not a ZIM release gets the warning `not-kiwix`.
186
+ */
187
+ export function checkReleases(bundles: readonly Bundle[], entries: readonly KiwixEntry[], options: ReleaseOptions): readonly ReleaseFinding[] {
188
+ const at = timeOf(options.at);
189
+ if (at === undefined) throw new RangeError(`checkReleases: the date "${options.at}" is not a date YYYY-MM-DD.`);
190
+ const maxAgeDays = options.maxAgeDays ?? 365;
191
+ const latest = latestReleases(entries);
192
+ const out: ReleaseFinding[] = [];
193
+ const add = (level: "error" | "warning", code: ReleaseCode, id: string, message: string): void => {
194
+ out.push({ level, code, record: "bundle", id, message });
195
+ };
196
+ for (const bundle of bundles) {
197
+ if (bundle.url === undefined) continue;
198
+ const file = kiwixKeyOf(bundle.url);
199
+ if (file === undefined) {
200
+ add("warning", "not-kiwix", bundle.id, `The bundle "${bundle.id}" has the address "${bundle.url}". It is not a ZIM release of Kiwix.`);
201
+ continue;
202
+ }
203
+ const entry = latest.get(file.key);
204
+ if (entry === undefined) {
205
+ add("error", "not-in-feed", bundle.id, `The Kiwix feed has no file "${file.key}" of the bundle "${bundle.id}".`);
206
+ } else if (entry.release > file.release) {
207
+ const released = timeOf(`${file.release}-01`);
208
+ const old = released !== undefined && (at - released) / DAY_MS > maxAgeDays;
209
+ add(old ? "error" : "warning", old ? "old-release" : "newer-release", bundle.id, `The bundle "${bundle.id}" has the release ${file.release}. The Kiwix feed has ${entry.release}.`);
210
+ }
211
+ if (bundle.sha256 === undefined) add("warning", "no-hash", bundle.id, `The bundle "${bundle.id}" has no SHA-256. Read it from the .meta4 file of its release.`);
212
+ }
213
+ return out;
214
+ }