wiki-graph 0.7.1 → 0.8.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/dist/cli.js +668 -633
- package/dist/cli.js.map +1 -1
- package/dist/data/help/commands/library-predicate.jinja +13 -0
- package/dist/data/help/commands/library.jinja +9 -2
- package/dist/data/help/commands/predicate.jinja +11 -9
- package/dist/data/help/commands/uri.jinja +13 -0
- package/dist/data/help/topics/library.jinja +3 -1
- package/dist/data/help/topics/readiness.jinja +3 -3
- package/dist/data/help/topics/recipe.jinja +1 -1
- package/dist/data/help/topics/uri.jinja +6 -1
- package/dist/gc-worker.js +102 -85
- package/dist/gc-worker.js.map +1 -1
- package/dist/index.cjs +685 -186
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +602 -99
- package/dist/index.js.map +1 -1
- package/dist/queue-worker.js +657 -622
- package/dist/queue-worker.js.map +1 -1
- package/package.json +3 -3
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 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)
|
|
6
|
+
var Yw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Zw=(t,e)=>{for(var n in e)Yw(t,n,{get:e[n],enumerable:!0})};async function ui(t){let e=await t.openReader();try{return e.size}finally{await e.close()}}async function wt(t){return await ui(t)===0}async function ae(t){return new TextDecoder().decode(await Vt(t))}async function Vt(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(U(t)){let e=0;for(let n of await t.list())e+=await Ie(n);return e}return await ui(t)}async function Ye(t){return await t.getLastModified?.()}function U(t){return t.kind==="directory"}var Au=i(()=>{"use strict"});function lo(t){Yt().installedPlatform=t}function A(){let{installedPlatform:t}=Yt();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 kt(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 We(t,e){let n=mo(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=mo(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=mo(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 mo(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 Yt(){let t=globalThis,e=t[Lu];if(e!==void 0)return e;let n={storageContext:new uo};return Object.defineProperty(t,Lu,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}function po(t){Yt().installedStorage=t}async function mi(t,e){return t===void 0?await e():await Yt().storageContext.run(t,e)}function R(){let{installedStorage:t,storageContext:e}=Yt(),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 Lu,uo,y=i(()=>{"use strict";Au();Lu=Symbol.for("wiki-graph-core.runtime.v1");uo=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}=Yt();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 pi(t){if(tk.test(t))throw new Error(`invalid template name ${t}`);let n=t.replace(nk,"").replace(ek,"");if(n.split("/").includes(".."))throw new Error(`invalid template name ${t}`);return`${n}.jinja`}var ek,tk,nk,Fn=i(()=>{"use strict";y();ek=/\.jinja$/iu,tk=/^\.+\//u,nk=/^\/+/u});var Nu=i(()=>{"use strict";y();Fn()});import*as Du from"async_hooks";import*as Mu from"crypto";import*as fi from"fs";import*as B from"fs/promises";import*as Fu from"os";import*as O from"path";import*as bo from"process";import{Readable as Gu,Writable as rk}from"stream";import{pipeline as ik}from"stream/promises";import*as So from"sqlite3";import*as ju from"yauzl";import*as Uu from"yazl";import{Environment as ak,Loader as ok}from"nunjucks";async function Wu(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 Bu(t,e,n){if(qu(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 qu(t){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("File offset must be a non-negative safe integer")}function Hu(t,e){return`node-${t}:${Buffer.from(O.resolve(e),"utf8").toString("base64url")}`}function ho(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 Gn(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 sk(t,e){let n=(e.mode==="readonly"?jn.OPEN_READONLY:jn.OPEN_READWRITE|(e.create?jn.OPEN_CREATE:0))|jn.OPEN_FULLMUTEX;return new yo(await dk(t,n))}async function dk(t,e){let n=$u(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 jn.Database(n,e,s=>{s?a(s):r(o)})})}async function ck(t){let e=$u(t,"file");if(e===void 0)throw new TypeError("The Node ZIP adapter requires a NodeFile");let n=await new Promise((o,s)=>{ju.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 uk(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 mk(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 lk(n,s)}}}async function uk(t,e,n){let r=await n.openWriter();try{let a=await hi(t,e);await Ju(a,r),await r.commit()}catch(a){throw await r.abort().catch(()=>{}),a}}async function lk(t,e){return await Ku(await hi(t,e))}async function mk(t,e,n,r){if(Bu(n,r,e.uncompressedSize),r===0)return new Uint8Array;if(e.compressionMethod!==0){let o=await pk(await hi(t,e),n,r);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}let a=await Ku(await hi(t,e,{decompress:null,decrypt:null,end:n+r,start:n}));return new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}async function pk(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 hi(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 hk(t,e){let n=new Uu.ZipFile,r=await t.openWriter(),a=n.outputStream,o=Ju(a,r),s={cancelled:!1,complete:!1},d;try{d=bk(e);let c=fk(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&&Sk(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 fk(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(yk(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(gk(r.value),r.value.name,{compress:!1,size:r.value.size})}}function yk(t){return Gu.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 $u(t,e){if(typeof t!="object"||t===null)return;let n=t;return n[wo]===e&&typeof n.path=="string"?n.path:void 0}function gk(t){return Gu.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 bk(t){let e=t[Symbol.asyncIterator];return e===void 0?t[Symbol.iterator]():e.call(t)}function Sk(t){if(t.return!==void 0)try{Promise.resolve(t.return()).catch(()=>{})}catch{}}async function Ju(t,e){await ik(t,new rk({write:(n,r,a)=>{e.write(n).then(()=>a(),o=>a(o instanceof Error?o:new Error("Cannot stream ZIP archive")))}}))}async function Ku(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 kk(){let t=globalThis.__WIKIGRAPH_DATA_DIR__;if(typeof t=="string"&&t!=="")return t;let e=fo.cwd();for(;;){for(let r of[O.join(e,"data"),O.join(e,"packages","core","data")])try{if(fi.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 zu(t=O.join(Fu.homedir(),".wikigraph")){return{library:new De(t),documentStore:new De(O.join(t,"documents"))}}function Un(t){lo(wk),po(zu(t))}async function Zt(t,e){return await mi(t===void 0?void 0:zu(t),e)}var fo,jn,wo,se,De,yo,wk,go,de=i(()=>{"use strict";Nu();fo=bo.default??bo,jn=So.default??So,wo=Symbol.for("wiki-graph-sdk.node-resource.v1"),se=class{constructor(e,n=O.basename(e)){this.path=e;this.identity=Hu("file",e),this.name=n}path;kind="file";[wo]="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");Bu(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-${Mu.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 Wu(n,a)},writeAt:async(a,o)=>{if(r)throw new Error("Cannot write to a closed FileWriter");qu(a),await Wu(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=Hu("directory",e),this.name=O.basename(e)}path;kind="directory";[wo]="directory";identity;name;async getFile(e){Gn(e);let n=new se(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){Gn(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 se(O.join(this.path,n.name),n.name))}async createFile(e){Gn(e),await B.mkdir(this.path,{recursive:!0});let n=new se(O.join(this.path,e));return await B.writeFile(n.path,"",{flag:"wx"}),n}async createDirectory(e){Gn(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){Gn(e),await B.rm(O.join(this.path,e),{force:!0,recursive:n?.recursive===!0})}};yo=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()})})}};wk={asyncContext:{create:()=>new Du.AsyncLocalStorage},database:{open:sk},lifecycle:{instanceId:`node-process:${fo.pid}`,isInstanceAlive:t=>{let e=/^node-process:(\d+)$/u.exec(t);if(e===null)return Promise.resolve(void 0);try{return fo.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=ho(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))},getFile:t=>{let e=ho(t,"file");return Promise.resolve(e===void 0?void 0:new se(e))},resolveLegacyDirectory:t=>{let e=ho(t,"directory");return Promise.resolve(e===void 0?void 0:new De(e))}},templates:{createEnvironment:t=>new ak(new go,t)},zip:{open:ck,write:hk}},go=class extends ok{#e;constructor(e){super(),this.#e=e}getSource(e){let n=pi(e),r=O.join(this.#e??kk(),n);return{noCache:!1,path:n,src:fi.readFileSync(r,"utf8")}}}});var Me=i(()=>{"use strict"});function Qu(t){return new TextEncoder().encode(t)}function xt(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 xk}from"@noble/hashes/legacy.js";import{sha256 as Ik,sha512 as Ek}from"@noble/hashes/sha2.js";function oe(t){let e=vk(t);return{update(n){return e.update(typeof n=="string"?Qu(n):n),this},digest(n){let r=e.digest();return n==="hex"?xt(r):r}}}function Bn(t){let e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),e}function Ze(){if(typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let t=Bn(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=xt(t);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function vk(t){switch(t){case"sha1":return xk.create();case"sha256":return Ik.create();case"sha512":return Ek.create()}}var F=i(()=>{"use strict";Ee()});var yi=i(()=>{"use strict";F()});var Vu=i(()=>{"use strict";y()});var Yu=i(()=>{"use strict";Vu()});var Zu=i(()=>{"use strict"});function Fe(t){return t instanceof Error}function en(t){let e=[],n=new Set,r=t;for(;r!==void 0&&!n.has(r);){if(n.add(r),r instanceof Error){el(e,Ak(r)),r=r.cause;continue}el(e,String(r));break}return e.join(": ")}function Ak(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&&Lk(n)?`${t.name} (${r})`:n===""?t.name:r===void 0?n:`${n} (${r})`}function Lk(t){return/(?:^|[\s:'"(=])\/(?:[^\s/]+\/)*[^\s/]+/u.test(t)||/(?:^|[\s:'"(=])[A-Za-z]:[\\/]/u.test(t)||/\bfile:\/\//iu.test(t)}function el(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 tl=i(()=>{"use strict";pe()});var nl=i(()=>{"use strict"});import{APICallError as tA}from"ai";var rl=i(()=>{"use strict";y()});var et=i(()=>{"use strict";y()});var It,Hn=i(()=>{"use strict";It=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 xo=i(()=>{"use strict";et()});var Io=i(()=>{"use strict"});var il=i(()=>{"use strict";y()});var Eo=i(()=>{"use strict"});import{generateText as TA,streamText as _A}from"ai";var ol=i(()=>{"use strict";Yu();Zu();tl();nl();rl();et();Fn();Hn();yi();pe();xo();Io();il();Eo()});var sl=i(()=>{"use strict";ol()});var Ro=i(()=>{"use strict";sl();xo();Io();Eo()});var Dk,Co,dl,tn=i(()=>{"use strict";Dk=Object.freeze(["serial-generation/editor-compress","serial-generation/editor-review","serial-generation/editor-review-guide","serial-generation/reader-choice","serial-generation/reader-extraction"]),Co=Object.freeze({compress:"serial-generation/editor-compress",review:"serial-generation/editor-review",reviewGuide:"serial-generation/editor-review-guide"}),dl=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 To=i(()=>{"use strict"});async function Fk(t){try{return await wt(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 Mk,N,_o,w=i(()=>{"use strict";y();pe();Mk=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 kt(e),o=r.mode==="readwrite"&&r.create&&n.trim()!==""&&await Fk(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 _o(s),r),await d.#o(`PRAGMA busy_timeout = ${Mk}`),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)}};_o=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 Et(){let t=R().library,e=bi.get(t.identity);if(e!==void 0){await e;return}let n=jk(t);bi.set(t.identity,n);try{await n}finally{bi.get(t.identity)===n&&bi.delete(t.identity)}}async function Ii(){let t=await J(R().library,"core.sqlite");if(t===void 0||await Ei(t))return 0;let e=await N.open(t,"",{mode:"readonly"});try{return await nn(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 jk(t){let e=await Ii();if(e>Po)throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`);let n=await H(t,"core.sqlite");if(e===0){await Si(n,Po);return}for(;e<Po;)switch(e){case 1:await cl(t),await Si(n,2),e=2;break;case 2:await cl(t),await Si(n,3),e=3;break;case 3:await Uk(n),await Si(n,4),e=4;break;default:throw new Error(`Unsupported Wiki Graph home schema version: ${e}.`)}}async function cl(t){await hl(t),await pl(t)}async function Uk(t){let e=R().library;await hl(e),await Bk(t),await pl(e)}async function Bk(t){let e=await N.open(t,"",{create:!1,mode:"readwrite"});try{if(!await nn(e,"libraries"))return;let n=await ki(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 Si(t,e){let n=await N.open(t,"",{create:!0,mode:"readwrite"});try{await n.execute(Gk),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",e,new Date().toISOString()])}finally{await n.close()}}async function
|
|
10
|
+
updated_at = excluded.updated_at`,["home",e,new Date().toISOString()])}finally{await n.close()}}async function pl(t){await $n(await t.getDirectory("cache"),["search-sessions.sqlite","continuation-cursors.sqlite","cache.sqlite"]);let e=await t.getDirectory("staging");await $n(e,["library","work"]),await wi(e,"staging.sqlite");let n=await t.getDirectory("tmp");await wi(n,"gc.sqlite"),await wi(n,"wikg-coordinator.sqlite"),await $n(n,["gc.last-run"]);let r=await t.getDirectory("jobs");await $n(r,["cache","work"]),await wi(r,"job.sqlite");let a=R().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:U(s)})}async function wi(t,e){await $n(t,[e,`${e}-wal`,`${e}-shm`])}async function $n(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:U(a)})}}async function hl(t){await ll(await J(t,"core.sqlite"),[["library_locks","Cannot upgrade home with active library locks."],["state_locks","Cannot upgrade home with active state locks."]]),await ll(await J(t,"tmp/gc.sqlite"),[["gc_locks","Cannot upgrade home with an active GC lock."]]),await qk(await J(t,"jobs/job.sqlite")),await ul(await J(t,"staging/staging.sqlite"),"legacy coordinator"),await ul(await J(t,"tmp/wikg-coordinator.sqlite"),"coordinator")}async function qk(t){if(t===void 0||await Ei(t))return;let e=await N.open(t,"",{mode:"readonly"});try{if(await nn(e,"build_worker_lease")){let n=await ki(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: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(
|
|
14
|
+
LIMIT 1`,[Date.now()-xi],()=>!0)===!0)throw Jn("Cannot upgrade home with an active build worker.")}}finally{await e.close()}}async function ul(t,e){if(t===void 0||await Ei(t))return;let n=await N.open(t,"",{mode:"readonly"});try{if(await nn(n,"archive_owners")){let r=await ki(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(ml(o.heartbeatAt))throw Jn(`Cannot upgrade home with active ${e} state.`);continue}let s=await A().lifecycle.isInstanceAlive(o.hostInstanceId);if(s===!0||s===void 0&&ml(o.heartbeatAt))throw Jn(`Cannot upgrade home with active ${e} state.`)}}for(let r of["entry_locks","entry_sqlite_leases","archive_commit_locks"]){if(!await nn(n,r)||!(await ki(n,r)).has("heartbeat_at"))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-xi],()=>!0)===!0)throw Jn(`Cannot upgrade home with active ${e} state.`)}}finally{await n.close()}}async function ll(t,e){if(t===void 0||await Ei(t))return;let n=await N.open(t,"",{mode:"readonly"});try{for(let[r,a]of e){if(!await nn(n,r))continue;if(await n.queryOne(`SELECT 1 AS active FROM ${r} WHERE heartbeat_at >= ? LIMIT 1`,[Date.now()-xi],()=>!0)===!0)throw Jn(a)}}finally{await n.close()}}function Jn(t){return new Q("home_upgrade_blocked",t)}function ml(t){return t!==void 0&&Date.now()-t<=xi}async function Ei(t){return await wt(t)}async function ki(t,e){return new Set(await t.queryAll(`PRAGMA table_info(${e})`,void 0,n=>E(n,"name")))}async function nn(t,e){return await t.queryOne("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",[e],()=>!0)===!0}var Po,xi,Gk,bi,vi=i(()=>{"use strict";y();pe();Z();w();Po=4,xi=300*1e3,Gk=`
|
|
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
|
-
`,K),b(g,K),
|
|
21
|
+
`,bi=new Map});async function X(t,e,n={create:!0,mode:"readwrite"}){await Et();let r=await H(R().library,t);return n.mode==="readonly"?await Kn(r,e,n):await Kn(r,e,n)}async function Kn(t,e,n={create:!0,mode:"readwrite"}){let r=await kt(t);return n.mode==="readonly"?await N.open(r,e,n):await N.open(r,e,n)}var fl=i(()=>{"use strict";y();vi();w()});function Ci(...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 Ao(t){return Ci(t).split("/").at(-1)??""}var vt=i(()=>{"use strict"});var zn=i(()=>{"use strict";vt()});var yl=i(()=>{"use strict"});function rn(t){let e=new Set(Object.values(t));return n=>e.has(n)}function Qn(t,e){let n=rn(t);return r=>{if(n(r))return r;throw new Error(`Unknown ${e}: ${r}`)}}var Lo=i(()=>{"use strict"});var he,gl,Oo,ve,bl,Ti,Re=i(()=>{"use strict";Lo();he=(a=>(a.Verbatim="verbatim",a.Detailed="detailed",a.Focused="focused",a.Relevant="relevant",a))(he||{}),gl=rn(he),Oo=Qn(he,"chunk retention"),ve=(r=>(r.Critical="critical",r.Important="important",r.Helpful="helpful",r))(ve||{}),bl=rn(ve),Ti=Qn(ve,"chunk importance")});var No=i(()=>{"use strict";Re()});function tt(t){let e=0,n=!1;for(let r of t.trim()){if(Hk.test(r)){e+=1,n=!1;continue}if($k.test(r)){n||(e+=1),n=!0;continue}n&&Jk.test(r)||(n=!1)}return e}var Hk,$k,Jk,nt=i(()=>{"use strict";Hk=new RegExp("\\p{Script=Han}","u"),$k=/[\p{Letter}\p{Number}]/u,Jk=new RegExp("\\p{Mark}","u")});var wl=i(()=>{"use strict";nt();Re()});var _i=i(()=>{"use strict"});var Do=i(()=>{"use strict";zn();Re();No();wl();_i()});var kl=i(()=>{"use strict";zn();yl();Do()});var Mo=i(()=>{"use strict";kl();No();Do();_i()});var Pi=i(()=>{"use strict";y();vt()});var Fo=i(()=>{"use strict"});var Il=i(()=>{"use strict";vt();Pi()});var El=i(()=>{"use strict";nt()});var Go=i(()=>{"use strict"});var jo=i(()=>{"use strict";vt();pe();Fo();Pi();Il();El();Go()});var vl=i(()=>{"use strict";vt();Pi();jo()});var Uo=i(()=>{"use strict";vl();Fo();jo();Go()});import{z as fe}from"zod";var Bo,Ge,Rl,qo,Xn=i(()=>{"use strict";Bo=["epub","pdf","txt","markdown"],Ge=1,Rl=fe.enum(Bo),qo=fe.object({version:fe.literal(Ge),sourceFormat:Rl,title:fe.string().min(1).nullable().default(null),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 Cl(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(ex.has(t))throw new Error(`Invalid ${e}: ${t} is reserved.`);return t}var ex,ye=i(()=>{"use strict";Ee();F();ex=new Set(["tree","source","summary","title","state","chunk","entity","triple","cover","meta","job","help"])});import{z as je}from"zod";var rt,Ho,Tl,$o=i(()=>{"use strict";ye();rt=1,Ho=je.object({key:je.string().min(1).transform(t=>Cl(t)).optional(),title:je.string().min(1).nullable().optional(),serialId:je.number().int().nonnegative().optional(),children:je.lazy(()=>je.array(Ho))}),Tl=je.object({version:je.literal(rt),items:je.array(Ho)})});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 tx(t){let[e]=t.split("#",1);return Ce(e??"")}function Jo(t){if(t===void 0)return;let e=t.startsWith("#")?t.slice(1):t;return e===""?void 0:e}function Vn(t){let[e,n]=t.split("#",2);return{path:Ce(e??""),fragment:Jo(n)}}function nx(t){return t.split("/").slice(0,-1).join("/")}function rx(...t){return t.filter(Boolean).join("/")}var Ai,Yn=i(()=>{"use strict";y();F();Ai=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=oe("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=tx(n);if(r==="")throw new Error(`Invalid EPUB href: ${n}`);return Ce(rx(nx(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:${oe("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 ix}from"htmlparser2";async function Nl(t,e){let n=new Map;for(let[r,a]of e.entries()){let o=await Wl(t,r),s=Dl(o,a);for(let d of a){let c=s.get(d.id)??"";n.set(d.id,{hasContent:c.trim()!=="",wordsCount:tt(c)})}}return n}function sx(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 Wl(t,e){return await t.readText(e)}function Dl(t,e){let n=Ml(t,e,!1);return new Map([...n.entries()].map(([r,a])=>[e[r].id,a.text]))}function dx(t,e,n){let r=Ml(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 Ml(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=ix(t,{decodeEntities:!0}),u=(c.children??[]).find(Al);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=ux(C);return[g,{segments:L.segments,text:L.text}]}));function m(g,C){if(Pl(g)){if(d<0||d>=o.length)return;let j=g.data??"";if(j==="")return;let ie=o[d],St=ie?.spineIndex;if(n&&St===void 0)throw new Error(`EPUB section ${ie?.id??"unknown"} cannot produce a CFI locator.`);let ci=n&&St!==void 0?Ol(St,C,0,j.length):Ko;f(d,j,ci,n?0:void 0,n?j.length:void 0);return}let L=px(g);if(L===void 0){b(g,C);return}if(ox.has(L))return;let K=C,q=g.attribs?.id??g.attribs?.["xml:id"];if(q!==void 0){let j=r.get(q);j!==void 0&&j>d&&(d=j)}L==="br"&&k(d,`
|
|
22
|
+
`,K),b(g,K),ax.has(L)&&k(d,`
|
|
23
23
|
|
|
24
|
-
`,K)}function b(g,C){let L=0,K=new Map;for(let q of g.children??[]){if(
|
|
25
|
-
`?(m+=1,
|
|
26
|
-
`,locator:
|
|
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=`
|
|
24
|
+
`,K)}function b(g,C){let L=0,K=new Map;for(let q of g.children??[]){if(Pl(q)){if(d<0||d>=o.length)continue;let ie=q.data??"";if(ie==="")continue;let St=L*2+1,ci=K.get(St)??0;K.set(St,ci+ie.length);let Vw=Ll(C,St,!0);v(q,Vw,ci,ie.length);continue}if(!Al(q))continue;let j=Ll(C,L,!1,q.attribs?.id??q.attribs?.["xml:id"]);L+=1,m(q,j)}}function v(g,C,L,K){if(d<0||d>=o.length)return;let q=g.data??"",j=o[d],ie=j?.spineIndex;if(n&&ie===void 0)throw new Error(`EPUB section ${j?.id??"unknown"} cannot produce a CFI locator.`);f(d,q,n&&ie!==void 0?Ol(ie,C,L,L+K):Ko,n?L:void 0,n?L+K:void 0)}function f(g,C,L,K,q){let j=a.get(g);j!==void 0&&j.push({locator:L,...q===void 0?{}:{locatorEnd:q},...K===void 0?{}:{locatorStart:K},text:C})}function k(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?fx(q,L):Ko)}}function cx(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 ux(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 v=u[b],f=c.locatorStart===void 0?void 0:c.locatorStart+m;m+=v.length;let k=c.locatorEnd===void 0||c.locatorStart===void 0?void 0:c.locatorStart+m;v==="\r"&&u[b+1]===`
|
|
25
|
+
`?(m+=1,k=c.locatorStart===void 0?void 0:c.locatorStart+m,e.push({baseLocator:c.locator,char:`
|
|
26
|
+
`,locator:zo(c.locator,f,k),locatorEnd:k,locatorStart:f}),b+=1):e.push({baseLocator:c.locator,char:v,locator:zo(c.locator,f,k),locatorEnd:k,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:zo(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 zo(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=lx(r);if(a===void 0)throw new Error("EPUB text mapping has an invalid CFI range locator.");return{...t,cfi:`epubcfi(${a.parentPath},${_l(a.startPath,e)},${_l(a.endPath,n)})`}}function lx(t){if(!t.startsWith("epubcfi(")||!t.endsWith(")"))return;let e=mx(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 mx(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 _l(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 px(t){return t.name?.toLowerCase()}function Pl(t){return t.type==="text"}function Al(t){return t.name!==void 0&&t.type!=="directive"}function Ll(t,e,n,r){let a=n?e:(e+1)*2,o=n||r===void 0?"":`[${gx(r)}]`;return`${t}/${a}${o}`}function Ol(t,e,n,r){let a=Fl(t),{parentPath:o,textPath:s}=hx(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 hx(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 fx(t,e){return{cfi:`epubcfi(${yx(t)}${e})`}}function yx(t){return`${Fl(t)}!`}function Fl(t){return`/6/${(t+1)*2}`}function gx(t){return[...t].map(e=>"[]^(),;=".includes(e)?`^${e}`:e).join("")}var ax,ox,Ko,Li,Gl=i(()=>{"use strict";nt();ax=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"]),ox=new Set(["script","style"]),Ko={},Li=class{#e;#t;constructor(e,n){this.#e=e,this.#t=sx(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=dx(o,r.targets,e),d=cx(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 Wl(this.#e,e);return Dl(r,n)}}});import{SaxesParser as bx}from"saxes";function an(t){let e=new bx({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 jl(r)}function ge(t,e){return t.children.find(n=>er(n.name)===e)}function Ue(t,e){return t.children.filter(n=>er(n.name)===e)}function ee(t,e){return t.attributes[e]}function Zn(t){let e=t.text;for(let n of t.children)e+=Zn(n);return e}function er(t){let e=t.indexOf(":");return e===-1?t:t.slice(e+1)}function jl(t){return{name:t.name,attributes:Object.freeze({...t.attributes}),children:Object.freeze(t.children.map(jl)),text:t.text}}var Oi=i(()=>{"use strict"});async function Bl(t){let e=await kx(t),n=an(await t.readText(e)),r=xx(ee(n,"version")),a=ge(n,"metadata"),o=ge(n,"manifest"),s=ge(n,"spine"),d=ge(n,"guide"),c=Ex(t,e,o),u=new Map([...c.values()].map(C=>[C.path,C])),m=vx(s,c),b=Rx(t,e,d),v=Ix(a),f=Cx(c),k=Tx(c,s),g=_x(c,a);return{version:r,opfPath:e,metadata:{...v,version:Ge,sourceFormat:"epub"},manifest:c,manifestByPath:u,spine:m,navPath:f,ncxPath:k,coverPath:g?.path,coverMediaType:g?.mediaType,guideNonContentPaths:b}}async function kx(t){let e=an(await t.readText("META-INF/container.xml")),r=ge(e,"rootfiles")?.children.find(o=>er(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 xx(t){return t?.trim().startsWith("3")===!0?3:2}function Ix(t){if(t===void 0)return Ul();let e=Rt(t,"title"),n=Rt(t,"creator"),r=Rt(t,"language"),a=Rt(t,"identifier"),o=Rt(t,"publisher"),s=Rt(t,"date"),d=Rt(t,"description");return{...Ul(),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 Ul(){return{version:Ge,sourceFormat:"epub",title:null,authors:[],language:null,identifier:null,publisher:null,publishedAt:null,description:null}}function Rt(t,e){return t.children.filter(n=>er(n.name)===e).map(n=>Ax(Zn(n))).filter(n=>n!==void 0)}function Ex(t,e,n){let r=new Map;if(n===void 0)return r;for(let a of Ue(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 vx(t,e){return t===void 0?[]:Ue(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 Rx(t,e,n){let r=new Set;if(n===void 0)return r;for(let a of Ue(n,"reference")){let o=(ee(a,"type")??"").trim().toLowerCase();if(!wx.has(o))continue;let s=ee(a,"href");s===void 0||s.trim()===""||r.add(t.resolveRelativePath(e,Vn(s).path))}return r}function Cx(t){for(let e of t.values())if(e.properties.has("nav"))return e.path}function Tx(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 _x(t,e){for(let r of t.values())if(r.properties.has("cover-image")&&r.mediaType.startsWith("image/"))return r;let n=Px(e);if(n!==void 0){let r=t.get(n);if(r?.mediaType.startsWith("image/")===!0)return r}for(let r of Sx){let a=t.get(r);if(a?.mediaType.startsWith("image/")===!0)return a}for(let r of t.values())if(r.mediaType.startsWith("image/")&&Ao(r.path).toLowerCase().includes("cover"))return r}function Px(t){if(t!==void 0)for(let e of Ue(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 Ax(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Sx,wx,Qo=i(()=>{"use strict";vt();Xn();Yn();Oi();Sx=["cover-image","coverimg","cover-img","cover"],wx=new Set(["cover","titlepage","other.titlepage"])});import{parseDocument as Lx}from"htmlparser2";async function Hl(t,e){let n=await Nx(t,e)??await Wx(t,e)??[];if(n.length===0)return ql(e,new Set);let r=Kl(n),a=ql(e,r);return a.length===0?n:[...n,...a]}async function Nx(t,e){if(e.navPath===void 0)return;let n=Lx(await t.readText(e.navPath),{decodeEntities:!0}),r=Xo(n,s=>it(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=Xo(r,s=>it(s)==="ol");if(a===void 0)return;let o=tr(a).filter(s=>it(s)==="li").map(s=>$l(t,e.navPath,s)).filter(s=>s!==void 0);return o.length===0?void 0:o}async function Wx(t,e){if(e.ncxPath===void 0)return;let n=an(await t.readText(e.ncxPath)),r=ge(n,"navMap");if(r===void 0)return;let a=Ue(r,"navPoint").map(o=>Jl(t,e.ncxPath,o)).filter(o=>o!==void 0);return a.length===0?void 0:a}function $l(t,e,n){let r=zl(n),a=r===void 0?void 0:Vl(Ql(r)),o=r!==void 0&&it(r)==="a"?r.attribs?.href:void 0,s=Mx(t,e,o),d=tr(n).filter(c=>it(c)==="ol").flatMap(c=>tr(c)).filter(c=>it(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 Jl(t,e,n){let r=ge(n,"navLabel"),a=r===void 0?void 0:ge(r,"text"),o=a===void 0?void 0:Vl(Zn(a)),s=ge(n,"content"),d=Fx(t,e,ee(s??n,"src")),c=Ue(n,"navPoint").map(u=>Jl(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 ql(t,e){return t.spine.filter(n=>!Dx(t,n.path,e)).filter(n=>!e.has(n.path)).map(n=>({title:Gx(n.path),path:n.path,fragment:void 0,children:[]}))}function Dx(t,e,n){if(t.guideNonContentPaths.has(e))return!0;let r=Vo(e).toLowerCase();return t.navPath===e?!0:Ox.has(r)&&!n.has(e)}function Kl(t){let e=new Set;for(let n of t){n.path!==void 0&&e.add(n.path);for(let r of Kl(n.children))e.add(r)}return e}function Mx(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Vn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function Fx(t,e,n){if(n===void 0||n.trim()==="")return{path:void 0,fragment:void 0};let{path:r,fragment:a}=Vn(n);return{path:r===""?void 0:t.resolveRelativePath(e,r),fragment:a}}function Xo(t,e){if(Xl(t)&&e(t))return t;for(let n of t.children??[]){let r=Xo(n,e);if(r!==void 0)return r}}function zl(t){for(let e of tr(t)){let n=it(e);if(n==="a"||n==="span")return e}for(let e of tr(t)){if(it(e)==="ol")continue;let n=zl(e);if(n!==void 0)return n}}function Ql(t){return t.type==="text"?t.data??"":(t.children??[]).map(Ql).join("")}function tr(t){return(t.children??[]).filter(Xl)}function Xl(t){return t.type==="tag"||t.type==="script"||t.type==="style"}function it(t){return t.name?.toLowerCase()}function Gx(t){let e=jx(t),n=Vo(t).slice(0,-e.length||void 0).trim();return n===""?void 0:n}function Vo(t){return t.replaceAll("\\","/").split("/").at(-1)??""}function jx(t){let e=Vo(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n)}function Vl(t){let e=t.replace(/\s+/gu," ").trim();return e===""?void 0:e}var Ox,Yl=i(()=>{"use strict";Yn();Qo();Oi();Ox=new Set(["toc.xhtml","nav.xhtml","contents.xhtml","tableofcontents.xhtml","cover.xhtml","titlepage.xhtml"])});function Ux(t){if(t.hasEntry("META-INF/encryption.xml"))throw new Error("Encrypted EPUB is not supported: found META-INF/encryption.xml.")}async function Bx(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 qx(t,e){let n=new Map;return e.map((r,a)=>Zl(t,r,[a],n))}function Zl(t,e,n,r){let a=Jo(e.fragment),o=e.path===void 0?`toc:${n.join(".")}`:t.createSectionId(e.path,a),s=Hx(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)=>Zl(t,d,[...n,c],r))}}function em(t,e){return t.map(n=>{let r=e.get(n.id);return{...n,hasContent:r?.hasContent??!1,wordsCount:r?.wordsCount??0,children:em(n.children,e)}})}function Hx(t,e){let n=e.get(t)??0;return e.set(t,n+1),n===0?t:`${t}~${n+1}`}function $x(t,e){let n=new Map,r=new Map(e.spine.map(a=>[a.path,a.spineIndex]));for(let a of tm(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 tm(t){let e=[];for(let n of t)e.push(n),e.push(...tm(n.children));return e}var Yo,Zo,nr,es,nm=i(()=>{"use strict";Yn();Yn();Gl();Yl();Qo();Yo=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)}},Zo=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){Ux(e);let n=await Bl(e),r={digest:e.digest,mediaType:"application/epub+zip",name:e.name,...n.metadata.identifier===null?{}:{identifier:n.metadata.identifier}},a=await Hl(e,n),o=qx(e,a),s=$x(o,n),d=await Nl(e,s),c=em(o,d),u=await Bx(e,n);return new t(r,n,u,c,new Li(e,s))}readMeta(){return Promise.resolve(this.#t.metadata)}readCover(){return Promise.resolve(this.#n)}readSections(){return Promise.resolve(this.#r.map(e=>new Yo(this,e)))}async openSection(e){return await this.#i.openSection(e)}async openSectionWithProvenance(e){return await this.#i.openSectionWithProvenance(e,this.#e)}},nr=class{get format(){return"epub"}async openSession(e,n){let r=await Ai.open(e);try{let a=await Zo.open(r);return await n(a)}finally{await r.close()}}},es=new nr});var rm=i(()=>{"use strict";nm()});var im=i(()=>{"use strict";y()});import{SaxesParser as pN}from"saxes";var am=i(()=>{"use strict";nt();Oi();im()});var sm=i(()=>{"use strict";am()});async function*Kx(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 zx(t){let e=t.lastIndexOf("."),n=(e<=0?t:t.slice(0,e)).trim();return n===""?null:n}var Jx,ts,ns,rr,dm,cm,um=i(()=>{"use strict";Xn();Jx="root",ts=class{#e;#t;constructor(e,n=Jx){this.#e=e,this.#t=n}get id(){return this.#t}get hasContent(){return!0}get title(){}get children(){return[]}open(){return Promise.resolve(Kx(this.#e))}},ns=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,this.#e=new ts(e)}readMeta(){return Promise.resolve({version:Ge,sourceFormat:this.#n,title:zx(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])}},rr=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 ns(e,this.#e))}},dm=new rr("txt"),cm=new rr("markdown")});var ir=i(()=>{"use strict"});import{z as ue}from"zod";var vN,RN,lm=i(()=>{"use strict";ir();vN=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()}),RN=ue.object({type:ue.literal("text"),text:ue.string(),locator:ue.record(ue.string(),ue.unknown())})});var at=i(()=>{"use strict";Xn();rm();sm();um();lm();$o()});var is=i(()=>{"use strict"});var ar=i(()=>{"use strict";at();ye();is();Z()});var Qx,pm,hm,fm,or=i(()=>{"use strict";w();ir();Qx=`
|
|
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 Aw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Lw=(t,e)=>{f
|
|
|
34
34
|
media_type TEXT NOT NULL,
|
|
35
35
|
name TEXT,
|
|
36
36
|
identifier TEXT
|
|
37
|
-
`,
|
|
37
|
+
`,pm=`
|
|
38
38
|
CREATE TABLE IF NOT EXISTS serials (
|
|
39
39
|
id INTEGER PRIMARY KEY,
|
|
40
40
|
document_order INTEGER NOT NULL DEFAULT 0
|
|
@@ -330,7 +330,7 @@ var Aw=Object.defineProperty;var i=(t,e)=>()=>(t&&(e=t(t=0)),e);var Lw=(t,e)=>{f
|
|
|
330
330
|
ON text_sentence_records(kind, chapter_id, sentence_index);
|
|
331
331
|
|
|
332
332
|
CREATE TABLE IF NOT EXISTS source_artifacts (
|
|
333
|
-
${
|
|
333
|
+
${Qx}
|
|
334
334
|
);
|
|
335
335
|
|
|
336
336
|
CREATE TABLE IF NOT EXISTS source_locators (
|
|
@@ -396,7 +396,7 @@ ${Tk}
|
|
|
396
396
|
triple_predicate,
|
|
397
397
|
triple_object_qid
|
|
398
398
|
);
|
|
399
|
-
`,
|
|
399
|
+
`,hm=`
|
|
400
400
|
id INTEGER PRIMARY KEY,
|
|
401
401
|
archive_id INTEGER NOT NULL,
|
|
402
402
|
kind INTEGER NOT NULL,
|
|
@@ -406,14 +406,14 @@ ${Tk}
|
|
|
406
406
|
byte_offset INTEGER NOT NULL DEFAULT 0,
|
|
407
407
|
byte_length INTEGER NOT NULL DEFAULT 0,
|
|
408
408
|
UNIQUE(archive_id, kind, chapter_id, sentence_index)
|
|
409
|
-
`,
|
|
409
|
+
`,fm=`
|
|
410
410
|
CREATE TABLE IF NOT EXISTS search_index_state (
|
|
411
411
|
key TEXT PRIMARY KEY,
|
|
412
412
|
value TEXT NOT NULL
|
|
413
413
|
);
|
|
414
414
|
|
|
415
415
|
CREATE TABLE IF NOT EXISTS text_sentence_records (
|
|
416
|
-
${
|
|
416
|
+
${hm}
|
|
417
417
|
);
|
|
418
418
|
|
|
419
419
|
CREATE INDEX IF NOT EXISTS idx_text_sentence_records_chapter
|
|
@@ -470,22 +470,22 @@ ${Yl}
|
|
|
470
470
|
updated_at INTEGER NOT NULL,
|
|
471
471
|
PRIMARY KEY (archive_id, chapter_id)
|
|
472
472
|
);
|
|
473
|
-
`});var
|
|
473
|
+
`});var Ct=i(()=>{"use strict";w();Re()});var ym=i(()=>{"use strict";w();Ct()});var gm=i(()=>{"use strict";w()});var bm=i(()=>{"use strict";w();yi()});var Sm=i(()=>{"use strict";w();Re()});var wm=i(()=>{"use strict";w();Ct()});var km=i(()=>{"use strict";w();Ct()});var xm=i(()=>{"use strict";w();Ct()});var Im=i(()=>{"use strict";w();Ct()});var Em=i(()=>{"use strict";w();Ct()});var Cm=i(()=>{"use strict";Ee();w();ir()});var Tm=i(()=>{"use strict";w()});var _m=i(()=>{"use strict";w()});var Pm=i(()=>{"use strict";w()});var Am=i(()=>{"use strict";Tm();_m();Pm()});var ds=i(()=>{"use strict";ym();gm();bm();Sm();wm();km();xm();Im();Em();Cm();Am()});var cs=i(()=>{"use strict"});var $m=i(()=>{"use strict";y()});var Jm=i(()=>{"use strict";pe();zn()});var Tt=i(()=>{"use strict"});var Km=i(()=>{"use strict";y();w();or();Tt()});var zm=i(()=>{"use strict";pe();cs()});var Qm=i(()=>{"use strict"});import{z as us}from"zod";var iM,Vm=i(()=>{"use strict";y();Xn();$o();ar();w();Mo();or();ds();Re();cs();$m();Jm();Km();zn();zm();Qm();iM=us.object({mediaType:us.string().min(1),path:us.string()})});var Ym=i(()=>{"use strict"});var ms=i(()=>{"use strict";Vm();Ym()});var ep=i(()=>{"use strict";Uo()});var _=i(()=>{"use strict";w();fl();Mo();Uo();ms();ep();or();ir();ds();Re()});var hs=i(()=>{"use strict"});var qe=i(()=>{"use strict";hs()});async function ip(t){let e=await nI(t);try{return await tI(e,t),await e.queryOne(`
|
|
474
474
|
SELECT 1 AS active
|
|
475
475
|
FROM state_locks
|
|
476
476
|
WHERE scope = ? AND resource_key = ?
|
|
477
477
|
LIMIT 1
|
|
478
|
-
`,[t.scope,t.resourceKey],()=>!0)===!0}finally{await e.close()}}async function
|
|
478
|
+
`,[t.scope,t.resourceKey],()=>!0)===!0}finally{await e.close()}}async function tI(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(`
|
|
479
479
|
SELECT scope, resource_key, mode, owner_id, owner_pid, heartbeat_at
|
|
480
480
|
FROM state_locks
|
|
481
481
|
${n.length===0?"":`WHERE ${n.join(" AND ")}`}
|
|
482
|
-
`,r,o=>({lock:
|
|
482
|
+
`,r,o=>({lock:rI(o),resourceKey:E(o,"resource_key"),scope:E(o,"scope")}));for(let{lock:o,resourceKey:s,scope:d}of a)aI(o,e.staleMs)&&await t.run(`
|
|
483
483
|
DELETE FROM state_locks
|
|
484
484
|
WHERE scope = ?
|
|
485
485
|
AND resource_key = ?
|
|
486
486
|
AND owner_id = ?
|
|
487
487
|
AND heartbeat_at = ?
|
|
488
|
-
`,[d,s,o.ownerId,o.heartbeatAt])}async function
|
|
488
|
+
`,[d,s,o.ownerId,o.heartbeatAt])}async function nI(t){if(t.databaseFile!==void 0)return await N.open(t.databaseFile,rp,{create:!0,mode:"readwrite"});if(t.stateDatabaseName!==void 0)return await X(t.stateDatabaseName,rp);throw new Error("State lock requires a database File or state database name.")}function rI(t){return{heartbeatAt:S(t,"heartbeat_at"),mode:iI(E(t,"mode")),ownerId:E(t,"owner_id")}}function iI(t){return t==="read"||t==="write"?t:"write"}function aI(t,e=eI){return Date.now()-t.heartbeatAt>e}var rp,eI,Ni=i(()=>{"use strict";F();w();_();rp=`
|
|
489
489
|
CREATE TABLE IF NOT EXISTS state_locks (
|
|
490
490
|
scope TEXT NOT NULL,
|
|
491
491
|
resource_key TEXT NOT NULL,
|
|
@@ -499,7 +499,7 @@ ${Yl}
|
|
|
499
499
|
|
|
500
500
|
CREATE INDEX IF NOT EXISTS idx_state_locks_resource
|
|
501
501
|
ON state_locks(scope, resource_key);
|
|
502
|
-
`,
|
|
502
|
+
`,eI=300*1e3});async function sp(t){return await ip({stateDatabaseName:"core.sqlite",resourceKey:dI(t),scope:sI,staleMs:op})||await cI(t)}function dI(t){return String(t)}async function cI(t){let e=await uI();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&&mI(n)}finally{await e.close()}}async function uI(){let t=await X("core.sqlite",oI);return await lI(t),t}async function lI(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 mI(t){return Date.now()-t.heartbeatAt<=op}var oI,sI,op,_t=i(()=>{"use strict";w();_();Ni();oI=`
|
|
503
503
|
CREATE TABLE IF NOT EXISTS library_locks (
|
|
504
504
|
library_id INTEGER PRIMARY KEY,
|
|
505
505
|
mode TEXT NOT NULL,
|
|
@@ -508,8 +508,7 @@ ${Yl}
|
|
|
508
508
|
heartbeat_at INTEGER NOT NULL,
|
|
509
509
|
created_at INTEGER NOT NULL
|
|
510
510
|
);
|
|
511
|
-
`,
|
|
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
|
+
`,sI="library",op=300*1e3});var qM,Lt=i(()=>{"use strict";y();w();_();qe();Ee();F();_t();hs();qM=Promise.resolve()});var $M,dr=i(()=>{"use strict";$M=new RegExp("\\p{Script=Han}","u")});var ys=i(()=>{"use strict";Ee()});var gs,Ot=i(()=>{"use strict";gs=`
|
|
513
512
|
CREATE TABLE IF NOT EXISTS search_sessions (
|
|
514
513
|
session_id TEXT PRIMARY KEY,
|
|
515
514
|
archive_key TEXT NOT NULL,
|
|
@@ -613,72 +612,31 @@ ON search_sessions(expires_at);
|
|
|
613
612
|
|
|
614
613
|
CREATE INDEX IF NOT EXISTS idx_search_sessions_prune
|
|
615
614
|
ON search_sessions(accessed_at DESC, created_at DESC, session_id);
|
|
616
|
-
`});async function
|
|
615
|
+
`});async function on(){let t=await X("cache/search-sessions.sqlite",gs);return bs?t:await hI(t)?(bs=!0,t):(await pI(t),bs=!0,t)}async function pI(t){await t.execute(`
|
|
617
616
|
DROP TABLE IF EXISTS search_evidence_hit_events;
|
|
618
617
|
DROP TABLE IF EXISTS search_triple_hits;
|
|
619
618
|
DROP TABLE IF EXISTS search_entity_hits;
|
|
620
619
|
DROP TABLE IF EXISTS search_chunk_hits;
|
|
621
620
|
DROP TABLE IF EXISTS search_sessions;
|
|
622
|
-
${
|
|
623
|
-
`)}async function
|
|
621
|
+
${gs}
|
|
622
|
+
`)}async function hI(t){return await Wi(t,"search_entity_hits","archive_id")&&await Wi(t,"search_chunk_hits","archive_id")&&await Wi(t,"search_triple_hits","archive_id")&&await Wi(t,"search_evidence_hit_events","archive_id")}async function Wi(t,e,n){return(await t.queryAll(`PRAGMA table_info(${e})`,void 0,a=>String(a.name))).includes(n)}var bs,sn=i(()=>{"use strict";_();Ot();bs=!1});var Di=i(()=>{"use strict"});async function up(t,e){await lp(t,e),await t.run("DELETE FROM search_sessions WHERE session_id = ?",[e])}async function lp(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 mp(t){await t.run(`
|
|
624
623
|
DELETE FROM predicate_dictionary
|
|
625
624
|
WHERE NOT EXISTS (
|
|
626
625
|
SELECT 1
|
|
627
626
|
FROM search_triple_hits
|
|
628
627
|
WHERE search_triple_hits.predicate_id = predicate_dictionary.id
|
|
629
628
|
)
|
|
630
|
-
`)}var
|
|
629
|
+
`)}var Ss=i(()=>{"use strict";w();sn();Di();Ot()});async function Mi(t){let e=await on();try{let n=await pp(e),r=await e.queryOne("SELECT COUNT(*) AS count FROM search_sessions",void 0,c=>S(c,"count")),a=t.force?await bI(e):await gI(e,t.now),o=t.force?[]:await SI(e),s=[...new Set([...a,...o])].sort();!t.dryRun&&s.length>0&&(await e.transaction(async()=>{for(let c of s)await up(e,c);await mp(e)}),await e.run("VACUUM"));let d=await pp(e);return{freedBytes:Math.max(0,n-d),removed:s.length,scanned:r??0}}finally{await e.close()}}async function gI(t,e){return await t.queryAll(`
|
|
631
630
|
SELECT session_id
|
|
632
631
|
FROM search_sessions
|
|
633
632
|
WHERE expires_at < ?
|
|
634
|
-
`,[e],n=>E(n,"session_id"))}async function
|
|
633
|
+
`,[e],n=>E(n,"session_id"))}async function bI(t){return await t.queryAll("SELECT session_id FROM search_sessions",void 0,e=>E(e,"session_id"))}async function SI(t){return await t.queryAll(`
|
|
635
634
|
SELECT session_id
|
|
636
635
|
FROM search_sessions
|
|
637
636
|
ORDER BY accessed_at DESC, created_at DESC, session_id
|
|
638
637
|
LIMIT -1 OFFSET ?
|
|
639
|
-
`,[500],e=>E(e,"session_id"))}async function
|
|
640
|
-
|
|
641
|
-
library_id INTEGER NOT NULL,
|
|
642
|
-
public_id TEXT NOT NULL,
|
|
643
|
-
relative_path TEXT NOT NULL,
|
|
644
|
-
status TEXT NOT NULL DEFAULT 'present',
|
|
645
|
-
last_seen_mutation_token TEXT,
|
|
646
|
-
last_seen_size INTEGER,
|
|
647
|
-
last_seen_mtime_ms INTEGER,
|
|
648
|
-
last_scanned_at TEXT,
|
|
649
|
-
created_at TEXT NOT NULL,
|
|
650
|
-
updated_at TEXT NOT NULL,
|
|
651
|
-
UNIQUE(library_id, public_id)
|
|
652
|
-
`,Dz=`
|
|
653
|
-
CREATE TABLE IF NOT EXISTS library_archives (
|
|
654
|
-
${EE}
|
|
655
|
-
);
|
|
656
|
-
|
|
657
|
-
CREATE INDEX IF NOT EXISTS idx_library_archives_library
|
|
658
|
-
ON library_archives(library_id);
|
|
659
|
-
|
|
660
|
-
CREATE INDEX IF NOT EXISTS idx_library_archives_library_path
|
|
661
|
-
ON library_archives(library_id, relative_path);
|
|
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:
|
|
667
|
-
${o}
|
|
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=`
|
|
638
|
+
`,[500],e=>E(e,"session_id"))}async function pp(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 hp=i(()=>{"use strict";w();sn();Ot();Ss()});var fp=i(()=>{"use strict";Ot()});var ws=i(()=>{"use strict"});var Fi=i(()=>{"use strict";w();sn();Di();fp();ws()});var gp=i(()=>{"use strict";F();Ot()});var bp=i(()=>{"use strict";w();ys();sn();Fi();gp();Di();Ot();Ss()});var Sp=i(()=>{"use strict";w();sn();Fi()});var Wt=i(()=>{"use strict";ys();hp();Fi();bp();Sp();ws()});var Gi=i(()=>{"use strict"});var ji=i(()=>{"use strict";at()});var xs=i(()=>{"use strict";Ee()});var Ui=i(()=>{"use strict"});var Is=i(()=>{"use strict";Ui()});var Es=i(()=>{"use strict";Ui()});var Bi=i(()=>{"use strict";Gi();xs();Is();Es()});var Lp=i(()=>{"use strict";qe()});var Op=i(()=>{"use strict";Gi();ji();xs();Ui();Bi();Is();Es();Lp()});var W=i(()=>{"use strict";Op()});var Rs=i(()=>{"use strict"});var Cs=i(()=>{"use strict";Z();ar();is();Rs()});var Np=i(()=>{"use strict";Cs()});var Y=i(()=>{"use strict";Cs();Np();Rs()});var uj,lj,Dt=i(()=>{"use strict";F();uj=new RegExp("\\p{Script=Han}+","gu"),lj=new RegExp("^\\p{Script=Han}+$","u")});var qi=i(()=>{"use strict";F()});var Ps=i(()=>{"use strict";Tt()});var Hi=i(()=>{"use strict";w();Ps()});var Mp=i(()=>{"use strict";Dt();qi();Hi();Tt()});var Gp=i(()=>{"use strict";Tt()});var jp=i(()=>{"use strict";Dt()});var Up=i(()=>{"use strict"});var Ws=i(()=>{"use strict";w();Up();qi()});var qp=i(()=>{"use strict";w();Dt();jp();Ps();Tt();Ws();Hi()});var Hp=i(()=>{"use strict";Mp();Gp();qi();qp();Ws();Tt();Hi()});var $e=i(()=>{"use strict";Hp();Dt()});var Mt=i(()=>{"use strict";Y();$e();Dt();ji()});var ne=i(()=>{"use strict";ye();qe();W()});var Se=i(()=>{"use strict";qe();W()});var Te=i(()=>{"use strict";Y();nt();W();ne()});var Pe=i(()=>{"use strict";Y();$e();W();ne();Se();Te();W();Mt()});var mn=i(()=>{"use strict";Wt();$e();Pe();Se()});var Bs=i(()=>{"use strict";Y();dr();W();ne();Te();Se()});var hr=i(()=>{"use strict";Z()});var Ae=i(()=>{"use strict";Y();hr();W();ne();Te()});var Qi=i(()=>{"use strict"});var fr=i(()=>{"use strict"});var yr=i(()=>{"use strict";Te();Ae()});var qs=i(()=>{"use strict";W();Ae();fr();yr()});var rh=i(()=>{"use strict";$e();Mt();W();Pe();Qi();Ae();fr();qs();yr();yr();fr()});var ih=i(()=>{"use strict";rh();qs();fr();yr()});var br=i(()=>{"use strict";ih()});var oh=i(()=>{"use strict";Wt();W();ne();Te();Ae();Se();br()});var Sr=i(()=>{"use strict";ne();Ae();W();Se();br();oh()});var Js=i(()=>{"use strict";Y();W();ne();Te();Ae();Sr();wr();Se()});var wr=i(()=>{"use strict";W();ne();Te();Se();Js()});var Zi=i(()=>{"use strict";W();Pe();Se()});var ea=i(()=>{"use strict";W();$e()});var ta=i(()=>{"use strict";Y();dr();Wt();$e();W();mn();Bs();Sr();wr();Pe();Zi();ea()});var hn=i(()=>{"use strict";$e()});var ph=i(()=>{"use strict";dr();Wt();W();Mt();mn();Bs();Sr();wr();ta();Pe();hn()});var hh=i(()=>{"use strict";ph();Zi();ea();ta();mn();Pe()});var na=i(()=>{"use strict";Ae();br();ne()});var kr=i(()=>{"use strict";W()});var ra=i(()=>{"use strict";W();Mt();ne();Pe();mn();$e();kr()});var Qs=i(()=>{"use strict";W();Se();na();ra();kr()});var Xs=i(()=>{"use strict"});var gh=i(()=>{"use strict";hr();W();Ae();na();Qs();ra();kr();Xs();ne();Qi()});var oa=i(()=>{"use strict";gh();Qs();na();ra();kr();Xs()});var Vs=i(()=>{"use strict";_();qe();Y();hr();W();Ae();br();wr();Se();oa();ne();Te()});var bh=i(()=>{"use strict";_();Y();ye();qe();Ee();W();Te()});var Sh=i(()=>{"use strict";Vs();oa();ne()});var rd=i(()=>{"use strict";hh();Vs();oa();Mt();ne();Js();Sr();bh();Sh()});var xh=i(()=>{"use strict";rd()});var EE,Ih=i(()=>{"use strict";Ee();F();w();_();EE=10080*60*1e3});var Eh=i(()=>{"use strict"});var vh=i(()=>{"use strict";w();Ih();Eh()});var Rh=i(()=>{"use strict"});var Ch=i(()=>{"use strict";vh();Rh()});var ct=i(()=>{"use strict";xh();Ch();Wt()});var Je=i(()=>{"use strict"});var ut=i(()=>{"use strict";Je()});import{z as dd}from"zod";var Tr,ua,cd,f1,lt=i(()=>{"use strict";Je();Tr=1,ua=5,cd=`${JSON.stringify({formatVersion:Tr,schemaVersion:ua})}
|
|
639
|
+
`,f1=dd.object({formatVersion:dd.literal(Tr),schemaVersion:dd.number().int().positive().optional()})});var Oh=i(()=>{"use strict";y();ut();Je();lt()});var la=i(()=>{"use strict";y();Je();lt();ut()});var Nh=i(()=>{"use strict";Je()});var Dh=i(()=>{"use strict";y();Je();Nh();lt();ut()});var jh=i(()=>{"use strict";Oh();la();lt();Dh()});var Kh=i(()=>{"use strict";qe()});var zh=i(()=>{"use strict";Z()});var ga=i(()=>{"use strict"});var Ar=i(()=>{"use strict";To();Fn()});var hd=i(()=>{"use strict";y();ga();Ar()});var Qh=i(()=>{"use strict";Ar()});var Xh=i(()=>{"use strict";ga();Ar()});var fd=i(()=>{"use strict";Ar()});var Vh=i(()=>{"use strict";hd();Qh();Xh();fd();ga();Z()});var Yh=i(()=>{"use strict";hd();Vh();fd()});var Zh=i(()=>{"use strict";zh();Yh()});var ba=i(()=>{"use strict";Z();y();Zh();Le()});var mt=i(()=>{"use strict"});var $J,Lr=i(()=>{"use strict";y();w();Hn();mt();$J=new It(1)});var gd=i(()=>{"use strict";w();F();mt();Lr()});var Sa=i(()=>{"use strict";y();F()});var bd=i(()=>{"use strict";F();Lr();Sa()});var kd=i(()=>{"use strict";y();lt();Je();ut();la();mt();gd();bd();Lr()});var af=i(()=>{"use strict";mt();ut()});var xd=i(()=>{"use strict";y();F();Lr()});var Id=i(()=>{"use strict";y();F();la();lt();ut();mt();kd();af();gd();xd();bd();Sa()});var of=i(()=>{"use strict";F();Id();kd();xd();mt()});async function wa(t){let e=R().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(!U(d)||!d.name.startsWith(".wikg-session-"))continue;n+=1;let c=await Ye(d);!t.force&&(c===void 0||t.now-c<$E)||(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())U(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 $E,sf=i(()=>{"use strict";y();pe();$E=3600*1e3});var df=i(()=>{"use strict";w();y();F();mt();Sa()});var vd=i(()=>{"use strict";of();Id();sf();df()});var Rd=i(()=>{"use strict";vd()});var cf=i(()=>{"use strict";_();ba();ct();Rd()});var Le=i(()=>{"use strict";jh();Kh();cf();Rd()});var Td,_d=i(()=>{"use strict";Td=["queued","running","canceling","paused","succeeded","failed","canceled"]});async function uf(){return await z(R().library,"jobs/work")}async function lf(t){let e=await R().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 Or=i(()=>{"use strict";y()});var Nr=i(()=>{"use strict";F()});var Pd=i(()=>{"use strict"});var Wr=i(()=>{"use strict";y()});var mf,pf=i(()=>{"use strict";mf=`
|
|
682
640
|
CREATE TABLE IF NOT EXISTS build_jobs (
|
|
683
641
|
job_id TEXT PRIMARY KEY,
|
|
684
642
|
archive_key TEXT NOT NULL,
|
|
@@ -737,7 +695,7 @@ CREATE TABLE IF NOT EXISTS build_worker_lease (
|
|
|
737
695
|
|
|
738
696
|
INSERT OR IGNORE INTO build_worker_lease (id)
|
|
739
697
|
VALUES (1);
|
|
740
|
-
`});function
|
|
698
|
+
`});function Ut(t){let e=VE(jt(t,"current_step"),"current_step"),n=jt(t,"owner_id"),r=t.owner_pid===null?void 0:ce(t,"owner_pid"),a=t.reading_summary_started_at===null?void 0:ce(t,"reading_summary_started_at"),o=t.finished_at===null?void 0:ce(t,"finished_at"),s=jt(t,"error_json"),d=t.input_revision===null?void 0:ce(t,"input_revision"),c=jt(t,"llm_json"),u=jt(t,"prompt");return{archiveKey:Oe(t,"archive_key"),archiveIdentity:Oe(t,"archive_path"),cacheLocator:Oe(t,"cache_path"),chapterId:ce(t,"chapter_id"),createdAt:ce(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:ce(t,"queue_rank"),state:XE(Oe(t,"state")),...a===void 0?{}:{readingSummaryStartedAt:a},target:hf(Oe(t,"target"),"target"),updatedAt:ce(t,"updated_at"),workspaceLocator:Oe(t,"workspace_path")}}async function Mr(t){let e=A().resources,[n,r,a,o,s]=await Promise.all([e.getFile(t.archiveIdentity),Ad(t.cacheLocator),QE(t.eventsLocator),Ad(t.logLocator),Ad(t.workspaceLocator)]);if(n===void 0)throw Dr("archive");if(r===void 0)throw Dr("cache");if(a===void 0)throw Dr("events");if(o===void 0)throw Dr("log");if(s===void 0)throw Dr("workspace");let{archiveIdentity:d,cacheLocator:c,eventsLocator:u,logLocator:m,ownerPid:b,workspaceLocator:v,...f}=t;return{...f,archive:n,cache:r,events:a,log:o,workspace:s}}async function Ad(t){return t.startsWith("jobs/")?await We(R().library,t)??zE(t):await A().resources.getDirectory(t)}function zE(t){let e=R().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 We(e,n(r)),getFile:async r=>await J(e,n(r)),getLastModified:async()=>await(await We(e,t))?.getLastModified?.(),identity:`managed:library:${t}`,kind:"directory",list:async()=>(await We(e,t))?.list()??[],name:t.split("/").at(-1)??t,remove:async(r,a)=>{await(await We(e,t))?.remove(r,a)}}}async function QE(t){return t.startsWith("jobs/")?await J(R().library,t):await A().resources.getFile(t)}function Dr(t){return new Error(`Build job ${t} resource is unavailable`)}function XE(t){if(Td.includes(t))return t;throw new Error(`Invalid build job state: ${t}`)}function hf(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 VE(t,e){return t===void 0?void 0:hf(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 ce(t,e){let n=t[e];if(typeof n!="number")throw new TypeError(`Expected ${e} to be a number`);return n}function jt(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 Bt=i(()=>{"use strict";_d();y()});async function bn(){let t=await X("jobs/job.sqlite",mf);try{return await t.run(`
|
|
741
699
|
UPDATE build_jobs
|
|
742
700
|
SET workspace_path = 'jobs/work/' || job_id,
|
|
743
701
|
cache_path = 'jobs/cache/' || job_id,
|
|
@@ -747,33 +705,92 @@ VALUES (1);
|
|
|
747
705
|
OR cache_path NOT LIKE 'jobs/cache/%'
|
|
748
706
|
OR log_path NOT LIKE 'jobs/logs/%'
|
|
749
707
|
OR events_path NOT LIKE 'jobs/events/%'
|
|
750
|
-
`),t}catch(e){throw await t.close().catch(()=>{}),e}}var
|
|
708
|
+
`),t}catch(e){throw await t.close().catch(()=>{}),e}}var Sn=i(()=>{"use strict";_();y();pf();Bt()});var ka=i(()=>{"use strict";Nr();Wr();Sn();Or()});var xa=i(()=>{"use strict";Bt();ka();Or()});var Ld=i(()=>{"use strict";F();Or();Nr();Pd();Wr();Sn();xa();ka();Ni();Bt()});var bf=i(()=>{"use strict";Nr();Sn();xa();Bt();Ni()});var Sf=i(()=>{"use strict";F();Nr();Pd();Wr();Sn();xa();ka();Ld();Bt()});function iv(t){return nv.has(t)}async function av(t,e){if((await e.list()).some(a=>!iv(a.name)))return 0;let r=await pt(e);return await t.remove(e.name,{recursive:!0}),r}async function wf(t){let e=0,n=0,r=0;for(let a of await t.list()){if(!U(a))continue;r+=1;let o=await Ye(a);if(o===void 0||Date.now()-o<rv)continue;let s=await av(t,a);(s>0||await t.getDirectory(a.name)===void 0)&&(e+=s,n+=1)}return{freedBytes:e,removed:n,scanned:r}}async function pt(t){return await Ie(t)}var nv,rv,Od=i(()=>{"use strict";y();nv=new Set([".DS_Store"]),rv=6e4});async function Ia(t){let e=await bn(),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=>ce(c,"count")),a=await e.queryAll(`
|
|
751
709
|
SELECT *
|
|
752
710
|
FROM build_jobs
|
|
753
711
|
WHERE state IN ('succeeded', 'failed', 'canceled')
|
|
754
712
|
AND updated_at <= ?
|
|
755
|
-
`,[n],
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
713
|
+
`,[n],Ut),o=await Promise.all(a.map(Mr)),s=t.dryRun?{freedBytes:0,removed:0,scanned:0}:await wf(await uf()),d=0;for(let c of o)d+=await pt(c.workspace),d+=await pt(c.cache),d+=await pt(c.log),d+=await pt(c.events),t.dryRun||(await lf(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 kf=i(()=>{"use strict";Od();Or();Sn();Bt()});var Kd=i(()=>{"use strict";_d();Ld();bf();Sf();Wr();kf()});async function Ef(t){let n=await(await R().library.getDirectory("staging"))?.getDirectory("library");if(n===void 0)return{freedBytes:0,removed:0,scanned:0};let r=await sv();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(!U(u)||(s+=1,a.has(u.name)))continue;let m=Number(u.name);if(Number.isInteger(m)&&await sp(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 sv(){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 wn=i(()=>{"use strict";F();y();w();or();_();Le();Mt();hn();Dt();kn();Lt();_t();Z()});var vf=i(()=>{"use strict"});var dv,rV,kn=i(()=>{"use strict";y();w();_();qe();Le();Le();Kd();ct();Ee();F();Lt();wn();_t();vf();dv=`
|
|
714
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
715
|
+
library_id INTEGER NOT NULL,
|
|
716
|
+
public_id TEXT NOT NULL,
|
|
717
|
+
relative_path TEXT NOT NULL,
|
|
718
|
+
status TEXT NOT NULL DEFAULT 'present',
|
|
719
|
+
last_seen_mutation_token TEXT,
|
|
720
|
+
last_seen_size INTEGER,
|
|
721
|
+
last_seen_mtime_ms INTEGER,
|
|
722
|
+
last_scanned_at TEXT,
|
|
723
|
+
created_at TEXT NOT NULL,
|
|
724
|
+
updated_at TEXT NOT NULL,
|
|
725
|
+
UNIQUE(library_id, public_id)
|
|
726
|
+
`,rV=`
|
|
727
|
+
CREATE TABLE IF NOT EXISTS library_archives (
|
|
728
|
+
${dv}
|
|
729
|
+
);
|
|
730
|
+
|
|
731
|
+
CREATE INDEX IF NOT EXISTS idx_library_archives_library
|
|
732
|
+
ON library_archives(library_id);
|
|
733
|
+
|
|
734
|
+
CREATE INDEX IF NOT EXISTS idx_library_archives_library_path
|
|
735
|
+
ON library_archives(library_id, relative_path);
|
|
736
|
+
`});var _f=i(()=>{"use strict";ct();kn();_t();wn();Lt()});var zd=i(()=>{"use strict";Le();kn();Lt()});var Lf=i(()=>{"use strict";Gi();Bi();dr();ea();Zi();mn();Pe();ta();Wt();hn();wn();zd()});var Of=i(()=>{"use strict";rd();Qi();Bi();ji();Lf();Pe();kn();zd();Lt();wn();_t()});var Ca=i(()=>{"use strict";Lt();_f();kn();Of();wn();_t()});function Ta(t){let e=t.trim();return e===""?[]:Array.from(wv.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function ke(t){let e=t.replace(/\s+/gu," ").trim(),n=kv(e),r="";for(let a of n)if(!xv(a)){if(!Gr(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function kv(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&&Sv.has(e[e.length-1]??"")&&Gr(e[e.length-2]??"")&&n<t.length-1&&Gr(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&Gr(a)&&Gr(o)&&e.push(r),n+=1}return e}function Gr(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function xv(t){return/[\p{P}\p{S}]/u.test(t)}var Sv,wv,jr=i(()=>{"use strict";Sv=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),wv=new Intl.Segmenter(void 0,{granularity:"sentence"})});function Xd(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Wf(t,e){let n=_a(t,2),r=_a(e,2),a=_a(t,3),o=_a(e,3);return(Nf(n,r)+Nf(a,o))/2}function _a(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 Nf(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 Df(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 Mf(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function Ff(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 Gf(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
|
|
737
|
+
prev: ${Qd(t.prevText)}
|
|
738
|
+
text: ${Qd(t.text,120)}
|
|
739
|
+
next: ${Qd(t.nextText)}`}function Qd(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var Vd=i(()=>{"use strict"});var Yd=i(()=>{"use strict"});function Uf(t,e,n){return t.mode==="head_tail"?vv(t,e):Zd(t.text??"",e,n)}function vv(t,e){let n=t.head??"",r=t.tail??"",a=ke(e),o=ke(n),s=ke(r);if(o===""||s==="")return Xd();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let v=o.length+s.length,f=Math.min(1,v/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=Zd(n,e,"start_anchor"),m=Zd(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 Zd(t,e,n){let r=t.trim(),a=e.trim(),o=ke(r),s=ke(a);if(o===""||s==="")return Xd();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=jf({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*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),v=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),L=new Set([...v,...C]).size,K=[...v].filter(ie=>C.has(ie)).length;if((L===0?0:K/L)<.35)continue;let j=.35*Wf(o,g)+.35*Ff(o,g)+.2*Df(o,g)+.1*Mf(o,g)+jf({candidateNormalized:s,label:n,matchEnd:k+f,matchStart:k,queryNormalized:o});j>d&&(d=Math.min(1,j),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function jf(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 Bf=i(()=>{"use strict";jr();Vd();Yd()});function qf(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 Hf(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?ec(t.tail??"","end_anchor"):ec(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:ec(t.text??"",e)}}function tc(t){return t.mode==="head_tail"?ke(t.head??"").length+ke(t.tail??"").length:ke(t.text??"").length}function ec(t,e){let n=Ta(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var $f=i(()=>{"use strict";jr()});var qt,Qf=i(()=>{"use strict";Bf();$f();Vd();Yd();qt=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[v,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:v===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:v.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${v.occurrenceId}).`}]:[{confidence:Math.min(u.score,v.score),sentenceIds:n.slice(u.index,v.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 v=e.overrides.end_anchor,[f,k,g]=v===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[v,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,n){let[r,a]=qf(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[Hf(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&&tc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&tc(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=Uf(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=>Gf(s)).join(`
|
|
740
|
+
`);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
|
|
741
|
+
${o}
|
|
742
|
+
Please provide a more specific anchor or surrounding context.`}}}});var Xf=i(()=>{"use strict"});var Vf=i(()=>{"use strict";Qf();Xf()});var Pa,Yf=i(()=>{"use strict";Pa=["Evidence selection:",'- Return evidence as [{"sentence_id":"S1","quote":"exact short source quote"}].',"- evidence.quote is a locator for the source sentence, not a proof excerpt.","- Choose the shortest exact quote that still uniquely identifies the intended sentence.","- If the quote is too short, it may match multiple sentences; if it is too long, it may include unnecessary text or cross sentence boundaries.","- Do not use a whole sentence by default.","- evidence is an array. Use multiple items when the claim needs multiple source sentences.","- A source sentence means exactly one displayed source line labeled S1, S2, S3, etc.","- Each evidence item must point to exactly one source sentence.","- Each evidence item must quote one continuous span from exactly one labeled source line, for example only from S2.","- Never merge text from two labeled source lines into one evidence quote.","- sentence_id must be one of the sentence IDs shown in the source context.","- quote must be copied from the untagged original source sentence.","- If the source context contains XML-like tags, do not copy the tags into quote; copy only the visible text."].join(`
|
|
743
|
+
`)});var nc=i(()=>{"use strict"});var Zf=i(()=>{"use strict";nc();jr()});var In=i(()=>{"use strict";Vf();Yf();nc();Zf();jr()});import{z as Ur}from"zod";var PY,ty=i(()=>{"use strict";PY=Ur.object({meanings:Ur.array(Ur.object({information:Ur.string(),qid:Ur.string().regex(/^Q[1-9][0-9]*$/u)}).strict())}).strict()});var ny=i(()=>{"use strict"});var La=i(()=>{"use strict"});var WY,ay=i(()=>{"use strict";La();WY=336*60*60*1e3});var oy=i(()=>{"use strict";La()});var sy=i(()=>{"use strict";ty();ny();ay();La();oy()});async function ic(t){let e=await Br.open();try{return await e.gc(t)}finally{await e.close()}}function jv(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"||!Array.isArray(n.sites)?void 0:{qid:n.qid,refreshedAt:n.refreshedAt,sites:n.sites}}catch{return}}function Uv(t){try{let e=JSON.parse(t);return typeof e.qid=="string"&&(e.wiki==="zhwiki"||e.wiki==="enwiki")&&typeof e.pageId=="number"&&typeof e.revisionId=="number"&&typeof e.parsedPage=="object"&&e.parsedPage!==null&&typeof e.profile=="object"&&e.profile!==null?e:void 0}catch{return}}var Fv,Gv,Br,dy=i(()=>{"use strict";sy();_();Fv=`
|
|
744
|
+
CREATE TABLE IF NOT EXISTS wikimedia_qid_cache_v2 (
|
|
745
|
+
qid TEXT PRIMARY KEY,
|
|
746
|
+
record_json TEXT NOT NULL,
|
|
747
|
+
refreshed_at TEXT NOT NULL
|
|
748
|
+
);
|
|
749
|
+
CREATE INDEX IF NOT EXISTS idx_wikimedia_qid_cache_v2_refreshed_at
|
|
750
|
+
ON wikimedia_qid_cache_v2(refreshed_at);
|
|
751
|
+
CREATE TABLE IF NOT EXISTS wikimedia_disambiguation_cache_v2 (
|
|
752
|
+
qid TEXT NOT NULL,
|
|
753
|
+
wiki TEXT NOT NULL,
|
|
754
|
+
page_id INTEGER NOT NULL,
|
|
755
|
+
revision_id INTEGER NOT NULL,
|
|
756
|
+
normalizer_version TEXT NOT NULL,
|
|
757
|
+
model_id TEXT NOT NULL,
|
|
758
|
+
record_json TEXT NOT NULL,
|
|
759
|
+
PRIMARY KEY(qid,wiki,page_id,revision_id,normalizer_version,model_id)
|
|
760
|
+
);
|
|
761
|
+
`,Gv=336*60*60*1e3,Br=class t{#e;constructor(e){this.#e=e}static async open(){return new t(await X("cache/cache.sqlite",Fv))}async getQids(e,n){if(e.length===0)return new Map;n?.signal?.throwIfAborted();let r=await this.#e.queryAll(`SELECT record_json FROM wikimedia_qid_cache_v2
|
|
762
|
+
WHERE qid IN (${e.map(()=>"?").join(",")})`,e,o=>String(o.record_json)),a=new Map;for(let o of r){let s=jv(o);s!==void 0&&a.set(s.qid,s)}return a}async putQids(e,n){n?.signal?.throwIfAborted(),await this.#e.transaction(async()=>{for(let r of e)n?.signal?.throwIfAborted(),await this.#e.run(`INSERT INTO wikimedia_qid_cache_v2(qid,record_json,refreshed_at)
|
|
763
|
+
VALUES(?,?,?)
|
|
764
|
+
ON CONFLICT(qid) DO UPDATE SET
|
|
765
|
+
record_json=excluded.record_json,
|
|
766
|
+
refreshed_at=excluded.refreshed_at`,[r.qid,JSON.stringify(r),r.refreshedAt])})}async getDisambiguations(e,n,r){if(e.length===0)return[];r?.signal?.throwIfAborted();let a=e.map(()=>"(qid=? AND wiki=? AND page_id=? AND revision_id=?)"),o=e.flatMap(d=>[d.qid,d.wiki,d.pageId,d.revisionId]);return(await this.#e.queryAll(`SELECT record_json FROM wikimedia_disambiguation_cache_v2
|
|
767
|
+
WHERE normalizer_version=? AND model_id=?
|
|
768
|
+
AND (${a.join(" OR ")})`,[n.normalizerVersion,n.modelId,...o],d=>String(d.record_json))).flatMap(d=>{let c=Uv(d);return c===void 0?[]:[c]})}async putDisambiguations(e,n,r){r?.signal?.throwIfAborted(),await this.#e.transaction(async()=>{for(let a of e)r?.signal?.throwIfAborted(),await this.#e.run(`INSERT INTO wikimedia_disambiguation_cache_v2(
|
|
769
|
+
qid,wiki,page_id,revision_id,normalizer_version,model_id,record_json
|
|
770
|
+
) VALUES(?,?,?,?,?,?,?)
|
|
771
|
+
ON CONFLICT(qid,wiki,page_id,revision_id,normalizer_version,model_id)
|
|
772
|
+
DO UPDATE SET record_json=excluded.record_json`,[a.qid,a.wiki,a.pageId,a.revisionId,n.normalizerVersion,n.modelId,JSON.stringify(a)])})}async close(){await this.#e.close()}async gc(e){let n=new Date(e.now-Gv).toISOString(),r=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_qid_cache_v2",void 0,o=>Number(o.count))??0,a=await this.#e.queryOne("SELECT COUNT(*) AS count FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n],o=>Number(o.count))??0;return!e.dryRun&&a>0&&(await this.#e.transaction(async()=>{let o=await this.#e.queryAll("SELECT qid FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n],s=>String(s.qid));for(let s of o)await this.#e.run("DELETE FROM wikimedia_disambiguation_cache_v2 WHERE qid = ?",[s]);await this.#e.run("DELETE FROM wikimedia_qid_cache_v2 WHERE refreshed_at < ?",[n])}),await this.#e.run("VACUUM")),{freedBytes:0,removed:a,scanned:r}}}});var oc=i(()=>{"use strict";dy()});var sc=i(()=>{"use strict"});var dc=i(()=>{"use strict"});import{jsonrepair as t2}from"jsonrepair";var cy=i(()=>{"use strict"});var uy=i(()=>{"use strict";dc();sc();cy()});var Ne=i(()=>{"use strict";sc();dc();uy()});var qr=i(()=>{"use strict"});import{z as ze}from"zod";var Jv,Kv,R2,lc=i(()=>{"use strict";Ne();qr();Jv=ze.object({candidateId:ze.string().min(1),decision:ze.enum(["continue","recall","skip_this_time","never_recall"]),qid:ze.string().nullable().optional()}).strict(),Kv=ze.object({decisions:ze.array(Jv),groupId:ze.string().min(1)}).strict(),R2=ze.object({groups:ze.array(Kv)}).strict()});import{z as Hr}from"zod";var Xv,L2,py=i(()=>{"use strict";Ne();qr();lc();Xv=Hr.object({decision:Hr.enum(["keep","reject"]),qid:Hr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),L2=Hr.object({qids:Hr.array(Xv)}).strict()});var hy=i(()=>{"use strict"});import{z as $r}from"zod";var Vv,M2,fy=i(()=>{"use strict";Ne();Vv=$r.object({note:$r.string().max(24).optional(),surfaceId:$r.string().min(1)}).strict(),M2=$r.object({protectedSurfaces:$r.array(Vv)}).strict()});var mc=i(()=>{"use strict"});var yy=i(()=>{"use strict";mc()});var gy=i(()=>{"use strict"});var pc=i(()=>{"use strict"});var by=i(()=>{"use strict";pc();qr()});var ft=i(()=>{"use strict";lc();py();qr();hy();fy();yy();mc();gy();by();pc()});var h3,fc=i(()=>{"use strict";tn();h3=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 yc=i(()=>{"use strict";et()});var Iy=i(()=>{"use strict";yc()});var Ey=i(()=>{"use strict";Iy();yc()});var vy=i(()=>{"use strict"});var Ry=i(()=>{"use strict"});var Cy=i(()=>{"use strict";vy();Ry()});var Jr=i(()=>{"use strict";Ne()});var Ty=i(()=>{"use strict";_();Jr()});var _y=i(()=>{"use strict";Jr()});var Py=i(()=>{"use strict"});import{z as x}from"zod";var Ay,lR,Ly,mR,pR,hR,fR,yR,gR,Oa=i(()=>{"use strict";_();Ay=x.object({from:x.union([x.number().int(),x.string()]),strength:x.string().optional(),to:x.union([x.number().int(),x.string()])}),lR=x.object({quote:x.string().optional(),sentence_id:x.string().optional()}).passthrough(),Ly=x.union([x.record(x.string(),x.unknown()),x.array(lR)]),mR=x.object({content:x.string(),evidence:Ly.nullish(),label:x.string(),retention:x.enum(["verbatim","detailed","focused","relevant"]),temp_id:x.string()}).passthrough(),pR=x.object({chunks:x.array(mR),fragment_summary:x.string(),links:x.array(Ay)}),hR=x.object({content:x.string(),evidence:Ly.nullish(),importance:x.enum(["critical","important","helpful"]),label:x.string(),temp_id:x.string()}).passthrough(),fR=x.object({chunk_id:x.number().int(),importance:x.enum(["critical","important","helpful"])}),yR=x.object({chunks:x.array(hR),importance_annotations:x.array(fR),links:x.array(Ay)}),gR=x.object({choice:x.string()})});var Oy=i(()=>{"use strict";Ne();In();Py();Jr();Oa()});var Ny=i(()=>{"use strict";Ne();_();Ty();Jr();_y();Oy();Oa()});var Wy=i(()=>{"use strict";Ny();Oa()});var Na=i(()=>{"use strict"});import{detect as E8,validateISO2 as v8}from"tinyld";var gc=i(()=>{"use strict";Me()});var Dy=i(()=>{"use strict";gc();Me()});var My=i(()=>{"use strict"});import{z as Kr}from"zod";var xR,K8,Gy=i(()=>{"use strict";Ne();In();Wy();Na();Na();Dy();My();xR=Kr.object({content:Kr.string(),id:Kr.number(),label:Kr.string()}),K8=Kr.array(xR)});var bc=i(()=>{"use strict";Gy()});var jy=i(()=>{"use strict";nt()});var Sc=i(()=>{"use strict";jy()});var Uy=i(()=>{"use strict";Cy();bc();Sc()});var Wa=i(()=>{"use strict";Uy();Sc()});var Da=i(()=>{"use strict"});var Ma=i(()=>{"use strict";Wa();Da()});var By=i(()=>{"use strict";Ma()});var qy=i(()=>{"use strict"});var Fa=i(()=>{"use strict"});var Hy=i(()=>{"use strict";Fa()});var vn,I5,TR,Ga=i(()=>{"use strict";Lo();vn=(r=>(r.Critical="critical",r.Major="major",r.Minor="minor",r))(vn||{}),I5=rn(vn),TR=Qn(vn,"review severity")});var T5,kc=i(()=>{"use strict";Fa();Ga();T5=Object.freeze({critical:9,major:3,minor:1})});var $y=i(()=>{"use strict";gc();Me();Ga()});var Jy=i(()=>{"use strict";y();et();kc()});var xc=i(()=>{"use strict";_()});var Ky=i(()=>{"use strict"});import{z as Rn}from"zod";var _R,PR,Y5,zy=i(()=>{"use strict";et();Ne();Fa();xc();Ga();_R=["critical","major","minor"],PR=Rn.object({problem:Rn.string(),severity:Rn.enum(_R),suggestion:Rn.string().default("")}),Y5=Rn.object({issues:Rn.array(PR)})});var Qy=i(()=>{"use strict";qy();Hy();kc();$y();Jy();xc();Ky();zy()});var Ic=i(()=>{"use strict";Qy()});var Vy=i(()=>{"use strict"});var Yy=i(()=>{"use strict"});var Zy=i(()=>{"use strict";Vy();Yy()});var zr=i(()=>{"use strict"});var L4,O4,Cn=i(()=>{"use strict";_();L4={critical:9,helpful:1,important:3},O4={detailed:9,focused:3,relevant:1,verbatim:27}});var Tn=i(()=>{"use strict"});var Qr=i(()=>{"use strict"});var Ec=i(()=>{"use strict";Tn()});var vc=i(()=>{"use strict";Cn();Tn();zr();Qr();Ec()});var Rc=i(()=>{"use strict";zr();vc();Qr()});var tg=i(()=>{"use strict";Cn();Tn();Qr()});var ng=i(()=>{"use strict";Cn();Tn();zr();Qr();Ec()});var rg=i(()=>{"use strict";Rc();Tn();zr();tg();vc();ng()});var ig=i(()=>{"use strict";rg();Rc()});var ag=i(()=>{"use strict";Cn()});var og=i(()=>{"use strict";ig();ag()});var sg=i(()=>{"use strict";Zy();og();Cn()});var dg=i(()=>{"use strict";sg()});var Cc=i(()=>{"use strict";Z()});var cg=i(()=>{"use strict"});var Tc=i(()=>{"use strict";Ma()});var Ua=i(()=>{"use strict"});var ug=i(()=>{"use strict";Hn();tn();Ic();Wa();dg();Ma();Da();Cc();cg();Tc();Ua()});var lg=i(()=>{"use strict";Cc();Ua();Z()});var mg=i(()=>{"use strict";By();ug();Da();lg();Tc();Ua()});var _n=i(()=>{"use strict";mg()});var pg=i(()=>{"use strict";ye();Hn();_n();at()});var hg=i(()=>{"use strict";at();at();_();ye();Ey();_n();pg();ba();y()});var Ac,yt=i(()=>{"use strict";Ac=["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 Lc=i(()=>{"use strict";yt()});var gg=i(()=>{"use strict";et();Ro();hg();fc();Le();Lc();y()});var Ba=i(()=>{"use strict"});import{z as p}from"zod";var bg,V,BR,qR,Sg,HR,$R,JR,KR,zR,QR,XR,VR,YR,ZR,eC,tC,nC,rC,w9,Pn=i(()=>{"use strict";y();Re();Ba();bg=1,V=p.number().int().nonnegative(),BR=p.literal(bg),qR=p.string().regex(/^Q[1-9][0-9]*$/u),Sg=p.number().min(0).max(1).optional(),HR=p.object({text:p.string(),wordsCount:V}).strict(),$R=p.object({type:p.literal("meta"),schemaVersion:BR,chapterId:p.number().int(),stream:p.enum(["knowledge-graph","reading-graph","summary"])}).strict(),JR=p.object({type:p.literal("parameter"),scope:p.enum(["knowledge-graph","reading-graph","summary"]),language:p.string().optional(),prompt:p.string()}).strict(),KR=p.object({type:p.literal("source-fragment"),fragmentId:V,summary:p.string(),sentences:p.array(HR)}).strict(),zR=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(ve).optional(),wordsCount:V,weight:p.number()}).strict(),QR=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(),XR=p.object({type:p.literal("fragment-group"),groupId:V,startSentenceIndex:V,endSentenceIndex:V}).strict(),VR=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(),YR=p.object({type:p.literal("snake-chunk"),snakeId:p.string().min(1),chunkId:p.string().min(1),position:V}).strict(),ZR=p.object({type:p.literal("snake-edge"),fromSnakeId:p.string().min(1),toSnakeId:p.string().min(1),weight:p.number()}).strict(),eC=p.object({type:p.literal("summary"),text:p.string()}).strict(),tC=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:qR,confidence:Sg,note:p.string().optional()}).strict(),nC=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:Sg,note:p.string().optional()}).strict(),rC=p.object({type:p.literal("end")}).strict(),w9=p.discriminatedUnion("type",[$R,JR,KR,zR,QR,XR,VR,YR,ZR,eC,tC,nC,rC])});var wg=i(()=>{"use strict"});var kg=i(()=>{"use strict"});import{sha256 as v9}from"@noble/hashes/sha2.js";var R9,C9,Oc=i(()=>{"use strict";R9=new RegExp("\\p{Script=Han}+","gu"),C9=new RegExp("^\\p{Script=Han}+$","u")});var Nc=i(()=>{"use strict";Oc()});import{z as l}from"zod";function xg(){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 Ig(){return l.object({fromChunkId:l.string(),strength:l.string().optional(),toChunkId:l.string(),type:l.literal("reading-edge"),weight:l.number()})}function Eg(){return l.object({endSentenceIndex:P,groupId:P,startSentenceIndex:P,type:l.literal("fragment-group")})}function vg(){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 Rg(){return l.object({chunkId:l.string(),position:P,snakeId:l.string(),type:l.literal("snake-chunk")})}function Cg(){return l.object({fromSnakeId:l.string(),toSnakeId:l.string(),type:l.literal("snake-edge"),weight:l.number()})}function Tg(){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 iC(){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,Wc,O9,N9,$t=i(()=>{"use strict";P=l.number().int().nonnegative(),Wc={sentenceIndex:P,text:l.string(),wordsCount:P},O9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string().optional(),type:l.literal("job-options")}),l.object({...Wc,fragmentId:P.optional(),type:l.literal("source-text")}),l.object({fragmentId:P,summary:l.string(),type:l.literal("source-fragment")}),l.object({...Wc,fragmentId:P.optional(),type:l.literal("source-sentence")}),l.object({...Wc,type:l.literal("summary-sentence")}),l.object({chapterId:l.number().int(),title:l.string(),type:l.literal("chapter-title")}),xg(),Ig(),Eg(),vg(),Rg(),Cg(),Tg()]),N9=l.discriminatedUnion("type",[l.object({language:l.string().optional(),prompt:l.string(),scope:l.enum(["knowledge-graph","reading-graph"]),type:l.literal("job-parameter")}),xg(),Ig(),Eg(),vg(),Rg(),Cg(),Tg(),iC(),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 Dc=i(()=>{"use strict";$t()});var Mc=i(()=>{"use strict"});var Jt,Fc=i(()=>{"use strict";Jt=["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(`
|
|
773
|
+
`)});import{jsonrepair as U9}from"jsonrepair";var _g=i(()=>{"use strict"});var Pg=i(()=>{"use strict";Fc();Mc();_g()});var le=i(()=>{"use strict";Mc();Fc();Pg()});var Og=i(()=>{"use strict"});var Xr=i(()=>{"use strict"});import{z as Xe}from"zod";var dC,cC,p7,jc=i(()=>{"use strict";le();Xr();dC=Xe.object({candidateId:Xe.string().min(1),decision:Xe.enum(["continue","recall","skip_this_time","never_recall"]),qid:Xe.string().nullable().optional()}).strict(),cC=Xe.object({decisions:Xe.array(dC),groupId:Xe.string().min(1)}).strict(),p7=Xe.object({groups:Xe.array(cC)}).strict()});import{z as Vr}from"zod";var lC,k7,Wg=i(()=>{"use strict";le();Xr();jc();lC=Vr.object({decision:Vr.enum(["keep","reject"]),qid:Vr.string().regex(/^Q[1-9][0-9]*$/)}).strict(),k7=Vr.object({qids:Vr.array(lC)}).strict()});var Uc=i(()=>{"use strict"});import{z as Yr}from"zod";var mC,R7,Dg=i(()=>{"use strict";le();mC=Yr.object({note:Yr.string().max(24).optional(),surfaceId:Yr.string().min(1)}).strict(),R7=Yr.object({protectedSurfaces:Yr.array(mC)}).strict()});var Mg=i(()=>{"use strict";Uc()});var Fg=i(()=>{"use strict"});var Bc=i(()=>{"use strict"});var Gg=i(()=>{"use strict";Bc();Xr()});var Zr=i(()=>{"use strict";Og();Wg();Xr();jc();Uc();Dg();Mg();Fg();Gg();Bc()});var Ha=i(()=>{"use strict"});var jg=i(()=>{"use strict";Zr();Ha()});var Ug=i(()=>{"use strict";Zr()});var qc=i(()=>{"use strict"});var Bg=i(()=>{"use strict";Zr();Ha();Ug();qc()});function $a(t){let e=t.trim();return e===""?[]:Array.from(fC.segment(e)).map(n=>n.segment.trim()).filter(n=>n!=="")}function xe(t){let e=t.replace(/\s+/gu," ").trim(),n=yC(e),r="";for(let a of n)if(!gC(a)){if(!ei(a)){r+=a;continue}r+=a.toLowerCase().normalize("NFD").replace(new RegExp("\\p{M}","gu"),"")}return r}function yC(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&&hC.has(e[e.length-1]??"")&&ei(e[e.length-2]??"")&&n<t.length-1&&ei(t[n+1]??"")){e.pop(),n+=1;continue}let a=e[e.length-1]??"",o=t[n+1]??"";a!==""&&o!==""&&ei(a)&&ei(o)&&e.push(r),n+=1}return e}function ei(t){return t!==""&&new RegExp("\\p{Script=Latin}","u").test(t)&&new RegExp("\\p{L}","u").test(t)}function gC(t){return/[\p{P}\p{S}]/u.test(t)}var hC,fC,ti=i(()=>{"use strict";hC=new Set(["\u2010","\u2011","\u2012","\u2013","\u2014","\u2015"]),fC=new Intl.Segmenter(void 0,{granularity:"sentence"})});function $c(){return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:-1,matchStart:-1,score:0}}function Hg(t,e){let n=Ja(t,2),r=Ja(e,2),a=Ja(t,3),o=Ja(e,3);return(qg(n,r)+qg(a,o))/2}function Ja(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 qg(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 $g(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 Jg(t,e){return 1-Math.abs(t.length-e.length)/Math.max(t.length,e.length)}function Kg(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 zg(t){return` - ${t.occurrenceId} score=${t.score.toFixed(3)}
|
|
774
|
+
prev: ${Hc(t.prevText)}
|
|
775
|
+
text: ${Hc(t.text,120)}
|
|
776
|
+
next: ${Hc(t.nextText)}`}function Hc(t,e=80){let n=t.replace(/\s+/gu," ").trim();return n===""?"(none)":n.length<=e?n:`${n.slice(0,e-3)}...`}var Jc=i(()=>{"use strict"});var Kc=i(()=>{"use strict"});function Xg(t,e,n){return t.mode==="head_tail"?wC(t,e):zc(t.text??"",e,n)}function wC(t,e){let n=t.head??"",r=t.tail??"",a=xe(e),o=xe(n),s=xe(r);if(o===""||s==="")return $c();let d=a.indexOf(o),c=a.lastIndexOf(s);if(d!==-1&&c!==-1&&d<=c){let v=o.length+s.length,f=Math.min(1,v/Math.max(1,a.length));return{exactNormalized:!1,exactRaw:!1,exactSubstring:!0,matchEnd:c+s.length,matchStart:d,score:.82+.18*f}}let u=zc(n,e,"start_anchor"),m=zc(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 zc(t,e,n){let r=t.trim(),a=e.trim(),o=xe(r),s=xe(a);if(o===""||s==="")return $c();if(r===a)return{exactNormalized:!0,exactRaw:!0,exactSubstring:!0,matchEnd:s.length,matchStart:0,score:1};if(o===s)return{exactNormalized:!0,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:.995};if(s.includes(o)){let f=s.indexOf(o),k=o.length/Math.max(1,s.length),g=Qg({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*k+g)}}if(o.includes(s)){let f=s.length/Math.max(1,o.length);return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:s.length,matchStart:0,score:Math.min(.92,.78+.14*f)}}let d=0,c=-1,u=-1,m=Math.min(s.length,Math.max(o.length,Math.floor(o.length*1.2))),b=Math.min(m,Math.max(1,Math.floor(o.length*.8))),v=new Set(o);for(let f=b;f<=m;f+=1)for(let k=0;k<=s.length-f;k+=1){let g=s.slice(k,k+f),C=new Set(g),L=new Set([...v,...C]).size,K=[...v].filter(ie=>C.has(ie)).length;if((L===0?0:K/L)<.35)continue;let j=.35*Hg(o,g)+.35*Kg(o,g)+.2*$g(o,g)+.1*Jg(o,g)+Qg({candidateNormalized:s,label:n,matchEnd:k+f,matchStart:k,queryNormalized:o});j>d&&(d=Math.min(1,j),c=k,u=k+f)}return{exactNormalized:!1,exactRaw:!1,exactSubstring:!1,matchEnd:u,matchStart:c,score:d}}function Qg(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 Vg=i(()=>{"use strict";ti();Jc();Kc()});function Yg(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 Zg(t,e){if(t===void 0)return;if(t.mode==="head_tail"){let r=e==="end_anchor"?Qc(t.tail??"","end_anchor"):Qc(t.head??"","start_anchor");return r===""?void 0:{mode:"full",text:r}}return{mode:"full",text:Qc(t.text??"",e)}}function Xc(t){return t.mode==="head_tail"?xe(t.head??"").length+xe(t.tail??"").length:xe(t.text??"").length}function Qc(t,e){let n=$a(t);return n.length<=1?t.trim():e==="end_anchor"?n[n.length-1]??t.trim():n[0]??t.trim()}var eb=i(()=>{"use strict";ti()});var An,ib=i(()=>{"use strict";Vg();eb();Jc();Kc();An=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[v,f,k]=this.resolveAnchor({anchor:c,candidateSentenceIds:n,candidateTexts:r,label:"end_anchor",minIndex:u.index});return k!==void 0?[void 0,k]:v===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:v.index<u.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${u.occurrenceId} -> ${v.occurrenceId}).`}]:[{confidence:Math.min(u.score,v.score),sentenceIds:n.slice(u.index,v.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 v=e.overrides.end_anchor,[f,k,g]=v===void 0?this.resolveAnchor({anchor:m,candidateSentenceIds:e.candidateSentenceIds,candidateTexts:e.candidateTexts,label:"end_anchor",minIndex:d.index}):[v,"choice_final",void 0];return g!==void 0?[void 0,g]:f===void 0?[void 0,{candidates:[],code:"none",fieldName:"end_anchor",message:"end_anchor could not be matched: no candidate selected"}]:f.index<d.index?[void 0,{candidates:[],code:"invalid_range",fieldName:"end_anchor",message:`Invalid evidence range: end_anchor resolved before start_anchor (${d.occurrenceId} -> ${f.occurrenceId}).`}]:[{confidence:Math.min(d.score,f.score),sentenceIds:e.candidateSentenceIds.slice(d.index,f.index+1),strategy:`${c}+${k}`},void 0]}parseAnchor(e,n){let[r,a]=Yg(e);return a!==void 0?[void 0,{candidates:[],code:"invalid_anchor",fieldName:n,message:`Invalid evidence.${n}: ${a}`}]:[Zg(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&&Xc(e.anchor)>=8)return[o[0],"exact_substring",void 0];if(o.length>1&&Xc(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=Xg(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=>zg(s)).join(`
|
|
760
777
|
`);return{candidates:a,code:n,fieldName:e,message:`${e} is ambiguous. Top candidates:
|
|
761
778
|
${o}
|
|
762
|
-
Please provide a more specific anchor or surrounding context.`}}}});var
|
|
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
|
+
Please provide a more specific anchor or surrounding context.`}}}});var ab=i(()=>{"use strict"});var ob=i(()=>{"use strict";ib();ab()});var Vc,sb=i(()=>{"use strict";Vc=["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(`
|
|
780
|
+
`)});var Yc=i(()=>{"use strict"});var db=i(()=>{"use strict";Yc();ti()});var Ka=i(()=>{"use strict";ob();sb();Yc();db();ti()});var ub=i(()=>{"use strict"});import{z as D}from"zod";var lb,EC,vC,RC,tte,nte,mb=i(()=>{"use strict";le();Ka();ub();lb=D.object({head:D.string().optional(),mode:D.enum(["full","head_tail"]).optional(),tail:D.string().optional(),text:D.string().optional()}).strict(),EC=D.object({quote:D.string().optional(),sentence_id:D.string().optional()}).strict(),vC=D.union([D.object({end_anchor:D.union([D.string(),lb]).optional(),quote:D.string().optional(),sentence_id:D.string().optional(),start_anchor:D.union([D.string(),lb]).optional()}).strict(),D.array(EC)]),RC=D.object({confidence:D.number().min(0).max(1).optional(),evidence:vC,predicate:D.string().min(1).max(64),sourceMentionId:D.string().min(1),targetMentionId:D.string().min(1)}).strict(),tte=D.object({relations:D.array(RC)}).strict(),nte=new An});var pb=i(()=>{"use strict"});var hb=i(()=>{"use strict"});var fb=i(()=>{"use strict";mb();pb();hb()});var yb=i(()=>{"use strict";fb();Ha();qc()});var ni,Ln=i(()=>{"use strict";ni=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 Pte,eu=i(()=>{"use strict";le();$t();jg();Bg();yb();Zr();Ln();Pte=["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 gb=i(()=>{"use strict"});var bb=i(()=>{"use strict"});var Sb=i(()=>{"use strict";gb();bb()});var zt=i(()=>{"use strict"});var ri=i(()=>{"use strict";le()});var kb=i(()=>{"use strict";zt();ri()});var xb=i(()=>{"use strict";ri()});var Ib=i(()=>{"use strict"});import{z as I}from"zod";var Eb,PC,vb,AC,LC,OC,NC,WC,DC,za=i(()=>{"use strict";zt();Eb=I.object({from:I.union([I.number().int(),I.string()]),strength:I.string().optional(),to:I.union([I.number().int(),I.string()])}),PC=I.object({quote:I.string().optional(),sentence_id:I.string().optional()}).passthrough(),vb=I.union([I.record(I.string(),I.unknown()),I.array(PC)]),AC=I.object({content:I.string(),evidence:vb.nullish(),label:I.string(),retention:I.enum(["verbatim","detailed","focused","relevant"]),temp_id:I.string()}).passthrough(),LC=I.object({chunks:I.array(AC),fragment_summary:I.string(),links:I.array(Eb)}),OC=I.object({content:I.string(),evidence:vb.nullish(),importance:I.enum(["critical","important","helpful"]),label:I.string(),temp_id:I.string()}).passthrough(),NC=I.object({chunk_id:I.number().int(),importance:I.enum(["critical","important","helpful"])}),WC=I.object({chunks:I.array(OC),importance_annotations:I.array(NC),links:I.array(Eb)}),DC=I.object({choice:I.string()})});var Rb=i(()=>{"use strict";le();Ka();Ib();ri();za()});var Cb=i(()=>{"use strict";le();zt();kb();ri();xb();Rb();za()});var Tb=i(()=>{"use strict";Cb();za()});var nu=i(()=>{"use strict"});import{detect as Ane,validateISO2 as Lne}from"tinyld";var _b=i(()=>{"use strict"});var Pb=i(()=>{"use strict"});import{z as ii}from"zod";var GC,Vne,Ab=i(()=>{"use strict";le();Ka();Tb();nu();nu();_b();Pb();GC=ii.object({content:ii.string(),id:ii.number(),label:ii.string()}),Vne=ii.array(GC)});var Lb=i(()=>{"use strict";Ab()});var Ob=i(()=>{"use strict";Sb();Lb()});var Nb=i(()=>{"use strict";Ob()});var Wb=i(()=>{"use strict"});var Db=i(()=>{"use strict"});var ru=i(()=>{"use strict";Wb();le();Ln();Db()});var Mb=i(()=>{"use strict"});var Fb=i(()=>{"use strict"});var Gb=i(()=>{"use strict";Mb();Fb()});var ai=i(()=>{"use strict"});var Wre,Dre,On=i(()=>{"use strict";zt();Wre={critical:9,helpful:1,important:3},Dre={detailed:9,focused:3,relevant:1,verbatim:27}});var Nn=i(()=>{"use strict"});var oi=i(()=>{"use strict"});var iu=i(()=>{"use strict";Nn()});var au=i(()=>{"use strict";On();Nn();ai();oi();iu()});var ou=i(()=>{"use strict";ai();au();oi()});var Ub=i(()=>{"use strict";On();Nn();oi()});var Bb=i(()=>{"use strict";On();Nn();ai();oi();iu()});var qb=i(()=>{"use strict";ou();Nn();ai();Ub();au();Bb()});var Hb=i(()=>{"use strict";qb();ou()});var $b=i(()=>{"use strict";On()});var Jb=i(()=>{"use strict";Hb();$b()});var Kb=i(()=>{"use strict";Gb();Jb();On()});var su=i(()=>{"use strict";$t();Ln();Nb();ru();Kb()});var zb=i(()=>{"use strict"});var Xa=i(()=>{"use strict"});var Qb=i(()=>{"use strict";Xa()});var Va=i(()=>{"use strict"});var uae,Vb=i(()=>{"use strict";Xa();Va();uae=Object.freeze({critical:9,major:3,minor:1})});import{detect as pae,validateISO2 as hae}from"tinyld";var Yb=i(()=>{"use strict";Va()});var Zb=i(()=>{"use strict"});var eS=i(()=>{"use strict";zt()});var du=i(()=>{"use strict";eS()});var tS=i(()=>{"use strict"});import{z as Wn}from"zod";var QC,XC,Lae,nS=i(()=>{"use strict";le();Xa();du();Va();QC=["critical","major","minor"],XC=Wn.object({problem:Wn.string(),severity:Wn.enum(QC),suggestion:Wn.string().default("")}),Lae=Wn.object({issues:Wn.array(XC)})});var rS=i(()=>{"use strict";zb();Qb();Vb();Yb();Zb();du();tS();nS()});var cu=i(()=>{"use strict";$t();Ln();zt();ru();rS()});var iS=i(()=>{"use strict";Nc();$t();Dc();eu();su();cu()});import{z as G}from"zod";var Dn,VC,YC,ZC,eT,Ioe,aS=i(()=>{"use strict";Dn=G.number().finite().nonnegative(),VC=G.enum(["committing","enrichment","grounding","indexing","matching","narrowing","relation-discovery","reading-extraction","screening","summary-compression"]),YC=G.enum(["candidate","char","item","page","qid","record","sentence","window"]),ZC=G.object({cacheReadTokens:Dn.optional(),inputTokens:Dn.optional(),outputTokens:Dn.optional()}),eT=G.object({done:Dn,force:G.boolean().optional(),phase:VC,phaseDetail:G.string().optional(),total:Dn,unit:YC}),Ioe=G.discriminatedUnion("event",[G.object({characters:Dn,event:G.literal("output-characters")}),G.object({event:G.literal("token-usage"),usage:ZC}),G.object({event:G.literal("progress"),progress:eT}),G.object({event:G.literal("artifact"),record:G.unknown()}),G.object({event:G.literal("complete"),revision:G.number().int().nonnegative()}),G.object({event:G.literal("error"),message:G.string()})])});var oS=i(()=>{"use strict"});var sS=i(()=>{"use strict"});var si=i(()=>{"use strict";wg();kg();iS();Dc();Nc();$t();eu();su();cu();Ln();aS();oS();sS();Oc()});var dS=i(()=>{"use strict";si();hn()});import{z as T}from"zod";var tT,nT,Koe,zoe,Qoe,cS=i(()=>{"use strict";y();tT="wikg-index-output/v1",nT=T.enum(["fts","embedding-source","embedding-summary"]),Koe=T.object({artifactKind:nT,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(tT),type:T.literal("manifest")}),zoe=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")}),Qoe=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 Qt=i(()=>{"use strict";dS();cS()});var uS=i(()=>{"use strict";Me();yt()});var lS=i(()=>{"use strict";_();Wa()});var pS=i(()=>{"use strict";y();_();Y();_n();Pn();Qt();uS();lS()});var Ya=i(()=>{"use strict"});var hS=i(()=>{"use strict";Ya()});var fS=i(()=>{"use strict"});var yS=i(()=>{"use strict";Ya()});var gS=i(()=>{"use strict";Ya()});var bS=i(()=>{"use strict";hS();fS();yS();gS()});import{z as h}from"zod";var SS,hT,fT,yT,gT,bT,ST,wT,kT,xT,IT,wS=i(()=>{"use strict";Re();SS=h.tuple([h.number(),h.number()]),hT=h.object({text:h.string(),wordsCount:h.number()}),fT=h.object({serialId:h.number(),fragmentId:h.number(),summary:h.string(),sentences:h.array(hT)}),yT=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}})),gT=h.object({id:h.number(),generation:h.number(),sentenceId:SS,label:h.string(),content:h.string(),sentenceIds:h.array(SS),retention:h.enum(he).optional(),importance:h.enum(ve).optional(),wordsCount:h.number(),weight:h.number()}),bT=h.object({fromId:h.number(),toId:h.number(),strength:h.string().optional(),weight:h.number()}),ST=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()}),wT=h.object({snakeId:h.number(),chunkId:h.number(),position:h.number()}),kT=h.object({fromSnakeId:h.number(),toSnakeId:h.number(),weight:h.number()}),xT=h.object({serialId:h.number(),groupId:h.number(),startSentenceIndex:h.number(),endSentenceIndex:h.number()}),IT=h.object({chunks:h.array(gT),fragmentGroups:h.array(xT),fragments:h.array(fT),readingEdges:h.array(bT),serial:yT,snakeChunks:h.array(wT),snakeEdges:h.array(kT),snakes:h.array(ST)})});var kS=i(()=>{"use strict";y();wS()});var xS=i(()=>{"use strict";tn();Ic();Z()});var IS=i(()=>{"use strict";y();_();Y();bS();kS();Ba();xS();Pn();Qt()});var ES=i(()=>{"use strict"});var Za=i(()=>{"use strict";IS();Ba();ES()});var vS=i(()=>{"use strict";Y();Za()});var RS=i(()=>{"use strict"});var CS=i(()=>{"use strict";pS();vS();RS()});var TS=i(()=>{"use strict";si()});var PS=i(()=>{"use strict";si();_();Y();Qt();Za()});var AS=i(()=>{"use strict";si();ft();tn()});var LS=i(()=>{"use strict";CS();Za();TS();PS();AS()});import{z as $}from"zod";var cce,vT,uce,pu=i(()=>{"use strict";y();cce=$.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()}),vT=$.tuple([$.number().int().nonnegative(),$.number().int().nonnegative()]).readonly(),uce=$.object({id:$.string().min(1),sourceMentionId:$.string().min(1),targetMentionId:$.string().min(1),predicate:$.string().min(1),evidenceSentenceIds:$.array(vT).min(1),confidence:$.number().min(0).max(1).optional(),note:$.string().optional()})});var hu=i(()=>{"use strict";y();Me();Pn();pu()});var NS=i(()=>{"use strict";Pn();Qt();pu()});var eo=i(()=>{"use strict"});var WS=i(()=>{"use strict";ft();eo()});var fu=i(()=>{"use strict"});var DS=i(()=>{"use strict";ft()});var yu=i(()=>{"use strict"});var gu=i(()=>{"use strict";ft();eo();DS();yu()});var FS=i(()=>{"use strict";gu()});var GS=i(()=>{"use strict";Me()});var jS=i(()=>{"use strict";bc();In();Na()});import{z as M}from"zod";var US,_T,PT,AT,eue,tue,BS=i(()=>{"use strict";Ne();In();jS();US=M.object({head:M.string().optional(),mode:M.enum(["full","head_tail"]).optional(),tail:M.string().optional(),text:M.string().optional()}).strict(),_T=M.object({quote:M.string().optional(),sentence_id:M.string().optional()}).strict(),PT=M.union([M.object({end_anchor:M.union([M.string(),US]).optional(),quote:M.string().optional(),sentence_id:M.string().optional(),start_anchor:M.union([M.string(),US]).optional()}).strict(),M.array(_T)]),AT=M.object({confidence:M.number().min(0).max(1).optional(),evidence:PT,predicate:M.string().min(1).max(64),sourceMentionId:M.string().min(1),targetMentionId:M.string().min(1)}).strict(),eue=M.object({relations:M.array(AT)}).strict(),tue=new qt});var qS=i(()=>{"use strict"});var HS=i(()=>{"use strict";BS();qS()});var $S=i(()=>{"use strict";HS();eo();yu()});var bu=i(()=>{"use strict";Y();fu()});var zS=i(()=>{"use strict";ft();yt();hu();WS();fu();FS();GS();$S();bu()});var QS=i(()=>{"use strict"});var XS=i(()=>{"use strict";hu();NS();zS();gu();bu();QS()});var VS=i(()=>{"use strict";XS()});var di=i(()=>{"use strict";Y()});var Su=i(()=>{"use strict";yt()});var wu=i(()=>{"use strict";Me();yt();_n();di();Su()});var ew=i(()=>{"use strict";yt();di();wu()});var ku=i(()=>{"use strict";ye();Z()});var nw=i(()=>{"use strict";ye();ar();at();ku();Z()});var rw=i(()=>{"use strict";_n();ye();di();nw();ku();Z()});import{z as Xt}from"zod";var iw,Dle,aw=i(()=>{"use strict";iw=Xt.object({children:Xt.lazy(()=>Xt.array(iw)),uri:Xt.string().min(1),title:Xt.string().nullable().optional()}).strict(),Dle=Xt.object({chapters:Xt.array(iw)}).strict()});var ow=i(()=>{"use strict";Y()});var sw=i(()=>{"use strict";ew();di();wu();rw();Su();aw();ow()});var dw=i(()=>{"use strict";hr()});var Ve=i(()=>{"use strict";gg();ct();Kd();LS();VS();ct();Lc();sw();dw();ba()});async function Bw(t="global"){let e=await _u(),n=Ze(),r=Date.now(),a=!1;try{await e.transaction(async()=>{await X_(e),await e.run(`
|
|
764
781
|
INSERT OR IGNORE INTO gc_locks (
|
|
765
782
|
scope, owner_id, owner_pid, heartbeat_at, created_at
|
|
766
783
|
) VALUES (?, ?, ?, ?, ?)
|
|
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(()=>{
|
|
784
|
+
`,[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(()=>{Q_(t,n).catch(()=>{})},z_);return async()=>{clearInterval(o);let s=await _u();try{await s.run("DELETE FROM gc_locks WHERE scope = ? AND owner_id = ?",[t,n])}finally{await s.close()}}}async function Q_(t,e){let n=await _u();try{await n.run(`
|
|
768
785
|
UPDATE gc_locks
|
|
769
786
|
SET heartbeat_at = ?, owner_pid = ?
|
|
770
787
|
WHERE scope = ? AND owner_id = ?
|
|
771
|
-
`,[Date.now(),0,t,e])}finally{await n.close()}}async function
|
|
788
|
+
`,[Date.now(),0,t,e])}finally{await n.close()}}async function X_(t){let e=await t.queryAll("SELECT * FROM gc_locks",void 0,Z_);for(let{lock:n,scope:r}of e.filter(({lock:a})=>V_(a)))await t.run(`
|
|
772
789
|
DELETE FROM gc_locks
|
|
773
790
|
WHERE scope = ?
|
|
774
791
|
AND owner_id = ?
|
|
775
792
|
AND heartbeat_at = ?
|
|
776
|
-
`,[r,n.ownerId,n.heartbeatAt])}function
|
|
793
|
+
`,[r,n.ownerId,n.heartbeatAt])}function V_(t){return!(Date.now()-t.heartbeatAt<K_)}async function _u(){return await X("tmp/gc.sqlite",J_)}function Y_(t){return{createdAt:S(t,"created_at"),heartbeatAt:S(t,"heartbeat_at"),ownerId:E(t,"owner_id"),ownerPid:S(t,"owner_pid")}}function Z_(t){return{lock:Y_(t),scope:E(t,"scope")}}var J_,K_,z_,qw=i(()=>{"use strict";F();w();_();J_=`
|
|
777
794
|
CREATE TABLE IF NOT EXISTS gc_locks (
|
|
778
795
|
scope TEXT PRIMARY KEY,
|
|
779
796
|
owner_id TEXT NOT NULL,
|
|
@@ -781,8 +798,8 @@ CREATE TABLE IF NOT EXISTS gc_locks (
|
|
|
781
798
|
heartbeat_at INTEGER NOT NULL,
|
|
782
799
|
created_at INTEGER NOT NULL
|
|
783
800
|
);
|
|
784
|
-
`,
|
|
785
|
-
`)}var
|
|
786
|
-
`}function
|
|
801
|
+
`,K_=6e4,z_=2e4});async function Hw(t){let e=await R().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 tP(e)){n+=1;let s=await Ye(o.value);if(!t.force&&(s===void 0||t.now-s<eP))continue;let d=await pt(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 tP(t){let e=[];for(let n of await t.list())if(U(n))for(let r of await n.list())e.push({parent:n,value:r});return e}var eP,$w=i(()=>{"use strict";y();Od();eP=3600*1e3});async function co(t={}){let e=Date.now(),n=await Bw();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 aP(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 nP)a.push(await iP(s,r));let o={finishedAt:Date.now(),freedBytes:Pu(a,"freedBytes"),jobs:a,removed:Pu(a,"removed"),scanned:Pu(a,"scanned"),skipped:!1,startedAt:e};return await oP(o.finishedAt).catch(()=>{}),o}finally{await n()}}async function iP(t,e){try{return{name:t.name,...await t.run(e)}}catch(n){return{error:en(n),freedBytes:0,name:t.name,removed:0,scanned:0}}}function Pu(t,e){return t.reduce((n,r)=>{let a=r[e];return n+(typeof a=="number"?a:0)},0)}async function aP(t){let e=await J(R().library,"tmp/gc.last-run"),n=Number((e===void 0?"":await ae(e).catch(()=>"")).trim());return!Number.isFinite(n)||t-n>=rP}async function oP(t){let e=await H(R().library,"tmp/gc.last-run");await me(e,`${t}
|
|
802
|
+
`)}var nP,rP,Jw=i(()=>{"use strict";y();ct();Ve();Le();Ca();oc();pe();qw();$w();nP=[{name:"wikg-coordinator",run:wa},{name:"search-cache",run:Mi},{name:"library-index",run:Ef},{name:"build-queue",run:Ia},{name:"wikimedia-cache",run:ic},{name:"tmp",run:Hw}],rP=600*1e3});var Kw=i(()=>{"use strict";Jw()});var zw=i(()=>{"use strict";Kw()});var Qw={};Zw(Qw,{tryRunWikiGraphGc:()=>sP});async function sP(t={}){Un();let{stateDir:e,...n}=t;return await Zt(e,async()=>await co(n))}var Xw=i(()=>{"use strict";zw();de()});de();import{AsyncLocalStorage as G_}from"async_hooks";import{randomUUID as jfe}from"crypto";import{link as Bfe,mkdtemp as qfe,rename as Hfe,rm as $fe,stat as Jfe}from"fs/promises";import{tmpdir as zfe}from"os";import{basename as Xfe,dirname as Vfe,join as Yfe}from"path";import{Readable as eye}from"stream";Me();y();yi();import{z as qn}from"zod";var Rk=1,FP=qn.object({completedAt:qn.string().optional(),startedAt:qn.string(),status:qn.enum(["running","succeeded"]),version:qn.literal(Rk)});Ro();tn();et();Z();To();Fn();Ca();In();oc();ft();fc();Ve();ye();Le();_();at();ct();_();ar();_i();vi();Qt();y();nt();Je();lt();ut();vd();vi();Ca();hn();Qt();_();y();Le();y();w();w();y();w();y();ms();y();pe();Ve();Ve();Ve();Ve();Ve();yt();ft();_();Pn();y();import{createHash as ife}from"crypto";import{createReadStream as ofe}from"fs";import{rm as dfe}from"fs/promises";import{basename as ufe}from"path";import{createAnthropic as lhe}from"@ai-sdk/anthropic";import{createGoogleGenerativeAI as phe}from"@ai-sdk/google";import{createOpenAI as fhe}from"@ai-sdk/openai";import{createOpenAICompatible as ghe}from"@ai-sdk/openai-compatible";de();import{z as re}from"zod";import{AsyncLocalStorage as x_}from"async_hooks";var Rw=Symbol.for("wiki-graph-sdk.runtime-context.v1"),I_=E_();function E_(){let t=globalThis,e=t[Rw];if(e!==void 0)return e;let n=new x_;return Object.defineProperty(t,Rw,{configurable:!1,enumerable:!1,value:n,writable:!1}),n}async function vu(t,e){return await I_.run(t,e)}de();import{join as Rhe}from"path";import{homedir as The}from"os";var R_=["anthropic","google","openai","openai-compatible"],Cw=re.enum(R_),Ohe=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:Cw.optional()}).optional(),model:re.string().min(1).optional(),name:re.string().min(1).optional(),provider:Cw.optional()});import{homedir as Mhe}from"os";import{isAbsolute as Ghe,resolve as jhe}from"path";import{realpath as Hhe,stat as $he}from"fs/promises";import{basename as Khe,dirname as zhe,isAbsolute as Qhe,join as Xhe,relative as Vhe,resolve as Yhe}from"path";de();de();import{embed as kfe,embedMany as xfe}from"ai";import{createOpenAI as Efe}from"@ai-sdk/openai";import{createOpenAICompatible as Rfe}from"@ai-sdk/openai-compatible";import{spawn as fye}from"child_process";import{streamText as Pye}from"ai";Ve();de();var M_=["WIKIGRAPH_DEV","WIKIGRAPH_ENV_POLICY","WIKIGRAPH_QUEUE_DISABLE_AUTOSTART","WIKIGRAPH_STATE_DIR"];function Nw(t){let e=F_(t.env);if(t.envPolicy==="production"){let o=M_.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=Ow(t.stateDir??n);if(r===void 0)throw new Error("Wiki Graph development entries require an explicit runtime state directory.");let a=Ow(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 F_(t){return t===void 0?{...process.env}:{...process.env,...t}}function Ow(t){if(!(t===void 0||t.trim()===""))return t}de();de();import{mkdir as Age}from"fs/promises";var Dge=64*1024;de();import{basename as jge}from"path";de();de();var j_=new G_;async function Ww(t,e){return await j_.run(t,async()=>await vu({cwd:t.cwd,env:t.env,envPolicy:t.envPolicy,providers:{},...t.stateDir===void 0?{}:{stateDir:t.stateDir}},e))}var Dw="--wikigraph-internal-child",Mw="--wikigraph-dev-project-root",Fw="--wikigraph-env-policy",Gw="--wikigraph-state-dir";async function jw(t,e){let n=U_(process.argv.slice(2));if(n.internalChild!==t)throw new Error("This Wiki Graph worker entry is internal.");let r=Nw({argv:n.argv,devProjectRoot:n.devProjectRoot,envPolicy:n.envPolicy,stateDir:n.stateDir});return await Zt(r.stateDir,async()=>Ww({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 U_(t){let e=[],n,r,a="production",o;for(let s=0;s<t.length;s+=1){let d=t[s];if(d===Dw){if(s+1>=t.length)throw new Error(`${Dw} requires a value.`);n=t[s+1],s+=1;continue}if(d===Fw){let c=t[s+1];if(c!=="development"&&c!=="production")throw new Error(`${Fw} requires development or production.`);a=c,s+=1;continue}if(d===Mw){let c=t[s+1];if(c===void 0||c.trim()==="")throw new Error(`${Mw} requires a value.`);r=c,s+=1;continue}if(d!==Gw){e.push(d);continue}if(s+1>=t.length)throw new Error(`${Gw} requires a value.`);o=t[s+1],s+=1}return{argv:e,devProjectRoot:r,envPolicy:a,internalChild:n??"",stateDir:o}}var B_={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 Jbe}from"path";import{createReadStream as eSe}from"fs";import{mkdtemp as nSe,rm as rSe}from"fs/promises";import{join as aSe}from"path";import{tmpdir as sSe}from"os";var q_=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 Uw(t){return`${JSON.stringify(Tu(t),null,2)}
|
|
803
|
+
`}function Tu(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>Tu(e)??null);if(typeof t=="object")return H_(t)}function H_(t){let e=Object.entries(t).map(([r,a],o)=>({index:o,key:r,priority:q_.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=Tu(r.value);a!==void 0&&(n[r.key]=a)}return n}import{homedir as ySe}from"os";import{isAbsolute as bSe,relative as SSe,resolve as wSe}from"path";import{existsSync as vSe,readFileSync as RSe}from"fs";import{dirname as TSe,join as _Se,parse as PSe,resolve as ASe}from"path";Un();var{tryRunWikiGraphGc:dP}=await Promise.resolve().then(()=>(Xw(),Qw));async function cP(){await jw("gc-worker",async({argv:t})=>{let e=uP(t);process.stdout.write(Uw(await dP({dryRun:e.dryRun,force:e.force})))})}function uP(t){return{dryRun:t.includes("--dry-run"),force:t.includes("--force")}}cP().catch(t=>{process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}
|
|
787
804
|
`),process.exitCode=1});
|
|
788
805
|
//# sourceMappingURL=gc-worker.js.map
|