wiki-graph 0.6.0 → 0.7.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.
package/dist/gc-worker.js CHANGED
@@ -3,28 +3,28 @@ import { fileURLToPath as __WIKIGRAPH_FILE_URL_TO_PATH__ } from "url";
3
3
  import { resolve as __WIKIGRAPH_RESOLVE__ } from "path";
4
4
  globalThis.__WIKIGRAPH_CLI_DIST_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL(".", import.meta.url)));
5
5
  globalThis.__WIKIGRAPH_DATA_DIR__ ??= __WIKIGRAPH_RESOLVE__(__WIKIGRAPH_FILE_URL_TO_PATH__(new URL("./data", import.meta.url)));
6
- var _y=Object.defineProperty;var i=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ty=(e,t)=>{for(var n in t)_y(e,n,{get:t[n],enumerable:!0})};async function Q(e){let t=await e.read({encoding:"utf8"});return typeof t=="string"?t:new TextDecoder().decode(t)}async function V(e,t){let n=await e.openWriter();try{await n.write(t),await n.commit()}catch(r){throw await n.abort().catch(()=>{}),r}}async function pe(e){if(G(e)){let t=0;for(let n of await e.list())t+=await pe(n);return t}return e.getSize===void 0?e.size??0:await e.getSize()}async function Le(e){return e.getLastModified===void 0?e.lastModified:await e.getLastModified()}function G(e){return"list"in e}var ic=i(()=>{"use strict"});function Ci(e){Ht=e}function L(){if(Ht===void 0)throw new Error("No WikiGraph runtime platform has been installed. Provide a runtime adapter before using wiki-graph-core.");return Ht}async function he(e){if(typeof e!="string")return e;let t=await L().resources.getFile(e);if(t===void 0)throw new Error("Host file is unavailable");return t}async function K(e,t){let n=t.replaceAll("\\","/").split("/").filter(Boolean);if(n.some(o=>o==="."||o===".."))throw new TypeError(`Directory path must remain relative: ${t}`);let r=n.pop();if(!r)return;let a=e;for(let o of n){let s=await a.getDirectory(o);if(!s)return;a=s}return await a.getFile(r)}async function q(e,t){let n=ac(t),r=e;for(let a of n){let o=await r.getDirectory(a);if(o!==void 0){r=o;continue}try{r=await r.createDirectory(a)}catch(s){let c=await r.getDirectory(a);if(c===void 0)throw s;r=c}}return r}async function j(e,t){let n=ac(t),r=n.pop();if(!r)throw new TypeError("File name must remain relative");let a=await q(e,n.join("/")),o=await a.getFile(r);if(o!==void 0)return o;try{return await a.createFile(r)}catch(s){let c=await a.getFile(r);if(c!==void 0)return c;throw s}}function ac(e){let t=e.replaceAll("\\","/");if(t.startsWith("/"))throw new TypeError(`Directory path must remain relative: ${e}`);let n=t.split("/").filter(Boolean);if(n.some(r=>r==="."||r===".."))throw new TypeError(`Directory path must remain relative: ${e}`);return n}function Ai(e){sc=e}async function Pi(e,t){return e===void 0?await t():await oc.run(e,t)}function I(){let e=oc.getStore()??sc;if(e===void 0)throw new Error("No WikiGraph storage roots have been configured. Pass storage to WikiGraph or install process-default storage.");return e}var Ht,Ti,oc,sc,p=i(()=>{"use strict";ic();Ti=class{#e;#t;run(t,n){let r=this.#n();if(r!==void 0)return r.run(t,n);let a=this.#t;this.#t=t;try{return n()}finally{this.#t=a}}enterWith(t){let n=this.#n();n!==void 0?n.enterWith(t):this.#t=t}getStore(){return this.#n()?.getStore()??this.#t}#n(){if(this.#e!==void 0)return this.#e;if(Ht!==void 0)return this.#e=Ht.asyncContext.create(),this.#t!==void 0&&(this.#e.enterWith(this.#t),this.#t=void 0),this.#e}},oc=new Ti});function cc(e){if(Ay.test(e))throw new Error(`invalid template name ${e}`);let n=e.replace(Py,"").replace(Cy,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${e}`);return`${n}.jinja`}var Cy,Ay,Py,$t=i(()=>{"use strict";p();Cy=/\.jinja$/iu,Ay=/^\.+\//u,Py=/^\/+/u});var Re=i(()=>{"use strict"});function Ic(e){return new TextEncoder().encode(e)}function Qe(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}var fe=i(()=>{"use strict"});import{sha1 as Vy}from"@noble/hashes/legacy.js";import{sha256 as Yy,sha512 as Zy}from"@noble/hashes/sha2.js";function X(e){let t=eg(e);return{update(n){return t.update(typeof n=="string"?Ic(n):n),this},digest(n){let r=t.digest();return n==="hex"?Qe(r):r}}}function zt(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),t}function Ne(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let e=zt(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Qe(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function eg(e){switch(e){case"sha1":return Vy.create();case"sha256":return Yy.create();case"sha512":return Zy.create()}}var O=i(()=>{"use strict";fe()});var mr=i(()=>{"use strict";O()});var Rc=i(()=>{"use strict";p()});var vc=i(()=>{"use strict";Rc()});var _c=i(()=>{"use strict"});function Ve(e){return e instanceof Error}function Ye(e){let t=[],n=new Set,r=e;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){Tc(t,og(r)),r=r.cause;continue}Tc(t,String(r));break}return t.join(": ")}function og(e){let t=e,n=e.message.trim(),r=typeof t.code=="string"&&t.code!==""?t.code:void 0;return r==="ENOENT"?"File not found (ENOENT)":r==="EACCES"||r==="EPERM"?`Permission denied (${r})`:r!==void 0&&sg(n)?`${e.name} (${r})`:n===""?e.name:r===void 0?n:`${n} (${r})`}function sg(e){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(e)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(e)||/\bfile:\/\//iu.test(e)}function Tc(e,t){let n=t.trim();if(n==="")return;let r=e.at(-1);if(r===void 0){e.push(n);return}if(!(r===n||r.includes(n))){if(n.includes(r)){e[e.length-1]=n;return}e.push(n)}}var ee=i(()=>{"use strict";p()});var Cc=i(()=>{"use strict";ee()});var Ac=i(()=>{"use strict"});import{APICallError as iR}from"ai";var Pc=i(()=>{"use strict";p()});var ye=i(()=>{"use strict";p()});var Ze,Qt=i(()=>{"use strict";Ze=class{#e=0;#t;#n=[];constructor(t){if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");this.#t=t}async use(t){await this.#r();try{return await t()}finally{this.#i()}}async#r(){if(this.#e<this.#t){this.#e+=1;return}await new Promise(t=>{this.#n.push(()=>{this.#e+=1,t()})})}#i(){this.#e-=1,this.#n.shift()?.()}}});var Wi=i(()=>{"use strict";ye()});var ji=i(()=>{"use strict"});var Lc=i(()=>{"use strict";p()});var Gi=i(()=>{"use strict"});import{generateText as PR,streamText as LR}from"ai";var Dc=i(()=>{"use strict";vc();_c();Cc();Ac();Pc();ye();$t();Qt();mr();ee();Wi();ji();Lc();Gi()});var Fc=i(()=>{"use strict";Dc()});var Ui=i(()=>{"use strict";Fc();Wi();ji();Gi()});var lg,Hi,Mc,Yt=i(()=>{"use strict";lg=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),Hi=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),Mc=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var qi=i(()=>{"use strict"});async function pg(e){if(e.size!==void 0)return e.size===0;if(e.getSize!==void 0)return await e.getSize()===0;let t=await e.read();return typeof t=="string"?t.length===0:t.byteLength===0}function h(e,t){let n=e[t];if(typeof n!="number")throw new TypeError(`Expected ${t} to be a number`);return n}function S(e,t){let n=e[t];if(typeof n!="string")throw new TypeError(`Expected ${t} to be a string`);return n}var mg,N,$i,y=i(()=>{"use strict";p();mg=900*1e3;N=class e{#e;#t;#n;#r;#i=!1;#u=Promise.resolve();#c=0;constructor(t,n={}){this.#e=t,this.#t=n.onWrite,this.#n=L().asyncContext.create()}static async open(t,n="",r={}){let a=await he(t),o=r.readonly!==!0&&n.trim()!==""&&await pg(a),s=new $i(await L().database.open(a,r)),c=new e(s,r);return await c.#o(`PRAGMA busy_timeout = ${mg}`),r.readonly!==!0&&n.trim()!==""&&(await c.#o(n),o&&c.#d()),c}static async initialize(t,n){let r=await e.open(t);try{n.trim()!==""&&await r.#o(n)}finally{await r.close()}}async queryAll(t,n,r){return await this.#a(async()=>(this.#s(),(await this.#m(t,n)).map(r)))}async queryOne(t,n,r){return await this.#a(async()=>{this.#s();let a=await this.#p(t,n);return a===void 0?void 0:r(a)})}async run(t,n){await this.#a(async()=>{this.#s(),await this.#h(t,n),this.#d()})}async execute(t){await this.#a(async()=>{this.#s(),await this.#o(t),this.#d()})}async transaction(t){return await this.#a(async()=>{this.#s();let n=this.#c===0,r=this.#r??Symbol("database transaction scope");n&&(await this.#o("BEGIN IMMEDIATE"),this.#r=r),this.#c+=1;try{let a=await this.#n.run(r,t);return n&&await this.#o("COMMIT"),a}catch(a){throw n&&await this.#o("ROLLBACK"),a}finally{this.#c-=1,n&&(this.#r=void 0)}})}async flush(){await this.#a(()=>{this.#s()})}async close(){await this.#a(async()=>{this.#i||(await this.#l(),this.#i=!0)})}async getLastInsertRowId(){let t=await this.queryOne("SELECT last_insert_rowid() AS row_id",void 0,n=>h(n,"row_id"));if(t===void 0)throw new Error("Could not read last_insert_rowid()");return t}#s(){if(this.#i)throw new Error("Database is already closed")}async#a(t){let n=this.#n.getStore();if(n!==void 0&&n===this.#r)return await t();let r=this.#u.then(t);return this.#u=r.then(()=>{},()=>{}),await r}#d(){this.#t?.()}async#l(){await this.#e.close()}async#o(t){await this.#e.execute(t)}async#m(t,n){return await this.#e.queryAll(t,n)}async#p(t,n){return await this.#e.queryOne(t,n)}async#h(t,n){await this.#e.run(t,n)}};$i=class{#e;constructor(t){this.#e=t}async close(){await this.#e.close()}async execute(t){await this.#e.execute(t)}async queryAll(t,n){return[...await this.#e.queryAll(t,n)]}async queryOne(t,n){return await this.#e.queryOne(t,n)}async run(t,n){await this.#e.run(t,n)}}});async function It(){let e=I().library,t=pr.get(e.identity);if(t!==void 0){await t;return}let n=yg(e);pr.set(e.identity,n);try{await n}finally{pr.get(e.identity)===n&&pr.delete(e.identity)}}async function br(){let e=await K(I().library,"core.sqlite");if(e===void 0||await Sr(e))return 0;let t=await N.open(e,"",{readonly:!0});try{return await xt(t,"schema_versions")?await t.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],n=>h(n,"version"))??1:1}finally{await t.close()}}async function yg(e){let t=await br();if(t>Ki)throw new Error(`Unsupported Wiki Graph home schema version: ${t}.`);let n=await j(e,"core.sqlite");if(t===0){await hr(n,Ki);return}for(;t<Ki;)switch(t){case 1:await Wc(e),await hr(n,2),t=2;break;case 2:await Wc(e),await hr(n,3),t=3;break;case 3:await gg(n),await hr(n,4),t=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${t}.`)}}async function Wc(e){await Hc(e),await Uc(e)}async function gg(e){let t=I().library;await Hc(t),await bg(e),await Uc(t)}async function bg(e){let t=await N.open(e);try{if(!await xt(t,"libraries"))return;let n=await yr(t,"libraries"),r=n.has("folder_identity")?"folder_identity":n.has("folder_path")?"folder_path":void 0;if(r===void 0)throw new Error("Cannot migrate library registry without a folder reference.");let a=await t.queryAll(`SELECT id, ${r} AS folder_reference FROM libraries ORDER BY id`,void 0,s=>({id:h(s,"id"),reference:S(s,"folder_reference")})),o=[];for(let s of a){let c=L().resources,d=r==="folder_identity"||c.resolveLegacyDirectory===void 0?await c.getDirectory(s.reference):await c.resolveLegacyDirectory(s.reference);if(d===void 0)throw new Error(`Cannot migrate unavailable library Directory for registry id ${s.id}.`);o.push({id:s.id,identity:d.identity})}await t.transaction(async()=>{n.has("folder_identity")||await t.run("ALTER TABLE libraries RENAME COLUMN folder_path TO folder_identity");for(let s of o)await t.run("UPDATE libraries SET folder_identity = ? WHERE id = ?",[s.identity,s.id])})}finally{await t.close()}}async function hr(e,t){let n=await N.open(e);try{await n.execute(fg),await n.run(`INSERT INTO schema_versions (scope, version, updated_at)
6
+ var Cw=Object.defineProperty;var i=(n,e)=>()=>(n&&(e=n(n=0)),e);var Tw=(n,e)=>{for(var t in e)Cw(n,t,{get:e[t],enumerable:!0})};async function oi(n){let e=await n.openReader();try{return e.size}finally{await e.close()}}async function pn(n){return await oi(n)===0}async function ae(n){return new TextDecoder().decode(await $n(n))}async function $n(n){let e=await n.openReader();try{let t=new Uint8Array(e.size);for(let r=0;r<e.size;){let a=await e.read(r,Math.min(65536,e.size-r));t.set(a,r),r+=a.byteLength}return t}finally{await e.close()}}async function me(n,e){let t=await n.openWriter();try{await t.write(e),await t.commit()}catch(r){throw await t.abort().catch(()=>{}),r}}async function Ie(n){if(j(n)){let e=0;for(let t of await n.list())e+=await Ie(t);return e}return await oi(n)}async function ze(n){return await n.getLastModified?.()}function j(n){return n.kind==="directory"}var pu=i(()=>{"use strict"});function Ja(n){Jn().installedPlatform=n}function L(){let{installedPlatform:n}=Jn();if(n===void 0)throw new Error("No WikiGraph runtime platform has been installed. Provide a runtime adapter before using wiki-graph-core.");return n}async function hn(n){if(typeof n!="string")return n;let e=await L().resources.getFile(n);if(e===void 0)throw new Error("Host file is unavailable");return e}async function J(n,e){let t=e.replaceAll("\\","/").split("/").filter(Boolean);if(t.some(o=>o==="."||o===".."))throw new TypeError(`Directory path must remain relative: ${e}`);let r=t.pop();if(!r)return;let a=n;for(let o of t){let s=await a.getDirectory(o);if(!s)return;a=s}return await a.getFile(r)}async function Oe(n,e){let t=Ka(e),r=n;for(let a of t){let o=await r.getDirectory(a);if(!o)return;r=o}return r}async function z(n,e){let t=Ka(e),r=n;for(let a of t){let o=await r.getDirectory(a);if(o!==void 0){r=o;continue}try{r=await r.createDirectory(a)}catch(s){let d=await r.getDirectory(a);if(d===void 0)throw s;r=d}}return r}async function H(n,e){let t=Ka(e),r=t.pop();if(!r)throw new TypeError("File name must remain relative");let a=await z(n,t.join("/")),o=await a.getFile(r);if(o!==void 0)return o;try{return await a.createFile(r)}catch(s){let d=await a.getFile(r);if(d!==void 0)return d;throw s}}function Ka(n){let e=n.replaceAll("\\","/");if(e.startsWith("/"))throw new TypeError(`Directory path must remain relative: ${n}`);let t=e.split("/").filter(Boolean);if(t.some(r=>r==="."||r===".."))throw new TypeError(`Directory path must remain relative: ${n}`);return t}function Jn(){let n=globalThis,e=n[hu];if(e!==void 0)return e;let t={storageContext:new $a};return Object.defineProperty(n,hu,{configurable:!1,enumerable:!1,value:t,writable:!1}),t}function za(n){Jn().installedStorage=n}async function di(n,e){return n===void 0?await e():await Jn().storageContext.run(n,e)}function v(){let{installedStorage:n,storageContext:e}=Jn(),t=e.getStore()??n;if(t===void 0)throw new Error("No WikiGraph storage roots have been configured. Pass storage to WikiGraph or install process-default storage.");return t}var hu,$a,y=i(()=>{"use strict";pu();hu=Symbol.for("wiki-graph-core.runtime.v1");$a=class{#e;#n;run(e,t){let r=this.#t();if(r!==void 0)return r.run(e,t);let a=this.#n;this.#n=e;try{return t()}finally{this.#n=a}}enterWith(e){let t=this.#t();t!==void 0?t.enterWith(e):this.#n=e}getStore(){return this.#t()?.getStore()??this.#n}#t(){if(this.#e!==void 0)return this.#e;let{installedPlatform:e}=Jn();if(e!==void 0)return this.#e=e.asyncContext.create(),this.#n!==void 0&&(this.#e.enterWith(this.#n),this.#n=void 0),this.#e}}});function ci(n){if(Pw.test(n))throw new Error(`invalid template name ${n}`);let t=n.replace(Aw,"").replace(_w,"");if(t.split("/").includes(".."))throw new Error(`invalid template name ${n}`);return`${t}.jinja`}var _w,Pw,Aw,Tt=i(()=>{"use strict";y();_w=/\.jinja$/iu,Pw=/^\.+\//u,Aw=/^\/+/u});var yu=i(()=>{"use strict";y();Tt()});import*as bu from"async_hooks";import*as Su from"crypto";import*as li from"fs";import*as B from"fs/promises";import*as wu from"os";import*as O from"path";import*as Za from"process";import{Readable as ku,Writable as Lw}from"stream";import{pipeline as Ow}from"stream/promises";import*as eo from"sqlite3";import*as xu from"yauzl";import*as Iu from"yazl";import{Environment as Nw,Loader as Dw}from"nunjucks";async function gu(n,e,t){let r=Buffer.from(e),a=0;for(;a<r.byteLength;){let o=await n.write(r,a,r.byteLength-a,t===void 0?null:t+a);if(o.bytesWritten===0)throw new Error("File writer made no progress");a+=o.bytesWritten}}function Eu(n,e,t){if(Ru(n),!Number.isSafeInteger(e)||e<0)throw new RangeError("File read length must be a non-negative safe integer");if(n>t||e>t-n)throw new RangeError("File read range exceeds the file size")}function Ru(n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("File offset must be a non-negative safe integer")}function vu(n,e){return`node-${n}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function Qa(n,e){let t=`node-${e}:`;if(!n.startsWith(t))return O.isAbsolute(n)?n:void 0;try{return Buffer.from(n.slice(t.length),"base64url").toString("utf8")}catch{return}}function _t(n){if(n.length===0||n==="."||n===".."||O.isAbsolute(n)||n.includes("/")||n.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${n}`)}async function Ww(n,e){let t=(e.mode==="readonly"?Pt.OPEN_READONLY:Pt.OPEN_READWRITE|(e.create?Pt.OPEN_CREATE:0))|Pt.OPEN_FULLMUTEX;return new Va(await Fw(n,t))}async function Fw(n,e){let t=Cu(n,"file");if(t===void 0)throw new TypeError("The Node database adapter requires a NodeFile");return await new Promise((r,a)=>{let o=new Pt.Database(t,e,s=>{s?a(s):r(o)})})}async function Mw(n){let e=Cu(n,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let t=await new Promise((o,s)=>{xu.open(e,{autoClose:!1,lazyEntries:!0},(d,c)=>{d||c===void 0?s(d??new Error("Cannot open ZIP")):o(c)})}),r=await new Promise((o,s)=>{let d=new Map,c=m=>{t.close(),s(m instanceof Error?m:new Error("Cannot scan ZIP central directory"))},u=()=>{t.off("error",c),o(d)};t.on("entry",m=>{m.fileName.endsWith("/")||d.set(m.fileName,m),t.readEntry()}),t.once("error",c),t.once("end",u),t.readEntry()}),a=!1;return{close:()=>(a||t.close(),a=!0,Promise.resolve()),copyEntry:async(o,s)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let d=r.get(o);return d===void 0?!1:(await Gw(t,d,s),!0)},getEntrySize:o=>{if(a)throw new Error("Cannot read a closed ZIP archive");return Promise.resolve(r.get(o)?.uncompressedSize)},listEntries:()=>Promise.resolve([...r.keys()]),readEntryRange:async(o,s,d)=>{if(a)throw new Error("Cannot read a closed ZIP archive");let c=r.get(o);if(c!==void 0)return await Bw(t,c,s,d)},readEntry:async o=>{if(a)throw new Error("Cannot read a closed ZIP archive");let s=r.get(o);if(s!==void 0)return await jw(t,s)}}}async function Gw(n,e,t){let r=await t.openWriter();try{let a=await ui(n,e);await Tu(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function jw(n,e){return await _u(await ui(n,e))}async function Bw(n,e,t,r){if(Eu(t,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await Uw(await ui(n,e),t,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await _u(await ui(n,e,{decompress:null,decrypt:null,end:t+r,start:t}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function Uw(n,e,t){let r=[],a=e+t,o=0,s=0;for await(let d of n){let c=Buffer.isBuffer(d)?d:Buffer.from(d),u=o+c.byteLength;if(u>e&&o<a){let m=c.subarray(Math.max(0,e-o),Math.min(c.byteLength,a-o));r.push(m),s+=m.byteLength}if(o=u,o>=a)break}if(s!==t)throw new Error("ZIP entry changed while reading its byte range");return Buffer.concat(r,s)}async function ui(n,e,t){return await new Promise((r,a)=>{let o=(s,d)=>{s||d===void 0?a(s??new Error(`Cannot read ZIP entry: ${e.fileName}`)):r(d)};t===void 0?n.openReadStream(e,o):n.openReadStream(e,t,o)})}async function qw(n,e){let t=new Iu.ZipFile,r=await n.openWriter(),a=t.outputStream,o=Tu(a,r),s={cancelled:!1,complete:!1},d;try{d=Kw(e);let c=Hw(t,d,s);if(await Promise.race([c,o]),!s.complete)throw new Error("ZIP output ended before entry production completed");t.end(),await o,await r.commit()}catch(c){throw s.cancelled=!0,!s.complete&&d!==void 0&&zw(d),a.destroyed||a.destroy(c instanceof Error?c:new Error("Cannot write ZIP archive")),await o.catch(()=>{}),await r.abort().catch(()=>{}),c}}async function Hw(n,e,t){for(;!t.cancelled;){let r=await e.next();if(t.cancelled)return;if(r.done){t.complete=!0;return}"file"in r.value?n.addReadStream($w(r.value.file),r.value.name,{compress:!1}):"data"in r.value?n.addBuffer(Buffer.from(r.value.data),r.value.name,{compress:!1}):n.addReadStream(Jw(r.value),r.value.name,{compress:!1,size:r.value.size})}}function $w(n){return ku.from((async function*(){let e=await n.openReader();try{for(let t=0;t<e.size;){let r=await e.read(t,Math.min(65536,e.size-t));t+=r.byteLength,yield r}}finally{await e.close()}})())}function Cu(n,e){if(typeof n!="object"||n===null)return;let t=n;return t[no]===e&&typeof t.path=="string"?t.path:void 0}function Jw(n){return ku.from((async function*(){for(let e=0;e<n.size;){let t=await n.read(e,Math.min(65536,n.size-e));e+=t.byteLength,yield t}})())}function Kw(n){let e=n[Symbol.asyncIterator];return e===void 0?n[Symbol.iterator]():e.call(n)}function zw(n){if(n.return!==void 0)try{Promise.resolve(n.return()).catch(()=>{})}catch{}}async function Tu(n,e){await Ow(n,new Lw({write:(t,r,a)=>{e.write(t).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function _u(n){return await new Promise((e,t)=>{let r=[];n.on("data",a=>r.push(a)),n.once("error",t),n.once("end",()=>e(Buffer.concat(r)))})}function Xw(){let n=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof n=="string"&&n!=="")return n;let e=Xa.cwd();for(;;){for(let r of[O.join(e,"data"),O.join(e,"packages","core","data")])try{if(li.statSync(r).isDirectory())return r}catch{}let t=O.dirname(e);if(t===e)throw new Error("Could not locate data directory");e=t}}function Pu(n=O.join(wu.homedir(),".wikigraph")){return{library:new Ne(n),documentStore:new Ne(O.join(n,"documents"))}}function At(n){Ja(Qw),za(Pu(n))}async function Kn(n,e){return await di(n===void 0?void 0:Pu(n),e)}var Xa,Pt,no,de,Ne,Va,Qw,Ya,ce=i(()=>{"use strict";yu();Xa=Za.default??Za,Pt=eo.default??eo,no=Symbol.for("wiki-graph-sdk.node-resource.v1"),de=class{constructor(e,t=O.basename(e)){this.path=e;this.identity=vu("file",e),this.name=t}path;kind="file";[no]="file";identity;name;async openReader(){let e=await B.open(this.path,"r"),t=!1;try{let r=await e.stat();if(!r.isFile())throw new Error("File reader requires a regular file");let{size:a}=r;return{size:a,close:async()=>{t||await e.close(),t=!0},read:async(o,s)=>{if(t)throw new Error("Cannot read from a closed FileReader");Eu(o,s,a);let d=Buffer.allocUnsafe(s),c=0;for(;c<s;){let u=await e.read(d,c,s-c,o+c);if(u.bytesRead===0)throw new Error("File changed while reading its byte range");c+=u.bytesRead}return new Uint8Array(d.buffer,d.byteOffset,c)}}}catch(r){throw await e.close(),r}}async getLastModified(){try{return(await B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async openWriter(){await B.mkdir(O.dirname(this.path),{recursive:!0});let e=`${this.path}.tmp-${Su.randomUUID()}`,t=await B.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await gu(t,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");Ru(a),await gu(t,o,a)},commit:async()=>{r||(await t.close(),await B.rename(e,this.path)),r=!0},abort:async()=>{r||(await t.close(),await B.rm(e,{force:!0})),r=!0}}}};Ne=class n{constructor(e){this.path=e;this.identity=vu("directory",e),this.name=O.basename(e)}path;kind="directory";[no]="directory";identity;name;async getFile(e){_t(e);let t=new de(O.join(this.path,e));try{return(await B.stat(t.path)).isFile()?t:void 0}catch{return}}async getLastModified(){try{return(await B.stat(this.path)).mtimeMs}catch(e){if(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT")return;throw e}}async getDirectory(e){_t(e);let t=new n(O.join(this.path,e));try{return(await B.stat(t.path)).isDirectory()?t:void 0}catch{return}}async list(){return(await B.readdir(this.path,{withFileTypes:!0})).map(t=>t.isDirectory()?new n(O.join(this.path,t.name)):new de(O.join(this.path,t.name),t.name))}async createFile(e){_t(e),await B.mkdir(this.path,{recursive:!0});let t=new de(O.join(this.path,e));return await B.writeFile(t.path,"",{flag:"wx"}),t}async createDirectory(e){_t(e),await B.mkdir(this.path,{recursive:!0});let t=new n(O.join(this.path,e));return await B.mkdir(t.path),t}async remove(e,t){_t(e),await B.rm(O.join(this.path,e),{force:!0,recursive:t?.recursive===!0})}};Va=class{constructor(e){this.database=e}database;async close(){await new Promise((e,t)=>{this.database.close(r=>{r?t(r):e()})})}async execute(e){await new Promise((t,r)=>{this.database.exec(e,a=>{a?r(a):t()})})}async queryAll(e,t=[]){return await new Promise((r,a)=>{this.database.all(e,[...t],(o,s)=>{o?a(o):r(s)})})}async queryOne(e,t=[]){return await new Promise((r,a)=>{this.database.get(e,[...t],(o,s)=>{o?a(o):r(s)})})}async run(e,t=[]){await new Promise((r,a)=>{this.database.run(e,[...t],o=>{o?a(o):r()})})}};Qw={asyncContext:{create:()=>new bu.AsyncLocalStorage},database:{open:Ww},lifecycle:{instanceId:`node-process:${Xa.pid}`,isInstanceAlive:n=>{let e=/^node-process:(\d+)$/u.exec(n);if(e===null)return Promise.resolve(void 0);try{return Xa.kill(Number(e[1]),0),Promise.resolve(!0)}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="ESRCH"?Promise.resolve(!1):Promise.resolve(!0)}}},resources:{getDirectory:n=>{let e=Qa(n,"directory");return Promise.resolve(e===void 0?void 0:new Ne(e))},getFile:n=>{let e=Qa(n,"file");return Promise.resolve(e===void 0?void 0:new de(e))},resolveLegacyDirectory:n=>{let e=Qa(n,"directory");return Promise.resolve(e===void 0?void 0:new Ne(e))}},templates:{createEnvironment:n=>new Nw(new Ya,n)},zip:{open:Mw,write:qw}},Ya=class extends Dw{#e;constructor(e){super(),this.#e=e}getSource(e){let t=ci(e),r=O.join(this.#e??Xw(),t);return{noCache:!1,path:t,src:li.readFileSync(r,"utf8")}}}});var De=i(()=>{"use strict"});function Au(n){return new TextEncoder().encode(n)}function fn(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}var Ee=i(()=>{"use strict"});import{sha1 as Vw}from"@noble/hashes/legacy.js";import{sha256 as Yw,sha512 as Zw}from"@noble/hashes/sha2.js";function oe(n){let e=ek(n);return{update(t){return e.update(typeof t=="string"?Au(t):t),this},digest(t){let r=e.digest();return t==="hex"?fn(r):r}}}function Lt(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function Qe(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let n=Lt(16);n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=fn(n);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function ek(n){switch(n){case"sha1":return Vw.create();case"sha256":return Yw.create();case"sha512":return Zw.create()}}var U=i(()=>{"use strict";Ee()});var mi=i(()=>{"use strict";U()});var Ou=i(()=>{"use strict";y()});var Nu=i(()=>{"use strict";Ou()});var Du=i(()=>{"use strict"});function We(n){return n instanceof Error}function zn(n){let e=[],t=new Set,r=n;for(;r!==void 0&&!t.has(r);){if(t.add(r),r instanceof Error){Wu(e,ok(r)),r=r.cause;continue}Wu(e,String(r));break}return e.join(": ")}function ok(n){let e=n,t=n.message.trim(),r=typeof e.code=="string"&&e.code!==""?e.code:void 0;return r==="ENOENT"?"File not found (ENOENT)":r==="EACCES"||r==="EPERM"?`Permission denied (${r})`:r!==void 0&&sk(t)?`${n.name} (${r})`:t===""?n.name:r===void 0?t:`${t} (${r})`}function sk(n){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(n)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(n)||/\bfile:\/\//iu.test(n)}function Wu(n,e){let t=e.trim();if(t==="")return;let r=n.at(-1);if(r===void 0){n.push(t);return}if(!(r===t||r.includes(t))){if(t.includes(r)){n[n.length-1]=t;return}n.push(t)}}var pe=i(()=>{"use strict";y()});var Fu=i(()=>{"use strict";pe()});var Mu=i(()=>{"use strict"});import{APICallError as IP}from"ai";var Gu=i(()=>{"use strict";y()});var Xe=i(()=>{"use strict";y()});var yn,Nt=i(()=>{"use strict";yn=class{#e=0;#n;#t=[];constructor(e){if(!Number.isInteger(e)||e<1)throw new RangeError("concurrency must be a positive integer");this.#n=e}async use(e){await this.#r();try{return await e()}finally{this.#i()}}async#r(){if(this.#e<this.#n){this.#e+=1;return}await new Promise(e=>{this.#t.push(()=>{this.#e+=1,e()})})}#i(){this.#e-=1,this.#t.shift()?.()}}});var ro=i(()=>{"use strict";Xe()});var io=i(()=>{"use strict"});var ju=i(()=>{"use strict";y()});var ao=i(()=>{"use strict"});import{generateText as XP,streamText as VP}from"ai";var Uu=i(()=>{"use strict";Nu();Du();Fu();Mu();Gu();Xe();Tt();Nt();mi();pe();ro();io();ju();ao()});var qu=i(()=>{"use strict";Uu()});var so=i(()=>{"use strict";qu();ro();io();ao()});var lk,co,Hu,Qn=i(()=>{"use strict";lk=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),co=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),Hu=Object.freeze({choice:"serial-generation/reader-choice",extraction:"serial-generation/reader-extraction"})});var Q,Z=i(()=>{"use strict";Q=class extends Error{code;details;constructor(e,t,r={},a={}){super(t,a),this.name="WikiGraphError",this.code=e,this.details=r}}});var uo=i(()=>{"use strict"});async function pk(n){try{return await pn(n)}catch(e){if(We(e)&&e.code==="ENOENT")return!0;throw e}}function S(n,e){let t=n[e];if(typeof t!="number")throw new TypeError(`Expected ${e} to be a number`);return t}function E(n,e){let t=n[e];if(typeof t!="string")throw new TypeError(`Expected ${e} to be a string`);return t}var mk,N,lo,w=i(()=>{"use strict";y();pe();mk=900*1e3;N=class n{#e;#n;#t;#r;#i=!1;#u=Promise.resolve();#d=0;constructor(e,t={}){this.#e=e,this.#n=t.onWrite,this.#t=L().asyncContext.create()}static async open(e,t,r){let a=await hn(e),o=r.mode==="readwrite"&&r.create&&t.trim()!==""&&await pk(a),s=r.mode==="readonly"?await L().database.open(a,{mode:"readonly"}):await L().database.open(a,{create:r.create,mode:"readwrite"}),d;try{return d=new n(new lo(s),r),await d.#o(`PRAGMA busy_timeout = ${mk}`),r.mode==="readwrite"&&t.trim()!==""&&(await d.#o(t),o&&d.#c()),d}catch(c){throw d===void 0?await s.close().catch(()=>{}):await d.close().catch(()=>{}),c}}static async initialize(e,t){let r=await n.open(e,"",{create:!0,mode:"readwrite"});try{t.trim()!==""&&await r.#o(t)}finally{await r.close()}}async queryAll(e,t,r){return await this.#a(async()=>(this.#s(),(await this.#m(e,t)).map(r)))}async queryOne(e,t,r){return await this.#a(async()=>{this.#s();let a=await this.#p(e,t);return a===void 0?void 0:r(a)})}async run(e,t){await this.#a(async()=>{this.#s(),await this.#h(e,t),this.#c()})}async execute(e){await this.#a(async()=>{this.#s(),await this.#o(e),this.#c()})}async transaction(e){return await this.#a(async()=>{this.#s();let t=this.#d===0,r=this.#r??Symbol("database transaction scope");t&&(await this.#o("BEGIN IMMEDIATE"),this.#r=r),this.#d+=1;try{let a=await this.#t.run(r,e);return t&&await this.#o("COMMIT"),a}catch(a){throw t&&await this.#o("ROLLBACK"),a}finally{this.#d-=1,t&&(this.#r=void 0)}})}async flush(){await this.#a(()=>{this.#s()})}async close(){await this.#a(async()=>{this.#i||(await this.#l(),this.#i=!0)})}async getLastInsertRowId(){let e=await this.queryOne("SELECT last_insert_rowid() AS row_id",void 0,t=>S(t,"row_id"));if(e===void 0)throw new Error("Could not read last_insert_rowid()");return e}#s(){if(this.#i)throw new Error("Database is already closed")}async#a(e){let t=this.#t.getStore();if(t!==void 0&&t===this.#r)return await e();let r=this.#u.then(e);return this.#u=r.then(()=>{},()=>{}),await r}#c(){this.#n?.()}async#l(){await this.#e.close()}async#o(e){await this.#e.execute(e)}async#m(e,t){return await this.#e.queryAll(e,t)}async#p(e,t){return await this.#e.queryOne(e,t)}async#h(e,t){await this.#e.run(e,t)}};lo=class{#e;constructor(e){this.#e=e}async close(){await this.#e.close()}async execute(e){await this.#e.execute(e)}async queryAll(e,t){return[...await this.#e.queryAll(e,t)]}async queryOne(e,t){return await this.#e.queryOne(e,t)}async run(e,t){await this.#e.run(e,t)}}});async function gn(){let n=v().library,e=hi.get(n.identity);if(e!==void 0){await e;return}let t=fk(n);hi.set(n.identity,t);try{await t}finally{hi.get(n.identity)===t&&hi.delete(n.identity)}}async function Si(){let n=await J(v().library,"core.sqlite");if(n===void 0||await wi(n))return 0;let e=await N.open(n,"",{mode:"readonly"});try{return await Xn(e,"schema_versions")?await e.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],t=>S(t,"version"))??1:1}finally{await e.close()}}async function fk(n){let e=await Si();if(e>mo)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let t=await H(n,"core.sqlite");if(e===0){await fi(t,mo);return}for(;e<mo;)switch(e){case 1:await $u(n),await fi(t,2),e=2;break;case 2:await $u(n),await fi(t,3),e=3;break;case 3:await yk(t),await fi(t,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function $u(n){await Xu(n),await Qu(n)}async function yk(n){let e=v().library;await Xu(e),await gk(n),await Qu(e)}async function gk(n){let e=await N.open(n,"",{create:!1,mode:"readwrite"});try{if(!await Xn(e,"libraries"))return;let t=await gi(e,"libraries"),r=t.has("folder_identity")?"folder_identity":t.has("folder_path")?"folder_path":void 0;if(r===void 0)throw new Error("Cannot migrate library registry without a folder reference.");let a=await e.queryAll(`SELECT id, ${r} AS folder_reference FROM libraries ORDER BY id`,void 0,s=>({id:S(s,"id"),reference:E(s,"folder_reference")})),o=[];for(let s of a){let d=L().resources,c=r==="folder_identity"||d.resolveLegacyDirectory===void 0?await d.getDirectory(s.reference):await d.resolveLegacyDirectory(s.reference);if(c===void 0)throw new Error(`Cannot migrate unavailable library Directory for registry id ${s.id}.`);o.push({id:s.id,identity:c.identity})}await e.transaction(async()=>{t.has("folder_identity")||await e.run("ALTER TABLE libraries RENAME COLUMN folder_path TO folder_identity");for(let s of o)await e.run("UPDATE libraries SET folder_identity = ? WHERE id = ?",[s.identity,s.id])})}finally{await e.close()}}async function fi(n,e){let t=await N.open(n,"",{create:!0,mode:"readwrite"});try{await t.execute(hk),await t.run(`INSERT INTO schema_versions (scope, version, updated_at)
7
7
  VALUES (?, ?, ?)
8
8
  ON CONFLICT(scope) DO UPDATE SET
9
9
  version = excluded.version,
10
- updated_at = excluded.updated_at`,["home",t,new Date().toISOString()])}finally{await n.close()}}async function Uc(e){await Zt(await e.getDirectory("cache"),["search-sessions.sqlite","continuation-cursors.sqlite","cache.sqlite"]);let t=await e.getDirectory("staging");await Zt(t,["library","work"]),await fr(t,"staging.sqlite");let n=await e.getDirectory("tmp");await fr(n,"gc.sqlite"),await fr(n,"wikg-coordinator.sqlite"),await Zt(n,["gc.last-run"]);let r=await e.getDirectory("jobs");await Zt(r,["cache","work"]),await fr(r,"job.sqlite");let a=I().documentStore,o;try{o=await a.list()}catch(s){if(Ve(s)&&s.code==="ENOENT")return;throw s}for(let s of o)(s.name===".wikg-work"||s.name===".wikg-cache"||s.name.startsWith(".wikg-session-")||s.name.startsWith(".wikg-upgrade-"))&&await a.remove(s.name,{recursive:G(s)})}async function fr(e,t){await Zt(e,[t,`${t}-wal`,`${t}-shm`])}async function Zt(e,t){if(e===void 0)return;let n=new Map((await e.list()).map(r=>[r.name,r]));for(let r of t){let a=n.get(r);a!==void 0&&await e.remove(r,{recursive:G(a)})}}async function Hc(e){await Gc(await K(e,"core.sqlite"),[["library_locks","Cannot upgrade home with active library locks."],["state_locks","Cannot upgrade home with active state locks."]]),await Gc(await K(e,"tmp/gc.sqlite"),[["gc_locks","Cannot upgrade home with an active GC lock."]]),await Sg(await K(e,"jobs/job.sqlite")),await jc(await K(e,"staging/staging.sqlite"),"legacy coordinator"),await jc(await K(e,"tmp/wikg-coordinator.sqlite"),"coordinator")}async function Sg(e){if(e===void 0||await Sr(e))return;let t=await N.open(e,"",{readonly:!0});try{if(await xt(t,"build_worker_lease")){let n=await yr(t,"build_worker_lease"),a=["owner_id","owner_pid"].filter(s=>n.has(s)).map(s=>`${s} IS NOT NULL`).join(" OR ");if(await t.queryOne(`SELECT 1 AS active FROM build_worker_lease
10
+ updated_at = excluded.updated_at`,["home",e,new Date().toISOString()])}finally{await t.close()}}async function Qu(n){await Dt(await n.getDirectory("cache"),["search-sessions.sqlite","continuation-cursors.sqlite","cache.sqlite"]);let e=await n.getDirectory("staging");await Dt(e,["library","work"]),await yi(e,"staging.sqlite");let t=await n.getDirectory("tmp");await yi(t,"gc.sqlite"),await yi(t,"wikg-coordinator.sqlite"),await Dt(t,["gc.last-run"]);let r=await n.getDirectory("jobs");await Dt(r,["cache","work"]),await yi(r,"job.sqlite");let a=v().documentStore,o;try{o=await a.list()}catch(s){if(We(s)&&s.code==="ENOENT")return;throw s}for(let s of o)(s.name===".wikg-work"||s.name===".wikg-cache"||s.name.startsWith(".wikg-session-")||s.name.startsWith(".wikg-upgrade-"))&&await a.remove(s.name,{recursive:j(s)})}async function yi(n,e){await Dt(n,[e,`${e}-wal`,`${e}-shm`])}async function Dt(n,e){if(n===void 0)return;let t=new Map((await n.list()).map(r=>[r.name,r]));for(let r of e){let a=t.get(r);a!==void 0&&await n.remove(r,{recursive:j(a)})}}async function Xu(n){await Ku(await J(n,"core.sqlite"),[["library_locks","Cannot upgrade home with active library locks."],["state_locks","Cannot upgrade home with active state locks."]]),await Ku(await J(n,"tmp/gc.sqlite"),[["gc_locks","Cannot upgrade home with an active GC lock."]]),await bk(await J(n,"jobs/job.sqlite")),await Ju(await J(n,"staging/staging.sqlite"),"legacy coordinator"),await Ju(await J(n,"tmp/wikg-coordinator.sqlite"),"coordinator")}async function bk(n){if(n===void 0||await wi(n))return;let e=await N.open(n,"",{mode:"readonly"});try{if(await Xn(e,"build_worker_lease")){let t=await gi(e,"build_worker_lease"),a=["owner_id","owner_pid"].filter(s=>t.has(s)).map(s=>`${s} IS NOT NULL`).join(" OR ");if(await e.queryOne(`SELECT 1 AS active FROM build_worker_lease
11
11
  WHERE heartbeat_at IS NOT NULL
12
12
  AND heartbeat_at >= ?
13
13
  ${a===""?"":`AND (${a})`}
14
- LIMIT 1`,[Date.now()-gr],()=>!0)===!0)throw en("Cannot upgrade home with an active build worker.")}}finally{await t.close()}}async function jc(e,t){if(e===void 0||await Sr(e))return;let n=await N.open(e,"",{readonly:!0});try{if(await xt(n,"archive_owners")){let r=await yr(n,"archive_owners"),a=await n.queryAll(`SELECT heartbeat_at${r.has("host_instance_id")?", host_instance_id":""}
15
- FROM archive_owners`,void 0,o=>({heartbeatAt:h(o,"heartbeat_at"),hostInstanceId:typeof o.host_instance_id=="string"?o.host_instance_id:void 0}));for(let o of a){if(o.hostInstanceId===void 0){if(Bc(o.heartbeatAt))throw en(`Cannot upgrade home with active ${t} state.`);continue}let s=await L().lifecycle.isInstanceAlive(o.hostInstanceId);if(s===!0||s===void 0&&Bc(o.heartbeatAt))throw en(`Cannot upgrade home with active ${t} state.`)}}for(let r of["entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await xt(n,r)||!(await yr(n,r)).has("heartbeat_at"))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-gr],()=>!0)===!0)throw en(`Cannot upgrade home with active ${t} state.`)}}finally{await n.close()}}async function Gc(e,t){if(e===void 0||await Sr(e))return;let n=await N.open(e,"",{readonly:!0});try{for(let[r,a]of t){if(!await xt(n,r))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-gr],()=>!0)===!0)throw en(a)}}finally{await n.close()}}function en(e){return new Error(`${e} ${hg}`)}function Bc(e){return e!==void 0&&Date.now()-e<=gr}async function Sr(e){if(e.getSize!==void 0)return await e.getSize()===0;if(e.size!==void 0)return e.size===0;let t=await e.read();return typeof t=="string"?t.length===0:t.byteLength===0}async function yr(e,t){return new Set(await e.queryAll(`PRAGMA table_info(${t})`,void 0,n=>S(n,"name")))}async function xt(e,t){return await e.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[t],()=>!0)===!0}var Ki,gr,hg,fg,pr,wr=i(()=>{"use strict";p();ee();y();Ki=4,gr=300*1e3,hg="Stop the active operation, then run `wg maintenance upgrade home`. See: `wg maintenance upgrade --help`.",fg=`
14
+ LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Wt("Cannot upgrade home with an active build worker.")}}finally{await e.close()}}async function Ju(n,e){if(n===void 0||await wi(n))return;let t=await N.open(n,"",{mode:"readonly"});try{if(await Xn(t,"archive_owners")){let r=await gi(t,"archive_owners"),a=await t.queryAll(`SELECT heartbeat_at${r.has("host_instance_id")?", host_instance_id":""}
15
+ FROM archive_owners`,void 0,o=>({heartbeatAt:S(o,"heartbeat_at"),hostInstanceId:typeof o.host_instance_id=="string"?o.host_instance_id:void 0}));for(let o of a){if(o.hostInstanceId===void 0){if(zu(o.heartbeatAt))throw Wt(`Cannot upgrade home with active ${e} state.`);continue}let s=await L().lifecycle.isInstanceAlive(o.hostInstanceId);if(s===!0||s===void 0&&zu(o.heartbeatAt))throw Wt(`Cannot upgrade home with active ${e} state.`)}}for(let r of["entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await Xn(t,r)||!(await gi(t,r)).has("heartbeat_at"))continue;if(await t.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Wt(`Cannot upgrade home with active ${e} state.`)}}finally{await t.close()}}async function Ku(n,e){if(n===void 0||await wi(n))return;let t=await N.open(n,"",{mode:"readonly"});try{for(let[r,a]of e){if(!await Xn(t,r))continue;if(await t.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Wt(a)}}finally{await t.close()}}function Wt(n){return new Q("home_upgrade_blocked",n)}function zu(n){return n!==void 0&&Date.now()-n<=bi}async function wi(n){return await pn(n)}async function gi(n,e){return new Set(await n.queryAll(`PRAGMA table_info(${e})`,void 0,t=>E(t,"name")))}async function Xn(n,e){return await n.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var mo,bi,hk,hi,ki=i(()=>{"use strict";y();pe();Z();w();mo=4,bi=300*1e3,hk=`
16
16
  CREATE TABLE IF NOT EXISTS schema_versions (
17
17
  scope TEXT PRIMARY KEY,
18
18
  version INTEGER NOT NULL,
19
19
  updated_at TEXT NOT NULL
20
20
  );
21
- `,pr=new Map});async function B(e,t,n={}){await It();let r=await j(I().library,e);return await Ji(r,t,n)}async function Ji(e,t,n={}){return await N.open(await he(e),t,n)}var qc=i(()=>{"use strict";p();wr();y()});function Er(...e){let t=[];for(let n of e)for(let r of n.replaceAll("\\","/").split("/"))if(!(r===""||r==="."))if(r===".."){if(t.length===0)throw new TypeError("Relative path escapes its root");t.pop()}else t.push(r);return t.join("/")}function zi(e){return Er(e).split("/").at(-1)??""}var et=i(()=>{"use strict"});var tn=i(()=>{"use strict";et()});var $c=i(()=>{"use strict"});function kt(e){let t=new Set(Object.values(e));return n=>t.has(n)}function nn(e,t){let n=kt(e);return r=>{if(n(r))return r;throw new Error(`Unknown ${t}: ${r}`)}}var Xi=i(()=>{"use strict"});var ae,Kc,Jc,ge,zc,Qi,be=i(()=>{"use strict";Xi();ae=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(ae||{}),Kc=kt(ae),Jc=nn(ae,"chunk retention"),ge=(r=>(r.Critical="critical",r.Important="important",r.Helpful="helpful",r))(ge||{}),zc=kt(ge),Qi=nn(ge,"chunk importance")});var Vi=i(()=>{"use strict";be()});function tt(e){let t=0,n=!1;for(let r of e.trim()){if(wg.test(r)){t+=1,n=!1;continue}if(Eg.test(r)){n||(t+=1),n=!0;continue}n&&xg.test(r)||(n=!1)}return t}var wg,Eg,xg,nt=i(()=>{"use strict";wg=new RegExp("\\p{Script=Han}","u"),Eg=/[\p{Letter}\p{Number}]/u,xg=new RegExp("\\p{Mark}","u")});var Qc=i(()=>{"use strict";nt();be()});var xr=i(()=>{"use strict"});var Zi=i(()=>{"use strict";tn();be();Vi();Qc();xr()});var Vc=i(()=>{"use strict";tn();$c();Zi()});var ea=i(()=>{"use strict";Vc();Vi();Zi();xr()});var Ir=i(()=>{"use strict";p();et()});var ta=i(()=>{"use strict"});var ed=i(()=>{"use strict";et();Ir()});var td=i(()=>{"use strict";nt()});var na=i(()=>{"use strict"});var ra=i(()=>{"use strict";et();ee();ta();Ir();ed();td();na()});var nd=i(()=>{"use strict";et();Ir();ra()});var ia=i(()=>{"use strict";nd();ta();ra();na()});import{z as oe}from"zod";var rd,De,id,ad,rn=i(()=>{"use strict";rd=["epub","pdf","txt","markdown"],De=1,id=oe.enum(rd),ad=oe.object({version:oe.literal(De),sourceFormat:id,title:oe.string().min(1).nullable(),authors:oe.array(oe.string().min(1)),language:oe.string().min(1).nullable(),identifier:oe.string().min(1).nullable(),publisher:oe.string().min(1).nullable(),publishedAt:oe.string().min(1).nullable(),description:oe.string().min(1).nullable()})});function od(e,t="chapter key"){if(e===""||e==="."||e===".."||e.includes("/"))throw new Error(`Invalid ${t}: chapter paths do not support empty, '.', '..', or relative segments.`);if(!/^[a-z0-9][a-z0-9-]*$/u.test(e))throw new Error(`Invalid ${t}: ${e}. Use lowercase letters, numbers, and hyphens.`);if(/^\d+$/u.test(e))throw new Error(`Invalid ${t}: numeric chapter keys are not accepted.`);if(Ag.has(e))throw new Error(`Invalid ${t}: ${e} is reserved.`);return e}var Ag,se=i(()=>{"use strict";fe();O();Ag=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as ve}from"zod";var rt,aa,sd,oa=i(()=>{"use strict";se();rt=1,aa=ve.object({key:ve.string().min(1).transform(e=>od(e)).optional(),title:ve.string().min(1).nullable().optional(),serialId:ve.number().int().nonnegative().optional(),children:ve.lazy(()=>ve.array(aa))}),sd=ve.object({version:ve.literal(rt),items:ve.array(aa)})});function Se(e){let t=[];for(let n of e.replaceAll("\\","/").trim().split("/"))n===""||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function Pg(e){let[t]=e.split("#",1);return Se(t??"")}function sa(e){if(e===void 0)return;let t=e.startsWith("#")?e.slice(1):e;return t===""?void 0:t}function an(e){let[t,n]=e.split("#",2);return{path:Se(t??""),fragment:sa(n)}}function Lg(e){return e.split("/").slice(0,-1).join("/")}function Og(...e){return e.filter(Boolean).join("/")}var kr,on=i(()=>{"use strict";p();O();kr=class e{#e;#t;#n;#r;constructor(t,n,r,a){this.#e=t,this.#n=n,this.#t=r,this.#r=a}static async open(t){let n=await t.read(),r=typeof n=="string"?new TextEncoder().encode(n):n,a=X("sha256").update(r).digest("hex"),o=await L().zip.open(t);try{let s=new Map;for(let c of await o.listEntries()){let d=Se(c);d!==""&&s.set(d,c)}return new e(t,o,s,a)}catch(s){throw await o.close(),s}}close(){return this.#n.close()}hasEntry(t){return this.#t.has(Se(t))}listEntries(){return[...this.#t.keys()]}async readText(t){return new TextDecoder().decode(await this.readBuffer(t))}async readBuffer(t){let n=this.#i(t),r=await this.#n.readEntry(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${Se(t)}`);return r}resolveRelativePath(t,n){let r=Pg(n);if(r==="")throw new Error(`Invalid EPUB href: ${n}`);return Se(Og(Lg(Se(t)),r))}createSectionId(t,n){let r=Se(t);return n===void 0||n===""?r:`${r}#${n}`}createSyntheticSectionId(t,n){let r=Se(t);return`toc:${X("sha1").update(`${r}:${n??""}`).digest("hex").slice(0,10)}`}get name(){return this.#e.name}get digest(){return this.#r}#i(t){let n=Se(t),r=this.#t.get(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${n}`);return r}}});import{parseDocument as Ng}from"htmlparser2";async function pd(e,t){let n=new Map;for(let[r,a]of t.entries()){let o=await hd(e,r),s=fd(o,a);for(let c of a){let d=s.get(c.id)??"";n.set(c.id,{hasContent:d.trim()!=="",wordsCount:tt(d)})}}return n}function Mg(e){let t=new Map;for(let[n,r]of e.entries())for(let a of r)t.set(a.id,{path:n,targets:r});return t}async function hd(e,t){return await e.readText(t)}function fd(e,t){let n=yd(e,t,!1);return new Map([...n.entries()].map(([r,a])=>[t[r].id,a.text]))}function Wg(e,t,n){let r=yd(e,t,!0),a=t.findIndex(s=>s.id===n),o=r.get(a);if(o===void 0)throw new Error("EPUB section content could not be parsed.");return o}function yd(e,t,n){let r=new Map,a=new Map,o=[...t],c=o[0]?.fragment===void 0&&o[0]!==void 0?0:-1;o.forEach((g,v)=>{a.set(v,[]),g.fragment!==void 0&&!r.has(g.fragment)&&r.set(g.fragment,v)});let d=Ng(e,{decodeEntities:!0}),u=(d.children??[]).find(ud);if(u===void 0){if(n)throw new Error("EPUB XHTML document has no root element for CFI.");f(d,"")}else f(u,"");return new Map([...a.entries()].map(([g,v])=>{let P=Gg(v);return[g,{segments:P.segments,text:P.text}]}));function f(g,v){if(dd(g)){if(c<0||c>=o.length)return;let W=g.data??"";if(W==="")return;let Z=o[c],Xe=Z?.spineIndex;if(n&&Xe===void 0)throw new Error(`EPUB section ${Z?.id??"unknown"} cannot produce a CFI locator.`);let ur=n&&Xe!==void 0?md(Xe,v,0,W.length):ca;w(c,W,ur,n?0:void 0,n?W.length:void 0);return}let P=Hg(g);if(P===void 0){x(g,v);return}if(Fg.has(P))return;let H=v,M=g.attribs?.id??g.attribs?.["xml:id"];if(M!==void 0){let W=r.get(M);W!==void 0&&W>c&&(c=W)}P==="br"&&R(c,`
22
- `,H),x(g,H),Dg.has(P)&&R(c,`
21
+ `,hi=new Map});async function X(n,e,t={create:!0,mode:"readwrite"}){await gn();let r=await H(v().library,n);return t.mode==="readonly"?await Ft(r,e,t):await Ft(r,e,t)}async function Ft(n,e,t={create:!0,mode:"readwrite"}){let r=await hn(n);return t.mode==="readonly"?await N.open(r,e,t):await N.open(r,e,t)}var Vu=i(()=>{"use strict";y();ki();w()});function Ii(...n){let e=[];for(let t of n)for(let r of t.replaceAll("\\","/").split("/"))if(!(r===""||r==="."))if(r===".."){if(e.length===0)throw new TypeError("Relative path escapes its root");e.pop()}else e.push(r);return e.join("/")}function po(n){return Ii(n).split("/").at(-1)??""}var bn=i(()=>{"use strict"});var Mt=i(()=>{"use strict";bn()});var Yu=i(()=>{"use strict"});function Vn(n){let e=new Set(Object.values(n));return t=>e.has(t)}function Gt(n,e){let t=Vn(n);return r=>{if(t(r))return r;throw new Error(`Unknown ${e}: ${r}`)}}var ho=i(()=>{"use strict"});var he,Zu,fo,Re,el,Ei,ve=i(()=>{"use strict";ho();he=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(he||{}),Zu=Vn(he),fo=Gt(he,"chunk retention"),Re=(r=>(r.Critical="critical",r.Important="important",r.Helpful="helpful",r))(Re||{}),el=Vn(Re),Ei=Gt(Re,"chunk importance")});var yo=i(()=>{"use strict";ve()});function Sn(n){let e=0,t=!1;for(let r of n.trim()){if(Sk.test(r)){e+=1,t=!1;continue}if(wk.test(r)){t||(e+=1),t=!0;continue}t&&kk.test(r)||(t=!1)}return e}var Sk,wk,kk,wn=i(()=>{"use strict";Sk=new RegExp("\\p{Script=Han}","u"),wk=/[\p{Letter}\p{Number}]/u,kk=new RegExp("\\p{Mark}","u")});var tl=i(()=>{"use strict";wn();ve()});var Ri=i(()=>{"use strict"});var bo=i(()=>{"use strict";Mt();ve();yo();tl();Ri()});var rl=i(()=>{"use strict";Mt();Yu();bo()});var So=i(()=>{"use strict";rl();yo();bo();Ri()});var vi=i(()=>{"use strict";y();bn()});var wo=i(()=>{"use strict"});var al=i(()=>{"use strict";bn();vi()});var ol=i(()=>{"use strict";wn()});var ko=i(()=>{"use strict"});var xo=i(()=>{"use strict";bn();pe();wo();vi();al();ol();ko()});var sl=i(()=>{"use strict";bn();vi();xo()});var Io=i(()=>{"use strict";sl();wo();xo();ko()});import{z as fe}from"zod";var dl,Ve,cl,ul,jt=i(()=>{"use strict";dl=["epub","pdf","txt","markdown"],Ve=1,cl=fe.enum(dl),ul=fe.object({version:fe.literal(Ve),sourceFormat:cl,title:fe.string().min(1).nullable(),authors:fe.array(fe.string().min(1)),language:fe.string().min(1).nullable(),identifier:fe.string().min(1).nullable(),publisher:fe.string().min(1).nullable(),publishedAt:fe.string().min(1).nullable(),description:fe.string().min(1).nullable()})});function ll(n,e="chapter key"){if(n===""||n==="."||n===".."||n.includes("/"))throw new Error(`Invalid ${e}: chapter paths do not support empty, '.', '..', or relative segments.`);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new Error(`Invalid ${e}: ${n}. Use lowercase letters, numbers, and hyphens.`);if(/^\d+$/u.test(n))throw new Error(`Invalid ${e}: numeric chapter keys are not accepted.`);if(_k.has(n))throw new Error(`Invalid ${e}: ${n} is reserved.`);return n}var _k,ye=i(()=>{"use strict";Ee();U();_k=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as Fe}from"zod";var Ye,Eo,ml,Ro=i(()=>{"use strict";ye();Ye=1,Eo=Fe.object({key:Fe.string().min(1).transform(n=>ll(n)).optional(),title:Fe.string().min(1).nullable().optional(),serialId:Fe.number().int().nonnegative().optional(),children:Fe.lazy(()=>Fe.array(Eo))}),ml=Fe.object({version:Fe.literal(Ye),items:Fe.array(Eo)})});function Ce(n){let e=[];for(let t of n.replaceAll("\\","/").trim().split("/"))t===""||t==="."||(t===".."?e.pop():e.push(t));return e.join("/")}function Pk(n){let[e]=n.split("#",1);return Ce(e??"")}function vo(n){if(n===void 0)return;let e=n.startsWith("#")?n.slice(1):n;return e===""?void 0:e}function Bt(n){let[e,t]=n.split("#",2);return{path:Ce(e??""),fragment:vo(t)}}function Ak(n){return n.split("/").slice(0,-1).join("/")}function Lk(...n){return n.filter(Boolean).join("/")}var Ci,Ut=i(()=>{"use strict";y();U();Ci=class n{#e;#n;#t;#r;constructor(e,t,r,a){this.#e=e,this.#t=t,this.#n=r,this.#r=a}static async open(e){let t=await e.openReader(),r=oe("sha256");try{for(let s=0;s<t.size;){let d=await t.read(s,Math.min(65536,t.size-s));r.update(d),s+=d.byteLength}}finally{await t.close()}let a=r.digest("hex"),o=await L().zip.open(e);try{let s=new Map;for(let d of await o.listEntries()){let c=Ce(d);c!==""&&s.set(c,d)}return new n(e,o,s,a)}catch(s){throw await o.close(),s}}close(){return this.#t.close()}hasEntry(e){return this.#n.has(Ce(e))}listEntries(){return[...this.#n.keys()]}async readText(e){return new TextDecoder().decode(await this.readBuffer(e))}async readBuffer(e){let t=this.#i(e),r=await this.#t.readEntry(t);if(r===void 0)throw new Error(`EPUB entry does not exist: ${Ce(e)}`);return r}resolveRelativePath(e,t){let r=Pk(t);if(r==="")throw new Error(`Invalid EPUB href: ${t}`);return Ce(Lk(Ak(Ce(e)),r))}createSectionId(e,t){let r=Ce(e);return t===void 0||t===""?r:`${r}#${t}`}createSyntheticSectionId(e,t){let r=Ce(e);return`toc:${oe("sha1").update(`${r}:${t??""}`).digest("hex").slice(0,10)}`}get name(){return this.#e.name}get digest(){return this.#r}#i(e){let t=Ce(e),r=this.#n.get(t);if(r===void 0)throw new Error(`EPUB entry does not exist: ${t}`);return r}}});import{parseDocument as Ok}from"htmlparser2";async function bl(n,e){let t=new Map;for(let[r,a]of e.entries()){let o=await Sl(n,r),s=wl(o,a);for(let d of a){let c=s.get(d.id)??"";t.set(d.id,{hasContent:c.trim()!=="",wordsCount:Sn(c)})}}return t}function Wk(n){let e=new Map;for(let[t,r]of n.entries())for(let a of r)e.set(a.id,{path:t,targets:r});return e}async function Sl(n,e){return await n.readText(e)}function wl(n,e){let t=kl(n,e,!1);return new Map([...t.entries()].map(([r,a])=>[e[r].id,a.text]))}function Fk(n,e,t){let r=kl(n,e,!0),a=e.findIndex(s=>s.id===t),o=r.get(a);if(o===void 0)throw new Error("EPUB section content could not be parsed.");return o}function kl(n,e,t){let r=new Map,a=new Map,o=[...e],d=o[0]?.fragment===void 0&&o[0]!==void 0?0:-1;o.forEach((g,C)=>{a.set(C,[]),g.fragment!==void 0&&!r.has(g.fragment)&&r.set(g.fragment,C)});let c=Ok(n,{decodeEntities:!0}),u=(c.children??[]).find(fl);if(u===void 0){if(t)throw new Error("EPUB XHTML document has no root element for CFI.");m(c,"")}else m(u,"");return new Map([...a.entries()].map(([g,C])=>{let A=Gk(C);return[g,{segments:A.segments,text:A.text}]}));function m(g,C){if(hl(g)){if(d<0||d>=o.length)return;let G=g.data??"";if(G==="")return;let ie=o[d],mn=ie?.spineIndex;if(t&&mn===void 0)throw new Error(`EPUB section ${ie?.id??"unknown"} cannot produce a CFI locator.`);let ai=t&&mn!==void 0?gl(mn,C,0,G.length):Co;f(d,G,ai,t?0:void 0,t?G.length:void 0);return}let A=Uk(g);if(A===void 0){b(g,C);return}if(Dk.has(A))return;let K=C,q=g.attribs?.id??g.attribs?.["xml:id"];if(q!==void 0){let G=r.get(q);G!==void 0&&G>d&&(d=G)}A==="br"&&k(d,`
22
+ `,K),b(g,K),Nk.has(A)&&k(d,`
23
23
 
24
- `,H)}function x(g,v){let P=0,H=new Map;for(let M of g.children??[]){if(dd(M)){if(c<0||c>=o.length)continue;let Z=M.data??"";if(Z==="")continue;let Xe=P*2+1,ur=H.get(Xe)??0;H.set(Xe,ur+Z.length);let vy=ld(v,Xe,!0);D(M,vy,ur,Z.length);continue}if(!ud(M))continue;let W=ld(v,P,!1,M.attribs?.id??M.attribs?.["xml:id"]);P+=1,f(M,W)}}function D(g,v,P,H){if(c<0||c>=o.length)return;let M=g.data??"",W=o[c],Z=W?.spineIndex;if(n&&Z===void 0)throw new Error(`EPUB section ${W?.id??"unknown"} cannot produce a CFI locator.`);w(c,M,n&&Z!==void 0?md(Z,v,P,P+H):ca,n?P:void 0,n?P+H:void 0)}function w(g,v,P,H,M){let W=a.get(g);W!==void 0&&W.push({locator:P,...M===void 0?{}:{locatorEnd:M},...H===void 0?{}:{locatorStart:H},text:v})}function R(g,v,P){if(g<0||g>=o.length)return;let H=o[g],M=H?.spineIndex;if(n&&M===void 0)throw new Error(`EPUB section ${H?.id??"unknown"} cannot produce a CFI locator.`);w(g,v,n&&M!==void 0?$g(M,P):ca)}}function jg(e,t){let n=[],r=0;for(let a of e){let o=r;r+=Array.from(a.text).length,o!==r&&n.push({artifactDigest:t,locator:a.locator,sourceEnd:r,sourceStart:o})}return n}function Gg(e){let t=[];for(let d of e){let u=Array.from(d.text),f=0;for(let x=0;x<u.length;x+=1){let D=u[x],w=d.locatorStart===void 0?void 0:d.locatorStart+f;f+=D.length;let R=d.locatorEnd===void 0||d.locatorStart===void 0?void 0:d.locatorStart+f;D==="\r"&&u[x+1]===`
25
- `?(f+=1,R=d.locatorStart===void 0?void 0:d.locatorStart+f,t.push({baseLocator:d.locator,char:`
26
- `,locator:da(d.locator,w,R),locatorEnd:R,locatorStart:w}),x+=1):t.push({baseLocator:d.locator,char:D,locator:da(d.locator,w,R),locatorEnd:R,locatorStart:w})}}let n=[],r=0;for(let d of t){if(d.char===`
27
- `){if(r+=1,r>2)continue}else r=0;n.push(d)}let a=0;for(;a<n.length&&n[a].char.trim()==="";)a+=1;let o=n.length;for(;o>a&&n[o-1].char.trim()==="";)o-=1;let s=n.slice(a,o),c=[];for(let d of s){let u=c.at(-1);u!==void 0&&u.locatorBase===d.baseLocator&&u.locatorEnd===d.locatorStart&&u.locatorStart!==void 0&&d.locatorEnd!==void 0?c[c.length-1]={locatorBase:u.locatorBase,locator:da(u.locatorBase??u.locator,u.locatorStart,d.locatorEnd),locatorEnd:d.locatorEnd,locatorStart:u.locatorStart,text:u.text+d.char}:u!==void 0&&u.locatorBase===d.baseLocator&&u.locatorStart===void 0&&d.locatorStart===void 0?c[c.length-1]={locatorBase:u.locatorBase,locator:u.locator,text:u.text+d.char}:c.push({locatorBase:d.baseLocator,locator:d.locator,...d.locatorEnd===void 0?{}:{locatorEnd:d.locatorEnd},...d.locatorStart===void 0?{}:{locatorStart:d.locatorStart},text:d.char})}return{segments:c,text:s.map(d=>d.char).join("")}}function da(e,t,n){if(t===void 0||n===void 0)return e;let r=e.cfi;if(typeof r!="string")throw new Error("EPUB text mapping is missing a CFI locator.");let a=Bg(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...e,cfi:`epubcfi(${a.parentPath},${cd(a.startPath,t)},${cd(a.endPath,n)})`}}function Bg(e){if(!e.startsWith("epubcfi(")||!e.endsWith(")"))return;let t=Ug(e.slice(8,-1));if(t.length!==3||t.some(o=>o===""))return;let[n,r,a]=t;if(!(n===void 0||r===void 0||a===void 0))return{endPath:a,parentPath:n,startPath:r}}function Ug(e){let t=[],n=0,r=0,a=!1;for(let o=0;o<e.length;o+=1){let s=e[o];if(a){a=!1;continue}if(s==="^"){a=!0;continue}if(s==="["){r+=1;continue}if(s==="]"){r-=1;continue}s===","&&r===0&&(t.push(e.slice(n,o)),n=o+1)}return t.push(e.slice(n)),t}function cd(e,t){if(!/:\d+$/u.test(e))throw new Error("EPUB text mapping has an invalid CFI offset.");return e.replace(/:\d+$/u,`:${t}`)}function Hg(e){return e.name?.toLowerCase()}function dd(e){return e.type==="text"}function ud(e){return e.name!==void 0&&e.type!=="directive"}function ld(e,t,n,r){let a=n?t:(t+1)*2,o=n||r===void 0?"":`[${Jg(r)}]`;return`${e}/${a}${o}`}function md(e,t,n,r){let a=gd(e),{parentPath:o,textPath:s}=qg(t),c=o===""?a:`${a}!${o}`,d=o===""?`!${s}:${n}`:`${s}:${n}`,u=o===""?`!${s}:${r}`:`${s}:${r}`;return{cfi:`epubcfi(${c},${d},${u})`}}function qg(e){let t=e.lastIndexOf("/");if(t<0||t===e.length-1)throw new Error(`EPUB text mapping has an invalid CFI path: ${e}`);return{parentPath:e.slice(0,t),textPath:e.slice(t)}}function $g(e,t){return{cfi:`epubcfi(${Kg(e)}${t})`}}function Kg(e){return`${gd(e)}!`}function gd(e){return`/6/${(e+1)*2}`}function Jg(e){return[...e].map(t=>"[]^(),;=".includes(t)?`^${t}`:t).join("")}var Dg,Fg,ca,Rr,bd=i(()=>{"use strict";nt();Dg=new Set(["address","article","aside","blockquote","br","dd","div","dl","dt","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","td","th","tr","ul"]),Fg=new Set(["script","style"]),ca={},Rr=class{#e;#t;constructor(t,n){this.#e=t,this.#t=Mg(n)}async openSection(t){let n=this.#t.get(t);return n===void 0?[]:[(await this.#n(n.path,n.targets)).get(t)??""]}async openSectionWithProvenance(t,n){let r=this.#t.get(t);if(r===void 0)return{stream:[]};if(r.targets.find(d=>d.id===t)?.spineIndex===void 0)throw new Error(`EPUB section ${t} is not associated with a spine item.`);let o=await this.#e.readText(r.path),s=Wg(o,r.targets,t),c=jg(s.segments,n.digest);if(s.text.length>0&&c.length===0)throw new Error(`EPUB section ${t} produced text without provenance mappings.`);return{provenance:{artifacts:[n],mappings:c},stream:[s.text]}}async#n(t,n){let r=await hd(this.#e,t);return fd(r,n)}}});import{SaxesParser as zg}from"saxes";function sn(e){let t=new zg({xmlns:!1}),n=[],r;if(t.on("opentag",a=>{let o={name:a.name,attributes:Object.fromEntries(Object.entries(a.attributes).map(([c,d])=>[c,String(d)])),children:[],text:""},s=n[n.length-1];s===void 0?r=o:s.children.push(o),n.push(o)}),t.on("text",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),t.on("cdata",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),t.on("closetag",()=>{n.pop()}),t.write(e).close(),r===void 0)throw new Error("XML document is empty");return Sd(r)}function ce(e,t){return e.children.find(n=>dn(n.name)===t)}function Fe(e,t){return e.children.filter(n=>dn(n.name)===t)}function J(e,t){return e.attributes[t]}function cn(e){let t=e.text;for(let n of e.children)t+=cn(n);return t}function dn(e){let t=e.indexOf(":");return t===-1?e:e.slice(t+1)}function Sd(e){return{name:e.name,attributes:Object.freeze({...e.attributes}),children:Object.freeze(e.children.map(Sd)),text:e.text}}var ua=i(()=>{"use strict"});async function Ed(e){let t=await Vg(e),n=sn(await e.readText(t)),r=Yg(J(n,"version")),a=ce(n,"metadata"),o=ce(n,"manifest"),s=ce(n,"spine"),c=ce(n,"guide"),d=eb(e,t,o),u=new Map([...d.values()].map(v=>[v.path,v])),f=tb(s,d),x=nb(e,t,c),D=Zg(a),w=rb(d),R=ib(d,s),g=ab(d,a);return{version:r,opfPath:t,metadata:{...D,version:De,sourceFormat:"epub"},manifest:d,manifestByPath:u,spine:f,navPath:w,ncxPath:R,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:x}}async function Vg(e){let t=sn(await e.readText("META-INF/container.xml")),r=ce(t,"rootfiles")?.children.find(o=>dn(o.name)==="rootfile"),a=r===void 0?void 0:J(r,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function Yg(e){return e?.trim().startsWith("3")===!0?3:2}function Zg(e){if(e===void 0)return wd();let t=it(e,"title"),n=it(e,"creator"),r=it(e,"language"),a=it(e,"identifier"),o=it(e,"publisher"),s=it(e,"date"),c=it(e,"description");return{...wd(),title:t[0]??null,authors:[...n],language:r[0]??null,identifier:a[0]??null,publisher:o[0]??null,publishedAt:s[0]??null,description:c[0]??null}}function wd(){return{version:De,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function it(e,t){return e.children.filter(n=>dn(n.name)===t).map(n=>sb(cn(n))).filter(n=>n!==void 0)}function eb(e,t,n){let r=new Map;if(n===void 0)return r;for(let a of Fe(n,"item")){let o=J(a,"id"),s=J(a,"href"),c=J(a,"media-type")??"";o===void 0||s===void 0||r.set(o,{id:o,path:e.resolveRelativePath(t,s),mediaType:c,properties:new Set((J(a,"properties")??"").split(/\s+/u).map(d=>d.trim().toLowerCase()).filter(d=>d!==""))})}return r}function tb(e,t){return e===void 0?[]:Fe(e,"itemref").map((n,r)=>{let a=J(n,"idref");if(a===void 0)return;let o=t.get(a);if(!(o===void 0||o.mediaType!=="application/xhtml+xml"&&o.mediaType!=="text/html"))return{idref:a,path:o.path,mediaType:o.mediaType,spineIndex:r}}).filter(n=>n!==void 0)}function nb(e,t,n){let r=new Set;if(n===void 0)return r;for(let a of Fe(n,"reference")){let o=(J(a,"type")??"").trim().toLowerCase();if(!Qg.has(o))continue;let s=J(a,"href");s===void 0||s.trim()===""||r.add(e.resolveRelativePath(t,an(s).path))}return r}function rb(e){for(let t of e.values())if(t.properties.has("nav"))return t.path}function ib(e,t){let n=t===void 0?void 0:J(t,"toc");if(n!==void 0)return e.get(n)?.path;for(let r of e.values())if(r.mediaType==="application/x-dtbncx+xml")return r.path}function ab(e,t){for(let r of e.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=ob(t);if(n!==void 0){let r=e.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of Xg){let a=e.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of e.values())if(r.mediaType.startsWith("image/")&&zi(r.path).toLowerCase().includes("cover"))return r}function ob(e){if(e!==void 0)for(let t of Fe(e,"meta")){if((J(t,"name")??"").trim().toLowerCase()!=="cover")continue;let r=J(t,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function sb(e){let t=e.replace(/\s+/gu," ").trim();return t===""?void 0:t}var Xg,Qg,la=i(()=>{"use strict";et();rn();on();ua();Xg=["cover-image","coverimg","cover-img","cover"],Qg=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as cb}from"htmlparser2";async function Id(e,t){let n=await ub(e,t)??await lb(e,t)??[];if(n.length===0)return xd(t,new Set);let r=vd(n),a=xd(t,r);return a.length===0?n:[...n,...a]}async function ub(e,t){if(t.navPath===void 0)return;let n=cb(await e.readText(t.navPath),{decodeEntities:!0}),r=ma(n,s=>Me(s)!=="nav"?!1:(s.attribs?.["epub:type"]??s.attribs?.type??"").split(/\s+/u).map(d=>d.trim().toLowerCase()).includes("toc"));if(r===void 0)return;let a=ma(r,s=>Me(s)==="ol");if(a===void 0)return;let o=un(a).filter(s=>Me(s)==="li").map(s=>kd(e,t.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function lb(e,t){if(t.ncxPath===void 0)return;let n=sn(await e.readText(t.ncxPath)),r=ce(n,"navMap");if(r===void 0)return;let a=Fe(r,"navPoint").map(o=>Rd(e,t.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function kd(e,t,n){let r=_d(n),a=r===void 0?void 0:Ad(Td(r)),o=r!==void 0&&Me(r)==="a"?r.attribs?.href:void 0,s=pb(e,t,o),c=un(n).filter(d=>Me(d)==="ol").flatMap(d=>un(d)).filter(d=>Me(d)==="li").map(d=>kd(e,t,d)).filter(d=>d!==void 0);if(!(a===void 0&&s.path===void 0&&c.length===0))return{title:a,path:s.path,fragment:s.fragment,children:c}}function Rd(e,t,n){let r=ce(n,"navLabel"),a=r===void 0?void 0:ce(r,"text"),o=a===void 0?void 0:Ad(cn(a)),s=ce(n,"content"),c=hb(e,t,J(s??n,"src")),d=Fe(n,"navPoint").map(u=>Rd(e,t,u)).filter(u=>u!==void 0);if(!(o===void 0&&c.path===void 0&&d.length===0))return{title:o,path:c.path,fragment:c.fragment,children:d}}function xd(e,t){return e.spine.filter(n=>!mb(e,n.path,t)).filter(n=>!t.has(n.path)).map(n=>({title:fb(n.path),path:n.path,fragment:void 0,children:[]}))}function mb(e,t,n){if(e.guideNonContentPaths.has(t))return!0;let r=pa(t).toLowerCase();return e.navPath===t?!0:db.has(r)&&!n.has(t)}function vd(e){let t=new Set;for(let n of e){n.path!==void 0&&t.add(n.path);for(let r of vd(n.children))t.add(r)}return t}function pb(e,t,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=an(n);return{path:r===""?void 0:e.resolveRelativePath(t,r),fragment:a}}function hb(e,t,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=an(n);return{path:r===""?void 0:e.resolveRelativePath(t,r),fragment:a}}function ma(e,t){if(Cd(e)&&t(e))return e;for(let n of e.children??[]){let r=ma(n,t);if(r!==void 0)return r}}function _d(e){for(let t of un(e)){let n=Me(t);if(n==="a"||n==="span")return t}for(let t of un(e)){if(Me(t)==="ol")continue;let n=_d(t);if(n!==void 0)return n}}function Td(e){return e.type==="text"?e.data??"":(e.children??[]).map(Td).join("")}function un(e){return(e.children??[]).filter(Cd)}function Cd(e){return e.type==="tag"||e.type==="script"||e.type==="style"}function Me(e){return e.name?.toLowerCase()}function fb(e){let t=yb(e),n=pa(e).slice(0,-t.length||void 0).trim();return n===""?void 0:n}function pa(e){return e.replaceAll("\\","/").split("/").at(-1)??""}function yb(e){let t=pa(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n)}function Ad(e){let t=e.replace(/\s+/gu," ").trim();return t===""?void 0:t}var db,Pd=i(()=>{"use strict";on();la();ua();db=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function gb(e){if(e.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function bb(e,t){if(!(t.coverPath===void 0||t.coverMediaType===void 0))return{path:t.coverPath,mediaType:t.coverMediaType,data:await e.readBuffer(t.coverPath)}}function Sb(e,t){let n=new Map;return t.map((r,a)=>Ld(e,r,[a],n))}function Ld(e,t,n,r){let a=sa(t.fragment),o=t.path===void 0?`toc:${n.join(".")}`:e.createSectionId(t.path,a),s=wb(o,r);return{hasContent:t.path!==void 0,id:s,title:t.title,path:t.path,fragment:a,wordsCount:0,children:t.children.map((c,d)=>Ld(e,c,[...n,d],r))}}function Od(e,t){return e.map(n=>{let r=t.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:Od(n.children,t)}})}function wb(e,t){let n=t.get(e)??0;return t.set(e,n+1),n===0?e:`${e}~${n+1}`}function Eb(e,t){let n=new Map,r=new Map(t.spine.map(a=>[a.path,a.spineIndex]));for(let a of Nd(e)){if(a.path===void 0)continue;let o=n.get(a.path)??[];o.push({id:a.id,path:a.path,fragment:a.fragment,spineIndex:r.get(a.path)}),n.set(a.path,o)}return n}function Nd(e){let t=[];for(let n of e)t.push(n),t.push(...Nd(n.children));return t}var ha,fa,ln,ya,Dd=i(()=>{"use strict";on();on();bd();Pd();la();ha=class e{#e;#t;constructor(t,n){this.#e=t,this.#t=n}get id(){return this.#t.id}get hasContent(){return this.#t.hasContent}get title(){return this.#t.title}get wordsCount(){return this.#t.wordsCount}get children(){return this.#t.children.map(t=>new e(this.#e,t))}async open(){return await this.#e.openSection(this.#t.id)}async openWithProvenance(){return await this.#e.openSectionWithProvenance(this.#t.id)}},fa=class e{#e;#t;#n;#r;#i;constructor(t,n,r,a,o){this.#e=t,this.#t=n,this.#n=r,this.#r=a,this.#i=o}static async open(t){gb(t);let n=await Ed(t),r={digest:t.digest,mediaType:"application/epub+zip",name:t.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await Id(t,n),o=Sb(t,a),s=Eb(o,n),c=await pd(t,s),d=Od(o,c),u=await bb(t,n);return new e(r,n,u,d,new Rr(t,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(t=>new ha(this,t)))}async openSection(t){return await this.#i.openSection(t)}async openSectionWithProvenance(t){return await this.#i.openSectionWithProvenance(t,this.#e)}},ln=class{get format(){return"epub"}async openSession(t,n){let r=await kr.open(t);try{let a=await fa.open(r);return await n(a)}finally{await r.close()}}},ya=new ln});var Fd=i(()=>{"use strict";Dd()});async function*Ib(e){for(let t of e.match(/.*(?:\r?\n|$)/gu)??[])t!==""&&(yield t)}function kb(e){let t=e.lastIndexOf("."),n=(t<=0?e:e.slice(0,t)).trim();return n===""?null:n}var xb,ga,ba,mn,Md,Wd,jd=i(()=>{"use strict";rn();xb="root",ga=class{#e;#t;constructor(t,n=xb){this.#e=t,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(Ib(this.#e))}},ba=class{#e;#t;#n;constructor(t,n,r){this.#t=t,this.#n=n,this.#e=new ga(typeof r=="string"?r:new TextDecoder().decode(r))}readMeta(){return Promise.resolve({version:De,sourceFormat:this.#n,title:kb(this.#t.name),authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null})}readCover(){return Promise.resolve(void 0)}readSections(){return Promise.resolve([this.#e])}},mn=class{#e;constructor(t){this.#e=t}get format(){return this.#e}async openSession(t,n){let r=await t.read({encoding:"utf8"});return await n(new ba(t,this.#e,r))}},Md=new mn("txt"),Wd=new mn("markdown")});var pn=i(()=>{"use strict"});import{z as te}from"zod";var mT,pT,Gd=i(()=>{"use strict";pn();mT=te.object({type:te.literal("artifact"),digest:te.string().regex(/^[0-9a-f]{64}$/iu),mediaType:te.string().min(1),name:te.string().optional(),identifier:te.string().max(1024).optional()}),pT=te.object({type:te.literal("text"),text:te.string(),locator:te.record(te.string(),te.unknown())})});var at=i(()=>{"use strict";rn();Fd();jd();Gd();oa()});var wa=i(()=>{"use strict"});var hn=i(()=>{"use strict";at();se();wa()});var vb,Bd,Ud,Hd,fn=i(()=>{"use strict";y();pn();vb=`
24
+ `,K)}function b(g,C){let A=0,K=new Map;for(let q of g.children??[]){if(hl(q)){if(d<0||d>=o.length)continue;let ie=q.data??"";if(ie==="")continue;let mn=A*2+1,ai=K.get(mn)??0;K.set(mn,ai+ie.length);let vw=yl(C,mn,!0);R(q,vw,ai,ie.length);continue}if(!fl(q))continue;let G=yl(C,A,!1,q.attribs?.id??q.attribs?.["xml:id"]);A+=1,m(q,G)}}function R(g,C,A,K){if(d<0||d>=o.length)return;let q=g.data??"",G=o[d],ie=G?.spineIndex;if(t&&ie===void 0)throw new Error(`EPUB section ${G?.id??"unknown"} cannot produce a CFI locator.`);f(d,q,t&&ie!==void 0?gl(ie,C,A,A+K):Co,t?A:void 0,t?A+K:void 0)}function f(g,C,A,K,q){let G=a.get(g);G!==void 0&&G.push({locator:A,...q===void 0?{}:{locatorEnd:q},...K===void 0?{}:{locatorStart:K},text:C})}function k(g,C,A){if(g<0||g>=o.length)return;let K=o[g],q=K?.spineIndex;if(t&&q===void 0)throw new Error(`EPUB section ${K?.id??"unknown"} cannot produce a CFI locator.`);f(g,C,t&&q!==void 0?Hk(q,A):Co)}}function Mk(n,e){let t=[],r=0;for(let a of n){let o=r;r+=Array.from(a.text).length,o!==r&&t.push({artifactDigest:e,locator:a.locator,sourceEnd:r,sourceStart:o})}return t}function Gk(n){let e=[];for(let c of n){let u=Array.from(c.text),m=0;for(let b=0;b<u.length;b+=1){let R=u[b],f=c.locatorStart===void 0?void 0:c.locatorStart+m;m+=R.length;let k=c.locatorEnd===void 0||c.locatorStart===void 0?void 0:c.locatorStart+m;R==="\r"&&u[b+1]===`
25
+ `?(m+=1,k=c.locatorStart===void 0?void 0:c.locatorStart+m,e.push({baseLocator:c.locator,char:`
26
+ `,locator:To(c.locator,f,k),locatorEnd:k,locatorStart:f}),b+=1):e.push({baseLocator:c.locator,char:R,locator:To(c.locator,f,k),locatorEnd:k,locatorStart:f})}}let t=[],r=0;for(let c of e){if(c.char===`
27
+ `){if(r+=1,r>2)continue}else r=0;t.push(c)}let a=0;for(;a<t.length&&t[a].char.trim()==="";)a+=1;let o=t.length;for(;o>a&&t[o-1].char.trim()==="";)o-=1;let s=t.slice(a,o),d=[];for(let c of s){let u=d.at(-1);u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorEnd===c.locatorStart&&u.locatorStart!==void 0&&c.locatorEnd!==void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:To(u.locatorBase??u.locator,u.locatorStart,c.locatorEnd),locatorEnd:c.locatorEnd,locatorStart:u.locatorStart,text:u.text+c.char}:u!==void 0&&u.locatorBase===c.baseLocator&&u.locatorStart===void 0&&c.locatorStart===void 0?d[d.length-1]={locatorBase:u.locatorBase,locator:u.locator,text:u.text+c.char}:d.push({locatorBase:c.baseLocator,locator:c.locator,...c.locatorEnd===void 0?{}:{locatorEnd:c.locatorEnd},...c.locatorStart===void 0?{}:{locatorStart:c.locatorStart},text:c.char})}return{segments:d,text:s.map(c=>c.char).join("")}}function To(n,e,t){if(e===void 0||t===void 0)return n;let r=n.cfi;if(typeof r!="string")throw new Error("EPUB text mapping is missing a CFI locator.");let a=jk(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...n,cfi:`epubcfi(${a.parentPath},${pl(a.startPath,e)},${pl(a.endPath,t)})`}}function jk(n){if(!n.startsWith("epubcfi(")||!n.endsWith(")"))return;let e=Bk(n.slice(8,-1));if(e.length!==3||e.some(o=>o===""))return;let[t,r,a]=e;if(!(t===void 0||r===void 0||a===void 0))return{endPath:a,parentPath:t,startPath:r}}function Bk(n){let e=[],t=0,r=0,a=!1;for(let o=0;o<n.length;o+=1){let s=n[o];if(a){a=!1;continue}if(s==="^"){a=!0;continue}if(s==="["){r+=1;continue}if(s==="]"){r-=1;continue}s===","&&r===0&&(e.push(n.slice(t,o)),t=o+1)}return e.push(n.slice(t)),e}function pl(n,e){if(!/:\d+$/u.test(n))throw new Error("EPUB text mapping has an invalid CFI offset.");return n.replace(/:\d+$/u,`:${e}`)}function Uk(n){return n.name?.toLowerCase()}function hl(n){return n.type==="text"}function fl(n){return n.name!==void 0&&n.type!=="directive"}function yl(n,e,t,r){let a=t?e:(e+1)*2,o=t||r===void 0?"":`[${Jk(r)}]`;return`${n}/${a}${o}`}function gl(n,e,t,r){let a=xl(n),{parentPath:o,textPath:s}=qk(e),d=o===""?a:`${a}!${o}`,c=o===""?`!${s}:${t}`:`${s}:${t}`,u=o===""?`!${s}:${r}`:`${s}:${r}`;return{cfi:`epubcfi(${d},${c},${u})`}}function qk(n){let e=n.lastIndexOf("/");if(e<0||e===n.length-1)throw new Error(`EPUB text mapping has an invalid CFI path: ${n}`);return{parentPath:n.slice(0,e),textPath:n.slice(e)}}function Hk(n,e){return{cfi:`epubcfi(${$k(n)}${e})`}}function $k(n){return`${xl(n)}!`}function xl(n){return`/6/${(n+1)*2}`}function Jk(n){return[...n].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var Nk,Dk,Co,Ti,Il=i(()=>{"use strict";wn();Nk=new Set(["address","article","aside","blockquote","br","dd","div","dl","dt","figcaption","figure","footer","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","td","th","tr","ul"]),Dk=new Set(["script","style"]),Co={},Ti=class{#e;#n;constructor(e,t){this.#e=e,this.#n=Wk(t)}async openSection(e){let t=this.#n.get(e);return t===void 0?[]:[(await this.#t(t.path,t.targets)).get(e)??""]}async openSectionWithProvenance(e,t){let r=this.#n.get(e);if(r===void 0)return{stream:[]};if(r.targets.find(c=>c.id===e)?.spineIndex===void 0)throw new Error(`EPUB section ${e} is not associated with a spine item.`);let o=await this.#e.readText(r.path),s=Fk(o,r.targets,e),d=Mk(s.segments,t.digest);if(s.text.length>0&&d.length===0)throw new Error(`EPUB section ${e} produced text without provenance mappings.`);return{provenance:{artifacts:[t],mappings:d},stream:[s.text]}}async#t(e,t){let r=await Sl(this.#e,e);return wl(r,t)}}});import{SaxesParser as Kk}from"saxes";function qt(n){let e=new Kk({xmlns:!1}),t=[],r;if(e.on("opentag",a=>{let o={name:a.name,attributes:Object.fromEntries(Object.entries(a.attributes).map(([d,c])=>[d,String(c)])),children:[],text:""},s=t[t.length-1];s===void 0?r=o:s.children.push(o),t.push(o)}),e.on("text",a=>{let o=t[t.length-1];o!==void 0&&(o.text+=a)}),e.on("cdata",a=>{let o=t[t.length-1];o!==void 0&&(o.text+=a)}),e.on("closetag",()=>{t.pop()}),e.write(n).close(),r===void 0)throw new Error("XML document is empty");return El(r)}function ge(n,e){return n.children.find(t=>$t(t.name)===e)}function Ze(n,e){return n.children.filter(t=>$t(t.name)===e)}function ee(n,e){return n.attributes[e]}function Ht(n){let e=n.text;for(let t of n.children)e+=Ht(t);return e}function $t(n){let e=n.indexOf(":");return e===-1?n:n.slice(e+1)}function El(n){return{name:n.name,attributes:Object.freeze({...n.attributes}),children:Object.freeze(n.children.map(El)),text:n.text}}var _o=i(()=>{"use strict"});async function vl(n){let e=await Xk(n),t=qt(await n.readText(e)),r=Vk(ee(t,"version")),a=ge(t,"metadata"),o=ge(t,"manifest"),s=ge(t,"spine"),d=ge(t,"guide"),c=Zk(n,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=ex(s,c),b=nx(n,e,d),R=Yk(a),f=tx(c),k=rx(c,s),g=ix(c,a);return{version:r,opfPath:e,metadata:{...R,version:Ve,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:f,ncxPath:k,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:b}}async function Xk(n){let e=qt(await n.readText("META-INF/container.xml")),r=ge(e,"rootfiles")?.children.find(o=>$t(o.name)==="rootfile"),a=r===void 0?void 0:ee(r,"full-path");if(a===void 0||a.trim()==="")throw new Error("EPUB container.xml does not contain an OPF rootfile");return a}function Vk(n){return n?.trim().startsWith("3")===!0?3:2}function Yk(n){if(n===void 0)return Rl();let e=kn(n,"title"),t=kn(n,"creator"),r=kn(n,"language"),a=kn(n,"identifier"),o=kn(n,"publisher"),s=kn(n,"date"),d=kn(n,"description");return{...Rl(),title:e[0]??null,authors:[...t],language:r[0]??null,identifier:a[0]??null,publisher:o[0]??null,publishedAt:s[0]??null,description:d[0]??null}}function Rl(){return{version:Ve,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function kn(n,e){return n.children.filter(t=>$t(t.name)===e).map(t=>ox(Ht(t))).filter(t=>t!==void 0)}function Zk(n,e,t){let r=new Map;if(t===void 0)return r;for(let a of Ze(t,"item")){let o=ee(a,"id"),s=ee(a,"href"),d=ee(a,"media-type")??"";o===void 0||s===void 0||r.set(o,{id:o,path:n.resolveRelativePath(e,s),mediaType:d,properties:new Set((ee(a,"properties")??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).filter(c=>c!==""))})}return r}function ex(n,e){return n===void 0?[]:Ze(n,"itemref").map((t,r)=>{let a=ee(t,"idref");if(a===void 0)return;let o=e.get(a);if(!(o===void 0||o.mediaType!=="application/xhtml+xml"&&o.mediaType!=="text/html"))return{idref:a,path:o.path,mediaType:o.mediaType,spineIndex:r}}).filter(t=>t!==void 0)}function nx(n,e,t){let r=new Set;if(t===void 0)return r;for(let a of Ze(t,"reference")){let o=(ee(a,"type")??"").trim().toLowerCase();if(!Qk.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(n.resolveRelativePath(e,Bt(s).path))}return r}function tx(n){for(let e of n.values())if(e.properties.has("nav"))return e.path}function rx(n,e){let t=e===void 0?void 0:ee(e,"toc");if(t!==void 0)return n.get(t)?.path;for(let r of n.values())if(r.mediaType==="application/x-dtbncx+xml")return r.path}function ix(n,e){for(let r of n.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let t=ax(e);if(t!==void 0){let r=n.get(t);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of zk){let a=n.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of n.values())if(r.mediaType.startsWith("image/")&&po(r.path).toLowerCase().includes("cover"))return r}function ax(n){if(n!==void 0)for(let e of Ze(n,"meta")){if((ee(e,"name")??"").trim().toLowerCase()!=="cover")continue;let r=ee(e,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function ox(n){let e=n.replace(/\s+/gu," ").trim();return e===""?void 0:e}var zk,Qk,Po=i(()=>{"use strict";bn();jt();Ut();_o();zk=["cover-image","coverimg","cover-img","cover"],Qk=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as sx}from"htmlparser2";async function Tl(n,e){let t=await cx(n,e)??await ux(n,e)??[];if(t.length===0)return Cl(e,new Set);let r=Al(t),a=Cl(e,r);return a.length===0?t:[...t,...a]}async function cx(n,e){if(e.navPath===void 0)return;let t=sx(await n.readText(e.navPath),{decodeEntities:!0}),r=Ao(t,s=>en(s)!=="nav"?!1:(s.attribs?.["epub:type"]??s.attribs?.type??"").split(/\s+/u).map(c=>c.trim().toLowerCase()).includes("toc"));if(r===void 0)return;let a=Ao(r,s=>en(s)==="ol");if(a===void 0)return;let o=Jt(a).filter(s=>en(s)==="li").map(s=>_l(n,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function ux(n,e){if(e.ncxPath===void 0)return;let t=qt(await n.readText(e.ncxPath)),r=ge(t,"navMap");if(r===void 0)return;let a=Ze(r,"navPoint").map(o=>Pl(n,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function _l(n,e,t){let r=Ll(t),a=r===void 0?void 0:Dl(Ol(r)),o=r!==void 0&&en(r)==="a"?r.attribs?.href:void 0,s=mx(n,e,o),d=Jt(t).filter(c=>en(c)==="ol").flatMap(c=>Jt(c)).filter(c=>en(c)==="li").map(c=>_l(n,e,c)).filter(c=>c!==void 0);if(!(a===void 0&&s.path===void 0&&d.length===0))return{title:a,path:s.path,fragment:s.fragment,children:d}}function Pl(n,e,t){let r=ge(t,"navLabel"),a=r===void 0?void 0:ge(r,"text"),o=a===void 0?void 0:Dl(Ht(a)),s=ge(t,"content"),d=px(n,e,ee(s??t,"src")),c=Ze(t,"navPoint").map(u=>Pl(n,e,u)).filter(u=>u!==void 0);if(!(o===void 0&&d.path===void 0&&c.length===0))return{title:o,path:d.path,fragment:d.fragment,children:c}}function Cl(n,e){return n.spine.filter(t=>!lx(n,t.path,e)).filter(t=>!e.has(t.path)).map(t=>({title:hx(t.path),path:t.path,fragment:void 0,children:[]}))}function lx(n,e,t){if(n.guideNonContentPaths.has(e))return!0;let r=Lo(e).toLowerCase();return n.navPath===e?!0:dx.has(r)&&!t.has(e)}function Al(n){let e=new Set;for(let t of n){t.path!==void 0&&e.add(t.path);for(let r of Al(t.children))e.add(r)}return e}function mx(n,e,t){if(t===void 0||t.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Bt(t);return{path:r===""?void 0:n.resolveRelativePath(e,r),fragment:a}}function px(n,e,t){if(t===void 0||t.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Bt(t);return{path:r===""?void 0:n.resolveRelativePath(e,r),fragment:a}}function Ao(n,e){if(Nl(n)&&e(n))return n;for(let t of n.children??[]){let r=Ao(t,e);if(r!==void 0)return r}}function Ll(n){for(let e of Jt(n)){let t=en(e);if(t==="a"||t==="span")return e}for(let e of Jt(n)){if(en(e)==="ol")continue;let t=Ll(e);if(t!==void 0)return t}}function Ol(n){return n.type==="text"?n.data??"":(n.children??[]).map(Ol).join("")}function Jt(n){return(n.children??[]).filter(Nl)}function Nl(n){return n.type==="tag"||n.type==="script"||n.type==="style"}function en(n){return n.name?.toLowerCase()}function hx(n){let e=fx(n),t=Lo(n).slice(0,-e.length||void 0).trim();return t===""?void 0:t}function Lo(n){return n.replaceAll("\\","/").split("/").at(-1)??""}function fx(n){let e=Lo(n),t=e.lastIndexOf(".");return t<=0?"":e.slice(t)}function Dl(n){let e=n.replace(/\s+/gu," ").trim();return e===""?void 0:e}var dx,Wl=i(()=>{"use strict";Ut();Po();_o();dx=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function yx(n){if(n.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function gx(n,e){if(!(e.coverPath===void 0||e.coverMediaType===void 0))return{path:e.coverPath,mediaType:e.coverMediaType,data:await n.readBuffer(e.coverPath)}}function bx(n,e){let t=new Map;return e.map((r,a)=>Fl(n,r,[a],t))}function Fl(n,e,t,r){let a=vo(e.fragment),o=e.path===void 0?`toc:${t.join(".")}`:n.createSectionId(e.path,a),s=Sx(o,r);return{hasContent:e.path!==void 0,id:s,title:e.title,path:e.path,fragment:a,wordsCount:0,children:e.children.map((d,c)=>Fl(n,d,[...t,c],r))}}function Ml(n,e){return n.map(t=>{let r=e.get(t.id);return{...t,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:Ml(t.children,e)}})}function Sx(n,e){let t=e.get(n)??0;return e.set(n,t+1),t===0?n:`${n}~${t+1}`}function wx(n,e){let t=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of Gl(n)){if(a.path===void 0)continue;let o=t.get(a.path)??[];o.push({id:a.id,path:a.path,fragment:a.fragment,spineIndex:r.get(a.path)}),t.set(a.path,o)}return t}function Gl(n){let e=[];for(let t of n)e.push(t),e.push(...Gl(t.children));return e}var Oo,No,Kt,Do,jl=i(()=>{"use strict";Ut();Ut();Il();Wl();Po();Oo=class n{#e;#n;constructor(e,t){this.#e=e,this.#n=t}get id(){return this.#n.id}get hasContent(){return this.#n.hasContent}get title(){return this.#n.title}get wordsCount(){return this.#n.wordsCount}get children(){return this.#n.children.map(e=>new n(this.#e,e))}async open(){return await this.#e.openSection(this.#n.id)}async openWithProvenance(){return await this.#e.openSectionWithProvenance(this.#n.id)}},No=class n{#e;#n;#t;#r;#i;constructor(e,t,r,a,o){this.#e=e,this.#n=t,this.#t=r,this.#r=a,this.#i=o}static async open(e){yx(e);let t=await vl(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...t.metadata.identifier===null?{}:{identifier:t.metadata.identifier}},a=await Tl(e,t),o=bx(e,a),s=wx(o,t),d=await bl(e,s),c=Ml(o,d),u=await gx(e,t);return new n(r,t,u,c,new Ti(e,s))}readMeta(){return Promise.resolve(this.#n.metadata)}readCover(){return Promise.resolve(this.#t)}readSections(){return Promise.resolve(this.#r.map(e=>new Oo(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},Kt=class{get format(){return"epub"}async openSession(e,t){let r=await Ci.open(e);try{let a=await No.open(r);return await t(a)}finally{await r.close()}}},Do=new Kt});var Bl=i(()=>{"use strict";jl()});async function*xx(n){let e=await n.openReader(),t=new TextDecoder,r="";try{for(let a=0;a<e.size;){let o=await e.read(a,Math.min(65536,e.size-a));a+=o.byteLength,r+=t.decode(o,{stream:a<e.size});let s=r.split(/(?<=\n)/u);r=s.pop()??"";for(let d of s)d!==""&&(yield d)}r+=t.decode(),r!==""&&(yield r)}finally{await e.close()}}function Ix(n){let e=n.lastIndexOf("."),t=(e<=0?n:n.slice(0,e)).trim();return t===""?null:t}var kx,Wo,Fo,zt,Ul,ql,Hl=i(()=>{"use strict";jt();kx="root",Wo=class{#e;#n;constructor(e,t=kx){this.#e=e,this.#n=t}get id(){return this.#n}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(xx(this.#e))}},Fo=class{#e;#n;#t;constructor(e,t){this.#n=e,this.#t=t,this.#e=new Wo(e)}readMeta(){return Promise.resolve({version:Ve,sourceFormat:this.#t,title:Ix(this.#n.name),authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null})}readCover(){return Promise.resolve(void 0)}readSections(){return Promise.resolve([this.#e])}},zt=class{#e;constructor(e){this.#e=e}get format(){return this.#e}async openSession(e,t){return await(await e.openReader()).close(),await t(new Fo(e,this.#e))}},Ul=new zt("txt"),ql=new zt("markdown")});var Qt=i(()=>{"use strict"});import{z as ue}from"zod";var WO,FO,$l=i(()=>{"use strict";Qt();WO=ue.object({type:ue.literal("artifact"),digest:ue.string().regex(/^[0-9a-f]{64}$/iu),mediaType:ue.string().min(1),name:ue.string().optional(),identifier:ue.string().max(1024).optional()}),FO=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var xn=i(()=>{"use strict";jt();Bl();Hl();$l();Ro()});var Go=i(()=>{"use strict"});var Xt=i(()=>{"use strict";xn();ye();Go();Z()});var Ex,Kl,zl,Ql,Vt=i(()=>{"use strict";w();Qt();Ex=`
28
28
  id INTEGER PRIMARY KEY AUTOINCREMENT,
29
29
  digest BLOB NOT NULL UNIQUE,
30
30
  short_uid TEXT NOT NULL UNIQUE
@@ -34,7 +34,7 @@ var _y=Object.defineProperty;var i=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ty=(e,t)=>{f
34
34
  media_type TEXT NOT NULL,
35
35
  name TEXT,
36
36
  identifier TEXT
37
- `,Bd=`
37
+ `,Kl=`
38
38
  CREATE TABLE IF NOT EXISTS serials (
39
39
  id INTEGER PRIMARY KEY,
40
40
  document_order INTEGER NOT NULL DEFAULT 0
@@ -321,6 +321,8 @@ var _y=Object.defineProperty;var i=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ty=(e,t)=>{f
321
321
  words_count INTEGER NOT NULL DEFAULT 0,
322
322
  byte_offset INTEGER NOT NULL DEFAULT 0,
323
323
  byte_length INTEGER NOT NULL DEFAULT 0,
324
+ character_offset INTEGER NOT NULL DEFAULT 0,
325
+ character_length INTEGER NOT NULL DEFAULT 0,
324
326
  UNIQUE(kind, chapter_id, sentence_index)
325
327
  );
326
328
 
@@ -328,7 +330,7 @@ var _y=Object.defineProperty;var i=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ty=(e,t)=>{f
328
330
  ON text_sentence_records(kind, chapter_id, sentence_index);
329
331
 
330
332
  CREATE TABLE IF NOT EXISTS source_artifacts (
331
- ${vb}
333
+ ${Ex}
332
334
  );
333
335
 
334
336
  CREATE TABLE IF NOT EXISTS source_locators (
@@ -394,7 +396,7 @@ ${vb}
394
396
  triple_predicate,
395
397
  triple_object_qid
396
398
  );
397
- `,Ud=`
399
+ `,zl=`
398
400
  id INTEGER PRIMARY KEY,
399
401
  archive_id INTEGER NOT NULL,
400
402
  kind INTEGER NOT NULL,
@@ -404,14 +406,14 @@ ${vb}
404
406
  byte_offset INTEGER NOT NULL DEFAULT 0,
405
407
  byte_length INTEGER NOT NULL DEFAULT 0,
406
408
  UNIQUE(archive_id, kind, chapter_id, sentence_index)
407
- `,Hd=`
409
+ `,Ql=`
408
410
  CREATE TABLE IF NOT EXISTS search_index_state (
409
411
  key TEXT PRIMARY KEY,
410
412
  value TEXT NOT NULL
411
413
  );
412
414
 
413
415
  CREATE TABLE IF NOT EXISTS text_sentence_records (
414
- ${Ud}
416
+ ${zl}
415
417
  );
416
418
 
417
419
  CREATE INDEX IF NOT EXISTS idx_text_sentence_records_chapter
@@ -468,22 +470,22 @@ ${Ud}
468
470
  updated_at INTEGER NOT NULL,
469
471
  PRIMARY KEY (archive_id, chapter_id)
470
472
  );
471
- `});var ot=i(()=>{"use strict";y();be()});var qd=i(()=>{"use strict";y();ot()});var $d=i(()=>{"use strict";y()});var Kd=i(()=>{"use strict";y();mr()});var Jd=i(()=>{"use strict";y();be()});var zd=i(()=>{"use strict";y();ot()});var Xd=i(()=>{"use strict";y();ot()});var Qd=i(()=>{"use strict";y();ot()});var Vd=i(()=>{"use strict";y();ot()});var Yd=i(()=>{"use strict";y();ot()});var tu=i(()=>{"use strict";fe();y();pn()});var nu=i(()=>{"use strict";y()});var ru=i(()=>{"use strict";y()});var iu=i(()=>{"use strict";y()});var au=i(()=>{"use strict";nu();ru();iu()});var ka=i(()=>{"use strict";qd();$d();Kd();Jd();zd();Xd();Qd();Vd();Yd();tu();au()});var Ra=i(()=>{"use strict"});var Su=i(()=>{"use strict";p()});var wu=i(()=>{"use strict";ee();tn()});var st=i(()=>{"use strict"});var Eu=i(()=>{"use strict";y();fn();st()});var xu=i(()=>{"use strict";ee();Ra()});var Iu=i(()=>{"use strict"});import{z as va}from"zod";var UA,vu=i(()=>{"use strict";p();rn();oa();hn();y();ea();fn();ka();be();Ra();Su();wu();Eu();tn();xu();Iu();UA=va.object({mediaType:va.string().min(1),path:va.string()})});var _u=i(()=>{"use strict"});var _a=i(()=>{"use strict";vu();_u()});var Cu=i(()=>{"use strict";ia()});var k=i(()=>{"use strict";y();qc();ea();ia();_a();Cu();fn();pn();ka();be()});var Ca=i(()=>{"use strict"});var _e=i(()=>{"use strict";Ca()});async function Ou(e){let t=await Nb(e);try{return await Ob(t,e),await t.queryOne(`
473
+ `});var In=i(()=>{"use strict";w();ve()});var Xl=i(()=>{"use strict";w();In()});var Vl=i(()=>{"use strict";w()});var Yl=i(()=>{"use strict";w();mi()});var Zl=i(()=>{"use strict";w();ve()});var em=i(()=>{"use strict";w();In()});var nm=i(()=>{"use strict";w();In()});var tm=i(()=>{"use strict";w();In()});var rm=i(()=>{"use strict";w();In()});var im=i(()=>{"use strict";w();In()});var sm=i(()=>{"use strict";Ee();w();Qt()});var dm=i(()=>{"use strict";w()});var cm=i(()=>{"use strict";w()});var um=i(()=>{"use strict";w()});var lm=i(()=>{"use strict";dm();cm();um()});var qo=i(()=>{"use strict";Xl();Vl();Yl();Zl();em();nm();tm();rm();im();sm();lm()});var Ho=i(()=>{"use strict"});var Rm=i(()=>{"use strict";y()});var vm=i(()=>{"use strict";pe();Mt()});var En=i(()=>{"use strict"});var Cm=i(()=>{"use strict";y();w();Vt();En()});var Tm=i(()=>{"use strict";pe();Ho()});var _m=i(()=>{"use strict"});import{z as $o}from"zod";var hW,Am=i(()=>{"use strict";y();jt();Ro();Xt();w();So();Vt();qo();ve();Ho();Rm();vm();Cm();Mt();Tm();_m();hW=$o.object({mediaType:$o.string().min(1),path:$o.string()})});var Lm=i(()=>{"use strict"});var Ko=i(()=>{"use strict";Am();Lm()});var Nm=i(()=>{"use strict";Io()});var _=i(()=>{"use strict";w();Vu();So();Io();Ko();Nm();Vt();Qt();qo();ve()});var Qo=i(()=>{"use strict"});var Ge=i(()=>{"use strict";Qo()});async function Mm(n){let e=await Lx(n);try{return await Ax(e,n),await e.queryOne(`
472
474
  SELECT 1 AS active
473
475
  FROM state_locks
474
476
  WHERE scope = ? AND resource_key = ?
475
477
  LIMIT 1
476
- `,[e.scope,e.resourceKey],()=>!0)===!0}finally{await t.close()}}async function Ob(e,t){let n=[],r=[];t.scope!==void 0&&(n.push("scope = ?"),r.push(t.scope)),t.resourceKey!==void 0&&(n.push("resource_key = ?"),r.push(t.resourceKey));let a=await e.queryAll(`
478
+ `,[n.scope,n.resourceKey],()=>!0)===!0}finally{await e.close()}}async function Ax(n,e){let t=[],r=[];e.scope!==void 0&&(t.push("scope = ?"),r.push(e.scope)),e.resourceKey!==void 0&&(t.push("resource_key = ?"),r.push(e.resourceKey));let a=await n.queryAll(`
477
479
  SELECT scope, resource_key, mode, owner_id, owner_pid, heartbeat_at
478
480
  FROM state_locks
479
- ${n.length===0?"":`WHERE ${n.join(" AND ")}`}
480
- `,r,o=>({lock:Db(o),resourceKey:S(o,"resource_key"),scope:S(o,"scope")}));for(let{lock:o,resourceKey:s,scope:c}of a)Mb(o,t.staleMs)&&await e.run(`
481
+ ${t.length===0?"":`WHERE ${t.join(" AND ")}`}
482
+ `,r,o=>({lock:Ox(o),resourceKey:E(o,"resource_key"),scope:E(o,"scope")}));for(let{lock:o,resourceKey:s,scope:d}of a)Dx(o,e.staleMs)&&await n.run(`
481
483
  DELETE FROM state_locks
482
484
  WHERE scope = ?
483
485
  AND resource_key = ?
484
486
  AND owner_id = ?
485
487
  AND heartbeat_at = ?
486
- `,[c,s,o.ownerId,o.heartbeatAt])}async function Nb(e){if(e.databaseFile!==void 0)return await N.open(e.databaseFile,Lu);if(e.stateDatabaseName!==void 0)return await B(e.stateDatabaseName,Lu);throw new Error("State lock requires a database File or state database name.")}function Db(e){return{heartbeatAt:h(e,"heartbeat_at"),mode:Fb(S(e,"mode")),ownerId:S(e,"owner_id")}}function Fb(e){return e==="read"||e==="write"?e:"write"}function Mb(e,t=Lb){return Date.now()-e.heartbeatAt>t}var Lu,Lb,Nu=i(()=>{"use strict";O();y();k();Lu=`
488
+ `,[d,s,o.ownerId,o.heartbeatAt])}async function Lx(n){if(n.databaseFile!==void 0)return await N.open(n.databaseFile,Fm,{create:!0,mode:"readwrite"});if(n.stateDatabaseName!==void 0)return await X(n.stateDatabaseName,Fm);throw new Error("State lock requires a database File or state database name.")}function Ox(n){return{heartbeatAt:S(n,"heartbeat_at"),mode:Nx(E(n,"mode")),ownerId:E(n,"owner_id")}}function Nx(n){return n==="read"||n==="write"?n:"write"}function Dx(n,e=Px){return Date.now()-n.heartbeatAt>e}var Fm,Px,Gm=i(()=>{"use strict";U();w();_();Fm=`
487
489
  CREATE TABLE IF NOT EXISTS state_locks (
488
490
  scope TEXT NOT NULL,
489
491
  resource_key TEXT NOT NULL,
@@ -497,7 +499,7 @@ ${Ud}
497
499
 
498
500
  CREATE INDEX IF NOT EXISTS idx_state_locks_resource
499
501
  ON state_locks(scope, resource_key);
500
- `,Lb=300*1e3});async function Fu(e){return await Ou({stateDatabaseName:"core.sqlite",resourceKey:Gb(e),scope:jb,staleMs:Du})||await Bb(e)}function Gb(e){return String(e)}async function Bb(e){let t=await Ub();try{let n=await t.queryOne("SELECT owner_pid, heartbeat_at FROM library_locks WHERE library_id = ?",[e],r=>({heartbeatAt:h(r,"heartbeat_at"),ownerPid:h(r,"owner_pid")}));return n!==void 0&&qb(n)}finally{await t.close()}}async function Ub(){let e=await B("core.sqlite",Wb);return await Hb(e),e}async function Hb(e){new Set(await e.queryAll("PRAGMA table_info(library_locks)",void 0,n=>S(n,"name"))).has("heartbeat_at")||await e.run("ALTER TABLE library_locks ADD COLUMN heartbeat_at INTEGER NOT NULL DEFAULT 0")}function qb(e){return Date.now()-e.heartbeatAt<=Du}var Wb,jb,Du,yn=i(()=>{"use strict";y();k();Nu();Wb=`
502
+ `,Px=300*1e3});async function Bm(n){return await Mm({stateDatabaseName:"core.sqlite",resourceKey:Mx(n),scope:Fx,staleMs:jm})||await Gx(n)}function Mx(n){return String(n)}async function Gx(n){let e=await jx();try{let t=await e.queryOne("SELECT owner_pid, heartbeat_at FROM library_locks WHERE library_id = ?",[n],r=>({heartbeatAt:S(r,"heartbeat_at"),ownerPid:S(r,"owner_pid")}));return t!==void 0&&Ux(t)}finally{await e.close()}}async function jx(){let n=await X("core.sqlite",Wx);return await Bx(n),n}async function Bx(n){new Set(await n.queryAll("PRAGMA table_info(library_locks)",void 0,t=>E(t,"name"))).has("heartbeat_at")||await n.run("ALTER TABLE library_locks ADD COLUMN heartbeat_at INTEGER NOT NULL DEFAULT 0")}function Ux(n){return Date.now()-n.heartbeatAt<=jm}var Wx,Fx,jm,Yt=i(()=>{"use strict";w();_();Gm();Wx=`
501
503
  CREATE TABLE IF NOT EXISTS library_locks (
502
504
  library_id INTEGER PRIMARY KEY,
503
505
  mode TEXT NOT NULL,
@@ -506,8 +508,8 @@ ${Ud}
506
508
  heartbeat_at INTEGER NOT NULL,
507
509
  created_at INTEGER NOT NULL
508
510
  );
509
- `,jb="library",Du=300*1e3});var TP,vt=i(()=>{"use strict";p();y();k();_e();fe();O();yn();Ca();TP=Promise.resolve()});var Te=i(()=>{"use strict"});var Ge=i(()=>{"use strict";Te()});import{z as La}from"zod";var bn,vr,Oa,FP,Be=i(()=>{"use strict";Te();bn=1,vr=4,Oa=`${JSON.stringify({formatVersion:bn,schemaVersion:vr})}
510
- `,FP=La.object({formatVersion:La.literal(bn),schemaVersion:La.number().int().positive().optional()})});var Bu=i(()=>{"use strict";p();Ge();Te();Be()});var Tr=i(()=>{"use strict";p();Te();Be();Ge()});var Hu=i(()=>{"use strict";Te()});var $u=i(()=>{"use strict";p();Te();Hu();Be();Ge()});var zu=i(()=>{"use strict";Bu();Tr();Be();$u()});var al=i(()=>{"use strict";_e()});var ol=i(()=>{"use strict"});var Cr=i(()=>{"use strict"});var En=i(()=>{"use strict";qi();$t()});var Ga=i(()=>{"use strict";p();Cr();En()});var sl=i(()=>{"use strict";En()});var cl=i(()=>{"use strict";Cr();En()});var Ba=i(()=>{"use strict";En()});var dl=i(()=>{"use strict";Ga();sl();cl();Ba();Cr()});var ul=i(()=>{"use strict";Ga();dl();Ba()});var ll=i(()=>{"use strict";ol();ul()});var Ar=i(()=>{"use strict";ll();Ce()});var nO,xn=i(()=>{"use strict";nO=new RegExp("\\p{Script=Han}","u")});var Ua=i(()=>{"use strict";fe()});var Ha,ct=i(()=>{"use strict";Ha=`
511
+ `,Fx="library",jm=300*1e3});var eF,Yn=i(()=>{"use strict";y();w();_();Ge();Ee();U();Yt();Qo();eF=Promise.resolve()});var je=i(()=>{"use strict"});var tn=i(()=>{"use strict";je()});import{z as Zo}from"zod";var er,_i,es,dF,rn=i(()=>{"use strict";je();er=1,_i=5,es=`${JSON.stringify({formatVersion:er,schemaVersion:_i})}
512
+ `,dF=Zo.object({formatVersion:Zo.literal(er),schemaVersion:Zo.number().int().positive().optional()})});var Km=i(()=>{"use strict";y();tn();je();rn()});var Pi=i(()=>{"use strict";y();je();rn();tn()});var zm=i(()=>{"use strict";je()});var Xm=i(()=>{"use strict";y();je();zm();rn();tn()});var Zm=i(()=>{"use strict";Km();Pi();rn();Xm()});var op=i(()=>{"use strict";Ge()});var sp=i(()=>{"use strict";Z()});var Di=i(()=>{"use strict"});var rr=i(()=>{"use strict";uo();Tt()});var ss=i(()=>{"use strict";y();Di();rr()});var dp=i(()=>{"use strict";rr()});var cp=i(()=>{"use strict";Di();rr()});var ds=i(()=>{"use strict";rr()});var up=i(()=>{"use strict";ss();dp();cp();ds();Di();Z()});var lp=i(()=>{"use strict";ss();up();ds()});var mp=i(()=>{"use strict";sp();lp()});var Wi=i(()=>{"use strict";Z();y();mp();Be()});var OM,ir=i(()=>{"use strict";OM=new RegExp("\\p{Script=Han}","u")});var cs=i(()=>{"use strict";Ee()});var us,vn=i(()=>{"use strict";us=`
511
513
  CREATE TABLE IF NOT EXISTS search_sessions (
512
514
  session_id TEXT PRIMARY KEY,
513
515
  archive_key TEXT NOT NULL,
@@ -611,77 +613,30 @@ ON search_sessions(expires_at);
611
613
 
612
614
  CREATE INDEX IF NOT EXISTS idx_search_sessions_prune
613
615
  ON search_sessions(accessed_at DESC, created_at DESC, session_id);
614
- `});async function Tt(){let e=await B("cache/search-sessions.sqlite",Ha);return qa?e:await iS(e)?(qa=!0,e):(await rS(e),qa=!0,e)}async function rS(e){await e.execute(`
616
+ `});async function nt(){let n=await X("cache/search-sessions.sqlite",us);return ls?n:await nI(n)?(ls=!0,n):(await eI(n),ls=!0,n)}async function eI(n){await n.execute(`
615
617
  DROP TABLE IF EXISTS search_evidence_hit_events;
616
618
  DROP TABLE IF EXISTS search_triple_hits;
617
619
  DROP TABLE IF EXISTS search_entity_hits;
618
620
  DROP TABLE IF EXISTS search_chunk_hits;
619
621
  DROP TABLE IF EXISTS search_sessions;
620
- ${Ha}
621
- `)}async function iS(e){return await Pr(e,"search_entity_hits","archive_id")&&await Pr(e,"search_chunk_hits","archive_id")&&await Pr(e,"search_triple_hits","archive_id")&&await Pr(e,"search_evidence_hit_events","archive_id")}async function Pr(e,t,n){return(await e.queryAll(`PRAGMA table_info(${t})`,void 0,a=>String(a.name))).includes(n)}var qa,Ct=i(()=>{"use strict";k();ct();qa=!1});var Lr=i(()=>{"use strict"});async function hl(e,t){await fl(e,t),await e.run("DELETE FROM search_sessions WHERE session_id = ?",[t])}async function fl(e,t){await e.run("DELETE FROM search_results WHERE session_id = ?",[t]),await e.run("DELETE FROM search_evidence_hit_events WHERE session_id = ?",[t]),await e.run("DELETE FROM search_entity_hits WHERE session_id = ?",[t]),await e.run("DELETE FROM search_triple_hits WHERE session_id = ?",[t]),await e.run("DELETE FROM search_chunk_hits WHERE session_id = ?",[t])}async function yl(e){await e.run(`
622
+ ${us}
623
+ `)}async function nI(n){return await Fi(n,"search_entity_hits","archive_id")&&await Fi(n,"search_chunk_hits","archive_id")&&await Fi(n,"search_triple_hits","archive_id")&&await Fi(n,"search_evidence_hit_events","archive_id")}async function Fi(n,e,t){return(await n.queryAll(`PRAGMA table_info(${e})`,void 0,a=>String(a.name))).includes(t)}var ls,tt=i(()=>{"use strict";_();vn();ls=!1});var Mi=i(()=>{"use strict"});async function fp(n,e){await yp(n,e),await n.run("DELETE FROM search_sessions WHERE session_id = ?",[e])}async function yp(n,e){await n.run("DELETE FROM search_results WHERE session_id = ?",[e]),await n.run("DELETE FROM search_evidence_hit_events WHERE session_id = ?",[e]),await n.run("DELETE FROM search_entity_hits WHERE session_id = ?",[e]),await n.run("DELETE FROM search_triple_hits WHERE session_id = ?",[e]),await n.run("DELETE FROM search_chunk_hits WHERE session_id = ?",[e])}async function gp(n){await n.run(`
622
624
  DELETE FROM predicate_dictionary
623
625
  WHERE NOT EXISTS (
624
626
  SELECT 1
625
627
  FROM search_triple_hits
626
628
  WHERE search_triple_hits.predicate_id = predicate_dictionary.id
627
629
  )
628
- `)}var $a=i(()=>{"use strict";y();Ct();Lr();ct()});async function Or(e){let t=await Tt();try{let n=await gl(t),r=await t.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,d=>h(d,"count")),a=e.force?await cS(t):await sS(t,e.now),o=e.force?[]:await dS(t),s=[...new Set([...a,...o])].sort();!e.dryRun&&s.length>0&&(await t.transaction(async()=>{for(let d of s)await hl(t,d);await yl(t)}),await t.run("VACUUM"));let c=await gl(t);return{freedBytes:Math.max(0,n-c),removed:s.length,scanned:r??0}}finally{await t.close()}}async function sS(e,t){return await e.queryAll(`
630
+ `)}var ms=i(()=>{"use strict";w();tt();Mi();vn()});async function Gi(n){let e=await nt();try{let t=await bp(e),r=await e.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,c=>S(c,"count")),a=n.force?await aI(e):await iI(e,n.now),o=n.force?[]:await oI(e),s=[...new Set([...a,...o])].sort();!n.dryRun&&s.length>0&&(await e.transaction(async()=>{for(let c of s)await fp(e,c);await gp(e)}),await e.run("VACUUM"));let d=await bp(e);return{freedBytes:Math.max(0,t-d),removed:s.length,scanned:r??0}}finally{await e.close()}}async function iI(n,e){return await n.queryAll(`
629
631
  SELECT session_id
630
632
  FROM search_sessions
631
633
  WHERE expires_at < ?
632
- `,[t],n=>S(n,"session_id"))}async function cS(e){return await e.queryAll("SELECT session_id FROM search_sessions",void 0,t=>S(t,"session_id"))}async function dS(e){return await e.queryAll(`
634
+ `,[e],t=>E(t,"session_id"))}async function aI(n){return await n.queryAll("SELECT session_id FROM search_sessions",void 0,e=>E(e,"session_id"))}async function oI(n){return await n.queryAll(`
633
635
  SELECT session_id
634
636
  FROM search_sessions
635
637
  ORDER BY accessed_at DESC, created_at DESC, session_id
636
638
  LIMIT -1 OFFSET ?
637
- `,[500],t=>S(t,"session_id"))}async function gl(e){let t=await e.queryOne("PRAGMA page_count",void 0,r=>h(r,"page_count"))??0,n=await e.queryOne("PRAGMA page_size",void 0,r=>h(r,"page_size"))??0;return t*n}var bl=i(()=>{"use strict";y();Ct();ct();$a()});var Sl=i(()=>{"use strict";ct()});var Ka=i(()=>{"use strict"});var Nr=i(()=>{"use strict";y();Ct();Lr();Sl();Ka()});var El=i(()=>{"use strict";O();ct()});var xl=i(()=>{"use strict";y();Ua();Ct();Nr();El();Lr();ct();$a()});var Il=i(()=>{"use strict";y();Ct();Nr()});var dt=i(()=>{"use strict";Ua();bl();Nr();xl();Il();Ka()});var Fr=i(()=>{"use strict"});var Pl=i(()=>{"use strict"});var za=i(()=>{"use strict";fe()});var Mr=i(()=>{"use strict"});var Xa=i(()=>{"use strict";Mr()});var Qa=i(()=>{"use strict";Mr()});var Wr=i(()=>{"use strict";Fr();za();Xa();Qa()});var Ml=i(()=>{"use strict";_e()});var Wl=i(()=>{"use strict";Fr();Pl();za();Mr();Wr();Xa();Qa();Ml()});var C=i(()=>{"use strict";Wl()});var Ya=i(()=>{"use strict"});var Za=i(()=>{"use strict";hn();wa();Ya()});var jl=i(()=>{"use strict";Za()});var $=i(()=>{"use strict";Za();jl();Ya()});var SD,wD,Ue=i(()=>{"use strict";O();SD=new RegExp("\\p{Script=Han}+","gu"),wD=new RegExp("^\\p{Script=Han}+$","u")});var Gr=i(()=>{"use strict";O()});var to=i(()=>{"use strict";st()});var Ur=i(()=>{"use strict";y();to()});var Jl=i(()=>{"use strict";Ue();Gr();Ur();st()});var Xl=i(()=>{"use strict";st()});var Ql=i(()=>{"use strict";Ue()});var Vl=i(()=>{"use strict"});var oo=i(()=>{"use strict";y();Vl();Gr()});var Zl=i(()=>{"use strict";y();Ue();Ql();to();st();oo();Ur()});var em=i(()=>{"use strict";Jl();Xl();Gr();Zl();oo();st();Ur()});var qe=i(()=>{"use strict";em();Ue()});var lt=i(()=>{"use strict";$();qe();Ue()});var z=i(()=>{"use strict";se();_e();C()});var de=i(()=>{"use strict";_e();C()});var ue=i(()=>{"use strict";$();nt();C();z()});var le=i(()=>{"use strict";$();qe();C();z();de();ue();C();lt()});var Tn=i(()=>{"use strict";dt();qe();le();de()});var ho=i(()=>{"use strict";$();xn();C();z();ue();de()});var Cn=i(()=>{"use strict"});var xe=i(()=>{"use strict";$();Cn();C();z();ue()});var An=i(()=>{"use strict";ue()});var Pn=i(()=>{"use strict";ue();xe()});var fo=i(()=>{"use strict";C();xe();An();Pn()});var hm=i(()=>{"use strict";qe();lt();C();le();xe();An();fo();Pn();Pn();An()});var fm=i(()=>{"use strict";hm();fo();An();Pn()});var Nn=i(()=>{"use strict";fm()});var gm=i(()=>{"use strict";dt();C();z();ue();xe();de();Nn()});var Dn=i(()=>{"use strict";z();xe();C();de();Nn();gm()});var bo=i(()=>{"use strict";$();C();z();ue();xe();Dn();Fn();de()});var Fn=i(()=>{"use strict";C();z();ue();de();bo()});var Xr=i(()=>{"use strict";C();le();de()});var Qr=i(()=>{"use strict";C();le()});var Vr=i(()=>{"use strict";$();xn();dt();qe();C();Tn();ho();Dn();Fn();le();Xr();Qr()});var xm=i(()=>{"use strict";xn();dt();C();lt();Tn();ho();Dn();Fn();Vr();le()});var Im=i(()=>{"use strict";xm();Xr();Qr();Vr();Tn();le()});var Yr=i(()=>{"use strict";xe();Nn();z()});var Mn=i(()=>{"use strict";C()});var Zr=i(()=>{"use strict";C();lt();z();le();Tn();qe();Mn()});var wo=i(()=>{"use strict";C();de();Yr();Zr();Mn()});async function Eo(e){let t=await B("cache/cache.sqlite",rw);try{await ow(t);let n=await km(t),r=await dw(t),a=new Date(e.now-iw).toISOString(),o=await uw(t,a);!e.dryRun&&o>0&&(await t.transaction(async()=>{await t.run("DELETE FROM qid_cache WHERE checked_at < ?",[a]),await t.run("DELETE FROM disambiguation_cache WHERE checked_at < ?",[a])}),await t.run("VACUUM"));let s=await km(t);return{freedBytes:e.dryRun?aw(n,r,o):Math.max(0,n-s),removed:o,scanned:r}}finally{await t.close()}}function aw(e,t,n){return t===0||n===0?0:Math.round(e*(n/t))}async function ow(e){await sw(e),await cw(e)}async function sw(e){(await Wn(e,"qid_cache")).has("language")||await e.transaction(async()=>{(await Wn(e,"qid_cache")).has("language")||(await e.run("ALTER TABLE qid_cache RENAME TO qid_cache_legacy"),await e.run(Rm),await e.run(`
638
- INSERT OR IGNORE INTO qid_cache (
639
- qid, language, label, description, pages_json, checked_at, updated_at
640
- )
641
- SELECT qid, 'en', label, description, pages_json, checked_at, updated_at
642
- FROM qid_cache_legacy
643
- `),await e.run("DROP TABLE qid_cache_legacy"))})}async function cw(e){(await Wn(e,"disambiguation_cache")).has("wiki")||await e.transaction(async()=>{(await Wn(e,"disambiguation_cache")).has("wiki")||(await e.run("ALTER TABLE disambiguation_cache RENAME TO disambiguation_cache_legacy"),await e.run(vm),await e.run(`
644
- INSERT OR IGNORE INTO disambiguation_cache (
645
- qid, wiki, pages_json, profile_json, checked_at
646
- )
647
- SELECT qid, 'enwiki', pages_json, profile_json, checked_at
648
- FROM disambiguation_cache_legacy
649
- `),await e.run("DROP TABLE disambiguation_cache_legacy"))}),(await Wn(e,"disambiguation_cache")).has("profile_error_json")||await e.run("ALTER TABLE disambiguation_cache ADD COLUMN profile_error_json TEXT")}async function Wn(e,t){let n=await e.queryAll(`PRAGMA table_info(${t})`,void 0,r=>lw(r.name,"name"));return new Set(n)}async function dw(e){let t=await ei(e,"qid_cache"),n=await ei(e,"disambiguation_cache");return t+n}async function uw(e,t){let n=await ei(e,"qid_cache",t),r=await ei(e,"disambiguation_cache",t);return n+r}async function ei(e,t,n){return await e.queryOne(`
650
- SELECT COUNT(*) AS count
651
- FROM ${t}
652
- ${n===void 0?"":"WHERE checked_at < ?"}
653
- `,n===void 0?void 0:[n],r=>h(r,"count"))??0}async function km(e){let t=await e.queryOne("PRAGMA page_count",void 0,r=>h(r,"page_count"))??0,n=await e.queryOne("PRAGMA page_size",void 0,r=>h(r,"page_size"))??0;return t*n}function lw(e,t){if(typeof e!="string")throw new Error(`Expected ${t} to be a string.`);return e}var Rm,vm,rw,iw,xo=i(()=>{"use strict";y();k();p();Rm=`
654
- CREATE TABLE IF NOT EXISTS qid_cache (
655
- qid TEXT NOT NULL,
656
- language TEXT NOT NULL,
657
- label TEXT,
658
- description TEXT,
659
- pages_json TEXT NOT NULL,
660
- checked_at TEXT NOT NULL,
661
- updated_at TEXT NOT NULL,
662
- PRIMARY KEY (qid, language)
663
- );
664
- `,vm=`
665
- CREATE TABLE IF NOT EXISTS disambiguation_cache (
666
- qid TEXT NOT NULL,
667
- wiki TEXT NOT NULL,
668
- pages_json TEXT NOT NULL,
669
- profile_json TEXT,
670
- profile_error_json TEXT,
671
- checked_at TEXT NOT NULL,
672
- PRIMARY KEY (qid, wiki)
673
- );
674
- `,rw=`
675
- ${Rm}
676
-
677
- CREATE INDEX IF NOT EXISTS idx_qid_cache_checked_at
678
- ON qid_cache(checked_at);
679
-
680
- ${vm}
681
-
682
- CREATE INDEX IF NOT EXISTS idx_disambiguation_cache_checked_at
683
- ON disambiguation_cache(checked_at);
684
- `,iw=720*60*60*1e3});var Io=i(()=>{"use strict"});var ko=i(()=>{"use strict"});import{jsonrepair as _G}from"jsonrepair";var _m=i(()=>{"use strict"});var Tm=i(()=>{"use strict";ko();Io();_m()});var re=i(()=>{"use strict";Io();ko();Tm()});import{z as ie}from"zod";var fw,QG,Cm=i(()=>{"use strict";re();fw=ie.object({category:ie.string().min(1).optional(),information:ie.string(),name:ie.string().min(1),priority:ie.enum(["primary","secondary","other"]),qid:ie.union([ie.string(),ie.null()])}).strict(),QG=ie.object({meanings:ie.array(fw),sourceQid:ie.string().regex(/^Q[1-9]\d*$/u),surface:ie.string().min(1).optional()}).strict()});var _o=i(()=>{"use strict"});var Am=i(()=>{"use strict";p();O();ye();ee()});var ti=i(()=>{"use strict"});import{DomUtils as s0,parseDocument as c0}from"htmlparser2";var To=i(()=>{"use strict";ti()});var Pm=i(()=>{"use strict"});var Co=i(()=>{"use strict";ti()});var Nm=i(()=>{"use strict";ye();ee();_o();To();ti();Pm();Co()});var Ao=i(()=>{"use strict";Nm();To();Co()});var $0,Mm=i(()=>{"use strict";xo();Am();re();Ao();$0=360*60*1e3});var jn=i(()=>{"use strict";xo();Cm();_o();Mm();Ao()});var Lo=i(()=>{"use strict";jn()});var jm=i(()=>{"use strict";Cn();C();xe();Yr();wo();Zr();Mn();Lo();z()});var ni=i(()=>{"use strict";jm();wo();Yr();Zr();Mn();Lo()});var Oo=i(()=>{"use strict";k();_e();$();Cn();C();xe();Nn();Fn();de();ni();z();ue()});var Gm=i(()=>{"use strict";k();$();se();_e();fe();C();ue()});var Bm=i(()=>{"use strict";Oo();ni();z()});var Jo=i(()=>{"use strict";Im();Oo();ni();lt();z();bo();Dn();Gm();Bm()});var qm=i(()=>{"use strict";Jo()});var kw,$m=i(()=>{"use strict";fe();O();y();k();kw=10080*60*1e3});var Km=i(()=>{"use strict"});var Jm=i(()=>{"use strict";y();$m();Km()});var zm=i(()=>{"use strict"});var Xm=i(()=>{"use strict";Jm();zm()});var Pt=i(()=>{"use strict";qm();Xm();dt()});var ht=i(()=>{"use strict"});var HU,Un=i(()=>{"use strict";p();y();Qt();ht();HU=new Ze(1)});var Xo=i(()=>{"use strict";y();O();ht();Un()});var oi=i(()=>{"use strict";p();O()});var Qo=i(()=>{"use strict";O();Un();oi()});var np=i(()=>{"use strict";p();Be();Te();Ge();Tr();ht();Xo();Qo();Un()});var rp=i(()=>{"use strict";ht();Ge()});var ip=i(()=>{"use strict";p();O();Un()});var Zo=i(()=>{"use strict";p();O();Tr();Be();Ge();ht();np();rp();Xo();ip();Qo();oi()});var ap=i(()=>{"use strict";Zo()});async function si(e){let t=I().documentStore,n=0,r=0,a=0,o;try{o=await t.list()}catch(c){if(Ve(c)&&c.code==="ENOENT")return{freedBytes:a,removed:r,scanned:n};throw c}for(let c of o){if(!G(c)||!c.name.startsWith(".wikg-session-"))continue;n+=1;let d=await Le(c);!e.force&&(d===void 0||e.now-d<Aw)||(a+=await pe(c),e.dryRun||await t.remove(c.name,{recursive:!0}),r+=1)}let s=await t.getDirectory(".wikg-cache");if(s!==void 0)for(let c of await s.list())G(c)&&(n+=1,e.force&&(a+=await pe(c),e.dryRun||await s.remove(c.name,{recursive:!0}),r+=1));return{freedBytes:a,removed:r,scanned:n}}var Aw,op=i(()=>{"use strict";p();ee();Aw=3600*1e3});var sp=i(()=>{"use strict";y();p();O();ht();oi()});var es=i(()=>{"use strict";ap();Zo();op();sp()});var ts=i(()=>{"use strict";es()});var dp=i(()=>{"use strict";k();Ar();Pt();ts()});var Ce=i(()=>{"use strict";zu();al();dp();ts()});var qn=i(()=>{"use strict";qe()});async function lp(e){let n=await(await I().library.getDirectory("staging"))?.getDirectory("library");if(n===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await Nw();if(r===void 0)return{freedBytes:0,removed:0,scanned:0};let a=new Set(r.map(u=>String(u))),o=await n.list(),s=0,c=0,d=0;for(let u of o){if(!G(u)||(s+=1,a.has(u.name)))continue;let f=Number(u.name);if(Number.isInteger(f)&&await Fu(f))continue;let x=await pe(u);e.dryRun||await n.remove(u.name,{recursive:!0}),c+=1,d+=x}return{freedBytes:d,removed:c,scanned:s}}async function Nw(){let e=await B("core.sqlite","");try{return await e.queryAll("SELECT id FROM libraries",void 0,t=>h(t,"id"))}catch{return}finally{await e.close()}}var Kn=i(()=>{"use strict";O();p();y();fn();k();Ce();lt();qn();Ue();Jn();vt();yn()});var Fw,S$,Jn=i(()=>{"use strict";p();y();k();_e();Ce();fe();O();vt();Kn();yn();Fw=`
639
+ `,[500],e=>E(e,"session_id"))}async function bp(n){let e=await n.queryOne("PRAGMA page_count",void 0,r=>S(r,"page_count"))??0,t=await n.queryOne("PRAGMA page_size",void 0,r=>S(r,"page_size"))??0;return e*t}var Sp=i(()=>{"use strict";w();tt();vn();ms()});var wp=i(()=>{"use strict";vn()});var ps=i(()=>{"use strict"});var ji=i(()=>{"use strict";w();tt();Mi();wp();ps()});var xp=i(()=>{"use strict";U();vn()});var Ip=i(()=>{"use strict";w();cs();tt();ji();xp();Mi();vn();ms()});var Ep=i(()=>{"use strict";w();tt();ji()});var Cn=i(()=>{"use strict";cs();Sp();ji();Ip();Ep();ps()});var Bi=i(()=>{"use strict"});var Lp=i(()=>{"use strict"});var fs=i(()=>{"use strict";Ee()});var Ui=i(()=>{"use strict"});var ys=i(()=>{"use strict";Ui()});var gs=i(()=>{"use strict";Ui()});var qi=i(()=>{"use strict";Bi();fs();ys();gs()});var Mp=i(()=>{"use strict";Ge()});var Gp=i(()=>{"use strict";Bi();Lp();fs();Ui();qi();ys();gs();Mp()});var D=i(()=>{"use strict";Gp()});var Ss=i(()=>{"use strict"});var ws=i(()=>{"use strict";Z();Xt();Go();Ss()});var jp=i(()=>{"use strict";ws()});var Y=i(()=>{"use strict";ws();jp();Ss()});var Vj,Yj,Tn=i(()=>{"use strict";U();Vj=new RegExp("\\p{Script=Han}+","gu"),Yj=new RegExp("^\\p{Script=Han}+$","u")});var Hi=i(()=>{"use strict";U()});var Is=i(()=>{"use strict";En()});var Ji=i(()=>{"use strict";w();Is()});var qp=i(()=>{"use strict";Tn();Hi();Ji();En()});var $p=i(()=>{"use strict";En()});var Jp=i(()=>{"use strict";Tn()});var Kp=i(()=>{"use strict"});var Ts=i(()=>{"use strict";w();Kp();Hi()});var Qp=i(()=>{"use strict";w();Tn();Jp();Is();En();Ts();Ji()});var Xp=i(()=>{"use strict";qp();$p();Hi();Qp();Ts();En();Ji()});var on=i(()=>{"use strict";Xp();Tn()});var Pn=i(()=>{"use strict";Y();on();Tn()});var te=i(()=>{"use strict";ye();Ge();D()});var Se=i(()=>{"use strict";Ge();D()});var Te=i(()=>{"use strict";Y();wn();D();te()});var we=i(()=>{"use strict";Y();on();D();te();Se();Te();D();Pn()});var lr=i(()=>{"use strict";Cn();on();we();Se()});var Ds=i(()=>{"use strict";Y();ir();D();te();Te();Se()});var mr=i(()=>{"use strict";Z()});var Pe=i(()=>{"use strict";Y();mr();D();te();Te()});var pr=i(()=>{"use strict"});var hr=i(()=>{"use strict";Te();Pe()});var Ws=i(()=>{"use strict";D();Pe();pr();hr()});var ch=i(()=>{"use strict";on();Pn();D();we();Pe();pr();Ws();hr();hr();pr()});var uh=i(()=>{"use strict";ch();Ws();pr();hr()});var yr=i(()=>{"use strict";uh()});var mh=i(()=>{"use strict";Cn();D();te();Te();Pe();Se();yr()});var gr=i(()=>{"use strict";te();Pe();D();Se();yr();mh()});var Gs=i(()=>{"use strict";Y();D();te();Te();Pe();gr();br();Se()});var br=i(()=>{"use strict";D();te();Te();Se();Gs()});var Zi=i(()=>{"use strict";D();we();Se()});var ea=i(()=>{"use strict";D();we()});var na=i(()=>{"use strict";Y();ir();Cn();on();D();lr();Ds();gr();br();we();Zi();ea()});var bh=i(()=>{"use strict";ir();Cn();D();Pn();lr();Ds();gr();br();na();we()});var Sh=i(()=>{"use strict";bh();Zi();ea();na();lr();we()});var ta=i(()=>{"use strict";Pe();yr();te()});var Sr=i(()=>{"use strict";D()});var ra=i(()=>{"use strict";D();Pn();te();we();lr();on();Sr()});var Bs=i(()=>{"use strict";D();Se();ta();ra();Sr()});var Us=i(()=>{"use strict"});var kh=i(()=>{"use strict";mr();D();Pe();ta();Bs();ra();Sr();Us();te()});var ia=i(()=>{"use strict";kh();Bs();ta();ra();Sr();Us()});var qs=i(()=>{"use strict";_();Ge();Y();mr();D();Pe();yr();br();Se();ia();te();Te()});var xh=i(()=>{"use strict";_();Y();ye();Ge();Ee();D();Te()});var Ih=i(()=>{"use strict";qs();ia();te()});var Ys=i(()=>{"use strict";Sh();qs();ia();Pn();te();Gs();gr();xh();Ih()});var vh=i(()=>{"use strict";Ys()});var dE,Ch=i(()=>{"use strict";Ee();U();w();_();dE=10080*60*1e3});var Th=i(()=>{"use strict"});var _h=i(()=>{"use strict";w();Ch();Th()});var Ph=i(()=>{"use strict"});var Ah=i(()=>{"use strict";_h();Ph()});var dt=i(()=>{"use strict";vh();Ah();Cn()});var On=i(()=>{"use strict"});var B1,Rr=i(()=>{"use strict";y();w();Nt();On();B1=new yn(1)});var td=i(()=>{"use strict";w();U();On();Rr()});var sa=i(()=>{"use strict";y();U()});var rd=i(()=>{"use strict";U();Rr();sa()});var Wh=i(()=>{"use strict";y();rn();je();tn();Pi();On();td();rd();Rr()});var Fh=i(()=>{"use strict";On();tn()});var Mh=i(()=>{"use strict";y();U();Rr()});var od=i(()=>{"use strict";y();U();Pi();rn();tn();On();Wh();Fh();td();Mh();rd();sa()});var Gh=i(()=>{"use strict";od()});async function da(n){let e=v().documentStore,t=0,r=0,a=0,o;try{o=await e.list()}catch(d){if(We(d)&&d.code==="ENOENT")return{freedBytes:a,removed:r,scanned:t};throw d}for(let d of o){if(!j(d)||!d.name.startsWith(".wikg-session-"))continue;t+=1;let c=await ze(d);!n.force&&(c===void 0||n.now-c<hE)||(a+=await Ie(d),n.dryRun||await e.remove(d.name,{recursive:!0}),r+=1)}let s=await e.getDirectory(".wikg-cache");if(s!==void 0)for(let d of await s.list())j(d)&&(t+=1,n.force&&(a+=await Ie(d),n.dryRun||await s.remove(d.name,{recursive:!0}),r+=1));return{freedBytes:a,removed:r,scanned:t}}var hE,jh=i(()=>{"use strict";y();pe();hE=3600*1e3});var Bh=i(()=>{"use strict";w();y();U();On();sa()});var sd=i(()=>{"use strict";Gh();od();jh();Bh()});var dd=i(()=>{"use strict";sd()});var qh=i(()=>{"use strict";_();Wi();dt();dd()});var Be=i(()=>{"use strict";Zm();op();qh();dd()});var vr=i(()=>{"use strict";on()});async function Hh(n){let t=await(await v().library.getDirectory("staging"))?.getDirectory("library");if(t===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await bE();if(r===void 0)return{freedBytes:0,removed:0,scanned:0};let a=new Set(r.map(u=>String(u))),o=await t.list(),s=0,d=0,c=0;for(let u of o){if(!j(u)||(s+=1,a.has(u.name)))continue;let m=Number(u.name);if(Number.isInteger(m)&&await Bm(m))continue;let b=await Ie(u);n.dryRun||await t.remove(u.name,{recursive:!0}),d+=1,c+=b}return{freedBytes:c,removed:d,scanned:s}}async function bE(){let n=await X("core.sqlite","");try{return await n.queryAll("SELECT id FROM libraries",void 0,e=>S(e,"id"))}catch{return}finally{await n.close()}}var Cr=i(()=>{"use strict";U();y();w();Vt();_();Be();Pn();vr();Tn();Tr();Yn();Yt();Z()});var wE,bz,Tr=i(()=>{"use strict";y();w();_();Ge();Be();Ee();U();Yn();Cr();Yt();wE=`
685
640
  id INTEGER PRIMARY KEY AUTOINCREMENT,
686
641
  library_id INTEGER NOT NULL,
687
642
  public_id TEXT NOT NULL,
@@ -694,9 +649,9 @@ ON disambiguation_cache(checked_at);
694
649
  created_at TEXT NOT NULL,
695
650
  updated_at TEXT NOT NULL,
696
651
  UNIQUE(library_id, public_id)
697
- `,S$=`
652
+ `,bz=`
698
653
  CREATE TABLE IF NOT EXISTS library_archives (
699
- ${Fw}
654
+ ${wE}
700
655
  );
701
656
 
702
657
  CREATE INDEX IF NOT EXISTS idx_library_archives_library
@@ -704,14 +659,26 @@ ${Fw}
704
659
 
705
660
  CREATE INDEX IF NOT EXISTS idx_library_archives_library_path
706
661
  ON library_archives(library_id, relative_path);
707
- `});var is=i(()=>{"use strict";Ce();Jn();vt()});var fp=i(()=>{"use strict";Fr();Wr();xn();Qr();Xr();le();Vr();dt();qn();Kn();is()});var yp=i(()=>{"use strict";Jo();Wr();fp();le();Jn();is();vt();Kn()});var ci=i(()=>{"use strict";vt();Jn();yp();Kn();yn()});function di(e){let t=e.trim();return t===""?[]:Array.from(zw.segment(t)).map(n=>n.segment.trim()).filter(n=>n!=="")}function me(e){let t=e.replace(/\s+/gu," ").trim(),n=Xw(t),r="";for(let a of n)if(!Qw(a)){if(!zn(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function Xw(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===void 0)break;if(r!==" "){t.push(r),n+=1;continue}if(t.length>=2&&Jw.has(t[t.length-1]??"")&&zn(t[t.length-2]??"")&&n<e.length-1&&zn(e[n+1]??"")){t.pop(),n+=1;continue}let a=t[t.length-1]??"",o=e[n+1]??"";a!==""&&o!==""&&zn(a)&&zn(o)&&t.push(r),n+=1}return t}function zn(e){return e!==""&&new RegExp("\\p{Script=Latin}","u").test(e)&&new RegExp("\\p{L}","u").test(e)}function Qw(e){return/[\p{P}\p{S}]/u.test(e)}var Jw,zw,Xn=i(()=>{"use strict";Jw=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),zw=new Intl.Segmenter(void 0,{granularity:"sentence"})});function os(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function bp(e,t){let n=ui(e,2),r=ui(t,2),a=ui(e,3),o=ui(t,3);return(gp(n,r)+gp(a,o))/2}function ui(e,t){if(e.length<=t)return e===""?new Set:new Set([e]);let n=new Set;for(let r=0;r<=e.length-t;r+=1)n.add(e.slice(r,r+t));return n}function gp(e,t){if(e.size===0||t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return 2*n/(e.size+t.size)}function Sp(e,t){if(e===t)return 1;if(e===""||t==="")return 0;let n=Array.from({length:t.length+1},(o,s)=>s),r=new Array(t.length+1).fill(0);for(let[o,s]of[...e].entries()){r[0]=o+1;for(let[c,d]of[...t].entries()){let u=(r[c]??0)+1,f=(n[c+1]??0)+1,x=(n[c]??0)+(s===d?0:1);r[c+1]=Math.min(u,f,x)}[n,r]=[r,n]}return 1-(n[t.length]??Math.max(e.length,t.length))/Math.max(e.length,t.length)}function wp(e,t){return 1-Math.abs(e.length-t.length)/Math.max(e.length,t.length)}function Ep(e,t){if(e===t)return 1;let n=e.length,r=t.length;if(n===0||r===0)return 0;let a=Array.from({length:n+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=n;s+=1)for(let c=1;c<=r;c+=1){if(e[s-1]!==t[c-1])continue;let d=a[s];d!==void 0&&(d[c]=(a[s-1]?.[c-1]??0)+1,o=Math.max(o,d[c]??0))}return 2*o/(n+r)}function xp(e){return` - ${e.occurrenceId} score=${e.score.toFixed(3)}
708
- prev: ${as(e.prevText)}
709
- text: ${as(e.text,120)}
710
- next: ${as(e.nextText)}`}function as(e,t=80){let n=e.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=t?n:`${n.slice(0,t-3)}...`}var ss=i(()=>{"use strict"});var cs=i(()=>{"use strict"});function kp(e,t,n){return e.mode==="head_tail"?Zw(e,t):ds(e.text??"",t,n)}function Zw(e,t){let n=e.head??"",r=e.tail??"",a=me(t),o=me(n),s=me(r);if(o===""||s==="")return os();let c=a.indexOf(o),d=a.lastIndexOf(s);if(c!==-1&&d!==-1&&c<=d){let D=o.length+s.length,w=Math.min(1,D/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:d+s.length,matchStart:c,score:.82+.18*w}}let u=ds(n,t,"start_anchor"),f=ds(r,t,"end_anchor"),x=u.matchStart<=f.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,f.matchEnd),matchStart:Math.min(u.matchStart,f.matchStart),score:(u.score+f.score)/2*x}}function ds(e,t,n){let r=e.trim(),a=t.trim(),o=me(r),s=me(a);if(o===""||s==="")return os();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let w=s.indexOf(o),R=o.length/Math.max(1,s.length),g=Ip({candidateNormalized:s,label:n,matchEnd:w+o.length,matchStart:w,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:w+o.length,matchStart:w,score:Math.min(1,.75+.25*R+g)}}if(o.includes(s)){let w=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*w)}}let c=0,d=-1,u=-1,f=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),x=Math.min(f,Math.max(1,Math.floor(o.length*.8))),D=new Set(o);for(let w=x;w<=f;w+=1)for(let R=0;R<=s.length-w;R+=1){let g=s.slice(R,R+w),v=new Set(g),P=new Set([...D,...v]).size,H=[...D].filter(Z=>v.has(Z)).length;if((P===0?0:H/P)<.35)continue;let W=.35*bp(o,g)+.35*Ep(o,g)+.2*Sp(o,g)+.1*wp(o,g)+Ip({candidateNormalized:s,label:n,matchEnd:R+w,matchStart:R,queryNormalized:o});W>c&&(c=Math.min(1,W),d=R,u=R+w)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:d,score:c}}function Ip(e){if(e.matchStart<0||e.matchEnd<0||e.queryNormalized.length<12||e.label==="start_anchor"&&e.matchStart!==0||e.label==="end_anchor"&&e.matchEnd!==e.candidateNormalized.length)return 0;let t=e.queryNormalized.length/Math.max(1,e.candidateNormalized.length);return .08*(.5+.5*Math.min(1,t))}var Rp=i(()=>{"use strict";Xn();ss();cs()});function vp(e){if(e==null)return[void 0,"anchor is required"];if(typeof e=="string"){let o=e.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(c=>c.trim()).filter(c=>c!=="");if(s.length>=2){let c=s[0],d=s[s.length-1];return c===void 0||d===void 0?[void 0,"anchor string is empty"]:[{head:c,mode:"head_tail",tail:d},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof e!="object")return[void 0,`expected string or object, got ${typeof e}`];let t=e;if((t.mode==="head_tail"||t.head!==void 0?"head_tail":"full")==="full"){let o=typeof t.text=="string"?t.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof t.head=="string"?t.head.trim():"",a=typeof t.tail=="string"?t.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function _p(e,t){if(e===void 0)return;if(e.mode==="head_tail"){let r=t==="end_anchor"?us(e.tail??"","end_anchor"):us(e.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:us(e.text??"",t)}}function ls(e){return e.mode==="head_tail"?me(e.head??"").length+me(e.tail??"").length:me(e.text??"").length}function us(e,t){let n=di(e);return n.length<=1?e.trim():t==="end_anchor"?n[n.length-1]??e.trim():n[0]??e.trim()}var Tp=i(()=>{"use strict";Xn()});var ft,Lp=i(()=>{"use strict";Rp();Tp();ss();cs();ft=class{resolve(t,n,r){let a=t.start_anchor??t.start,o=t.end_anchor??t.end,[s,c]=this.parseAnchor(a,"start_anchor");if(c!==void 0)return[void 0,c];let d;if(o!==void 0){let[g,v]=this.parseAnchor(o,"end_anchor");if(v!==void 0)return[void 0,v];d=g}let[u,f,x]=this.resolveAnchor({anchor:s,candidateSentenceIds:n,candidateTexts:r,label:"start_anchor"});if(x!==void 0)return[void 0,x];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(d===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:f},void 0];let[D,w,R]=this.resolveAnchor({anchor:d,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return R!==void 0?[void 0,R]:D===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:D.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${D.occurrenceId}).`}]:[{confidence:Math.min(u.score,D.score),sentenceIds:n.slice(u.index,D.index+1),strategy:`${f}+${w}`},void 0]}resolveWithOverrides(t){let n=t.evidence.start_anchor??t.evidence.start,r=t.evidence.end_anchor??t.evidence.end,[a,o]=this.parseAnchor(n,"start_anchor");if(o!==void 0)return[void 0,o];let s=t.overrides.start_anchor,[c,d,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:t.candidateSentenceIds,candidateTexts:t.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(c===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:c.score,sentenceIds:[c.sentenceId],strategy:d},void 0];let[f,x]=this.parseAnchor(r,"end_anchor");if(x!==void 0)return[void 0,x];let D=t.overrides.end_anchor,[w,R,g]=D===void 0?this.resolveAnchor({anchor:f,candidateSentenceIds:t.candidateSentenceIds,candidateTexts:t.candidateTexts,label:"end_anchor",minIndex:c.index}):[D,"choice_final",void 0];return g!==void 0?[void 0,g]:w===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:w.index<c.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${c.occurrenceId} -> ${w.occurrenceId}).`}]:[{confidence:Math.min(c.score,w.score),sentenceIds:t.candidateSentenceIds.slice(c.index,w.index+1),strategy:`${d}+${R}`},void 0]}parseAnchor(t,n){let[r,a]=vp(t);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[_p(r,n),void 0]}resolveAnchor(t){if(t.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:t.label,message:`${t.label} is missing`}];let n=this.rankAnchor(t.anchor,t.candidateSentenceIds,t.candidateTexts,t.label),r=t.minIndex;if(r!==void 0&&(n=n.filter(f=>f.index>=r)),n.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:t.label,message:`${t.label} could not be matched: no candidates available`}];let a=n.filter(f=>f.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#t(t.label,"ambiguous_exact_raw",a)];let o=n.filter(f=>f.exactSubstring);if(o.length===1&&ls(t.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&ls(t.anchor)>=8){let f=this.#e(o);return f!==void 0?[f,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#t(t.label,"ambiguous_exact_substring",o)]}let s=n.filter(f=>f.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let f=this.#e(s);return f!==void 0?[f,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#t(t.label,"ambiguous_exact_normalized",s)]}let c=n[0];if(c===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:t.label,message:`${t.label} could not be matched: no candidates available`}];let d=n[1]?.score??0,u=c.score-d;return c.score<.55?[void 0,"low_confidence",{candidates:n.slice(0,3),code:"low_confidence",fieldName:t.label,message:`${t.label} could not be matched confidently. Best candidate score=${c.score.toFixed(3)}.`}]:n.length===1?[c,"auto_top1_single_candidate",void 0]:c.score>=.97?[c,"auto_top1_very_high",void 0]:c.score>=.9&&u>=.07?[c,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#t(t.label,"ambiguous_ranked",n)]}rankAnchor(t,n,r,a){let o=[];for(let[s,c]of n.entries()){let d=r[s]??"",u=s>0?r[s-1]??"":"",f=s<r.length-1?r[s+1]??"":"",x=kp(t,d,a);o.push({exactNormalized:x.exactNormalized,exactRaw:x.exactRaw,exactSubstring:x.exactSubstring,index:s,nextText:f,occurrenceId:`S${s+1}`,prevText:u,score:x.score,sentenceId:c,text:d})}return o.sort((s,c)=>s.score!==c.score?c.score-s.score:s.exactRaw!==c.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==c.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==c.exactNormalized?s.exactNormalized?-1:1:s.index-c.index),o}#e(t){if(t.length===0)return;if(t.length===1)return t[0];let n=t[0];if(n===void 0)return;let r=t[1]?.score??0;if(n.score>=.9&&n.score-r>=.07)return n}#t(t,n,r){let a=r.slice(0,3),o=a.map(s=>xp(s)).join(`
711
- `);return{candidates:a,code:n,fieldName:t,message:`${t} is ambiguous. Top candidates:
662
+ `});var ld=i(()=>{"use strict";Be();Tr();Yn()});var Kh=i(()=>{"use strict";Bi();qi();ir();ea();Zi();we();na();Cn();vr();Cr();ld()});var zh=i(()=>{"use strict";Ys();qi();Kh();we();Tr();ld();Yn();Cr()});var ua=i(()=>{"use strict";Yn();Tr();zh();Cr();Yt()});function la(n){let e=n.trim();return e===""?[]:Array.from(LE.segment(e)).map(t=>t.segment.trim()).filter(t=>t!=="")}function ke(n){let e=n.replace(/\s+/gu," ").trim(),t=OE(e),r="";for(let a of t)if(!NE(a)){if(!_r(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function OE(n){let e=[],t=0;for(;t<n.length;){let r=n[t];if(r===void 0)break;if(r!==" "){e.push(r),t+=1;continue}if(e.length>=2&&AE.has(e[e.length-1]??"")&&_r(e[e.length-2]??"")&&t<n.length-1&&_r(n[t+1]??"")){e.pop(),t+=1;continue}let a=e[e.length-1]??"",o=n[t+1]??"";a!==""&&o!==""&&_r(a)&&_r(o)&&e.push(r),t+=1}return e}function _r(n){return n!==""&&new RegExp("\\p{Script=Latin}","u").test(n)&&new RegExp("\\p{L}","u").test(n)}function NE(n){return/[\p{P}\p{S}]/u.test(n)}var AE,LE,Pr=i(()=>{"use strict";AE=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),LE=new Intl.Segmenter(void 0,{granularity:"sentence"})});function pd(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Xh(n,e){let t=ma(n,2),r=ma(e,2),a=ma(n,3),o=ma(e,3);return(Qh(t,r)+Qh(a,o))/2}function ma(n,e){if(n.length<=e)return n===""?new Set:new Set([n]);let t=new Set;for(let r=0;r<=n.length-e;r+=1)t.add(n.slice(r,r+e));return t}function Qh(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&(t+=1);return 2*t/(n.size+e.size)}function Vh(n,e){if(n===e)return 1;if(n===""||e==="")return 0;let t=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...n].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(t[d+1]??0)+1,b=(t[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[t,r]=[r,t]}return 1-(t[e.length]??Math.max(n.length,e.length))/Math.max(n.length,e.length)}function Yh(n,e){return 1-Math.abs(n.length-e.length)/Math.max(n.length,e.length)}function Zh(n,e){if(n===e)return 1;let t=n.length,r=e.length;if(t===0||r===0)return 0;let a=Array.from({length:t+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=t;s+=1)for(let d=1;d<=r;d+=1){if(n[s-1]!==e[d-1])continue;let c=a[s];c!==void 0&&(c[d]=(a[s-1]?.[d-1]??0)+1,o=Math.max(o,c[d]??0))}return 2*o/(t+r)}function ef(n){return` - ${n.occurrenceId} score=${n.score.toFixed(3)}
663
+ prev: ${md(n.prevText)}
664
+ text: ${md(n.text,120)}
665
+ next: ${md(n.nextText)}`}function md(n,e=80){let t=n.replace(/\s+/gu," ").trim();return t===""?"(none)":t.length<=e?t:`${t.slice(0,e-3)}...`}var hd=i(()=>{"use strict"});var fd=i(()=>{"use strict"});function tf(n,e,t){return n.mode==="head_tail"?FE(n,e):yd(n.text??"",e,t)}function FE(n,e){let t=n.head??"",r=n.tail??"",a=ke(e),o=ke(t),s=ke(r);if(o===""||s==="")return pd();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let R=o.length+s.length,f=Math.min(1,R/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=yd(t,e,"start_anchor"),m=yd(r,e,"end_anchor"),b=u.matchStart<=m.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,m.matchEnd),matchStart:Math.min(u.matchStart,m.matchStart),score:(u.score+m.score)/2*b}}function yd(n,e,t){let r=n.trim(),a=e.trim(),o=ke(r),s=ke(a);if(o===""||s==="")return pd();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=nf({candidateNormalized:s,label:t,matchEnd:f+o.length,matchStart:f,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:f+o.length,matchStart:f,score:Math.min(1,.75+.25*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),R=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),A=new Set([...R,...C]).size,K=[...R].filter(ie=>C.has(ie)).length;if((A===0?0:K/A)<.35)continue;let G=.35*Xh(o,g)+.35*Zh(o,g)+.2*Vh(o,g)+.1*Yh(o,g)+nf({candidateNormalized:s,label:t,matchEnd:k+f,matchStart:k,queryNormalized:o});G>d&&(d=Math.min(1,G),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function nf(n){if(n.matchStart<0||n.matchEnd<0||n.queryNormalized.length<12||n.label==="start_anchor"&&n.matchStart!==0||n.label==="end_anchor"&&n.matchEnd!==n.candidateNormalized.length)return 0;let e=n.queryNormalized.length/Math.max(1,n.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var rf=i(()=>{"use strict";Pr();hd();fd()});function af(n){if(n==null)return[void 0,"anchor is required"];if(typeof n=="string"){let o=n.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(d=>d.trim()).filter(d=>d!=="");if(s.length>=2){let d=s[0],c=s[s.length-1];return d===void 0||c===void 0?[void 0,"anchor string is empty"]:[{head:d,mode:"head_tail",tail:c},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof n!="object")return[void 0,`expected string or object, got ${typeof n}`];let e=n;if((e.mode==="head_tail"||e.head!==void 0?"head_tail":"full")==="full"){let o=typeof e.text=="string"?e.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof e.head=="string"?e.head.trim():"",a=typeof e.tail=="string"?e.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function of(n,e){if(n===void 0)return;if(n.mode==="head_tail"){let r=e==="end_anchor"?gd(n.tail??"","end_anchor"):gd(n.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:gd(n.text??"",e)}}function bd(n){return n.mode==="head_tail"?ke(n.head??"").length+ke(n.tail??"").length:ke(n.text??"").length}function gd(n,e){let t=la(n);return t.length<=1?n.trim():e==="end_anchor"?t[t.length-1]??n.trim():t[0]??n.trim()}var sf=i(()=>{"use strict";Pr()});var Nn,lf=i(()=>{"use strict";rf();sf();hd();fd();Nn=class{resolve(e,t,r){let a=e.start_anchor??e.start,o=e.end_anchor??e.end,[s,d]=this.parseAnchor(a,"start_anchor");if(d!==void 0)return[void 0,d];let c;if(o!==void 0){let[g,C]=this.parseAnchor(o,"end_anchor");if(C!==void 0)return[void 0,C];c=g}let[u,m,b]=this.resolveAnchor({anchor:s,candidateSentenceIds:t,candidateTexts:r,label:"start_anchor"});if(b!==void 0)return[void 0,b];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(c===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:m},void 0];let[R,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:t,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:R===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:R.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${R.occurrenceId}).`}]:[{confidence:Math.min(u.score,R.score),sentenceIds:t.slice(u.index,R.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let t=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(t,"start_anchor");if(o!==void 0)return[void 0,o];let s=e.overrides.start_anchor,[d,c,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(d===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:d.score,sentenceIds:[d.sentenceId],strategy:c},void 0];let[m,b]=this.parseAnchor(r,"end_anchor");if(b!==void 0)return[void 0,b];let R=e.overrides.end_anchor,[f,k,g]=R===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[R,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,t){let[r,a]=af(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:t,message:`Invalid evidence.${t}: ${a}`}]:[of(r,t),void 0]}resolveAnchor(e){if(e.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:e.label,message:`${e.label} is missing`}];let t=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(t=t.filter(m=>m.index>=r)),t.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=t.filter(m=>m.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#n(e.label,"ambiguous_exact_raw",a)];let o=t.filter(m=>m.exactSubstring);if(o.length===1&&bd(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&bd(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#n(e.label,"ambiguous_exact_substring",o)]}let s=t.filter(m=>m.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let m=this.#e(s);return m!==void 0?[m,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#n(e.label,"ambiguous_exact_normalized",s)]}let d=t[0];if(d===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let c=t[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:t.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:t.length===1?[d,"auto_top1_single_candidate",void 0]:d.score>=.97?[d,"auto_top1_very_high",void 0]:d.score>=.9&&u>=.07?[d,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#n(e.label,"ambiguous_ranked",t)]}rankAnchor(e,t,r,a){let o=[];for(let[s,d]of t.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=tf(e,c,a);o.push({exactNormalized:b.exactNormalized,exactRaw:b.exactRaw,exactSubstring:b.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:b.score,sentenceId:d,text:c})}return o.sort((s,d)=>s.score!==d.score?d.score-s.score:s.exactRaw!==d.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==d.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==d.exactNormalized?s.exactNormalized?-1:1:s.index-d.index),o}#e(e){if(e.length===0)return;if(e.length===1)return e[0];let t=e[0];if(t===void 0)return;let r=e[1]?.score??0;if(t.score>=.9&&t.score-r>=.07)return t}#n(e,t,r){let a=r.slice(0,3),o=a.map(s=>ef(s)).join(`
666
+ `);return{candidates:a,code:t,fieldName:e,message:`${e} is ambiguous. Top candidates:
712
667
  ${o}
713
- Please provide a more specific anchor or surrounding context.`}}}});var Op=i(()=>{"use strict"});var Np=i(()=>{"use strict";Lp();Op()});var li,Dp=i(()=>{"use strict";li=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
714
- `)});var ms=i(()=>{"use strict"});var Fp=i(()=>{"use strict";ms();Xn()});var Lt=i(()=>{"use strict";Np();Dp();ms();Fp();Xn()});var Qn=i(()=>{"use strict"});import{z as Ae}from"zod";var sE,cE,F1,fs=i(()=>{"use strict";re();Qn();sE=Ae.object({candidateId:Ae.string().min(1),decision:Ae.enum(["continue","recall","skip_this_time","never_recall"]),qid:Ae.string().nullable().optional()}).strict(),cE=Ae.object({decisions:Ae.array(sE),groupId:Ae.string().min(1)}).strict(),F1=Ae.object({groups:Ae.array(cE)}).strict()});import{z as Vn}from"zod";var lE,U1,jp=i(()=>{"use strict";re();Qn();fs();lE=Vn.object({decision:Vn.enum(["keep","reject"]),qid:Vn.string().regex(/^Q[1-9][0-9]*$/)}).strict(),U1=Vn.object({qids:Vn.array(lE)}).strict()});var Gp=i(()=>{"use strict";jn()});import{z as Yn}from"zod";var mE,z1,Bp=i(()=>{"use strict";re();mE=Yn.object({note:Yn.string().max(24).optional(),surfaceId:Yn.string().min(1)}).strict(),z1=Yn.object({protectedSurfaces:Yn.array(mE)}).strict()});var ys=i(()=>{"use strict"});var Up=i(()=>{"use strict";ys()});var Hp=i(()=>{"use strict"});var gs=i(()=>{"use strict"});var qp=i(()=>{"use strict";gs();Qn()});var yt=i(()=>{"use strict";fs();jp();Qn();Gp();Bp();Up();ys();Hp();qp();gs()});var RK,bs=i(()=>{"use strict";Yt();RK=Object.freeze({"serial-generation/editor-compress":Object.freeze({temperature:.7,topP:.9}),"serial-generation/editor-review":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/editor-review-guide":Object.freeze({temperature:.4,topP:.6}),"serial-generation/reader-choice":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/reader-extraction":Object.freeze({temperature:[.3,.95],topP:[.4,.8]})})});var Ss=i(()=>{"use strict";ye()});var Jp=i(()=>{"use strict";Ss()});var zp=i(()=>{"use strict";Jp();Ss()});var Xp=i(()=>{"use strict"});var Qp=i(()=>{"use strict"});var Vp=i(()=>{"use strict";Xp();Qp()});var Zn=i(()=>{"use strict";re()});var Yp=i(()=>{"use strict";k();Zn()});var Zp=i(()=>{"use strict";Zn()});var eh=i(()=>{"use strict"});import{z as b}from"zod";var th,CE,nh,AE,PE,LE,OE,NE,DE,pi=i(()=>{"use strict";k();th=b.object({from:b.union([b.number().int(),b.string()]),strength:b.string().optional(),to:b.union([b.number().int(),b.string()])}),CE=b.object({quote:b.string().optional(),sentence_id:b.string().optional()}).passthrough(),nh=b.union([b.record(b.string(),b.unknown()),b.array(CE)]),AE=b.object({content:b.string(),evidence:nh.nullish(),label:b.string(),retention:b.enum(["verbatim","detailed","focused","relevant"]),temp_id:b.string()}).passthrough(),PE=b.object({chunks:b.array(AE),fragment_summary:b.string(),links:b.array(th)}),LE=b.object({content:b.string(),evidence:nh.nullish(),importance:b.enum(["critical","important","helpful"]),label:b.string(),temp_id:b.string()}).passthrough(),OE=b.object({chunk_id:b.number().int(),importance:b.enum(["critical","important","helpful"])}),NE=b.object({chunks:b.array(LE),importance_annotations:b.array(OE),links:b.array(th)}),DE=b.object({choice:b.string()})});var rh=i(()=>{"use strict";re();Lt();eh();Zn();pi()});var ih=i(()=>{"use strict";re();k();Yp();Zn();Zp();rh();pi()});var ah=i(()=>{"use strict";ih();pi()});var hi=i(()=>{"use strict"});import{detect as DJ,validateISO2 as FJ}from"tinyld";var ws=i(()=>{"use strict";Re()});var oh=i(()=>{"use strict";ws();Re()});var sh=i(()=>{"use strict"});import{z as er}from"zod";var GE,iz,dh=i(()=>{"use strict";re();Lt();ah();hi();hi();oh();sh();GE=er.object({content:er.string(),id:er.number(),label:er.string()}),iz=er.array(GE)});var Es=i(()=>{"use strict";dh()});var uh=i(()=>{"use strict";nt()});var xs=i(()=>{"use strict";uh()});var lh=i(()=>{"use strict";Vp();Es();xs()});var fi=i(()=>{"use strict";lh();xs()});var yi=i(()=>{"use strict"});var gi=i(()=>{"use strict";fi();yi()});var mh=i(()=>{"use strict";gi()});var ph=i(()=>{"use strict"});var bi=i(()=>{"use strict"});var hh=i(()=>{"use strict";bi()});var Ot,Nz,KE,Si=i(()=>{"use strict";Xi();Ot=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(Ot||{}),Nz=kt(Ot),KE=nn(Ot,"review severity")});var jz,ks=i(()=>{"use strict";bi();Si();jz=Object.freeze({critical:9,major:3,minor:1})});var fh=i(()=>{"use strict";ws();Re();Si()});var yh=i(()=>{"use strict";p();ye();ks()});var Rs=i(()=>{"use strict";k()});var gh=i(()=>{"use strict"});import{z as Nt}from"zod";var JE,zE,dX,bh=i(()=>{"use strict";ye();re();bi();Rs();Si();JE=["critical","major","minor"],zE=Nt.object({problem:Nt.string(),severity:Nt.enum(JE),suggestion:Nt.string().default("")}),dX=Nt.object({issues:Nt.array(zE)})});var Sh=i(()=>{"use strict";ph();hh();ks();fh();yh();Rs();gh();bh()});var vs=i(()=>{"use strict";Sh()});var Eh=i(()=>{"use strict"});var xh=i(()=>{"use strict"});var Ih=i(()=>{"use strict";Eh();xh()});var tr=i(()=>{"use strict"});var HX,qX,Dt=i(()=>{"use strict";k();HX={critical:9,helpful:1,important:3},qX={detailed:9,focused:3,relevant:1,verbatim:27}});var Ft=i(()=>{"use strict"});var nr=i(()=>{"use strict"});var _s=i(()=>{"use strict";Ft()});var Ts=i(()=>{"use strict";Dt();Ft();tr();nr();_s()});var Cs=i(()=>{"use strict";tr();Ts();nr()});var Rh=i(()=>{"use strict";Dt();Ft();nr()});var vh=i(()=>{"use strict";Dt();Ft();tr();nr();_s()});var _h=i(()=>{"use strict";Cs();Ft();tr();Rh();Ts();vh()});var Th=i(()=>{"use strict";_h();Cs()});var Ch=i(()=>{"use strict";Dt()});var Ah=i(()=>{"use strict";Th();Ch()});var Ph=i(()=>{"use strict";Ih();Ah();Dt()});var Lh=i(()=>{"use strict";Ph()});var As=i(()=>{"use strict"});var Oh=i(()=>{"use strict"});var Ps=i(()=>{"use strict";gi()});var Ei=i(()=>{"use strict"});var Nh=i(()=>{"use strict";Qt();Yt();vs();fi();Lh();gi();yi();As();Oh();Ps();Ei()});var Dh=i(()=>{"use strict";As();Ei()});var Fh=i(()=>{"use strict";mh();Nh();yi();Dh();Ps();Ei()});var Mt=i(()=>{"use strict";Fh()});var Mh=i(()=>{"use strict";se();Qt();Mt();at()});var Wh=i(()=>{"use strict";at();at();k();se();zp();Mt();Mh();Ar();p()});var jh,Ke=i(()=>{"use strict";jh=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var Ns=i(()=>{"use strict";Ke()});var Gh=i(()=>{"use strict";ye();Ui();Wh();bs();Ce();Ns();p()});var Ds,Fs=i(()=>{"use strict";Ds=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function Bh(){return await q(I().library,"jobs/work")}async function Uh(e){let t=await I().library.getDirectory("jobs");if(t!==void 0)for(let[n,r,a]of[["work",e,!0],["cache",e,!0],["logs",e,!0],["events",`${e}.ndjson`,!1]]){let o=await t.getDirectory(n);o!==void 0&&await o.remove(r,{recursive:a})}}var rr=i(()=>{"use strict";p()});var ir=i(()=>{"use strict";O()});var Ms=i(()=>{"use strict"});var ar=i(()=>{"use strict";p()});var Hh,qh=i(()=>{"use strict";Hh=`
668
+ Please provide a more specific anchor or surrounding context.`}}}});var mf=i(()=>{"use strict"});var pf=i(()=>{"use strict";lf();mf()});var pa,hf=i(()=>{"use strict";pa=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
669
+ `)});var Sd=i(()=>{"use strict"});var ff=i(()=>{"use strict";Sd();Pr()});var lt=i(()=>{"use strict";pf();hf();Sd();ff();Pr()});import{z as Ar}from"zod";var LQ,gf=i(()=>{"use strict";LQ=Ar.object({meanings:Ar.array(Ar.object({information:Ar.string(),qid:Ar.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var bf=i(()=>{"use strict"});var Sf=i(()=>{"use strict"});var wf=i(()=>{"use strict"});var kf=i(()=>{"use strict";gf();bf();Sf();wf()});async function kd(n){let e=await Lr.open();try{return await e.gc(n)}finally{await e.close()}}function YE(n){try{let e=JSON.parse(n);if(typeof e!="object"||e===null)return;let t=e;return typeof t.qid!="string"||typeof t.refreshedAt!="string"||typeof t.disambiguation!="boolean"||!Array.isArray(t.sites)?void 0:{disambiguation:t.disambiguation,qid:t.qid,refreshedAt:t.refreshedAt,sites:t.sites}}catch{return}}var XE,VE,Lr,xf=i(()=>{"use strict";kf();_();XE=`
670
+ CREATE TABLE IF NOT EXISTS wikimedia_cache_v1 (
671
+ qid TEXT PRIMARY KEY,
672
+ record_json TEXT NOT NULL,
673
+ refreshed_at TEXT NOT NULL
674
+ );
675
+ CREATE INDEX IF NOT EXISTS idx_wikimedia_cache_v1_refreshed_at
676
+ ON wikimedia_cache_v1(refreshed_at);
677
+ `,VE=336*60*60*1e3,Lr=class n{#e;constructor(e){this.#e=e}static async open(){return new n(await X("cache/cache.sqlite",XE))}async get(e){let t=new Map;for(let r of e){let a=await this.#e.queryOne("SELECT record_json FROM wikimedia_cache_v1 WHERE qid = ?",[r],s=>String(s.record_json)),o=a===void 0?void 0:YE(a);o!==void 0&&o.qid===r&&t.set(r,o)}return t}async put(e){await this.#e.transaction(async()=>{for(let t of e)await this.#e.run(`INSERT INTO wikimedia_cache_v1(qid,record_json,refreshed_at)
678
+ VALUES(?,?,?)
679
+ ON CONFLICT(qid) DO UPDATE SET
680
+ record_json=excluded.record_json,
681
+ refreshed_at=excluded.refreshed_at`,[t.qid,JSON.stringify(t),t.refreshedAt])})}async close(){await this.#e.close()}async gc(e){let t=new Date(e.now-VE).toISOString(),r=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_cache_v1",void 0,o=>Number(o.count))??0,a=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_cache_v1 WHERE refreshed_at < ?",[t],o=>Number(o.count))??0;return!e.dryRun&&a>0&&(await this.#e.run("DELETE FROM wikimedia_cache_v1 WHERE refreshed_at < ?",[t]),await this.#e.run("VACUUM")),{freedBytes:0,removed:a,scanned:r}}}});var Id=i(()=>{"use strict";xf()});var Ed=i(()=>{"use strict"});var Rd=i(()=>{"use strict"});import{jsonrepair as YQ}from"jsonrepair";var If=i(()=>{"use strict"});var Ef=i(()=>{"use strict";Rd();Ed();If()});var Ae=i(()=>{"use strict";Ed();Rd();Ef()});var Or=i(()=>{"use strict"});import{z as He}from"zod";var rR,iR,IX,Td=i(()=>{"use strict";Ae();Or();rR=He.object({candidateId:He.string().min(1),decision:He.enum(["continue","recall","skip_this_time","never_recall"]),qid:He.string().nullable().optional()}).strict(),iR=He.object({decisions:He.array(rR),groupId:He.string().min(1)}).strict(),IX=He.object({groups:He.array(iR)}).strict()});import{z as Nr}from"zod";var sR,_X,Cf=i(()=>{"use strict";Ae();Or();Td();sR=Nr.object({decision:Nr.enum(["keep","reject"]),qid:Nr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),_X=Nr.object({qids:Nr.array(sR)}).strict()});var Tf=i(()=>{"use strict"});import{z as Dr}from"zod";var dR,NX,_f=i(()=>{"use strict";Ae();dR=Dr.object({note:Dr.string().max(24).optional(),surfaceId:Dr.string().min(1)}).strict(),NX=Dr.object({protectedSurfaces:Dr.array(dR)}).strict()});var _d=i(()=>{"use strict"});var Pf=i(()=>{"use strict";_d()});var Af=i(()=>{"use strict"});var Pd=i(()=>{"use strict"});var Lf=i(()=>{"use strict";Pd();Or()});var sn=i(()=>{"use strict";Td();Cf();Or();Tf();_f();Pf();_d();Af();Lf();Pd()});var lV,Ld=i(()=>{"use strict";Qn();lV=Object.freeze({"serial-generation/editor-compress":Object.freeze({temperature:.7,topP:.9}),"serial-generation/editor-review":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/editor-review-guide":Object.freeze({temperature:.4,topP:.6}),"serial-generation/reader-choice":Object.freeze({temperature:[.3,.95],topP:[.4,.8]}),"serial-generation/reader-extraction":Object.freeze({temperature:[.3,.95],topP:[.4,.8]})})});var Od=i(()=>{"use strict";Xe()});var Ff=i(()=>{"use strict";Od()});var Mf=i(()=>{"use strict";Ff();Od()});var Gf=i(()=>{"use strict"});var jf=i(()=>{"use strict"});var Bf=i(()=>{"use strict";Gf();jf()});var Wr=i(()=>{"use strict";Ae()});var Uf=i(()=>{"use strict";_();Wr()});var qf=i(()=>{"use strict";Wr()});var Hf=i(()=>{"use strict"});import{z as x}from"zod";var $f,xR,Jf,IR,ER,RR,vR,CR,TR,fa=i(()=>{"use strict";_();$f=x.object({from:x.union([x.number().int(),x.string()]),strength:x.string().optional(),to:x.union([x.number().int(),x.string()])}),xR=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).passthrough(),Jf=x.union([x.record(x.string(),x.unknown()),x.array(xR)]),IR=x.object({content:x.string(),evidence:Jf.nullish(),label:x.string(),retention:x.enum(["verbatim","detailed","focused","relevant"]),temp_id:x.string()}).passthrough(),ER=x.object({chunks:x.array(IR),fragment_summary:x.string(),links:x.array($f)}),RR=x.object({content:x.string(),evidence:Jf.nullish(),importance:x.enum(["critical","important","helpful"]),label:x.string(),temp_id:x.string()}).passthrough(),vR=x.object({chunk_id:x.number().int(),importance:x.enum(["critical","important","helpful"])}),CR=x.object({chunks:x.array(RR),importance_annotations:x.array(vR),links:x.array($f)}),TR=x.object({choice:x.string()})});var Kf=i(()=>{"use strict";Ae();lt();Hf();Wr();fa()});var zf=i(()=>{"use strict";Ae();_();Uf();Wr();qf();Kf();fa()});var Qf=i(()=>{"use strict";zf();fa()});var ya=i(()=>{"use strict"});import{detect as kY,validateISO2 as xY}from"tinyld";var Nd=i(()=>{"use strict";De()});var Xf=i(()=>{"use strict";Nd();De()});var Vf=i(()=>{"use strict"});import{z as Fr}from"zod";var OR,HY,Zf=i(()=>{"use strict";Ae();lt();Qf();ya();ya();Xf();Vf();OR=Fr.object({content:Fr.string(),id:Fr.number(),label:Fr.string()}),HY=Fr.array(OR)});var Dd=i(()=>{"use strict";Zf()});var ey=i(()=>{"use strict";wn()});var Wd=i(()=>{"use strict";ey()});var ny=i(()=>{"use strict";Bf();Dd();Wd()});var ga=i(()=>{"use strict";ny();Wd()});var ba=i(()=>{"use strict"});var Sa=i(()=>{"use strict";ga();ba()});var ty=i(()=>{"use strict";Sa()});var ry=i(()=>{"use strict"});var wa=i(()=>{"use strict"});var iy=i(()=>{"use strict";wa()});var pt,w2,GR,ka=i(()=>{"use strict";ho();pt=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(pt||{}),w2=Vn(pt),GR=Gt(pt,"review severity")});var R2,Md=i(()=>{"use strict";wa();ka();R2=Object.freeze({critical:9,major:3,minor:1})});var ay=i(()=>{"use strict";Nd();De();ka()});var oy=i(()=>{"use strict";y();Xe();Md()});var Gd=i(()=>{"use strict";_()});var sy=i(()=>{"use strict"});import{z as ht}from"zod";var jR,BR,Q2,dy=i(()=>{"use strict";Xe();Ae();wa();Gd();ka();jR=["critical","major","minor"],BR=ht.object({problem:ht.string(),severity:ht.enum(jR),suggestion:ht.string().default("")}),Q2=ht.object({issues:ht.array(BR)})});var cy=i(()=>{"use strict";ry();iy();Md();ay();oy();Gd();sy();dy()});var jd=i(()=>{"use strict";cy()});var ly=i(()=>{"use strict"});var my=i(()=>{"use strict"});var py=i(()=>{"use strict";ly();my()});var Mr=i(()=>{"use strict"});var _3,P3,ft=i(()=>{"use strict";_();_3={critical:9,helpful:1,important:3},P3={detailed:9,focused:3,relevant:1,verbatim:27}});var yt=i(()=>{"use strict"});var Gr=i(()=>{"use strict"});var Bd=i(()=>{"use strict";yt()});var Ud=i(()=>{"use strict";ft();yt();Mr();Gr();Bd()});var qd=i(()=>{"use strict";Mr();Ud();Gr()});var fy=i(()=>{"use strict";ft();yt();Gr()});var yy=i(()=>{"use strict";ft();yt();Mr();Gr();Bd()});var gy=i(()=>{"use strict";qd();yt();Mr();fy();Ud();yy()});var by=i(()=>{"use strict";gy();qd()});var Sy=i(()=>{"use strict";ft()});var wy=i(()=>{"use strict";by();Sy()});var ky=i(()=>{"use strict";py();wy();ft()});var xy=i(()=>{"use strict";ky()});var Hd=i(()=>{"use strict";Z()});var Iy=i(()=>{"use strict"});var $d=i(()=>{"use strict";Sa()});var Ia=i(()=>{"use strict"});var Ey=i(()=>{"use strict";Nt();Qn();jd();ga();xy();Sa();ba();Hd();Iy();$d();Ia()});var Ry=i(()=>{"use strict";Hd();Ia();Z()});var vy=i(()=>{"use strict";ty();Ey();ba();Ry();$d();Ia()});var gt=i(()=>{"use strict";vy()});var Cy=i(()=>{"use strict";ye();Nt();gt();xn()});var Ty=i(()=>{"use strict";xn();xn();_();ye();Mf();gt();Cy();Wi();y()});var zd,dn=i(()=>{"use strict";zd=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var Qd=i(()=>{"use strict";dn()});var Ay=i(()=>{"use strict";Xe();so();Ty();Ld();Be();Qd();y()});var Xd,Vd=i(()=>{"use strict";Xd=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function Ly(){return await z(v().library,"jobs/work")}async function Oy(n){let e=await v().library.getDirectory("jobs");if(e!==void 0)for(let[t,r,a]of[["work",n,!0],["cache",n,!0],["logs",n,!0],["events",`${n}.ndjson`,!1]]){let o=await e.getDirectory(t);o!==void 0&&await o.remove(r,{recursive:a})}}var jr=i(()=>{"use strict";y()});var Br=i(()=>{"use strict";U()});var Yd=i(()=>{"use strict"});var Ur=i(()=>{"use strict";y()});var Ny,Dy=i(()=>{"use strict";Ny=`
715
682
  CREATE TABLE IF NOT EXISTS build_jobs (
716
683
  job_id TEXT PRIMARY KEY,
717
684
  archive_key TEXT NOT NULL,
@@ -770,25 +737,43 @@ CREATE TABLE IF NOT EXISTS build_worker_lease (
770
737
 
771
738
  INSERT OR IGNORE INTO build_worker_lease (id)
772
739
  VALUES (1);
773
- `});function bt(e){let t=cx(gt(e,"current_step"),"current_step"),n=gt(e,"owner_id"),r=e.owner_pid===null?void 0:Y(e,"owner_pid"),a=e.reading_summary_started_at===null?void 0:Y(e,"reading_summary_started_at"),o=e.finished_at===null?void 0:Y(e,"finished_at"),s=gt(e,"error_json"),c=e.input_revision===null?void 0:Y(e,"input_revision"),d=gt(e,"llm_json"),u=gt(e,"prompt");return{archiveKey:ke(e,"archive_key"),archiveIdentity:ke(e,"archive_path"),cacheIdentity:ke(e,"cache_path"),chapterId:Y(e,"chapter_id"),createdAt:Y(e,"created_at"),...t===void 0?{}:{currentStep:t},...s===void 0?{}:{errorJSON:s},eventsIdentity:ke(e,"events_path"),...o===void 0?{}:{finishedAt:o},jobId:ke(e,"job_id"),...c===void 0?{}:{inputRevision:c},logIdentity:ke(e,"log_path"),...d===void 0?{}:{llmJSON:d},...n===void 0?{}:{ownerId:n},...r===void 0?{}:{ownerPid:r},...u===void 0?{}:{prompt:u},queueRank:Y(e,"queue_rank"),state:sx(ke(e,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:$h(ke(e,"target"),"target"),updatedAt:Y(e,"updated_at"),workspaceIdentity:ke(e,"workspace_path")}}async function sr(e){let t=L().resources,[n,r,a,o,s]=await Promise.all([t.getFile(e.archiveIdentity),t.getDirectory(e.cacheIdentity),t.getFile(e.eventsIdentity),t.getDirectory(e.logIdentity),t.getDirectory(e.workspaceIdentity)]);if(n===void 0)throw or("archive");if(r===void 0)throw or("cache");if(a===void 0)throw or("events");if(o===void 0)throw or("log");if(s===void 0)throw or("workspace");let{archiveIdentity:c,cacheIdentity:d,eventsIdentity:u,logIdentity:f,ownerPid:x,workspaceIdentity:D,...w}=e;return{...w,archive:n,cache:r,events:a,log:o,workspace:s}}function or(e){return new Error(`Build job ${e} resource is unavailable`)}function sx(e){if(Ds.includes(e))return e;throw new Error(`Invalid build job state: ${e}`)}function $h(e,t){if(e==="index-embedding-source"||e==="index-embedding-summary"||e==="index-fts"||e==="reading-graph"||e==="knowledge-graph"||e==="reading-summary")return e;throw new Error(`Invalid ${t}: ${e}`)}function cx(e,t){return e===void 0?void 0:$h(e,t)}function ke(e,t){let n=e[t];if(typeof n!="string")throw new TypeError(`Expected ${t} to be a string`);return n}function Y(e,t){let n=e[t];if(typeof n!="number")throw new TypeError(`Expected ${t} to be a number`);return n}function gt(e,t){let n=e[t];if(n!=null){if(typeof n!="string")throw new TypeError(`Expected ${t} to be a string`);return n}}var St=i(()=>{"use strict";Fs();p()});async function jt(){return await B("jobs/job.sqlite",Hh)}var Gt=i(()=>{"use strict";k();qh();St()});var xi=i(()=>{"use strict";ir();ar();Gt();rr()});var Ii=i(()=>{"use strict";St();xi();rr()});var Ws=i(()=>{"use strict";O();rr();ir();Ms();ar();Gt();Ii();xi();St()});var Xh=i(()=>{"use strict";ir();Gt();Ii();St()});var Qh=i(()=>{"use strict";O();ir();Ms();ar();Gt();Ii();xi();Ws();St()});function fx(e){return px.has(e)}async function yx(e,t){if((await t.list()).some(a=>!fx(a.name)))return 0;let r=await Je(t);return await e.remove(t.name,{recursive:!0}),r}async function Vh(e){let t=0,n=0,r=0;for(let a of await e.list()){if(!G(a))continue;r+=1;let o=await Le(a);if(o===void 0||Date.now()-o<hx)continue;let s=await yx(e,a);(s>0||await e.getDirectory(a.name)===void 0)&&(t+=s,n+=1)}return{freedBytes:t,removed:n,scanned:r}}async function Je(e){return await pe(e)}var px,hx,js=i(()=>{"use strict";p();px=new Set([".DS_Store"]),hx=6e4});async function ki(e){let t=await jt(),n=e.force?e.now:e.now-10080*60*1e3;try{let r=await t.queryOne("SELECT COUNT(*) AS count FROM build_jobs",void 0,d=>Y(d,"count")),a=await t.queryAll(`
740
+ `});function Fn(n){let e=nv(Wn(n,"current_step"),"current_step"),t=Wn(n,"owner_id"),r=n.owner_pid===null?void 0:se(n,"owner_pid"),a=n.reading_summary_started_at===null?void 0:se(n,"reading_summary_started_at"),o=n.finished_at===null?void 0:se(n,"finished_at"),s=Wn(n,"error_json"),d=n.input_revision===null?void 0:se(n,"input_revision"),c=Wn(n,"llm_json"),u=Wn(n,"prompt");return{archiveKey:Le(n,"archive_key"),archiveIdentity:Le(n,"archive_path"),cacheLocator:Le(n,"cache_path"),chapterId:se(n,"chapter_id"),createdAt:se(n,"created_at"),...e===void 0?{}:{currentStep:e},...s===void 0?{}:{errorJSON:s},eventsLocator:Le(n,"events_path"),...o===void 0?{}:{finishedAt:o},jobId:Le(n,"job_id"),...d===void 0?{}:{inputRevision:d},logLocator:Le(n,"log_path"),...c===void 0?{}:{llmJSON:c},...t===void 0?{}:{ownerId:t},...r===void 0?{}:{ownerPid:r},...u===void 0?{}:{prompt:u},queueRank:se(n,"queue_rank"),state:ev(Le(n,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:Wy(Le(n,"target"),"target"),updatedAt:se(n,"updated_at"),workspaceLocator:Le(n,"workspace_path")}}async function Hr(n){let e=L().resources,[t,r,a,o,s]=await Promise.all([e.getFile(n.archiveIdentity),Zd(n.cacheLocator),ZR(n.eventsLocator),Zd(n.logLocator),Zd(n.workspaceLocator)]);if(t===void 0)throw qr("archive");if(r===void 0)throw qr("cache");if(a===void 0)throw qr("events");if(o===void 0)throw qr("log");if(s===void 0)throw qr("workspace");let{archiveIdentity:d,cacheLocator:c,eventsLocator:u,logLocator:m,ownerPid:b,workspaceLocator:R,...f}=n;return{...f,archive:t,cache:r,events:a,log:o,workspace:s}}async function Zd(n){return n.startsWith("jobs/")?await Oe(v().library,n)??YR(n):await L().resources.getDirectory(n)}function YR(n){let e=v().library,t=r=>`${n}/${r}`;return{createDirectory:async r=>await z(e,t(r)),createFile:async r=>await H(e,t(r)),getDirectory:async r=>await Oe(e,t(r)),getFile:async r=>await J(e,t(r)),getLastModified:async()=>await(await Oe(e,n))?.getLastModified?.(),identity:`managed:library:${n}`,kind:"directory",list:async()=>(await Oe(e,n))?.list()??[],name:n.split("/").at(-1)??n,remove:async(r,a)=>{await(await Oe(e,n))?.remove(r,a)}}}async function ZR(n){return n.startsWith("jobs/")?await J(v().library,n):await L().resources.getFile(n)}function qr(n){return new Error(`Build job ${n} resource is unavailable`)}function ev(n){if(Xd.includes(n))return n;throw new Error(`Invalid build job state: ${n}`)}function Wy(n,e){if(n==="index-embedding-source"||n==="index-embedding-summary"||n==="index-fts"||n==="reading-graph"||n==="knowledge-graph"||n==="reading-summary")return n;throw new Error(`Invalid ${e}: ${n}`)}function nv(n,e){return n===void 0?void 0:Wy(n,e)}function Le(n,e){let t=n[e];if(typeof t!="string")throw new TypeError(`Expected ${e} to be a string`);return t}function se(n,e){let t=n[e];if(typeof t!="number")throw new TypeError(`Expected ${e} to be a number`);return t}function Wn(n,e){let t=n[e];if(t!=null){if(typeof t!="string")throw new TypeError(`Expected ${e} to be a string`);return t}}var Mn=i(()=>{"use strict";Vd();y()});async function bt(){let n=await X("jobs/job.sqlite",Ny);try{return await n.run(`
741
+ UPDATE build_jobs
742
+ SET workspace_path = 'jobs/work/' || job_id,
743
+ cache_path = 'jobs/cache/' || job_id,
744
+ log_path = 'jobs/logs/' || job_id,
745
+ events_path = 'jobs/events/' || job_id || '.ndjson'
746
+ WHERE workspace_path NOT LIKE 'jobs/work/%'
747
+ OR cache_path NOT LIKE 'jobs/cache/%'
748
+ OR log_path NOT LIKE 'jobs/logs/%'
749
+ OR events_path NOT LIKE 'jobs/events/%'
750
+ `),n}catch(e){throw await n.close().catch(()=>{}),e}}var St=i(()=>{"use strict";_();y();Dy();Mn()});var Ea=i(()=>{"use strict";Br();Ur();St();jr()});var Ra=i(()=>{"use strict";Mn();Ea();jr()});var ec=i(()=>{"use strict";U();jr();Br();Yd();Ur();St();Ra();Ea();Mn()});var jy=i(()=>{"use strict";Br();St();Ra();Mn()});var By=i(()=>{"use strict";U();Br();Yd();Ur();St();Ra();Ea();ec();Mn()});function dv(n){return ov.has(n)}async function cv(n,e){if((await e.list()).some(a=>!dv(a.name)))return 0;let r=await un(e);return await n.remove(e.name,{recursive:!0}),r}async function Uy(n){let e=0,t=0,r=0;for(let a of await n.list()){if(!j(a))continue;r+=1;let o=await ze(a);if(o===void 0||Date.now()-o<sv)continue;let s=await cv(n,a);(s>0||await n.getDirectory(a.name)===void 0)&&(e+=s,t+=1)}return{freedBytes:e,removed:t,scanned:r}}async function un(n){return await Ie(n)}var ov,sv,nc=i(()=>{"use strict";y();ov=new Set([".DS_Store"]),sv=6e4});async function va(n){let e=await bt(),t=n.force?n.now:n.now-10080*60*1e3;try{let r=await e.queryOne("SELECT COUNT(*) AS count FROM build_jobs",void 0,c=>se(c,"count")),a=await e.queryAll(`
774
751
  SELECT *
775
752
  FROM build_jobs
776
753
  WHERE state IN ('succeeded', 'failed', 'canceled')
777
754
  AND updated_at <= ?
778
- `,[n],bt),o=await Promise.all(a.map(sr)),s=e.dryRun?{freedBytes:0,removed:0,scanned:0}:await Vh(await Bh()),c=0;for(let d of o)c+=await Je(d.workspace),c+=await Je(d.cache),c+=await Je(d.log),c+=await Je(d.events),e.dryRun||(await Uh(d.jobId),await t.run("DELETE FROM build_jobs WHERE job_id = ?",[d.jobId]));return{freedBytes:c+s.freedBytes,removed:o.length+s.removed,scanned:(r??0)+s.scanned}}finally{await t.close()}}var Yh=i(()=>{"use strict";js();rr();Gt();St()});var yf=i(()=>{"use strict";Fs();Ws();Xh();Qh();ar();Yh()});var Ri=i(()=>{"use strict"});import{z as l}from"zod";var gf,U,bx,Sx,bf,wx,Ex,xx,Ix,kx,Rx,vx,_x,Tx,Cx,Ax,Px,Lx,Ox,r8,Bt=i(()=>{"use strict";p();be();Ri();gf=1,U=l.number().int().nonnegative(),bx=l.literal(gf),Sx=l.string().regex(/^Q[1-9][0-9]*$/u),bf=l.number().min(0).max(1).optional(),wx=l.object({text:l.string(),wordsCount:U}).strict(),Ex=l.object({type:l.literal("meta"),schemaVersion:bx,chapterId:l.number().int(),stream:l.enum(["knowledge-graph","reading-graph","summary"])}).strict(),xx=l.object({type:l.literal("parameter"),scope:l.enum(["knowledge-graph","reading-graph","summary"]),language:l.string().optional(),prompt:l.string()}).strict(),Ix=l.object({type:l.literal("source-fragment"),fragmentId:U,summary:l.string(),sentences:l.array(wx)}).strict(),kx=l.object({type:l.literal("reading-chunk"),id:l.string().min(1),generation:l.number().int(),sentenceIndex:U,label:l.string(),content:l.string(),sentenceIndexes:l.array(U).min(1),retention:l.enum(ae).optional(),importance:l.enum(ge).optional(),wordsCount:U,weight:l.number()}).strict(),Rx=l.object({type:l.literal("reading-edge"),fromChunkId:l.string().min(1),toChunkId:l.string().min(1),strength:l.string().optional(),weight:l.number()}).strict(),vx=l.object({type:l.literal("fragment-group"),groupId:U,startSentenceIndex:U,endSentenceIndex:U}).strict(),_x=l.object({type:l.literal("snake"),id:l.string().min(1),groupId:U,localSnakeId:U,size:U,firstLabel:l.string(),lastLabel:l.string(),wordsCount:U,weight:l.number()}).strict(),Tx=l.object({type:l.literal("snake-chunk"),snakeId:l.string().min(1),chunkId:l.string().min(1),position:U}).strict(),Cx=l.object({type:l.literal("snake-edge"),fromSnakeId:l.string().min(1),toSnakeId:l.string().min(1),weight:l.number()}).strict(),Ax=l.object({type:l.literal("summary"),text:l.string()}).strict(),Px=l.object({type:l.literal("mention"),id:l.string().min(1),fragmentId:U.optional(),sentenceIndex:U.optional(),rangeStart:U,rangeEnd:U,surface:l.string().min(1),qid:Sx,confidence:bf,note:l.string().optional()}).strict(),Lx=l.object({type:l.literal("mention-link"),id:l.string().min(1),sourceMentionId:l.string().min(1),targetMentionId:l.string().min(1),predicate:l.string().min(1),evidenceSentenceIndexes:l.array(U).min(1),confidence:bf,note:l.string().optional()}).strict(),Ox=l.object({type:l.literal("end")}).strict(),r8=l.discriminatedUnion("type",[Ex,xx,Ix,kx,Rx,vx,_x,Tx,Cx,Ax,Px,Lx,Ox])});var Sf=i(()=>{"use strict";qn();Ue()});import{z as E}from"zod";var Nx,Dx,u8,l8,m8,wf=i(()=>{"use strict";p();Nx="wikg-index-output/v1",Dx=E.enum(["fts","embedding-source","embedding-summary"]),u8=E.object({artifactKind:Dx,chapterId:E.number().int().nonnegative(),embedding:E.object({dimensions:E.number().int().nonnegative(),identity:E.string().optional(),model:E.string()}).optional(),inputRevision:E.number().int().nonnegative(),protocol:E.literal(Nx),type:E.literal("manifest")}),l8=E.object({metadata:E.record(E.string(),E.unknown()).optional(),objectId:E.string().min(1),objectKind:E.string().min(1),rowId:E.string().min(1),sentenceIndex:E.number().int().nonnegative().optional(),text:E.string(),tokens:E.array(E.string()),type:E.literal("lexical-row")}),m8=E.object({endSentenceIndex:E.number().int().nonnegative(),segmentIndex:E.number().int().nonnegative(),startSentenceIndex:E.number().int().nonnegative(),text:E.string(),vector:E.array(E.number()),wordsCount:E.number().int().nonnegative(),type:E.literal("segment")})});var Ut=i(()=>{"use strict";Sf();wf()});var Ef=i(()=>{"use strict";Re();Ke()});var xf=i(()=>{"use strict";k();fi()});var kf=i(()=>{"use strict";p();k();$();Mt();Bt();Ut();Ef();xf()});var vi=i(()=>{"use strict"});var Rf=i(()=>{"use strict";vi()});var vf=i(()=>{"use strict"});var _f=i(()=>{"use strict";vi()});var Tf=i(()=>{"use strict";vi()});var Cf=i(()=>{"use strict";Rf();vf();_f();Tf()});import{z as m}from"zod";var Af,Jx,zx,Xx,Qx,Vx,Yx,Zx,eI,tI,nI,Pf=i(()=>{"use strict";be();Af=m.tuple([m.number(),m.number()]),Jx=m.object({text:m.string(),wordsCount:m.number()}),zx=m.object({serialId:m.number(),fragmentId:m.number(),summary:m.string(),sentences:m.array(Jx)}),Xx=m.object({documentOrder:m.number().optional(),id:m.number(),knowledgeGraphReady:m.boolean(),knowledgeGraphParameterHash:m.string().optional(),revision:m.number().optional(),topologyParameterHash:m.string().optional(),topologyReady:m.boolean()}).transform(e=>({documentOrder:e.documentOrder??e.id,id:e.id,knowledgeGraphReady:e.knowledgeGraphReady,...e.knowledgeGraphParameterHash===void 0?{}:{knowledgeGraphParameterHash:e.knowledgeGraphParameterHash},revision:e.revision??0,topologyReady:e.topologyReady,...e.topologyParameterHash===void 0?{}:{topologyParameterHash:e.topologyParameterHash}})),Qx=m.object({id:m.number(),generation:m.number(),sentenceId:Af,label:m.string(),content:m.string(),sentenceIds:m.array(Af),retention:m.enum(ae).optional(),importance:m.enum(ge).optional(),wordsCount:m.number(),weight:m.number()}),Vx=m.object({fromId:m.number(),toId:m.number(),strength:m.string().optional(),weight:m.number()}),Yx=m.object({id:m.number(),serialId:m.number(),groupId:m.number(),localSnakeId:m.number(),size:m.number(),firstLabel:m.string(),lastLabel:m.string(),wordsCount:m.number(),weight:m.number()}),Zx=m.object({snakeId:m.number(),chunkId:m.number(),position:m.number()}),eI=m.object({fromSnakeId:m.number(),toSnakeId:m.number(),weight:m.number()}),tI=m.object({serialId:m.number(),groupId:m.number(),startSentenceIndex:m.number(),endSentenceIndex:m.number()}),nI=m.object({chunks:m.array(Qx),fragmentGroups:m.array(tI),fragments:m.array(zx),readingEdges:m.array(Vx),serial:Xx,snakeChunks:m.array(Zx),snakeEdges:m.array(eI),snakes:m.array(Yx)})});var Lf=i(()=>{"use strict";p();Pf()});var Of=i(()=>{"use strict";Yt();vs()});var Nf=i(()=>{"use strict";p();k();$();Cf();Lf();Ri();Of();Bt();Ut()});var Df=i(()=>{"use strict"});var Hs=i(()=>{"use strict";Nf();Ri();Df()});var Ff=i(()=>{"use strict";$();Hs()});var Mf=i(()=>{"use strict"});var Wf=i(()=>{"use strict";kf();Ff();Mf()});var jf=i(()=>{"use strict";Wf();Hs()});import{z as F}from"zod";var s6,iI,c6,qs=i(()=>{"use strict";p();s6=F.object({id:F.string().min(1),chapterId:F.number().int(),sentenceIndex:F.number().int().nonnegative().optional(),rangeStart:F.number().int().nonnegative(),rangeEnd:F.number().int().nonnegative(),surface:F.string().min(1),qid:F.string().regex(/^Q[1-9][0-9]*$/),confidence:F.number().min(0).max(1).optional(),note:F.string().optional()}),iI=F.tuple([F.number().int().nonnegative(),F.number().int().nonnegative()]).readonly(),c6=F.object({id:F.string().min(1),sourceMentionId:F.string().min(1),targetMentionId:F.string().min(1),predicate:F.string().min(1),evidenceSentenceIds:F.array(iI).min(1),confidence:F.number().min(0).max(1).optional(),note:F.string().optional()})});var $s=i(()=>{"use strict";p();Re();Bt();qs()});var Bf=i(()=>{"use strict";Bt();Ut();qs()});var _i=i(()=>{"use strict"});var Uf=i(()=>{"use strict";yt();_i()});var Ks=i(()=>{"use strict"});var Hf=i(()=>{"use strict";yt()});var Js=i(()=>{"use strict"});var zs=i(()=>{"use strict";yt();_i();Hf();Js()});var $f=i(()=>{"use strict";zs()});var Kf=i(()=>{"use strict";Re()});var Xs=i(()=>{"use strict"});var Jf=i(()=>{"use strict";Es();Lt();hi()});import{z as A}from"zod";var zf,cI,dI,uI,Z6,eZ,Xf=i(()=>{"use strict";re();Lt();Jf();zf=A.object({head:A.string().optional(),mode:A.enum(["full","head_tail"]).optional(),tail:A.string().optional(),text:A.string().optional()}).strict(),cI=A.object({quote:A.string().optional(),sentence_id:A.string().optional()}).strict(),dI=A.union([A.object({end_anchor:A.union([A.string(),zf]).optional(),quote:A.string().optional(),sentence_id:A.string().optional(),start_anchor:A.union([A.string(),zf]).optional()}).strict(),A.array(cI)]),uI=A.object({confidence:A.number().min(0).max(1).optional(),evidence:dI,predicate:A.string().min(1).max(64),sourceMentionId:A.string().min(1),targetMentionId:A.string().min(1)}).strict(),Z6=A.object({relations:A.array(uI)}).strict(),eZ=new ft});var Qf=i(()=>{"use strict"});var Vf=i(()=>{"use strict";Xf();Qf()});var Yf=i(()=>{"use strict";Vf();_i();Js()});var Qs=i(()=>{"use strict";$();Ks()});var ry=i(()=>{"use strict";yt();Ke();$s();Uf();Ks();$f();Kf();Xs();Yf();Qs()});var iy=i(()=>{"use strict"});var ay=i(()=>{"use strict";$s();Bf();ry();zs();Xs();Qs();iy()});var oy=i(()=>{"use strict";ay()});var dr=i(()=>{"use strict";$()});var Vs=i(()=>{"use strict";Ke()});var Ys=i(()=>{"use strict";Re();Ke();Mt();dr();Vs()});var dy=i(()=>{"use strict";Ke();dr();Ys()});var Zs=i(()=>{"use strict";se()});var uy=i(()=>{"use strict";se();hn();at();Zs()});var ly=i(()=>{"use strict";Mt();se();dr();uy();Zs()});import{z as wt}from"zod";var my,N5,py=i(()=>{"use strict";my=wt.object({children:wt.lazy(()=>wt.array(my)),uri:wt.string().min(1),title:wt.string().nullable().optional()}).strict(),N5=wt.object({chapters:wt.array(my)}).strict()});var hy=i(()=>{"use strict";$()});var fy=i(()=>{"use strict";dy();dr();Ys();ly();Vs();py();hy()});var yy=i(()=>{"use strict";Cn()});var ze=i(()=>{"use strict";Gh();Pt();yf();jf();oy();Pt();Ns();fy();yy();Ar()});async function by(e="global"){let t=await tc(),n=Ne(),r=Date.now(),a=!1;try{await t.transaction(async()=>{await ek(t),await t.run(`
755
+ `,[t],Fn),o=await Promise.all(a.map(Hr)),s=n.dryRun?{freedBytes:0,removed:0,scanned:0}:await Uy(await Ly()),d=0;for(let c of o)d+=await un(c.workspace),d+=await un(c.cache),d+=await un(c.log),d+=await un(c.events),n.dryRun||(await Oy(c.jobId),await e.run("DELETE FROM build_jobs WHERE job_id = ?",[c.jobId]));return{freedBytes:d+s.freedBytes,removed:o.length+s.removed,scanned:(r??0)+s.scanned}}finally{await e.close()}}var qy=i(()=>{"use strict";nc();jr();St();Mn()});var Jy=i(()=>{"use strict";Vd();ec();jy();By();Ur();qy()});var _a=i(()=>{"use strict"});import{z as p}from"zod";var Ky,V,lv,mv,zy,pv,hv,fv,yv,gv,bv,Sv,wv,kv,xv,Iv,Ev,Rv,vv,XZ,wt=i(()=>{"use strict";y();ve();_a();Ky=1,V=p.number().int().nonnegative(),lv=p.literal(Ky),mv=p.string().regex(/^Q[1-9][0-9]*$/u),zy=p.number().min(0).max(1).optional(),pv=p.object({text:p.string(),wordsCount:V}).strict(),hv=p.object({type:p.literal("meta"),schemaVersion:lv,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),fv=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),yv=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(pv)}).strict(),gv=p.object({type:p.literal("reading-chunk"),id:p.string().min(1),generation:p.number().int(),sentenceIndex:V,label:p.string(),content:p.string(),sentenceIndexes:p.array(V).min(1),retention:p.enum(he).optional(),importance:p.enum(Re).optional(),wordsCount:V,weight:p.number()}).strict(),bv=p.object({type:p.literal("reading-edge"),fromChunkId:p.string().min(1),toChunkId:p.string().min(1),strength:p.string().optional(),weight:p.number()}).strict(),Sv=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),wv=p.object({type:p.literal("snake"),id:p.string().min(1),groupId:V,localSnakeId:V,size:V,firstLabel:p.string(),lastLabel:p.string(),wordsCount:V,weight:p.number()}).strict(),kv=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),xv=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),Iv=p.object({type:p.literal("summary"),text:p.string()}).strict(),Ev=p.object({type:p.literal("mention"),id:p.string().min(1),fragmentId:V.optional(),sentenceIndex:V.optional(),rangeStart:V,rangeEnd:V,surface:p.string().min(1),qid:mv,confidence:zy,note:p.string().optional()}).strict(),Rv=p.object({type:p.literal("mention-link"),id:p.string().min(1),sourceMentionId:p.string().min(1),targetMentionId:p.string().min(1),predicate:p.string().min(1),evidenceSentenceIndexes:p.array(V).min(1),confidence:zy,note:p.string().optional()}).strict(),vv=p.object({type:p.literal("end")}).strict(),XZ=p.discriminatedUnion("type",[hv,fv,yv,gv,bv,Sv,wv,kv,xv,Iv,Ev,Rv,vv])});var Qy=i(()=>{"use strict"});var Xy=i(()=>{"use strict"});import{sha256 as n6}from"@noble/hashes/sha2.js";var t6,r6,fc=i(()=>{"use strict";t6=new RegExp("\\p{Script=Han}+","gu"),r6=new RegExp("^\\p{Script=Han}+$","u")});var yc=i(()=>{"use strict";fc()});import{z as l}from"zod";function Vy(){return l.object({content:l.string(),generation:l.number().int(),id:l.string(),importance:l.enum(["critical","helpful","important"]).optional(),label:l.string(),retention:l.enum(["detailed","focused","relevant","verbatim"]).optional(),sentenceIndex:P,sentenceIndexes:l.array(P),type:l.literal("reading-chunk"),weight:l.number(),wordsCount:P})}function Yy(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function Zy(){return l.object({endSentenceIndex:P,groupId:P,startSentenceIndex:P,type:l.literal("fragment-group")})}function eg(){return l.object({firstLabel:l.string(),groupId:P,id:l.string(),lastLabel:l.string(),localSnakeId:P,size:P,type:l.literal("snake"),weight:l.number(),wordsCount:P})}function ng(){return l.object({chunkId:l.string(),position:P,snakeId:l.string(),type:l.literal("snake-chunk")})}function tg(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function rg(){return l.object({confidence:l.number().optional(),fragmentId:P.optional(),id:l.string(),note:l.string().optional(),qid:l.string(),rangeEnd:P,rangeStart:P,sentenceIndex:P.optional(),surface:l.string(),type:l.literal("mention")})}function Cv(){return l.object({confidence:l.number().optional(),evidenceSentenceIndexes:l.array(P),id:l.string(),note:l.string().optional(),predicate:l.string(),sourceMentionId:l.string(),targetMentionId:l.string(),type:l.literal("mention-link")})}var P,gc,c6,u6,Gn=i(()=>{"use strict";P=l.number().int().nonnegative(),gc={sentenceIndex:P,text:l.string(),wordsCount:P},c6=l.discriminatedUnion("type",[l.object({extractionPrompt:l.string().optional(),language:l.string().optional(),policyPrompt:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...gc,fragmentId:P.optional(),type:l.literal("source-text")}),l.object({fragmentId:P,summary:l.string(),type:l.literal("source-fragment")}),l.object({...gc,fragmentId:P.optional(),type:l.literal("source-sentence")}),l.object({...gc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),Vy(),Yy(),Zy(),eg(),ng(),tg(),rg()]),u6=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),Vy(),Yy(),Zy(),eg(),ng(),tg(),rg(),Cv(),l.object({position:P,text:l.string(),type:l.literal("summary-part")}),l.object({metadata:l.record(l.string(),l.unknown()),objectId:l.string(),objectKind:l.string(),rowId:l.string(),sentenceIndex:P.optional(),text:l.string(),tokens:l.array(l.string()),type:l.literal("lexical-row")}),l.object({dimensions:P,identity:l.string().optional(),model:l.string(),source:l.enum(["source","summary"]),type:l.literal("embedding-metadata"),version:l.literal(1)}),l.object({endSentenceIndex:P,segmentIndex:P,startSentenceIndex:P,text:l.string(),type:l.literal("embedding-segment"),vector:l.array(l.number()),wordsCount:P})])});var bc=i(()=>{"use strict";Gn()});var Sc=i(()=>{"use strict"});var jn,wc=i(()=>{"use strict";jn=["Classify the raw assistant reply into exactly one label.","Labels:","- malformed_json: the reply is trying to provide JSON, but it is broken or truncated","- natural_language: the reply is plain conversational language, apology, refusal, or explanation instead of JSON","- ambiguous: unclear or mixed","Reply with the label only."].join(`
756
+ `)});import{jsonrepair as g6}from"jsonrepair";var ig=i(()=>{"use strict"});var ag=i(()=>{"use strict";wc();Sc();ig()});var le=i(()=>{"use strict";Sc();wc();ag()});var dg=i(()=>{"use strict"});var $r=i(()=>{"use strict"});import{z as Je}from"zod";var Av,Lv,q6,xc=i(()=>{"use strict";le();$r();Av=Je.object({candidateId:Je.string().min(1),decision:Je.enum(["continue","recall","skip_this_time","never_recall"]),qid:Je.string().nullable().optional()}).strict(),Lv=Je.object({decisions:Je.array(Av),groupId:Je.string().min(1)}).strict(),q6=Je.object({groups:Je.array(Lv)}).strict()});import{z as Jr}from"zod";var Nv,V6,ug=i(()=>{"use strict";le();$r();xc();Nv=Jr.object({decision:Jr.enum(["keep","reject"]),qid:Jr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),V6=Jr.object({qids:Jr.array(Nv)}).strict()});var Ic=i(()=>{"use strict"});import{z as Kr}from"zod";var Dv,t9,lg=i(()=>{"use strict";le();Dv=Kr.object({note:Kr.string().max(24).optional(),surfaceId:Kr.string().min(1)}).strict(),t9=Kr.object({protectedSurfaces:Kr.array(Dv)}).strict()});var mg=i(()=>{"use strict";Ic()});var pg=i(()=>{"use strict"});var Ec=i(()=>{"use strict"});var hg=i(()=>{"use strict";Ec();$r()});var zr=i(()=>{"use strict";dg();ug();$r();xc();Ic();lg();mg();pg();hg();Ec()});var Aa=i(()=>{"use strict"});var fg=i(()=>{"use strict";zr();Aa()});var yg=i(()=>{"use strict";zr()});var Rc=i(()=>{"use strict"});var gg=i(()=>{"use strict";zr();Aa();yg();Rc()});function La(n){let e=n.trim();return e===""?[]:Array.from(Mv.segment(e)).map(t=>t.segment.trim()).filter(t=>t!=="")}function xe(n){let e=n.replace(/\s+/gu," ").trim(),t=Gv(e),r="";for(let a of t)if(!jv(a)){if(!Qr(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function Gv(n){let e=[],t=0;for(;t<n.length;){let r=n[t];if(r===void 0)break;if(r!==" "){e.push(r),t+=1;continue}if(e.length>=2&&Fv.has(e[e.length-1]??"")&&Qr(e[e.length-2]??"")&&t<n.length-1&&Qr(n[t+1]??"")){e.pop(),t+=1;continue}let a=e[e.length-1]??"",o=n[t+1]??"";a!==""&&o!==""&&Qr(a)&&Qr(o)&&e.push(r),t+=1}return e}function Qr(n){return n!==""&&new RegExp("\\p{Script=Latin}","u").test(n)&&new RegExp("\\p{L}","u").test(n)}function jv(n){return/[\p{P}\p{S}]/u.test(n)}var Fv,Mv,Xr=i(()=>{"use strict";Fv=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),Mv=new Intl.Segmenter(void 0,{granularity:"sentence"})});function Cc(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Sg(n,e){let t=Oa(n,2),r=Oa(e,2),a=Oa(n,3),o=Oa(e,3);return(bg(t,r)+bg(a,o))/2}function Oa(n,e){if(n.length<=e)return n===""?new Set:new Set([n]);let t=new Set;for(let r=0;r<=n.length-e;r+=1)t.add(n.slice(r,r+e));return t}function bg(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&(t+=1);return 2*t/(n.size+e.size)}function wg(n,e){if(n===e)return 1;if(n===""||e==="")return 0;let t=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...n].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(t[d+1]??0)+1,b=(t[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[t,r]=[r,t]}return 1-(t[e.length]??Math.max(n.length,e.length))/Math.max(n.length,e.length)}function kg(n,e){return 1-Math.abs(n.length-e.length)/Math.max(n.length,e.length)}function xg(n,e){if(n===e)return 1;let t=n.length,r=e.length;if(t===0||r===0)return 0;let a=Array.from({length:t+1},()=>new Array(r+1).fill(0)),o=0;for(let s=1;s<=t;s+=1)for(let d=1;d<=r;d+=1){if(n[s-1]!==e[d-1])continue;let c=a[s];c!==void 0&&(c[d]=(a[s-1]?.[d-1]??0)+1,o=Math.max(o,c[d]??0))}return 2*o/(t+r)}function Ig(n){return` - ${n.occurrenceId} score=${n.score.toFixed(3)}
757
+ prev: ${vc(n.prevText)}
758
+ text: ${vc(n.text,120)}
759
+ next: ${vc(n.nextText)}`}function vc(n,e=80){let t=n.replace(/\s+/gu," ").trim();return t===""?"(none)":t.length<=e?t:`${t.slice(0,e-3)}...`}var Tc=i(()=>{"use strict"});var _c=i(()=>{"use strict"});function Rg(n,e,t){return n.mode==="head_tail"?qv(n,e):Pc(n.text??"",e,t)}function qv(n,e){let t=n.head??"",r=n.tail??"",a=xe(e),o=xe(t),s=xe(r);if(o===""||s==="")return Cc();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let R=o.length+s.length,f=Math.min(1,R/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=Pc(t,e,"start_anchor"),m=Pc(r,e,"end_anchor"),b=u.matchStart<=m.matchStart?1:.85;return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:Math.max(u.matchEnd,m.matchEnd),matchStart:Math.min(u.matchStart,m.matchStart),score:(u.score+m.score)/2*b}}function Pc(n,e,t){let r=n.trim(),a=e.trim(),o=xe(r),s=xe(a);if(o===""||s==="")return Cc();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=Eg({candidateNormalized:s,label:t,matchEnd:f+o.length,matchStart:f,queryNormalized:o});return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:f+o.length,matchStart:f,score:Math.min(1,.75+.25*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),R=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),A=new Set([...R,...C]).size,K=[...R].filter(ie=>C.has(ie)).length;if((A===0?0:K/A)<.35)continue;let G=.35*Sg(o,g)+.35*xg(o,g)+.2*wg(o,g)+.1*kg(o,g)+Eg({candidateNormalized:s,label:t,matchEnd:k+f,matchStart:k,queryNormalized:o});G>d&&(d=Math.min(1,G),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function Eg(n){if(n.matchStart<0||n.matchEnd<0||n.queryNormalized.length<12||n.label==="start_anchor"&&n.matchStart!==0||n.label==="end_anchor"&&n.matchEnd!==n.candidateNormalized.length)return 0;let e=n.queryNormalized.length/Math.max(1,n.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var vg=i(()=>{"use strict";Xr();Tc();_c()});function Cg(n){if(n==null)return[void 0,"anchor is required"];if(typeof n=="string"){let o=n.trim();if(o==="")return[void 0,"anchor string is empty"];if(o.includes("...")){let s=o.split("...").map(d=>d.trim()).filter(d=>d!=="");if(s.length>=2){let d=s[0],c=s[s.length-1];return d===void 0||c===void 0?[void 0,"anchor string is empty"]:[{head:d,mode:"head_tail",tail:c},void 0]}}return[{mode:"full",text:o},void 0]}if(typeof n!="object")return[void 0,`expected string or object, got ${typeof n}`];let e=n;if((e.mode==="head_tail"||e.head!==void 0?"head_tail":"full")==="full"){let o=typeof e.text=="string"?e.text.trim():"";return o===""?[void 0,"full anchor requires non-empty 'text'"]:[{mode:"full",text:o},void 0]}let r=typeof e.head=="string"?e.head.trim():"",a=typeof e.tail=="string"?e.tail.trim():"";return r!==""&&a===""?[{mode:"full",text:r},void 0]:r===""&&a!==""?[{mode:"full",text:a},void 0]:r===""||a===""?[void 0,"head_tail anchor requires non-empty 'head' and 'tail'"]:[{head:r,mode:"head_tail",tail:a},void 0]}function Tg(n,e){if(n===void 0)return;if(n.mode==="head_tail"){let r=e==="end_anchor"?Ac(n.tail??"","end_anchor"):Ac(n.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:Ac(n.text??"",e)}}function Lc(n){return n.mode==="head_tail"?xe(n.head??"").length+xe(n.tail??"").length:xe(n.text??"").length}function Ac(n,e){let t=La(n);return t.length<=1?n.trim():e==="end_anchor"?t[t.length-1]??n.trim():t[0]??n.trim()}var _g=i(()=>{"use strict";Xr()});var kt,Og=i(()=>{"use strict";vg();_g();Tc();_c();kt=class{resolve(e,t,r){let a=e.start_anchor??e.start,o=e.end_anchor??e.end,[s,d]=this.parseAnchor(a,"start_anchor");if(d!==void 0)return[void 0,d];let c;if(o!==void 0){let[g,C]=this.parseAnchor(o,"end_anchor");if(C!==void 0)return[void 0,C];c=g}let[u,m,b]=this.resolveAnchor({anchor:s,candidateSentenceIds:t,candidateTexts:r,label:"start_anchor"});if(b!==void 0)return[void 0,b];if(u===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(c===void 0)return[{confidence:u.score,sentenceIds:[u.sentenceId],strategy:m},void 0];let[R,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:t,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:R===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:R.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${R.occurrenceId}).`}]:[{confidence:Math.min(u.score,R.score),sentenceIds:t.slice(u.index,R.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let t=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(t,"start_anchor");if(o!==void 0)return[void 0,o];let s=e.overrides.start_anchor,[d,c,u]=s===void 0?this.resolveAnchor({anchor:a,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"start_anchor"}):[s,"choice_final",void 0];if(u!==void 0)return[void 0,u];if(d===void 0)return[void 0,{candidates:[],code:"none",fieldName:"start_anchor",message:"start_anchor could not be matched: no candidate selected"}];if(r===void 0)return[{confidence:d.score,sentenceIds:[d.sentenceId],strategy:c},void 0];let[m,b]=this.parseAnchor(r,"end_anchor");if(b!==void 0)return[void 0,b];let R=e.overrides.end_anchor,[f,k,g]=R===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[R,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,t){let[r,a]=Cg(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:t,message:`Invalid evidence.${t}: ${a}`}]:[Tg(r,t),void 0]}resolveAnchor(e){if(e.anchor===void 0)return[void 0,"invalid",{candidates:[],code:"invalid",fieldName:e.label,message:`${e.label} is missing`}];let t=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(t=t.filter(m=>m.index>=r)),t.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=t.filter(m=>m.exactRaw);if(a.length===1)return[a[0],"exact_raw",void 0];if(a.length>1)return[void 0,"ambiguous_exact_raw",this.#n(e.label,"ambiguous_exact_raw",a)];let o=t.filter(m=>m.exactSubstring);if(o.length===1&&Lc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&Lc(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#n(e.label,"ambiguous_exact_substring",o)]}let s=t.filter(m=>m.exactNormalized);if(s.length===1)return[s[0],"exact_normalized",void 0];if(s.length>1){let m=this.#e(s);return m!==void 0?[m,"exact_normalized_scored",void 0]:[void 0,"ambiguous_exact_normalized",this.#n(e.label,"ambiguous_exact_normalized",s)]}let d=t[0];if(d===void 0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let c=t[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:t.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:t.length===1?[d,"auto_top1_single_candidate",void 0]:d.score>=.97?[d,"auto_top1_very_high",void 0]:d.score>=.9&&u>=.07?[d,"auto_top1",void 0]:[void 0,"ambiguous_ranked",this.#n(e.label,"ambiguous_ranked",t)]}rankAnchor(e,t,r,a){let o=[];for(let[s,d]of t.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=Rg(e,c,a);o.push({exactNormalized:b.exactNormalized,exactRaw:b.exactRaw,exactSubstring:b.exactSubstring,index:s,nextText:m,occurrenceId:`S${s+1}`,prevText:u,score:b.score,sentenceId:d,text:c})}return o.sort((s,d)=>s.score!==d.score?d.score-s.score:s.exactRaw!==d.exactRaw?s.exactRaw?-1:1:s.exactSubstring!==d.exactSubstring?s.exactSubstring?-1:1:s.exactNormalized!==d.exactNormalized?s.exactNormalized?-1:1:s.index-d.index),o}#e(e){if(e.length===0)return;if(e.length===1)return e[0];let t=e[0];if(t===void 0)return;let r=e[1]?.score??0;if(t.score>=.9&&t.score-r>=.07)return t}#n(e,t,r){let a=r.slice(0,3),o=a.map(s=>Ig(s)).join(`
760
+ `);return{candidates:a,code:t,fieldName:e,message:`${e} is ambiguous. Top candidates:
761
+ ${o}
762
+ Please provide a more specific anchor or surrounding context.`}}}});var Ng=i(()=>{"use strict"});var Dg=i(()=>{"use strict";Og();Ng()});var Oc,Wg=i(()=>{"use strict";Oc=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
763
+ `)});var Nc=i(()=>{"use strict"});var Fg=i(()=>{"use strict";Nc();Xr()});var Na=i(()=>{"use strict";Dg();Wg();Nc();Fg();Xr()});var Gg=i(()=>{"use strict"});import{z as W}from"zod";var jg,Kv,zv,Qv,A7,L7,Bg=i(()=>{"use strict";le();Na();Gg();jg=W.object({head:W.string().optional(),mode:W.enum(["full","head_tail"]).optional(),tail:W.string().optional(),text:W.string().optional()}).strict(),Kv=W.object({quote:W.string().optional(),sentence_id:W.string().optional()}).strict(),zv=W.union([W.object({end_anchor:W.union([W.string(),jg]).optional(),quote:W.string().optional(),sentence_id:W.string().optional(),start_anchor:W.union([W.string(),jg]).optional()}).strict(),W.array(Kv)]),Qv=W.object({confidence:W.number().min(0).max(1).optional(),evidence:zv,predicate:W.string().min(1).max(64),sourceMentionId:W.string().min(1),targetMentionId:W.string().min(1)}).strict(),A7=W.object({relations:W.array(Qv)}).strict(),L7=new kt});var Ug=i(()=>{"use strict"});var qg=i(()=>{"use strict"});var Hg=i(()=>{"use strict";Bg();Ug();qg()});var $g=i(()=>{"use strict";Hg();Aa();Rc()});var Vr,xt=i(()=>{"use strict";Vr=Object.freeze({guaranteedResponseIntent:"guaranteed-response-intent",knowledgeGraph:"knowledge-graph",readingGraphEvidenceChoice:"reading-graph-evidence-choice",readingGraphExtraction:"reading-graph-extraction",readingSummaryCompress:"reading-summary-compress",readingSummaryReview:"reading-summary-review",readingSummaryReviewGuide:"reading-summary-review-guide"})});var oee,Wc=i(()=>{"use strict";le();Gn();fg();gg();$g();zr();xt();oee=["Recall only source mentions that should become stable searchable knowledge graph objects.","Prefer named entities: historical persons, places, organizations, dynasties, political entities, named works, named events, battles, titles, and explicitly named domain concepts.","Recall a non-named common concept only when it is a central recurring topic of the chapter and would be useful as an entity search result across multiple evidence passages.","Do not recall a surface merely because it is useful for summarizing the story or explaining a detail.","Do not recall pure numbers, standalone dates without a named event role, units of measurement, dimensions, ordinal labels, chapter numbers, punctuation fragments, common function words, generic verbs, generic adjectives, generic roles, generic objects, or incidental attributes.","Measurements, quantities, dimensions, tactical details, and descriptive attributes should remain evidence text, not entity mentions.","When uncertain, skip the mention rather than creating a noisy knowledge graph object."].join(" ")});var Jg=i(()=>{"use strict"});var Kg=i(()=>{"use strict"});var zg=i(()=>{"use strict";Jg();Kg()});var Un=i(()=>{"use strict"});var Yr=i(()=>{"use strict";le()});var Xg=i(()=>{"use strict";Un();Yr()});var Vg=i(()=>{"use strict";Yr()});var Yg=i(()=>{"use strict"});import{z as I}from"zod";var Zg,Zv,eb,eC,nC,tC,rC,iC,aC,Da=i(()=>{"use strict";Un();Zg=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),Zv=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),eb=I.union([I.record(I.string(),I.unknown()),I.array(Zv)]),eC=I.object({content:I.string(),evidence:eb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),nC=I.object({chunks:I.array(eC),fragment_summary:I.string(),links:I.array(Zg)}),tC=I.object({content:I.string(),evidence:eb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),rC=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),iC=I.object({chunks:I.array(tC),importance_annotations:I.array(rC),links:I.array(Zg)}),aC=I.object({choice:I.string()})});var nb=i(()=>{"use strict";le();Na();Yg();Yr();Da()});var tb=i(()=>{"use strict";le();Un();Xg();Yr();Vg();nb();Da()});var rb=i(()=>{"use strict";tb();Da()});var Mc=i(()=>{"use strict"});import{detect as sne,validateISO2 as dne}from"tinyld";var ib=i(()=>{"use strict"});var ab=i(()=>{"use strict"});import{z as Zr}from"zod";var dC,Cne,ob=i(()=>{"use strict";le();Na();rb();Mc();Mc();ib();ab();dC=Zr.object({content:Zr.string(),id:Zr.number(),label:Zr.string()}),Cne=Zr.array(dC)});var sb=i(()=>{"use strict";ob()});var db=i(()=>{"use strict";zg();sb()});var cb=i(()=>{"use strict";db()});var ub=i(()=>{"use strict"});var lb=i(()=>{"use strict"});var Gc=i(()=>{"use strict";ub();le();xt();lb()});var mb=i(()=>{"use strict"});var pb=i(()=>{"use strict"});var hb=i(()=>{"use strict";mb();pb()});var ei=i(()=>{"use strict"});var lte,mte,It=i(()=>{"use strict";Un();lte={critical:9,helpful:1,important:3},mte={detailed:9,focused:3,relevant:1,verbatim:27}});var Et=i(()=>{"use strict"});var ni=i(()=>{"use strict"});var jc=i(()=>{"use strict";Et()});var Bc=i(()=>{"use strict";It();Et();ei();ni();jc()});var Uc=i(()=>{"use strict";ei();Bc();ni()});var yb=i(()=>{"use strict";It();Et();ni()});var gb=i(()=>{"use strict";It();Et();ei();ni();jc()});var bb=i(()=>{"use strict";Uc();Et();ei();yb();Bc();gb()});var Sb=i(()=>{"use strict";bb();Uc()});var wb=i(()=>{"use strict";It()});var kb=i(()=>{"use strict";Sb();wb()});var xb=i(()=>{"use strict";hb();kb();It()});var qc=i(()=>{"use strict";Gn();xt();cb();Gc();xb()});var Ib=i(()=>{"use strict"});var Fa=i(()=>{"use strict"});var Eb=i(()=>{"use strict";Fa()});var Ma=i(()=>{"use strict"});var jre,vb=i(()=>{"use strict";Fa();Ma();jre=Object.freeze({critical:9,major:3,minor:1})});import{detect as qre,validateISO2 as Hre}from"tinyld";var Cb=i(()=>{"use strict";Ma()});var Tb=i(()=>{"use strict"});var _b=i(()=>{"use strict";Un()});var Hc=i(()=>{"use strict";_b()});var Pb=i(()=>{"use strict"});import{z as Rt}from"zod";var bC,SC,die,Ab=i(()=>{"use strict";le();Fa();Hc();Ma();bC=["critical","major","minor"],SC=Rt.object({problem:Rt.string(),severity:Rt.enum(bC),suggestion:Rt.string().default("")}),die=Rt.object({issues:Rt.array(SC)})});var Lb=i(()=>{"use strict";Ib();Eb();vb();Cb();Tb();Hc();Pb();Ab()});var $c=i(()=>{"use strict";Gn();xt();Un();Gc();Lb()});var Ob=i(()=>{"use strict";yc();Gn();bc();Wc();qc();$c()});import{z as M}from"zod";var vt,wC,kC,xC,IC,Zie,Nb=i(()=>{"use strict";vt=M.number().finite().nonnegative(),wC=M.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),kC=M.enum(["candidate","char","item","page","qid","record","sentence","window"]),xC=M.object({cacheReadTokens:vt.optional(),inputTokens:vt.optional(),outputTokens:vt.optional()}),IC=M.object({done:vt,force:M.boolean().optional(),phase:wC,phaseDetail:M.string().optional(),total:vt,unit:kC}),Zie=M.discriminatedUnion("event",[M.object({characters:vt,event:M.literal("output-characters")}),M.object({event:M.literal("token-usage"),usage:xC}),M.object({event:M.literal("progress"),progress:IC}),M.object({event:M.literal("artifact"),record:M.unknown()}),M.object({event:M.literal("complete"),revision:M.number().int().nonnegative()}),M.object({event:M.literal("error"),message:M.string()})])});var Db=i(()=>{"use strict"});var Wb=i(()=>{"use strict"});var ti=i(()=>{"use strict";Qy();Xy();Ob();bc();yc();Gn();Wc();qc();$c();xt();Nb();Db();Wb();fc()});var Fb=i(()=>{"use strict";ti();vr()});import{z as T}from"zod";var EC,RC,Iae,Eae,Rae,Mb=i(()=>{"use strict";y();EC="wikg-index-output/v1",RC=T.enum(["fts","embedding-source","embedding-summary"]),Iae=T.object({artifactKind:RC,chapterId:T.number().int().nonnegative(),embedding:T.object({dimensions:T.number().int().nonnegative(),identity:T.string().optional(),model:T.string()}).optional(),inputRevision:T.number().int().nonnegative(),protocol:T.literal(EC),type:T.literal("manifest")}),Eae=T.object({metadata:T.record(T.string(),T.unknown()).optional(),objectId:T.string().min(1),objectKind:T.string().min(1),rowId:T.string().min(1),sentenceIndex:T.number().int().nonnegative().optional(),text:T.string(),tokens:T.array(T.string()),type:T.literal("lexical-row")}),Rae=T.object({endSentenceIndex:T.number().int().nonnegative(),segmentIndex:T.number().int().nonnegative(),startSentenceIndex:T.number().int().nonnegative(),text:T.string(),vector:T.array(T.number()),wordsCount:T.number().int().nonnegative(),type:T.literal("segment")})});var qn=i(()=>{"use strict";Fb();Mb()});var Gb=i(()=>{"use strict";De();dn()});var jb=i(()=>{"use strict";_();ga()});var Ub=i(()=>{"use strict";y();_();Y();gt();wt();qn();Gb();jb()});var Ga=i(()=>{"use strict"});var qb=i(()=>{"use strict";Ga()});var Hb=i(()=>{"use strict"});var $b=i(()=>{"use strict";Ga()});var Jb=i(()=>{"use strict";Ga()});var Kb=i(()=>{"use strict";qb();Hb();$b();Jb()});import{z as h}from"zod";var zb,FC,MC,GC,jC,BC,UC,qC,HC,$C,JC,Qb=i(()=>{"use strict";ve();zb=h.tuple([h.number(),h.number()]),FC=h.object({text:h.string(),wordsCount:h.number()}),MC=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(FC)}),GC=h.object({documentOrder:h.number().optional(),id:h.number(),knowledgeGraphReady:h.boolean(),knowledgeGraphParameterHash:h.string().optional(),revision:h.number().optional(),topologyParameterHash:h.string().optional(),topologyReady:h.boolean()}).transform(n=>({documentOrder:n.documentOrder??n.id,id:n.id,knowledgeGraphReady:n.knowledgeGraphReady,...n.knowledgeGraphParameterHash===void 0?{}:{knowledgeGraphParameterHash:n.knowledgeGraphParameterHash},revision:n.revision??0,topologyReady:n.topologyReady,...n.topologyParameterHash===void 0?{}:{topologyParameterHash:n.topologyParameterHash}})),jC=h.object({id:h.number(),generation:h.number(),sentenceId:zb,label:h.string(),content:h.string(),sentenceIds:h.array(zb),retention:h.enum(he).optional(),importance:h.enum(Re).optional(),wordsCount:h.number(),weight:h.number()}),BC=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),UC=h.object({id:h.number(),serialId:h.number(),groupId:h.number(),localSnakeId:h.number(),size:h.number(),firstLabel:h.string(),lastLabel:h.string(),wordsCount:h.number(),weight:h.number()}),qC=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),HC=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),$C=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),JC=h.object({chunks:h.array(jC),fragmentGroups:h.array($C),fragments:h.array(MC),readingEdges:h.array(BC),serial:GC,snakeChunks:h.array(qC),snakeEdges:h.array(HC),snakes:h.array(UC)})});var Xb=i(()=>{"use strict";y();Qb()});var Vb=i(()=>{"use strict";Qn();jd();Z()});var Yb=i(()=>{"use strict";y();_();Y();Kb();Xb();_a();Vb();wt();qn()});var Zb=i(()=>{"use strict"});var ja=i(()=>{"use strict";Yb();_a();Zb()});var eS=i(()=>{"use strict";Y();ja()});var nS=i(()=>{"use strict"});var tS=i(()=>{"use strict";Ub();eS();nS()});var rS=i(()=>{"use strict";ti()});var aS=i(()=>{"use strict";ti();_();Y();qn();ja()});var oS=i(()=>{"use strict";ti();sn();Qn()});var sS=i(()=>{"use strict";tS();ja();rS();aS();oS()});import{z as $}from"zod";var Gse,zC,jse,Qc=i(()=>{"use strict";y();Gse=$.object({id:$.string().min(1),chapterId:$.number().int(),sentenceIndex:$.number().int().nonnegative().optional(),rangeStart:$.number().int().nonnegative(),rangeEnd:$.number().int().nonnegative(),surface:$.string().min(1),qid:$.string().regex(/^Q[1-9][0-9]*$/),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()}),zC=$.tuple([$.number().int().nonnegative(),$.number().int().nonnegative()]).readonly(),jse=$.object({id:$.string().min(1),sourceMentionId:$.string().min(1),targetMentionId:$.string().min(1),predicate:$.string().min(1),evidenceSentenceIds:$.array(zC).min(1),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()})});var Xc=i(()=>{"use strict";y();De();wt();Qc()});var cS=i(()=>{"use strict";wt();qn();Qc()});var Ba=i(()=>{"use strict"});var uS=i(()=>{"use strict";sn();Ba()});var Vc=i(()=>{"use strict"});var lS=i(()=>{"use strict";sn()});var Yc=i(()=>{"use strict"});var Zc=i(()=>{"use strict";sn();Ba();lS();Yc()});var pS=i(()=>{"use strict";Zc()});var hS=i(()=>{"use strict";De()});var fS=i(()=>{"use strict";Dd();lt();ya()});import{z as F}from"zod";var yS,YC,ZC,eT,Pde,Ade,gS=i(()=>{"use strict";Ae();lt();fS();yS=F.object({head:F.string().optional(),mode:F.enum(["full","head_tail"]).optional(),tail:F.string().optional(),text:F.string().optional()}).strict(),YC=F.object({quote:F.string().optional(),sentence_id:F.string().optional()}).strict(),ZC=F.union([F.object({end_anchor:F.union([F.string(),yS]).optional(),quote:F.string().optional(),sentence_id:F.string().optional(),start_anchor:F.union([F.string(),yS]).optional()}).strict(),F.array(YC)]),eT=F.object({confidence:F.number().min(0).max(1).optional(),evidence:ZC,predicate:F.string().min(1).max(64),sourceMentionId:F.string().min(1),targetMentionId:F.string().min(1)}).strict(),Pde=F.object({relations:F.array(eT)}).strict(),Ade=new Nn});var bS=i(()=>{"use strict"});var SS=i(()=>{"use strict";gS();bS()});var wS=i(()=>{"use strict";SS();Ba();Yc()});var eu=i(()=>{"use strict";Y();Vc()});var IS=i(()=>{"use strict";sn();dn();Xc();uS();Vc();pS();hS();wS();eu()});var ES=i(()=>{"use strict"});var RS=i(()=>{"use strict";Xc();cS();IS();Zc();eu();ES()});var vS=i(()=>{"use strict";RS()});var ri=i(()=>{"use strict";Y()});var nu=i(()=>{"use strict";dn()});var tu=i(()=>{"use strict";De();dn();gt();ri();nu()});var _S=i(()=>{"use strict";dn();ri();tu()});var ru=i(()=>{"use strict";ye();Z()});var AS=i(()=>{"use strict";ye();Xt();xn();ru();Z()});var LS=i(()=>{"use strict";gt();ye();ri();AS();ru();Z()});import{z as Hn}from"zod";var OS,mue,NS=i(()=>{"use strict";OS=Hn.object({children:Hn.lazy(()=>Hn.array(OS)),uri:Hn.string().min(1),title:Hn.string().nullable().optional()}).strict(),mue=Hn.object({chapters:Hn.array(OS)}).strict()});var DS=i(()=>{"use strict";Y()});var WS=i(()=>{"use strict";_S();ri();tu();LS();nu();NS();DS()});var FS=i(()=>{"use strict";mr()});var Ke=i(()=>{"use strict";Ay();dt();Jy();sS();vS();dt();Qd();WS();FS();Wi()});async function gw(n="global"){let e=await lu(),t=Qe(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await b_(e),await e.run(`
779
764
  INSERT OR IGNORE INTO gc_locks (
780
765
  scope, owner_id, owner_pid, heartbeat_at, created_at
781
766
  ) VALUES (?, ?, ?, ?, ?)
782
- `,[e,n,0,r,r]),a=await t.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[e],s=>S(s,"owner_id"))===n})}finally{await t.close()}if(!a)return;let o=setInterval(()=>{ZI(e,n).catch(()=>{})},YI);return async()=>{clearInterval(o);let s=await tc();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[e,n])}finally{await s.close()}}}async function ZI(e,t){let n=await tc();try{await n.run(`
767
+ `,[n,t,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[n],s=>E(s,"owner_id"))===t})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{g_(n,t).catch(()=>{})},y_);return async()=>{clearInterval(o);let s=await lu();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[n,t])}finally{await s.close()}}}async function g_(n,e){let t=await lu();try{await t.run(`
783
768
  UPDATE gc_locks
784
769
  SET heartbeat_at = ?, owner_pid = ?
785
770
  WHERE scope = ? AND owner_id = ?
786
- `,[Date.now(),0,e,t])}finally{await n.close()}}async function ek(e){let t=await e.queryAll("SELECT * FROM gc_locks",void 0,rk);for(let{lock:n,scope:r}of t.filter(({lock:a})=>tk(a)))await e.run(`
771
+ `,[Date.now(),0,n,e])}finally{await t.close()}}async function b_(n){let e=await n.queryAll("SELECT * FROM gc_locks",void 0,k_);for(let{lock:t,scope:r}of e.filter(({lock:a})=>S_(a)))await n.run(`
787
772
  DELETE FROM gc_locks
788
773
  WHERE scope = ?
789
774
  AND owner_id = ?
790
775
  AND heartbeat_at = ?
791
- `,[r,n.ownerId,n.heartbeatAt])}function tk(e){return!(Date.now()-e.heartbeatAt<VI)}async function tc(){return await B("tmp/gc.sqlite",QI)}function nk(e){return{createdAt:h(e,"created_at"),heartbeatAt:h(e,"heartbeat_at"),ownerId:S(e,"owner_id"),ownerPid:h(e,"owner_pid")}}function rk(e){return{lock:nk(e),scope:S(e,"scope")}}var QI,VI,YI,Sy=i(()=>{"use strict";O();y();k();QI=`
776
+ `,[r,t.ownerId,t.heartbeatAt])}function S_(n){return!(Date.now()-n.heartbeatAt<f_)}async function lu(){return await X("tmp/gc.sqlite",h_)}function w_(n){return{createdAt:S(n,"created_at"),heartbeatAt:S(n,"heartbeat_at"),ownerId:E(n,"owner_id"),ownerPid:S(n,"owner_pid")}}function k_(n){return{lock:w_(n),scope:E(n,"scope")}}var h_,f_,y_,bw=i(()=>{"use strict";U();w();_();h_=`
792
777
  CREATE TABLE IF NOT EXISTS gc_locks (
793
778
  scope TEXT PRIMARY KEY,
794
779
  owner_id TEXT NOT NULL,
@@ -796,8 +781,8 @@ CREATE TABLE IF NOT EXISTS gc_locks (
796
781
  heartbeat_at INTEGER NOT NULL,
797
782
  created_at INTEGER NOT NULL
798
783
  );
799
- `,VI=6e4,YI=2e4});async function wy(e){let t=await I().library.getDirectory("tmp"),n=0,r=0,a=0;if(t===void 0)return{freedBytes:a,removed:r,scanned:n};for(let o of await ak(t)){n+=1;let s=await Le(o.value);if(!e.force&&(s===void 0||e.now-s<ik))continue;let c=await Je(o.value);e.dryRun||await o.parent.remove(o.value.name,{recursive:!0}),r+=1,a+=c}return{freedBytes:a,removed:r,scanned:n}}async function ak(e){let t=[];for(let n of await e.list())if(G(n))for(let r of await n.list())t.push({parent:n,value:r});return t}var ik,Ey=i(()=>{"use strict";p();js();ik=3600*1e3});async function rc(e={}){let t=Date.now(),n=await by();if(n===void 0)return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:t};try{if(e.opportunistic===!0&&!await dk(t))return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:t};let r={dryRun:e.dryRun===!0,force:e.force===!0,now:t},a=[];for(let s of ok)a.push(await ck(s,r));let o={finishedAt:Date.now(),freedBytes:nc(a,"freedBytes"),jobs:a,removed:nc(a,"removed"),scanned:nc(a,"scanned"),skipped:!1,startedAt:t};return await uk(o.finishedAt).catch(()=>{}),o}finally{await n()}}async function ck(e,t){try{return{name:e.name,...await e.run(t)}}catch(n){return{error:Ye(n),freedBytes:0,name:e.name,removed:0,scanned:0}}}function nc(e,t){return e.reduce((n,r)=>{let a=r[t];return n+(typeof a=="number"?a:0)},0)}async function dk(e){let t=await K(I().library,"tmp/gc.last-run"),n=Number((t===void 0?"":await Q(t).catch(()=>"")).trim());return!Number.isFinite(n)||e-n>=sk}async function uk(e){let t=await j(I().library,"tmp/gc.last-run");await V(t,`${e}
800
- `)}var ok,sk,xy=i(()=>{"use strict";p();Pt();ze();Ce();jn();ci();ee();Sy();Ey();ok=[{name:"wikg-coordinator",run:si},{name:"search-cache",run:Or},{name:"library-index",run:lp},{name:"wikipage-cache",run:Eo},{name:"build-queue",run:ki},{name:"tmp",run:wy}],sk=600*1e3});var Iy=i(()=>{"use strict";xy()});var ky={};Ty(ky,{tryRunWikiGraphGc:()=>rc});var Ry=i(()=>{"use strict";Iy()});p();$t();import*as dc from"async_hooks";import*as uc from"crypto";import*as lr from"fs";import*as T from"fs/promises";import*as lc from"os";import*as _ from"path";import*as Fi from"process";import{Writable as Ly}from"stream";import{pipeline as Oy}from"stream/promises";import*as Mi from"sqlite3";import*as mc from"yauzl";import*as pc from"yazl";import{Environment as Ny,Loader as Dy}from"nunjucks";var Oi=Fi.default??Fi,Jt=Mi.default??Mi,Oe=class{constructor(t,n=_.basename(t)){this.path=t;this.identity=hc("file",t),this.name=n}path;identity;name;async read(t){return await T.readFile(this.path,t?.encoding===void 0?void 0:{encoding:t.encoding})}async getSize(){try{return(await T.stat(this.path)).size}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return 0;throw t}}async getLastModified(){try{return(await T.stat(this.path)).mtimeMs}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return;throw t}}async openWriter(){await T.mkdir(_.dirname(this.path),{recursive:!0});let t=`${this.path}.tmp-${uc.randomUUID()}`,n=await T.open(t,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");typeof a=="string"?await n.write(a):await n.write(Buffer.from(a))},commit:async()=>{r||(await n.close(),await T.rename(t,this.path)),r=!0},abort:async()=>{r||(await n.close(),await T.rm(t,{force:!0})),r=!0}}}},Et=class e{constructor(t){this.path=t;this.identity=hc("directory",t),this.name=_.basename(t)}path;identity;name;async getFile(t){Kt(t);let n=new Oe(_.join(this.path,t));try{return(await T.stat(n.path)).isFile()?n:void 0}catch{return}}async getLastModified(){try{return(await T.stat(this.path)).mtimeMs}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return;throw t}}async getDirectory(t){Kt(t);let n=new e(_.join(this.path,t));try{return(await T.stat(n.path)).isDirectory()?n:void 0}catch{return}}async list(){return(await T.readdir(this.path,{withFileTypes:!0})).map(n=>n.isDirectory()?new e(_.join(this.path,n.name)):new Oe(_.join(this.path,n.name),n.name))}async createFile(t){Kt(t),await T.mkdir(this.path,{recursive:!0});let n=new Oe(_.join(this.path,t));return await T.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(t){Kt(t),await T.mkdir(this.path,{recursive:!0});let n=new e(_.join(this.path,t));return await T.mkdir(n.path),n}async remove(t,n){Kt(t),await T.rm(_.join(this.path,t),{force:!0,recursive:n?.recursive===!0})}};function hc(e,t){return`node-${e}:${Buffer.from(_.resolve(t),"utf8").toString("base64url")}`}function Li(e,t){let n=`node-${t}:`;if(!e.startsWith(n))return _.isAbsolute(e)?e:void 0;try{return Buffer.from(e.slice(n.length),"base64url").toString("utf8")}catch{return}}function Kt(e){if(e.length===0||e==="."||e===".."||_.isAbsolute(e)||e.includes("/")||e.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${e}`)}var Ni=class{constructor(t){this.database=t}database;async close(){await new Promise((t,n)=>{this.database.close(r=>{r?n(r):t()})})}async execute(t){await new Promise((n,r)=>{this.database.exec(t,a=>{a?r(a):n()})})}async queryAll(t,n=[]){return await new Promise((r,a)=>{this.database.all(t,[...n],(o,s)=>{o?a(o):r(s)})})}async queryOne(t,n=[]){return await new Promise((r,a)=>{this.database.get(t,[...n],(o,s)=>{o?a(o):r(s)})})}async run(t,n=[]){await new Promise((r,a)=>{this.database.run(t,[...n],o=>{o?a(o):r()})})}};async function Fy(e,t={}){let n=(t.readonly===!0?Jt.OPEN_READONLY:Jt.OPEN_READWRITE|Jt.OPEN_CREATE)|Jt.OPEN_FULLMUTEX;return new Ni(await My(e,n))}async function My(e,t){if(!(e instanceof Oe))throw new TypeError("The Node database adapter requires a NodeFile");return await new Promise((n,r)=>{let a=new Jt.Database(e.path,t,o=>{o?r(o):n(a)})})}async function Wy(e){if(!(e instanceof Oe))throw new TypeError("The Node ZIP adapter requires a NodeFile");let t=await new Promise((a,o)=>{mc.open(e.path,{autoClose:!1,lazyEntries:!0},(s,c)=>{s||c===void 0?o(s??new Error("Cannot open ZIP")):a(c)})}),n=await new Promise((a,o)=>{let s=new Map,c=u=>{t.close(),o(u instanceof Error?u:new Error("Cannot scan ZIP central directory"))},d=()=>{t.off("error",c),a(s)};t.on("entry",u=>{u.fileName.endsWith("/")||s.set(u.fileName,u),t.readEntry()}),t.once("error",c),t.once("end",d),t.readEntry()}),r=!1;return{close:()=>(r||t.close(),r=!0,Promise.resolve()),listEntries:()=>Promise.resolve([...n.keys()]),readEntry:async a=>{if(r)throw new Error("Cannot read a closed ZIP archive");let o=n.get(a);if(o!==void 0)return await jy(t,o)}}}async function jy(e,t){let n=await new Promise((r,a)=>{e.openReadStream(t,(o,s)=>{o||s===void 0?a(o??new Error(`Cannot read ZIP entry: ${t.fileName}`)):r(s)})});return await $y(n)}async function Gy(e,t){let n=new pc.ZipFile,r=await e.openWriter(),a=n.outputStream,o=qy(a,r),s={cancelled:!1,complete:!1},c;try{c=Uy(t);let d=By(n,c,s);if(await Promise.race([d,o]),!s.complete)throw new Error("ZIP output ended before entry production completed");n.end(),await o,await r.commit()}catch(d){throw s.cancelled=!0,!s.complete&&c!==void 0&&Hy(c),a.destroyed||a.destroy(d instanceof Error?d:new Error("Cannot write ZIP archive")),await o.catch(()=>{}),await r.abort().catch(()=>{}),d}}async function By(e,t,n){for(;!n.cancelled;){let r=await t.next();if(n.cancelled)return;if(r.done){n.complete=!0;return}e.addBuffer(Buffer.from(r.value.data),r.value.name,{compress:!1})}}function Uy(e){let t=e[Symbol.asyncIterator];return t===void 0?e[Symbol.iterator]():t.call(e)}function Hy(e){if(e.return!==void 0)try{Promise.resolve(e.return()).catch(()=>{})}catch{}}async function qy(e,t){await Oy(e,new Ly({write:(n,r,a)=>{t.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function $y(e){return await new Promise((t,n)=>{let r=[];e.on("data",a=>r.push(a)),e.once("error",n),e.once("end",()=>t(Buffer.concat(r)))})}var Ky={asyncContext:{create:()=>new dc.AsyncLocalStorage},database:{open:Fy},lifecycle:{instanceId:`node-process:${Oi.pid}`,isInstanceAlive:e=>{let t=/^node-process:(\d+)$/u.exec(e);if(t===null)return Promise.resolve(void 0);try{return Oi.kill(Number(t[1]),0),Promise.resolve(!0)}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ESRCH"?Promise.resolve(!1):Promise.resolve(!0)}}},resources:{getDirectory:e=>{let t=Li(e,"directory");return Promise.resolve(t===void 0?void 0:new Et(t))},getFile:e=>{let t=Li(e,"file");return Promise.resolve(t===void 0?void 0:new Oe(t))},resolveLegacyDirectory:e=>{let t=Li(e,"directory");return Promise.resolve(t===void 0?void 0:new Et(t))}},templates:{createEnvironment:e=>new Ny(new Di,e)},zip:{open:Wy,write:Gy}},Di=class extends Dy{getSource(t){let n=cc(t),r=_.join(Jy(),n);return{noCache:!1,path:n,src:lr.readFileSync(r,"utf8")}}};function Jy(){let e=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof e=="string"&&e!=="")return e;let t=Oi.cwd();for(;;){for(let r of[_.join(t,"data"),_.join(t,"packages","core","data")])try{if(lr.statSync(r).isDirectory())return r}catch{}let n=_.dirname(t);if(n===t)throw new Error("Could not locate data directory");t=n}}function fc(e=_.join(lc.homedir(),".wikigraph")){return{library:new Et(e),documentStore:new Et(_.join(e,"documents"))}}function yc(e){Ci(Ky),Ai(fc(e))}async function gc(e,t){return await Pi(e===void 0?void 0:fc(e),t)}var zy=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function Sc(e){let t=Xy(e.env);if(e.envPolicy==="production"){let o=zy.filter(s=>t[s]!==void 0);if(o.length>0)throw new Error(`Wiki Graph production entries do not support runtime env overrides: ${o.join(", ")}. Use the development entry or explicit SDK options instead.`);return{env:t,envPolicy:e.envPolicy,stateDir:e.stateDir}}let n=t.WIKIGRAPH_DEV??t.WIKIGRAPH_STATE_DIR,r=bc(e.stateDir??n);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=bc(e.devProjectRoot);if(a===void 0)throw new Error("Wiki Graph development entries require an explicit project root.");return{devProjectRoot:a,env:t,envPolicy:e.envPolicy,stateDir:r}}function Xy(e){return e===void 0?{...process.env}:{...process.env,...e}}function bc(e){if(!(e===void 0||e.trim()===""))return e}var wc="--wikigraph-internal-child",Ec="--wikigraph-state-dir";async function xc(e,t){let n=Qy(process.argv.slice(2));if(n.internalChild!==e)throw new Error("This Wiki Graph worker entry is internal.");let r=Sc({argv:n.argv,envPolicy:"production",stateDir:n.stateDir});return await gc(r.stateDir,()=>t(n))}function Qy(e){let t=[],n,r;for(let a=0;a<e.length;a+=1){let o=e[a];if(o===wc){if(a+1>=e.length)throw new Error(`${wc} requires a value.`);n=e[a+1],a+=1;continue}if(o!==Ec){t.push(o);continue}if(a+1>=e.length)throw new Error(`${Ec} requires a value.`);r=e[a+1],a+=1}return{argv:t,internalChild:n??"",stateDir:r}}Re();p();mr();import{z as Xt}from"zod";var tg=1,Bk=Xt.object({completedAt:Xt.string().optional(),startedAt:Xt.string(),status:Xt.enum(["running","succeeded"]),version:Xt.literal(tg)});Ui();Yt();ye();qi();$t();ci();Lt();jn();yt();bs();ze();se();Ce();k();at();Pt();k();hn();xr();wr();Ut();p();nt();Te();Be();Ge();es();wr();ci();qn();Ut();k();p();Ce();p();y();y();p();y();p();_a();p();ee();ze();ze();ze();ze();ze();Ke();yt();k();Bt();p();var $I={command:`${"wg"} --help`,config:`${"wg"} help config`,format:`${"wg"} help format`,readiness:`${"wg"} help readiness`,root:`${"wg"} --help`,runtime:`${"wg"} help runtime`,uri:`${"wg"} help uri`};import{extname as $7}from"path";import{createReadStream as nee}from"fs";import{mkdtemp as iee,rm as aee}from"fs/promises";import{join as see}from"path";import{tmpdir as dee}from"os";import{AsyncLocalStorage as KI}from"async_hooks";var X7=new KI;var JI=new Map(["at","seq","uri","id","jobId","type","target","label","labels","title","state","name","qid","predicate","subjectLabel","objectLabel","subjectQid","objectQid","score","queueRank","chapter","chapterId","fragment","fragmentId","position","range","start","end","shown","total","count","mentionCount","nodeCount","edgeCount","summaryCount","limit","order","match","lens","terms","types","chapters","query","objects","items","nextCursor","archiveKey","archivePath","workspacePath","eventsPath","createdAt","updatedAt","finishedAt","currentStep","step","phase","phaseDetail","phaseDone","phaseTotal","phaseUnit","words","totalWords","outputTokens","authors","language","identifier","publisher","publishedAt","sourceFormat","snippet","summary","description","recommendation","risk","error","message","children","nodes","links","neighbors","incoming","outgoing","nodeGroups","sourceFragments","sources","tree","meta","evidence","content","source","text","prompt","llmJSON","errorJSON"].map((e,t)=>[e,t]));function gy(e){return`${JSON.stringify(ec(e),null,2)}
801
- `}function ec(e){if(e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>ec(t)??null);if(typeof e=="object")return zI(e)}function zI(e){let t=Object.entries(e).map(([r,a],o)=>({index:o,key:r,priority:JI.get(r)??Number.MAX_SAFE_INTEGER,value:a})),n={};for(let r of t.sort((a,o)=>a.priority-o.priority||a.index-o.index)){let a=ec(r.value);a!==void 0&&(n[r.key]=a)}return n}import{homedir as bee}from"os";import{isAbsolute as wee,relative as Eee,resolve as xee}from"path";import{existsSync as _ee,readFileSync as Tee}from"fs";import{dirname as Aee,join as Pee,parse as Lee,resolve as Oee}from"path";yc();var{tryRunWikiGraphGc:lk}=await Promise.resolve().then(()=>(Ry(),ky));async function mk(){await xc("gc-worker",async({argv:e})=>{let t=pk(e);process.stdout.write(gy(await lk({dryRun:t.dryRun,force:t.force})))})}function pk(e){return{dryRun:e.includes("--dry-run"),force:e.includes("--force")}}mk().catch(e=>{process.stderr.write(`${e instanceof Error?e.stack??e.message:String(e)}
784
+ `,f_=6e4,y_=2e4});async function Sw(n){let e=await v().library.getDirectory("tmp"),t=0,r=0,a=0;if(e===void 0)return{freedBytes:a,removed:r,scanned:t};for(let o of await I_(e)){t+=1;let s=await ze(o.value);if(!n.force&&(s===void 0||n.now-s<x_))continue;let d=await un(o.value);n.dryRun||await o.parent.remove(o.value.name,{recursive:!0}),r+=1,a+=d}return{freedBytes:a,removed:r,scanned:t}}async function I_(n){let e=[];for(let t of await n.list())if(j(t))for(let r of await t.list())e.push({parent:t,value:r});return e}var x_,ww=i(()=>{"use strict";y();nc();x_=3600*1e3});async function Ha(n={}){let e=Date.now(),t=await gw();if(t===void 0)return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};try{if(n.opportunistic===!0&&!await C_(e))return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};let r={dryRun:n.dryRun===!0,force:n.force===!0,now:e},a=[];for(let s of E_)a.push(await v_(s,r));let o={finishedAt:Date.now(),freedBytes:mu(a,"freedBytes"),jobs:a,removed:mu(a,"removed"),scanned:mu(a,"scanned"),skipped:!1,startedAt:e};return await T_(o.finishedAt).catch(()=>{}),o}finally{await t()}}async function v_(n,e){try{return{name:n.name,...await n.run(e)}}catch(t){return{error:zn(t),freedBytes:0,name:n.name,removed:0,scanned:0}}}function mu(n,e){return n.reduce((t,r)=>{let a=r[e];return t+(typeof a=="number"?a:0)},0)}async function C_(n){let e=await J(v().library,"tmp/gc.last-run"),t=Number((e===void 0?"":await ae(e).catch(()=>"")).trim());return!Number.isFinite(t)||n-t>=R_}async function T_(n){let e=await H(v().library,"tmp/gc.last-run");await me(e,`${n}
785
+ `)}var E_,R_,kw=i(()=>{"use strict";y();dt();Ke();Be();ua();Id();pe();bw();ww();E_=[{name:"wikg-coordinator",run:da},{name:"search-cache",run:Gi},{name:"library-index",run:Hh},{name:"build-queue",run:va},{name:"wikimedia-cache",run:kd},{name:"tmp",run:Sw}],R_=600*1e3});var xw=i(()=>{"use strict";kw()});var Iw=i(()=>{"use strict";xw()});var Ew={};Tw(Ew,{tryRunWikiGraphGc:()=>__});async function __(n={}){At();let{stateDir:e,...t}=n;return await Kn(e,async()=>await Ha(t))}var Rw=i(()=>{"use strict";Iw();ce()});ce();import{AsyncLocalStorage as s_}from"async_hooks";import{randomUUID as Qpe}from"crypto";import{link as Vpe,mkdtemp as Ype,rename as Zpe,rm as ehe,stat as nhe}from"fs/promises";import{tmpdir as rhe}from"os";import{basename as ahe,dirname as ohe,join as she}from"path";import{Readable as che}from"stream";De();y();mi();import{z as Ot}from"zod";var nk=1,oP=Ot.object({completedAt:Ot.string().optional(),startedAt:Ot.string(),status:Ot.enum(["running","succeeded"]),version:Ot.literal(nk)});so();Qn();Xe();Z();uo();Tt();ua();lt();Id();sn();Ld();Ke();ye();Be();_();xn();dt();_();Xt();Ri();ki();qn();y();wn();je();rn();tn();sd();ki();ua();vr();qn();_();y();Be();y();w();w();y();w();y();Ko();y();pe();Ke();Ke();Ke();Ke();Ke();dn();sn();_();wt();y();import{rm as bpe}from"fs/promises";import{createAnthropic as jme}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as Ume}from"@ai-sdk/google";import{createOpenAI as Hme}from"@ai-sdk/openai";import{createOpenAICompatible as Jme}from"@ai-sdk/openai-compatible";ce();import{z as re}from"zod";import{AsyncLocalStorage as $T}from"async_hooks";var rw=Symbol.for("wiki-graph-sdk.runtime-context.v1"),JT=KT();function KT(){let n=globalThis,e=n[rw];if(e!==void 0)return e;let t=new $T;return Object.defineProperty(n,rw,{configurable:!1,enumerable:!1,value:t,writable:!1}),t}async function cu(n,e){return await JT.run(n,e)}ce();import{join as npe}from"path";import{homedir as rpe}from"os";var QT=["anthropic","google","openai","openai-compatible"],iw=re.enum(QT),dpe=re.object({apiKey:re.string().min(1).optional(),baseURL:re.string().min(1).optional(),baseUrl:re.string().min(1).optional(),chatCompletionsUrl:re.string().min(1).optional(),llm:re.object({apiKey:re.string().min(1).optional(),baseURL:re.string().min(1).optional(),baseUrl:re.string().min(1).optional(),chatCompletionsUrl:re.string().min(1).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:iw.optional()}).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:iw.optional()});import{homedir as lpe}from"os";import{isAbsolute as ppe,resolve as hpe}from"path";ce();import{embed as vpe,embedMany as Cpe}from"ai";import{createOpenAI as _pe}from"@ai-sdk/openai";import{createOpenAICompatible as Ape}from"@ai-sdk/openai-compatible";import{spawn as khe}from"child_process";import{streamText as Whe}from"ai";Ke();ce();var a_=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function cw(n){let e=o_(n.env);if(n.envPolicy==="production"){let o=a_.filter(s=>e[s]!==void 0);if(o.length>0)throw new Error(`Wiki Graph production entries do not support runtime env overrides: ${o.join(", ")}. Use the development entry or explicit SDK options instead.`);return{env:e,envPolicy:n.envPolicy,stateDir:n.stateDir}}let t=e.WIKIGRAPH_DEV??e.WIKIGRAPH_STATE_DIR,r=dw(n.stateDir??t);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=dw(n.devProjectRoot);if(a===void 0)throw new Error("Wiki Graph development entries require an explicit project root.");return{devProjectRoot:a,env:e,envPolicy:n.envPolicy,stateDir:r}}function o_(n){return n===void 0?{...process.env}:{...process.env,...n}}function dw(n){if(!(n===void 0||n.trim()===""))return n}ce();ce();import{mkdir as Efe}from"fs/promises";ce();import{basename as Afe}from"path";ce();ce();var d_=new s_;async function uw(n,e){return await d_.run(n,async()=>await cu({cwd:n.cwd,env:n.env,envPolicy:n.envPolicy,...n.stateDir===void 0?{}:{stateDir:n.stateDir}},e))}var lw="--wikigraph-internal-child",mw="--wikigraph-dev-project-root",pw="--wikigraph-env-policy",hw="--wikigraph-state-dir";async function fw(n,e){let t=c_(process.argv.slice(2));if(t.internalChild!==n)throw new Error("This Wiki Graph worker entry is internal.");let r=cw({argv:t.argv,devProjectRoot:t.devProjectRoot,envPolicy:t.envPolicy,stateDir:t.stateDir});return await Kn(r.stateDir,async()=>uw({argv:t.argv,cwd:process.cwd(),devProjectRoot:r.devProjectRoot,env:r.env,envPolicy:r.envPolicy,exitCode:0,queueAutostart:!1,stateDir:r.stateDir,stderr:process.stderr,stdin:process.stdin,stdout:process.stdout},async()=>await e(t)))}function c_(n){let e=[],t,r,a="production",o;for(let s=0;s<n.length;s+=1){let d=n[s];if(d===lw){if(s+1>=n.length)throw new Error(`${lw} requires a value.`);t=n[s+1],s+=1;continue}if(d===pw){let c=n[s+1];if(c!=="development"&&c!=="production")throw new Error(`${pw} requires development or production.`);a=c,s+=1;continue}if(d===mw){let c=n[s+1];if(c===void 0||c.trim()==="")throw new Error(`${mw} requires a value.`);r=c,s+=1;continue}if(d!==hw){e.push(d);continue}if(s+1>=n.length)throw new Error(`${hw} requires a value.`);o=n[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:t??"",stateDir:o}}var u_={command:`${"wg"} --help`,config:`${"wg"} help config`,format:`${"wg"} help format`,readiness:`${"wg"} help readiness`,root:`${"wg"} --help`,runtime:`${"wg"} help runtime`,uri:`${"wg"} help uri`};import{extname as Wye}from"path";import{createReadStream as Hye}from"fs";import{mkdtemp as Jye,rm as Kye}from"fs/promises";import{join as Qye}from"path";import{tmpdir as Vye}from"os";var l_=new Map(["at","seq","uri","id","jobId","type","target","label","labels","title","state","name","qid","predicate","subjectLabel","objectLabel","subjectQid","objectQid","score","queueRank","chapter","chapterId","fragment","fragmentId","position","range","start","end","shown","total","count","mentionCount","nodeCount","edgeCount","summaryCount","limit","order","match","lens","terms","types","chapters","query","objects","items","nextCursor","archiveKey","archivePath","workspacePath","eventsPath","createdAt","updatedAt","finishedAt","currentStep","step","phase","phaseDetail","phaseDone","phaseTotal","phaseUnit","words","totalWords","outputTokens","authors","language","identifier","publisher","publishedAt","sourceFormat","snippet","summary","description","recommendation","risk","error","message","children","nodes","links","neighbors","incoming","outgoing","nodeGroups","sourceFragments","sources","tree","meta","evidence","content","source","text","prompt","llmJSON","errorJSON"].map((n,e)=>[n,e]));function yw(n){return`${JSON.stringify(uu(n),null,2)}
786
+ `}function uu(n){if(n===null||typeof n=="boolean"||typeof n=="number"||typeof n=="string")return n;if(Array.isArray(n))return n.map(e=>uu(e)??null);if(typeof n=="object")return m_(n)}function m_(n){let e=Object.entries(n).map(([r,a],o)=>({index:o,key:r,priority:l_.get(r)??Number.MAX_SAFE_INTEGER,value:a})),t={};for(let r of e.sort((a,o)=>a.priority-o.priority||a.index-o.index)){let a=uu(r.value);a!==void 0&&(t[r.key]=a)}return t}import{homedir as oge}from"os";import{isAbsolute as dge,relative as cge,resolve as uge}from"path";import{existsSync as fge,readFileSync as yge}from"fs";import{dirname as bge,join as Sge,parse as wge,resolve as kge}from"path";At();var{tryRunWikiGraphGc:P_}=await Promise.resolve().then(()=>(Rw(),Ew));async function A_(){await fw("gc-worker",async({argv:n})=>{let e=L_(n);process.stdout.write(yw(await P_({dryRun:e.dryRun,force:e.force})))})}function L_(n){return{dryRun:n.includes("--dry-run"),force:n.includes("--force")}}A_().catch(n=>{process.stderr.write(`${n instanceof Error?n.stack??n.message:String(n)}
802
787
  `),process.exitCode=1});
803
788
  //# sourceMappingURL=gc-worker.js.map