Compare commits

..
7 Commits
Author SHA1 Message Date
ztimson 3c80bfae93 Track download progress
Publish Library / Build NPM Project (push) Successful in 1m50s
Publish Library / Tag Version (push) Successful in 7s
2026-10-05 15:08:09 -04:00
ztimson ba4bdceab1 Track download progress
Publish Library / Build NPM Project (push) Successful in 1m47s
Publish Library / Tag Version (push) Successful in 21s
2026-10-05 15:00:09 -04:00
ztimson 5bc27fa632 Summary fix
Publish Library / Build NPM Project (push) Successful in 3m35s
Publish Library / Tag Version (push) Successful in 7s
2026-09-21 13:27:36 -04:00
ztimson 943280f326 Bump 0.4.5
Publish Library / Build NPM Project (push) Successful in 3m44s
Publish Library / Tag Version (push) Successful in 10s
2026-09-21 00:38:53 -04:00
ztimson dc24f48a36 Better catalog search
Publish Library / Build NPM Project (push) Successful in 3m6s
Publish Library / Tag Version (push) Canceled after 9s
2026-09-20 23:27:16 -04:00
ztimson 812e72a8cd Better catalog search
Publish Library / Build NPM Project (push) Successful in 4m2s
Publish Library / Tag Version (push) Failing after 19s
2026-09-20 23:26:57 -04:00
ztimson a45d7bad8c Search fix
Publish Library / Build NPM Project (push) Successful in 4m13s
Publish Library / Tag Version (push) Successful in 16s
2026-09-20 20:57:46 -04:00
6 changed files with 182 additions and 55 deletions
+3
View File
@@ -146,6 +146,9 @@ function resolveArchiveName() {
}
async function install() {
if (fs.existsSync(BIN_DIR) && (await fs.promises.readdir(BIN_DIR)).some(f => f.startsWith('kiwix-')))
return console.log(`Already installed: ${BIN_DIR}`);
const {archiveName, ext} = resolveArchiveName();
const url = `${BASE_URL}/${archiveName}`;
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kiwix-install-'));
+7 -7
View File
@@ -1,17 +1,17 @@
{
"name": "@ztimson/zim-utils",
"version": "0.3.6",
"version": "0.4.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ztimson/zim-utils",
"version": "0.3.6",
"version": "0.4.8",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"@ztimson/utils": "^0.30.8",
"adm-zip": "^0.5.16",
"@ztimson/utils": "^0.30.9",
"adm-zip": "^0.5.18",
"lzma1": "^0.3.0",
"tar": "^7.4.3",
"zstd-codec": "^0.1.5"
@@ -30,9 +30,9 @@
}
},
"node_modules/@ztimson/utils": {
"version": "0.30.8",
"resolved": "https://registry.npmjs.org/@ztimson/utils/-/utils-0.30.8.tgz",
"integrity": "sha512-+vBjcinqckqMHkP95xWiQeQz2E7Q1oS0b+Odjp+F9rvQ4z0US4JdodjqhEaqh+RAO/yP77x4Eu0a04yBB4HNdw==",
"version": "0.30.9",
"resolved": "https://registry.npmjs.org/@ztimson/utils/-/utils-0.30.9.tgz",
"integrity": "sha512-th/6qBaRJFnxoQk+01ESXjFqhYzsiXziOzd3gPgFG6XrusA+oHtfgxBKJ77ygPq//0cI85srWgAzvQcAmKUAQw==",
"license": "MIT",
"dependencies": {
"var-persist": "^1.0.1"
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@ztimson/zim-utils",
"version": "0.4.2",
"version": "0.4.8",
"description": "Native, dependency-light ZIM archive reader/searcher and Kiwix catalog downloader for Node.js",
"author": "Zak Timson",
"license": "MIT",
@@ -15,10 +15,10 @@
"postinstall": "node ./bin/install-kwix.js"
},
"dependencies": {
"@ztimson/utils": "^0.30.8",
"@ztimson/utils": "^0.30.9",
"lzma1": "^0.3.0",
"tar": "^7.4.3",
"zstd-codec": "^0.1.5",
"adm-zip": "^0.5.16"
"adm-zip": "^0.5.18"
}
}
+104 -24
View File
@@ -2,19 +2,29 @@ import {fuzzyMatch} from './utils.js';
import {decodeHtml} from '@ztimson/utils';
export const CATALOG_URL = 'https://library.kiwix.org';
export const VIEWER_URL = 'https://browse.library.kiwix.org';
const PAGE_SIZE = 100;
export function parseEntries(xml, catalog = CATALOG_URL) {
const blocks = xml.match(/<entry>[\s\S]*?<\/entry>/g) || [];
return blocks.map(b => {
const grab = re => (b.match(re) || [])[1] || '';
const linkMatch = b.match(/<link[^>]*type=["']application\/x-zim[^"']*["'][^>]*href=["']([^"']+)["']/);
const iconMatch = b.match(/<link[^>]*rel=["']http:\/\/opds-spec\.org\/image\/thumbnail["'][^>]*href=["']([^"']+)["']/)
|| b.match(/<link[^>]*type=["']image\/[^"']*["'][^>]*href=["']([^"']+)["']/);
let tags = grab(/<tags>([^<]*)<\/tags>/);
if(tags) tags = tags.split(';');
if (tags) tags = tags.split(';');
const name = grab(/<name>([^<]*)<\/name>/);
const href = linkMatch ? linkMatch[1] : null;
const filename = href
? decodeURIComponent(new URL(href).pathname.split('/').pop()).replace(/\.meta4$/i, '')
: name;
const viewerName = filename.replace(/\.zim$/i, '');
return {
id: grab(/<id>([^<]*)<\/id>/),
title: decodeHtml(grab(/<title>([^<]*)<\/title>/)),
@@ -22,25 +32,52 @@ export function parseEntries(xml, catalog = CATALOG_URL) {
summary: decodeHtml(grab(/<summary>([^<]*)<\/summary>/)),
language: grab(/<language>([^<]*)<\/language>/),
name,
flavour: grab(/<flavour>([^<]*)<\/flavour>/),
category: grab(/<category>([^<]*)<\/category>/),
tags,
mediaCount: Number(grab(/<mediaCount>([^<]*)<\/mediaCount>/)) || 0,
author: grab(/<author>\s*<name>([^<]*)<\/name>\s*<\/author>/m),
publisher: grab(/<publisher>\s*<name>([^<]*)<\/name>\s*<\/publisher>/m),
articleCount: Number(grab(/<articleCount>([^<]*)<\/articleCount>/)) || 0,
sizeMb: linkMatch ? +(Number((b.match(/length=["'](\d+)["']/) || [])[1] || 0) / 1024 / 1024).toFixed(1) : '?',
href: linkMatch ? linkMatch[1] : null,
sizeMb: href
? +(Number((b.match(/length=["'](\d+)["']/) || [])[1] || 0) / 1024 / 1024).toFixed(1)
: '?',
href,
icon: iconMatch ? new URL(iconMatch[1], catalog).href : null,
viewer: name ? new URL(`viewer#${name}`, catalog).href : null,
viewer: viewerName ? `${VIEWER_URL}/viewer#${viewerName}` : null,
};
});
}
async function fetchEntries(term, lang, url = CATALOG_URL) {
const params = new URLSearchParams({q: term, count: String(PAGE_SIZE), lang: lang || 'eng'});
const res = await fetch(`${url}/catalog/v2/entries?${params}`);
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return parseEntries(await res.text());
const entries = [];
let start = 0;
let total = Infinity;
while (start < total) {
const params = new URLSearchParams({
q: term,
count: String(PAGE_SIZE),
start: String(start),
lang: lang || 'eng',
});
const res = await fetch(`${url}/catalog/v2/entries?${params}`);
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
const xml = await res.text();
const page = parseEntries(xml, url);
const totalResults = Number((xml.match(/<totalResults>(\d+)<\/totalResults>/) || [])[1]);
entries.push(...page);
if (Number.isFinite(totalResults)) total = totalResults;
if (!page.length || start + page.length >= total) break;
start += page.length;
}
return entries;
}
/** Looks up a single catalog entry by exact `name` (used to check for available updates). */
@@ -48,30 +85,73 @@ export async function zimCatalogInfo(name, url = CATALOG_URL) {
const params = new URLSearchParams({name, count: '5'});
const res = await fetch(`${url}/catalog/v2/entries?${params}`);
if (!res.ok) return null;
return parseEntries(await res.text()).find(e => e.name === name) || null;
return parseEntries(await res.text(), url).find(e => e.name === name) || null;
}
/** Searches the Kiwix catalog for ZIMs matching `terms` within `category`, ranked by term coverage then fuzzy similarity. */
/** Searches the Kiwix catalog for ZIMs matching `terms`, ranked by relevance. */
export async function zimCatalog(terms, opts = {lang: 'eng', count: 20, url: CATALOG_URL}) {
opts = Object.assign({lang: 'eng', count: 20, url: CATALOG_URL}, opts)
const termList = [...String(terms).split(',')].filter(Boolean).map(t => t.trim().toLowerCase());
const results = await Promise.allSettled(termList.map(t => fetchEntries(t, opts.lang, opts.url)));
const byName = new Map();
opts = Object.assign({lang: 'eng', count: 20, url: CATALOG_URL}, opts);
const termList = [...String(terms).split(',')]
.filter(Boolean)
.map(t => t.trim().toLowerCase());
const results = await Promise.allSettled(
termList.map(t => fetchEntries(t, opts.lang, opts.url))
);
const byZim = new Map();
results.forEach((r, i) => {
if (r.status !== 'fulfilled') return;
const term = termList[i];
for (const entry of r.value) {
if (!entry.name) continue;
if (!byName.has(entry.name)) byName.set(entry.name, {entry, hitTerms: new Set()});
byName.get(entry.name).hitTerms.add(term);
const zimId = entry.href || entry.id || entry.name;
if (!zimId) continue;
if (!byZim.has(zimId)) {
byZim.set(zimId, {entry, hitTerms: new Set()});
}
byZim.get(zimId).hitTerms.add(term);
}
});
if (!byName.size) return [];
return [...byName.values()].map(({entry, hitTerms}) => {
const text = `${entry.title} ${entry.summary}`.trim();
return {entry, hits: hitTerms.size, fuzzy: fuzzyMatch(text, ...termList).max};
}).toSorted((a, b) =>
b.hits - a.hits || b.fuzzy - a.fuzzy || b.entry.articleCount - a.entry.articleCount
).slice(0, opts.count).map(r => r.entry);
if (!byZim.size) return [];
return [...byZim.values()]
.map(({entry, hitTerms}) => {
const title = entry.title.toLowerCase();
const summary = entry.summary.toLowerCase();
const titleWords = title.split(/\W+/).filter(Boolean);
const exactTitle = termList.some(term => title === term);
const exactWord = termList.some(term => titleWords.includes(term));
const titleMatch = termList.some(term => title.includes(term));
const titleFuzzy = fuzzyMatch(title, ...termList).max;
const summaryFuzzy = fuzzyMatch(summary, ...termList).max;
return {
entry,
hits: hitTerms.size,
exactTitle,
exactWord,
titleMatch,
titleFuzzy,
summaryFuzzy,
};
})
.toSorted((a, b) =>
Number(b.exactTitle) - Number(a.exactTitle)
|| Number(b.exactWord) - Number(a.exactWord)
|| Number(b.titleMatch) - Number(a.titleMatch)
|| b.titleFuzzy - a.titleFuzzy
|| b.summaryFuzzy - a.summaryFuzzy
|| b.hits - a.hits
|| new Date(b.entry.updated) - new Date(a.entry.updated)
)
.map(r => r.entry);
}
+56 -18
View File
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import {pipeline} from 'node:stream/promises';
import {Readable} from 'node:stream';
import {PromiseProgress} from '@ztimson/utils';
import {KiwixServer} from './server.js';
import {zimCatalog, zimCatalogInfo, CATALOG_URL} from './catalog.js';
@@ -17,6 +18,7 @@ export class ZimManager {
#dir;
#server;
#ownsServer;
#active = {}; // name -> in-flight PromiseProgress, for on-demand status lookups
/** @param {{catalog?: string, server?: KiwixServer, port?: number, host?: string, binDir?: string, url?: string}} [opts]
* server: reuse an existing KiwixServer instance directly.
@@ -41,11 +43,16 @@ export class ZimManager {
return this.#server;
}
async #download(url, destPath) {
/** Streams `url` to `destPath`, reporting raw bytes/total via `onBytes(size, total)` as chunks arrive. */
async #download(url, destPath, onBytes) {
const {res} = await this.#resolveUrl(url);
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
const total = Number(res.headers.get('content-length')) || 0;
const tmpPath = `${destPath}.part`;
await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(tmpPath));
let size = 0;
const readable = Readable.fromWeb(res.body);
if (onBytes) readable.on('data', chunk => onBytes(size += chunk.length, total));
await pipeline(readable, fs.createWriteStream(tmpPath));
await fs.promises.rename(tmpPath, destPath);
}
@@ -75,7 +82,8 @@ export class ZimManager {
return false;
}
async #update(name, catalogEntry, localMatch, force) {
/** Performs the actual download + post-processing for a resolved catalog entry, forwarding byte progress via `onBytes`. */
async #update(name, catalogEntry, localMatch, force, onBytes) {
const remoteDate = catalogEntry.updated ? new Date(catalogEntry.updated) : null;
const localDate = localMatch?.updated ?? null;
if (!force && localMatch && remoteDate && localDate && remoteDate <= localDate)
@@ -84,13 +92,22 @@ export class ZimManager {
const filename = path.basename(new URL(catalogEntry.href).pathname).replace(/\.meta4$/i, '');
const destPath = path.join(this.#dir, filename);
await this.#download(catalogEntry.href, destPath);
await this.#download(catalogEntry.href, destPath, onBytes);
if (localMatch && localMatch.file !== filename) await fs.promises.rm(path.join(this.#dir, localMatch.file), {force: true});
await this.#ensureServer();
await this.#waitUntilVisible(filename, {expect: true});
return {name, status: 'updated', file: filename};
}
/** Wraps `#update` in a tracked `PromiseProgress`, registered in `#active` under `name` until it settles. */
#trackedUpdate(name, catalogEntry, localMatch, force) {
const dl = new PromiseProgress((resolve, reject, prog) =>
this.#update(name, catalogEntry, localMatch, force, prog).then(resolve, reject));
this.#active[name] = dl;
dl.catch(() => {}).finally(() => { if (this.#active[name] === dl) delete this.#active[name]; });
return dl;
}
catalog(search, opts = {}) {
return zimCatalog(search, {url: this.#catalogUrl, ...opts});
}
@@ -111,18 +128,28 @@ export class ZimManager {
return {file: match.file, status: 'deleted'};
}
/** Downloads/updates a single ZIM by direct href, matching against any existing local copy by name. */
async download(href, {force = false} = {}) {
const {url: finalUrl} = await this.#resolveUrl(href);
const filename = path.basename(new URL(finalUrl).pathname).replace(/\.meta4$/i, '');
await fs.promises.mkdir(this.#dir, {recursive: true});
const local = await this.list();
const exact = local.find(l => l.file === filename);
if (exact && !force) return {name: exact.name ?? this.#stripDate(filename), status: 'skipped', reason: 'already downloaded', file: filename};
const name = this.#stripDate(filename);
const localMatch = local.find(l => l.name === name) ?? null;
const catalogEntry = await zimCatalogInfo(name, this.#catalogUrl) || {name, updated: null, href};
return this.#update(name, catalogEntry, localMatch, force);
/** Downloads/updates a single ZIM by direct href, matching against any existing local copy by name.
* Returns a `PromiseProgress` with live `.progress`/`.speed`/`.eta`/etc getters & `onProgress` callback,
* while also tracking it internally (see `progress()`/`downloads()`) in case the reference is dropped. */
download(href, {force = false} = {}) {
let dl;
dl = new PromiseProgress(async (resolve, reject, prog) => {
try {
const {url: finalUrl} = await this.#resolveUrl(href);
const filename = path.basename(new URL(finalUrl).pathname).replace(/\.meta4$/i, '');
await fs.promises.mkdir(this.#dir, {recursive: true});
const local = await this.list();
const exact = local.find(l => l.file === filename);
if (exact && !force) return resolve({name: exact.name ?? this.#stripDate(filename), status: 'skipped', reason: 'already downloaded', file: filename});
const name = this.#stripDate(filename);
const localMatch = local.find(l => l.name === name) ?? null;
const catalogEntry = await zimCatalogInfo(name, this.#catalogUrl) || {name, updated: null, href};
this.#active[name] = dl;
dl.catch(() => {}).finally(() => { if (this.#active[name] === dl) delete this.#active[name]; });
resolve(await this.#update(name, catalogEntry, localMatch, force, prog));
} catch (e) { reject(e); }
});
return dl;
}
async link(href) {
@@ -159,7 +186,8 @@ export class ZimManager {
return server.search(terms, {limit, sources});
}
/** Checks all local ZIMs against the catalog and updates any that are outdated. */
/** Checks all local ZIMs against the catalog and updates any that are outdated.
* Each in-flight update is individually tracked in `#active` - use `progress(name)`/`downloads()` to poll them mid-run. */
async updateAll({force = false} = {}) {
const local = await this.list();
const results = [];
@@ -168,11 +196,21 @@ export class ZimManager {
const catalogEntry = await zimCatalogInfo(entry.name, this.#catalogUrl);
if (!catalogEntry) { results.push({name: entry.name, status: 'skipped', reason: 'missing from catalog'}); continue; }
try {
results.push(await this.#update(entry.name, catalogEntry, entry, force));
results.push(await this.#trackedUpdate(entry.name, catalogEntry, entry, force));
} catch (e) {
results.push({name: entry.name, status: 'error', reason: e.message});
}
}
return results;
}
/** Live progress snapshot (speed/eta/size/total/...) for a single named download, or `null` if nothing's in flight. */
progress(name) {
return this.#active[name] ? {name, ...this.#active[name].meta} : null;
}
/** Live progress snapshots for every currently active download. */
downloads() {
return Object.entries(this.#active).map(([name, dl]) => ({name, ...dl.meta}));
}
}
+9 -3
View File
@@ -32,6 +32,12 @@ function tokenize(terms) {
return String(terms).split(/[,\s]+/).map(t => t.trim()).filter(Boolean);
}
function normalizeSummary(summary) {
if(typeof summary === 'string') return summary;
if(summary && typeof summary === 'object') return summary._text || '';
return '';
}
export class KiwixServer {
static #empty = '<?xml version="1.0" encoding="UTF-8" ?>\n<library version="20110515"></library>\n';
@@ -218,7 +224,7 @@ export class KiwixServer {
id: e.id,
title: e.title,
updated: new Date(e.date),
summary: e.description,
summary: normalizeSummary(e.description),
language: e.language,
name: e.name,
category: tags.find(t => t.startsWith('_category'))?.slice(10) || '',
@@ -275,7 +281,7 @@ export class KiwixServer {
const found = fromXml(await res.text())?.rss?.channel?.item || [];
return found.map(hit => {
return makeArray(found).map(hit => {
const resultBook = bookMap.get(hit.book?.title) || book;
const prefix = `/content/${resultBook.href}/`;
@@ -292,7 +298,7 @@ export class KiwixServer {
href: `${resultBook.href}/${page}`,
icon: resultBook.icon,
viewer: this.baseUrl + hit.link,
summary: hit.description,
summary: normalizeSummary(hit.description),
xapianScore: +hit.score || 0,
};
}).filter(Boolean);