generated from ztimson/template
Compare commits
7
Commits
0.3.1
..
fee24e97cd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fee24e97cd | ||
|
|
50c4b2ac21 | ||
|
|
499d83c9be | ||
|
|
0f8637f913 | ||
|
|
57cb9c8bd1 | ||
|
|
7a2f17bfe9 | ||
|
|
a2bde0b5cd |
@@ -87,6 +87,7 @@ await server.stop(); // Kill server
|
||||
```
|
||||
|
||||
#### List Local ZIMs
|
||||
|
||||
```js
|
||||
const local = await server.list();
|
||||
[
|
||||
|
||||
+46
-14
@@ -2,8 +2,10 @@ import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import https from 'node:https';
|
||||
import {execFileSync} from 'node:child_process';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {createWriteStream} from 'node:fs';
|
||||
import AdmZip from 'adm-zip';
|
||||
import * as tar from 'tar';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -11,9 +13,8 @@ const VERSION = '3.8.1';
|
||||
const BASE_URL = 'https://download.kiwix.org/release/kiwix-tools';
|
||||
const PLATFORM_MAP = {linux: 'linux', darwin: 'macos', win32: 'win'};
|
||||
|
||||
const BIN_DIR = path.join(__dirname, '..', 'bin'); // project root/bin
|
||||
const BIN_DIR = path.join(__dirname, '..', 'bin');
|
||||
|
||||
/** Download a file, following redirects. */
|
||||
function download(url, dest) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const file = fs.createWriteStream(dest);
|
||||
@@ -31,7 +32,6 @@ function download(url, dest) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Recursively chmod all files under a directory. */
|
||||
function chmodRecursive(dir, mode) {
|
||||
for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
|
||||
const full = path.join(dir, entry.name);
|
||||
@@ -56,20 +56,52 @@ async function downloadAndExtract() {
|
||||
await fs.promises.mkdir(BIN_DIR, {recursive: true});
|
||||
|
||||
console.log('Extracting...');
|
||||
execFileSync('tar', ['-xf', archivePath, '-C', BIN_DIR]); // bsdtar handles zip too
|
||||
|
||||
// Archives (tar.gz) may wrap contents in a subdirectory - flatten it into BIN_DIR
|
||||
const wrapperDir = (await fs.promises.readdir(BIN_DIR, {withFileTypes: true}))
|
||||
.find(e => e.isDirectory() && e.name.startsWith('kiwix-tools_'));
|
||||
if (wrapperDir) {
|
||||
const wrapperPath = path.join(BIN_DIR, wrapperDir.name);
|
||||
for (const entry of await fs.promises.readdir(wrapperPath)) {
|
||||
await fs.promises.rename(path.join(wrapperPath, entry), path.join(BIN_DIR, entry));
|
||||
// Use npm-installable libraries for extraction
|
||||
if (archiveName.endsWith('.zip')) {
|
||||
const zip = new AdmZip(archivePath);
|
||||
const zipName = zip.getZipName(); // e.g. "kiwix-tools_linux-x86_64-3.8.1"
|
||||
const extractDir = path.join(BIN_DIR, zipName);
|
||||
|
||||
await zip.extractAllToAsync(extractDir, true);
|
||||
|
||||
// Flatten the extracted directory into BIN_DIR
|
||||
if (fs.existsSync(extractDir)) {
|
||||
for (const entry of await fs.promises.readdir(extractDir)) {
|
||||
const src = path.join(extractDir, entry);
|
||||
const dest = path.join(BIN_DIR, entry);
|
||||
await fs.promises.rename(src, dest);
|
||||
}
|
||||
await fs.promises.rmdir(extractDir);
|
||||
}
|
||||
await fs.promises.rmdir(wrapperPath);
|
||||
} else if (archiveName.endsWith('.tar.gz')) {
|
||||
// Extract to a temp dir first to check for subdirectory wrapper
|
||||
const extractDir = path.join(tmpDir, 'extracted');
|
||||
await fs.promises.mkdir(extractDir, {recursive: true});
|
||||
|
||||
await tar.extract({
|
||||
file: archivePath,
|
||||
cwd: extractDir,
|
||||
silent: false
|
||||
});
|
||||
|
||||
const list = await fs.promises.readdir(extractDir, {withFileTypes: true});
|
||||
const wrapper = list.find(e => e.isDirectory() && e.name.startsWith('kiwix-tools_'));
|
||||
const finalDir = wrapper ? path.join(extractDir, wrapper.name) : extractDir;
|
||||
|
||||
// Flatten into BIN_DIR
|
||||
for (const entry of await fs.promises.readdir(finalDir)) {
|
||||
const src = path.join(finalDir, entry);
|
||||
const dest = path.join(BIN_DIR, entry);
|
||||
await fs.promises.rename(src, dest);
|
||||
}
|
||||
|
||||
await fs.promises.rmdir(finalDir);
|
||||
}
|
||||
|
||||
if (process.platform !== 'win32') chmodRecursive(BIN_DIR, 0o755);
|
||||
if (process.platform !== 'win32') {
|
||||
chmodRecursive(BIN_DIR, 0o755);
|
||||
}
|
||||
|
||||
await fs.promises.rm(tmpDir, {recursive: true, force: true});
|
||||
console.log('Installed to:', BIN_DIR);
|
||||
|
||||
+5
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/zim-utils",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.5",
|
||||
"description": "Native, dependency-light ZIM archive reader/searcher and Kiwix catalog downloader for Node.js",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
@@ -17,6 +17,8 @@
|
||||
"dependencies": {
|
||||
"@ztimson/utils": "^0.30.8",
|
||||
"lzma1": "^0.3.0",
|
||||
"zstd-codec": "^0.1.5"
|
||||
"tar": "^7.4.3",
|
||||
"zstd-codec": "^0.1.5",
|
||||
"adm-zip": "^0.5.16"
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-9
@@ -10,7 +10,7 @@ import {zimCatalog, zimCatalogInfo, CATALOG_URL} from './catalog.js';
|
||||
export class ZimManager {
|
||||
#catalogUrl;
|
||||
#dir;
|
||||
server;
|
||||
#server;
|
||||
#ownsServer;
|
||||
|
||||
/** @param {{catalog?: string, server?: KiwixServer, port?: number, host?: string, binDir?: string, url?: string}} [opts]
|
||||
@@ -21,15 +21,15 @@ export class ZimManager {
|
||||
this.#catalogUrl = catalog;
|
||||
this.#dir = dir;
|
||||
this.#ownsServer = !server;
|
||||
this.server = server ?? new KiwixServer(dir, {port, host, binDir, url});
|
||||
this.#server = server ?? new KiwixServer(dir, {port, host, binDir, url});
|
||||
}
|
||||
|
||||
/** The KiwixServer backing this manager - reuse it directly for content/search access, or pass into another ZimManager. */
|
||||
get server() { return this.server; }
|
||||
get server() { return this.#server; }
|
||||
|
||||
async #ensureServer() {
|
||||
if (!this.server.running) await this.server.start();
|
||||
return this.server;
|
||||
if (!this.#server.running) await this.#server.start();
|
||||
return this.#server;
|
||||
}
|
||||
|
||||
async #download(url, destPath) {
|
||||
@@ -74,14 +74,15 @@ export class ZimManager {
|
||||
|
||||
/** Stops the internally-owned KiwixServer, if this manager created its own (no-op if one was passed in). */
|
||||
async close() {
|
||||
if (this.#ownsServer) await this.server.stop();
|
||||
if (this.#ownsServer) await this.#server.stop();
|
||||
}
|
||||
|
||||
async delete(nameOrFile) {
|
||||
const local = await this.list();
|
||||
const match = local.find(l => l.name === nameOrFile || l.file === nameOrFile);
|
||||
const match = local.find(l => l.name === nameOrFile || l.href === nameOrFile);
|
||||
if (!match) throw new Error(`ZIM not found locally: ${nameOrFile}`);
|
||||
await fs.promises.rm(path.join(this.#dir, match.file), {force: true});
|
||||
const file = match.href + (match.href.endsWith('.zim') ? '' : '.zim');
|
||||
await fs.promises.rm(path.join(this.#dir, file), {force: true});
|
||||
const server = await this.#ensureServer();
|
||||
await server.reload();
|
||||
return {file: match.file, status: 'deleted'};
|
||||
@@ -89,9 +90,9 @@ export class ZimManager {
|
||||
|
||||
/** Downloads/updates a single ZIM by direct href, matching against any existing local copy by name. */
|
||||
async download(href, {force = false} = {}) {
|
||||
await fs.promises.mkdir(this.#dir, {recursive: true});
|
||||
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 name = filename.replace(/\.zim$/i, '').replace(/_\d{4}-\d{2}(?:_\d+)?$/, '');
|
||||
|
||||
const local = await this.list();
|
||||
|
||||
+27
-21
@@ -6,8 +6,7 @@ import net from 'node:net';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {decodeHtml, fromXml} from '@ztimson/utils';
|
||||
import {fuzzyMatch, weightedScore} from './utils.js';
|
||||
import {fromXml} from '@ztimson/utils';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -28,6 +27,8 @@ function findFreePort() {
|
||||
|
||||
/** Owns a kiwix-serve process's full lifecycle: library.xml, start/stop/reload, content + search access. */
|
||||
export class KiwixServer {
|
||||
static #empty = '<?xml version="1.0" encoding="UTF-8" ?>\n<library version="20110515"></library>\n';
|
||||
|
||||
#dir;
|
||||
#host;
|
||||
#port;
|
||||
@@ -50,6 +51,12 @@ export class KiwixServer {
|
||||
this.#binDir = binDir;
|
||||
this.#libraryPath = path.join(dir, 'library.xml');
|
||||
this.#remote = url ? url.replace(/\/$/, '') : null;
|
||||
if (!this.#remote) this.#ensureLocalStore();
|
||||
}
|
||||
|
||||
#ensureLocalStore() {
|
||||
fs.mkdirSync(this.#dir, {recursive: true});
|
||||
if (!fs.existsSync(this.#libraryPath)) fs.writeFileSync(this.#libraryPath, KiwixServer.#empty);
|
||||
}
|
||||
|
||||
#assertRunning() {
|
||||
@@ -62,15 +69,22 @@ export class KiwixServer {
|
||||
|
||||
/** Reads library.xml from disk if we own the server, or over HTTP if attached to a remote one. */
|
||||
async #fetchLibraryXml() {
|
||||
if (this.#remote) return (await fetch(`${this.#remote}/library.xml`).catch(() => null))?.text?.() ?? '';
|
||||
return fs.promises.readFile(this.#libraryPath, 'utf8').catch(() => '');
|
||||
if (!this.#remote) return fs.promises.readFile(this.#libraryPath, 'utf8').catch(() => '');
|
||||
try {
|
||||
const res = await fetch(`${this.#remote}/library.xml`);
|
||||
return res.ok ? await res.text() : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/** Rebuilds library.xml from scratch by scanning `dir` for .zim files - no-op if attached to a remote server. */
|
||||
async #rebuildLibrary() {
|
||||
if (this.#remote) return;
|
||||
await fs.promises.rm(this.#libraryPath, {force: true});
|
||||
for (const f of await this.#zimFiles()) await execFileAsync(this.#bin('kiwix-manage'), [this.#libraryPath, 'add', path.join(this.#dir, f)]);
|
||||
const files = await this.#zimFiles();
|
||||
if (!files.length) return fs.promises.writeFile(this.#libraryPath, KiwixServer.#empty);
|
||||
for (const f of files) await execFileAsync(this.#bin('kiwix-manage'), [this.#libraryPath, 'add', path.join(this.#dir, f)]);
|
||||
}
|
||||
|
||||
async #waitUntilReady() {
|
||||
@@ -134,6 +148,7 @@ export class KiwixServer {
|
||||
async list() {
|
||||
this.#assertRunning();
|
||||
const xml = await this.#fetchLibraryXml();
|
||||
if (!xml) return [];
|
||||
const entries = fromXml(xml);
|
||||
return (entries?.library?.book || []).map(e => {
|
||||
const tags = e.tags.split(';');
|
||||
@@ -180,30 +195,23 @@ export class KiwixServer {
|
||||
return {mimetype: res.headers.get('content-type'), data: Buffer.from(await res.arrayBuffer())};
|
||||
}
|
||||
|
||||
/**
|
||||
* Two-pass fulltext search across every local ZIM: xapian prefilter (kiwix-serve's
|
||||
* own index), then fuzzy-reranked by title so the strongest matches surface first.
|
||||
* Returns a flat array matching the catalog/list shape: {id, title, name, category, ..., href, score}
|
||||
*/
|
||||
/** Fulltext search across every local ZIM via kiwix-serve's own xapian index */
|
||||
async search(terms, limit = 20) {
|
||||
this.#assertRunning();
|
||||
const termList = String(terms).split(',').map(t => t.trim()).filter(Boolean);
|
||||
const termList = String(terms).split(/[,\s]+/).map(t => t.trim()).filter(Boolean);
|
||||
if (!termList.length) return [];
|
||||
|
||||
const params = new URLSearchParams({pattern: termList.join(' '), format: 'xml', pageLength: String(limit)});
|
||||
const res = await fetch(`${this.baseUrl}/search?${params}`);
|
||||
if (!res.ok) return [];
|
||||
|
||||
const xml = await res.text();
|
||||
let found = fromXml(xml);
|
||||
found = found?.rss?.channel?.item || [];
|
||||
|
||||
const found = fromXml(await res.text())?.rss?.channel?.item || [];
|
||||
const books = await this.list();
|
||||
const bookMap = new Map(books.map(b => [b.title, b]));
|
||||
|
||||
const enriched = found.map(hit => {
|
||||
return found.map(hit => {
|
||||
const book = bookMap.get(hit.book.title);
|
||||
if(!book) return null;
|
||||
if (!book) return null;
|
||||
const prefix = `/content/${book.href}/`;
|
||||
const page = hit.link.startsWith(prefix) ? hit.link.slice(prefix.length) : hit.link.replace(/^\/+/, '');
|
||||
return {
|
||||
@@ -216,10 +224,8 @@ export class KiwixServer {
|
||||
icon: book.icon,
|
||||
viewer: this.baseUrl + hit.link,
|
||||
summary: hit.description,
|
||||
score: weightedScore(hit.title, termList) + weightedScore(hit.description, termList),
|
||||
score: +hit.score || 0,
|
||||
};
|
||||
}).filter(hit => !!hit && hit.score > 0);
|
||||
|
||||
return enriched.toSorted((a, b) => b.score - a.score).slice(0, limit);
|
||||
}).filter(Boolean);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,10 +40,3 @@ export function fuzzyMatch(target, ...terms) {
|
||||
similarities,
|
||||
};
|
||||
}
|
||||
|
||||
export function weightedScore(text, termList) {
|
||||
if (!text) return 0;
|
||||
const covered = termList.reduce((sum, t) => sum + t.length, 0);
|
||||
const coverage = Math.min(1, covered / text.length);
|
||||
return fuzzyMatch(text, ...termList).max * coverage;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user