wiki-graph 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/dist/cli.js +2449 -663
- package/dist/cli.js.map +1 -1
- package/dist/data/help/commands/predicate.jinja +35 -2
- package/dist/data/help/commands/uri.jinja +1 -0
- package/dist/data/help/topics/config.jinja +26 -6
- package/dist/data/help/topics/readiness.jinja +3 -2
- package/dist/gc-worker.js +77 -92
- package/dist/gc-worker.js.map +1 -1
- package/dist/index.cjs +1247 -4800
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.js +1233 -4885
- package/dist/index.js.map +1 -1
- package/dist/queue-worker.js +2359 -575
- package/dist/queue-worker.js.map +1 -1
- package/package.json +7 -16
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 Aw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Lw=(t,e)=>{for(var n in e)Aw(t,n,{get:e[n],enumerable:!0})};async function oi(t){let e=await t.openReader();try{return e.size}finally{await e.close()}}async function ht(t){return await oi(t)===0}async function ae(t){return new TextDecoder().decode(await Ht(t))}async function Ht(t){let e=await t.openReader();try{let n=new Uint8Array(e.size);for(let r=0;r<e.size;){let a=await e.read(r,Math.min(65536,e.size-r));n.set(a,r),r+=a.byteLength}return n}finally{await e.close()}}async function me(t,e){let n=await t.openWriter();try{await n.write(e),await n.commit()}catch(r){throw await n.abort().catch(()=>{}),r}}async function Ie(t){if(j(t)){let e=0;for(let n of await t.list())e+=await Ie(n);return e}return await oi(t)}async function Qe(t){return await t.getLastModified?.()}function j(t){return t.kind==="directory"}var pu=i(()=>{"use strict"});function za(t){$t().installedPlatform=t}function A(){let{installedPlatform:t}=$t();if(t===void 0)throw new Error("No WikiGraph runtime platform has been installed. Provide a runtime adapter before using wiki-graph-core.");return t}async function ft(t){if(typeof t!="string")return t;let e=await A().resources.getFile(t);if(e===void 0)throw new Error("Host file is unavailable");return e}async function J(t,e){let n=e.replaceAll("\\","/").split("/").filter(Boolean);if(n.some(o=>o==="."||o===".."))throw new TypeError(`Directory path must remain relative: ${e}`);let r=n.pop();if(!r)return;let a=t;for(let o of n){let s=await a.getDirectory(o);if(!s)return;a=s}return await a.getFile(r)}async function Ne(t,e){let n=Qa(e),r=t;for(let a of n){let o=await r.getDirectory(a);if(!o)return;r=o}return r}async function z(t,e){let n=Qa(e),r=t;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 d=await r.getDirectory(a);if(d===void 0)throw s;r=d}}return r}async function H(t,e){let n=Qa(e),r=n.pop();if(!r)throw new TypeError("File name must remain relative");let a=await z(t,n.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 Qa(t){let e=t.replaceAll("\\","/");if(e.startsWith("/"))throw new TypeError(`Directory path must remain relative: ${t}`);let n=e.split("/").filter(Boolean);if(n.some(r=>r==="."||r===".."))throw new TypeError(`Directory path must remain relative: ${t}`);return n}function $t(){let t=globalThis,e=t[hu];if(e!==void 0)return e;let n={storageContext:new Ka};return Object.defineProperty(t,hu,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function Xa(t){$t().installedStorage=t}async function di(t,e){return t===void 0?await e():await $t().storageContext.run(t,e)}function v(){let{installedStorage:t,storageContext:e}=$t(),n=e.getStore()??t;if(n===void 0)throw new Error("No WikiGraph storage roots have been configured. Pass storage to WikiGraph or install process-default storage.");return n}var hu,Ka,y=i(()=>{"use strict";pu();hu=Symbol.for("wiki-graph-core.runtime.v1");Ka=class{#e;#t;run(e,n){let r=this.#n();if(r!==void 0)return r.run(e,n);let a=this.#t;this.#t=e;try{return n()}finally{this.#t=a}}enterWith(e){let n=this.#n();n!==void 0?n.enterWith(e):this.#t=e}getStore(){return this.#n()?.getStore()??this.#t}#n(){if(this.#e!==void 0)return this.#e;let{installedPlatform:e}=$t();if(e!==void 0)return this.#e=e.asyncContext.create(),this.#t!==void 0&&(this.#e.enterWith(this.#t),this.#t=void 0),this.#e}}});function ci(t){if(Nw.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(Dw,"").replace(Ow,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var Ow,Nw,Dw,_n=i(()=>{"use strict";y();Ow=/\.jinja$/iu,Nw=/^\.+\//u,Dw=/^\/+/u});var yu=i(()=>{"use strict";y();_n()});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 to from"process";import{Readable as xu,Writable as Ww}from"stream";import{pipeline as Fw}from"stream/promises";import*as no from"sqlite3";import*as ku from"yauzl";import*as Iu from"yazl";import{Environment as Mw,Loader as Gw}from"nunjucks";async function gu(t,e,n){let r=Buffer.from(e),a=0;for(;a<r.byteLength;){let o=await t.write(r,a,r.byteLength-a,n===void 0?null:n+a);if(o.bytesWritten===0)throw new Error("File writer made no progress");a+=o.bytesWritten}}function Eu(t,e,n){if(Ru(t),!Number.isSafeInteger(e)||e<0)throw new RangeError("File read length must be a non-negative safe integer");if(t>n||e>n-t)throw new RangeError("File read range exceeds the file size")}function Ru(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function vu(t,e){return`node-${t}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function Va(t,e){let n=`node-${e}:`;if(!t.startsWith(n))return O.isAbsolute(t)?t:void 0;try{return Buffer.from(t.slice(n.length),"base64url").toString("utf8")}catch{return}}function Pn(t){if(t.length===0||t==="."||t===".."||O.isAbsolute(t)||t.includes("/")||t.includes("\\"))throw new TypeError(`Directory child must be a relative name: ${t}`)}async function jw(t,e){let n=(e.mode==="readonly"?An.OPEN_READONLY:An.OPEN_READWRITE|(e.create?An.OPEN_CREATE:0))|An.OPEN_FULLMUTEX;return new Za(await Bw(t,n))}async function Bw(t,e){let n=Cu(t,"file");if(n===void 0)throw new TypeError("The Node database adapter requires a NodeFile");return await new Promise((r,a)=>{let o=new An.Database(n,e,s=>{s?a(s):r(o)})})}async function Uw(t){let e=Cu(t,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let n=await new Promise((o,s)=>{ku.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=>{n.close(),s(m instanceof Error?m:new Error("Cannot scan ZIP central directory"))},u=()=>{n.off("error",c),o(d)};n.on("entry",m=>{m.fileName.endsWith("/")||d.set(m.fileName,m),n.readEntry()}),n.once("error",c),n.once("end",u),n.readEntry()}),a=!1;return{close:()=>(a||n.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 qw(n,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 $w(n,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 Hw(n,s)}}}async function qw(t,e,n){let r=await n.openWriter();try{let a=await ui(t,e);await Tu(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function Hw(t,e){return await _u(await ui(t,e))}async function $w(t,e,n,r){if(Eu(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await Jw(await ui(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await _u(await ui(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function Jw(t,e,n){let r=[],a=e+n,o=0,s=0;for await(let d of t){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!==n)throw new Error("ZIP entry changed while reading its byte range");return Buffer.concat(r,s)}async function ui(t,e,n){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)};n===void 0?t.openReadStream(e,o):t.openReadStream(e,n,o)})}async function Kw(t,e){let n=new Iu.ZipFile,r=await t.openWriter(),a=n.outputStream,o=Tu(a,r),s={cancelled:!1,complete:!1},d;try{d=Vw(e);let c=zw(n,d,s);if(await Promise.race([c,o]),!s.complete)throw new Error("ZIP output ended before entry production completed");n.end(),await o,await r.commit()}catch(c){throw s.cancelled=!0,!s.complete&&d!==void 0&&Yw(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 zw(t,e,n){for(;!n.cancelled;){let r=await e.next();if(n.cancelled)return;if(r.done){n.complete=!0;return}"file"in r.value?t.addReadStream(Qw(r.value.file),r.value.name,{compress:!1}):"data"in r.value?t.addBuffer(Buffer.from(r.value.data),r.value.name,{compress:!1}):t.addReadStream(Xw(r.value),r.value.name,{compress:!1,size:r.value.size})}}function Qw(t){return xu.from((async function*(){let e=await t.openReader();try{for(let n=0;n<e.size;){let r=await e.read(n,Math.min(65536,e.size-n));n+=r.byteLength,yield r}}finally{await e.close()}})())}function Cu(t,e){if(typeof t!="object"||t===null)return;let n=t;return n[ro]===e&&typeof n.path=="string"?n.path:void 0}function Xw(t){return xu.from((async function*(){for(let e=0;e<t.size;){let n=await t.read(e,Math.min(65536,t.size-e));e+=n.byteLength,yield n}})())}function Vw(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function Yw(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function Tu(t,e){await Fw(t,new Ww({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function _u(t){return await new Promise((e,n)=>{let r=[];t.on("data",a=>r.push(a)),t.once("error",n),t.once("end",()=>e(Buffer.concat(r)))})}function ex(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=Ya.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 n=O.dirname(e);if(n===e)throw new Error("Could not locate data directory");e=n}}function Pu(t=O.join(wu.homedir(),".wikigraph")){return{library:new De(t),documentStore:new De(O.join(t,"documents"))}}function Ln(t){za(Zw),Xa(Pu(t))}async function Jt(t,e){return await di(t===void 0?void 0:Pu(t),e)}var Ya,An,ro,oe,De,Za,Zw,eo,ce=i(()=>{"use strict";yu();Ya=to.default??to,An=no.default??no,ro=Symbol.for("wiki-graph-sdk.node-resource.v1"),oe=class{constructor(e,n=O.basename(e)){this.path=e;this.identity=vu("file",e),this.name=n}path;kind="file";[ro]="file";identity;name;async openReader(){let e=await B.open(this.path,"r"),n=!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()=>{n||await e.close(),n=!0},read:async(o,s)=>{if(n)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()}`,n=await B.open(e,"wx"),r=!1;return{write:async a=>{if(r)throw new Error("Cannot write to a closed FileWriter");await gu(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");Ru(a),await gu(n,o,a)},commit:async()=>{r||(await n.close(),await B.rename(e,this.path)),r=!0},abort:async()=>{r||(await n.close(),await B.rm(e,{force:!0})),r=!0}}}};De=class t{constructor(e){this.path=e;this.identity=vu("directory",e),this.name=O.basename(e)}path;kind="directory";[ro]="directory";identity;name;async getFile(e){Pn(e);let n=new oe(O.join(this.path,e));try{return(await B.stat(n.path)).isFile()?n: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){Pn(e);let n=new t(O.join(this.path,e));try{return(await B.stat(n.path)).isDirectory()?n:void 0}catch{return}}async list(){return(await B.readdir(this.path,{withFileTypes:!0})).map(n=>n.isDirectory()?new t(O.join(this.path,n.name)):new oe(O.join(this.path,n.name),n.name))}async createFile(e){Pn(e),await B.mkdir(this.path,{recursive:!0});let n=new oe(O.join(this.path,e));return await B.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){Pn(e),await B.mkdir(this.path,{recursive:!0});let n=new t(O.join(this.path,e));return await B.mkdir(n.path),n}async remove(e,n){Pn(e),await B.rm(O.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};Za=class{constructor(e){this.database=e}database;async close(){await new Promise((e,n)=>{this.database.close(r=>{r?n(r):e()})})}async execute(e){await new Promise((n,r)=>{this.database.exec(e,a=>{a?r(a):n()})})}async queryAll(e,n=[]){return await new Promise((r,a)=>{this.database.all(e,[...n],(o,s)=>{o?a(o):r(s)})})}async queryOne(e,n=[]){return await new Promise((r,a)=>{this.database.get(e,[...n],(o,s)=>{o?a(o):r(s)})})}async run(e,n=[]){await new Promise((r,a)=>{this.database.run(e,[...n],o=>{o?a(o):r()})})}};Zw={asyncContext:{create:()=>new bu.AsyncLocalStorage},database:{open:jw},lifecycle:{instanceId:`node-process:${Ya.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return Ya.kill(Number(e[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:t=>{let e=Va(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))},getFile:t=>{let e=Va(t,"file");return Promise.resolve(e===void 0?void 0:new oe(e))},resolveLegacyDirectory:t=>{let e=Va(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))}},templates:{createEnvironment:t=>new Mw(new eo,t)},zip:{open:Uw,write:Kw}},eo=class extends Gw{#e;constructor(e){super(),this.#e=e}getSource(e){let n=ci(e),r=O.join(this.#e??ex(),n);return{noCache:!1,path:n,src:li.readFileSync(r,"utf8")}}}});var We=i(()=>{"use strict"});function Au(t){return new TextEncoder().encode(t)}function yt(t){let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return e}var Ee=i(()=>{"use strict"});import{sha1 as tx}from"@noble/hashes/legacy.js";import{sha256 as nx,sha512 as rx}from"@noble/hashes/sha2.js";function se(t){let e=ix(t);return{update(n){return e.update(typeof n=="string"?Au(n):n),this},digest(n){let r=e.digest();return n==="hex"?yt(r):r}}}function On(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}function Xe(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let t=On(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=yt(t);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function ix(t){switch(t){case"sha1":return tx.create();case"sha256":return nx.create();case"sha512":return rx.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 Fe(t){return t instanceof Error}function Kt(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){Wu(e,ux(r)),r=r.cause;continue}Wu(e,String(r));break}return e.join(": ")}function ux(t){let e=t,n=t.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&&lx(n)?`${t.name} (${r})`:n===""?t.name:r===void 0?n:`${n} (${r})`}function lx(t){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(t)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(t)||/\bfile:\/\//iu.test(t)}function Wu(t,e){let n=e.trim();if(n==="")return;let r=t.at(-1);if(r===void 0){t.push(n);return}if(!(r===n||r.includes(n))){if(n.includes(r)){t[t.length-1]=n;return}t.push(n)}}var pe=i(()=>{"use strict";y()});var Fu=i(()=>{"use strict";pe()});var Mu=i(()=>{"use strict"});import{APICallError as TP}from"ai";var Gu=i(()=>{"use strict";y()});var Ve=i(()=>{"use strict";y()});var gt,Dn=i(()=>{"use strict";gt=class{#e=0;#t;#n=[];constructor(e){if(!Number.isInteger(e)||e<1)throw new RangeError("concurrency must be a positive integer");this.#t=e}async use(e){await this.#r();try{return await e()}finally{this.#i()}}async#r(){if(this.#e<this.#t){this.#e+=1;return}await new Promise(e=>{this.#n.push(()=>{this.#e+=1,e()})})}#i(){this.#e-=1,this.#n.shift()?.()}}});var ao=i(()=>{"use strict";Ve()});var oo=i(()=>{"use strict"});var ju=i(()=>{"use strict";y()});var so=i(()=>{"use strict"});import{generateText as tA,streamText as nA}from"ai";var Uu=i(()=>{"use strict";Nu();Du();Fu();Mu();Gu();Ve();_n();Dn();mi();pe();ao();oo();ju();so()});var qu=i(()=>{"use strict";Uu()});var uo=i(()=>{"use strict";qu();ao();oo();so()});var fx,lo,Hu,zt=i(()=>{"use strict";fx=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),lo=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,n,r={},a={}){super(n,a),this.name="WikiGraphError",this.code=e,this.details=r}}});var mo=i(()=>{"use strict"});async function gx(t){try{return await ht(t)}catch(e){if(Fe(e)&&e.code==="ENOENT")return!0;throw e}}function S(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function E(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}var yx,N,po,w=i(()=>{"use strict";y();pe();yx=900*1e3;N=class t{#e;#t;#n;#r;#i=!1;#u=Promise.resolve();#d=0;constructor(e,n={}){this.#e=e,this.#t=n.onWrite,this.#n=A().asyncContext.create()}static async open(e,n,r){let a=await ft(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await gx(a),s=r.mode==="readonly"?await A().database.open(a,{mode:"readonly"}):await A().database.open(a,{create:r.create,mode:"readwrite"}),d;try{return d=new t(new po(s),r),await d.#o(`PRAGMA busy_timeout = ${yx}`),r.mode==="readwrite"&&n.trim()!==""&&(await d.#o(n),o&&d.#c()),d}catch(c){throw d===void 0?await s.close().catch(()=>{}):await d.close().catch(()=>{}),c}}static async initialize(e,n){let r=await t.open(e,"",{create:!0,mode:"readwrite"});try{n.trim()!==""&&await r.#o(n)}finally{await r.close()}}async queryAll(e,n,r){return await this.#a(async()=>(this.#s(),(await this.#m(e,n)).map(r)))}async queryOne(e,n,r){return await this.#a(async()=>{this.#s();let a=await this.#p(e,n);return a===void 0?void 0:r(a)})}async run(e,n){await this.#a(async()=>{this.#s(),await this.#h(e,n),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 n=this.#d===0,r=this.#r??Symbol("database transaction scope");n&&(await this.#o("BEGIN IMMEDIATE"),this.#r=r),this.#d+=1;try{let a=await this.#n.run(r,e);return n&&await this.#o("COMMIT"),a}catch(a){throw n&&await this.#o("ROLLBACK"),a}finally{this.#d-=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 e=await this.queryOne("SELECT last_insert_rowid() AS row_id",void 0,n=>S(n,"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 n=this.#n.getStore();if(n!==void 0&&n===this.#r)return await e();let r=this.#u.then(e);return this.#u=r.then(()=>{},()=>{}),await r}#c(){this.#t?.()}async#l(){await this.#e.close()}async#o(e){await this.#e.execute(e)}async#m(e,n){return await this.#e.queryAll(e,n)}async#p(e,n){return await this.#e.queryOne(e,n)}async#h(e,n){await this.#e.run(e,n)}};po=class{#e;constructor(e){this.#e=e}async close(){await this.#e.close()}async execute(e){await this.#e.execute(e)}async queryAll(e,n){return[...await this.#e.queryAll(e,n)]}async queryOne(e,n){return await this.#e.queryOne(e,n)}async run(e,n){await this.#e.run(e,n)}}});async function bt(){let t=v().library,e=hi.get(t.identity);if(e!==void 0){await e;return}let n=Sx(t);hi.set(t.identity,n);try{await n}finally{hi.get(t.identity)===n&&hi.delete(t.identity)}}async function Si(){let t=await J(v().library,"core.sqlite");if(t===void 0||await wi(t))return 0;let e=await N.open(t,"",{mode:"readonly"});try{return await Qt(e,"schema_versions")?await e.queryOne("SELECT version FROM schema_versions WHERE scope = ?",["home"],n=>S(n,"version"))??1:1}finally{await e.close()}}async function Sx(t){let e=await Si();if(e>ho)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let n=await H(t,"core.sqlite");if(e===0){await fi(n,ho);return}for(;e<ho;)switch(e){case 1:await $u(t),await fi(n,2),e=2;break;case 2:await $u(t),await fi(n,3),e=3;break;case 3:await wx(n),await fi(n,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function $u(t){await Xu(t),await Qu(t)}async function wx(t){let e=v().library;await Xu(e),await xx(t),await Qu(e)}async function xx(t){let e=await N.open(t,"",{create:!1,mode:"readwrite"});try{if(!await Qt(e,"libraries"))return;let n=await gi(e,"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 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=A().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()=>{n.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(t,e){let n=await N.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute(bx),await n.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",
|
|
10
|
+
updated_at = excluded.updated_at`,["home",e,new Date().toISOString()])}finally{await n.close()}}async function Qu(t){await Wn(await t.getDirectory("cache"),["search-sessions.sqlite","continuation-cursors.sqlite","cache.sqlite"]);let e=await t.getDirectory("staging");await Wn(e,["library","work"]),await yi(e,"staging.sqlite");let n=await t.getDirectory("tmp");await yi(n,"gc.sqlite"),await yi(n,"wikg-coordinator.sqlite"),await Wn(n,["gc.last-run"]);let r=await t.getDirectory("jobs");await Wn(r,["cache","work"]),await yi(r,"job.sqlite");let a=v().documentStore,o;try{o=await a.list()}catch(s){if(Fe(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(t,e){await Wn(t,[e,`${e}-wal`,`${e}-shm`])}async function Wn(t,e){if(t===void 0)return;let n=new Map((await t.list()).map(r=>[r.name,r]));for(let r of e){let a=n.get(r);a!==void 0&&await t.remove(r,{recursive:j(a)})}}async function Xu(t){await Ku(await J(t,"core.sqlite"),[["library_locks","Cannot upgrade home with active library locks."],["state_locks","Cannot upgrade home with active state locks."]]),await Ku(await J(t,"tmp/gc.sqlite"),[["gc_locks","Cannot upgrade home with an active GC lock."]]),await kx(await J(t,"jobs/job.sqlite")),await Ju(await J(t,"staging/staging.sqlite"),"legacy coordinator"),await Ju(await J(t,"tmp/wikg-coordinator.sqlite"),"coordinator")}async function kx(t){if(t===void 0||await wi(t))return;let e=await N.open(t,"",{mode:"readonly"});try{if(await Qt(e,"build_worker_lease")){let n=await gi(e,"build_worker_lease"),a=["owner_id","owner_pid"].filter(s=>n.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()-
|
|
15
|
-
FROM archive_owners`,void 0,o=>({heartbeatAt:
|
|
14
|
+
LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Fn("Cannot upgrade home with an active build worker.")}}finally{await e.close()}}async function Ju(t,e){if(t===void 0||await wi(t))return;let n=await N.open(t,"",{mode:"readonly"});try{if(await Qt(n,"archive_owners")){let r=await gi(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: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 Fn(`Cannot upgrade home with active ${e} state.`);continue}let s=await A().lifecycle.isInstanceAlive(o.hostInstanceId);if(s===!0||s===void 0&&zu(o.heartbeatAt))throw Fn(`Cannot upgrade home with active ${e} state.`)}}for(let r of["entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await Qt(n,r)||!(await gi(n,r)).has("heartbeat_at"))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Fn(`Cannot upgrade home with active ${e} state.`)}}finally{await n.close()}}async function Ku(t,e){if(t===void 0||await wi(t))return;let n=await N.open(t,"",{mode:"readonly"});try{for(let[r,a]of e){if(!await Qt(n,r))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-bi],()=>!0)===!0)throw Fn(a)}}finally{await n.close()}}function Fn(t){return new Q("home_upgrade_blocked",t)}function zu(t){return t!==void 0&&Date.now()-t<=bi}async function wi(t){return await ht(t)}async function gi(t,e){return new Set(await t.queryAll(`PRAGMA table_info(${e})`,void 0,n=>E(n,"name")))}async function Qt(t,e){return await t.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var ho,bi,bx,hi,xi=i(()=>{"use strict";y();pe();Z();w();ho=4,bi=300*1e3,bx=`
|
|
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
|
-
`,
|
|
22
|
-
`,
|
|
21
|
+
`,hi=new Map});async function X(t,e,n={create:!0,mode:"readwrite"}){await bt();let r=await H(v().library,t);return n.mode==="readonly"?await Mn(r,e,n):await Mn(r,e,n)}async function Mn(t,e,n={create:!0,mode:"readwrite"}){let r=await ft(t);return n.mode==="readonly"?await N.open(r,e,n):await N.open(r,e,n)}var Vu=i(()=>{"use strict";y();xi();w()});function Ii(...t){let e=[];for(let n of t)for(let r of n.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 fo(t){return Ii(t).split("/").at(-1)??""}var St=i(()=>{"use strict"});var Gn=i(()=>{"use strict";St()});var Yu=i(()=>{"use strict"});function Xt(t){let e=new Set(Object.values(t));return n=>e.has(n)}function jn(t,e){let n=Xt(t);return r=>{if(n(r))return r;throw new Error(`Unknown ${e}: ${r}`)}}var yo=i(()=>{"use strict"});var he,Zu,go,Re,el,Ei,ve=i(()=>{"use strict";yo();he=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(he||{}),Zu=Xt(he),go=jn(he,"chunk retention"),Re=(r=>(r.Critical="critical",r.Important="important",r.Helpful="helpful",r))(Re||{}),el=Xt(Re),Ei=jn(Re,"chunk importance")});var bo=i(()=>{"use strict";ve()});function Ye(t){let e=0,n=!1;for(let r of t.trim()){if(Ix.test(r)){e+=1,n=!1;continue}if(Ex.test(r)){n||(e+=1),n=!0;continue}n&&Rx.test(r)||(n=!1)}return e}var Ix,Ex,Rx,Ze=i(()=>{"use strict";Ix=new RegExp("\\p{Script=Han}","u"),Ex=/[\p{Letter}\p{Number}]/u,Rx=new RegExp("\\p{Mark}","u")});var nl=i(()=>{"use strict";Ze();ve()});var Ri=i(()=>{"use strict"});var wo=i(()=>{"use strict";Gn();ve();bo();nl();Ri()});var rl=i(()=>{"use strict";Gn();Yu();wo()});var xo=i(()=>{"use strict";rl();bo();wo();Ri()});var vi=i(()=>{"use strict";y();St()});var ko=i(()=>{"use strict"});var al=i(()=>{"use strict";St();vi()});var ol=i(()=>{"use strict";Ze()});var Io=i(()=>{"use strict"});var Eo=i(()=>{"use strict";St();pe();ko();vi();al();ol();Io()});var sl=i(()=>{"use strict";St();vi();Eo()});var Ro=i(()=>{"use strict";sl();ko();Eo();Io()});import{z as fe}from"zod";var dl,et,cl,ul,Bn=i(()=>{"use strict";dl=["epub","pdf","txt","markdown"],et=1,cl=fe.enum(dl),ul=fe.object({version:fe.literal(et),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(t,e="chapter key"){if(t===""||t==="."||t===".."||t.includes("/"))throw new Error(`Invalid ${e}: chapter paths do not support empty, '.', '..', or relative segments.`);if(!/^[a-z0-9][a-z0-9-]*$/u.test(t))throw new Error(`Invalid ${e}: ${t}. Use lowercase letters, numbers, and hyphens.`);if(/^\d+$/u.test(t))throw new Error(`Invalid ${e}: numeric chapter keys are not accepted.`);if(Ox.has(t))throw new Error(`Invalid ${e}: ${t} is reserved.`);return t}var Ox,ye=i(()=>{"use strict";Ee();U();Ox=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as Me}from"zod";var tt,vo,ml,Co=i(()=>{"use strict";ye();tt=1,vo=Me.object({key:Me.string().min(1).transform(t=>ll(t)).optional(),title:Me.string().min(1).nullable().optional(),serialId:Me.number().int().nonnegative().optional(),children:Me.lazy(()=>Me.array(vo))}),ml=Me.object({version:Me.literal(tt),items:Me.array(vo)})});function Ce(t){let e=[];for(let n of t.replaceAll("\\","/").trim().split("/"))n===""||n==="."||(n===".."?e.pop():e.push(n));return e.join("/")}function Nx(t){let[e]=t.split("#",1);return Ce(e??"")}function To(t){if(t===void 0)return;let e=t.startsWith("#")?t.slice(1):t;return e===""?void 0:e}function Un(t){let[e,n]=t.split("#",2);return{path:Ce(e??""),fragment:To(n)}}function Dx(t){return t.split("/").slice(0,-1).join("/")}function Wx(...t){return t.filter(Boolean).join("/")}var Ci,qn=i(()=>{"use strict";y();U();Ci=class t{#e;#t;#n;#r;constructor(e,n,r,a){this.#e=e,this.#n=n,this.#t=r,this.#r=a}static async open(e){let n=await e.openReader(),r=se("sha256");try{for(let s=0;s<n.size;){let d=await n.read(s,Math.min(65536,n.size-s));r.update(d),s+=d.byteLength}}finally{await n.close()}let a=r.digest("hex"),o=await A().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 t(e,o,s,a)}catch(s){throw await o.close(),s}}close(){return this.#n.close()}hasEntry(e){return this.#t.has(Ce(e))}listEntries(){return[...this.#t.keys()]}async readText(e){return new TextDecoder().decode(await this.readBuffer(e))}async readBuffer(e){let n=this.#i(e),r=await this.#n.readEntry(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${Ce(e)}`);return r}resolveRelativePath(e,n){let r=Nx(n);if(r==="")throw new Error(`Invalid EPUB href: ${n}`);return Ce(Wx(Dx(Ce(e)),r))}createSectionId(e,n){let r=Ce(e);return n===void 0||n===""?r:`${r}#${n}`}createSyntheticSectionId(e,n){let r=Ce(e);return`toc:${se("sha1").update(`${r}:${n??""}`).digest("hex").slice(0,10)}`}get name(){return this.#e.name}get digest(){return this.#r}#i(e){let n=Ce(e),r=this.#t.get(n);if(r===void 0)throw new Error(`EPUB entry does not exist: ${n}`);return r}}});import{parseDocument as Fx}from"htmlparser2";async function bl(t,e){let n=new Map;for(let[r,a]of e.entries()){let o=await Sl(t,r),s=wl(o,a);for(let d of a){let c=s.get(d.id)??"";n.set(d.id,{hasContent:c.trim()!=="",wordsCount:Ye(c)})}}return n}function jx(t){let e=new Map;for(let[n,r]of t.entries())for(let a of r)e.set(a.id,{path:n,targets:r});return e}async function Sl(t,e){return await t.readText(e)}function wl(t,e){let n=xl(t,e,!1);return new Map([...n.entries()].map(([r,a])=>[e[r].id,a.text]))}function Bx(t,e,n){let r=xl(t,e,!0),a=e.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 xl(t,e,n){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=Fx(t,{decodeEntities:!0}),u=(c.children??[]).find(fl);if(u===void 0){if(n)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 L=qx(C);return[g,{segments:L.segments,text:L.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],pt=ie?.spineIndex;if(n&&pt===void 0)throw new Error(`EPUB section ${ie?.id??"unknown"} cannot produce a CFI locator.`);let ai=n&&pt!==void 0?gl(pt,C,0,G.length):_o;f(d,G,ai,n?0:void 0,n?G.length:void 0);return}let L=Jx(g);if(L===void 0){b(g,C);return}if(Gx.has(L))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)}L==="br"&&x(d,`
|
|
22
|
+
`,K),b(g,K),Mx.has(L)&&x(d,`
|
|
23
23
|
|
|
24
|
-
`,
|
|
25
|
-
`?(
|
|
26
|
-
`,locator:
|
|
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 L=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 pt=L*2+1,ai=K.get(pt)??0;K.set(pt,ai+ie.length);let Pw=yl(C,pt,!0);R(q,Pw,ai,ie.length);continue}if(!fl(q))continue;let G=yl(C,L,!1,q.attribs?.id??q.attribs?.["xml:id"]);L+=1,m(q,G)}}function R(g,C,L,K){if(d<0||d>=o.length)return;let q=g.data??"",G=o[d],ie=G?.spineIndex;if(n&&ie===void 0)throw new Error(`EPUB section ${G?.id??"unknown"} cannot produce a CFI locator.`);f(d,q,n&&ie!==void 0?gl(ie,C,L,L+K):_o,n?L:void 0,n?L+K:void 0)}function f(g,C,L,K,q){let G=a.get(g);G!==void 0&&G.push({locator:L,...q===void 0?{}:{locatorEnd:q},...K===void 0?{}:{locatorStart:K},text:C})}function x(g,C,L){if(g<0||g>=o.length)return;let K=o[g],q=K?.spineIndex;if(n&&q===void 0)throw new Error(`EPUB section ${K?.id??"unknown"} cannot produce a CFI locator.`);f(g,C,n&&q!==void 0?zx(q,L):_o)}}function Ux(t,e){let n=[],r=0;for(let a of t){let o=r;r+=Array.from(a.text).length,o!==r&&n.push({artifactDigest:e,locator:a.locator,sourceEnd:r,sourceStart:o})}return n}function qx(t){let e=[];for(let c of t){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 x=c.locatorEnd===void 0||c.locatorStart===void 0?void 0:c.locatorStart+m;R==="\r"&&u[b+1]===`
|
|
25
|
+
`?(m+=1,x=c.locatorStart===void 0?void 0:c.locatorStart+m,e.push({baseLocator:c.locator,char:`
|
|
26
|
+
`,locator:Po(c.locator,f,x),locatorEnd:x,locatorStart:f}),b+=1):e.push({baseLocator:c.locator,char:R,locator:Po(c.locator,f,x),locatorEnd:x,locatorStart:f})}}let n=[],r=0;for(let c of e){if(c.char===`
|
|
27
|
+
`){if(r+=1,r>2)continue}else r=0;n.push(c)}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),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:Po(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 Po(t,e,n){if(e===void 0||n===void 0)return t;let r=t.cfi;if(typeof r!="string")throw new Error("EPUB text mapping is missing a CFI locator.");let a=Hx(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${pl(a.startPath,e)},${pl(a.endPath,n)})`}}function Hx(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=$x(t.slice(8,-1));if(e.length!==3||e.some(o=>o===""))return;let[n,r,a]=e;if(!(n===void 0||r===void 0||a===void 0))return{endPath:a,parentPath:n,startPath:r}}function $x(t){let e=[],n=0,r=0,a=!1;for(let o=0;o<t.length;o+=1){let s=t[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(t.slice(n,o)),n=o+1)}return e.push(t.slice(n)),e}function pl(t,e){if(!/:\d+$/u.test(t))throw new Error("EPUB text mapping has an invalid CFI offset.");return t.replace(/:\d+$/u,`:${e}`)}function Jx(t){return t.name?.toLowerCase()}function hl(t){return t.type==="text"}function fl(t){return t.name!==void 0&&t.type!=="directive"}function yl(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${Xx(r)}]`;return`${t}/${a}${o}`}function gl(t,e,n,r){let a=kl(t),{parentPath:o,textPath:s}=Kx(e),d=o===""?a:`${a}!${o}`,c=o===""?`!${s}:${n}`:`${s}:${n}`,u=o===""?`!${s}:${r}`:`${s}:${r}`;return{cfi:`epubcfi(${d},${c},${u})`}}function Kx(t){let e=t.lastIndexOf("/");if(e<0||e===t.length-1)throw new Error(`EPUB text mapping has an invalid CFI path: ${t}`);return{parentPath:t.slice(0,e),textPath:t.slice(e)}}function zx(t,e){return{cfi:`epubcfi(${Qx(t)}${e})`}}function Qx(t){return`${kl(t)}!`}function kl(t){return`/6/${(t+1)*2}`}function Xx(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var Mx,Gx,_o,Ti,Il=i(()=>{"use strict";Ze();Mx=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"]),Gx=new Set(["script","style"]),_o={},Ti=class{#e;#t;constructor(e,n){this.#e=e,this.#t=jx(n)}async openSection(e){let n=this.#t.get(e);return n===void 0?[]:[(await this.#n(n.path,n.targets)).get(e)??""]}async openSectionWithProvenance(e,n){let r=this.#t.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=Bx(o,r.targets,e),d=Ux(s.segments,n.digest);if(s.text.length>0&&d.length===0)throw new Error(`EPUB section ${e} produced text without provenance mappings.`);return{provenance:{artifacts:[n],mappings:d},stream:[s.text]}}async#n(e,n){let r=await Sl(this.#e,e);return wl(r,n)}}});import{SaxesParser as Vx}from"saxes";function Vt(t){let e=new Vx({xmlns:!1}),n=[],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=n[n.length-1];s===void 0?r=o:s.children.push(o),n.push(o)}),e.on("text",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),e.on("cdata",a=>{let o=n[n.length-1];o!==void 0&&(o.text+=a)}),e.on("closetag",()=>{n.pop()}),e.write(t).close(),r===void 0)throw new Error("XML document is empty");return El(r)}function ge(t,e){return t.children.find(n=>$n(n.name)===e)}function Ge(t,e){return t.children.filter(n=>$n(n.name)===e)}function ee(t,e){return t.attributes[e]}function Hn(t){let e=t.text;for(let n of t.children)e+=Hn(n);return e}function $n(t){let e=t.indexOf(":");return e===-1?t:t.slice(e+1)}function El(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(El)),text:t.text}}var _i=i(()=>{"use strict"});async function vl(t){let e=await ek(t),n=Vt(await t.readText(e)),r=tk(ee(n,"version")),a=ge(n,"metadata"),o=ge(n,"manifest"),s=ge(n,"spine"),d=ge(n,"guide"),c=rk(t,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=ik(s,c),b=ak(t,e,d),R=nk(a),f=ok(c),x=sk(c,s),g=dk(c,a);return{version:r,opfPath:e,metadata:{...R,version:et,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:f,ncxPath:x,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:b}}async function ek(t){let e=Vt(await t.readText("META-INF/container.xml")),r=ge(e,"rootfiles")?.children.find(o=>$n(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 tk(t){return t?.trim().startsWith("3")===!0?3:2}function nk(t){if(t===void 0)return Rl();let e=wt(t,"title"),n=wt(t,"creator"),r=wt(t,"language"),a=wt(t,"identifier"),o=wt(t,"publisher"),s=wt(t,"date"),d=wt(t,"description");return{...Rl(),title:e[0]??null,authors:[...n],language:r[0]??null,identifier:a[0]??null,publisher:o[0]??null,publishedAt:s[0]??null,description:d[0]??null}}function Rl(){return{version:et,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function wt(t,e){return t.children.filter(n=>$n(n.name)===e).map(n=>uk(Hn(n))).filter(n=>n!==void 0)}function rk(t,e,n){let r=new Map;if(n===void 0)return r;for(let a of Ge(n,"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:t.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 ik(t,e){return t===void 0?[]:Ge(t,"itemref").map((n,r)=>{let a=ee(n,"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(n=>n!==void 0)}function ak(t,e,n){let r=new Set;if(n===void 0)return r;for(let a of Ge(n,"reference")){let o=(ee(a,"type")??"").trim().toLowerCase();if(!Zx.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Un(s).path))}return r}function ok(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function sk(t,e){let n=e===void 0?void 0:ee(e,"toc");if(n!==void 0)return t.get(n)?.path;for(let r of t.values())if(r.mediaType==="application/x-dtbncx+xml")return r.path}function dk(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=ck(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of Yx){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&fo(r.path).toLowerCase().includes("cover"))return r}function ck(t){if(t!==void 0)for(let e of Ge(t,"meta")){if((ee(e,"name")??"").trim().toLowerCase()!=="cover")continue;let r=ee(e,"content");if(r!==void 0&&r.trim()!=="")return r.trim()}}function uk(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Yx,Zx,Ao=i(()=>{"use strict";St();Bn();qn();_i();Yx=["cover-image","coverimg","cover-img","cover"],Zx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as lk}from"htmlparser2";async function Tl(t,e){let n=await pk(t,e)??await hk(t,e)??[];if(n.length===0)return Cl(e,new Set);let r=Al(n),a=Cl(e,r);return a.length===0?n:[...n,...a]}async function pk(t,e){if(e.navPath===void 0)return;let n=lk(await t.readText(e.navPath),{decodeEntities:!0}),r=Lo(n,s=>nt(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=Lo(r,s=>nt(s)==="ol");if(a===void 0)return;let o=Jn(a).filter(s=>nt(s)==="li").map(s=>_l(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function hk(t,e){if(e.ncxPath===void 0)return;let n=Vt(await t.readText(e.ncxPath)),r=ge(n,"navMap");if(r===void 0)return;let a=Ge(r,"navPoint").map(o=>Pl(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function _l(t,e,n){let r=Ll(n),a=r===void 0?void 0:Dl(Ol(r)),o=r!==void 0&&nt(r)==="a"?r.attribs?.href:void 0,s=yk(t,e,o),d=Jn(n).filter(c=>nt(c)==="ol").flatMap(c=>Jn(c)).filter(c=>nt(c)==="li").map(c=>_l(t,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(t,e,n){let r=ge(n,"navLabel"),a=r===void 0?void 0:ge(r,"text"),o=a===void 0?void 0:Dl(Hn(a)),s=ge(n,"content"),d=gk(t,e,ee(s??n,"src")),c=Ge(n,"navPoint").map(u=>Pl(t,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(t,e){return t.spine.filter(n=>!fk(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:bk(n.path),path:n.path,fragment:void 0,children:[]}))}function fk(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=Oo(e).toLowerCase();return t.navPath===e?!0:mk.has(r)&&!n.has(e)}function Al(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of Al(n.children))e.add(r)}return e}function yk(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Un(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function gk(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Un(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function Lo(t,e){if(Nl(t)&&e(t))return t;for(let n of t.children??[]){let r=Lo(n,e);if(r!==void 0)return r}}function Ll(t){for(let e of Jn(t)){let n=nt(e);if(n==="a"||n==="span")return e}for(let e of Jn(t)){if(nt(e)==="ol")continue;let n=Ll(e);if(n!==void 0)return n}}function Ol(t){return t.type==="text"?t.data??"":(t.children??[]).map(Ol).join("")}function Jn(t){return(t.children??[]).filter(Nl)}function Nl(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function nt(t){return t.name?.toLowerCase()}function bk(t){let e=Sk(t),n=Oo(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function Oo(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function Sk(t){let e=Oo(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function Dl(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var mk,Wl=i(()=>{"use strict";qn();Ao();_i();mk=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function wk(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function xk(t,e){if(!(e.coverPath===void 0||e.coverMediaType===void 0))return{path:e.coverPath,mediaType:e.coverMediaType,data:await t.readBuffer(e.coverPath)}}function kk(t,e){let n=new Map;return e.map((r,a)=>Fl(t,r,[a],n))}function Fl(t,e,n,r){let a=To(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=Ik(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(t,d,[...n,c],r))}}function Ml(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:Ml(n.children,e)}})}function Ik(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function Ek(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of Gl(t)){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 Gl(t){let e=[];for(let n of t)e.push(n),e.push(...Gl(n.children));return e}var No,Do,Kn,Wo,jl=i(()=>{"use strict";qn();qn();Il();Wl();Ao();No=class t{#e;#t;constructor(e,n){this.#e=e,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(e=>new t(this.#e,e))}async open(){return await this.#e.openSection(this.#t.id)}async openWithProvenance(){return await this.#e.openSectionWithProvenance(this.#t.id)}},Do=class t{#e;#t;#n;#r;#i;constructor(e,n,r,a,o){this.#e=e,this.#t=n,this.#n=r,this.#r=a,this.#i=o}static async open(e){wk(e);let n=await vl(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await Tl(e,n),o=kk(e,a),s=Ek(o,n),d=await bl(e,s),c=Ml(o,d),u=await xk(e,n);return new t(r,n,u,c,new Ti(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new No(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},Kn=class{get format(){return"epub"}async openSession(e,n){let r=await Ci.open(e);try{let a=await Do.open(r);return await n(a)}finally{await r.close()}}},Wo=new Kn});var Bl=i(()=>{"use strict";jl()});var Ul=i(()=>{"use strict";y()});import{SaxesParser as jO}from"saxes";var ql=i(()=>{"use strict";Ze();_i();Ul()});var $l=i(()=>{"use strict";ql()});async function*vk(t){let e=await t.openReader(),n=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+=n.decode(o,{stream:a<e.size});let s=r.split(/(?<=\n)/u);r=s.pop()??"";for(let d of s)d!==""&&(yield d)}r+=n.decode(),r!==""&&(yield r)}finally{await e.close()}}function Ck(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var Rk,Fo,Mo,zn,Jl,Kl,zl=i(()=>{"use strict";Bn();Rk="root",Fo=class{#e;#t;constructor(e,n=Rk){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(vk(this.#e))}},Mo=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new Fo(e)}readMeta(){return Promise.resolve({version:et,sourceFormat:this.#n,title:Ck(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])}},zn=class{#e;constructor(e){this.#e=e}get format(){return this.#e}async openSession(e,n){return await(await e.openReader()).close(),await n(new Mo(e,this.#e))}},Jl=new zn("txt"),Kl=new zn("markdown")});var Qn=i(()=>{"use strict"});import{z as ue}from"zod";var YO,ZO,Ql=i(()=>{"use strict";Qn();YO=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()}),ZO=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var xt=i(()=>{"use strict";Bn();Bl();$l();zl();Ql();Co()});var jo=i(()=>{"use strict"});var Xn=i(()=>{"use strict";xt();ye();jo();Z()});var Tk,Vl,Yl,Zl,Vn=i(()=>{"use strict";w();Qn();Tk=`
|
|
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
|
-
`,
|
|
37
|
+
`,Vl=`
|
|
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
|
-
${
|
|
333
|
+
${Tk}
|
|
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
|
-
`,
|
|
399
|
+
`,Yl=`
|
|
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
|
-
`,
|
|
409
|
+
`,Zl=`
|
|
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
|
-
${
|
|
416
|
+
${Yl}
|
|
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
|
|
473
|
+
`});var kt=i(()=>{"use strict";w();ve()});var em=i(()=>{"use strict";w();kt()});var tm=i(()=>{"use strict";w()});var nm=i(()=>{"use strict";w();mi()});var rm=i(()=>{"use strict";w();ve()});var im=i(()=>{"use strict";w();kt()});var am=i(()=>{"use strict";w();kt()});var om=i(()=>{"use strict";w();kt()});var sm=i(()=>{"use strict";w();kt()});var dm=i(()=>{"use strict";w();kt()});var lm=i(()=>{"use strict";Ee();w();Qn()});var mm=i(()=>{"use strict";w()});var pm=i(()=>{"use strict";w()});var hm=i(()=>{"use strict";w()});var fm=i(()=>{"use strict";mm();pm();hm()});var Ho=i(()=>{"use strict";em();tm();nm();rm();im();am();om();sm();dm();lm();fm()});var $o=i(()=>{"use strict"});var _m=i(()=>{"use strict";y()});var Pm=i(()=>{"use strict";pe();Gn()});var It=i(()=>{"use strict"});var Am=i(()=>{"use strict";y();w();Vn();It()});var Lm=i(()=>{"use strict";pe();$o()});var Om=i(()=>{"use strict"});import{z as Jo}from"zod";var AW,Dm=i(()=>{"use strict";y();Bn();Co();Xn();w();xo();Vn();Ho();ve();$o();_m();Pm();Am();Gn();Lm();Om();AW=Jo.object({mediaType:Jo.string().min(1),path:Jo.string()})});var Wm=i(()=>{"use strict"});var zo=i(()=>{"use strict";Dm();Wm()});var Mm=i(()=>{"use strict";Ro()});var _=i(()=>{"use strict";w();Vu();xo();Ro();zo();Mm();Vn();Qn();Ho();ve()});var Xo=i(()=>{"use strict"});var Be=i(()=>{"use strict";Xo()});async function Um(t){let e=await Wk(t);try{return await Dk(e,t),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
|
-
`,[
|
|
478
|
+
`,[t.scope,t.resourceKey],()=>!0)===!0}finally{await e.close()}}async function Dk(t,e){let n=[],r=[];e.scope!==void 0&&(n.push("scope = ?"),r.push(e.scope)),e.resourceKey!==void 0&&(n.push("resource_key = ?"),r.push(e.resourceKey));let a=await t.queryAll(`
|
|
477
479
|
SELECT scope, resource_key, mode, owner_id, owner_pid, heartbeat_at
|
|
478
480
|
FROM state_locks
|
|
479
481
|
${n.length===0?"":`WHERE ${n.join(" AND ")}`}
|
|
480
|
-
`,r,o=>({lock:
|
|
482
|
+
`,r,o=>({lock:Fk(o),resourceKey:E(o,"resource_key"),scope:E(o,"scope")}));for(let{lock:o,resourceKey:s,scope:d}of a)Gk(o,e.staleMs)&&await t.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
|
-
`,[
|
|
488
|
+
`,[d,s,o.ownerId,o.heartbeatAt])}async function Wk(t){if(t.databaseFile!==void 0)return await N.open(t.databaseFile,Bm,{create:!0,mode:"readwrite"});if(t.stateDatabaseName!==void 0)return await X(t.stateDatabaseName,Bm);throw new Error("State lock requires a database File or state database name.")}function Fk(t){return{heartbeatAt:S(t,"heartbeat_at"),mode:Mk(E(t,"mode")),ownerId:E(t,"owner_id")}}function Mk(t){return t==="read"||t==="write"?t:"write"}function Gk(t,e=Nk){return Date.now()-t.heartbeatAt>e}var Bm,Nk,qm=i(()=>{"use strict";U();w();_();Bm=`
|
|
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
|
-
`,
|
|
502
|
+
`,Nk=300*1e3});async function $m(t){return await Um({stateDatabaseName:"core.sqlite",resourceKey:Uk(t),scope:Bk,staleMs:Hm})||await qk(t)}function Uk(t){return String(t)}async function qk(t){let e=await Hk();try{let n=await e.queryOne("SELECT owner_pid, heartbeat_at FROM library_locks WHERE library_id = ?",[t],r=>({heartbeatAt:S(r,"heartbeat_at"),ownerPid:S(r,"owner_pid")}));return n!==void 0&&Jk(n)}finally{await e.close()}}async function Hk(){let t=await X("core.sqlite",jk);return await $k(t),t}async function $k(t){new Set(await t.queryAll("PRAGMA table_info(library_locks)",void 0,n=>E(n,"name"))).has("heartbeat_at")||await t.run("ALTER TABLE library_locks ADD COLUMN heartbeat_at INTEGER NOT NULL DEFAULT 0")}function Jk(t){return Date.now()-t.heartbeatAt<=Hm}var jk,Bk,Hm,Yn=i(()=>{"use strict";w();_();qm();jk=`
|
|
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
|
-
`,
|
|
510
|
-
`,
|
|
511
|
+
`,Bk="library",Hm=300*1e3});var gF,Yt=i(()=>{"use strict";y();w();_();Be();Ee();U();Yn();Xo();gF=Promise.resolve()});var Ue=i(()=>{"use strict"});var it=i(()=>{"use strict";Ue()});import{z as es}from"zod";var er,Pi,ts,RF,at=i(()=>{"use strict";Ue();er=1,Pi=5,ts=`${JSON.stringify({formatVersion:er,schemaVersion:Pi})}
|
|
512
|
+
`,RF=es.object({formatVersion:es.literal(er),schemaVersion:es.number().int().positive().optional()})});var Vm=i(()=>{"use strict";y();it();Ue();at()});var Ai=i(()=>{"use strict";y();Ue();at();it()});var Ym=i(()=>{"use strict";Ue()});var ep=i(()=>{"use strict";y();Ue();Ym();at();it()});var rp=i(()=>{"use strict";Vm();Ai();at();ep()});var up=i(()=>{"use strict";Be()});var lp=i(()=>{"use strict";Z()});var Wi=i(()=>{"use strict"});var rr=i(()=>{"use strict";mo();_n()});var ds=i(()=>{"use strict";y();Wi();rr()});var mp=i(()=>{"use strict";rr()});var pp=i(()=>{"use strict";Wi();rr()});var cs=i(()=>{"use strict";rr()});var hp=i(()=>{"use strict";ds();mp();pp();cs();Wi();Z()});var fp=i(()=>{"use strict";ds();hp();cs()});var yp=i(()=>{"use strict";lp();fp()});var Fi=i(()=>{"use strict";Z();y();yp();qe()});var XM,ir=i(()=>{"use strict";XM=new RegExp("\\p{Script=Han}","u")});var us=i(()=>{"use strict";Ee()});var ls,Rt=i(()=>{"use strict";ls=`
|
|
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
|
|
616
|
+
`});async function tn(){let t=await X("cache/search-sessions.sqlite",ls);return ms?t:await aI(t)?(ms=!0,t):(await iI(t),ms=!0,t)}async function iI(t){await t.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
|
-
${
|
|
621
|
-
`)}async function
|
|
622
|
+
${ls}
|
|
623
|
+
`)}async function aI(t){return await Mi(t,"search_entity_hits","archive_id")&&await Mi(t,"search_chunk_hits","archive_id")&&await Mi(t,"search_triple_hits","archive_id")&&await Mi(t,"search_evidence_hit_events","archive_id")}async function Mi(t,e,n){return(await t.queryAll(`PRAGMA table_info(${e})`,void 0,a=>String(a.name))).includes(n)}var ms,nn=i(()=>{"use strict";_();Rt();ms=!1});var Gi=i(()=>{"use strict"});async function Sp(t,e){await wp(t,e),await t.run("DELETE FROM search_sessions WHERE session_id = ?",[e])}async function wp(t,e){await t.run("DELETE FROM search_results WHERE session_id = ?",[e]),await t.run("DELETE FROM search_evidence_hit_events WHERE session_id = ?",[e]),await t.run("DELETE FROM search_entity_hits WHERE session_id = ?",[e]),await t.run("DELETE FROM search_triple_hits WHERE session_id = ?",[e]),await t.run("DELETE FROM search_chunk_hits WHERE session_id = ?",[e])}async function xp(t){await t.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
|
|
630
|
+
`)}var ps=i(()=>{"use strict";w();nn();Gi();Rt()});async function ji(t){let e=await tn();try{let n=await kp(e),r=await e.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,c=>S(c,"count")),a=t.force?await cI(e):await dI(e,t.now),o=t.force?[]:await uI(e),s=[...new Set([...a,...o])].sort();!t.dryRun&&s.length>0&&(await e.transaction(async()=>{for(let c of s)await Sp(e,c);await xp(e)}),await e.run("VACUUM"));let d=await kp(e);return{freedBytes:Math.max(0,n-d),removed:s.length,scanned:r??0}}finally{await e.close()}}async function dI(t,e){return await t.queryAll(`
|
|
629
631
|
SELECT session_id
|
|
630
632
|
FROM search_sessions
|
|
631
633
|
WHERE expires_at < ?
|
|
632
|
-
`,[
|
|
634
|
+
`,[e],n=>E(n,"session_id"))}async function cI(t){return await t.queryAll("SELECT session_id FROM search_sessions",void 0,e=>E(e,"session_id"))}async function uI(t){return await t.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],
|
|
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 kp(t){let e=await t.queryOne("PRAGMA page_count",void 0,r=>S(r,"page_count"))??0,n=await t.queryOne("PRAGMA page_size",void 0,r=>S(r,"page_size"))??0;return e*n}var Ip=i(()=>{"use strict";w();nn();Rt();ps()});var Ep=i(()=>{"use strict";Rt()});var hs=i(()=>{"use strict"});var Bi=i(()=>{"use strict";w();nn();Gi();Ep();hs()});var vp=i(()=>{"use strict";U();Rt()});var Cp=i(()=>{"use strict";w();us();nn();Bi();vp();Gi();Rt();ps()});var Tp=i(()=>{"use strict";w();nn();Bi()});var vt=i(()=>{"use strict";us();Ip();Bi();Cp();Tp();hs()});var Ui=i(()=>{"use strict"});var Wp=i(()=>{"use strict"});var ys=i(()=>{"use strict";Ee()});var qi=i(()=>{"use strict"});var gs=i(()=>{"use strict";qi()});var bs=i(()=>{"use strict";qi()});var Hi=i(()=>{"use strict";Ui();ys();gs();bs()});var Up=i(()=>{"use strict";Be()});var qp=i(()=>{"use strict";Ui();Wp();ys();qi();Hi();gs();bs();Up()});var D=i(()=>{"use strict";qp()});var ws=i(()=>{"use strict"});var xs=i(()=>{"use strict";Z();Xn();jo();ws()});var Hp=i(()=>{"use strict";xs()});var Y=i(()=>{"use strict";xs();Hp();ws()});var h0,f0,Ct=i(()=>{"use strict";U();h0=new RegExp("\\p{Script=Han}+","gu"),f0=new RegExp("^\\p{Script=Han}+$","u")});var $i=i(()=>{"use strict";U()});var Es=i(()=>{"use strict";It()});var Ki=i(()=>{"use strict";w();Es()});var Kp=i(()=>{"use strict";Ct();$i();Ki();It()});var Qp=i(()=>{"use strict";It()});var Xp=i(()=>{"use strict";Ct()});var Vp=i(()=>{"use strict"});var _s=i(()=>{"use strict";w();Vp();$i()});var Zp=i(()=>{"use strict";w();Ct();Xp();Es();It();_s();Ki()});var eh=i(()=>{"use strict";Kp();Qp();$i();Zp();_s();It();Ki()});var st=i(()=>{"use strict";eh();Ct()});var _t=i(()=>{"use strict";Y();st();Ct()});var ne=i(()=>{"use strict";ye();Be();D()});var Se=i(()=>{"use strict";Be();D()});var Te=i(()=>{"use strict";Y();Ze();D();ne()});var we=i(()=>{"use strict";Y();st();D();ne();Se();Te();D();_t()});var lr=i(()=>{"use strict";vt();st();we();Se()});var Ws=i(()=>{"use strict";Y();ir();D();ne();Te();Se()});var mr=i(()=>{"use strict";Z()});var Pe=i(()=>{"use strict";Y();mr();D();ne();Te()});var pr=i(()=>{"use strict"});var hr=i(()=>{"use strict";Te();Pe()});var Fs=i(()=>{"use strict";D();Pe();pr();hr()});var ph=i(()=>{"use strict";st();_t();D();we();Pe();pr();Fs();hr();hr();pr()});var hh=i(()=>{"use strict";ph();Fs();pr();hr()});var yr=i(()=>{"use strict";hh()});var yh=i(()=>{"use strict";vt();D();ne();Te();Pe();Se();yr()});var gr=i(()=>{"use strict";ne();Pe();D();Se();yr();yh()});var js=i(()=>{"use strict";Y();D();ne();Te();Pe();gr();br();Se()});var br=i(()=>{"use strict";D();ne();Te();Se();js()});var ea=i(()=>{"use strict";D();we();Se()});var ta=i(()=>{"use strict";D();we()});var na=i(()=>{"use strict";Y();ir();vt();st();D();lr();Ws();gr();br();we();ea();ta()});var kh=i(()=>{"use strict";ir();vt();D();_t();lr();Ws();gr();br();na();we()});var Ih=i(()=>{"use strict";kh();ea();ta();na();lr();we()});var ra=i(()=>{"use strict";Pe();yr();ne()});var Sr=i(()=>{"use strict";D()});var ia=i(()=>{"use strict";D();_t();ne();we();lr();st();Sr()});var Us=i(()=>{"use strict";D();Se();ra();ia();Sr()});var qs=i(()=>{"use strict"});var Rh=i(()=>{"use strict";mr();D();Pe();ra();Us();ia();Sr();qs();ne()});var aa=i(()=>{"use strict";Rh();Us();ra();ia();Sr();qs()});var Hs=i(()=>{"use strict";_();Be();Y();mr();D();Pe();yr();br();Se();aa();ne();Te()});var vh=i(()=>{"use strict";_();Y();ye();Be();Ee();D();Te()});var Ch=i(()=>{"use strict";Hs();aa();ne()});var Zs=i(()=>{"use strict";Ih();Hs();aa();_t();ne();js();gr();vh();Ch()});var Ph=i(()=>{"use strict";Zs()});var mE,Ah=i(()=>{"use strict";Ee();U();w();_();mE=10080*60*1e3});var Lh=i(()=>{"use strict"});var Oh=i(()=>{"use strict";w();Ah();Lh()});var Nh=i(()=>{"use strict"});var Dh=i(()=>{"use strict";Oh();Nh()});var cn=i(()=>{"use strict";Ph();Dh();vt()});var Lt=i(()=>{"use strict"});var iJ,Rr=i(()=>{"use strict";y();w();Dn();Lt();iJ=new gt(1)});var rd=i(()=>{"use strict";w();U();Lt();Rr()});var da=i(()=>{"use strict";y();U()});var id=i(()=>{"use strict";U();Rr();da()});var jh=i(()=>{"use strict";y();at();Ue();it();Ai();Lt();rd();id();Rr()});var Bh=i(()=>{"use strict";Lt();it()});var Uh=i(()=>{"use strict";y();U();Rr()});var sd=i(()=>{"use strict";y();U();Ai();at();it();Lt();jh();Bh();rd();Uh();id();da()});var qh=i(()=>{"use strict";sd()});async function ca(t){let e=v().documentStore,n=0,r=0,a=0,o;try{o=await e.list()}catch(d){if(Fe(d)&&d.code==="ENOENT")return{freedBytes:a,removed:r,scanned:n};throw d}for(let d of o){if(!j(d)||!d.name.startsWith(".wikg-session-"))continue;n+=1;let c=await Qe(d);!t.force&&(c===void 0||t.now-c<bE)||(a+=await Ie(d),t.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)&&(n+=1,t.force&&(a+=await Ie(d),t.dryRun||await s.remove(d.name,{recursive:!0}),r+=1));return{freedBytes:a,removed:r,scanned:n}}var bE,Hh=i(()=>{"use strict";y();pe();bE=3600*1e3});var $h=i(()=>{"use strict";w();y();U();Lt();da()});var dd=i(()=>{"use strict";qh();sd();Hh();$h()});var cd=i(()=>{"use strict";dd()});var Kh=i(()=>{"use strict";_();Fi();cn();cd()});var qe=i(()=>{"use strict";rp();up();Kh();cd()});var vr=i(()=>{"use strict";st()});async function zh(t){let n=await(await v().library.getDirectory("staging"))?.getDirectory("library");if(n===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await kE();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,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 $m(m))continue;let b=await Ie(u);t.dryRun||await n.remove(u.name,{recursive:!0}),d+=1,c+=b}return{freedBytes:c,removed:d,scanned:s}}async function kE(){let t=await X("core.sqlite","");try{return await t.queryAll("SELECT id FROM libraries",void 0,e=>S(e,"id"))}catch{return}finally{await t.close()}}var Cr=i(()=>{"use strict";U();y();w();Vn();_();qe();_t();vr();Ct();Tr();Yt();Yn();Z()});var EE,Dz,Tr=i(()=>{"use strict";y();w();_();Be();qe();Ee();U();Yt();Cr();Yn();EE=`
|
|
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
|
-
`,
|
|
652
|
+
`,Dz=`
|
|
698
653
|
CREATE TABLE IF NOT EXISTS library_archives (
|
|
699
|
-
${
|
|
654
|
+
${EE}
|
|
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
|
|
708
|
-
prev: ${
|
|
709
|
-
text: ${
|
|
710
|
-
next: ${
|
|
711
|
-
`);return{candidates:a,code:n,fieldName:
|
|
662
|
+
`});var md=i(()=>{"use strict";qe();Tr();Yt()});var Vh=i(()=>{"use strict";Ui();Hi();ir();ta();ea();we();na();vt();vr();Cr();md()});var Yh=i(()=>{"use strict";Zs();Hi();Vh();we();Tr();md();Yt();Cr()});var la=i(()=>{"use strict";Yt();Tr();Yh();Cr();Yn()});function ma(t){let e=t.trim();return e===""?[]:Array.from(WE.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function xe(t){let e=t.replace(/\s+/gu," ").trim(),n=FE(e),r="";for(let a of n)if(!ME(a)){if(!_r(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function FE(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(r===void 0)break;if(r!==" "){e.push(r),n+=1;continue}if(e.length>=2&&DE.has(e[e.length-1]??"")&&_r(e[e.length-2]??"")&&n<t.length-1&&_r(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&_r(a)&&_r(o)&&e.push(r),n+=1}return e}function _r(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function ME(t){return/[\p{P}\p{S}]/u.test(t)}var DE,WE,Pr=i(()=>{"use strict";DE=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),WE=new Intl.Segmenter(void 0,{granularity:"sentence"})});function hd(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function ef(t,e){let n=pa(t,2),r=pa(e,2),a=pa(t,3),o=pa(e,3);return(Zh(n,r)+Zh(a,o))/2}function pa(t,e){if(t.length<=e)return t===""?new Set:new Set([t]);let n=new Set;for(let r=0;r<=t.length-e;r+=1)n.add(t.slice(r,r+e));return n}function Zh(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let r of t)e.has(r)&&(n+=1);return 2*n/(t.size+e.size)}function tf(t,e){if(t===e)return 1;if(t===""||e==="")return 0;let n=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...t].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(n[d+1]??0)+1,b=(n[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[n,r]=[r,n]}return 1-(n[e.length]??Math.max(t.length,e.length))/Math.max(t.length,e.length)}function nf(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function rf(t,e){if(t===e)return 1;let n=t.length,r=e.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 d=1;d<=r;d+=1){if(t[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/(n+r)}function af(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
|
|
663
|
+
prev: ${pd(t.prevText)}
|
|
664
|
+
text: ${pd(t.text,120)}
|
|
665
|
+
next: ${pd(t.nextText)}`}function pd(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var fd=i(()=>{"use strict"});var yd=i(()=>{"use strict"});function sf(t,e,n){return t.mode==="head_tail"?BE(t,e):gd(t.text??"",e,n)}function BE(t,e){let n=t.head??"",r=t.tail??"",a=xe(e),o=xe(n),s=xe(r);if(o===""||s==="")return hd();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=gd(n,e,"start_anchor"),m=gd(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 gd(t,e,n){let r=t.trim(),a=e.trim(),o=xe(r),s=xe(a);if(o===""||s==="")return hd();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),x=o.length/Math.max(1,s.length),g=of({candidateNormalized:s,label:n,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*x+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 x=0;x<=s.length-f;x+=1){let g=s.slice(x,x+f),C=new Set(g),L=new Set([...R,...C]).size,K=[...R].filter(ie=>C.has(ie)).length;if((L===0?0:K/L)<.35)continue;let G=.35*ef(o,g)+.35*rf(o,g)+.2*tf(o,g)+.1*nf(o,g)+of({candidateNormalized:s,label:n,matchEnd:x+f,matchStart:x,queryNormalized:o});G>d&&(d=Math.min(1,G),c=x,u=x+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function of(t){if(t.matchStart<0||t.matchEnd<0||t.queryNormalized.length<12||t.label==="start_anchor"&&t.matchStart!==0||t.label==="end_anchor"&&t.matchEnd!==t.candidateNormalized.length)return 0;let e=t.queryNormalized.length/Math.max(1,t.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var df=i(()=>{"use strict";Pr();fd();yd()});function cf(t){if(t==null)return[void 0,"anchor is required"];if(typeof t=="string"){let o=t.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 t!="object")return[void 0,`expected string or object, got ${typeof t}`];let e=t;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 uf(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?bd(t.tail??"","end_anchor"):bd(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:bd(t.text??"",e)}}function Sd(t){return t.mode==="head_tail"?xe(t.head??"").length+xe(t.tail??"").length:xe(t.text??"").length}function bd(t,e){let n=ma(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var lf=i(()=>{"use strict";Pr()});var Ot,ff=i(()=>{"use strict";df();lf();fd();yd();Ot=class{resolve(e,n,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:n,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,x]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return x!==void 0?[void 0,x]: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:n.slice(u.index,R.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let n=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(n,"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,x,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}+${x}`},void 0]}parseAnchor(e,n){let[r,a]=cf(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[uf(r,n),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 n=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(n=n.filter(m=>m.index>=r)),n.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=n.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.#t(e.label,"ambiguous_exact_raw",a)];let o=n.filter(m=>m.exactSubstring);if(o.length===1&&Sd(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&Sd(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#t(e.label,"ambiguous_exact_substring",o)]}let s=n.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.#t(e.label,"ambiguous_exact_normalized",s)]}let d=n[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=n[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:n.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:n.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.#t(e.label,"ambiguous_ranked",n)]}rankAnchor(e,n,r,a){let o=[];for(let[s,d]of n.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=sf(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 n=e[0];if(n===void 0)return;let r=e[1]?.score??0;if(n.score>=.9&&n.score-r>=.07)return n}#t(e,n,r){let a=r.slice(0,3),o=a.map(s=>af(s)).join(`
|
|
666
|
+
`);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
|
|
712
667
|
${o}
|
|
713
|
-
Please provide a more specific anchor or surrounding context.`}}}});var
|
|
714
|
-
`)});var
|
|
668
|
+
Please provide a more specific anchor or surrounding context.`}}}});var yf=i(()=>{"use strict"});var gf=i(()=>{"use strict";ff();yf()});var ha,bf=i(()=>{"use strict";ha=["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 wd=i(()=>{"use strict"});var Sf=i(()=>{"use strict";wd();Pr()});var mn=i(()=>{"use strict";gf();bf();wd();Sf();Pr()});import{z as Ar}from"zod";var QQ,xf=i(()=>{"use strict";QQ=Ar.object({meanings:Ar.array(Ar.object({information:Ar.string(),qid:Ar.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var kf=i(()=>{"use strict"});var If=i(()=>{"use strict"});var Ef=i(()=>{"use strict"});var Rf=i(()=>{"use strict";xf();kf();If();Ef()});async function kd(t){let e=await Lr.open();try{return await e.gc(t)}finally{await e.close()}}function nR(t){try{let e=JSON.parse(t);if(typeof e!="object"||e===null)return;let n=e;return typeof n.qid!="string"||typeof n.refreshedAt!="string"||typeof n.disambiguation!="boolean"||!Array.isArray(n.sites)?void 0:{disambiguation:n.disambiguation,qid:n.qid,refreshedAt:n.refreshedAt,sites:n.sites}}catch{return}}var eR,tR,Lr,vf=i(()=>{"use strict";Rf();_();eR=`
|
|
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
|
+
`,tR=336*60*60*1e3,Lr=class t{#e;constructor(e){this.#e=e}static async open(){return new t(await X("cache/cache.sqlite",eR))}async get(e){let n=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:nR(a);o!==void 0&&o.qid===r&&n.set(r,o)}return n}async put(e){await this.#e.transaction(async()=>{for(let n 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`,[n.qid,JSON.stringify(n),n.refreshedAt])})}async close(){await this.#e.close()}async gc(e){let n=new Date(e.now-tR).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 < ?",[n],o=>Number(o.count))??0;return!e.dryRun&&a>0&&(await this.#e.run("DELETE FROM wikimedia_cache_v1 WHERE refreshed_at < ?",[n]),await this.#e.run("VACUUM")),{freedBytes:0,removed:a,scanned:r}}}});var Ed=i(()=>{"use strict";vf()});var Rd=i(()=>{"use strict"});var vd=i(()=>{"use strict"});import{jsonrepair as fX}from"jsonrepair";var Cf=i(()=>{"use strict"});var Tf=i(()=>{"use strict";vd();Rd();Cf()});var Le=i(()=>{"use strict";Rd();vd();Tf()});var Or=i(()=>{"use strict"});import{z as $e}from"zod";var sR,dR,jX,_d=i(()=>{"use strict";Le();Or();sR=$e.object({candidateId:$e.string().min(1),decision:$e.enum(["continue","recall","skip_this_time","never_recall"]),qid:$e.string().nullable().optional()}).strict(),dR=$e.object({decisions:$e.array(sR),groupId:$e.string().min(1)}).strict(),jX=$e.object({groups:$e.array(dR)}).strict()});import{z as Nr}from"zod";var lR,JX,Af=i(()=>{"use strict";Le();Or();_d();lR=Nr.object({decision:Nr.enum(["keep","reject"]),qid:Nr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),JX=Nr.object({qids:Nr.array(lR)}).strict()});var Lf=i(()=>{"use strict"});import{z as Dr}from"zod";var mR,VX,Of=i(()=>{"use strict";Le();mR=Dr.object({note:Dr.string().max(24).optional(),surfaceId:Dr.string().min(1)}).strict(),VX=Dr.object({protectedSurfaces:Dr.array(mR)}).strict()});var Pd=i(()=>{"use strict"});var Nf=i(()=>{"use strict";Pd()});var Df=i(()=>{"use strict"});var Ad=i(()=>{"use strict"});var Wf=i(()=>{"use strict";Ad();Or()});var dt=i(()=>{"use strict";_d();Af();Or();Lf();Of();Nf();Pd();Df();Wf();Ad()});var TV,Od=i(()=>{"use strict";zt();TV=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 Nd=i(()=>{"use strict";Ve()});var Bf=i(()=>{"use strict";Nd()});var Uf=i(()=>{"use strict";Bf();Nd()});var qf=i(()=>{"use strict"});var Hf=i(()=>{"use strict"});var $f=i(()=>{"use strict";qf();Hf()});var Wr=i(()=>{"use strict";Le()});var Jf=i(()=>{"use strict";_();Wr()});var Kf=i(()=>{"use strict";Wr()});var zf=i(()=>{"use strict"});import{z as k}from"zod";var Qf,vR,Xf,CR,TR,_R,PR,AR,LR,ya=i(()=>{"use strict";_();Qf=k.object({from:k.union([k.number().int(),k.string()]),strength:k.string().optional(),to:k.union([k.number().int(),k.string()])}),vR=k.object({quote:k.string().optional(),sentence_id:k.string().optional()}).passthrough(),Xf=k.union([k.record(k.string(),k.unknown()),k.array(vR)]),CR=k.object({content:k.string(),evidence:Xf.nullish(),label:k.string(),retention:k.enum(["verbatim","detailed","focused","relevant"]),temp_id:k.string()}).passthrough(),TR=k.object({chunks:k.array(CR),fragment_summary:k.string(),links:k.array(Qf)}),_R=k.object({content:k.string(),evidence:Xf.nullish(),importance:k.enum(["critical","important","helpful"]),label:k.string(),temp_id:k.string()}).passthrough(),PR=k.object({chunk_id:k.number().int(),importance:k.enum(["critical","important","helpful"])}),AR=k.object({chunks:k.array(_R),importance_annotations:k.array(PR),links:k.array(Qf)}),LR=k.object({choice:k.string()})});var Vf=i(()=>{"use strict";Le();mn();zf();Wr();ya()});var Yf=i(()=>{"use strict";Le();_();Jf();Wr();Kf();Vf();ya()});var Zf=i(()=>{"use strict";Yf();ya()});var ga=i(()=>{"use strict"});import{detect as MY,validateISO2 as GY}from"tinyld";var Dd=i(()=>{"use strict";We()});var ey=i(()=>{"use strict";Dd();We()});var ty=i(()=>{"use strict"});import{z as Fr}from"zod";var FR,s2,ry=i(()=>{"use strict";Le();mn();Zf();ga();ga();ey();ty();FR=Fr.object({content:Fr.string(),id:Fr.number(),label:Fr.string()}),s2=Fr.array(FR)});var Wd=i(()=>{"use strict";ry()});var iy=i(()=>{"use strict";Ze()});var Fd=i(()=>{"use strict";iy()});var ay=i(()=>{"use strict";$f();Wd();Fd()});var ba=i(()=>{"use strict";ay();Fd()});var Sa=i(()=>{"use strict"});var wa=i(()=>{"use strict";ba();Sa()});var oy=i(()=>{"use strict";wa()});var sy=i(()=>{"use strict"});var xa=i(()=>{"use strict"});var dy=i(()=>{"use strict";xa()});var hn,F2,qR,ka=i(()=>{"use strict";yo();hn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(hn||{}),F2=Xt(hn),qR=jn(hn,"review severity")});var U2,Gd=i(()=>{"use strict";xa();ka();U2=Object.freeze({critical:9,major:3,minor:1})});var cy=i(()=>{"use strict";Dd();We();ka()});var uy=i(()=>{"use strict";y();Ve();Gd()});var jd=i(()=>{"use strict";_()});var ly=i(()=>{"use strict"});import{z as fn}from"zod";var HR,$R,m3,my=i(()=>{"use strict";Ve();Le();xa();jd();ka();HR=["critical","major","minor"],$R=fn.object({problem:fn.string(),severity:fn.enum(HR),suggestion:fn.string().default("")}),m3=fn.object({issues:fn.array($R)})});var py=i(()=>{"use strict";sy();dy();Gd();cy();uy();jd();ly();my()});var Bd=i(()=>{"use strict";py()});var fy=i(()=>{"use strict"});var yy=i(()=>{"use strict"});var gy=i(()=>{"use strict";fy();yy()});var Mr=i(()=>{"use strict"});var J3,K3,yn=i(()=>{"use strict";_();J3={critical:9,helpful:1,important:3},K3={detailed:9,focused:3,relevant:1,verbatim:27}});var gn=i(()=>{"use strict"});var Gr=i(()=>{"use strict"});var Ud=i(()=>{"use strict";gn()});var qd=i(()=>{"use strict";yn();gn();Mr();Gr();Ud()});var Hd=i(()=>{"use strict";Mr();qd();Gr()});var Sy=i(()=>{"use strict";yn();gn();Gr()});var wy=i(()=>{"use strict";yn();gn();Mr();Gr();Ud()});var xy=i(()=>{"use strict";Hd();gn();Mr();Sy();qd();wy()});var ky=i(()=>{"use strict";xy();Hd()});var Iy=i(()=>{"use strict";yn()});var Ey=i(()=>{"use strict";ky();Iy()});var Ry=i(()=>{"use strict";gy();Ey();yn()});var vy=i(()=>{"use strict";Ry()});var $d=i(()=>{"use strict";Z()});var Cy=i(()=>{"use strict"});var Jd=i(()=>{"use strict";wa()});var Ea=i(()=>{"use strict"});var Ty=i(()=>{"use strict";Dn();zt();Bd();ba();vy();wa();Sa();$d();Cy();Jd();Ea()});var _y=i(()=>{"use strict";$d();Ea();Z()});var Py=i(()=>{"use strict";oy();Ty();Sa();_y();Jd();Ea()});var bn=i(()=>{"use strict";Py()});var Ay=i(()=>{"use strict";ye();Dn();bn();xt()});var Ly=i(()=>{"use strict";xt();xt();_();ye();Uf();bn();Ay();Fi();y()});var Qd,ct=i(()=>{"use strict";Qd=["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 Xd=i(()=>{"use strict";ct()});var Dy=i(()=>{"use strict";Ve();uo();Ly();Od();qe();Xd();y()});var Vd,Yd=i(()=>{"use strict";Vd=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function Wy(){return await z(v().library,"jobs/work")}async function Fy(t){let e=await v().library.getDirectory("jobs");if(e!==void 0)for(let[n,r,a]of[["work",t,!0],["cache",t,!0],["logs",t,!0],["events",`${t}.ndjson`,!1]]){let o=await e.getDirectory(n);o!==void 0&&await o.remove(r,{recursive:a})}}var jr=i(()=>{"use strict";y()});var Br=i(()=>{"use strict";U()});var Zd=i(()=>{"use strict"});var Ur=i(()=>{"use strict";y()});var My,Gy=i(()=>{"use strict";My=`
|
|
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
|
|
740
|
+
`});function Wt(t){let e=av(Dt(t,"current_step"),"current_step"),n=Dt(t,"owner_id"),r=t.owner_pid===null?void 0:de(t,"owner_pid"),a=t.reading_summary_started_at===null?void 0:de(t,"reading_summary_started_at"),o=t.finished_at===null?void 0:de(t,"finished_at"),s=Dt(t,"error_json"),d=t.input_revision===null?void 0:de(t,"input_revision"),c=Dt(t,"llm_json"),u=Dt(t,"prompt");return{archiveKey:Oe(t,"archive_key"),archiveIdentity:Oe(t,"archive_path"),cacheLocator:Oe(t,"cache_path"),chapterId:de(t,"chapter_id"),createdAt:de(t,"created_at"),...e===void 0?{}:{currentStep:e},...s===void 0?{}:{errorJSON:s},eventsLocator:Oe(t,"events_path"),...o===void 0?{}:{finishedAt:o},jobId:Oe(t,"job_id"),...d===void 0?{}:{inputRevision:d},logLocator:Oe(t,"log_path"),...c===void 0?{}:{llmJSON:c},...n===void 0?{}:{ownerId:n},...r===void 0?{}:{ownerPid:r},...u===void 0?{}:{prompt:u},queueRank:de(t,"queue_rank"),state:iv(Oe(t,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:jy(Oe(t,"target"),"target"),updatedAt:de(t,"updated_at"),workspaceLocator:Oe(t,"workspace_path")}}async function Hr(t){let e=A().resources,[n,r,a,o,s]=await Promise.all([e.getFile(t.archiveIdentity),ec(t.cacheLocator),rv(t.eventsLocator),ec(t.logLocator),ec(t.workspaceLocator)]);if(n===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}=t;return{...f,archive:n,cache:r,events:a,log:o,workspace:s}}async function ec(t){return t.startsWith("jobs/")?await Ne(v().library,t)??nv(t):await A().resources.getDirectory(t)}function nv(t){let e=v().library,n=r=>`${t}/${r}`;return{createDirectory:async r=>await z(e,n(r)),createFile:async r=>await H(e,n(r)),getDirectory:async r=>await Ne(e,n(r)),getFile:async r=>await J(e,n(r)),getLastModified:async()=>await(await Ne(e,t))?.getLastModified?.(),identity:`managed:library:${t}`,kind:"directory",list:async()=>(await Ne(e,t))?.list()??[],name:t.split("/").at(-1)??t,remove:async(r,a)=>{await(await Ne(e,t))?.remove(r,a)}}}async function rv(t){return t.startsWith("jobs/")?await J(v().library,t):await A().resources.getFile(t)}function qr(t){return new Error(`Build job ${t} resource is unavailable`)}function iv(t){if(Vd.includes(t))return t;throw new Error(`Invalid build job state: ${t}`)}function jy(t,e){if(t==="index-embedding-source"||t==="index-embedding-summary"||t==="index-fts"||t==="reading-graph"||t==="knowledge-graph"||t==="reading-summary")return t;throw new Error(`Invalid ${e}: ${t}`)}function av(t,e){return t===void 0?void 0:jy(t,e)}function Oe(t,e){let n=t[e];if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}function de(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function Dt(t,e){let n=t[e];if(n!=null){if(typeof n!="string")throw new TypeError(`Expected ${e} to be a string`);return n}}var Ft=i(()=>{"use strict";Yd();y()});async function Sn(){let t=await X("jobs/job.sqlite",My);try{return await t.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
|
+
`),t}catch(e){throw await t.close().catch(()=>{}),e}}var wn=i(()=>{"use strict";_();y();Gy();Ft()});var Ra=i(()=>{"use strict";Br();Ur();wn();jr()});var va=i(()=>{"use strict";Ft();Ra();jr()});var tc=i(()=>{"use strict";U();jr();Br();Zd();Ur();wn();va();Ra();Ft()});var Hy=i(()=>{"use strict";Br();wn();va();Ft()});var $y=i(()=>{"use strict";U();Br();Zd();Ur();wn();va();Ra();tc();Ft()});function mv(t){return uv.has(t)}async function pv(t,e){if((await e.list()).some(a=>!mv(a.name)))return 0;let r=await lt(e);return await t.remove(e.name,{recursive:!0}),r}async function Jy(t){let e=0,n=0,r=0;for(let a of await t.list()){if(!j(a))continue;r+=1;let o=await Qe(a);if(o===void 0||Date.now()-o<lv)continue;let s=await pv(t,a);(s>0||await t.getDirectory(a.name)===void 0)&&(e+=s,n+=1)}return{freedBytes:e,removed:n,scanned:r}}async function lt(t){return await Ie(t)}var uv,lv,nc=i(()=>{"use strict";y();uv=new Set([".DS_Store"]),lv=6e4});async function Ca(t){let e=await Sn(),n=t.force?t.now:t.now-10080*60*1e3;try{let r=await e.queryOne("SELECT COUNT(*) AS count FROM build_jobs",void 0,c=>de(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],
|
|
755
|
+
`,[n],Wt),o=await Promise.all(a.map(Hr)),s=t.dryRun?{freedBytes:0,removed:0,scanned:0}:await Jy(await Wy()),d=0;for(let c of o)d+=await lt(c.workspace),d+=await lt(c.cache),d+=await lt(c.log),d+=await lt(c.events),t.dryRun||(await Fy(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 Ky=i(()=>{"use strict";nc();jr();wn();Ft()});var Xy=i(()=>{"use strict";Yd();tc();Hy();$y();Ur();Ky()});var Pa=i(()=>{"use strict"});import{z as p}from"zod";var Vy,V,fv,yv,Yy,gv,bv,Sv,wv,xv,kv,Iv,Ev,Rv,vv,Cv,Tv,_v,Pv,h6,xn=i(()=>{"use strict";y();ve();Pa();Vy=1,V=p.number().int().nonnegative(),fv=p.literal(Vy),yv=p.string().regex(/^Q[1-9][0-9]*$/u),Yy=p.number().min(0).max(1).optional(),gv=p.object({text:p.string(),wordsCount:V}).strict(),bv=p.object({type:p.literal("meta"),schemaVersion:fv,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),Sv=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),wv=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(gv)}).strict(),xv=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(),kv=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(),Iv=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),Ev=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(),Rv=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),vv=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),Cv=p.object({type:p.literal("summary"),text:p.string()}).strict(),Tv=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:yv,confidence:Yy,note:p.string().optional()}).strict(),_v=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:Yy,note:p.string().optional()}).strict(),Pv=p.object({type:p.literal("end")}).strict(),h6=p.discriminatedUnion("type",[bv,Sv,wv,xv,kv,Iv,Ev,Rv,vv,Cv,Tv,_v,Pv])});var Zy=i(()=>{"use strict"});var eg=i(()=>{"use strict"});import{sha256 as S6}from"@noble/hashes/sha2.js";var w6,x6,yc=i(()=>{"use strict";w6=new RegExp("\\p{Script=Han}+","gu"),x6=new RegExp("^\\p{Script=Han}+$","u")});var gc=i(()=>{"use strict";yc()});import{z as l}from"zod";function tg(){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 ng(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function rg(){return l.object({endSentenceIndex:P,groupId:P,startSentenceIndex:P,type:l.literal("fragment-group")})}function ig(){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 ag(){return l.object({chunkId:l.string(),position:P,snakeId:l.string(),type:l.literal("snake-chunk")})}function og(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function sg(){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 Av(){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,bc,C6,T6,Mt=i(()=>{"use strict";P=l.number().int().nonnegative(),bc={sentenceIndex:P,text:l.string(),wordsCount:P},C6=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...bc,fragmentId:P.optional(),type:l.literal("source-text")}),l.object({fragmentId:P,summary:l.string(),type:l.literal("source-fragment")}),l.object({...bc,fragmentId:P.optional(),type:l.literal("source-sentence")}),l.object({...bc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),tg(),ng(),rg(),ig(),ag(),og(),sg()]),T6=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),tg(),ng(),rg(),ig(),ag(),og(),sg(),Av(),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 Sc=i(()=>{"use strict";Mt()});var wc=i(()=>{"use strict"});var Gt,xc=i(()=>{"use strict";Gt=["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 D6}from"jsonrepair";var dg=i(()=>{"use strict"});var cg=i(()=>{"use strict";xc();wc();dg()});var le=i(()=>{"use strict";wc();xc();cg()});var mg=i(()=>{"use strict"});var $r=i(()=>{"use strict"});import{z as Ke}from"zod";var Dv,Wv,s9,Ic=i(()=>{"use strict";le();$r();Dv=Ke.object({candidateId:Ke.string().min(1),decision:Ke.enum(["continue","recall","skip_this_time","never_recall"]),qid:Ke.string().nullable().optional()}).strict(),Wv=Ke.object({decisions:Ke.array(Dv),groupId:Ke.string().min(1)}).strict(),s9=Ke.object({groups:Ke.array(Wv)}).strict()});import{z as Jr}from"zod";var Mv,f9,hg=i(()=>{"use strict";le();$r();Ic();Mv=Jr.object({decision:Jr.enum(["keep","reject"]),qid:Jr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),f9=Jr.object({qids:Jr.array(Mv)}).strict()});var Ec=i(()=>{"use strict"});import{z as Kr}from"zod";var Gv,w9,fg=i(()=>{"use strict";le();Gv=Kr.object({note:Kr.string().max(24).optional(),surfaceId:Kr.string().min(1)}).strict(),w9=Kr.object({protectedSurfaces:Kr.array(Gv)}).strict()});var yg=i(()=>{"use strict";Ec()});var gg=i(()=>{"use strict"});var Rc=i(()=>{"use strict"});var bg=i(()=>{"use strict";Rc();$r()});var zr=i(()=>{"use strict";mg();hg();$r();Ic();Ec();fg();yg();gg();bg();Rc()});var La=i(()=>{"use strict"});var Sg=i(()=>{"use strict";zr();La()});var wg=i(()=>{"use strict";zr()});var vc=i(()=>{"use strict"});var xg=i(()=>{"use strict";zr();La();wg();vc()});function Oa(t){let e=t.trim();return e===""?[]:Array.from(Uv.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function ke(t){let e=t.replace(/\s+/gu," ").trim(),n=qv(e),r="";for(let a of n)if(!Hv(a)){if(!Qr(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function qv(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(r===void 0)break;if(r!==" "){e.push(r),n+=1;continue}if(e.length>=2&&Bv.has(e[e.length-1]??"")&&Qr(e[e.length-2]??"")&&n<t.length-1&&Qr(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&Qr(a)&&Qr(o)&&e.push(r),n+=1}return e}function Qr(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function Hv(t){return/[\p{P}\p{S}]/u.test(t)}var Bv,Uv,Xr=i(()=>{"use strict";Bv=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),Uv=new Intl.Segmenter(void 0,{granularity:"sentence"})});function Tc(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Ig(t,e){let n=Na(t,2),r=Na(e,2),a=Na(t,3),o=Na(e,3);return(kg(n,r)+kg(a,o))/2}function Na(t,e){if(t.length<=e)return t===""?new Set:new Set([t]);let n=new Set;for(let r=0;r<=t.length-e;r+=1)n.add(t.slice(r,r+e));return n}function kg(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let r of t)e.has(r)&&(n+=1);return 2*n/(t.size+e.size)}function Eg(t,e){if(t===e)return 1;if(t===""||e==="")return 0;let n=Array.from({length:e.length+1},(o,s)=>s),r=new Array(e.length+1).fill(0);for(let[o,s]of[...t].entries()){r[0]=o+1;for(let[d,c]of[...e].entries()){let u=(r[d]??0)+1,m=(n[d+1]??0)+1,b=(n[d]??0)+(s===c?0:1);r[d+1]=Math.min(u,m,b)}[n,r]=[r,n]}return 1-(n[e.length]??Math.max(t.length,e.length))/Math.max(t.length,e.length)}function Rg(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function vg(t,e){if(t===e)return 1;let n=t.length,r=e.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 d=1;d<=r;d+=1){if(t[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/(n+r)}function Cg(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
|
|
757
|
+
prev: ${Cc(t.prevText)}
|
|
758
|
+
text: ${Cc(t.text,120)}
|
|
759
|
+
next: ${Cc(t.nextText)}`}function Cc(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var _c=i(()=>{"use strict"});var Pc=i(()=>{"use strict"});function _g(t,e,n){return t.mode==="head_tail"?Kv(t,e):Ac(t.text??"",e,n)}function Kv(t,e){let n=t.head??"",r=t.tail??"",a=ke(e),o=ke(n),s=ke(r);if(o===""||s==="")return Tc();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=Ac(n,e,"start_anchor"),m=Ac(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 Ac(t,e,n){let r=t.trim(),a=e.trim(),o=ke(r),s=ke(a);if(o===""||s==="")return Tc();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),x=o.length/Math.max(1,s.length),g=Tg({candidateNormalized:s,label:n,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*x+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 x=0;x<=s.length-f;x+=1){let g=s.slice(x,x+f),C=new Set(g),L=new Set([...R,...C]).size,K=[...R].filter(ie=>C.has(ie)).length;if((L===0?0:K/L)<.35)continue;let G=.35*Ig(o,g)+.35*vg(o,g)+.2*Eg(o,g)+.1*Rg(o,g)+Tg({candidateNormalized:s,label:n,matchEnd:x+f,matchStart:x,queryNormalized:o});G>d&&(d=Math.min(1,G),c=x,u=x+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function Tg(t){if(t.matchStart<0||t.matchEnd<0||t.queryNormalized.length<12||t.label==="start_anchor"&&t.matchStart!==0||t.label==="end_anchor"&&t.matchEnd!==t.candidateNormalized.length)return 0;let e=t.queryNormalized.length/Math.max(1,t.candidateNormalized.length);return .08*(.5+.5*Math.min(1,e))}var Pg=i(()=>{"use strict";Xr();_c();Pc()});function Ag(t){if(t==null)return[void 0,"anchor is required"];if(typeof t=="string"){let o=t.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 t!="object")return[void 0,`expected string or object, got ${typeof t}`];let e=t;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 Lg(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?Lc(t.tail??"","end_anchor"):Lc(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:Lc(t.text??"",e)}}function Oc(t){return t.mode==="head_tail"?ke(t.head??"").length+ke(t.tail??"").length:ke(t.text??"").length}function Lc(t,e){let n=Oa(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var Og=i(()=>{"use strict";Xr()});var kn,Fg=i(()=>{"use strict";Pg();Og();_c();Pc();kn=class{resolve(e,n,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:n,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,x]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return x!==void 0?[void 0,x]: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:n.slice(u.index,R.index+1),strategy:`${m}+${f}`},void 0]}resolveWithOverrides(e){let n=e.evidence.start_anchor??e.evidence.start,r=e.evidence.end_anchor??e.evidence.end,[a,o]=this.parseAnchor(n,"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,x,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}+${x}`},void 0]}parseAnchor(e,n){let[r,a]=Ag(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[Lg(r,n),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 n=this.rankAnchor(e.anchor,e.candidateSentenceIds,e.candidateTexts,e.label),r=e.minIndex;if(r!==void 0&&(n=n.filter(m=>m.index>=r)),n.length===0)return[void 0,"none",{candidates:[],code:"none",fieldName:e.label,message:`${e.label} could not be matched: no candidates available`}];let a=n.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.#t(e.label,"ambiguous_exact_raw",a)];let o=n.filter(m=>m.exactSubstring);if(o.length===1&&Oc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&Oc(e.anchor)>=8){let m=this.#e(o);return m!==void 0?[m,"exact_substring_scored",void 0]:[void 0,"ambiguous_exact_substring",this.#t(e.label,"ambiguous_exact_substring",o)]}let s=n.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.#t(e.label,"ambiguous_exact_normalized",s)]}let d=n[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=n[1]?.score??0,u=d.score-c;return d.score<.55?[void 0,"low_confidence",{candidates:n.slice(0,3),code:"low_confidence",fieldName:e.label,message:`${e.label} could not be matched confidently. Best candidate score=${d.score.toFixed(3)}.`}]:n.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.#t(e.label,"ambiguous_ranked",n)]}rankAnchor(e,n,r,a){let o=[];for(let[s,d]of n.entries()){let c=r[s]??"",u=s>0?r[s-1]??"":"",m=s<r.length-1?r[s+1]??"":"",b=_g(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 n=e[0];if(n===void 0)return;let r=e[1]?.score??0;if(n.score>=.9&&n.score-r>=.07)return n}#t(e,n,r){let a=r.slice(0,3),o=a.map(s=>Cg(s)).join(`
|
|
760
|
+
`);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
|
|
761
|
+
${o}
|
|
762
|
+
Please provide a more specific anchor or surrounding context.`}}}});var Mg=i(()=>{"use strict"});var Gg=i(()=>{"use strict";Fg();Mg()});var Nc,jg=i(()=>{"use strict";Nc=["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 Dc=i(()=>{"use strict"});var Bg=i(()=>{"use strict";Dc();Xr()});var Da=i(()=>{"use strict";Gg();jg();Dc();Bg();Xr()});var qg=i(()=>{"use strict"});import{z as W}from"zod";var Hg,Vv,Yv,Zv,Q7,X7,$g=i(()=>{"use strict";le();Da();qg();Hg=W.object({head:W.string().optional(),mode:W.enum(["full","head_tail"]).optional(),tail:W.string().optional(),text:W.string().optional()}).strict(),Vv=W.object({quote:W.string().optional(),sentence_id:W.string().optional()}).strict(),Yv=W.union([W.object({end_anchor:W.union([W.string(),Hg]).optional(),quote:W.string().optional(),sentence_id:W.string().optional(),start_anchor:W.union([W.string(),Hg]).optional()}).strict(),W.array(Vv)]),Zv=W.object({confidence:W.number().min(0).max(1).optional(),evidence:Yv,predicate:W.string().min(1).max(64),sourceMentionId:W.string().min(1),targetMentionId:W.string().min(1)}).strict(),Q7=W.object({relations:W.array(Zv)}).strict(),X7=new kn});var Jg=i(()=>{"use strict"});var Kg=i(()=>{"use strict"});var zg=i(()=>{"use strict";$g();Jg();Kg()});var Qg=i(()=>{"use strict";zg();La();vc()});var Vr,In=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 Eee,Fc=i(()=>{"use strict";le();Mt();Sg();xg();Qg();zr();In();Eee=["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 Xg=i(()=>{"use strict"});var Vg=i(()=>{"use strict"});var Yg=i(()=>{"use strict";Xg();Vg()});var Bt=i(()=>{"use strict"});var Yr=i(()=>{"use strict";le()});var eb=i(()=>{"use strict";Bt();Yr()});var tb=i(()=>{"use strict";Yr()});var nb=i(()=>{"use strict"});import{z as I}from"zod";var rb,rC,ib,iC,aC,oC,sC,dC,cC,Wa=i(()=>{"use strict";Bt();rb=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),rC=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),ib=I.union([I.record(I.string(),I.unknown()),I.array(rC)]),iC=I.object({content:I.string(),evidence:ib.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),aC=I.object({chunks:I.array(iC),fragment_summary:I.string(),links:I.array(rb)}),oC=I.object({content:I.string(),evidence:ib.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),sC=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),dC=I.object({chunks:I.array(oC),importance_annotations:I.array(sC),links:I.array(rb)}),cC=I.object({choice:I.string()})});var ab=i(()=>{"use strict";le();Da();nb();Yr();Wa()});var ob=i(()=>{"use strict";le();Bt();eb();Yr();tb();ab();Wa()});var sb=i(()=>{"use strict";ob();Wa()});var Gc=i(()=>{"use strict"});import{detect as Rte,validateISO2 as vte}from"tinyld";var db=i(()=>{"use strict"});var cb=i(()=>{"use strict"});import{z as Zr}from"zod";var mC,$te,ub=i(()=>{"use strict";le();Da();sb();Gc();Gc();db();cb();mC=Zr.object({content:Zr.string(),id:Zr.number(),label:Zr.string()}),$te=Zr.array(mC)});var lb=i(()=>{"use strict";ub()});var mb=i(()=>{"use strict";Yg();lb()});var pb=i(()=>{"use strict";mb()});var hb=i(()=>{"use strict"});var fb=i(()=>{"use strict"});var jc=i(()=>{"use strict";hb();le();In();fb()});var yb=i(()=>{"use strict"});var gb=i(()=>{"use strict"});var bb=i(()=>{"use strict";yb();gb()});var ei=i(()=>{"use strict"});var _ne,Pne,En=i(()=>{"use strict";Bt();_ne={critical:9,helpful:1,important:3},Pne={detailed:9,focused:3,relevant:1,verbatim:27}});var Rn=i(()=>{"use strict"});var ti=i(()=>{"use strict"});var Bc=i(()=>{"use strict";Rn()});var Uc=i(()=>{"use strict";En();Rn();ei();ti();Bc()});var qc=i(()=>{"use strict";ei();Uc();ti()});var wb=i(()=>{"use strict";En();Rn();ti()});var xb=i(()=>{"use strict";En();Rn();ei();ti();Bc()});var kb=i(()=>{"use strict";qc();Rn();ei();wb();Uc();xb()});var Ib=i(()=>{"use strict";kb();qc()});var Eb=i(()=>{"use strict";En()});var Rb=i(()=>{"use strict";Ib();Eb()});var vb=i(()=>{"use strict";bb();Rb();En()});var Hc=i(()=>{"use strict";Mt();In();pb();jc();vb()});var Cb=i(()=>{"use strict"});var Ma=i(()=>{"use strict"});var Tb=i(()=>{"use strict";Ma()});var Ga=i(()=>{"use strict"});var iie,Pb=i(()=>{"use strict";Ma();Ga();iie=Object.freeze({critical:9,major:3,minor:1})});import{detect as sie,validateISO2 as die}from"tinyld";var Ab=i(()=>{"use strict";Ga()});var Lb=i(()=>{"use strict"});var Ob=i(()=>{"use strict";Bt()});var $c=i(()=>{"use strict";Ob()});var Nb=i(()=>{"use strict"});import{z as vn}from"zod";var kC,IC,vie,Db=i(()=>{"use strict";le();Ma();$c();Ga();kC=["critical","major","minor"],IC=vn.object({problem:vn.string(),severity:vn.enum(kC),suggestion:vn.string().default("")}),vie=vn.object({issues:vn.array(IC)})});var Wb=i(()=>{"use strict";Cb();Tb();Pb();Ab();Lb();$c();Nb();Db()});var Jc=i(()=>{"use strict";Mt();In();Bt();jc();Wb()});var Fb=i(()=>{"use strict";gc();Mt();Sc();Fc();Hc();Jc()});import{z as M}from"zod";var Cn,EC,RC,vC,CC,gae,Mb=i(()=>{"use strict";Cn=M.number().finite().nonnegative(),EC=M.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),RC=M.enum(["candidate","char","item","page","qid","record","sentence","window"]),vC=M.object({cacheReadTokens:Cn.optional(),inputTokens:Cn.optional(),outputTokens:Cn.optional()}),CC=M.object({done:Cn,force:M.boolean().optional(),phase:EC,phaseDetail:M.string().optional(),total:Cn,unit:RC}),gae=M.discriminatedUnion("event",[M.object({characters:Cn,event:M.literal("output-characters")}),M.object({event:M.literal("token-usage"),usage:vC}),M.object({event:M.literal("progress"),progress:CC}),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 Gb=i(()=>{"use strict"});var jb=i(()=>{"use strict"});var ni=i(()=>{"use strict";Zy();eg();Fb();Sc();gc();Mt();Fc();Hc();Jc();In();Mb();Gb();jb();yc()});var Bb=i(()=>{"use strict";ni();vr()});import{z as T}from"zod";var TC,_C,Bae,Uae,qae,Ub=i(()=>{"use strict";y();TC="wikg-index-output/v1",_C=T.enum(["fts","embedding-source","embedding-summary"]),Bae=T.object({artifactKind:_C,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(TC),type:T.literal("manifest")}),Uae=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")}),qae=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 Ut=i(()=>{"use strict";Bb();Ub()});var qb=i(()=>{"use strict";We();ct()});var Hb=i(()=>{"use strict";_();ba()});var Jb=i(()=>{"use strict";y();_();Y();bn();xn();Ut();qb();Hb()});var ja=i(()=>{"use strict"});var Kb=i(()=>{"use strict";ja()});var zb=i(()=>{"use strict"});var Qb=i(()=>{"use strict";ja()});var Xb=i(()=>{"use strict";ja()});var Vb=i(()=>{"use strict";Kb();zb();Qb();Xb()});import{z as h}from"zod";var Yb,BC,UC,qC,HC,$C,JC,KC,zC,QC,XC,Zb=i(()=>{"use strict";ve();Yb=h.tuple([h.number(),h.number()]),BC=h.object({text:h.string(),wordsCount:h.number()}),UC=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(BC)}),qC=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(t=>({documentOrder:t.documentOrder??t.id,id:t.id,knowledgeGraphReady:t.knowledgeGraphReady,...t.knowledgeGraphParameterHash===void 0?{}:{knowledgeGraphParameterHash:t.knowledgeGraphParameterHash},revision:t.revision??0,topologyReady:t.topologyReady,...t.topologyParameterHash===void 0?{}:{topologyParameterHash:t.topologyParameterHash}})),HC=h.object({id:h.number(),generation:h.number(),sentenceId:Yb,label:h.string(),content:h.string(),sentenceIds:h.array(Yb),retention:h.enum(he).optional(),importance:h.enum(Re).optional(),wordsCount:h.number(),weight:h.number()}),$C=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),JC=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()}),KC=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),zC=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),QC=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),XC=h.object({chunks:h.array(HC),fragmentGroups:h.array(QC),fragments:h.array(UC),readingEdges:h.array($C),serial:qC,snakeChunks:h.array(KC),snakeEdges:h.array(zC),snakes:h.array(JC)})});var eS=i(()=>{"use strict";y();Zb()});var tS=i(()=>{"use strict";zt();Bd();Z()});var nS=i(()=>{"use strict";y();_();Y();Vb();eS();Pa();tS();xn();Ut()});var rS=i(()=>{"use strict"});var Ba=i(()=>{"use strict";nS();Pa();rS()});var iS=i(()=>{"use strict";Y();Ba()});var aS=i(()=>{"use strict"});var oS=i(()=>{"use strict";Jb();iS();aS()});var sS=i(()=>{"use strict";ni()});var cS=i(()=>{"use strict";ni();_();Y();Ut();Ba()});var uS=i(()=>{"use strict";ni();dt();zt()});var lS=i(()=>{"use strict";oS();Ba();sS();cS();uS()});import{z as $}from"zod";var rde,YC,ide,Xc=i(()=>{"use strict";y();rde=$.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()}),YC=$.tuple([$.number().int().nonnegative(),$.number().int().nonnegative()]).readonly(),ide=$.object({id:$.string().min(1),sourceMentionId:$.string().min(1),targetMentionId:$.string().min(1),predicate:$.string().min(1),evidenceSentenceIds:$.array(YC).min(1),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()})});var Vc=i(()=>{"use strict";y();We();xn();Xc()});var pS=i(()=>{"use strict";xn();Ut();Xc()});var Ua=i(()=>{"use strict"});var hS=i(()=>{"use strict";dt();Ua()});var Yc=i(()=>{"use strict"});var fS=i(()=>{"use strict";dt()});var Zc=i(()=>{"use strict"});var eu=i(()=>{"use strict";dt();Ua();fS();Zc()});var gS=i(()=>{"use strict";eu()});var bS=i(()=>{"use strict";We()});var SS=i(()=>{"use strict";Wd();mn();ga()});import{z as F}from"zod";var wS,nT,rT,iT,zde,Qde,xS=i(()=>{"use strict";Le();mn();SS();wS=F.object({head:F.string().optional(),mode:F.enum(["full","head_tail"]).optional(),tail:F.string().optional(),text:F.string().optional()}).strict(),nT=F.object({quote:F.string().optional(),sentence_id:F.string().optional()}).strict(),rT=F.union([F.object({end_anchor:F.union([F.string(),wS]).optional(),quote:F.string().optional(),sentence_id:F.string().optional(),start_anchor:F.union([F.string(),wS]).optional()}).strict(),F.array(nT)]),iT=F.object({confidence:F.number().min(0).max(1).optional(),evidence:rT,predicate:F.string().min(1).max(64),sourceMentionId:F.string().min(1),targetMentionId:F.string().min(1)}).strict(),zde=F.object({relations:F.array(iT)}).strict(),Qde=new Ot});var kS=i(()=>{"use strict"});var IS=i(()=>{"use strict";xS();kS()});var ES=i(()=>{"use strict";IS();Ua();Zc()});var tu=i(()=>{"use strict";Y();Yc()});var CS=i(()=>{"use strict";dt();ct();Vc();hS();Yc();gS();bS();ES();tu()});var TS=i(()=>{"use strict"});var _S=i(()=>{"use strict";Vc();pS();CS();eu();tu();TS()});var PS=i(()=>{"use strict";_S()});var ri=i(()=>{"use strict";Y()});var nu=i(()=>{"use strict";ct()});var ru=i(()=>{"use strict";We();ct();bn();ri();nu()});var OS=i(()=>{"use strict";ct();ri();ru()});var iu=i(()=>{"use strict";ye();Z()});var DS=i(()=>{"use strict";ye();Xn();xt();iu();Z()});var WS=i(()=>{"use strict";bn();ye();ri();DS();iu();Z()});import{z as qt}from"zod";var FS,Pue,MS=i(()=>{"use strict";FS=qt.object({children:qt.lazy(()=>qt.array(FS)),uri:qt.string().min(1),title:qt.string().nullable().optional()}).strict(),Pue=qt.object({chapters:qt.array(FS)}).strict()});var GS=i(()=>{"use strict";Y()});var jS=i(()=>{"use strict";OS();ri();ru();WS();nu();MS();GS()});var BS=i(()=>{"use strict";mr()});var ze=i(()=>{"use strict";Dy();cn();Xy();lS();PS();cn();Xd();jS();BS();Fi()});async function xw(t="global"){let e=await lu(),n=Xe(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await I_(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
|
-
`,[
|
|
767
|
+
`,[t,n,0,r,r]),a=await e.queryOne("SELECT owner_id FROM gc_locks WHERE scope = ?",[t],s=>E(s,"owner_id"))===n})}finally{await e.close()}if(!a)return;let o=setInterval(()=>{k_(t,n).catch(()=>{})},x_);return async()=>{clearInterval(o);let s=await lu();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[t,n])}finally{await s.close()}}}async function k_(t,e){let n=await lu();try{await n.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
|
|
771
|
+
`,[Date.now(),0,t,e])}finally{await n.close()}}async function I_(t){let e=await t.queryAll("SELECT * FROM gc_locks",void 0,v_);for(let{lock:n,scope:r}of e.filter(({lock:a})=>E_(a)))await t.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
|
|
776
|
+
`,[r,n.ownerId,n.heartbeatAt])}function E_(t){return!(Date.now()-t.heartbeatAt<w_)}async function lu(){return await X("tmp/gc.sqlite",S_)}function R_(t){return{createdAt:S(t,"created_at"),heartbeatAt:S(t,"heartbeat_at"),ownerId:E(t,"owner_id"),ownerPid:S(t,"owner_pid")}}function v_(t){return{lock:R_(t),scope:E(t,"scope")}}var S_,w_,x_,kw=i(()=>{"use strict";U();w();_();S_=`
|
|
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
|
-
`,
|
|
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
|
|
784
|
+
`,w_=6e4,x_=2e4});async function Iw(t){let e=await v().library.getDirectory("tmp"),n=0,r=0,a=0;if(e===void 0)return{freedBytes:a,removed:r,scanned:n};for(let o of await T_(e)){n+=1;let s=await Qe(o.value);if(!t.force&&(s===void 0||t.now-s<C_))continue;let d=await lt(o.value);t.dryRun||await o.parent.remove(o.value.name,{recursive:!0}),r+=1,a+=d}return{freedBytes:a,removed:r,scanned:n}}async function T_(t){let e=[];for(let n of await t.list())if(j(n))for(let r of await n.list())e.push({parent:n,value:r});return e}var C_,Ew=i(()=>{"use strict";y();nc();C_=3600*1e3});async function Ja(t={}){let e=Date.now(),n=await xw();if(n===void 0)return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};try{if(t.opportunistic===!0&&!await L_(e))return{finishedAt:Date.now(),freedBytes:0,jobs:[],removed:0,scanned:0,skipped:!0,startedAt:e};let r={dryRun:t.dryRun===!0,force:t.force===!0,now:e},a=[];for(let s of __)a.push(await A_(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 O_(o.finishedAt).catch(()=>{}),o}finally{await n()}}async function A_(t,e){try{return{name:t.name,...await t.run(e)}}catch(n){return{error:Kt(n),freedBytes:0,name:t.name,removed:0,scanned:0}}}function mu(t,e){return t.reduce((n,r)=>{let a=r[e];return n+(typeof a=="number"?a:0)},0)}async function L_(t){let e=await J(v().library,"tmp/gc.last-run"),n=Number((e===void 0?"":await ae(e).catch(()=>"")).trim());return!Number.isFinite(n)||t-n>=P_}async function O_(t){let e=await H(v().library,"tmp/gc.last-run");await me(e,`${t}
|
|
785
|
+
`)}var __,P_,Rw=i(()=>{"use strict";y();cn();ze();qe();la();Ed();pe();kw();Ew();__=[{name:"wikg-coordinator",run:ca},{name:"search-cache",run:ji},{name:"library-index",run:zh},{name:"build-queue",run:Ca},{name:"wikimedia-cache",run:kd},{name:"tmp",run:Iw}],P_=600*1e3});var vw=i(()=>{"use strict";Rw()});var Cw=i(()=>{"use strict";vw()});var Tw={};Lw(Tw,{tryRunWikiGraphGc:()=>N_});async function N_(t={}){Ln();let{stateDir:e,...n}=t;return await Jt(e,async()=>await Ja(n))}var _w=i(()=>{"use strict";Cw();ce()});ce();import{AsyncLocalStorage as m_}from"async_hooks";import{randomUUID as She}from"crypto";import{link as xhe,mkdtemp as khe,rename as Ihe,rm as Ehe,stat as Rhe}from"fs/promises";import{tmpdir as Che}from"os";import{basename as _he,dirname as Phe,join as Ahe}from"path";import{Readable as Ohe}from"stream";We();y();mi();import{z as Nn}from"zod";var ax=1,lP=Nn.object({completedAt:Nn.string().optional(),startedAt:Nn.string(),status:Nn.enum(["running","succeeded"]),version:Nn.literal(ax)});uo();zt();Ve();Z();mo();_n();la();mn();Ed();dt();Od();ze();ye();qe();_();xt();cn();_();Xn();Ri();xi();Ut();y();Ze();Ue();at();it();dd();xi();la();vr();Ut();_();y();qe();y();w();w();y();w();y();zo();y();pe();ze();ze();ze();ze();ze();ct();dt();_();xn();y();import{createHash as Wpe}from"crypto";import{createReadStream as Mpe}from"fs";import{rm as jpe}from"fs/promises";import{basename as Upe}from"path";import{createAnthropic as ipe}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as ope}from"@ai-sdk/google";import{createOpenAI as dpe}from"@ai-sdk/openai";import{createOpenAICompatible as upe}from"@ai-sdk/openai-compatible";ce();import{z as re}from"zod";import{AsyncLocalStorage as QT}from"async_hooks";var sw=Symbol.for("wiki-graph-sdk.runtime-context.v1"),XT=VT();function VT(){let t=globalThis,e=t[sw];if(e!==void 0)return e;let n=new QT;return Object.defineProperty(t,sw,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}async function cu(t,e){return await XT.run(t,e)}ce();import{join as Spe}from"path";import{homedir as xpe}from"os";var ZT=["anthropic","google","openai","openai-compatible"],dw=re.enum(ZT),vpe=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:dw.optional()}).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:dw.optional()});import{homedir as _pe}from"os";import{isAbsolute as Ape,resolve as Lpe}from"path";ce();import{embed as Xpe,embedMany as Vpe}from"ai";import{createOpenAI as Zpe}from"@ai-sdk/openai";import{createOpenAICompatible as the}from"@ai-sdk/openai-compatible";import{spawn as $he}from"child_process";import{streamText as ofe}from"ai";ze();ce();var u_=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function pw(t){let e=l_(t.env);if(t.envPolicy==="production"){let o=u_.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:t.envPolicy,stateDir:t.stateDir}}let n=e.WIKIGRAPH_DEV??e.WIKIGRAPH_STATE_DIR,r=mw(t.stateDir??n);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=mw(t.devProjectRoot);if(a===void 0)throw new Error("Wiki Graph development entries require an explicit project root.");return{devProjectRoot:a,env:e,envPolicy:t.envPolicy,stateDir:r}}function l_(t){return t===void 0?{...process.env}:{...process.env,...t}}function mw(t){if(!(t===void 0||t.trim()===""))return t}ce();ce();import{mkdir as Qfe}from"fs/promises";ce();import{basename as nye}from"path";ce();ce();var p_=new m_;async function hw(t,e){return await p_.run(t,async()=>await cu({cwd:t.cwd,env:t.env,envPolicy:t.envPolicy,...t.stateDir===void 0?{}:{stateDir:t.stateDir}},e))}var fw="--wikigraph-internal-child",yw="--wikigraph-dev-project-root",gw="--wikigraph-env-policy",bw="--wikigraph-state-dir";async function Sw(t,e){let n=h_(process.argv.slice(2));if(n.internalChild!==t)throw new Error("This Wiki Graph worker entry is internal.");let r=pw({argv:n.argv,devProjectRoot:n.devProjectRoot,envPolicy:n.envPolicy,stateDir:n.stateDir});return await Jt(r.stateDir,async()=>hw({argv:n.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(n)))}function h_(t){let e=[],n,r,a="production",o;for(let s=0;s<t.length;s+=1){let d=t[s];if(d===fw){if(s+1>=t.length)throw new Error(`${fw} requires a value.`);n=t[s+1],s+=1;continue}if(d===gw){let c=t[s+1];if(c!=="development"&&c!=="production")throw new Error(`${gw} requires development or production.`);a=c,s+=1;continue}if(d===yw){let c=t[s+1];if(c===void 0||c.trim()==="")throw new Error(`${yw} requires a value.`);r=c,s+=1;continue}if(d!==bw){e.push(d);continue}if(s+1>=t.length)throw new Error(`${bw} requires a value.`);o=t[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:n??"",stateDir:o}}var f_={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 oge}from"path";import{createReadStream as hge}from"fs";import{mkdtemp as yge,rm as gge}from"fs/promises";import{join as Sge}from"path";import{tmpdir as xge}from"os";var y_=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((t,e)=>[t,e]));function ww(t){return`${JSON.stringify(uu(t),null,2)}
|
|
786
|
+
`}function uu(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>uu(e)??null);if(typeof t=="object")return g_(t)}function g_(t){let e=Object.entries(t).map(([r,a],o)=>({index:o,key:r,priority:y_.get(r)??Number.MAX_SAFE_INTEGER,value:a})),n={};for(let r of e.sort((a,o)=>a.priority-o.priority||a.index-o.index)){let a=uu(r.value);a!==void 0&&(n[r.key]=a)}return n}import{homedir as Pge}from"os";import{isAbsolute as Lge,relative as Oge,resolve as Nge}from"path";import{existsSync as Gge,readFileSync as jge}from"fs";import{dirname as Uge,join as qge,parse as Hge,resolve as $ge}from"path";Ln();var{tryRunWikiGraphGc:D_}=await Promise.resolve().then(()=>(_w(),Tw));async function W_(){await Sw("gc-worker",async({argv:t})=>{let e=F_(t);process.stdout.write(ww(await D_({dryRun:e.dryRun,force:e.force})))})}function F_(t){return{dryRun:t.includes("--dry-run"),force:t.includes("--force")}}W_().catch(t=>{process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}
|
|
802
787
|
`),process.exitCode=1});
|
|
803
788
|
//# sourceMappingURL=gc-worker.js.map
|