@abraca/wiki 2.27.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abracadabra-wiki.esm.js","names":["u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H"],"sources":["../src/parser.ts","../src/wikipedia.ts","../src/snapshot.ts","../src/render.ts","../../../node_modules/@noble/hashes/utils.js","../../../node_modules/@noble/hashes/_md.js","../../../node_modules/@noble/hashes/_u64.js","../../../node_modules/@noble/hashes/sha2.js","../src/crypto.ts","../src/connect.ts","../src/index.ts"],"sourcesContent":["/**\n * Minimal argument parser for the `abracadabra-wiki` bin.\n *\n * Single-purpose: there is no subcommand — the first bare word is the article\n * title (`positional[0]`). Supports `key=value`, `key=\"value with spaces\"`,\n * and `--flag` / `--key=value`.\n *\n * abracadabra-wiki \"<Article Title>\" [key=value ...] [--flags]\n */\n\nexport interface ParsedArgs {\n /** Positional arguments — `positional[0]` is the article title. */\n positional: string[]\n /** Key-value parameters, e.g. `{ lang: \"en\", \"user-agent\": \"...\" }`. */\n params: Record<string, string>\n /** Boolean flags, e.g. `dry-run`, `include-categories`, `quiet`. */\n flags: Set<string>\n}\n\n/**\n * Parse CLI arguments into a structured object.\n * @param argv Raw `process.argv` (includes node path and script path).\n */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const args = argv.slice(2) // skip node + script\n const result: ParsedArgs = { positional: [], params: {}, flags: new Set() }\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]\n\n // --flag or --key=value\n if (arg.startsWith('--')) {\n const stripped = arg.slice(2)\n const eqIdx = stripped.indexOf('=')\n if (eqIdx !== -1) {\n result.params[stripped.slice(0, eqIdx)] = stripped.slice(eqIdx + 1)\n } else {\n result.flags.add(stripped)\n }\n continue\n }\n\n // key=value pair\n const eqIdx = arg.indexOf('=')\n if (eqIdx > 0) {\n const key = arg.slice(0, eqIdx)\n let value = arg.slice(eqIdx + 1)\n // Strip surrounding quotes if present\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1)\n }\n result.params[key] = value\n continue\n }\n\n // Every bare word is positional (no subcommand for this single-purpose bin).\n result.positional.push(arg)\n }\n\n return result\n}\n","/**\n * Rate-limited wrapper around wtf_wikipedia + wtf-plugin-api.\n *\n * Responsibilities:\n * - Throttle requests to respect Wikimedia API etiquette\n * - Cache parsed Documents by canonical title\n * - Resolve redirects so callers always see the redirect target\n * - Expose getCategoryPages via wtf-plugin-api\n */\n// @ts-ignore — wtf_wikipedia ships its own types but they are imprecise; we\n// cast Link/Section APIs as needed below.\nimport wtf from 'wtf_wikipedia'\n// @ts-ignore — wtf-plugin-api is JS-only with no types; treat as opaque.\nimport wtfApiPlugin from 'wtf-plugin-api'\n\n// Augment wtf at module load so getCategoryPages becomes available.\nlet pluginExtended = false\nfunction ensurePlugin(): void {\n if (pluginExtended) return\n // @ts-ignore — extend is dynamically attached to the wtf default export.\n wtf.extend(wtfApiPlugin)\n pluginExtended = true\n}\n\nexport interface WikipediaClientConfig {\n lang: string\n domain?: string\n userAgent: string\n /** Max requests per second. */\n rate: number\n}\n\ninterface FetchOpts {\n lang?: string\n domain?: string\n 'Api-User-Agent'?: string\n follow_redirects?: boolean\n}\n\n/** A token-bucket-ish throttle: at most `rate` calls per second, FIFO. */\nclass RateLimiter {\n private lastTickMs = 0\n constructor(private intervalMs: number) {}\n\n async wait(): Promise<void> {\n const now = Date.now()\n const earliest = this.lastTickMs + this.intervalMs\n if (now < earliest) {\n await new Promise((r) => setTimeout(r, earliest - now))\n }\n this.lastTickMs = Math.max(now, earliest)\n }\n}\n\nexport class WikipediaClient {\n private cache = new Map<string, any>()\n private redirects = new Map<string, string>()\n private limiter: RateLimiter\n private fetchOpts: FetchOpts\n\n constructor(private config: WikipediaClientConfig) {\n ensurePlugin()\n this.limiter = new RateLimiter(Math.max(50, Math.floor(1000 / Math.max(0.1, config.rate))))\n this.fetchOpts = {\n lang: config.lang,\n 'Api-User-Agent': config.userAgent,\n follow_redirects: true,\n }\n if (config.domain) this.fetchOpts.domain = config.domain\n }\n\n /**\n * Fetch and parse a Wikipedia article.\n * - Returns the cached Document if we've seen this title before.\n * - Follows redirects and caches under both source and target titles.\n * - Returns null when the page does not exist.\n */\n async fetchArticle(rawTitle: string): Promise<any | null> {\n const title = canonicalTitle(rawTitle)\n if (this.cache.has(title)) return this.cache.get(title)\n if (this.redirects.has(title)) {\n const target = this.redirects.get(title)!\n return this.cache.get(target) ?? null\n }\n\n await this.limiter.wait()\n let doc: any\n try {\n doc = await (wtf as any).fetch(title, this.fetchOpts)\n } catch (err: any) {\n throw new Error(`Wikipedia fetch failed for \"${title}\": ${err?.message ?? err}`)\n }\n if (!doc) return null\n\n // wtf usually follows redirects automatically when follow_redirects=true,\n // but defensively handle the case where it surfaces a redirect doc.\n if (typeof doc.isRedirect === 'function' && doc.isRedirect()) {\n const target = doc.redirectTo?.()?.page\n if (typeof target === 'string') {\n this.redirects.set(title, canonicalTitle(target))\n const inner = await this.fetchArticle(target)\n return inner\n }\n }\n\n const resolvedTitle = canonicalTitle(doc.title?.() ?? title)\n this.cache.set(resolvedTitle, doc)\n if (resolvedTitle !== title) this.redirects.set(title, resolvedTitle)\n return doc\n }\n\n /**\n * Fetch the member pages of a category (and optionally sub-categories).\n * @param category Category title (with or without \"Category:\" prefix).\n * @param recursive Whether to traverse sub-categories.\n * @param maxDepth Recursion depth when recursive=true.\n */\n async fetchCategoryPages(\n category: string,\n recursive: boolean,\n maxDepth: number,\n ): Promise<Array<{ title: string; type: 'page' | 'subcat' }>> {\n await this.limiter.wait()\n const opts: Record<string, unknown> = {\n lang: this.config.lang,\n 'Api-User-Agent': this.config.userAgent,\n recursive,\n maxDepth,\n }\n if (this.config.domain) opts.domain = this.config.domain\n // @ts-ignore — getCategoryPages is attached at runtime via wtf.extend.\n const list: any[] = await wtf.getCategoryPages(category, opts)\n return (list ?? []).map((m) => ({\n title: canonicalTitle(m.title),\n type: m.type === 'subcat' ? 'subcat' : 'page',\n }))\n }\n}\n\n/** Normalize a Wikipedia title — trim, collapse spaces, strip leading/trailing colons. */\nexport function canonicalTitle(s: string): string {\n return (s ?? '').toString().replace(/_/g, ' ').replace(/\\s+/g, ' ').trim()\n}\n\n/** Detect a category-namespaced title. */\nconst CATEGORY_PREFIX = /^(Category|Catégorie|Kategorie|Categoría|Categoria|Categorie|Kategoria):/i\nexport function isCategoryTitle(title: string): boolean {\n return CATEGORY_PREFIX.test(title)\n}\n\n/** Strip the \"Category:\" prefix for display. */\nexport function stripCategoryPrefix(title: string): string {\n return title.replace(CATEGORY_PREFIX, '').trim()\n}\n","/**\n * Snapshot a wtf_wikipedia Document into a plain-data shape that's easy to\n * work with downstream. No BFS / no plan-building here — just a pure read\n * of one parsed page.\n */\nimport type { ExtractedArticle, ExtractedSection } from './types.ts'\nimport { canonicalTitle, isCategoryTitle, stripCategoryPrefix } from './wikipedia.ts'\n\nexport { canonicalTitle, isCategoryTitle, stripCategoryPrefix }\n\nexport function snapshotArticle(doc: any, title: string): ExtractedArticle {\n return {\n title,\n linkTitles: collectLinkTitles(doc),\n categories: collectCategories(doc),\n sections: snapshotSections(doc.sections?.() ?? []),\n infobox: snapshotInfobox(doc.infobox?.()),\n lead: leadParagraph(doc),\n url: typeof doc.url === 'function' ? doc.url() : null,\n }\n}\n\nexport function prettyCategoryLabel(catTitle: string): string {\n return stripCategoryPrefix(catTitle)\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Link / category extraction\n// ─────────────────────────────────────────────────────────────────────────\n\nfunction collectLinkTitles(doc: any): string[] {\n const links = doc.links?.() ?? []\n const out = new Set<string>()\n for (const l of links) {\n if (!l) continue\n const page = typeof l.page === 'function' ? l.page() : null\n if (typeof page !== 'string' || page.length === 0) continue\n if (isCategoryTitle(page)) continue\n out.add(canonicalTitle(page))\n }\n return [...out]\n}\n\nfunction collectCategories(doc: any): string[] {\n const out: string[] = []\n for (const c of (doc.categories?.() as string[] | undefined) ?? []) {\n const norm = canonicalTitle(c)\n if (norm) out.push(norm)\n }\n return out\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Sections — flatten wtf's parent-child references into a real tree\n// ─────────────────────────────────────────────────────────────────────────\n\nfunction snapshotSections(rawSections: any[]): ExtractedSection[] {\n const all = rawSections.map((s) => ({\n raw: s,\n title: s.title?.() || '',\n parentRef: typeof s.parent === 'function' ? s.parent() : null,\n children: [] as ExtractedSection[],\n }))\n\n const byRaw = new Map<any, (typeof all)[number]>()\n for (const s of all) byRaw.set(s.raw, s)\n\n const roots: (typeof all)[number][] = []\n for (const s of all) {\n if (s.parentRef && byRaw.has(s.parentRef)) {\n byRaw.get(s.parentRef)!.children.push(materialize(s))\n } else {\n roots.push(s)\n }\n }\n return roots.map(materialize)\n}\n\nfunction materialize(node: {\n raw: any\n title: string\n children: ExtractedSection[]\n}): ExtractedSection {\n const lists = node.raw.lists?.() ?? []\n const paragraphs = node.raw.paragraphs?.() ?? []\n\n let listLength = 0\n for (const l of lists) {\n const lines = l.lines?.() ?? []\n listLength += lines.length\n }\n const isList =\n lists.length > 0 && (paragraphs.length === 0 || listLength >= paragraphs.length * 2)\n\n const bodyParts: string[] = []\n for (const p of paragraphs) {\n const md = paragraphMarkdown(p)\n if (md) bodyParts.push(md)\n }\n for (const l of lists) {\n const lines = (l.lines?.() ?? []) as any[]\n for (const line of lines) {\n const text = lineText(line)\n if (text) bodyParts.push(`- ${text}`)\n }\n }\n\n return {\n title: node.title,\n body: bodyParts.join('\\n\\n'),\n isList,\n listLength,\n children: node.children,\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Infobox\n// ─────────────────────────────────────────────────────────────────────────\n\nfunction snapshotInfobox(box: any | null | undefined): Array<{ key: string; value: string }> | undefined {\n if (!box) return undefined\n const data = typeof box.json === 'function' ? box.json() : null\n if (!data || typeof data !== 'object') return undefined\n const rows: Array<{ key: string; value: string }> = []\n for (const [key, val] of Object.entries(data)) {\n const value = stringifyInfoboxValue(val)\n if (!value) continue\n rows.push({ key: humanKey(key), value })\n }\n return rows.length > 0 ? rows : undefined\n}\n\nfunction stringifyInfoboxValue(val: unknown): string {\n if (val == null) return ''\n if (typeof val === 'string') return val\n if (typeof val === 'number' || typeof val === 'boolean') return String(val)\n if (Array.isArray(val)) {\n return val.map(stringifyInfoboxValue).filter(Boolean).join(', ')\n }\n if (typeof val === 'object') {\n const o = val as Record<string, unknown>\n if (typeof o.text === 'string') return o.text\n if (typeof o.number === 'number') return String(o.number)\n }\n return ''\n}\n\nfunction humanKey(k: string): string {\n return k.replace(/_/g, ' ').replace(/^./, (m) => m.toUpperCase())\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Markdown rendering\n// ─────────────────────────────────────────────────────────────────────────\n\nfunction leadParagraph(doc: any): string {\n const paras = doc.paragraphs?.() ?? []\n const first = paras[0]\n if (!first) return ''\n return paragraphMarkdown(first)\n}\n\n/**\n * Render a paragraph as markdown, replacing internal links with `[[Title]]`.\n * The streaming orchestrator's link rewriter later swaps `[[Title]]` →\n * `[[docId|label]]` once IDs are known.\n */\nfunction paragraphMarkdown(paragraph: any): string {\n const sentences = paragraph.sentences?.() ?? []\n const out: string[] = []\n for (const s of sentences) {\n out.push(sentenceWithWikilinks(s))\n }\n return out.join(' ').trim()\n}\n\nfunction sentenceWithWikilinks(sentence: any): string {\n const text: string = (sentence.text?.() ?? '').toString()\n const links = sentence.links?.() ?? []\n if (links.length === 0) return text\n\n let result = text\n const replacements = links\n .map((l: any) => {\n const page = typeof l.page === 'function' ? l.page() : null\n const display = typeof l.text === 'function' ? l.text() : null\n if (typeof page !== 'string' || page.length === 0) return null\n if (isCategoryTitle(page)) return null\n const shown = (display && display.length > 0 ? display : page) as string\n return { page: canonicalTitle(page), shown }\n })\n .filter((x: any): x is { page: string; shown: string } => x !== null)\n .sort((a: any, b: any) => b.shown.length - a.shown.length)\n\n for (const { page, shown } of replacements) {\n if (!result.includes(shown)) continue\n const replacement = shown === page ? `[[${page}]]` : `[[${page}|${shown}]]`\n result = result.replace(shown, replacement)\n }\n return result\n}\n\nfunction lineText(line: any): string {\n if (!line) return ''\n if (typeof line === 'string') return line\n if (typeof line.text === 'string') return line.text\n if (typeof line.text === 'function') return line.text()\n return ''\n}\n","/**\n * Body rendering + page-type decisions for the streaming orchestrator.\n *\n * All rendering is title-driven: bodies are rendered with `[[Title]]`\n * placeholders, and `rewriteLinks` rewrites them to `[[docId|label]]`\n * using the live title→docId map at write time.\n */\nimport type { ExtractedArticle, ExtractedSection } from './types.ts'\n\nexport const ICONS = {\n graph: 'git-fork',\n article: 'book-open',\n category: 'tag',\n infobox: 'info',\n outline: 'list',\n gallery: 'images',\n section: 'pilcrow',\n categories: 'tags',\n} as const\n\n/** Decide a page type for a section based on its shape. */\nexport function pickSectionType(section: ExtractedSection): { type: string; icon: string } {\n if (section.children.length > 0) return { type: 'outline', icon: ICONS.outline }\n if (section.isList && section.listLength >= 5) return { type: 'outline', icon: ICONS.outline }\n return { type: 'doc', icon: ICONS.section }\n}\n\n/** Render the lead paragraph as the article-doc body. */\nexport function renderArticleLead(article: ExtractedArticle): string {\n return article.lead ?? ''\n}\n\n/** Render the article as a single doc, sections + infobox inlined. */\nexport function renderArticleSingleDoc(article: ExtractedArticle): string {\n const parts: string[] = []\n if (article.lead) parts.push(article.lead)\n if (article.infobox && article.infobox.length > 0) {\n parts.push('## Infobox', renderInfoboxBody(article.infobox))\n }\n for (const section of article.sections) {\n parts.push(...renderSectionInline(section, 2))\n }\n return parts.join('\\n\\n')\n}\n\nfunction renderSectionInline(section: ExtractedSection, level: number): string[] {\n const out: string[] = []\n const prefix = '#'.repeat(Math.min(6, level))\n if (section.title) out.push(`${prefix} ${section.title}`)\n if (section.body.trim()) out.push(section.body)\n for (const child of section.children) {\n out.push(...renderSectionInline(child, level + 1))\n }\n return out\n}\n\nexport function renderInfoboxBody(rows: Array<{ key: string; value: string }>): string {\n return rows.map((r) => `- **${r.key}:** ${r.value}`).join('\\n')\n}\n\nexport function renderCategoryBody(members: string[], subcategories: string[]): string {\n const parts: string[] = []\n if (members.length > 0) {\n parts.push('## Pages')\n parts.push(members.map((m) => `- [[${m}]]`).join('\\n'))\n }\n if (subcategories.length > 0) {\n parts.push('## Sub-categories')\n parts.push(subcategories.map((s) => `- ${s}`).join('\\n'))\n }\n return parts.join('\\n\\n')\n}\n\n/**\n * Replace `[[Title]]` / `[[Title|Alias]]` in markdown with\n * `[[docId|label]]` using the title→docId map. Unresolved titles fall\n * back to plain text (their alias or original title).\n */\nexport function rewriteLinks(\n markdown: string,\n titleToDocId: Map<string, string>,\n): string {\n const re = /\\[\\[([^\\]|]+?)(?:\\|([^\\]]+?))?\\]\\]/g\n return markdown.replace(re, (_match, target: string, alias?: string) => {\n const title = target.trim()\n const docId = titleToDocId.get(title)\n const display = (alias && alias.trim().length > 0 ? alias : title).trim()\n if (!docId) return display\n return `[[${docId}|${display}]]`\n })\n}\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n }\n return value;\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1)\n throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1)\n throw new Error('\"blockLen\" must be >= 1');\n}\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async () => { };\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n//# sourceMappingURL=sha2.js.map","/**\n * Ed25519 key generation, persistence, and challenge signing for CLI auth.\n * Mirrors @abraca/mcp/src/crypto.ts — standalone to avoid MCP SDK dependency.\n */\nimport * as ed from '@noble/ed25519'\nimport { sha512 } from '@noble/hashes/sha2.js'\nimport { readFile, writeFile, mkdir } from 'node:fs/promises'\n\n// @noble/ed25519 v3 hash hook\ned.hashes.sha512 = sha512\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m))\nimport { existsSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join, dirname } from 'node:path'\n\nconst DEFAULT_KEY_PATH = join(homedir(), '.abracadabra', 'cli.key')\n\nfunction toBase64url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url')\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n return new Uint8Array(Buffer.from(b64, 'base64url'))\n}\n\nexport interface CLIKeypair {\n privateKey: Uint8Array\n publicKeyB64: string\n}\n\n/**\n * Load an existing Ed25519 keypair from disk, or generate and persist a new one.\n * The file stores the raw 32-byte private key seed.\n */\nexport async function loadOrCreateKeypair(keyPath?: string): Promise<CLIKeypair> {\n const path = keyPath || DEFAULT_KEY_PATH\n\n if (existsSync(path)) {\n const seed = await readFile(path)\n if (seed.length !== 32) {\n throw new Error(`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`)\n }\n const privateKey = new Uint8Array(seed)\n const publicKey = ed.getPublicKey(privateKey)\n return { privateKey, publicKeyB64: toBase64url(publicKey) }\n }\n\n // Generate new keypair\n const privateKey = ed.utils.randomSecretKey()\n const publicKey = ed.getPublicKey(privateKey)\n\n // Ensure directory exists and write seed with restricted permissions\n const dir = dirname(path)\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true, mode: 0o700 })\n }\n await writeFile(path, Buffer.from(privateKey), { mode: 0o600 })\n\n console.error(`[abracadabra] Generated new keypair at ${path}`)\n console.error(`[abracadabra] Public key: ${toBase64url(publicKey)}`)\n\n return { privateKey, publicKeyB64: toBase64url(publicKey) }\n}\n\n/** Sign a base64url challenge with the private key; returns base64url signature. */\nexport function signChallenge(challengeB64: string, privateKey: Uint8Array): string {\n const challenge = fromBase64url(challengeB64)\n const sig = ed.sign(challenge, privateKey)\n return toBase64url(sig)\n}\n","/**\n * Open a DocumentManager session for the wiki command, mirroring the\n * auth/register flow that CLIConnection uses but using the modern public API.\n *\n * Reuses the CLI's Ed25519 keypair handling (loadOrCreateKeypair, signChallenge)\n * so the wiki command authenticates with the same identity as every other\n * subcommand.\n */\nimport { DocumentManager } from '@abraca/dabra'\nimport { loadOrCreateKeypair, signChallenge } from './crypto.ts'\n\nexport interface OpenSessionConfig {\n url: string\n name?: string\n color?: string\n inviteCode?: string\n keyFile?: string\n /** Suppress informational stderr logging. */\n quiet?: boolean\n}\n\nexport interface OpenSessionResult {\n dm: DocumentManager\n /** Active root doc id (the entry-point space). */\n rootDocId: string\n}\n\nexport async function openSession(config: OpenSessionConfig): Promise<OpenSessionResult> {\n const keypair = await loadOrCreateKeypair(config.keyFile)\n const sign = (challenge: string) => Promise.resolve(signChallenge(challenge, keypair.privateKey))\n\n const dm = new DocumentManager({\n url: config.url,\n name: config.name ?? 'Wiki Extractor',\n color: config.color,\n quiet: config.quiet,\n })\n\n // Authenticate first; register on first run.\n try {\n await dm.client.loginWithKey(keypair.publicKeyB64, sign)\n } catch (err: any) {\n const status = err?.status ?? err?.response?.status\n if (status === 404 || status === 422) {\n if (!config.quiet) {\n console.error('[abracadabra] Key not registered, creating new account...')\n }\n await dm.client.registerWithKey({\n publicKey: keypair.publicKeyB64,\n username: (config.name ?? 'wiki-extractor').replace(/\\s+/g, '-').toLowerCase(),\n displayName: config.name ?? 'Wiki Extractor',\n deviceName: 'CLI Wiki',\n inviteCode: config.inviteCode,\n })\n await dm.client.loginWithKey(keypair.publicKeyB64, sign)\n } else {\n throw err\n }\n }\n\n await dm.connect()\n\n const rootDocId = dm.rootDocId\n if (!rootDocId) {\n throw new Error('Connected but no rootDocId — server has no spaces.')\n }\n\n return { dm, rootDocId }\n}\n","#!/usr/bin/env node\n/**\n * `abracadabra-wiki <title>` — fetch Wikipedia articles and seed them into the\n * active Abracadabra space as a graph of docs.\n *\n * Streaming flow (no buffering): every newly-discovered title becomes a shell\n * doc immediately (visible in the dashboard right away), then bodies are filled\n * in one fetch at a time. The user sees the tree skeleton appear before the\n * first body is written.\n *\n * Authenticates with its own Ed25519 key (`ABRA_KEY_FILE`, default\n * `~/.abracadabra/cli.key`) via the modern `DocumentManager` API — the same\n * identity the `abracadabra` CLI uses, so both tools share one account.\n *\n * Usage:\n * abracadabra-wiki \"<Article Title>\" user-agent=\"you (you@example.com)\" [options]\n *\n * Environment:\n * ABRA_URL Server URL (required unless --dry-run)\n * ABRA_KEY_FILE Ed25519 key file (~/.abracadabra/cli.key)\n * ABRA_NAME / ABRA_COLOR Presence identity\n * ABRA_INVITE_CODE Invite code for first-run registration\n * ABRA_WIKI_USER_AGENT Default Api-User-Agent (or pass user-agent=...)\n */\nimport type { DocumentManager } from '@abraca/dabra'\nimport { parseArgs, type ParsedArgs } from './parser.ts'\nimport { WikipediaClient } from './wikipedia.ts'\nimport { snapshotArticle, canonicalTitle, prettyCategoryLabel } from './snapshot.ts'\nimport {\n ICONS,\n pickSectionType,\n renderArticleLead,\n renderArticleSingleDoc,\n renderInfoboxBody,\n renderCategoryBody,\n rewriteLinks,\n} from './render.ts'\nimport { openSession } from './connect.ts'\nimport type { WikiOptions, ExtractMode, ExtractedArticle, ExtractedSection } from './types.ts'\n\nconst USAGE = [\n 'abracadabra-wiki \"<Article Title>\" user-agent=\"<name (email)>\" [options]',\n '',\n 'Options:',\n ' mode=single|split single doc per article OR split into sections+infobox [split]',\n ' depth=<n> follow internal links to depth N [1]',\n ' category-depth=<n> recurse into sub-categories [1]',\n ' lang=<code> wiki language [en]',\n ' domain=<host> 3rd-party MediaWiki host (overrides lang)',\n ' parent=<docId> parent doc for the new graph [active space root]',\n ' user-agent=<str> Api-User-Agent header (REQUIRED by Wikimedia etiquette)',\n ' rate=<rps> max wikipedia requests per second [3]',\n ' --include-categories expand each article\\'s categories into nested graphs',\n ' --dry-run fetch only the entry article, print outline, no writes',\n '',\n 'Environment: ABRA_URL (required unless --dry-run), ABRA_KEY_FILE, ABRA_NAME,',\n ' ABRA_COLOR, ABRA_INVITE_CODE, ABRA_WIKI_USER_AGENT.',\n].join('\\n')\n\n/**\n * Run a Wikipedia import for already-parsed args. Returns a human-readable\n * summary (or an error/usage string). Exported for programmatic use.\n */\nexport async function runWiki(args: ParsedArgs): Promise<string> {\n const opts = parseOptions(args)\n if (typeof opts === 'string') return opts\n\n const log = (msg: string) => {\n if (!args.flags.has('quiet') && !args.flags.has('q')) {\n console.error(`[wiki] ${msg}`)\n }\n }\n\n const wp = new WikipediaClient({\n lang: opts.lang,\n domain: opts.domain,\n userAgent: opts.userAgent,\n rate: opts.rate,\n })\n\n if (opts.dryRun) {\n // Dry-run: fetch only the entry, print its outline, no server.\n log(`fetch ${opts.title}`)\n const doc = await wp.fetchArticle(opts.title)\n if (!doc) return `Article not found: \"${opts.title}\"`\n const snap = snapshotArticle(doc, canonicalTitle(doc.title?.() ?? opts.title))\n return [\n `Entry: ${snap.title}`,\n `URL: ${snap.url ?? '(none)'}`,\n `Internal links: ${snap.linkTitles.length}`,\n `Categories: ${snap.categories.length}`,\n `Sections: ${snap.sections.length}`,\n `Has infobox: ${snap.infobox && snap.infobox.length > 0 ? 'yes' : 'no'}`,\n '',\n '── Sections ──',\n printSections(snap.sections, ''),\n ].join('\\n')\n }\n\n // ── Connect ──────────────────────────────────────────────────────────\n // process.env access uses bracket notation to satisfy noUncheckedIndexedAccess.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const env = (globalThis as any).process?.env ?? {}\n const url = env['ABRA_URL']\n if (!url) {\n return 'ABRA_URL is required to write to the server. Set it or pass --dry-run.'\n }\n const { dm } = await openSession({\n url,\n name: env['ABRA_NAME'],\n color: env['ABRA_COLOR'],\n inviteCode: env['ABRA_INVITE_CODE'],\n keyFile: env['ABRA_KEY_FILE'],\n quiet: args.flags.has('quiet') || args.flags.has('q'),\n })\n\n try {\n const result = await runStreaming(dm, wp, opts, log)\n return [\n `Done. Created ${result.articleCount} articles${\n result.categoryCount > 0 ? ` + ${result.categoryCount} categories` : ''\n }.`,\n `Root: ${result.rootDocId}`,\n ].join('\\n')\n } finally {\n await dm.destroy().catch(() => {})\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Streaming orchestrator\n// ─────────────────────────────────────────────────────────────────────────\n\ninterface StreamResult {\n rootDocId: string\n articleCount: number\n categoryCount: number\n}\n\nasync function runStreaming(\n dm: DocumentManager,\n wp: WikipediaClient,\n opts: WikiOptions,\n log: (msg: string) => void,\n): Promise<StreamResult> {\n // Title → docId map. Drives [[Title]] → [[docId|label]] rewriting at write time.\n const titleToDocId = new Map<string, string>()\n // Snapshots of articles we've already fetched (avoid re-fetching).\n const fetched = new Map<string, ExtractedArticle>()\n // Articles whose section/infobox children have been created (split mode).\n const childrenCreated = new Set<string>()\n // Categories whose shells have been created.\n const categoryToDocId = new Map<string, string>()\n let categoriesContainerId: string | null = null\n\n // ── Fetch entry first; we need its title to label the root graph ─────\n log(`fetch ${opts.title}`)\n const entryDoc = await wp.fetchArticle(opts.title)\n if (!entryDoc) {\n throw new Error(`Article not found: \"${opts.title}\"`)\n }\n const entryTitle = canonicalTitle(entryDoc.title?.() ?? opts.title)\n const entrySnap = snapshotArticle(entryDoc, entryTitle)\n fetched.set(entryTitle, entrySnap)\n\n // ── Step 1: create root graph doc (visible immediately) ──────────────\n const rootEntry = dm.tree.create({\n parentId: opts.parentDocId ?? null,\n label: entryTitle,\n type: 'graph',\n meta: { icon: ICONS.graph },\n })\n log(`+ ${rootEntry.id.slice(0, 8)}… ${entryTitle} (graph)`)\n\n // ── Step 2: create the entry article shell ───────────────────────────\n const entryArticleId = createArticleShell(dm, entrySnap, rootEntry.id, log)\n titleToDocId.set(entryTitle, entryArticleId)\n\n // Queue of (title, depth) to process. Each entry is guaranteed to have\n // a shell doc already in titleToDocId.\n const queue: Array<{ title: string; depth: number }> = [{ title: entryTitle, depth: 0 }]\n let articleCount = 0\n\n // ── Step 3: streaming process ───────────────────────────────────────\n while (queue.length > 0) {\n const { title, depth } = queue.shift()!\n const articleDocId = titleToDocId.get(title)!\n\n // Ensure we've fetched this article.\n let snap = fetched.get(title)\n if (!snap) {\n log(`fetch [d${depth}] ${title}`)\n try {\n const doc = await wp.fetchArticle(title)\n if (!doc) {\n log(` not found — leaving stub`)\n continue\n }\n snap = snapshotArticle(doc, canonicalTitle(doc.title?.() ?? title))\n fetched.set(title, snap)\n } catch (err: any) {\n log(`! fetch failed: ${err?.message ?? err}`)\n continue\n }\n }\n\n // Create this article's section/infobox children (split mode only,\n // and only once per article).\n if (opts.mode === 'split' && !childrenCreated.has(title)) {\n createArticleChildren(dm, snap, articleDocId, log)\n childrenCreated.add(title)\n }\n\n // Discover new linked titles and pre-allocate shells immediately.\n if (depth < opts.depth) {\n for (const linkTitle of snap.linkTitles) {\n if (titleToDocId.has(linkTitle)) continue\n const shell = dm.tree.create({\n parentId: rootEntry.id,\n label: linkTitle,\n type: 'doc',\n meta: { icon: ICONS.article },\n })\n titleToDocId.set(linkTitle, shell.id)\n queue.push({ title: linkTitle, depth: depth + 1 })\n log(`+ ${shell.id.slice(0, 8)}… ${linkTitle} (doc, shell)`)\n }\n }\n\n // Pre-allocate category shells when first discovered.\n if (opts.includeCategories && snap.categories.length > 0) {\n if (!categoriesContainerId) {\n const c = dm.tree.create({\n parentId: rootEntry.id,\n label: 'Categories',\n type: 'graph',\n meta: { icon: ICONS.categories },\n })\n categoriesContainerId = c.id\n log(`+ ${c.id.slice(0, 8)}… Categories (graph)`)\n }\n for (const catTitle of snap.categories) {\n if (categoryToDocId.has(catTitle)) continue\n const cat = dm.tree.create({\n parentId: categoriesContainerId,\n label: prettyCategoryLabel(catTitle),\n type: 'graph',\n meta: { icon: ICONS.category },\n })\n categoryToDocId.set(catTitle, cat.id)\n log(`+ ${cat.id.slice(0, 8)}… ${prettyCategoryLabel(catTitle)} (graph, cat)`)\n }\n }\n\n // Write this article's body NOW (links resolve to whatever shells we\n // have allocated so far — that's all of this article's links since we\n // just allocated them above).\n const body =\n opts.mode === 'split' ? renderArticleLead(snap) : renderArticleSingleDoc(snap)\n if (body.trim().length > 0) {\n const rewritten = rewriteLinks(body, titleToDocId)\n try {\n await dm.content.write(articleDocId, rewritten)\n log(`✓ body ${title}`)\n } catch (err: any) {\n log(`! body write failed for ${title}: ${err?.message ?? err}`)\n }\n }\n\n // In split mode, also write each section/infobox doc body.\n if (opts.mode === 'split') {\n await writeChildrenBodies(dm, snap, articleDocId, titleToDocId, log)\n }\n\n articleCount++\n }\n\n // ── Step 4: fill in category bodies ─────────────────────────────────\n let categoryCount = 0\n if (opts.includeCategories && categoryToDocId.size > 0) {\n for (const [catTitle, catDocId] of categoryToDocId) {\n log(`category ${catTitle}`)\n try {\n const members = await wp.fetchCategoryPages(\n catTitle,\n opts.categoryDepth > 0,\n Math.max(0, opts.categoryDepth),\n )\n const memberArticles: string[] = []\n const subcats: string[] = []\n for (const m of members) {\n if (m.type === 'subcat') subcats.push(prettyCategoryLabel(m.title))\n else memberArticles.push(m.title)\n }\n const body = renderCategoryBody(memberArticles, subcats)\n const rewritten = rewriteLinks(body, titleToDocId)\n if (rewritten.trim().length > 0) {\n await dm.content.write(catDocId, rewritten)\n log(`✓ body category ${catTitle}`)\n }\n categoryCount++\n } catch (err: any) {\n log(`! category ${catTitle}: ${err?.message ?? err}`)\n }\n }\n }\n\n return { rootDocId: rootEntry.id, articleCount, categoryCount }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Shell + body helpers\n// ─────────────────────────────────────────────────────────────────────────\n\nfunction createArticleShell(\n dm: DocumentManager,\n article: ExtractedArticle,\n parentId: string,\n log: (msg: string) => void,\n): string {\n const meta: Record<string, unknown> = { icon: ICONS.article }\n if (article.url) meta.url = article.url\n const entry = dm.tree.create({\n parentId,\n label: article.title,\n type: 'doc',\n meta,\n })\n log(`+ ${entry.id.slice(0, 8)}… ${article.title} (doc)`)\n return entry.id\n}\n\n/**\n * Create section + infobox child docs for a split-mode article. Returns nothing\n * — children get bodies written later in writeChildrenBodies.\n */\nfunction createArticleChildren(\n dm: DocumentManager,\n article: ExtractedArticle,\n articleDocId: string,\n log: (msg: string) => void,\n): void {\n if (article.infobox && article.infobox.length > 0) {\n const ib = dm.tree.create({\n parentId: articleDocId,\n label: 'Infobox',\n type: 'outline',\n meta: { icon: ICONS.infobox },\n })\n log(` + ${ib.id.slice(0, 8)}… Infobox (outline)`)\n // We attach the docId to the article object so writeChildrenBodies\n // can find it without a second tree query.\n ;(article as any)._infoboxDocId = ib.id\n }\n for (const section of article.sections) {\n createSectionShell(dm, section, articleDocId, log)\n }\n}\n\nfunction createSectionShell(\n dm: DocumentManager,\n section: ExtractedSection,\n parentDocId: string,\n log: (msg: string) => void,\n): void {\n const hasChildren = section.children.length > 0\n if (!section.body.trim() && !hasChildren) return\n const { type, icon } = pickSectionType(section)\n const entry = dm.tree.create({\n parentId: parentDocId,\n label: section.title || 'Untitled section',\n type,\n meta: { icon },\n })\n log(` + ${entry.id.slice(0, 8)}… ${entry.label} (${type})`)\n ;(section as any)._docId = entry.id\n for (const child of section.children) {\n createSectionShell(dm, child, entry.id, log)\n }\n}\n\nasync function writeChildrenBodies(\n dm: DocumentManager,\n article: ExtractedArticle,\n _articleDocId: string,\n titleToDocId: Map<string, string>,\n log: (msg: string) => void,\n): Promise<void> {\n const infoboxDocId = (article as any)._infoboxDocId as string | undefined\n if (infoboxDocId && article.infobox && article.infobox.length > 0) {\n try {\n await dm.content.write(infoboxDocId, renderInfoboxBody(article.infobox))\n } catch (err: any) {\n log(`! infobox body write failed: ${err?.message ?? err}`)\n }\n }\n for (const section of article.sections) {\n await writeSectionBody(dm, section, titleToDocId, log)\n }\n}\n\nasync function writeSectionBody(\n dm: DocumentManager,\n section: ExtractedSection,\n titleToDocId: Map<string, string>,\n log: (msg: string) => void,\n): Promise<void> {\n const docId = (section as any)._docId as string | undefined\n if (docId && section.body.trim().length > 0) {\n try {\n await dm.content.write(docId, rewriteLinks(section.body, titleToDocId))\n } catch (err: any) {\n log(`! section body write failed for ${section.title}: ${err?.message ?? err}`)\n }\n }\n for (const child of section.children) {\n await writeSectionBody(dm, child, titleToDocId, log)\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Argument parsing + dry-run printing\n// ─────────────────────────────────────────────────────────────────────────\n\nfunction parseOptions(args: ParsedArgs): WikiOptions | string {\n const title = args.positional[0]?.trim() || args.params['title']\n if (!title) return 'Missing required positional argument: <title>. Example: abracadabra-wiki \"Toronto Raptors\"'\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const env = (globalThis as any).process?.env ?? {}\n const userAgent = args.params['user-agent'] || args.params['userAgent'] || env['ABRA_WIKI_USER_AGENT']\n if (!userAgent) {\n return [\n 'Missing required parameter: user-agent=\"your-name (you@example.com)\"',\n '(Wikimedia etiquette requires an Api-User-Agent header. Pass user-agent=... or set ABRA_WIKI_USER_AGENT.)',\n ].join('\\n')\n }\n\n const mode = (args.params['mode'] ?? 'split') as ExtractMode\n if (mode !== 'single' && mode !== 'split') {\n return `Invalid mode \"${mode}\". Use mode=single or mode=split.`\n }\n\n const depth = parseIntOr(args.params['depth'], 1)\n const categoryDepth = parseIntOr(args.params['category-depth'] ?? args.params['categoryDepth'], 1)\n const rate = parseFloatOr(args.params['rate'], 3)\n\n return {\n title,\n mode,\n depth,\n categoryDepth,\n includeCategories: args.flags.has('include-categories') || args.flags.has('includeCategories'),\n lang: args.params['lang'] ?? 'en',\n domain: args.params['domain'],\n parentDocId: args.params['parent'],\n userAgent,\n rate,\n dryRun: args.flags.has('dry-run') || args.flags.has('dryRun'),\n }\n}\n\nfunction parseIntOr(s: string | undefined, fallback: number): number {\n if (!s) return fallback\n const n = Number.parseInt(s, 10)\n return Number.isFinite(n) && n >= 0 ? n : fallback\n}\n\nfunction parseFloatOr(s: string | undefined, fallback: number): number {\n if (!s) return fallback\n const n = Number.parseFloat(s)\n return Number.isFinite(n) && n > 0 ? n : fallback\n}\n\nfunction printSections(sections: ExtractedSection[], indent: string): string {\n const lines: string[] = []\n for (const s of sections) {\n const hint = s.body ? ` (${s.body.length}b)` : ''\n lines.push(`${indent}- ${s.title}${hint}${s.children.length > 0 ? ` [${s.children.length} sub]` : ''}`)\n if (s.children.length > 0) {\n lines.push(printSections(s.children, indent + ' '))\n }\n }\n return lines.join('\\n')\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Bin entry\n// ─────────────────────────────────────────────────────────────────────────\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv)\n if (\n args.flags.has('help') ||\n args.flags.has('h') ||\n (!args.positional[0]?.trim() && !args.params['title'])\n ) {\n console.log(USAGE)\n return\n }\n const output = await runWiki(args)\n if (output) console.log(output)\n}\n\nmain().catch((err) => {\n console.error(`Fatal: ${err?.message ?? err}`)\n process.exit(1)\n})\n"],"x_google_ignoreList":[4,5,6,7],"mappings":";;;;;;;;;;;;;;;AAuBA,SAAgB,UAAU,MAA4B;CACpD,MAAM,OAAO,KAAK,MAAM,EAAE;CAC1B,MAAM,SAAqB;EAAE,YAAY,EAAE;EAAE,QAAQ,EAAE;EAAE,uBAAO,IAAI,KAAK;EAAE;AAE3E,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;AAGjB,MAAI,IAAI,WAAW,KAAK,EAAE;GACxB,MAAM,WAAW,IAAI,MAAM,EAAE;GAC7B,MAAM,QAAQ,SAAS,QAAQ,IAAI;AACnC,OAAI,UAAU,GACZ,QAAO,OAAO,SAAS,MAAM,GAAG,MAAM,IAAI,SAAS,MAAM,QAAQ,EAAE;OAEnE,QAAO,MAAM,IAAI,SAAS;AAE5B;;EAIF,MAAM,QAAQ,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AK,OAAO,MAAM;AAC/C,QAAM,KAAK,GAAG,OAAO,IAAI,EAAE,QAAQ,OAAO,EAAE,SAAS,SAAS,IAAI,KAAK,EAAE,SAAS,OAAO,SAAS,KAAK;AACvG,MAAI,EAAE,SAAS,SAAS,EACtB,OAAM,KAAK,cAAc,EAAE,UAAU,SAAS,KAAK,CAAC;;AAGxD,QAAO,MAAM,KAAK,KAAK;;AAOzB,eAAe,OAAsB;CACnC,MAAM,OAAO,UAAU,QAAQ,KAAK;AACpC,KACE,KAAK,MAAM,IAAI,OAAO,IACtB,KAAK,MAAM,IAAI,IAAI,IAClB,CAAC,KAAK,WAAW,IAAI,MAAM,IAAI,CAAC,KAAK,OAAO,UAC7C;AACA,UAAQ,IAAI,MAAM;AAClB;;CAEF,MAAM,SAAS,MAAM,QAAQ,KAAK;AAClC,KAAI,OAAQ,SAAQ,IAAI,OAAO;;AAGjC,MAAM,CAAC,OAAO,QAAQ;AACpB,SAAQ,MAAM,UAAU,KAAK,WAAW,MAAM;AAC9C,SAAQ,KAAK,EAAE;EACf"}
@@ -0,0 +1,27 @@
1
+ //#region packages/wiki/src/parser.d.ts
2
+ /**
3
+ * Minimal argument parser for the `abracadabra-wiki` bin.
4
+ *
5
+ * Single-purpose: there is no subcommand — the first bare word is the article
6
+ * title (`positional[0]`). Supports `key=value`, `key="value with spaces"`,
7
+ * and `--flag` / `--key=value`.
8
+ *
9
+ * abracadabra-wiki "<Article Title>" [key=value ...] [--flags]
10
+ */
11
+ interface ParsedArgs {
12
+ /** Positional arguments — `positional[0]` is the article title. */
13
+ positional: string[];
14
+ /** Key-value parameters, e.g. `{ lang: "en", "user-agent": "..." }`. */
15
+ params: Record<string, string>;
16
+ /** Boolean flags, e.g. `dry-run`, `include-categories`, `quiet`. */
17
+ flags: Set<string>;
18
+ }
19
+ //#endregion
20
+ //#region packages/wiki/src/index.d.ts
21
+ /**
22
+ * Run a Wikipedia import for already-parsed args. Returns a human-readable
23
+ * summary (or an error/usage string). Exported for programmatic use.
24
+ */
25
+ declare function runWiki(args: ParsedArgs): Promise<string>;
26
+ //#endregion
27
+ export { runWiki };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@abraca/wiki",
3
+ "version": "2.27.0",
4
+ "description": "Wikipedia → Abracadabra importer — fetch articles into a graph of CRDT docs",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/abracadabra-wiki.cjs",
8
+ "module": "dist/abracadabra-wiki.esm.js",
9
+ "types": "dist/index.d.ts",
10
+ "bin": {
11
+ "abracadabra-wiki": "./dist/abracadabra-wiki.esm.js"
12
+ },
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "exports": {
17
+ "source": {
18
+ "import": "./src/index.ts"
19
+ },
20
+ "default": {
21
+ "import": "./dist/abracadabra-wiki.esm.js",
22
+ "require": "./dist/abracadabra-wiki.cjs",
23
+ "types": "./dist/index.d.ts"
24
+ }
25
+ },
26
+ "files": [
27
+ "src",
28
+ "dist"
29
+ ],
30
+ "dependencies": {
31
+ "@noble/ed25519": "^3.1.0",
32
+ "@noble/hashes": "^2.2.0",
33
+ "wtf-plugin-api": "^2.0.1",
34
+ "wtf_wikipedia": "^10.4.1"
35
+ },
36
+ "peerDependencies": {
37
+ "@abraca/dabra": ">=2.0.0",
38
+ "y-protocols": "^1.0.6",
39
+ "yjs": "^13.6.8"
40
+ },
41
+ "devDependencies": {
42
+ "@abraca/dabra": "2.27.0"
43
+ }
44
+ }
package/src/connect.ts ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Open a DocumentManager session for the wiki command, mirroring the
3
+ * auth/register flow that CLIConnection uses but using the modern public API.
4
+ *
5
+ * Reuses the CLI's Ed25519 keypair handling (loadOrCreateKeypair, signChallenge)
6
+ * so the wiki command authenticates with the same identity as every other
7
+ * subcommand.
8
+ */
9
+ import { DocumentManager } from '@abraca/dabra'
10
+ import { loadOrCreateKeypair, signChallenge } from './crypto.ts'
11
+
12
+ export interface OpenSessionConfig {
13
+ url: string
14
+ name?: string
15
+ color?: string
16
+ inviteCode?: string
17
+ keyFile?: string
18
+ /** Suppress informational stderr logging. */
19
+ quiet?: boolean
20
+ }
21
+
22
+ export interface OpenSessionResult {
23
+ dm: DocumentManager
24
+ /** Active root doc id (the entry-point space). */
25
+ rootDocId: string
26
+ }
27
+
28
+ export async function openSession(config: OpenSessionConfig): Promise<OpenSessionResult> {
29
+ const keypair = await loadOrCreateKeypair(config.keyFile)
30
+ const sign = (challenge: string) => Promise.resolve(signChallenge(challenge, keypair.privateKey))
31
+
32
+ const dm = new DocumentManager({
33
+ url: config.url,
34
+ name: config.name ?? 'Wiki Extractor',
35
+ color: config.color,
36
+ quiet: config.quiet,
37
+ })
38
+
39
+ // Authenticate first; register on first run.
40
+ try {
41
+ await dm.client.loginWithKey(keypair.publicKeyB64, sign)
42
+ } catch (err: any) {
43
+ const status = err?.status ?? err?.response?.status
44
+ if (status === 404 || status === 422) {
45
+ if (!config.quiet) {
46
+ console.error('[abracadabra] Key not registered, creating new account...')
47
+ }
48
+ await dm.client.registerWithKey({
49
+ publicKey: keypair.publicKeyB64,
50
+ username: (config.name ?? 'wiki-extractor').replace(/\s+/g, '-').toLowerCase(),
51
+ displayName: config.name ?? 'Wiki Extractor',
52
+ deviceName: 'CLI Wiki',
53
+ inviteCode: config.inviteCode,
54
+ })
55
+ await dm.client.loginWithKey(keypair.publicKeyB64, sign)
56
+ } else {
57
+ throw err
58
+ }
59
+ }
60
+
61
+ await dm.connect()
62
+
63
+ const rootDocId = dm.rootDocId
64
+ if (!rootDocId) {
65
+ throw new Error('Connected but no rootDocId — server has no spaces.')
66
+ }
67
+
68
+ return { dm, rootDocId }
69
+ }
package/src/crypto.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Ed25519 key generation, persistence, and challenge signing for CLI auth.
3
+ * Mirrors @abraca/mcp/src/crypto.ts — standalone to avoid MCP SDK dependency.
4
+ */
5
+ import * as ed from '@noble/ed25519'
6
+ import { sha512 } from '@noble/hashes/sha2.js'
7
+ import { readFile, writeFile, mkdir } from 'node:fs/promises'
8
+
9
+ // @noble/ed25519 v3 hash hook
10
+ ed.hashes.sha512 = sha512
11
+ ed.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m))
12
+ import { existsSync } from 'node:fs'
13
+ import { homedir } from 'node:os'
14
+ import { join, dirname } from 'node:path'
15
+
16
+ const DEFAULT_KEY_PATH = join(homedir(), '.abracadabra', 'cli.key')
17
+
18
+ function toBase64url(bytes: Uint8Array): string {
19
+ return Buffer.from(bytes).toString('base64url')
20
+ }
21
+
22
+ function fromBase64url(b64: string): Uint8Array {
23
+ return new Uint8Array(Buffer.from(b64, 'base64url'))
24
+ }
25
+
26
+ export interface CLIKeypair {
27
+ privateKey: Uint8Array
28
+ publicKeyB64: string
29
+ }
30
+
31
+ /**
32
+ * Load an existing Ed25519 keypair from disk, or generate and persist a new one.
33
+ * The file stores the raw 32-byte private key seed.
34
+ */
35
+ export async function loadOrCreateKeypair(keyPath?: string): Promise<CLIKeypair> {
36
+ const path = keyPath || DEFAULT_KEY_PATH
37
+
38
+ if (existsSync(path)) {
39
+ const seed = await readFile(path)
40
+ if (seed.length !== 32) {
41
+ throw new Error(`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`)
42
+ }
43
+ const privateKey = new Uint8Array(seed)
44
+ const publicKey = ed.getPublicKey(privateKey)
45
+ return { privateKey, publicKeyB64: toBase64url(publicKey) }
46
+ }
47
+
48
+ // Generate new keypair
49
+ const privateKey = ed.utils.randomSecretKey()
50
+ const publicKey = ed.getPublicKey(privateKey)
51
+
52
+ // Ensure directory exists and write seed with restricted permissions
53
+ const dir = dirname(path)
54
+ if (!existsSync(dir)) {
55
+ await mkdir(dir, { recursive: true, mode: 0o700 })
56
+ }
57
+ await writeFile(path, Buffer.from(privateKey), { mode: 0o600 })
58
+
59
+ console.error(`[abracadabra] Generated new keypair at ${path}`)
60
+ console.error(`[abracadabra] Public key: ${toBase64url(publicKey)}`)
61
+
62
+ return { privateKey, publicKeyB64: toBase64url(publicKey) }
63
+ }
64
+
65
+ /** Sign a base64url challenge with the private key; returns base64url signature. */
66
+ export function signChallenge(challengeB64: string, privateKey: Uint8Array): string {
67
+ const challenge = fromBase64url(challengeB64)
68
+ const sig = ed.sign(challenge, privateKey)
69
+ return toBase64url(sig)
70
+ }