book-index-ui 0.65.0 → 0.65.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ "use strict";var _t=Object.create;var Z=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,St=Object.prototype.hasOwnProperty;var Et=(o,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of It(t))!St.call(o,n)&&n!==e&&Z(o,n,{get:()=>t[n],enumerable:!(s=bt(t,n))||s.enumerable});return o};var vt=(o,t,e)=>(e=o!=null?_t(kt(o)):{},Et(t||!o||!o.__esModule?Z(e,"default",{value:o,enumerable:!0}):e,o));const xt=require("./variant-supplement.cjs"),At={official:0,draft:1},$t={0:"official",1:"draft"},Ct={book:0,collection:2,work:3,entity:4},Pt={0:"book",2:"collection",3:"work",4:"entity"},at=62n,ct=59n,lt=19n,ht=8n,ut=(1n<<40n)-1n,Tt=(1n<<3n)-1n,jt=(1n<<11n)-1n,Ft=(1n<<8n)-1n,C="0123456789abcdefghijklmnopqrstuvwxyz",dt=new Map;for(let o=0;o<C.length;o++)dt.set(C[o],BigInt(o));function A(o){if(o===0n)return C[0];let t="";for(;o>0n;)t=C[Number(o%36n)]+t,o=o/36n;return t}function D(o){let t=0n;for(const e of o){const s=dt.get(e);if(s===void 0)throw new Error(`Invalid Base36 character: ${e}`);t=t*36n+s}return t}const tt="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ft=new Map;for(let o=0;o<tt.length;o++)ft.set(tt[o],BigInt(o));function yt(o){let t=0n;for(const e of o){const s=ft.get(e);if(s===void 0)throw new Error(`Invalid Base58 character: ${e}`);t=t*58n+s}return t}function _(o){return/[A-Z]/.test(o)?yt(o):D(o)}const Lt=A,Rt=D;function k(o){const t=Number(o>>at&1n),e=Number(o>>ct&Tt),s=o>>lt&ut,n=Number(o>>ht&jt),i=Number(o&Ft);return{status:$t[t]??"draft",type:Pt[e]??"book",timestamp:s,machineId:n,sequence:i}}function j(o,t,e,s,n){return BigInt(At[o])<<at|BigInt(Ct[t])<<ct|(e&ut)<<lt|BigInt(s)<<ht|BigInt(n)}function S(o){return k(_(o))}function gt(o){return S(o).type}function Bt(o){return S(o).status}const F={book:"Book",collection:"Collection",work:"Work",entity:"Entity"},Mt={Book:"book",Collection:"collection",Work:"work",Entity:"entity"},x=16,Dt="附刻";function T(o){const t=n=>typeof n=="string"?n:(n==null?void 0:n.book_title)??"",e=[],s=[];for(const n of Array.isArray(o)?o:[])if(n&&typeof n=="object"&&n.type===Dt){const i=t(n);i&&e.push(i)}else{const i=t(n);i&&s.push(i)}return{aliases:s,attached:e}}function $(o,t=x){let e=0;for(let s=0;s<o.length;s++)e=Math.imul(e,31)+o.charCodeAt(s)>>>0;return e%t}function Ot(o){const t={},e=o.dating;if(typeof e!="object"||e===null)return t;const s=e.era;typeof s=="string"&&s&&(t.era=s);const n=e.year;if(typeof n=="number")t.sort_year=n;else{const i=e.year_range;Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&(t.sort_year=i[0])}return t}function w(...o){const t=o.join("/");return t.startsWith("//")?"//"+t.slice(2).replace(/\/+/g,"/"):t.replace(/\/+/g,"/")}function Ut(o){if(!Array.isArray(o))return"";for(const t of o)if(typeof t=="object"&&t!==null){const e=t.dynasty;if(typeof e=="string"&&e)return e}return""}function et(o,t,e){var Q;const s=o.id||"";let n="",i="",r="";const c=o.authors;if(Array.isArray(c)&&c.length>0){const g=c[0];typeof g=="object"&&g!==null?(n=g.name||"",r=g.role||""):n=String(g)}else typeof c=="string"&&(n=c);i=Ut(c)||(typeof o.dynasty=="string"?o.dynasty:"");let a="";const l=o.current_location;if(typeof l=="object"&&l!==null?a=l.name||"":typeof l=="string"&&(a=l),!a&&Array.isArray(o.provenance)&&o.provenance.length>0){const g=(Q=o.provenance[0])==null?void 0:Q.institution;typeof g=="string"&&(a=g)}const h=T(o.additional_titles),u=Array.isArray(o.additional_titles)?h.aliases:void 0,d=h.attached.length>0?h.attached:void 0;let f;const m=o.juan_count;if(typeof m=="number"?f=m:typeof m=="object"&&m!==null&&(f=m.number||void 0),!f&&Array.isArray(o.measures)){const g=o.measures.find(I=>I&&I.unit==="卷"&&typeof I.number=="number"&&I.number>0);g&&(f=g.number)}const b=typeof o.measure_info=="string"?o.measure_info:"";let J=!1,W=!1;const H=o.resources;if(Array.isArray(H))for(const g of H){if(typeof g!="object"||g===null)continue;const I=g.types;Array.isArray(I)&&(I.includes("text")&&(J=!0),I.includes("image")&&(W=!0))}const y={id:s,title:o.title||"未命名",type:F[t],path:e,...Ot(o)};n&&(y.author=n),a&&(y.holder=a),u&&u.length>0&&(y.additional_titles=u),d&&d.length>0&&(y.attached_texts=d),f&&(y.juan_count=f),b&&(y.measure_info=b);const G=typeof o.edition=="string"?o.edition:"";G&&(y.edition=G),J&&(y.has_text=!0),W&&(y.has_image=!0),i&&(y.dynasty=i),r&&(y.role=r);const q=typeof o.subtype=="string"?o.subtype:"";q&&(y.subtype=q);const z=typeof o.period=="string"?o.period:"";z&&(y.period=z);const K=typeof o.loss_status=="string"?o.loss_status:"";K&&(y.loss_status=K);const V=typeof o.original_title=="string"?o.original_title:"";V&&(y.original_title=V);const Y=typeof o.work_id=="string"?o.work_id:"";Y&&(y.work_id=Y);const X=typeof o._promoted_to=="string"?o._promoted_to:"";return X&&(y.promoted_to=X),y}const Nt=60;function mt(o){const t=o.replace(/[^㐀-䶿一-鿿豈-﫿a-zA-Z0-9\u{20000}-\u{3134f}]/gu,"");return Array.from(t).slice(0,Nt).join("")||"Undefined"}class O{constructor(t,e){this.fs=t,this.officialRoot=w(e,"book-index"),this.draftRoot=w(e,"book-index-draft")}getRootByStatus(t){return t==="draft"?this.draftRoot:this.officialRoot}getRootById(t){const e=_(t),s=k(e);return this.getRootByStatus(s.status)}getPath(t,e,s){const n=this.getRootById(e),i=e.padEnd(3,"_").substring(0,3),[r,c,a]=[i[0],i[1],i[2]],l=F[t];return w(n,l,r,c,a,`${e}-${mt(s)}.json`)}async saveItem(t,e,s){const n=s.title||s.书名||"未命名",i=s.edition||"",r=i?`${n}${i}`:n,c=this.getPath(t,e,r),a=await this.findFileById(e);if(a&&a!==c)try{await this.fs.deleteFile(a)}catch{}const l=c.substring(0,c.lastIndexOf("/"));await this.fs.mkdir(l),s.id=e,s.type=t,await this.fs.writeFile(c,JSON.stringify(s,Jt,2));const h=this.getRootById(e),u=c.substring(h.length+1);return await this.updateIndexEntry(h,s,t,u),c}async updateIndexEntry(t,e,s,n){const i=e.id||"";if(!i)return;const r=`${s}s`,c=await this.loadShard(t,r,i),a=et(e,s,n);c[i]=a,await this.saveShard(t,r,i,c)}async deleteItem(t){const e=await this.findFileById(t);if(!e)return!1;const s=_(t),n=k(s),i=this.getRootByStatus(n.status),r=`${n.type}s`,c=await this.loadShard(i,r,t);return c[t]&&(delete c[t],await this.saveShard(i,r,t,c)),await this.fs.deleteFile(e),!0}async findFileById(t){const e=t.padEnd(3,"_").substring(0,3),[s,n,i]=[e[0],e[1],e[2]];for(const r of[this.officialRoot,this.draftRoot])for(const c of["Book","Collection","Work"]){const a=w(r,c,s,n,i);if(await this.fs.exists(a))try{const h=(await this.fs.readdir(a)).find(u=>u.startsWith(`${t}-`)&&u.endsWith(".json"));if(h)return w(a,h)}catch{}}return null}async loadMetadata(t){try{const e=await this.fs.readFile(t);return JSON.parse(e)}catch{return{}}}async getItem(t){const e=await this.findFileById(t);if(!e)return null;const s=await this.loadMetadata(e);return Object.keys(s).length>0?s:null}async loadEntries(t,e){const s=e?[this.getRootByStatus(e)]:[this.officialRoot,this.draftRoot],n=[],i=`${t}s`;for(const r of s){const c=await this.loadAllShards(r,i);for(const[a,l]of Object.entries(c))n.push({id:a,title:l.title,type:t,author:l.author||void 0,dynasty:l.dynasty||void 0,role:l.role||void 0,path:w(r,l.path),additional_titles:l.additional_titles,attached_texts:l.attached_texts,edition:l.edition,juan_count:l.juan_count,has_text:l.has_text,has_image:l.has_image,era:l.era,sort_year:l.sort_year})}return n}async searchEntries(t,e,s){const n=await this.loadEntries(e,s);return R(n,t)}async searchAll(t,e=5,s){const n=["work","book","collection"],i=await Promise.all(n.map(r=>this.searchEntries(t,r,s)));return{works:i[0].slice(0,e),books:i[1].slice(0,e),collections:i[2].slice(0,e),totalWorks:i[0].length,totalBooks:i[1].length,totalCollections:i[2].length}}async rebuildIndex(t){const e=this.getRootByStatus(t),s={books:Object.fromEntries(Array.from({length:x},(n,i)=>[i,{}])),collections:{0:{}},works:Object.fromEntries(Array.from({length:x},(n,i)=>[i,{}]))};for(const n of["Book","Collection","Work"]){const i=w(e,n);if(!await this.fs.exists(i))continue;const r=Mt[n],c=`${r}s`,a=await this.fs.glob(i,"**/*.json");for(const l of a)if(!l.includes("/index/"))try{const h=await this.loadMetadata(l);let u=h.id||h.ID||"";if(!u){const b=l.substring(l.lastIndexOf("/")+1);b.includes("-")&&(u=b.split("-")[0])}if(!u)continue;const d=l.substring(e.length+1),f=et({...h,id:u},r,d),m=c==="collections"?0:$(u);s[c][m][u]=f}catch{}}for(const[n,i]of Object.entries(s))for(const[r,c]of Object.entries(i)){const a=this.shardPath(e,n,Number(r)),l=a.substring(0,a.lastIndexOf("/"));await this.fs.mkdir(l),await this.fs.writeFile(a,JSON.stringify(st(c),null,await this.detectShardIndent(a)))}}getAssetDir(t){const e=this.getRootById(t),s=_(t),i=k(s).type,r=t.padEnd(3,"_").substring(0,3),[c,a,l]=[r[0],r[1],r[2]],h=F[i];return w(e,h,c,a,l,t)}async initAssetDir(t){const e=this.getAssetDir(t);return await this.fs.mkdir(e),e}async hasAssetDir(t){const e=this.getAssetDir(t);return this.fs.exists(e)}shardPath(t,e,s){return e==="collections"?w(t,"index","collections.json"):w(t,"index",e,`${s.toString(16)}.json`)}async loadShard(t,e,s){const n=$(s),i=this.shardPath(t,e,n);try{if(!await this.fs.exists(i))return{};const r=await this.fs.readFile(i);return JSON.parse(r)}catch{return{}}}async detectShardIndent(t,e=2){try{if(!await this.fs.exists(t))return e;const n=(await this.fs.readFile(t)).split(`
2
+ `)[1];if(n===void 0)return e;const i=n.replace(/^ +/,"");return!i||i.startsWith("}")?e:n.length-i.length||e}catch{return e}}async saveShard(t,e,s,n){const i=$(s),r=this.shardPath(t,e,i),c=r.substring(0,r.lastIndexOf("/"));await this.fs.mkdir(c);const a=await this.detectShardIndent(r);await this.fs.writeFile(r,JSON.stringify(st(n),null,a))}async loadAllShards(t,e){const s={};if(e==="collections"){const n=this.shardPath(t,e,0);try{if(await this.fs.exists(n)){const i=await this.fs.readFile(n);Object.assign(s,JSON.parse(i))}}catch{}return s}for(let n=0;n<x;n++){const i=this.shardPath(t,e,n);try{if(await this.fs.exists(i)){const r=await this.fs.readFile(i);Object.assign(s,JSON.parse(r))}}catch{}}return s}}function L(o,t){const e=t.toLowerCase();let s=0;const n=o.title.toLowerCase();n===e?s=200:n.startsWith(e)?s=150:n.includes(e)&&(s=100);const i=[...o.additional_titles||[],...o.attached_texts||[]];for(const l of i){const h=l.toLowerCase();h===e?s=Math.max(s,120):h.startsWith(e)?s=Math.max(s,90):h.includes(e)&&(s=Math.max(s,60))}let r=0;if(o.author){const l=o.author.toLowerCase();l===e?r=80:l.includes(e)&&(r=50)}let c=0;o.dynasty&&o.dynasty.toLowerCase().includes(e)&&(c=30);let a=s;return a===0&&(a=Math.max(r,c)),a===0?0:(a+=Math.max(0,20-n.length),o.type==="work"?a=Math.round(a*1.05):o.type==="collection"&&(a=Math.round(a*1.02)),o.has_text&&(a+=3),o.has_image&&(a+=2),a)}function st(o){const t={};for(const e of Object.keys(o).sort())t[e]=o[e];return t}function Jt(o,t){return t===null?void 0:t}function R(o,t){const e=o.map(s=>({entry:s,score:L(s,t)})).filter(s=>s.score>0);return e.sort((s,n)=>n.score!==s.score?n.score-s.score:s.entry.title.length-n.entry.title.length),e.map(s=>s.entry)}function nt(o,t,e,s){const n=o.map(i=>{const r=L(i,t);let c=0;const a=s[i.id];if(a&&e){const l={...i,title:a.t??i.title,author:a.a??i.author,additional_titles:a.at??i.additional_titles,attached_texts:a.axt??i.attached_texts};c=L(l,e)}return{entry:i,score:Math.max(r,c)}}).filter(i=>i.score>0);return n.sort((i,r)=>r.score!==i.score?r.score-i.score:i.entry.title.length-r.entry.title.length),n.map(i=>i.entry)}function Wt(o){const t=o.volumes??[];let e,s;if(t.length===0)e=[];else if(typeof t[0]=="number")e=t;else{s=[],e=[];for(const i of t){const r=i.volume;e.push(r);const c={};for(const[a,l]of Object.entries(i))a==="volume"||a==="status"||a==="file"||typeof l=="string"&&(a.includes("url")||a.includes("id"))&&(c[a]=l);s.push({volume:r,status:i.status,urls:Object.keys(c).length>0?c:void 0,file:i.file})}}const n={title:o.title??"",book_id:o.book_id??null,work_id:o.work_id??null,volumes:e,section:o.section,sub_items:o.sub_items,edition:o.edition,expected_volumes:o.expected_volumes,found_volumes:o.found_volumes,missing_volumes:o.missing_vols??o.missing_volumes};s&&(n.volume_details=s);for(const i of Object.keys(n))n[i]===void 0&&delete n[i];return n}function Ht(o){const t={total_books:o.total_books??0};return o.processed_volumes!=null&&(t.processed_volumes=o.processed_volumes),o.matched_works!=null&&(t.matched_works=o.matched_works),o.unmatched_works!=null&&(t.unmatched_works=o.unmatched_works),o.total_found_volumes!=null&&(t.total_found_volumes=o.total_found_volumes),t}function U(o){var n;const t=o,e=(t.books??[]).map(Wt),s={collection_id:t.collection_id??"",title:t.title??"",total_volumes:t.total_volumes??0,stats:Ht(t.stats??{}),books:e};return t.source&&(s.source=t.source),t.resource_id&&(s.resource_id=t.resource_id),t.resource_name&&(s.resource_name=t.resource_name),(n=t.sections)!=null&&n.length&&(s.sections=t.sections),t.volume_index&&Object.keys(t.volume_index).length>0&&(s.volume_index=t.volume_index),s}const ot=2;function P(o){const t=new Map;if(!o||typeof o!="object")return t;const e=o;if(typeof e.version!="number")return console.warn("[promotions] missing version field; treating as empty"),t;if(e.version!==1)return console.warn(`[promotions] unknown version ${e.version}; treating as empty`),t;const s=e.promotions;if(!s||typeof s!="object")return t;for(const[n,i]of Object.entries(s))i&&typeof i=="object"&&typeof i.production_id=="string"&&t.set(n,i.production_id);return t}const Gt={㐫:"凶",㐮:"襄",㐲:"伏",㑹:"會",㒒:"僕",㒵:"貌",㒺:"罔",㓂:"寇",㓕:"滅",㓗:"潔",㓙:"凶",㓛:"功",㓜:"幼",㔻:"丕",㕑:"廚",㕓:"廛",㕔:"廳",㕘:"參",㗋:"喉",㗖:"啖",㘭:"坳",㛰:"婚",㝛:"宿",㝠:"冥",㝡:"最",㝢:"宇",㝷:"尋",㟁:"岸",㠯:"以",㠶:"帆",㡌:"帽",㡬:"幾",㡳:"底",㢘:"廉",㢮:"弛",㢲:"巽",㣲:"微",㤀:"忘",㤗:"泰",㤙:"恩",㦯:"或",㦲:"哉",㦸:"戟",㧞:"拔",㨗:"捷",㨿:"據",㩀:"據",㩦:"攜",㪚:"散",㪷:"斗",㫁:"斷",㫄:"旁",㫖:"旨",㫤:"昶",㬥:"暴",㬰:"臾",㭍:"漆",㮚:"栗",㮣:"概",㯶:"棕",㯽:"檳",㰱:"歃",㱕:"歸",㳂:"沿",㳙:"涓",㳟:"恭",㳫:"沓",㳺:"游",㴱:"深",㵎:"澗",㵼:"瀉",㶑:"瀲",㶚:"灞",㷀:"煢",㸃:"點",㸑:"爨",㸔:"看",㽔:"蕤",㽞:"留",䂓:"規",䄂:"袖",䆒:"究",䆫:"窗",䆳:"邃",䇿:"策",䋲:"繩",䌫:"纜",䍐:"罕",䍧:"牂",䏻:"能",䑓:"臺",䑕:"鼠",䑛:"舐",䓁:"等",䓻:"蔻",䕃:"蔭",䕫:"夔",䕶:"護",䖍:"虔",䖏:"處",䖝:"虫",䖟:"虻",䘏:"卹",䘚:"卒",䘮:"喪",䙝:"褻",䛕:"諛",䜛:"讒",䜟:"讖",䜴:"豉",䜿:"豎",䝉:"蒙",䟦:"跋",䟽:"疏",䡖:"輕",䢴:"邗",䦨:"闌",䧏:"隆",䧟:"陷",䧺:"雄",䨇:"雙",䬃:"颯",䭾:"馱",䰟:"魂",䲭:"鴟",䴡:"麗",丅:"下",丗:"世",両:"兩",乆:"久",乗:"乘",亁:"乾",亊:"事",亷:"廉",亾:"亡",仭:"仞",伃:"妤",伷:"胄",佀:"似",倂:"併",倐:"倏",値:"值",偹:"備",僃:"備",儛:"舞",儞:"你",兊:"兌",兎:"兔",児:"兒",兠:"兜",兾:"冀",冄:"冉",冝:"宜",冦:"寇",冨:"富",冩:"写",冺:"泯",凂:"浼",凃:"涂",凖:"準",凟:"瀆",凢:"凡",凴:"憑",凾:"函",刋:"刊",刦:"劫",刧:"劫",刼:"劫",剏:"創",剙:"創",剰:"剩",劎:"劍",劒:"劍",劔:"劍",効:"效",勅:"敕",勲:"勛",匄:"丐",厪:"廑",厫:"廒",厯:"歷",厰:"廠",収:"收",吿:"告",呉:"吳",呌:"叫",呑:"吞",呪:"咒",咲:"笑",唘:"啟",唫:"吟",嗸:"嗷",嘑:"呼",嘷:"嗥",噐:"器",嚢:"囊",嚻:"囂",囏:"艱",囘:"回",囬:"回",囯:"國",圎:"圓",圏:"圈",圗:"圖",垜:"垛",埀:"垂",埓:"埒",堦:"階",塜:"冢",塟:"葬",塡:"填",塩:"鹽",塲:"場",墖:"塔",増:"增",壊:"壞",壍:"塹",壷:"壺",壻:"婿",夀:"壽",変:"變",夣:"夢",夲:"本",奨:"獎",妬:"妒",姙:"妊",姢:"娟",姧:"奸",姫:"姬",娯:"娛",婣:"姻",媫:"婕",嫓:"媲",孶:"孳",宐:"宜",宻:"密",宼:"寇",寃:"冤",寕:"寧",寗:"甯",寛:"寬",寜:"寧",寳:"寶",尅:"剋",尓:"爾",尙:"尚",尫:"尪",尭:"堯",屛:"屏",岀:"出",峩:"峨",崈:"崇",崐:"崑",崕:"崖",崘:"崙",嵓:"巖",嵳:"嵯",嶤:"嶢",巗:"巖",巵:"卮",巻:"卷",帀:"匝",帬:"裙",帯:"帶",幇:"幫",幷:"并",庻:"庶",庿:"廟",廏:"廄",廐:"廄",廵:"巡",廸:"迪",廹:"迫",廻:"迴",廽:"迴",彂:"發",彚:"彙",彛:"彝",彜:"彝",彞:"彝",徃:"往",従:"從",徤:"健",徧:"遍",徳:"德",徴:"徵",忩:"匆",忼:"慷",怱:"匆",恊:"協",恠:"怪",恡:"吝",恱:"悅",恵:"惠",悞:"誤",悤:"匆",悪:"惡",悮:"誤",悳:"德",惒:"和",愞:"懦",愼:"慎",愽:"博",慙:"慚",慿:"憑",憇:"憩",憹:"惱",懐:"懷",懴:"懺",戅:"戇",戞:"戛",戦:"戰",戯:"戲",戱:"戲",戸:"戶",戹:"厄",戻:"戾",扄:"扃",扵:"於",抜:"拔",抝:"拗",挿:"插",捜:"搜",掦:"剔",掲:"揭",揑:"捏",揔:"總",揷:"插",揺:"搖",搃:"總",撃:"擊",擕:"攜",擥:"攬",擧:"舉",攅:"攢",攺:"改",敇:"敕",敍:"敘",敭:"揚",斈:"學",斉:"齊",斚:"斝",斾:"旆",旉:"敷",旜:"旃",旤:"禍",昬:"昏",昻:"昂",晧:"皓",晩:"晚",暁:"曉",暎:"映",暦:"曆",曁:"暨",曵:"曳",曺:"曹",曽:"曾",朂:"勖",朙:"明",朞:"期",朩:"木",朶:"朵",枿:"櫱",栁:"柳",栢:"柏",桺:"柳",梹:"檳",棃:"梨",椉:"乘",椘:"楚",椶:"棕",楽:"樂",槀:"槁",槖:"橐",槩:"概",樷:"叢",橅:"模",橰:"槔",檝:"楫",欝:"鬱",欵:"款",歘:"欻",歩:"步",歳:"歲",歴:"歷",殱:"殲",毎:"每",氊:"氈",氷:"冰",汚:"污",浄:"淨",涖:"蒞",涙:"淚",淸:"清",渇:"渴",渉:"涉",湏:"須",湼:"涅",滛:"淫",漑:"溉",潄:"漱",澁:"澀",澘:"潸",濓:"濂",濙:"瀅",濳:"潛",濵:"濱",濶:"闊",瀬:"瀨",灋:"法",灔:"灩",灮:"光",炁:"氣",烖:"災",烱:"炯",煑:"煮",煕:"熙",熈:"熙",熖:"焰",熺:"熹",爕:"燮",爼:"俎",牐:"閘",牕:"窗",犂:"犁",犫:"犨",狥:"徇",猨:"猿",珎:"珍",珤:"寶",瑇:"玳",瑠:"琉",璝:"瑰",瓈:"璃",瓉:"瓚",瓌:"瑰",甆:"瓷",甎:"磚",甞:"嘗",畆:"畝",畊:"耕",畒:"畝",畞:"畝",畧:"略",畨:"番",畮:"畝",畱:"留",畺:"疆",疉:"疊",疎:"疏",痩:"瘦",癎:"癇",皐:"皋",皥:"皞",皷:"鼓",盌:"碗",眀:"明",眂:"視",眡:"視",睂:"眉",瞤:"瞬",矟:"槊",矦:"侯",碁:"棋",礮:"炮",礲:"礱",禆:"裨",禇:"褚",禩:"祀",秔:"粳",稲:"稻",稾:"稿",穂:"穗",穉:"稚",穏:"穩",穣:"穰",穪:"稱",穽:"阱",窓:"窗",窰:"窯",窻:"窗",竆:"窮",竒:"奇",竚:"佇",竝:"並",竢:"俟",筓:"笄",筞:"策",筯:"箸",箆:"篦",箒:"帚",簒:"篡",簮:"簪",籖:"籤",粃:"秕",粧:"妝",糓:"穀",糺:"糾",絍:"紝",綂:"統",綘:"縫",継:"繼",緍:"緡",緜:"綿",緤:"紲",緫:"總",縀:"緞",縁:"緣",縂:"總",縦:"縱",繋:"繫",纉:"纘",纎:"纖",纒:"纏",罇:"樽",罸:"罰",羮:"羹",翺:"翱",耉:"耇",耼:"聃",聦:"聰",聨:"聯",聫:"聯",聮:"聯",聴:"聽",聼:"聽",肎:"肯",肹:"肸",肻:"肯",胷:"胸",脇:"脅",脗:"吻",膓:"腸",臈:"臘",臯:"皋",舎:"舍",舩:"船",艶:"豔",苢:"苡",苽:"菰",茘:"荔",茰:"萸",荘:"莊",莭:"節",莵:"菟",莾:"莽",菓:"果",葢:"蓋",蒭:"芻",蔲:"蔻",蔴:"麻",蔵:"藏",蕋:"蕊",蕐:"華",蕚:"萼",薫:"薰",藳:"稿",蘂:"蕊",蘓:"蘇",虗:"虛",虵:"蛇",蝱:"虻",蟇:"蟆",蠏:"蟹",蠒:"繭",蠧:"蠹",蠭:"蜂",衂:"衄",衇:"脈",衘:"銜",衞:"衛",袐:"祕",袴:"褲",袵:"衽",裦:"褒",裵:"裴",襃:"褒",襍:"雜",覇:"霸",覉:"羈",覊:"羈",覔:"覓",覧:"覽",覩:"睹",詧:"察",諌:"諫",諐:"愆",謌:"歌",謩:"謨",譍:"應",譛:"譖",讁:"謫",讃:"讚",讐:"讎",貎:"猊",貟:"員",賍:"贓",賔:"賓",賖:"賒",賛:"贊",贑:"贛",趂:"趁",踈:"疏",蹏:"蹄",蹷:"蹶",躭:"耽",軄:"職",軰:"輩",輙:"輒",輭:"軟",辝:"辭",辠:"罪",辤:"辭",迯:"逃",逈:"迥",逓:"遞",逥:"迴",逰:"遊",逹:"達",逺:"遠",遅:"遲",遟:"遲",邉:"邊",邜:"卯",郞:"郎",郷:"鄉",鄊:"鄉",鄕:"鄉",鄼:"酇",酧:"酬",醤:"醬",醸:"釀",醻:"酬",醿:"醾",釡:"釜",鉄:"鐵",錬:"鍊",鍳:"鑒",鎻:"鎖",鏁:"鎖",鐡:"鐵",鑚:"鑽",鑛:"礦",閙:"鬧",閠:"閏",関:"關",閴:"闃",闗:"關",闘:"鬥",陁:"陀",隂:"陰",隟:"隙",隠:"隱",隣:"鄰",隲:"騭",隷:"隸",靁:"雷",靑:"青",靣:"面",鞉:"鼗",鞌:"鞍",鞵:"鞋",鞾:"靴",韈:"襪",韮:"韭",頋:"顧",頟:"額",頥:"頤",頳:"赬",頴:"穎",頺:"頹",頼:"賴",顇:"悴",顕:"顯",顚:"顛",顦:"憔",颷:"飆",飇:"飆",飜:"翻",飡:"餐",飬:"養",飮:"飲",飰:"飯",餙:"飾",饍:"膳",駈:"驅",駞:"駝",駵:"騮",騐:"驗",騘:"驄",髙:"高",髠:"髡",髤:"髹",髩:"鬢",髪:"髮",髴:"彿",鬂:"鬢",鬛:"鬣",鬪:"鬥",鬬:"鬥",鬭:"鬥",鬰:"鬱",鰌:"鰍",鰕:"蝦",鱓:"鱔",鳯:"鳳",鵞:"鵝",鵶:"鴉",鸎:"鶯",鸜:"鴝",麄:"粗",麕:"麇",麞:"獐",麺:"麵",黒:"黑",黙:"默",鼂:"晁",鼃:"蛙",鼈:"鱉",鼔:"鼓",齓:"齔",龎:"龐",龡:"吹","𠖇":"冥","𠞰":"剿","𠡠":"敕","𡨕":"冥","𢃄":"帶","𢎞":"弘","𢰅":"撰","𢷬":"搗","𣏌":"耜","𣙜":"榷","𣺌":"渺","𤦺":"琦","𤨏":"瑣","𤼵":"發","𥘉":"初","𥙷":"輔","𦂳":"緊","𦍑":"羌","𦕈":"眇","𦗟":"聽","𦙍":"胤","𦵏":"葬","𧰼":"象","𨼆":"隱","𨽻":"隸","𩔖":"類","𫉬":"獲","𫝊":"傳","𬒳":"被","兔":"兔"},pt=Gt;function wt(o){if(!o)return o;let t=!1,e="";for(const s of o){const n=pt[s]??xt.VARIANT_SUPPLEMENT[s];n!==void 0?(e+=n,t=!0):e+=s}return t?e:o}const qt="https://raw.githubusercontent.com",zt=["https://fastly.jsdelivr.net/gh","https://cdn.jsdelivr.net/gh"],Kt=5e3;class Vt{constructor(t){this.cache=null,this.cacheLoading=null,this.pathMap=new Map,this.promotions=new Map,this.searchSCache=null,this.t2sConverter=null,this.config={org:t.org,repos:t.repos,baseUrl:t.baseUrl??qt,cdnUrls:t.cdnUrls??zt,timeout:t.timeout??Kt}}async fetchPromotions(){try{const t=await this.fetchFileWithFallback(this.config.repos.draft,"promotions.json");return P(t)}catch{return new Map}}async ensureLoaded(){if(this.cache)return this.cache;if(this.cacheLoading)return this.cacheLoading;this.cacheLoading=(async()=>{let t=!1,e=!1;const[s,n,i]=await Promise.all([this.fetchPromotions(),this.fetchIndex(this.config.repos.draft).catch(a=>(console.warn("Failed to fetch draft index:",a),t=!0,{books:{},collections:{},works:{}})),this.fetchIndex(this.config.repos.official).catch(a=>(console.warn("Failed to fetch official index:",a),e=!0,{books:{},collections:{},works:{}}))]);if(this.promotions=s,t&&e)throw new Error("GithubStorage 已废弃:两个仓都读不到 index/ 分片。请改用 COS 产物或 BundleStorage。");const r=[...this.parseIndexResponse(n,!0),...this.parseIndexResponse(i,!1)],c=new Map;for(const a of r)a.isDraft&&a.promoted_to||c.set(a.id,a);return this.cache=Array.from(c.values()),this.cache})();try{return await this.cacheLoading}finally{this.cache||(this.cacheLoading=null)}}async fetchFileWithFallback(t,e){const s=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(e)}`;try{return await this.fetchJson(s)}catch{}for(const n of this.config.cdnUrls){const i=`${n}/${this.config.org}/${t}@main/${encodeURI(e)}`;try{return await this.fetchJson(i)}catch{continue}}throw new Error(`Failed to fetch ${e} for ${t} from all sources`)}async probeIndex(t){const e="index/collections.json",s=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(e)}`;try{if((await fetch(s,{method:"HEAD",signal:AbortSignal.timeout(this.config.timeout)})).ok)return!0}catch{}for(const r of this.config.cdnUrls){const c=`${r}/${this.config.org}/${t}@main/${encodeURI(e)}`;try{if((await fetch(c,{method:"HEAD",signal:AbortSignal.timeout(this.config.timeout)})).ok)return!0}catch{continue}}const n="index/works/0.json",i=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(n)}`;try{if((await fetch(i,{method:"HEAD",signal:AbortSignal.timeout(this.config.timeout)})).ok)return!0}catch{}for(const r of this.config.cdnUrls){const c=`${r}/${this.config.org}/${t}@main/${encodeURI(n)}`;try{if((await fetch(c,{method:"HEAD",signal:AbortSignal.timeout(this.config.timeout)})).ok)return!0}catch{continue}}return!1}async fetchIndex(t){if(!await this.probeIndex(t))throw new Error(`GithubStorage 已废弃:它读源仓的 index/ 分片,而 ${t} 已无 index/,读不到数据。请改用 COS 产物或 BundleStorage。`);const s={books:{},collections:{},works:{}};try{const i=await this.fetchFileWithFallback(t,"index/collections.json");s.collections=i}catch{}const n=[];for(const i of["books","works"])for(let r=0;r<x;r++){const c=`index/${i}/${r.toString(16)}.json`;n.push(this.fetchFileWithFallback(t,c).then(a=>{Object.assign(s[i],a)}).catch(()=>{}))}return await Promise.all(n),s}async fetchJson(t){const e=await fetch(t,{cache:"no-store",signal:AbortSignal.timeout(this.config.timeout)});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}parseIndexResponse(t,e){const s=[],n=[["books","book"],["collections","collection"],["works","work"],["entities","entity"]];for(const[i,r]of n){const c=t[i];if(c)for(const a of Object.values(c)){const l=a,h=T(l.additional_titles),u=r==="entity"?l.primary_name||a.title||a.name||a.id:a.title||a.name||a.id;s.push({id:a.id,title:u,type:r,isDraft:e,author:a.author,dynasty:a.dynasty,role:a.role,path:a.path,additional_titles:l.additional_titles?h.aliases:void 0,attached_texts:h.attached.length?h.attached:void 0,edition:l.edition,juan_count:l.juan_count,has_text:l.has_text,has_image:l.has_image,has_collated:l.has_collated,subtype:l.subtype,primary_name:l.primary_name,birth_year:l.birth_year,death_year:l.death_year,cbdb_id:l.cbdb_id,promoted_to:l.promoted_to}),this.pathMap.set(a.id,{path:a.path,isDraft:e})}}return s}async ensureSearchSBuilt(){var n,i;if(this.searchSCache)return{searchS:this.searchSCache,converter:this.t2sConverter||null};if(this.t2sConverter===!1)return{searchS:{},converter:null};try{const c=(await import("opencc-js")).Converter({from:"t",to:"cn"});this.t2sConverter=a=>c(wt(a))}catch{return this.t2sConverter=!1,this.searchSCache={},{searchS:{},converter:null}}const t=await this.ensureLoaded(),e=this.t2sConverter,s={};for(const r of t){const c={},a=e(r.title);if(a!==r.title&&(c.t=a),r.author){const l=e(r.author);l!==r.author&&(c.a=l)}if((n=r.additional_titles)!=null&&n.length){const l=r.additional_titles.map(e);l.some((h,u)=>h!==r.additional_titles[u])&&(c.at=l)}if((i=r.attached_texts)!=null&&i.length){const l=r.attached_texts.map(e);l.some((h,u)=>h!==r.attached_texts[u])&&(c.axt=l)}Object.keys(c).length>0&&(s[r.id]=c)}return this.searchSCache=s,{searchS:s,converter:e}}async loadEntries(t,e){let n=(await this.ensureLoaded()).filter(u=>u.type===t);const i=e.sortBy||"title",r=e.sortOrder||"asc";n.sort((u,d)=>{const f=String(u[i]??""),m=String(d[i]??""),b=f.localeCompare(m,"zh");return r==="asc"?b:-b});const c=e.page||1,a=e.pageSize||50,l=(c-1)*a;return{entries:n.slice(l,l+a),total:n.length,page:c,pageSize:a}}async search(t,e,s){const n=await this.ensureLoaded(),{searchS:i,converter:r}=await this.ensureSearchSBuilt(),c=n.filter(m=>m.type===e),a=r?r(t):void 0,h=Object.keys(i).length>0?nt(c,t,a,i):R(c,t),u=s.page||1,d=s.pageSize||50,f=(u-1)*d;return{entries:h.slice(f,f+d),total:h.length,page:u,pageSize:d}}async searchAll(t,e=5){const s=await this.ensureLoaded(),{searchS:n,converter:i}=await this.ensureSearchSBuilt(),r=["work","book","collection"],c=i?i(t):void 0,a=Object.keys(n).length>0,l=r.map(h=>{const u=s.filter(d=>d.type===h);return a?nt(u,t,c,n):R(u,t)});return{works:l[0].slice(0,e),books:l[1].slice(0,e),collections:l[2].slice(0,e),totalWorks:l[0].length,totalBooks:l[1].length,totalCollections:l[2].length}}async getItem(t){const e=await this.ensureLoaded(),s=this.promotions.get(t)??t,n=s!==t?t:void 0,i=this.pathMap.get(s);let r=null;if(i){const c=i.isDraft?this.config.repos.draft:this.config.repos.official;if(r=await this.fetchItemByPath(c,i.path),r){const a=e.find(l=>l.id===s);a!=null&&a.has_collated&&(r.has_collated=!0)}}else r=await this.findItemById(s);return r&&r.type==="entity"&&!r.title&&r.primary_name&&(r.title=r.primary_name),r&&n&&(r.redirected_from=n),r}async getEntry(t){const e=await this.ensureLoaded(),s=this.promotions.get(t)??t,n=s!==t?t:void 0,i=e.find(a=>a.id===s);if(i)return n?{...i,redirected_from:n}:i;const r=await this.findItemById(s);if(!r)return null;const c=this.buildEntryFromItem(s,r);return n?{...c,redirected_from:n}:c}async getAllEntries(){return this.ensureLoaded()}async saveItem(){throw new Error("GithubStorage 为只读模式,不支持保存")}async deleteItem(){throw new Error("GithubStorage 为只读模式,不支持删除")}async generateId(){throw new Error("GithubStorage 为只读模式,不支持生成 ID")}async fetchItemByPath(t,e){let s=null;const n=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(e)}`;try{s=await this.fetchJson(n)}catch{}if(!s)for(const i of this.config.cdnUrls){const r=`${i}/${this.config.org}/${t}@main/${encodeURI(e)}`;try{s=await this.fetchJson(r);break}catch{continue}}return s}async findItemById(t){const e={book:"Book",collection:"Collection",work:"Work",entity:"Entity"};let s,n;try{const h=k(_(t));s=h.type,n=h.status}catch{return null}const i=n==="draft"?this.config.repos.draft:this.config.repos.official,r=e[s],c=t.padEnd(3,"_").substring(0,3),a=`${r}/${c[0]}/${c[1]}/${c[2]}`,l=`https://api.github.com/repos/${this.config.org}/${i}/contents/${a}`;try{const h=await fetch(l,{signal:AbortSignal.timeout(this.config.timeout)});if(!h.ok)return null;const d=(await h.json()).find(m=>m.name.startsWith(`${t}-`)&&m.name.endsWith(".json"));if(!d)return null;const f=await this.fetchItemByPath(i,d.path);return f&&this.pathMap.set(t,{path:d.path,isDraft:n==="draft"}),f}catch{return null}}buildEntryFromItem(t,e){const s=(e.type||"").toLowerCase(),n=s==="work"?"work":s==="collection"?"collection":"book";let i;const r=e.authors;if(Array.isArray(r)&&r.length>0){const l=r[0];i=typeof l=="object"&&l!==null?l.name||"":String(l)}let c=!0;try{c=k(_(t)).status==="draft"}catch{}const a=this.pathMap.get(t);return{id:t,title:e.title||e.书名||t,type:n,isDraft:c,author:i,dynasty:e.dynasty,role:e.role,path:(a==null?void 0:a.path)||"",juan_count:e.n_juan,has_collated:e.has_collated}}async fetchFile(t,e){const s=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(e)}`;try{return await this.fetchJson(s)}catch{}for(const n of this.config.cdnUrls){const i=`${n}/${this.config.org}/${t}@main/${encodeURI(e)}`;try{return await this.fetchJson(i)}catch{continue}}return null}async resolveItemPath(t){await this.ensureLoaded();let e=this.pathMap.get(t);if(!e&&(await this.findItemById(t),e=this.pathMap.get(t),!e))return null;const s=e.isDraft?this.config.repos.draft:this.config.repos.official,n=e.path.substring(0,e.path.lastIndexOf("/"));return{repo:s,dir:n}}async getCollectionCatalogs(t){const e=await this.resolveItemPath(t);if(!e)return null;const s=await this.getItem(t);if(!s)return null;const n=s.resources||[];if(n.length===0)return null;const i=[];for(const r of n){const c=`${e.dir}/${t}/${r.id}/volume_book_mapping.json`,a=await this.fetchFile(e.repo,c);a&&i.push({resource_id:r.id,short_name:r.short_name,data:U(a)})}return i.length>0?i:null}async getCollectionCatalog(t){var s;const e=await this.getCollectionCatalogs(t);return((s=e==null?void 0:e[0])==null?void 0:s.data)??null}async getLineageGraph(t){const e=await this.resolveItemPath(t);if(!e)return null;const s=`${e.dir}/${t}/lineage_graph.json`;return this.fetchFile(e.repo,s)}async getCatalogProgress(){return this.fetchFile(this.config.repos.draft,"resource-catalog.json")}async getCollectionProgress(){return this.fetchFile(this.config.repos.draft,"resource-collection.json")}async getResourceProgress(){return this.fetchFile(this.config.repos.draft,"resource.json")}async getSiteProgress(){return this.fetchFile(this.config.repos.draft,"resource-site.json")}async getRecommended(){return this.fetchFile(this.config.repos.draft,"recommended.json")}clearCache(){this.cache=null,this.pathMap.clear(),this.searchSCache=null,this.t2sConverter=null}}const it=255;class N{constructor(t){if(this.lastTimestamp=-1,this.lastStatus=null,this.sequence=0,t<0||t>2047)throw new Error("Machine ID must be between 0 and 2047");this.machineId=t}nextId(t,e){let s=this._getCurrentTimestamp(t);if(s<this.lastTimestamp&&t===this.lastStatus)throw new Error("Clock moved backwards. Refusing to generate ID.");s===this.lastTimestamp&&t===this.lastStatus?(this.sequence=this.sequence+1&it,this.sequence===0&&(s=this._tilNextUnit(this.lastTimestamp,t))):this.sequence=0,this.lastTimestamp=s,this.lastStatus=t;const n=j(t,e,BigInt(s),this.machineId,this.sequence);return A(n)}nextIdRaw(t,e){let s=this._getCurrentTimestamp(t);if(s<this.lastTimestamp&&t===this.lastStatus)throw new Error("Clock moved backwards. Refusing to generate ID.");return s===this.lastTimestamp&&t===this.lastStatus?(this.sequence=this.sequence+1&it,this.sequence===0&&(s=this._tilNextUnit(this.lastTimestamp,t))):this.sequence=0,this.lastTimestamp=s,this.lastStatus=t,j(t,e,BigInt(s),this.machineId,this.sequence)}_getCurrentTimestamp(t){const e=Date.now();return t==="draft"?e:Math.floor(e/1e3)}_tilNextUnit(t,e){let s=this._getCurrentTimestamp(e);for(;s<=t;)s=this._getCurrentTimestamp(e);return s}}class Yt{constructor(t){this.recentEntities=[],this.storage=new O(t.fs,t.workspaceRoot),this.idGen=new N(t.machineId??0),this.fs=t.fs,this.workspaceRoot=t.workspaceRoot}async loadEntries(t,e){const s=await this.storage.loadEntries(t);return this.paginate(s,e)}async search(t,e,s){const n=await this.storage.searchEntries(t,e);return this.paginate(n,s)}async searchAll(t,e){return this.storage.searchAll(t,e)}async getItem(t){const e=await this.storage.getItem(t);return e&&e.type==="entity"&&!e.title&&e.primary_name&&(e.title=e.primary_name),e}async saveItem(t){const e=t.id;if(!e)throw new Error("metadata.id is required");const s=t.type||this.extractTypeFromId(e),n=await this.storage.saveItem(s,e,t);return{id:e,path:n}}async deleteItem(t){if(!await this.storage.deleteItem(t))throw new Error(`Item not found: ${t}`)}async generateId(t,e){return this.idGen.nextId(e,t)}async getEntry(t){const e=await this.storage.getItem(t);if(!e)return null;const s=e.type||this.extractTypeFromId(t);return{id:t,title:e.title||"未命名",type:s,author:this.extractAuthor(e),dynasty:this.extractYear(e)}}async getAllEntries(){const t=["book","collection","work"],e=[];for(const s of t){const n=await this.storage.loadEntries(s);e.push(...n)}return e}async getRelations(t){const e=await this.storage.getItem(t);if(!e)return null;const s={};if((e.type||this.extractTypeFromId(t))==="book"){if(e.work_id){const i=await this.resolveEntity(e.work_id);i&&(s.belongsToWork={...i,type:"work"})}if(e.contained_in&&Array.isArray(e.contained_in)&&e.contained_in.length>0){const i=e.contained_in[0],r=typeof i=="string"?i:i.id;if(r){const c=await this.resolveEntity(r);c&&(s.belongsToCollection={...c,type:"collection"})}}}return s}async linkEntity(t,e,s){const n=await this.storage.getItem(t);if(!n)throw new Error(`Source not found: ${t}`);const i=n.type||this.extractTypeFromId(t);switch(e){case"belongsToWork":case"work_id":n.work_id=s;break;case"belongsToCollection":case"contained_in":Array.isArray(n.contained_in)||(n.contained_in=[]);{const r=n.contained_in;r.some(a=>(typeof a=="string"?a:a.id)===s)||r.push({id:s})}break;default:throw new Error(`Unknown relation field: ${e}`)}await this.storage.saveItem(i,t,n)}async unlinkEntity(t,e){const s=await this.storage.getItem(t);if(!s)throw new Error(`Source not found: ${t}`);const n=s.type||this.extractTypeFromId(t);switch(e){case"belongsToWork":case"work_id":delete s.work_id;break;case"belongsToCollection":case"contained_in":s.contained_in=[];break;default:throw new Error(`Unknown relation field: ${e}`)}await this.storage.saveItem(n,t,s)}async createAndLink(t,e,s){const n=this.idGen.nextId("draft",s.type),i={id:n,type:s.type,title:s.title,...s.inheritData||{}};return await this.storage.saveItem(s.type,n,i),await this.linkEntity(t,e,n),{id:n}}async searchEntities(t,e){const s=e&&e!=="all"?[e]:["book","collection","work"],n=[];for(const i of s){const r=await this.storage.searchEntries(t,i);for(const c of r)n.push({id:c.id,title:c.title,type:c.type,author:c.author,dynasty:c.dynasty})}return n}async getRecentEntities(){return this.recentEntities}async addRecentEntity(t){this.recentEntities=[t,...this.recentEntities.filter(e=>e.id!==t.id)].slice(0,20)}async getCollectionCatalog(t){const e=await this.storage.findFileById(t);if(!e)return null;const n=e.substring(0,e.lastIndexOf("/"))+"/volume_book_mapping.json";try{const i=await this.storage.loadMetadata(n);return Object.keys(i).length===0?null:i}catch{return null}}async getRecommended(){const t=this.workspaceRoot+"/book-index-draft/recommended.json";try{const e=await this.fs.readFile(t);return JSON.parse(e)}catch{return null}}getAssetDir(t){return this.storage.getAssetDir(t)}async initAssetDir(t){return this.storage.initAssetDir(t)}async hasAssetDir(t){return this.storage.hasAssetDir(t)}getBookIndexStorage(){return this.storage}async rebuildIndex(t){await this.storage.rebuildIndex(t)}extractTypeFromId(t){try{const e=_(t);return k(e).type}catch{return"book"}}extractAuthor(t){const e=t.authors;if(Array.isArray(e)&&e.length>0){const s=e[0];return typeof s=="object"&&s!==null?s.name||"":String(s)}}extractYear(t){const e=t.publication_info;if(typeof e=="object"&&e!==null)return e.year||void 0}async resolveEntity(t){const e=await this.storage.getItem(t);return e?{id:t,title:e.title||"未命名"}:null}paginate(t,e){const s=e.page??1,n=e.pageSize??50;if(e.sortBy){const a=e.sortBy,l=e.sortOrder==="desc"?-1:1;t.sort((h,u)=>{const d=h[a]??"",f=u[a]??"";return d<f?-l:d>f?l:0})}const i=t.length,r=(s-1)*n;return{entries:t.slice(r,r+n),total:i,page:s,pageSize:n}}}function Xt(o){return o==="collated"||o==="self_collated"}const Qt=["default","manifest","fragments","sources","extra"],Zt=/^[a-z][a-z0-9-]*$/;function B(o){return typeof o!="string"?!1:o==="default"?!0:Zt.test(o)&&!Qt.includes(o)}function te(o){return/^\d+$/.test(o)}function v(o){return o.length>0&&!o.includes("..")&&!/[\\/?#%\s\u0000-\u001f\u007f]/.test(o)}const ee=/^(整理本|整理|转录全文|轉錄全文|转录|轉錄|全文|文本)$/;function se(o){var s;const t=ne(o),e=(s=o.edition_label)==null?void 0:s.trim();return e&&e!==t?`${e} · ${t}`:t}function ne(o){for(const t of[o.label,o.source_name]){const e=t==null?void 0:t.trim();if(e&&!ee.test(e))return e}return o.label||o.source_name||o.key}function oe(o,t){const e=(t==null?void 0:t.chapters)??[];if(e.length===0)return null;if(o){const s=e.find(n=>n.file===o.file);if(s)return s.file;if(o.n!==void 0){const n=e.find(i=>i.n===o.n);if(n)return n.file}}return e[0].file}function ie(o,t){const e=o==null?void 0:o.versions;if(!(!e||e.length===0))return(t!=null?e.find(s=>s.key===t):void 0)??e.find(s=>s.key==="default")??e[0]}const re="/data",ae=1e4;class ce{constructor(t={}){this.hubsLoading=null,this.chunkCache=new Map,this.chunkLoading=new Map,this.manifest=null,this.manifestLoading=null,this.entryFileCache=new Map,this.tiyaoCache=new Map,this.tiyaoLoading=new Map,this.metaCache=null,this.metaLoading=null,this.promotions=null,this.promotionsLoading=null,this.promotionsLoadFailed=!1,this.promotionShards=new Map,this.versionPromise=null,this.versionInjected=!1,this.basePath=t.basePath??re,this.timeout=t.timeout??ae,this.hubsPath=t.hubsPath??"_hubs.json",this.detailLayout=t.detailLayout??"auto",t.version!==void 0&&(this.version=t.version??null,this.versionInjected=!0)}async ensureVersion(){return this.version!==void 0?this.version:this.versionPromise?this.versionPromise:(this.versionPromise=(async()=>{try{const t=await fetch(`${this.basePath}/version.json`,{cache:"no-cache",signal:AbortSignal.timeout(this.timeout)});if(!t.ok)return null;const e=await t.json(),s=e==null?void 0:e.commitId;return!s||s==="unknown"?null:s.slice(0,12)}catch{return null}})(),this.version=await this.versionPromise,this.version)}async fetchJson(t){const e=await this.ensureVersion(),s=e?`${t}${t.includes("?")?"&":"?"}v=${e}`:t,n=await fetch(s,{cache:"no-cache",signal:AbortSignal.timeout(this.timeout)});if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);return n.json()}async ensurePromotions(){if(this.promotions)return this.promotions;if(this.promotionsLoading)return this.promotionsLoading;this.promotionsLoading=(async()=>{try{const t=await this.fetchJson(`${this.basePath}/promotions.json`);this.promotions=P(t),this.promotionsLoadFailed=!1}catch{this.promotions=new Map,this.promotionsLoadFailed=!0}return this.promotions})();try{return await this.promotionsLoading}finally{this.promotionsLoading=null}}promotionShard(t){const e=t.slice(-ot);let s=this.promotionShards.get(e);return s||(s=this.fetchJson(`${this.basePath}/promotions/${e}.json`).then(n=>{const i=P(n);return i.size>0?i:null},()=>null),this.promotionShards.set(e,s)),s}async canonicalIdFor(t){if(this.promotions&&!this.promotionsLoadFailed)return this.promotions.get(t)??t;if(t.length>=ot){const e=await this.promotionShard(t);if(e)return e.get(t)??t}return(await this.ensurePromotions()).get(t)??t}async loadManifest(){if(this.manifest)return this.manifest;if(this.manifestLoading)return this.manifestLoading;this.manifestLoading=(async()=>{try{this.manifest=await this.fetchJson(`${this.basePath}/chunks/_manifest.json`)}catch{this.manifest=[]}return this.manifest})();try{return await this.manifestLoading}finally{this.manifest||(this.manifestLoading=null)}}async resolvePrefix(t){const e=await this.loadManifest();let s=0,n=e.length-1,i=null;for(;s<=n;){const r=s+n>>1;e[r]<=t?(i=e[r],s=r+1):n=r-1}if(i&&t.startsWith(i))return i;for(const r of e)if(t.startsWith(r))return r;return null}async loadChunk(t){if(this.chunkCache.has(t))return this.chunkCache.get(t);const e=this.chunkLoading.get(t);if(e)return e;const s=(async()=>{try{const n=await this.fetchJson(`${this.basePath}/chunks/${t}.json`);return this.chunkCache.set(t,n),n}catch{return this.chunkCache.set(t,{}),{}}})();this.chunkLoading.set(t,s);try{return await s}finally{this.chunkLoading.delete(t)}}async loadDetail(t){return this.detailLayout!=="entry"&&((await this.loadManifest()).length>0||this.detailLayout==="chunks")?(await this.loadChunkForId(t))[t]||null:this.loadEntryFile(t)}loadEntryFile(t){let e=this.entryFileCache.get(t);return e||(e=this.fetchJson(`${this.basePath}/entry/${encodeURIComponent(t)}.json`).catch(()=>null),this.entryFileCache.set(t,e)),e}async loadChunkForId(t){const e=await this.resolvePrefix(t);return e?this.loadChunk(e):{}}async loadTiyaoGroup(t,e){const s=`${t}-${e}`;if(this.tiyaoCache.has(s))return this.tiyaoCache.get(s);const n=this.tiyaoLoading.get(s);if(n)return n;const i=c=>String(c).padStart(3,"0"),r=(async()=>{const c=await this.fetchJson(`${this.basePath}/tiyao/juan-${i(t)}-${i(e)}.json`);return this.tiyaoCache.set(s,c),c})();this.tiyaoLoading.set(s,r);try{return await r}finally{this.tiyaoLoading.delete(s)}}async getCounts(){if(this.metaCache)return this.metaCache;if(this.metaLoading){const t=await this.metaLoading;if(t)return t;throw new Error("BundleStorage: meta.json 加载失败")}this.metaLoading=(async()=>{const t=await this.fetchJson(`${this.basePath}/meta.json`);if(!t||typeof t.works!="number")throw new Error("BundleStorage: meta.json 格式无效");return this.metaCache=t,t})();try{const t=await this.metaLoading;if(!t)throw new Error("BundleStorage: meta.json 加载失败");return t}finally{this.metaLoading=null}}async getResourceCounts(){return(await this.getCounts()).resourceCounts??{hasText:0,hasImage:0}}async getSubtypeStats(){return(await this.getCounts()).subtypeStats??{}}async loadEntries(t,e){throw new Error("BundleStorage.loadEntries 已废弃:请使用 worker 搜索")}async search(t,e,s){throw new Error("BundleStorage.search 已废弃:请使用 worker 搜索")}async searchAll(t,e=5){throw new Error("BundleStorage.searchAll 已废弃:请使用 worker 搜索")}getHubs(){return this.hubsLoading??(this.hubsLoading=this.fetchJson(`${this.basePath}/${this.hubsPath}`).catch(()=>null)),this.hubsLoading}async getItem(t){try{const e=await this.canonicalIdFor(t),s=e!==t?t:void 0,n=await this.loadDetail(e);return n&&(n.type==="entity"&&!n.title&&n.primary_name&&(n.title=n.primary_name),s&&(n.redirected_from=s)),n}catch{return null}}async getEntry(t){var e,s;try{const n=await this.canonicalIdFor(t),i=n!==t?t:void 0,r=await this.loadDetail(n);if(!r)return null;const c=gt(n),a=T(r.additional_titles),l=c==="entity"?r.primary_name||r.title||r.name||n:r.title||r.name||n;return{id:n,title:l,type:c,isDraft:!0,author:r.author,dynasty:r.dynasty,role:r.role,additional_titles:r.additional_titles?a.aliases:void 0,attached_texts:a.attached.length?a.attached:void 0,edition:r.edition,juan_count:r.juan_count,has_text:r.has_text,has_image:r.has_image,has_collated:r.has_collated,subtype:r.subtype,primary_name:r.primary_name,birth_year:((e=r.dates)==null?void 0:e.birth)??void 0,death_year:((s=r.dates)==null?void 0:s.death)??void 0,cbdb_id:r.cbdb_id,...i?{redirected_from:i}:{}}}catch{return null}}async getAllEntries(){throw new Error("BundleStorage.getAllEntries 已废弃:请使用 getEntry / worker 搜索")}async saveItem(){throw new Error("BundleStorage 为只读模式,不支持保存")}async deleteItem(){throw new Error("BundleStorage 为只读模式,不支持删除")}async generateId(){throw new Error("BundleStorage 为只读模式,不支持生成 ID")}async getCollectionCatalogs(t){const e=await this.getItem(t);if(!e)return null;const s=e.resources||[];if(s.length===0)return null;const n=[];for(const i of s)try{const r=await this.fetchJson(`${this.basePath}/items/${t}/${i.id}/volume_book_mapping.json`);r&&n.push({resource_id:i.id,short_name:i.short_name,data:U(r)})}catch{}return n.length>0?n:null}async getCollectionCatalog(t){var s;const e=await this.getCollectionCatalogs(t);return((s=e==null?void 0:e[0])==null?void 0:s.data)??null}async getTextManifest(t){if(!v(t))return null;try{const e=await this.fetchJson(`${this.basePath}/items/${t}/manifest.json`);return e&&Array.isArray(e.versions)?e:null}catch{return null}}async getTextIndex(t,e){if(!v(t)||!B(e))return null;try{const s=await this.fetchJson(`${this.basePath}/items/${t}/${e}/index.json`);return s&&Array.isArray(s.chapters)?s:null}catch{return null}}async getChapter(t,e,s,n){if(!v(t)||!B(e)||!v(s))return null;const i=`${this.basePath}/items/${t}/${e}/${s}`,r=await this.ensureVersion(),c=r?`${i}.txt?v=${r}`:`${i}.txt`,a=fetch(c,{cache:"no-cache",signal:AbortSignal.timeout(this.timeout)}).then(d=>d.ok?d.text():null).catch(()=>null),l=n!=null&&n.json?this.fetchJson(`${i}.json`).catch(()=>null):Promise.resolve(null),[h,u]=await Promise.all([a,l]);return h!=null||u?{md:h,json:u}:null}async getLineageGraph(t){try{return await this.fetchJson(`${this.basePath}/items/${t}/lineage_graph.json`)}catch{return null}}async getCatalogProgress(){try{return await this.fetchJson(`${this.basePath}/resource-catalog.json`)}catch{return null}}async getCollectionProgress(){try{return await this.fetchJson(`${this.basePath}/resource-collection.json`)}catch{return null}}async getResourceProgress(){try{return await this.fetchJson(`${this.basePath}/resource.json`)}catch{return null}}async getSiteProgress(){try{return await this.fetchJson(`${this.basePath}/resource-site.json`)}catch{return null}}async getRecommended(){try{return await this.fetchJson(`${this.basePath}/recommended.json`)}catch{return null}}clearCache(){this.chunkCache.clear(),this.chunkLoading.clear(),this.manifest=null,this.manifestLoading=null,this.entryFileCache.clear(),this.tiyaoCache.clear(),this.tiyaoLoading.clear(),this.metaCache=null,this.metaLoading=null,this.versionInjected||(this.version=void 0,this.versionPromise=null)}}class E extends Error{constructor(t){super(t),this.name="BookIndexError"}}class le extends E{constructor(t){super(t),this.name="StorageError"}}class he extends E{constructor(t){super(t),this.name="IdGenerationError"}}class ue extends E{constructor(t){super(t),this.name="ConfigError"}}class de extends E{constructor(t){super(t),this.name="MigrationError"}}class fe{constructor(t,e,s=1){this.storage=new O(t,e),this.idGen=new N(s)}generateId(t="book",e="draft"){return this.idGen.nextIdRaw(e,t)}encodeId(t){return A(t)}decodeId(t){return _(t)}async saveItem(t,e,s="draft"){let n=t.id||t.ID;if(n)try{const r=S(n);e||(e=r.type)}catch{throw new E(`Invalid ID format: ${n}`)}else e||(e=t.type||"book"),n=this.idGen.nextId(s,e),t.id=n;return await this.storage.saveItem(e,n,t)}async getItem(t){return this.storage.getItem(t)}async findItemPath(t){return this.storage.findFileById(t)}async updateField(t,e,s){const n=await this.storage.findFileById(t);if(!n)return!1;try{const i=await this.storage.loadMetadata(n),r={基本信息:null,介绍:"description",资源:"resources",收藏历史:"history",其他版本:"related_books"},c=e in r?r[e]:e;if(c===null)return!1;if(c==="description"&&typeof s=="string"){const l=i[c]||{};i[c]={text:s,sources:l.sources||[]}}else i[c]=s;const a=S(t);return await this.storage.saveItem(a.type,t,i),!0}catch{return!1}}async deleteItem(t){return this.storage.deleteItem(t)}async rebuildIndices(){await this.storage.rebuildIndex("official"),await this.storage.rebuildIndex("draft")}getAssetDir(t){return this.storage.getAssetDir(t)}async initAssetDir(t){return this.storage.initAssetDir(t)}async hasAssetDir(t){return this.storage.hasAssetDir(t)}getStorage(){return this.storage}}const ye={wikisource:"wikisource",shidianguji:"shidianguji",archive:"archive",ctext:"ctext",nlc:"nlc","read.nlc":"nlc","db.sido":"sido","guji.artx":"guji-artx","digital.library":"digital-library"},rt=new Set(["text","image","physical","catalog","annotated"]),ge=new Set(["catalog","search"]),me=new Set(["com","org","net","cn","edu","gov","io","jp","tw","hk"]);function pe(o){if(!o)return"";try{const e=new URL(o).hostname;for(const[n,i]of Object.entries(ye))if(e.includes(n))return i;const s=e.split(".");if(s.length>=2){const n=s.filter(i=>!me.has(i)&&i.length>2);return n.length>0?n[n.length-1]:s[s.length-2]}return e}catch{return""}}function we(o){const t=[];o.name||t.push("name is required");let e=!1;if(o.types!==void 0)if(!Array.isArray(o.types)||o.types.length===0)t.push("types must be a non-empty array when present");else{for(const s of o.types)rt.has(s)||t.push(`invalid types atom '${s}', must be one of ${[...rt].join(", ")}`);e=o.types.length===1&&o.types[0]==="physical"}else t.push("types is required");return o.root_type&&!ge.has(o.root_type)&&t.push(`invalid root_type '${o.root_type}'`),!e&&!o.url&&t.push("url is required for non-physical resources"),t}const p=class p{constructor(t,e=""){if(this._type=null,this.title=e,typeof t=="string"){t.startsWith(p.PREFIX)&&(t=t.slice(p.PREFIX.length)),this.idStr=t;try{this.idInt=_(t)}catch{this.idInt=0n}}else this.idInt=t,this.idStr=A(t);if(this.idInt>0n)try{const s=S(this.idStr);this._type=s.type}catch{}}get type(){return this._type}getIcon(){return this._type===null?"":this._type==="book"?"📖 ":this._type==="collection"?"📚 ":this._type==="work"?"📜 ":""}render(t=!1){return`[${t?this.getIcon():""}${this.title}](${p.PREFIX}${this.idStr})`}static parseFromLink(t){const e=t.match(/\[(.*?)\]\((.*?)\)/);if(e){const s=e[1],n=e[2];if(n.startsWith(p.PREFIX)){const i=n.slice(p.PREFIX.length);return new p(i,s)}}return null}static isBidLink(t){return t.startsWith(p.PREFIX)}};p.PROTOCOL="bid:\\\\",p.PREFIX="bid:\\\\";let M=p;exports.BidLink=M;exports.BookIndexError=E;exports.BookIndexManager=fe;exports.BookIndexStorage=O;exports.BundleStorage=ce;exports.ConfigError=ue;exports.GithubStorage=Vt;exports.IdGenerationError=he;exports.IdGenerator=N;exports.LocalStorage=Yt;exports.MigrationError=de;exports.StorageError=le;exports.VARIANT_CHARS=pt;exports.base36Decode=D;exports.base36Encode=A;exports.base58Decode=yt;exports.buildId=j;exports.buildPromotionMap=P;exports.cleanName=mt;exports.decodeId=Rt;exports.decodeIdString=S;exports.encodeId=Lt;exports.extractIdFromUrl=pe;exports.extractStatus=Bt;exports.extractType=gt;exports.isChapterSegment=te;exports.isCollatedKind=Xt;exports.isSafeSegment=v;exports.isTextKey=B;exports.matchChapterAcrossVersions=oe;exports.normalizeCatalog=U;exports.normalizeVariants=wt;exports.parseId=k;exports.pickTextVersion=ie;exports.shardOf=$;exports.smartDecode=_;exports.splitExtraTitles=T;exports.textVersionLabel=se;exports.validateResource=we;
package/dist/storage.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./storage-entry-B6014X77.cjs");exports.BidLink=r.BidLink;exports.BookIndexError=r.BookIndexError;exports.BookIndexManager=r.BookIndexManager;exports.BookIndexStorage=r.BookIndexStorage;exports.BundleStorage=r.BundleStorage;exports.ConfigError=r.ConfigError;exports.GithubStorage=r.GithubStorage;exports.IdGenerationError=r.IdGenerationError;exports.IdGenerator=r.IdGenerator;exports.LocalStorage=r.LocalStorage;exports.MigrationError=r.MigrationError;exports.StorageError=r.StorageError;exports.buildPromotionMap=r.buildPromotionMap;exports.extractIdFromUrl=r.extractIdFromUrl;exports.validateResource=r.validateResource;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./storage-entry-h5vhXs0r.cjs");exports.BidLink=r.BidLink;exports.BookIndexError=r.BookIndexError;exports.BookIndexManager=r.BookIndexManager;exports.BookIndexStorage=r.BookIndexStorage;exports.BundleStorage=r.BundleStorage;exports.ConfigError=r.ConfigError;exports.GithubStorage=r.GithubStorage;exports.IdGenerationError=r.IdGenerationError;exports.IdGenerator=r.IdGenerator;exports.LocalStorage=r.LocalStorage;exports.MigrationError=r.MigrationError;exports.StorageError=r.StorageError;exports.buildPromotionMap=r.buildPromotionMap;exports.extractIdFromUrl=r.extractIdFromUrl;exports.validateResource=r.validateResource;
package/dist/storage.d.ts CHANGED
@@ -44,12 +44,10 @@ export declare interface BaseDetailData {
44
44
  /** 长篇附记(详情页展示,不进卡片/搜索摘要) */
45
45
  appendix?: AppendixEntry[];
46
46
  authors?: AuthorInfo[];
47
+ /** 别名(字符串);Book 上还可有 {book_title, type:'附刻'}=附刻之书(第 12 组 S2-T 起并入此处) */
47
48
  additional_titles?: (string | {
48
49
  book_title: string;
49
- })[];
50
- /** Book 附载篇目 */
51
- attached_texts?: (string | {
52
- book_title: string;
50
+ type?: string;
53
51
  })[];
54
52
  additional_works?: AdditionalWork[];
55
53
  indexed_by?: IndexedByEntry[];
@@ -71,6 +69,9 @@ export declare interface BaseDetailData {
71
69
  review?: ReviewInfo;
72
70
  /** 存佚:extant 今存 / fragment 殘 / lost 佚 等 */
73
71
  loss_status?: string;
72
+ /** 真偽:只在確定是偽書時寫(唯一值 forged),依據在 authenticity_basis */
73
+ authenticity?: 'forged' | (string & {});
74
+ authenticity_basis?: string;
74
75
  /** 數據修訂號與修訂日期(詳情頁提要卡底部小字) */
75
76
  revision?: number | string;
76
77
  revised_at?: string;
@@ -261,16 +262,6 @@ export declare class BookIndexStorage {
261
262
 
262
263
  /** Book.lineage —— 单本书的版本节点信息 */
263
264
  declare interface BookLineage {
264
- /**
265
- * @deprecated 年代已并入 dating(第 1 组),数据里不再有;detail-model 的年份推断仍留着兜底读取,待另行清理。
266
- */
267
- year?: number;
268
- /** @deprecated 同上,见 dating.text */
269
- year_text?: string;
270
- /** @deprecated 同上,见 dating.year_uncertain */
271
- year_uncertain?: boolean;
272
- /** @deprecated 同上,见 dating.year_range */
273
- year_range?: [number, number];
274
265
  /** 存佚(年代见 dating,所出之本见 base_edition,关联见 related_books) */
275
266
  status?: LineageStatus;
276
267
  /** 现存范围说明 */
@@ -490,6 +481,8 @@ declare interface CollatedJuan {
490
481
  page_title?: string;
491
482
  source_url?: string;
492
483
  sections: CollatedSection[];
484
+ /** 章的其余元数据(第 11 组起 page_title/source_url 等收在这里;读取时经 normalizeCollatedJuan 补到顶层) */
485
+ meta?: Record<string, unknown>;
493
486
  }
494
487
 
495
488
  /** 整理本参考文献 */
@@ -532,6 +525,8 @@ declare interface CollatedSection {
532
525
  header_line?: string;
533
526
  /** AI 生成的备注 */
534
527
  ai_note?: string;
528
+ /** 整理过程留下的解析证据(原下划线前缀字段,第 11 组收进这里),阅读器不显示 */
529
+ evidence?: Record<string, unknown>;
535
530
  }
536
531
 
537
532
  /** Collection.count:整数或 null,null=未知(不是 0) */
@@ -809,6 +804,11 @@ declare interface EntityDetailData extends BaseDetailData {
809
804
  _works?: DerivedEntityWork[];
810
805
  /** 外部数据库引用(CBDB 等) */
811
806
  external_ids?: ExternalIds;
807
+ /** CBDB 匹配过程元数据(2026-11-04 起,原 external_ids.cbdb_match/cbdb_source) */
808
+ external_ids_meta?: {
809
+ cbdb_match?: string;
810
+ cbdb_source?: string;
811
+ };
812
812
  /** 是否草稿 */
813
813
  isDraft?: boolean;
814
814
  /** 印影等图(GUJI-538/544):图本体在 book-index-asset,`file` 是仓内相对路径,URL=资源根+file */
@@ -851,6 +851,7 @@ declare interface EntityWorkRef {
851
851
  /** Entity.external_ids —— 外部数据库引用 */
852
852
  declare interface ExternalIds {
853
853
  cbdb_id?: number;
854
+ /** 旧位置(2026-11-04 前);现挪到顶层 external_ids_meta,过渡期两处都认 */
854
855
  cbdb_match?: string;
855
856
  cbdb_source?: string;
856
857
  /** 形如 Q123456 */
package/dist/storage.js CHANGED
@@ -1,4 +1,4 @@
1
- import { B as o, c as e, d as s, f as t, g as n, C as d, G as i, I as g, h as I, L as B, M as S, S as l, q as x, w as E, F as c } from "./storage-entry-DZmVSoZe.js";
1
+ import { B as o, c as e, d as s, f as t, g as n, C as d, G as i, I as g, h as I, L as x, M as B, S, q as l, x as E, H as c } from "./storage-entry-DuObqdka.js";
2
2
  export {
3
3
  o as BidLink,
4
4
  e as BookIndexError,
@@ -9,10 +9,10 @@ export {
9
9
  i as GithubStorage,
10
10
  g as IdGenerationError,
11
11
  I as IdGenerator,
12
- B as LocalStorage,
13
- S as MigrationError,
14
- l as StorageError,
15
- x as buildPromotionMap,
12
+ x as LocalStorage,
13
+ B as MigrationError,
14
+ S as StorageError,
15
+ l as buildPromotionMap,
16
16
  E as extractIdFromUrl,
17
17
  c as validateResource
18
18
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "book-index-ui",
3
- "version": "0.65.0",
3
+ "version": "0.65.2",
4
4
  "description": "React components for browsing and editing ancient book index metadata",
5
5
  "author": "Li Shaodong",
6
6
  "repository": {
@@ -1,2 +0,0 @@
1
- "use strict";var pt=Object.create;var X=Object.defineProperty;var wt=Object.getOwnPropertyDescriptor;var _t=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var kt=(o,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of _t(t))!It.call(o,n)&&n!==e&&X(o,n,{get:()=>t[n],enumerable:!(s=wt(t,n))||s.enumerable});return o};var St=(o,t,e)=>(e=o!=null?pt(bt(o)):{},kt(t||!o||!o.__esModule?X(e,"default",{value:o,enumerable:!0}):e,o));const Et=require("./variant-supplement.cjs"),vt={official:0,draft:1},xt={0:"official",1:"draft"},At={book:0,collection:2,work:3,entity:4},$t={0:"book",2:"collection",3:"work",4:"entity"},it=62n,rt=59n,at=19n,ct=8n,lt=(1n<<40n)-1n,Ct=(1n<<3n)-1n,Pt=(1n<<11n)-1n,jt=(1n<<8n)-1n,C="0123456789abcdefghijklmnopqrstuvwxyz",ht=new Map;for(let o=0;o<C.length;o++)ht.set(C[o],BigInt(o));function A(o){if(o===0n)return C[0];let t="";for(;o>0n;)t=C[Number(o%36n)]+t,o=o/36n;return t}function M(o){let t=0n;for(const e of o){const s=ht.get(e);if(s===void 0)throw new Error(`Invalid Base36 character: ${e}`);t=t*36n+s}return t}const Q="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ut=new Map;for(let o=0;o<Q.length;o++)ut.set(Q[o],BigInt(o));function dt(o){let t=0n;for(const e of o){const s=ut.get(e);if(s===void 0)throw new Error(`Invalid Base58 character: ${e}`);t=t*58n+s}return t}function _(o){return/[A-Z]/.test(o)?dt(o):M(o)}const Tt=A,Ft=M;function k(o){const t=Number(o>>it&1n),e=Number(o>>rt&Ct),s=o>>at&lt,n=Number(o>>ct&Pt),i=Number(o&jt);return{status:xt[t]??"draft",type:$t[e]??"book",timestamp:s,machineId:n,sequence:i}}function j(o,t,e,s,n){return BigInt(vt[o])<<it|BigInt(At[t])<<rt|(e&lt)<<at|BigInt(s)<<ct|BigInt(n)}function S(o){return k(_(o))}function ft(o){return S(o).type}function Lt(o){return S(o).status}const T={book:"Book",collection:"Collection",work:"Work",entity:"Entity"},Bt={Book:"book",Collection:"collection",Work:"work",Entity:"entity"},x=16;function $(o,t=x){let e=0;for(let s=0;s<o.length;s++)e=Math.imul(e,31)+o.charCodeAt(s)>>>0;return e%t}function Rt(o){const t={},e=o.dating;if(typeof e!="object"||e===null)return t;const s=e.era;typeof s=="string"&&s&&(t.era=s);const n=e.year;if(typeof n=="number")t.sort_year=n;else{const i=e.year_range;Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&(t.sort_year=i[0])}return t}function w(...o){const t=o.join("/");return t.startsWith("//")?"//"+t.slice(2).replace(/\/+/g,"/"):t.replace(/\/+/g,"/")}function Mt(o){if(!Array.isArray(o))return"";for(const t of o)if(typeof t=="object"&&t!==null){const e=t.dynasty;if(typeof e=="string"&&e)return e}return""}function Z(o,t,e){var Y;const s=o.id||"";let n="",i="",r="";const c=o.authors;if(Array.isArray(c)&&c.length>0){const y=c[0];typeof y=="object"&&y!==null?(n=y.name||"",r=y.role||""):n=String(y)}else typeof c=="string"&&(n=c);i=Mt(c)||(typeof o.dynasty=="string"?o.dynasty:"");let a="";const l=o.current_location;if(typeof l=="object"&&l!==null?a=l.name||"":typeof l=="string"&&(a=l),!a&&Array.isArray(o.provenance)&&o.provenance.length>0){const y=(Y=o.provenance[0])==null?void 0:Y.institution;typeof y=="string"&&(a=y)}const u=Array.isArray(o.additional_titles)?o.additional_titles.map(y=>typeof y=="string"?y:y==null?void 0:y.book_title).filter(Boolean):void 0,h=Array.isArray(o.attached_texts)?o.attached_texts.map(y=>typeof y=="string"?y:y==null?void 0:y.book_title).filter(Boolean):void 0;let f;const d=o.juan_count;if(typeof d=="number"?f=d:typeof d=="object"&&d!==null&&(f=d.number||void 0),!f&&Array.isArray(o.measures)){const y=o.measures.find(I=>I&&I.unit==="卷"&&typeof I.number=="number"&&I.number>0);y&&(f=y.number)}const m=typeof o.measure_info=="string"?o.measure_info:"";let b=!1,N=!1;const J=o.resources;if(Array.isArray(J))for(const y of J){if(typeof y!="object"||y===null)continue;const I=y.types;Array.isArray(I)&&(I.includes("text")&&(b=!0),I.includes("image")&&(N=!0))}const g={id:s,title:o.title||"未命名",type:T[t],path:e,...Rt(o)};n&&(g.author=n),a&&(g.holder=a),u&&u.length>0&&(g.additional_titles=u),h&&h.length>0&&(g.attached_texts=h),f&&(g.juan_count=f),m&&(g.measure_info=m);const W=typeof o.edition=="string"?o.edition:"";W&&(g.edition=W),b&&(g.has_text=!0),N&&(g.has_image=!0),i&&(g.dynasty=i),r&&(g.role=r);const H=typeof o.subtype=="string"?o.subtype:"";H&&(g.subtype=H);const G=typeof o.period=="string"?o.period:"";G&&(g.period=G);const q=typeof o.loss_status=="string"?o.loss_status:"";q&&(g.loss_status=q);const z=typeof o.original_title=="string"?o.original_title:"";z&&(g.original_title=z);const K=typeof o.work_id=="string"?o.work_id:"";K&&(g.work_id=K);const V=typeof o._promoted_to=="string"?o._promoted_to:"";return V&&(g.promoted_to=V),g}const Dt=60;function yt(o){const t=o.replace(/[^㐀-䶿一-鿿豈-﫿a-zA-Z0-9\u{20000}-\u{3134f}]/gu,"");return Array.from(t).slice(0,Dt).join("")||"Undefined"}class D{constructor(t,e){this.fs=t,this.officialRoot=w(e,"book-index"),this.draftRoot=w(e,"book-index-draft")}getRootByStatus(t){return t==="draft"?this.draftRoot:this.officialRoot}getRootById(t){const e=_(t),s=k(e);return this.getRootByStatus(s.status)}getPath(t,e,s){const n=this.getRootById(e),i=e.padEnd(3,"_").substring(0,3),[r,c,a]=[i[0],i[1],i[2]],l=T[t];return w(n,l,r,c,a,`${e}-${yt(s)}.json`)}async saveItem(t,e,s){const n=s.title||s.书名||"未命名",i=s.edition||"",r=i?`${n}${i}`:n,c=this.getPath(t,e,r),a=await this.findFileById(e);if(a&&a!==c)try{await this.fs.deleteFile(a)}catch{}const l=c.substring(0,c.lastIndexOf("/"));await this.fs.mkdir(l),s.id=e,s.type=t,await this.fs.writeFile(c,JSON.stringify(s,Ot,2));const u=this.getRootById(e),h=c.substring(u.length+1);return await this.updateIndexEntry(u,s,t,h),c}async updateIndexEntry(t,e,s,n){const i=e.id||"";if(!i)return;const r=`${s}s`,c=await this.loadShard(t,r,i),a=Z(e,s,n);c[i]=a,await this.saveShard(t,r,i,c)}async deleteItem(t){const e=await this.findFileById(t);if(!e)return!1;const s=_(t),n=k(s),i=this.getRootByStatus(n.status),r=`${n.type}s`,c=await this.loadShard(i,r,t);return c[t]&&(delete c[t],await this.saveShard(i,r,t,c)),await this.fs.deleteFile(e),!0}async findFileById(t){const e=t.padEnd(3,"_").substring(0,3),[s,n,i]=[e[0],e[1],e[2]];for(const r of[this.officialRoot,this.draftRoot])for(const c of["Book","Collection","Work"]){const a=w(r,c,s,n,i);if(await this.fs.exists(a))try{const u=(await this.fs.readdir(a)).find(h=>h.startsWith(`${t}-`)&&h.endsWith(".json"));if(u)return w(a,u)}catch{}}return null}async loadMetadata(t){try{const e=await this.fs.readFile(t);return JSON.parse(e)}catch{return{}}}async getItem(t){const e=await this.findFileById(t);if(!e)return null;const s=await this.loadMetadata(e);return Object.keys(s).length>0?s:null}async loadEntries(t,e){const s=e?[this.getRootByStatus(e)]:[this.officialRoot,this.draftRoot],n=[],i=`${t}s`;for(const r of s){const c=await this.loadAllShards(r,i);for(const[a,l]of Object.entries(c))n.push({id:a,title:l.title,type:t,author:l.author||void 0,dynasty:l.dynasty||void 0,role:l.role||void 0,path:w(r,l.path),additional_titles:l.additional_titles,attached_texts:l.attached_texts,edition:l.edition,juan_count:l.juan_count,has_text:l.has_text,has_image:l.has_image,era:l.era,sort_year:l.sort_year})}return n}async searchEntries(t,e,s){const n=await this.loadEntries(e,s);return L(n,t)}async searchAll(t,e=5,s){const n=["work","book","collection"],i=await Promise.all(n.map(r=>this.searchEntries(t,r,s)));return{works:i[0].slice(0,e),books:i[1].slice(0,e),collections:i[2].slice(0,e),totalWorks:i[0].length,totalBooks:i[1].length,totalCollections:i[2].length}}async rebuildIndex(t){const e=this.getRootByStatus(t),s={books:Object.fromEntries(Array.from({length:x},(n,i)=>[i,{}])),collections:{0:{}},works:Object.fromEntries(Array.from({length:x},(n,i)=>[i,{}]))};for(const n of["Book","Collection","Work"]){const i=w(e,n);if(!await this.fs.exists(i))continue;const r=Bt[n],c=`${r}s`,a=await this.fs.glob(i,"**/*.json");for(const l of a)if(!l.includes("/index/"))try{const u=await this.loadMetadata(l);let h=u.id||u.ID||"";if(!h){const b=l.substring(l.lastIndexOf("/")+1);b.includes("-")&&(h=b.split("-")[0])}if(!h)continue;const f=l.substring(e.length+1),d=Z({...u,id:h},r,f),m=c==="collections"?0:$(h);s[c][m][h]=d}catch{}}for(const[n,i]of Object.entries(s))for(const[r,c]of Object.entries(i)){const a=this.shardPath(e,n,Number(r)),l=a.substring(0,a.lastIndexOf("/"));await this.fs.mkdir(l),await this.fs.writeFile(a,JSON.stringify(tt(c),null,await this.detectShardIndent(a)))}}getAssetDir(t){const e=this.getRootById(t),s=_(t),i=k(s).type,r=t.padEnd(3,"_").substring(0,3),[c,a,l]=[r[0],r[1],r[2]],u=T[i];return w(e,u,c,a,l,t)}async initAssetDir(t){const e=this.getAssetDir(t);return await this.fs.mkdir(e),e}async hasAssetDir(t){const e=this.getAssetDir(t);return this.fs.exists(e)}shardPath(t,e,s){return e==="collections"?w(t,"index","collections.json"):w(t,"index",e,`${s.toString(16)}.json`)}async loadShard(t,e,s){const n=$(s),i=this.shardPath(t,e,n);try{if(!await this.fs.exists(i))return{};const r=await this.fs.readFile(i);return JSON.parse(r)}catch{return{}}}async detectShardIndent(t,e=2){try{if(!await this.fs.exists(t))return e;const n=(await this.fs.readFile(t)).split(`
2
- `)[1];if(n===void 0)return e;const i=n.replace(/^ +/,"");return!i||i.startsWith("}")?e:n.length-i.length||e}catch{return e}}async saveShard(t,e,s,n){const i=$(s),r=this.shardPath(t,e,i),c=r.substring(0,r.lastIndexOf("/"));await this.fs.mkdir(c);const a=await this.detectShardIndent(r);await this.fs.writeFile(r,JSON.stringify(tt(n),null,a))}async loadAllShards(t,e){const s={};if(e==="collections"){const n=this.shardPath(t,e,0);try{if(await this.fs.exists(n)){const i=await this.fs.readFile(n);Object.assign(s,JSON.parse(i))}}catch{}return s}for(let n=0;n<x;n++){const i=this.shardPath(t,e,n);try{if(await this.fs.exists(i)){const r=await this.fs.readFile(i);Object.assign(s,JSON.parse(r))}}catch{}}return s}}function F(o,t){const e=t.toLowerCase();let s=0;const n=o.title.toLowerCase();n===e?s=200:n.startsWith(e)?s=150:n.includes(e)&&(s=100);const i=[...o.additional_titles||[],...o.attached_texts||[]];for(const l of i){const u=l.toLowerCase();u===e?s=Math.max(s,120):u.startsWith(e)?s=Math.max(s,90):u.includes(e)&&(s=Math.max(s,60))}let r=0;if(o.author){const l=o.author.toLowerCase();l===e?r=80:l.includes(e)&&(r=50)}let c=0;o.dynasty&&o.dynasty.toLowerCase().includes(e)&&(c=30);let a=s;return a===0&&(a=Math.max(r,c)),a===0?0:(a+=Math.max(0,20-n.length),o.type==="work"?a=Math.round(a*1.05):o.type==="collection"&&(a=Math.round(a*1.02)),o.has_text&&(a+=3),o.has_image&&(a+=2),a)}function tt(o){const t={};for(const e of Object.keys(o).sort())t[e]=o[e];return t}function Ot(o,t){return t===null?void 0:t}function L(o,t){const e=o.map(s=>({entry:s,score:F(s,t)})).filter(s=>s.score>0);return e.sort((s,n)=>n.score!==s.score?n.score-s.score:s.entry.title.length-n.entry.title.length),e.map(s=>s.entry)}function et(o,t,e,s){const n=o.map(i=>{const r=F(i,t);let c=0;const a=s[i.id];if(a&&e){const l={...i,title:a.t??i.title,author:a.a??i.author,additional_titles:a.at??i.additional_titles,attached_texts:a.axt??i.attached_texts};c=F(l,e)}return{entry:i,score:Math.max(r,c)}}).filter(i=>i.score>0);return n.sort((i,r)=>r.score!==i.score?r.score-i.score:i.entry.title.length-r.entry.title.length),n.map(i=>i.entry)}function Ut(o){const t=o.volumes??[];let e,s;if(t.length===0)e=[];else if(typeof t[0]=="number")e=t;else{s=[],e=[];for(const i of t){const r=i.volume;e.push(r);const c={};for(const[a,l]of Object.entries(i))a==="volume"||a==="status"||a==="file"||typeof l=="string"&&(a.includes("url")||a.includes("id"))&&(c[a]=l);s.push({volume:r,status:i.status,urls:Object.keys(c).length>0?c:void 0,file:i.file})}}const n={title:o.title??"",book_id:o.book_id??null,work_id:o.work_id??null,volumes:e,section:o.section,sub_items:o.sub_items,edition:o.edition,expected_volumes:o.expected_volumes,found_volumes:o.found_volumes,missing_volumes:o.missing_vols??o.missing_volumes};s&&(n.volume_details=s);for(const i of Object.keys(n))n[i]===void 0&&delete n[i];return n}function Nt(o){const t={total_books:o.total_books??0};return o.processed_volumes!=null&&(t.processed_volumes=o.processed_volumes),o.matched_works!=null&&(t.matched_works=o.matched_works),o.unmatched_works!=null&&(t.unmatched_works=o.unmatched_works),o.total_found_volumes!=null&&(t.total_found_volumes=o.total_found_volumes),t}function O(o){var n;const t=o,e=(t.books??[]).map(Ut),s={collection_id:t.collection_id??"",title:t.title??"",total_volumes:t.total_volumes??0,stats:Nt(t.stats??{}),books:e};return t.source&&(s.source=t.source),t.resource_id&&(s.resource_id=t.resource_id),t.resource_name&&(s.resource_name=t.resource_name),(n=t.sections)!=null&&n.length&&(s.sections=t.sections),t.volume_index&&Object.keys(t.volume_index).length>0&&(s.volume_index=t.volume_index),s}const st=2;function P(o){const t=new Map;if(!o||typeof o!="object")return t;const e=o;if(typeof e.version!="number")return console.warn("[promotions] missing version field; treating as empty"),t;if(e.version!==1)return console.warn(`[promotions] unknown version ${e.version}; treating as empty`),t;const s=e.promotions;if(!s||typeof s!="object")return t;for(const[n,i]of Object.entries(s))i&&typeof i=="object"&&typeof i.production_id=="string"&&t.set(n,i.production_id);return t}const Jt={㐫:"凶",㐮:"襄",㐲:"伏",㑹:"會",㒒:"僕",㒵:"貌",㒺:"罔",㓂:"寇",㓕:"滅",㓗:"潔",㓙:"凶",㓛:"功",㓜:"幼",㔻:"丕",㕑:"廚",㕓:"廛",㕔:"廳",㕘:"參",㗋:"喉",㗖:"啖",㘭:"坳",㛰:"婚",㝛:"宿",㝠:"冥",㝡:"最",㝢:"宇",㝷:"尋",㟁:"岸",㠯:"以",㠶:"帆",㡌:"帽",㡬:"幾",㡳:"底",㢘:"廉",㢮:"弛",㢲:"巽",㣲:"微",㤀:"忘",㤗:"泰",㤙:"恩",㦯:"或",㦲:"哉",㦸:"戟",㧞:"拔",㨗:"捷",㨿:"據",㩀:"據",㩦:"攜",㪚:"散",㪷:"斗",㫁:"斷",㫄:"旁",㫖:"旨",㫤:"昶",㬥:"暴",㬰:"臾",㭍:"漆",㮚:"栗",㮣:"概",㯶:"棕",㯽:"檳",㰱:"歃",㱕:"歸",㳂:"沿",㳙:"涓",㳟:"恭",㳫:"沓",㳺:"游",㴱:"深",㵎:"澗",㵼:"瀉",㶑:"瀲",㶚:"灞",㷀:"煢",㸃:"點",㸑:"爨",㸔:"看",㽔:"蕤",㽞:"留",䂓:"規",䄂:"袖",䆒:"究",䆫:"窗",䆳:"邃",䇿:"策",䋲:"繩",䌫:"纜",䍐:"罕",䍧:"牂",䏻:"能",䑓:"臺",䑕:"鼠",䑛:"舐",䓁:"等",䓻:"蔻",䕃:"蔭",䕫:"夔",䕶:"護",䖍:"虔",䖏:"處",䖝:"虫",䖟:"虻",䘏:"卹",䘚:"卒",䘮:"喪",䙝:"褻",䛕:"諛",䜛:"讒",䜟:"讖",䜴:"豉",䜿:"豎",䝉:"蒙",䟦:"跋",䟽:"疏",䡖:"輕",䢴:"邗",䦨:"闌",䧏:"隆",䧟:"陷",䧺:"雄",䨇:"雙",䬃:"颯",䭾:"馱",䰟:"魂",䲭:"鴟",䴡:"麗",丅:"下",丗:"世",両:"兩",乆:"久",乗:"乘",亁:"乾",亊:"事",亷:"廉",亾:"亡",仭:"仞",伃:"妤",伷:"胄",佀:"似",倂:"併",倐:"倏",値:"值",偹:"備",僃:"備",儛:"舞",儞:"你",兊:"兌",兎:"兔",児:"兒",兠:"兜",兾:"冀",冄:"冉",冝:"宜",冦:"寇",冨:"富",冩:"写",冺:"泯",凂:"浼",凃:"涂",凖:"準",凟:"瀆",凢:"凡",凴:"憑",凾:"函",刋:"刊",刦:"劫",刧:"劫",刼:"劫",剏:"創",剙:"創",剰:"剩",劎:"劍",劒:"劍",劔:"劍",効:"效",勅:"敕",勲:"勛",匄:"丐",厪:"廑",厫:"廒",厯:"歷",厰:"廠",収:"收",吿:"告",呉:"吳",呌:"叫",呑:"吞",呪:"咒",咲:"笑",唘:"啟",唫:"吟",嗸:"嗷",嘑:"呼",嘷:"嗥",噐:"器",嚢:"囊",嚻:"囂",囏:"艱",囘:"回",囬:"回",囯:"國",圎:"圓",圏:"圈",圗:"圖",垜:"垛",埀:"垂",埓:"埒",堦:"階",塜:"冢",塟:"葬",塡:"填",塩:"鹽",塲:"場",墖:"塔",増:"增",壊:"壞",壍:"塹",壷:"壺",壻:"婿",夀:"壽",変:"變",夣:"夢",夲:"本",奨:"獎",妬:"妒",姙:"妊",姢:"娟",姧:"奸",姫:"姬",娯:"娛",婣:"姻",媫:"婕",嫓:"媲",孶:"孳",宐:"宜",宻:"密",宼:"寇",寃:"冤",寕:"寧",寗:"甯",寛:"寬",寜:"寧",寳:"寶",尅:"剋",尓:"爾",尙:"尚",尫:"尪",尭:"堯",屛:"屏",岀:"出",峩:"峨",崈:"崇",崐:"崑",崕:"崖",崘:"崙",嵓:"巖",嵳:"嵯",嶤:"嶢",巗:"巖",巵:"卮",巻:"卷",帀:"匝",帬:"裙",帯:"帶",幇:"幫",幷:"并",庻:"庶",庿:"廟",廏:"廄",廐:"廄",廵:"巡",廸:"迪",廹:"迫",廻:"迴",廽:"迴",彂:"發",彚:"彙",彛:"彝",彜:"彝",彞:"彝",徃:"往",従:"從",徤:"健",徧:"遍",徳:"德",徴:"徵",忩:"匆",忼:"慷",怱:"匆",恊:"協",恠:"怪",恡:"吝",恱:"悅",恵:"惠",悞:"誤",悤:"匆",悪:"惡",悮:"誤",悳:"德",惒:"和",愞:"懦",愼:"慎",愽:"博",慙:"慚",慿:"憑",憇:"憩",憹:"惱",懐:"懷",懴:"懺",戅:"戇",戞:"戛",戦:"戰",戯:"戲",戱:"戲",戸:"戶",戹:"厄",戻:"戾",扄:"扃",扵:"於",抜:"拔",抝:"拗",挿:"插",捜:"搜",掦:"剔",掲:"揭",揑:"捏",揔:"總",揷:"插",揺:"搖",搃:"總",撃:"擊",擕:"攜",擥:"攬",擧:"舉",攅:"攢",攺:"改",敇:"敕",敍:"敘",敭:"揚",斈:"學",斉:"齊",斚:"斝",斾:"旆",旉:"敷",旜:"旃",旤:"禍",昬:"昏",昻:"昂",晧:"皓",晩:"晚",暁:"曉",暎:"映",暦:"曆",曁:"暨",曵:"曳",曺:"曹",曽:"曾",朂:"勖",朙:"明",朞:"期",朩:"木",朶:"朵",枿:"櫱",栁:"柳",栢:"柏",桺:"柳",梹:"檳",棃:"梨",椉:"乘",椘:"楚",椶:"棕",楽:"樂",槀:"槁",槖:"橐",槩:"概",樷:"叢",橅:"模",橰:"槔",檝:"楫",欝:"鬱",欵:"款",歘:"欻",歩:"步",歳:"歲",歴:"歷",殱:"殲",毎:"每",氊:"氈",氷:"冰",汚:"污",浄:"淨",涖:"蒞",涙:"淚",淸:"清",渇:"渴",渉:"涉",湏:"須",湼:"涅",滛:"淫",漑:"溉",潄:"漱",澁:"澀",澘:"潸",濓:"濂",濙:"瀅",濳:"潛",濵:"濱",濶:"闊",瀬:"瀨",灋:"法",灔:"灩",灮:"光",炁:"氣",烖:"災",烱:"炯",煑:"煮",煕:"熙",熈:"熙",熖:"焰",熺:"熹",爕:"燮",爼:"俎",牐:"閘",牕:"窗",犂:"犁",犫:"犨",狥:"徇",猨:"猿",珎:"珍",珤:"寶",瑇:"玳",瑠:"琉",璝:"瑰",瓈:"璃",瓉:"瓚",瓌:"瑰",甆:"瓷",甎:"磚",甞:"嘗",畆:"畝",畊:"耕",畒:"畝",畞:"畝",畧:"略",畨:"番",畮:"畝",畱:"留",畺:"疆",疉:"疊",疎:"疏",痩:"瘦",癎:"癇",皐:"皋",皥:"皞",皷:"鼓",盌:"碗",眀:"明",眂:"視",眡:"視",睂:"眉",瞤:"瞬",矟:"槊",矦:"侯",碁:"棋",礮:"炮",礲:"礱",禆:"裨",禇:"褚",禩:"祀",秔:"粳",稲:"稻",稾:"稿",穂:"穗",穉:"稚",穏:"穩",穣:"穰",穪:"稱",穽:"阱",窓:"窗",窰:"窯",窻:"窗",竆:"窮",竒:"奇",竚:"佇",竝:"並",竢:"俟",筓:"笄",筞:"策",筯:"箸",箆:"篦",箒:"帚",簒:"篡",簮:"簪",籖:"籤",粃:"秕",粧:"妝",糓:"穀",糺:"糾",絍:"紝",綂:"統",綘:"縫",継:"繼",緍:"緡",緜:"綿",緤:"紲",緫:"總",縀:"緞",縁:"緣",縂:"總",縦:"縱",繋:"繫",纉:"纘",纎:"纖",纒:"纏",罇:"樽",罸:"罰",羮:"羹",翺:"翱",耉:"耇",耼:"聃",聦:"聰",聨:"聯",聫:"聯",聮:"聯",聴:"聽",聼:"聽",肎:"肯",肹:"肸",肻:"肯",胷:"胸",脇:"脅",脗:"吻",膓:"腸",臈:"臘",臯:"皋",舎:"舍",舩:"船",艶:"豔",苢:"苡",苽:"菰",茘:"荔",茰:"萸",荘:"莊",莭:"節",莵:"菟",莾:"莽",菓:"果",葢:"蓋",蒭:"芻",蔲:"蔻",蔴:"麻",蔵:"藏",蕋:"蕊",蕐:"華",蕚:"萼",薫:"薰",藳:"稿",蘂:"蕊",蘓:"蘇",虗:"虛",虵:"蛇",蝱:"虻",蟇:"蟆",蠏:"蟹",蠒:"繭",蠧:"蠹",蠭:"蜂",衂:"衄",衇:"脈",衘:"銜",衞:"衛",袐:"祕",袴:"褲",袵:"衽",裦:"褒",裵:"裴",襃:"褒",襍:"雜",覇:"霸",覉:"羈",覊:"羈",覔:"覓",覧:"覽",覩:"睹",詧:"察",諌:"諫",諐:"愆",謌:"歌",謩:"謨",譍:"應",譛:"譖",讁:"謫",讃:"讚",讐:"讎",貎:"猊",貟:"員",賍:"贓",賔:"賓",賖:"賒",賛:"贊",贑:"贛",趂:"趁",踈:"疏",蹏:"蹄",蹷:"蹶",躭:"耽",軄:"職",軰:"輩",輙:"輒",輭:"軟",辝:"辭",辠:"罪",辤:"辭",迯:"逃",逈:"迥",逓:"遞",逥:"迴",逰:"遊",逹:"達",逺:"遠",遅:"遲",遟:"遲",邉:"邊",邜:"卯",郞:"郎",郷:"鄉",鄊:"鄉",鄕:"鄉",鄼:"酇",酧:"酬",醤:"醬",醸:"釀",醻:"酬",醿:"醾",釡:"釜",鉄:"鐵",錬:"鍊",鍳:"鑒",鎻:"鎖",鏁:"鎖",鐡:"鐵",鑚:"鑽",鑛:"礦",閙:"鬧",閠:"閏",関:"關",閴:"闃",闗:"關",闘:"鬥",陁:"陀",隂:"陰",隟:"隙",隠:"隱",隣:"鄰",隲:"騭",隷:"隸",靁:"雷",靑:"青",靣:"面",鞉:"鼗",鞌:"鞍",鞵:"鞋",鞾:"靴",韈:"襪",韮:"韭",頋:"顧",頟:"額",頥:"頤",頳:"赬",頴:"穎",頺:"頹",頼:"賴",顇:"悴",顕:"顯",顚:"顛",顦:"憔",颷:"飆",飇:"飆",飜:"翻",飡:"餐",飬:"養",飮:"飲",飰:"飯",餙:"飾",饍:"膳",駈:"驅",駞:"駝",駵:"騮",騐:"驗",騘:"驄",髙:"高",髠:"髡",髤:"髹",髩:"鬢",髪:"髮",髴:"彿",鬂:"鬢",鬛:"鬣",鬪:"鬥",鬬:"鬥",鬭:"鬥",鬰:"鬱",鰌:"鰍",鰕:"蝦",鱓:"鱔",鳯:"鳳",鵞:"鵝",鵶:"鴉",鸎:"鶯",鸜:"鴝",麄:"粗",麕:"麇",麞:"獐",麺:"麵",黒:"黑",黙:"默",鼂:"晁",鼃:"蛙",鼈:"鱉",鼔:"鼓",齓:"齔",龎:"龐",龡:"吹","𠖇":"冥","𠞰":"剿","𠡠":"敕","𡨕":"冥","𢃄":"帶","𢎞":"弘","𢰅":"撰","𢷬":"搗","𣏌":"耜","𣙜":"榷","𣺌":"渺","𤦺":"琦","𤨏":"瑣","𤼵":"發","𥘉":"初","𥙷":"輔","𦂳":"緊","𦍑":"羌","𦕈":"眇","𦗟":"聽","𦙍":"胤","𦵏":"葬","𧰼":"象","𨼆":"隱","𨽻":"隸","𩔖":"類","𫉬":"獲","𫝊":"傳","𬒳":"被","兔":"兔"},gt=Jt;function mt(o){if(!o)return o;let t=!1,e="";for(const s of o){const n=gt[s]??Et.VARIANT_SUPPLEMENT[s];n!==void 0?(e+=n,t=!0):e+=s}return t?e:o}const Wt="https://raw.githubusercontent.com",Ht=["https://fastly.jsdelivr.net/gh","https://cdn.jsdelivr.net/gh"],Gt=5e3;class qt{constructor(t){this.cache=null,this.cacheLoading=null,this.pathMap=new Map,this.promotions=new Map,this.searchSCache=null,this.t2sConverter=null,this.config={org:t.org,repos:t.repos,baseUrl:t.baseUrl??Wt,cdnUrls:t.cdnUrls??Ht,timeout:t.timeout??Gt}}async fetchPromotions(){try{const t=await this.fetchFileWithFallback(this.config.repos.draft,"promotions.json");return P(t)}catch{return new Map}}async ensureLoaded(){if(this.cache)return this.cache;if(this.cacheLoading)return this.cacheLoading;this.cacheLoading=(async()=>{let t=!1,e=!1;const[s,n,i]=await Promise.all([this.fetchPromotions(),this.fetchIndex(this.config.repos.draft).catch(a=>(console.warn("Failed to fetch draft index:",a),t=!0,{books:{},collections:{},works:{}})),this.fetchIndex(this.config.repos.official).catch(a=>(console.warn("Failed to fetch official index:",a),e=!0,{books:{},collections:{},works:{}}))]);if(this.promotions=s,t&&e)throw new Error("GithubStorage 已废弃:两个仓都读不到 index/ 分片。请改用 COS 产物或 BundleStorage。");const r=[...this.parseIndexResponse(n,!0),...this.parseIndexResponse(i,!1)],c=new Map;for(const a of r)a.isDraft&&a.promoted_to||c.set(a.id,a);return this.cache=Array.from(c.values()),this.cache})();try{return await this.cacheLoading}finally{this.cache||(this.cacheLoading=null)}}async fetchFileWithFallback(t,e){const s=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(e)}`;try{return await this.fetchJson(s)}catch{}for(const n of this.config.cdnUrls){const i=`${n}/${this.config.org}/${t}@main/${encodeURI(e)}`;try{return await this.fetchJson(i)}catch{continue}}throw new Error(`Failed to fetch ${e} for ${t} from all sources`)}async probeIndex(t){const e="index/collections.json",s=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(e)}`;try{if((await fetch(s,{method:"HEAD",signal:AbortSignal.timeout(this.config.timeout)})).ok)return!0}catch{}for(const r of this.config.cdnUrls){const c=`${r}/${this.config.org}/${t}@main/${encodeURI(e)}`;try{if((await fetch(c,{method:"HEAD",signal:AbortSignal.timeout(this.config.timeout)})).ok)return!0}catch{continue}}const n="index/works/0.json",i=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(n)}`;try{if((await fetch(i,{method:"HEAD",signal:AbortSignal.timeout(this.config.timeout)})).ok)return!0}catch{}for(const r of this.config.cdnUrls){const c=`${r}/${this.config.org}/${t}@main/${encodeURI(n)}`;try{if((await fetch(c,{method:"HEAD",signal:AbortSignal.timeout(this.config.timeout)})).ok)return!0}catch{continue}}return!1}async fetchIndex(t){if(!await this.probeIndex(t))throw new Error(`GithubStorage 已废弃:它读源仓的 index/ 分片,而 ${t} 已无 index/,读不到数据。请改用 COS 产物或 BundleStorage。`);const s={books:{},collections:{},works:{}};try{const i=await this.fetchFileWithFallback(t,"index/collections.json");s.collections=i}catch{}const n=[];for(const i of["books","works"])for(let r=0;r<x;r++){const c=`index/${i}/${r.toString(16)}.json`;n.push(this.fetchFileWithFallback(t,c).then(a=>{Object.assign(s[i],a)}).catch(()=>{}))}return await Promise.all(n),s}async fetchJson(t){const e=await fetch(t,{cache:"no-store",signal:AbortSignal.timeout(this.config.timeout)});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}parseIndexResponse(t,e){var i,r;const s=[],n=[["books","book"],["collections","collection"],["works","work"],["entities","entity"]];for(const[c,a]of n){const l=t[c];if(l)for(const u of Object.values(l)){const h=u,f=a==="entity"?h.primary_name||u.title||u.name||u.id:u.title||u.name||u.id;s.push({id:u.id,title:f,type:a,isDraft:e,author:u.author,dynasty:u.dynasty,role:u.role,path:u.path,additional_titles:(i=h.additional_titles)==null?void 0:i.map(d=>typeof d=="string"?d:d==null?void 0:d.book_title).filter(Boolean),attached_texts:(r=h.attached_texts)==null?void 0:r.map(d=>typeof d=="string"?d:d==null?void 0:d.book_title).filter(Boolean),edition:h.edition,juan_count:h.juan_count,has_text:h.has_text,has_image:h.has_image,has_collated:h.has_collated,subtype:h.subtype,primary_name:h.primary_name,birth_year:h.birth_year,death_year:h.death_year,cbdb_id:h.cbdb_id,promoted_to:h.promoted_to}),this.pathMap.set(u.id,{path:u.path,isDraft:e})}}return s}async ensureSearchSBuilt(){var n,i;if(this.searchSCache)return{searchS:this.searchSCache,converter:this.t2sConverter||null};if(this.t2sConverter===!1)return{searchS:{},converter:null};try{const c=(await import("opencc-js")).Converter({from:"t",to:"cn"});this.t2sConverter=a=>c(mt(a))}catch{return this.t2sConverter=!1,this.searchSCache={},{searchS:{},converter:null}}const t=await this.ensureLoaded(),e=this.t2sConverter,s={};for(const r of t){const c={},a=e(r.title);if(a!==r.title&&(c.t=a),r.author){const l=e(r.author);l!==r.author&&(c.a=l)}if((n=r.additional_titles)!=null&&n.length){const l=r.additional_titles.map(e);l.some((u,h)=>u!==r.additional_titles[h])&&(c.at=l)}if((i=r.attached_texts)!=null&&i.length){const l=r.attached_texts.map(e);l.some((u,h)=>u!==r.attached_texts[h])&&(c.axt=l)}Object.keys(c).length>0&&(s[r.id]=c)}return this.searchSCache=s,{searchS:s,converter:e}}async loadEntries(t,e){let n=(await this.ensureLoaded()).filter(h=>h.type===t);const i=e.sortBy||"title",r=e.sortOrder||"asc";n.sort((h,f)=>{const d=String(h[i]??""),m=String(f[i]??""),b=d.localeCompare(m,"zh");return r==="asc"?b:-b});const c=e.page||1,a=e.pageSize||50,l=(c-1)*a;return{entries:n.slice(l,l+a),total:n.length,page:c,pageSize:a}}async search(t,e,s){const n=await this.ensureLoaded(),{searchS:i,converter:r}=await this.ensureSearchSBuilt(),c=n.filter(m=>m.type===e),a=r?r(t):void 0,u=Object.keys(i).length>0?et(c,t,a,i):L(c,t),h=s.page||1,f=s.pageSize||50,d=(h-1)*f;return{entries:u.slice(d,d+f),total:u.length,page:h,pageSize:f}}async searchAll(t,e=5){const s=await this.ensureLoaded(),{searchS:n,converter:i}=await this.ensureSearchSBuilt(),r=["work","book","collection"],c=i?i(t):void 0,a=Object.keys(n).length>0,l=r.map(u=>{const h=s.filter(f=>f.type===u);return a?et(h,t,c,n):L(h,t)});return{works:l[0].slice(0,e),books:l[1].slice(0,e),collections:l[2].slice(0,e),totalWorks:l[0].length,totalBooks:l[1].length,totalCollections:l[2].length}}async getItem(t){const e=await this.ensureLoaded(),s=this.promotions.get(t)??t,n=s!==t?t:void 0,i=this.pathMap.get(s);let r=null;if(i){const c=i.isDraft?this.config.repos.draft:this.config.repos.official;if(r=await this.fetchItemByPath(c,i.path),r){const a=e.find(l=>l.id===s);a!=null&&a.has_collated&&(r.has_collated=!0)}}else r=await this.findItemById(s);return r&&r.type==="entity"&&!r.title&&r.primary_name&&(r.title=r.primary_name),r&&n&&(r.redirected_from=n),r}async getEntry(t){const e=await this.ensureLoaded(),s=this.promotions.get(t)??t,n=s!==t?t:void 0,i=e.find(a=>a.id===s);if(i)return n?{...i,redirected_from:n}:i;const r=await this.findItemById(s);if(!r)return null;const c=this.buildEntryFromItem(s,r);return n?{...c,redirected_from:n}:c}async getAllEntries(){return this.ensureLoaded()}async saveItem(){throw new Error("GithubStorage 为只读模式,不支持保存")}async deleteItem(){throw new Error("GithubStorage 为只读模式,不支持删除")}async generateId(){throw new Error("GithubStorage 为只读模式,不支持生成 ID")}async fetchItemByPath(t,e){let s=null;const n=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(e)}`;try{s=await this.fetchJson(n)}catch{}if(!s)for(const i of this.config.cdnUrls){const r=`${i}/${this.config.org}/${t}@main/${encodeURI(e)}`;try{s=await this.fetchJson(r);break}catch{continue}}return s}async findItemById(t){const e={book:"Book",collection:"Collection",work:"Work",entity:"Entity"};let s,n;try{const u=k(_(t));s=u.type,n=u.status}catch{return null}const i=n==="draft"?this.config.repos.draft:this.config.repos.official,r=e[s],c=t.padEnd(3,"_").substring(0,3),a=`${r}/${c[0]}/${c[1]}/${c[2]}`,l=`https://api.github.com/repos/${this.config.org}/${i}/contents/${a}`;try{const u=await fetch(l,{signal:AbortSignal.timeout(this.config.timeout)});if(!u.ok)return null;const f=(await u.json()).find(m=>m.name.startsWith(`${t}-`)&&m.name.endsWith(".json"));if(!f)return null;const d=await this.fetchItemByPath(i,f.path);return d&&this.pathMap.set(t,{path:f.path,isDraft:n==="draft"}),d}catch{return null}}buildEntryFromItem(t,e){const s=(e.type||"").toLowerCase(),n=s==="work"?"work":s==="collection"?"collection":"book";let i;const r=e.authors;if(Array.isArray(r)&&r.length>0){const l=r[0];i=typeof l=="object"&&l!==null?l.name||"":String(l)}let c=!0;try{c=k(_(t)).status==="draft"}catch{}const a=this.pathMap.get(t);return{id:t,title:e.title||e.书名||t,type:n,isDraft:c,author:i,dynasty:e.dynasty,role:e.role,path:(a==null?void 0:a.path)||"",juan_count:e.n_juan,has_collated:e.has_collated}}async fetchFile(t,e){const s=`${this.config.baseUrl}/${this.config.org}/${t}/main/${encodeURI(e)}`;try{return await this.fetchJson(s)}catch{}for(const n of this.config.cdnUrls){const i=`${n}/${this.config.org}/${t}@main/${encodeURI(e)}`;try{return await this.fetchJson(i)}catch{continue}}return null}async resolveItemPath(t){await this.ensureLoaded();let e=this.pathMap.get(t);if(!e&&(await this.findItemById(t),e=this.pathMap.get(t),!e))return null;const s=e.isDraft?this.config.repos.draft:this.config.repos.official,n=e.path.substring(0,e.path.lastIndexOf("/"));return{repo:s,dir:n}}async getCollectionCatalogs(t){const e=await this.resolveItemPath(t);if(!e)return null;const s=await this.getItem(t);if(!s)return null;const n=s.resources||[];if(n.length===0)return null;const i=[];for(const r of n){const c=`${e.dir}/${t}/${r.id}/volume_book_mapping.json`,a=await this.fetchFile(e.repo,c);a&&i.push({resource_id:r.id,short_name:r.short_name,data:O(a)})}return i.length>0?i:null}async getCollectionCatalog(t){var s;const e=await this.getCollectionCatalogs(t);return((s=e==null?void 0:e[0])==null?void 0:s.data)??null}async getLineageGraph(t){const e=await this.resolveItemPath(t);if(!e)return null;const s=`${e.dir}/${t}/lineage_graph.json`;return this.fetchFile(e.repo,s)}async getCatalogProgress(){return this.fetchFile(this.config.repos.draft,"resource-catalog.json")}async getCollectionProgress(){return this.fetchFile(this.config.repos.draft,"resource-collection.json")}async getResourceProgress(){return this.fetchFile(this.config.repos.draft,"resource.json")}async getSiteProgress(){return this.fetchFile(this.config.repos.draft,"resource-site.json")}async getRecommended(){return this.fetchFile(this.config.repos.draft,"recommended.json")}clearCache(){this.cache=null,this.pathMap.clear(),this.searchSCache=null,this.t2sConverter=null}}const nt=255;class U{constructor(t){if(this.lastTimestamp=-1,this.lastStatus=null,this.sequence=0,t<0||t>2047)throw new Error("Machine ID must be between 0 and 2047");this.machineId=t}nextId(t,e){let s=this._getCurrentTimestamp(t);if(s<this.lastTimestamp&&t===this.lastStatus)throw new Error("Clock moved backwards. Refusing to generate ID.");s===this.lastTimestamp&&t===this.lastStatus?(this.sequence=this.sequence+1&nt,this.sequence===0&&(s=this._tilNextUnit(this.lastTimestamp,t))):this.sequence=0,this.lastTimestamp=s,this.lastStatus=t;const n=j(t,e,BigInt(s),this.machineId,this.sequence);return A(n)}nextIdRaw(t,e){let s=this._getCurrentTimestamp(t);if(s<this.lastTimestamp&&t===this.lastStatus)throw new Error("Clock moved backwards. Refusing to generate ID.");return s===this.lastTimestamp&&t===this.lastStatus?(this.sequence=this.sequence+1&nt,this.sequence===0&&(s=this._tilNextUnit(this.lastTimestamp,t))):this.sequence=0,this.lastTimestamp=s,this.lastStatus=t,j(t,e,BigInt(s),this.machineId,this.sequence)}_getCurrentTimestamp(t){const e=Date.now();return t==="draft"?e:Math.floor(e/1e3)}_tilNextUnit(t,e){let s=this._getCurrentTimestamp(e);for(;s<=t;)s=this._getCurrentTimestamp(e);return s}}class zt{constructor(t){this.recentEntities=[],this.storage=new D(t.fs,t.workspaceRoot),this.idGen=new U(t.machineId??0),this.fs=t.fs,this.workspaceRoot=t.workspaceRoot}async loadEntries(t,e){const s=await this.storage.loadEntries(t);return this.paginate(s,e)}async search(t,e,s){const n=await this.storage.searchEntries(t,e);return this.paginate(n,s)}async searchAll(t,e){return this.storage.searchAll(t,e)}async getItem(t){const e=await this.storage.getItem(t);return e&&e.type==="entity"&&!e.title&&e.primary_name&&(e.title=e.primary_name),e}async saveItem(t){const e=t.id;if(!e)throw new Error("metadata.id is required");const s=t.type||this.extractTypeFromId(e),n=await this.storage.saveItem(s,e,t);return{id:e,path:n}}async deleteItem(t){if(!await this.storage.deleteItem(t))throw new Error(`Item not found: ${t}`)}async generateId(t,e){return this.idGen.nextId(e,t)}async getEntry(t){const e=await this.storage.getItem(t);if(!e)return null;const s=e.type||this.extractTypeFromId(t);return{id:t,title:e.title||"未命名",type:s,author:this.extractAuthor(e),dynasty:this.extractYear(e)}}async getAllEntries(){const t=["book","collection","work"],e=[];for(const s of t){const n=await this.storage.loadEntries(s);e.push(...n)}return e}async getRelations(t){const e=await this.storage.getItem(t);if(!e)return null;const s={};if((e.type||this.extractTypeFromId(t))==="book"){if(e.work_id){const i=await this.resolveEntity(e.work_id);i&&(s.belongsToWork={...i,type:"work"})}if(e.contained_in&&Array.isArray(e.contained_in)&&e.contained_in.length>0){const i=e.contained_in[0],r=typeof i=="string"?i:i.id;if(r){const c=await this.resolveEntity(r);c&&(s.belongsToCollection={...c,type:"collection"})}}}return s}async linkEntity(t,e,s){const n=await this.storage.getItem(t);if(!n)throw new Error(`Source not found: ${t}`);const i=n.type||this.extractTypeFromId(t);switch(e){case"belongsToWork":case"work_id":n.work_id=s;break;case"belongsToCollection":case"contained_in":Array.isArray(n.contained_in)||(n.contained_in=[]);{const r=n.contained_in;r.some(a=>(typeof a=="string"?a:a.id)===s)||r.push({id:s})}break;default:throw new Error(`Unknown relation field: ${e}`)}await this.storage.saveItem(i,t,n)}async unlinkEntity(t,e){const s=await this.storage.getItem(t);if(!s)throw new Error(`Source not found: ${t}`);const n=s.type||this.extractTypeFromId(t);switch(e){case"belongsToWork":case"work_id":delete s.work_id;break;case"belongsToCollection":case"contained_in":s.contained_in=[];break;default:throw new Error(`Unknown relation field: ${e}`)}await this.storage.saveItem(n,t,s)}async createAndLink(t,e,s){const n=this.idGen.nextId("draft",s.type),i={id:n,type:s.type,title:s.title,...s.inheritData||{}};return await this.storage.saveItem(s.type,n,i),await this.linkEntity(t,e,n),{id:n}}async searchEntities(t,e){const s=e&&e!=="all"?[e]:["book","collection","work"],n=[];for(const i of s){const r=await this.storage.searchEntries(t,i);for(const c of r)n.push({id:c.id,title:c.title,type:c.type,author:c.author,dynasty:c.dynasty})}return n}async getRecentEntities(){return this.recentEntities}async addRecentEntity(t){this.recentEntities=[t,...this.recentEntities.filter(e=>e.id!==t.id)].slice(0,20)}async getCollectionCatalog(t){const e=await this.storage.findFileById(t);if(!e)return null;const n=e.substring(0,e.lastIndexOf("/"))+"/volume_book_mapping.json";try{const i=await this.storage.loadMetadata(n);return Object.keys(i).length===0?null:i}catch{return null}}async getRecommended(){const t=this.workspaceRoot+"/book-index-draft/recommended.json";try{const e=await this.fs.readFile(t);return JSON.parse(e)}catch{return null}}getAssetDir(t){return this.storage.getAssetDir(t)}async initAssetDir(t){return this.storage.initAssetDir(t)}async hasAssetDir(t){return this.storage.hasAssetDir(t)}getBookIndexStorage(){return this.storage}async rebuildIndex(t){await this.storage.rebuildIndex(t)}extractTypeFromId(t){try{const e=_(t);return k(e).type}catch{return"book"}}extractAuthor(t){const e=t.authors;if(Array.isArray(e)&&e.length>0){const s=e[0];return typeof s=="object"&&s!==null?s.name||"":String(s)}}extractYear(t){const e=t.publication_info;if(typeof e=="object"&&e!==null)return e.year||void 0}async resolveEntity(t){const e=await this.storage.getItem(t);return e?{id:t,title:e.title||"未命名"}:null}paginate(t,e){const s=e.page??1,n=e.pageSize??50;if(e.sortBy){const a=e.sortBy,l=e.sortOrder==="desc"?-1:1;t.sort((u,h)=>{const f=u[a]??"",d=h[a]??"";return f<d?-l:f>d?l:0})}const i=t.length,r=(s-1)*n;return{entries:t.slice(r,r+n),total:i,page:s,pageSize:n}}}function Kt(o){return o==="collated"||o==="self_collated"}const Vt=["default","manifest","fragments","sources","extra"],Yt=/^[a-z][a-z0-9-]*$/;function B(o){return typeof o!="string"?!1:o==="default"?!0:Yt.test(o)&&!Vt.includes(o)}function Xt(o){return/^\d+$/.test(o)}function v(o){return o.length>0&&!o.includes("..")&&!/[\\/?#%\s\u0000-\u001f\u007f]/.test(o)}const Qt=/^(整理本|整理|转录全文|轉錄全文|转录|轉錄|全文|文本)$/;function Zt(o){var s;const t=te(o),e=(s=o.edition_label)==null?void 0:s.trim();return e&&e!==t?`${e} · ${t}`:t}function te(o){for(const t of[o.label,o.source_name]){const e=t==null?void 0:t.trim();if(e&&!Qt.test(e))return e}return o.label||o.source_name||o.key}function ee(o,t){const e=(t==null?void 0:t.chapters)??[];if(e.length===0)return null;if(o){const s=e.find(n=>n.file===o.file);if(s)return s.file;if(o.n!==void 0){const n=e.find(i=>i.n===o.n);if(n)return n.file}}return e[0].file}function se(o,t){const e=o==null?void 0:o.versions;if(!(!e||e.length===0))return(t!=null?e.find(s=>s.key===t):void 0)??e.find(s=>s.key==="default")??e[0]}const ne="/data",oe=1e4;class ie{constructor(t={}){this.hubsLoading=null,this.chunkCache=new Map,this.chunkLoading=new Map,this.manifest=null,this.manifestLoading=null,this.entryFileCache=new Map,this.tiyaoCache=new Map,this.tiyaoLoading=new Map,this.metaCache=null,this.metaLoading=null,this.promotions=null,this.promotionsLoading=null,this.promotionsLoadFailed=!1,this.promotionShards=new Map,this.versionPromise=null,this.versionInjected=!1,this.basePath=t.basePath??ne,this.timeout=t.timeout??oe,this.hubsPath=t.hubsPath??"_hubs.json",this.detailLayout=t.detailLayout??"auto",t.version!==void 0&&(this.version=t.version??null,this.versionInjected=!0)}async ensureVersion(){return this.version!==void 0?this.version:this.versionPromise?this.versionPromise:(this.versionPromise=(async()=>{try{const t=await fetch(`${this.basePath}/version.json`,{cache:"no-cache",signal:AbortSignal.timeout(this.timeout)});if(!t.ok)return null;const e=await t.json(),s=e==null?void 0:e.commitId;return!s||s==="unknown"?null:s.slice(0,12)}catch{return null}})(),this.version=await this.versionPromise,this.version)}async fetchJson(t){const e=await this.ensureVersion(),s=e?`${t}${t.includes("?")?"&":"?"}v=${e}`:t,n=await fetch(s,{cache:"no-cache",signal:AbortSignal.timeout(this.timeout)});if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);return n.json()}async ensurePromotions(){if(this.promotions)return this.promotions;if(this.promotionsLoading)return this.promotionsLoading;this.promotionsLoading=(async()=>{try{const t=await this.fetchJson(`${this.basePath}/promotions.json`);this.promotions=P(t),this.promotionsLoadFailed=!1}catch{this.promotions=new Map,this.promotionsLoadFailed=!0}return this.promotions})();try{return await this.promotionsLoading}finally{this.promotionsLoading=null}}promotionShard(t){const e=t.slice(-st);let s=this.promotionShards.get(e);return s||(s=this.fetchJson(`${this.basePath}/promotions/${e}.json`).then(n=>{const i=P(n);return i.size>0?i:null},()=>null),this.promotionShards.set(e,s)),s}async canonicalIdFor(t){if(this.promotions&&!this.promotionsLoadFailed)return this.promotions.get(t)??t;if(t.length>=st){const e=await this.promotionShard(t);if(e)return e.get(t)??t}return(await this.ensurePromotions()).get(t)??t}async loadManifest(){if(this.manifest)return this.manifest;if(this.manifestLoading)return this.manifestLoading;this.manifestLoading=(async()=>{try{this.manifest=await this.fetchJson(`${this.basePath}/chunks/_manifest.json`)}catch{this.manifest=[]}return this.manifest})();try{return await this.manifestLoading}finally{this.manifest||(this.manifestLoading=null)}}async resolvePrefix(t){const e=await this.loadManifest();let s=0,n=e.length-1,i=null;for(;s<=n;){const r=s+n>>1;e[r]<=t?(i=e[r],s=r+1):n=r-1}if(i&&t.startsWith(i))return i;for(const r of e)if(t.startsWith(r))return r;return null}async loadChunk(t){if(this.chunkCache.has(t))return this.chunkCache.get(t);const e=this.chunkLoading.get(t);if(e)return e;const s=(async()=>{try{const n=await this.fetchJson(`${this.basePath}/chunks/${t}.json`);return this.chunkCache.set(t,n),n}catch{return this.chunkCache.set(t,{}),{}}})();this.chunkLoading.set(t,s);try{return await s}finally{this.chunkLoading.delete(t)}}async loadDetail(t){return this.detailLayout!=="entry"&&((await this.loadManifest()).length>0||this.detailLayout==="chunks")?(await this.loadChunkForId(t))[t]||null:this.loadEntryFile(t)}loadEntryFile(t){let e=this.entryFileCache.get(t);return e||(e=this.fetchJson(`${this.basePath}/entry/${encodeURIComponent(t)}.json`).catch(()=>null),this.entryFileCache.set(t,e)),e}async loadChunkForId(t){const e=await this.resolvePrefix(t);return e?this.loadChunk(e):{}}async loadTiyaoGroup(t,e){const s=`${t}-${e}`;if(this.tiyaoCache.has(s))return this.tiyaoCache.get(s);const n=this.tiyaoLoading.get(s);if(n)return n;const i=c=>String(c).padStart(3,"0"),r=(async()=>{const c=await this.fetchJson(`${this.basePath}/tiyao/juan-${i(t)}-${i(e)}.json`);return this.tiyaoCache.set(s,c),c})();this.tiyaoLoading.set(s,r);try{return await r}finally{this.tiyaoLoading.delete(s)}}async getCounts(){if(this.metaCache)return this.metaCache;if(this.metaLoading){const t=await this.metaLoading;if(t)return t;throw new Error("BundleStorage: meta.json 加载失败")}this.metaLoading=(async()=>{const t=await this.fetchJson(`${this.basePath}/meta.json`);if(!t||typeof t.works!="number")throw new Error("BundleStorage: meta.json 格式无效");return this.metaCache=t,t})();try{const t=await this.metaLoading;if(!t)throw new Error("BundleStorage: meta.json 加载失败");return t}finally{this.metaLoading=null}}async getResourceCounts(){return(await this.getCounts()).resourceCounts??{hasText:0,hasImage:0}}async getSubtypeStats(){return(await this.getCounts()).subtypeStats??{}}async loadEntries(t,e){throw new Error("BundleStorage.loadEntries 已废弃:请使用 worker 搜索")}async search(t,e,s){throw new Error("BundleStorage.search 已废弃:请使用 worker 搜索")}async searchAll(t,e=5){throw new Error("BundleStorage.searchAll 已废弃:请使用 worker 搜索")}getHubs(){return this.hubsLoading??(this.hubsLoading=this.fetchJson(`${this.basePath}/${this.hubsPath}`).catch(()=>null)),this.hubsLoading}async getItem(t){try{const e=await this.canonicalIdFor(t),s=e!==t?t:void 0,n=await this.loadDetail(e);return n&&(n.type==="entity"&&!n.title&&n.primary_name&&(n.title=n.primary_name),s&&(n.redirected_from=s)),n}catch{return null}}async getEntry(t){var e,s,n,i;try{const r=await this.canonicalIdFor(t),c=r!==t?t:void 0,a=await this.loadDetail(r);if(!a)return null;const l=ft(r),u=l==="entity"?a.primary_name||a.title||a.name||r:a.title||a.name||r;return{id:r,title:u,type:l,isDraft:!0,author:a.author,dynasty:a.dynasty,role:a.role,additional_titles:(e=a.additional_titles)==null?void 0:e.map(h=>typeof h=="string"?h:h==null?void 0:h.book_title).filter(Boolean),attached_texts:(s=a.attached_texts)==null?void 0:s.map(h=>typeof h=="string"?h:h==null?void 0:h.book_title).filter(Boolean),edition:a.edition,juan_count:a.juan_count,has_text:a.has_text,has_image:a.has_image,has_collated:a.has_collated,subtype:a.subtype,primary_name:a.primary_name,birth_year:((n=a.dates)==null?void 0:n.birth)??void 0,death_year:((i=a.dates)==null?void 0:i.death)??void 0,cbdb_id:a.cbdb_id,...c?{redirected_from:c}:{}}}catch{return null}}async getAllEntries(){throw new Error("BundleStorage.getAllEntries 已废弃:请使用 getEntry / worker 搜索")}async saveItem(){throw new Error("BundleStorage 为只读模式,不支持保存")}async deleteItem(){throw new Error("BundleStorage 为只读模式,不支持删除")}async generateId(){throw new Error("BundleStorage 为只读模式,不支持生成 ID")}async getCollectionCatalogs(t){const e=await this.getItem(t);if(!e)return null;const s=e.resources||[];if(s.length===0)return null;const n=[];for(const i of s)try{const r=await this.fetchJson(`${this.basePath}/items/${t}/${i.id}/volume_book_mapping.json`);r&&n.push({resource_id:i.id,short_name:i.short_name,data:O(r)})}catch{}return n.length>0?n:null}async getCollectionCatalog(t){var s;const e=await this.getCollectionCatalogs(t);return((s=e==null?void 0:e[0])==null?void 0:s.data)??null}async getTextManifest(t){if(!v(t))return null;try{const e=await this.fetchJson(`${this.basePath}/items/${t}/manifest.json`);return e&&Array.isArray(e.versions)?e:null}catch{return null}}async getTextIndex(t,e){if(!v(t)||!B(e))return null;try{const s=await this.fetchJson(`${this.basePath}/items/${t}/${e}/index.json`);return s&&Array.isArray(s.chapters)?s:null}catch{return null}}async getChapter(t,e,s,n){if(!v(t)||!B(e)||!v(s))return null;const i=`${this.basePath}/items/${t}/${e}/${s}`,r=await this.ensureVersion(),c=r?`${i}.txt?v=${r}`:`${i}.txt`,a=fetch(c,{cache:"no-cache",signal:AbortSignal.timeout(this.timeout)}).then(f=>f.ok?f.text():null).catch(()=>null),l=n!=null&&n.json?this.fetchJson(`${i}.json`).catch(()=>null):Promise.resolve(null),[u,h]=await Promise.all([a,l]);return u!=null||h?{md:u,json:h}:null}async getLineageGraph(t){try{return await this.fetchJson(`${this.basePath}/items/${t}/lineage_graph.json`)}catch{return null}}async getCatalogProgress(){try{return await this.fetchJson(`${this.basePath}/resource-catalog.json`)}catch{return null}}async getCollectionProgress(){try{return await this.fetchJson(`${this.basePath}/resource-collection.json`)}catch{return null}}async getResourceProgress(){try{return await this.fetchJson(`${this.basePath}/resource.json`)}catch{return null}}async getSiteProgress(){try{return await this.fetchJson(`${this.basePath}/resource-site.json`)}catch{return null}}async getRecommended(){try{return await this.fetchJson(`${this.basePath}/recommended.json`)}catch{return null}}clearCache(){this.chunkCache.clear(),this.chunkLoading.clear(),this.manifest=null,this.manifestLoading=null,this.entryFileCache.clear(),this.tiyaoCache.clear(),this.tiyaoLoading.clear(),this.metaCache=null,this.metaLoading=null,this.versionInjected||(this.version=void 0,this.versionPromise=null)}}class E extends Error{constructor(t){super(t),this.name="BookIndexError"}}class re extends E{constructor(t){super(t),this.name="StorageError"}}class ae extends E{constructor(t){super(t),this.name="IdGenerationError"}}class ce extends E{constructor(t){super(t),this.name="ConfigError"}}class le extends E{constructor(t){super(t),this.name="MigrationError"}}class he{constructor(t,e,s=1){this.storage=new D(t,e),this.idGen=new U(s)}generateId(t="book",e="draft"){return this.idGen.nextIdRaw(e,t)}encodeId(t){return A(t)}decodeId(t){return _(t)}async saveItem(t,e,s="draft"){let n=t.id||t.ID;if(n)try{const r=S(n);e||(e=r.type)}catch{throw new E(`Invalid ID format: ${n}`)}else e||(e=t.type||"book"),n=this.idGen.nextId(s,e),t.id=n;return await this.storage.saveItem(e,n,t)}async getItem(t){return this.storage.getItem(t)}async findItemPath(t){return this.storage.findFileById(t)}async updateField(t,e,s){const n=await this.storage.findFileById(t);if(!n)return!1;try{const i=await this.storage.loadMetadata(n),r={基本信息:null,介绍:"description",资源:"resources",收藏历史:"history",其他版本:"related_books"},c=e in r?r[e]:e;if(c===null)return!1;if(c==="description"&&typeof s=="string"){const l=i[c]||{};i[c]={text:s,sources:l.sources||[]}}else i[c]=s;const a=S(t);return await this.storage.saveItem(a.type,t,i),!0}catch{return!1}}async deleteItem(t){return this.storage.deleteItem(t)}async rebuildIndices(){await this.storage.rebuildIndex("official"),await this.storage.rebuildIndex("draft")}getAssetDir(t){return this.storage.getAssetDir(t)}async initAssetDir(t){return this.storage.initAssetDir(t)}async hasAssetDir(t){return this.storage.hasAssetDir(t)}getStorage(){return this.storage}}const ue={wikisource:"wikisource",shidianguji:"shidianguji",archive:"archive",ctext:"ctext",nlc:"nlc","read.nlc":"nlc","db.sido":"sido","guji.artx":"guji-artx","digital.library":"digital-library"},ot=new Set(["text","image","physical","catalog","annotated"]),de=new Set(["catalog","search"]),fe=new Set(["com","org","net","cn","edu","gov","io","jp","tw","hk"]);function ye(o){if(!o)return"";try{const e=new URL(o).hostname;for(const[n,i]of Object.entries(ue))if(e.includes(n))return i;const s=e.split(".");if(s.length>=2){const n=s.filter(i=>!fe.has(i)&&i.length>2);return n.length>0?n[n.length-1]:s[s.length-2]}return e}catch{return""}}function ge(o){const t=[];o.name||t.push("name is required");let e=!1;if(o.types!==void 0)if(!Array.isArray(o.types)||o.types.length===0)t.push("types must be a non-empty array when present");else{for(const s of o.types)ot.has(s)||t.push(`invalid types atom '${s}', must be one of ${[...ot].join(", ")}`);e=o.types.length===1&&o.types[0]==="physical"}else t.push("types is required");return o.root_type&&!de.has(o.root_type)&&t.push(`invalid root_type '${o.root_type}'`),!e&&!o.url&&t.push("url is required for non-physical resources"),t}const p=class p{constructor(t,e=""){if(this._type=null,this.title=e,typeof t=="string"){t.startsWith(p.PREFIX)&&(t=t.slice(p.PREFIX.length)),this.idStr=t;try{this.idInt=_(t)}catch{this.idInt=0n}}else this.idInt=t,this.idStr=A(t);if(this.idInt>0n)try{const s=S(this.idStr);this._type=s.type}catch{}}get type(){return this._type}getIcon(){return this._type===null?"":this._type==="book"?"📖 ":this._type==="collection"?"📚 ":this._type==="work"?"📜 ":""}render(t=!1){return`[${t?this.getIcon():""}${this.title}](${p.PREFIX}${this.idStr})`}static parseFromLink(t){const e=t.match(/\[(.*?)\]\((.*?)\)/);if(e){const s=e[1],n=e[2];if(n.startsWith(p.PREFIX)){const i=n.slice(p.PREFIX.length);return new p(i,s)}}return null}static isBidLink(t){return t.startsWith(p.PREFIX)}};p.PROTOCOL="bid:\\\\",p.PREFIX="bid:\\\\";let R=p;exports.BidLink=R;exports.BookIndexError=E;exports.BookIndexManager=he;exports.BookIndexStorage=D;exports.BundleStorage=ie;exports.ConfigError=ce;exports.GithubStorage=qt;exports.IdGenerationError=ae;exports.IdGenerator=U;exports.LocalStorage=zt;exports.MigrationError=le;exports.StorageError=re;exports.VARIANT_CHARS=gt;exports.base36Decode=M;exports.base36Encode=A;exports.base58Decode=dt;exports.buildId=j;exports.buildPromotionMap=P;exports.cleanName=yt;exports.decodeId=Ft;exports.decodeIdString=S;exports.encodeId=Tt;exports.extractIdFromUrl=ye;exports.extractStatus=Lt;exports.extractType=ft;exports.isChapterSegment=Xt;exports.isCollatedKind=Kt;exports.isSafeSegment=v;exports.isTextKey=B;exports.matchChapterAcrossVersions=ee;exports.normalizeCatalog=O;exports.normalizeVariants=mt;exports.parseId=k;exports.pickTextVersion=se;exports.shardOf=$;exports.smartDecode=_;exports.textVersionLabel=Zt;exports.validateResource=ge;