ezllm 0.0.42 → 0.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server.js +56 -56
- package/dist/web-ui/assets/{DashboardView-DRckeG7f.js → DashboardView-WtDwRkVw.js} +1 -1
- package/dist/web-ui/assets/{LayoutView-4x7mM1Nd.js → LayoutView-Bxe9Zpzg.js} +1 -1
- package/dist/web-ui/assets/{LoginView-D55GMnh2.js → LoginView-oHqStvWg.js} +1 -1
- package/dist/web-ui/assets/LogsView-C1rYzWM5.js +5 -0
- package/dist/web-ui/assets/{LogsView-u-0B5Xpc.css → LogsView-CXFJ_22b.css} +1 -1
- package/dist/web-ui/assets/{ManagedServicesView-aU7KD-uK.js → ManagedServicesView-Roep2c1v.js} +1 -1
- package/dist/web-ui/assets/PluginsView-Ar17i6aK.css +1 -0
- package/dist/web-ui/assets/PluginsView-xy5NajWq.js +2 -0
- package/dist/web-ui/assets/{ProvidersView-BuCzzvhA.js → ProvidersView-M_MSab-K.js} +1 -1
- package/dist/web-ui/assets/{ServiceStatusView-BfEtiG3k.js → ServiceStatusView-Dsrz87_B.js} +2 -2
- package/dist/web-ui/assets/{SettingsView-C3lfSDLN.js → SettingsView-CwdCfurj.js} +1 -1
- package/dist/web-ui/assets/{SetupView-BB5YHhmw.js → SetupView-8ajUBY2H.js} +1 -1
- package/dist/web-ui/assets/{config-B3YP6GMt.js → config-_F8xCbJI.js} +1 -1
- package/dist/web-ui/assets/format-CPPf8IfM.js +1 -0
- package/dist/web-ui/assets/{index-DVkpGX_l.js → index-W7WdLt_5.js} +1 -1
- package/dist/web-ui/assets/{message-JXw_u_ps.js → message-DpifAOwJ.js} +1 -1
- package/dist/web-ui/assets/providers-CkMtur-C.js +1 -0
- package/dist/web-ui/assets/{router-DxY62FPf.js → router-BgTNV93P.js} +2 -2
- package/dist/web-ui/assets/{useCopyToast-W6vLjLdg.js → useCopyToast-B_Qvf_Pf.js} +1 -1
- package/dist/web-ui/assets/{useManagerApi-7t9qNB2C.js → useManagerApi-USNyi1JZ.js} +1 -1
- package/dist/web-ui/assets/{useQuickRangeFilter-BWtDACYs.js → useQuickRangeFilter-DNSnrkx7.js} +1 -1
- package/dist/web-ui/assets/useToast-X_JkPDpr.js +1 -0
- package/dist/web-ui/index.html +3 -3
- package/package.json +1 -1
- package/dist/web-ui/assets/LogsView-Ck8cUn2K.js +0 -5
- package/dist/web-ui/assets/PluginsView-XtlAtfkK.js +0 -2
- package/dist/web-ui/assets/PluginsView-ggYmqCJ8.css +0 -1
- package/dist/web-ui/assets/format-7jzqzMS_.js +0 -1
- package/dist/web-ui/assets/providers-CbsDigh3.js +0 -1
- package/dist/web-ui/assets/src-DLq1gsLr.js +0 -1
- package/dist/web-ui/assets/useToast-DgnKZwIF.js +0 -1
package/dist/server.js
CHANGED
|
@@ -22,7 +22,12 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
22
22
|
`),s=o;r.tablePrimaryKey!==void 0&&(s=`${o},\n PRIMARY KEY (${xu(r.tablePrimaryKey)})`);let c=[`CREATE TABLE IF NOT EXISTS ${bu(r.name)} (\n${s}\n)`];for(let e of r.indexes)c.push(n(r.name,e));return c.map(e=>`${e};`).join(`
|
|
23
23
|
`)}).join(`
|
|
24
24
|
`)}function Du(e){return`${bu(e.meta.table)}.${bu(e.meta.name)}`}function W(e,t){return{kind:`condition`,text:e,values:t}}function Ou(e,t){return W(`${Du(e)} = ?`,[t])}function ku(e,t){return W(`${Du(e)} <> ?`,[t])}function Au(e,t){return W(`${Du(e)} > ?`,[t])}function ju(e,t){return W(`${Du(e)} >= ?`,[t])}function Mu(e,t){return W(`${Du(e)} < ?`,[t])}function Nu(e,t){return W(`${Du(e)} <= ?`,[t])}function Pu(e,t){return W(`${Du(e)} LIKE ?`,[t])}function Fu(e,t){if(t.length===0)return W(`0 = 1`,[]);let n=t.map(()=>`?`).join(`, `);return W(`${Du(e)} IN (${n})`,t)}function Iu(e){return W(`${Du(e)} IS NULL`,[])}function Lu(e){return W(`${Du(e)} IS NOT NULL`,[])}function Ru(e,t,n){return e.length===0?W(n,[]):W(e.map(e=>`(${e.text})`).join(` ${t} `),e.flatMap(e=>e.values))}function zu(...e){return Ru(e,`AND`,`1 = 1`)}function Bu(...e){return Ru(e,`OR`,`1 = 0`)}function Vu(e){return W(`NOT (${e.text})`,e.values)}function Hu(e,t){return{kind:`sort`,text:`${Du(e)} ${t}`,values:[]}}function Uu(e){return Hu(e,`ASC`)}function Wu(e){return Hu(e,`DESC`)}function Gu(e){return{kind:`aggregation`,text:e,values:[]}}function Ku(e,t){return Gu(`${e}(${Du(t)})`)}function qu(e){return Ku(`SUM`,e)}function Ju(e){return Ku(`MIN`,e)}function Yu(e){return Ku(`MAX`,e)}function Xu(e){return e?Ku(`COUNT`,e):Gu(`COUNT(*)`)}var G={eq:Ou,ne:ku,gt:Au,gte:ju,lt:Mu,lte:Nu,like:Pu,in:Fu,isNull:Iu,isNotNull:Lu,and:zu,or:Bu,not:Vu,asc:Uu,desc:Wu,sum:qu,count:Xu,min:Ju,max:Yu},Zu=class{executor;table;constructor(e,t){this.executor=e,this.table=t}get tableName(){return yu(this.table).name}get tableColumns(){return yu(this.table).columns}get quotedTable(){return bu(this.tableName)}},Qu=class extends Zu{conds=[];where(e){return this.conds.push(e),this}appendWhere(e,t){if(this.conds.length===0)return e;let n=zu(...this.conds);return t.push(...n.values),`${e} WHERE ${n.text}`}},$u=class extends Qu{allowAllRows=!1;allRows(){return this.allowAllRows=!0,this}assertWhereOrAllRows(e,t){if(this.conds.length===0&&!this.allowAllRows)throw Error(`${e} ${this.tableName}:无 where 条件会${t}全表;确需全表${t}请显式调用 .allRows()`)}};function ed(e,t){return typeof e==`bigint`||typeof t==`bigint`?BigInt(e)+BigInt(t):e+t}var td=class extends Zu{rows=[];conflictMode=``;orIgnore(){return this.conflictMode=` OR IGNORE`,this}orReplace(){return this.conflictMode=` OR REPLACE`,this}values(e){let t=Array.isArray(e)?e:[e];return this.rows=[...this.rows,...t],this}run(){if(this.rows.length===0)throw Error(`insert ${this.tableName}:未提供数据,请先调用 .values(...)`);let e=Object.keys(this.tableColumns),t=new Map;for(let n of this.rows){let r=e.filter(e=>n[e]!==void 0);if(r.length===0)throw Error(`insert ${this.tableName}:.values(...) 的行不含任何 schema 列`);let i=JSON.stringify(r),a=t.get(i);a===void 0?t.set(i,{columns:r,rows:[n]}):a.rows.push(n)}let n=0,r=0;for(let e of t.values()){let t=[],i=e.rows.map(n=>`(${e.columns.map(e=>(t.push(mu(n[e])),`?`)).join(`, `)})`),a=`INSERT${this.conflictMode} INTO ${this.quotedTable} (${xu(e.columns)}) VALUES ${i.join(`, `)}`,o=this.executor.run({text:a,values:t});n=ed(n,o.changes),r=o.lastInsertRowid}return{changes:n,lastInsertRowid:r}}},nd=class extends Qu{orders=[];groupCols=[];projection={kind:`all`};limitValue;offsetValue;orderBy(...e){return this.orders.push(...e),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}groupBy(...e){return this.groupCols.push(...e),this}columns(e){if(Array.isArray(e)){let t=e;if(t.length===0)throw Error(`select ${this.tableName}:columns([]) 至少要指定一列`);for(let e of t)if(!(e in this.tableColumns))throw Error(`select ${this.tableName}:columns 引用了不存在的列 ${String(e)}`);this.projection={kind:`subset`,columns:t}}else{let t=Object.entries(e);if(t.length===0)throw Error(`select ${this.tableName}:columns({}) 至少要有一个聚合表达式`);this.projection={kind:`aggregate`,entries:t}}return this}build(){let e;switch(this.projection.kind){case`subset`:e=xu(this.projection.columns);break;case`aggregate`:e=this.projection.entries.map(([e,t])=>`${t.text} AS ${bu(e)}`).join(`, `);break;default:e=xu(Object.keys(this.tableColumns))}let t=[];if(e.length===0)throw Error(`select ${this.tableName}:该表没有声明任何列,无法生成 SELECT 列清单`);let n=this.appendWhere(`SELECT ${e} FROM ${this.quotedTable}`,t);if(this.groupCols.length>0&&(n+=` GROUP BY ${this.groupCols.map(e=>Du(e)).join(`, `)}`),this.orders.length>0){n+=` ORDER BY ${this.orders.map(e=>e.text).join(`, `)}`;for(let e of this.orders)t.push(...e.values)}return this.limitValue!==void 0&&(n+=` LIMIT ?`,t.push(this.limitValue)),this.offsetValue!==void 0&&(this.limitValue===void 0&&(n+=` LIMIT -1`),n+=` OFFSET ?`,t.push(this.offsetValue)),{text:n,values:t}}all(){return this.executor.all(this.build())}get(){return this.executor.get(this.build())}values(){return this.executor.values(this.build())}},rd=class extends $u{patchEntries=[];set(e){return this.patchEntries=Object.entries(e),this}run(){if(this.patchEntries.length===0)throw Error(`update ${this.tableName}:缺少 set(...),没有要写入的列`);this.assertWhereOrAllRows(`update`,`更新`);let e=[],t=this.tableColumns,n=this.patchEntries.map(([n,r])=>{if(!Object.hasOwn(t,n))throw Error(`update ${this.tableName}:set({ ${n}: ... }) 的 \`${n}\` 不是该表的列`);return e.push(mu(r)),`${bu(n)} = ?`}).join(`, `),r=this.appendWhere(`UPDATE ${this.quotedTable} SET ${n}`,e);return this.executor.run({text:r,values:e})}},id=class extends $u{run(){this.assertWhereOrAllRows(`delete`,`删除`);let e=[],t=this.appendWhere(`DELETE FROM ${this.quotedTable}`,e);return this.executor.run({text:t,values:e})}},ad=new Map,od=class{name;native;statements=new Map;closed=!1;constructor(e,t){this.name=e,this.native=t}stmt(e){let t=this.statements.get(e);if(t!==void 0)return t;let n=this.native.prepare(e);return this.statements.set(e,n),n}runPrepared(e,t){return{...e.run(...hu(t))}}getPrepared(e,t){return e.get(...hu(t))}allPrepared(e,t){return e.all(...hu(t))}all(e){return this.allPrepared(this.stmt(e.text),e.values)}get(e){return this.getPrepared(this.stmt(e.text),e.values)}values(e){let t=this.stmt(e.text);t.setReturnArrays(!0);try{return this.allPrepared(t,e.values)}finally{t.setReturnArrays(!1)}}run(e){return this.runPrepared(this.stmt(e.text),e.values)}exec(e){this.native.exec(e)}createTables(e){e.length!==0&&this.native.exec(Eu(e))}insert(e){return new td(this,e)}select(e){return new nd(this,e)}update(e){return new rd(this,e)}delete(e){return new id(this,e)}transaction(e){if(this.inTransaction)throw Error(`transaction ${this.name}:不支持嵌套事务`);this.native.exec(`BEGIN`),this.inTransaction=!0;try{let t=e(this.txView);return this.native.exec(`COMMIT`),t}catch(e){try{this.native.exec(`ROLLBACK`)}catch{}throw e}finally{this.inTransaction=!1}}inTransaction=!1;txViewValue=null;get txView(){if(this.txViewValue===null){let e=this;this.txViewValue={insert:t=>e.insert(t),select:t=>e.select(t),update:t=>e.update(t),delete:t=>e.delete(t),all:t=>e.all(t),get:t=>e.get(t),values:t=>e.values(t),run:t=>e.run(t),exec:t=>e.exec(t)}}return this.txViewValue}prepare(e){let t=this.stmt(e);return{run:(...e)=>this.runPrepared(t,e),get:(...e)=>this.getPrepared(t,e),all:(...e)=>this.allPrepared(t,e)}}close(){this.closed||(this.closed=!0,this.statements.clear(),this.native.close(),ad.get(this.name)===this&&ad.delete(this.name))}};function sd(e){let t=ad.get(e);if(t!==void 0)return t;Rt();let n=new ue(c(xt(),`${e}.db`));try{n.exec(`PRAGMA busy_timeout = 5000`),n.exec(`PRAGMA journal_mode = WAL`),n.exec(`PRAGMA journal_size_limit = 67108864`)}catch(e){throw n.close(),e}let r=new od(e,n);return ad.set(e,r),r}var K=Tu(`logs`,{id:U().primaryKey({autoIncrement:!0}),time:H().notNull(),date:H().notNull(),method:H(),path:H(),model:H(),status:U(),stream:U(),error:H(),preview:H(),input_tokens:U().default(0),output_tokens:U().default(0),cache_read_tokens:U().default(0),cache_creation_tokens:U().default(0),ip:H(),session_id:H(),duration:U().default(0),headers:H(),client:H(),ttft:U()},[wu(`idx_logs_date`).on(`date`),wu(`idx_logs_time`).on(`time`),wu(`idx_logs_model`).on(`model`),wu(`idx_logs_session`).on(`session_id`),wu(`idx_logs_client`).on(`client`)]),cd=Tu(`log_details`,{log_id:U().primaryKey(),detail:Cu().notNull()}),ld=Tu(`log_blobs`,{hash:H().primaryKey(),content:Cu().notNull()}),ud=Tu(`log_id_alloc`,{next_id:U().notNull()}),q=Tu(`client_names`,{ua:H().primaryKey(),client:H(),source:H(),attempts:U().notNull().default(0),created_at:H().notNull(),updated_at:H().notNull()}),dd=[K,ud,q],fd=[cd,ld],pd=[[`headers`,`TEXT`],[`client`,`TEXT`],[`ttft`,`INTEGER`]],md=[`CREATE INDEX IF NOT EXISTS idx_logs_ua ON logs (${$l})`];function hd(e){let t=e.native.prepare(`PRAGMA table_info(logs)`).all();if(t.length===0)return;let n=new Set(t.map(e=>String(e.name)));for(let[t,r]of pd)n.has(t)||e.exec(`ALTER TABLE logs ADD COLUMN ${t} ${r}`)}function gd(e){for(let t of md)e.exec(t)}var _d=null;function vd(){return yd().native}function yd(){if(_d!==null)return _d;let e=sd(`logs`);return hd(e),e.createTables(dd),gd(e),_d=e,e}function J(){return yd()}function bd(e){return J().transaction(e)}var xd=1e3,Sd=!1,Cd=0,wd=0;function Td(){let e=e=>{let t=e.get(V`SELECT seq FROM sqlite_sequence WHERE name = 'logs'`);return t===void 0?0:Number(t.seq)},t=(t,n)=>{if(e(t)>=n)return;let r=t.run(V`UPDATE sqlite_sequence SET seq = ${n} WHERE name = 'logs'`);Number(r.changes)===0&&t.run(V`INSERT INTO sqlite_sequence (name, seq) VALUES ('logs', ${n})`)},n=t=>{if(t.select(ud).columns([`next_id`]).limit(1).get()!==void 0)return;let n=t.select(K).columns({m:G.max(K.id)}).get(),r=Math.max(Number(n?.m??0),e(t))+1;t.insert(ud).values({next_id:r}).run()};if(Cd>=wd){let e=J();bd(()=>{Sd||=(n(e),!0);let r=e.select(ud).columns([`next_id`]).limit(1).get();Cd=Number(r.next_id),wd=Cd+xd,e.update(ud).set({next_id:wd}).allRows().run(),t(e,wd-1)})}return Cd++}function Ed(e){return de(e,{params:{[pe.BROTLI_PARAM_QUALITY]:9}})}function Dd(e){if(!e)return`-`;if(typeof e==`string`){let t=e.split(`
|
|
25
|
-
`).filter(e=>e.startsWith(`data: `)&&e.slice(6).trimEnd()!==`[DONE]`);if(t.length>0)try{let e=JSON.parse(t[0].slice(6)).choices?.[0]?.delta;return e?.content||e?.reasoning_content||`(SSE)`}catch{return`(SSE `+e.length+` chars)`}return`(SSE `+e.length+` chars)`}let t=e;if(t.error)return`错误: `+(t.error.message||JSON.stringify(t.error));let n=t.choices?.[0];return n?n.message?.content?.slice(0,100)||n.delta?.content||`(流式)`:JSON.stringify(e).slice(0,100)}function Od(e,t,n=9){let r=(e,t=9)=>{let n=de(Buffer.from(e,`utf-8`),{params:{[pe.BROTLI_PARAM_QUALITY]:t}});return Buffer.concat([Buffer.from([2]),n])},i=e=>ne(`sha256`).update(e,`utf-8`).digest(`hex`),a=(e,t)=>{if(typeof e==`string`){if(e.length<8192)return e;let n=i(e);return t.has(n)||t.set(n,e),{[ql]:n}}if(Array.isArray(e))return e.map(e=>a(e,t));if(typeof e==`object`&&e){let n={};for(let[r,i]of Object.entries(e))n[r]=a(i,t);return n}return e},o=e.time||new Date().toISOString(),s=new Map,c=a(e,s);return{id:t,time:o,date:Zl(o),preview:Dd(e.response),detail:r(JSON.stringify(c),n),blobs:s,entry:e}}function kd(e){return{method:e.method||null,path:e.path||null,model:e.model||null,status:e.status??null,stream:+!!e.stream,error:e.error||null,input_tokens:e.input_tokens||0,output_tokens:e.output_tokens||0,cache_read_tokens:e.cache_read_tokens||0,cache_creation_tokens:e.cache_creation_tokens||0,ip:e.ip||null,session_id:e.session_id||null,duration:e.duration||0,ttft:e.ttft??null,headers:e.headers||null,client:e.client||null}}function Ad(e,t){let n=t.time||new Date().toISOString(),r=Zl(n),i=J();return bd(()=>{i.insert(K).values({id:e,time:n,date:r,preview:Dd(t.response),...kd(t)}).run()}),e}var jd=4,Md=/^logs-(\d{4})(\d{2})(\d{2})\.db$/,Nd=/^\d{6}$/;function Pd(){return c(xt(),`details`)}function Fd(e){return c(Pd(),e.slice(0,7).replace(/-/g,``))}function Id(e){let t=e.replace(/-/g,``);return`details/${t.slice(0,6)}/logs-${t}`}function Ld(e){return c(Fd(e),`logs-${e.replace(/-/g,``)}.db`)}var Rd=new class{#e=new Map;#t(e,t){let n=this.#e.get(e);if(n!==void 0)return this.#e.delete(e),this.#e.set(e,n),n;if(t.create)m(Fd(e),{recursive:!0});else if(!p(Ld(e)))return null;let r=sd(Id(e));return r.createTables(fd),this.#n(e,r)}#n(e,t){for(this.#e.set(e,t);this.#e.size>jd;){let e=this.#e.keys().next().value;this.#r(e)}return t}#r(e){let t=this.#e.get(e);if(t!==void 0){this.#e.delete(e);try{t.close()}catch{}}}open(e){return this.#t(e,{create:!0})}openIfExists(e){return this.#t(e,{create:!1})}closeAll(){for(let e of[...this.#e.keys()])this.#r(e)}listDetailDates(){let e;try{e=_(Pd())}catch{return[]}let t=[];for(let n of e){if(!Nd.test(n))continue;let e;try{e=_(c(Pd(),n))}catch{continue}for(let n of e){let e=Md.exec(n);e!==null&&t.push(`${e[1]}-${e[2]}-${e[3]}`)}}return t.sort()}deleteDetailDb(e){this.#r(e);let t=Ld(e),n=!1;p(t)&&(y(t,{force:!0}),n=!0);for(let e of[`-wal`,`-shm`])y(t+e,{force:!0});try{b(Fd(e))}catch{}return n}};function zd(e){if(e.length===0)return 0;let t=new Map;for(let n of e){let e=t.get(n.date);e===void 0?t.set(n.date,[n]):e.push(n)}let n=J();for(let[e,r]of t){bd(()=>{for(let e of r)n.insert(K).values({id:e.id,time:e.time,date:e.date,preview:e.preview,...kd(e.entry)}).orIgnore().run()});let t=Rd.open(e);t.transaction(()=>{for(let e of r){t.insert(cd).values({log_id:e.id,detail:e.detail}).orReplace().run();for(let[n,r]of e.blobs)t.insert(ld).values({hash:n,content:Ed(Buffer.from(r,`utf-8`))}).orIgnore().run()}})}return e.length}function Bd(e){return fe(Buffer.from(e)).toString(`utf-8`)}function Vd(e){if(e.length>0&&e[0]===2)return fe(Buffer.from(e.subarray(1)));throw Error(`详情 BLOB 格式非法:缺少 brotli 标记字节(历史 gzip 格式已不再支持)`)}function Hd(e){let t=Object.keys(e);if(t.length!==1||t[0]!==`__blob`)return null;let n=e[ql];return typeof n==`string`?n:null}function Ud(e,t){if(Array.isArray(e))return e.map(e=>Ud(e,t));if(typeof e==`object`&&e){let n=e,r=Hd(n);if(r!==null){let n=t.get(r);return n===void 0?e:n}let i={};for(let[e,r]of Object.entries(n))i[e]=Ud(r,t);return i}return e}function Wd(e,t){if(Array.isArray(e)){for(let n of e)Wd(n,t);return}if(typeof e==`object`&&e){let n=e,r=Hd(n);if(r!==null){t.add(r);return}for(let e of Object.values(n))Wd(e,t)}}function Gd(e,t){let n=new Map,r=[...e];if(r.length===0)return n;for(let e=0;e<r.length;e+=400){let i=r.slice(e,e+400),a=t.select(ld).columns([`hash`,`content`]).where(G.in(ld.hash,i)).all();for(let e of a)n.set(e.hash,Bd(e.content))}return n}function Kd(e){let t=J().select(K).where(G.eq(K.id,Number(e))).get();if(t===void 0)return null;let n=Rd.openIfExists(t.date);if(n===null)return null;let r=null,i=n.select(cd).columns([`detail`]).where(G.eq(cd.log_id,t.id)).get();if(i&&i.detail!=null&&i.detail.length>0)try{let e=JSON.parse(Vd(i.detail).toString(`utf-8`)),t=new Set;Wd(e,t),r=Ud(e,Gd(t,n))}catch(e){A(`[logs] 详情 ${String(t.id)} 解析失败,按无详情处理:`,Ql(e))}return r===null?null:{detail:r,meta:{_id:t.id,time:t.time,model:t.model||``,method:t.method||null,path:t.path||null,status:t.status??null,stream:!!t.stream,error:t.error||null,ip:t.ip||null,session_id:t.session_id||null,headers:t.headers||null,client:t.client||null,input_tokens:t.input_tokens??0,output_tokens:t.output_tokens??0,cache_read_tokens:t.cache_read_tokens??0,cache_creation_tokens:t.cache_creation_tokens??0,duration:t.duration??0,ttft:t.ttft??null}}}
|
|
25
|
+
`).filter(e=>e.startsWith(`data: `)&&e.slice(6).trimEnd()!==`[DONE]`);if(t.length>0)try{let e=JSON.parse(t[0].slice(6)).choices?.[0]?.delta;return e?.content||e?.reasoning_content||`(SSE)`}catch{return`(SSE `+e.length+` chars)`}return`(SSE `+e.length+` chars)`}let t=e;if(t.error)return`错误: `+(t.error.message||JSON.stringify(t.error));let n=t.choices?.[0];return n?n.message?.content?.slice(0,100)||n.delta?.content||`(流式)`:JSON.stringify(e).slice(0,100)}function Od(e,t,n=9){let r=(e,t=9)=>{let n=de(Buffer.from(e,`utf-8`),{params:{[pe.BROTLI_PARAM_QUALITY]:t}});return Buffer.concat([Buffer.from([2]),n])},i=e=>ne(`sha256`).update(e,`utf-8`).digest(`hex`),a=(e,t)=>{if(typeof e==`string`){if(e.length<8192)return e;let n=i(e);return t.has(n)||t.set(n,e),{[ql]:n}}if(Array.isArray(e))return e.map(e=>a(e,t));if(typeof e==`object`&&e){let n={};for(let[r,i]of Object.entries(e))n[r]=a(i,t);return n}return e},o=e.time||new Date().toISOString(),s=new Map,c=a(e,s);return{id:t,time:o,date:Zl(o),preview:Dd(e.response),detail:r(JSON.stringify(c),n),blobs:s,entry:e}}function kd(e){return{method:e.method||null,path:e.path||null,model:e.model||null,status:e.status??null,stream:+!!e.stream,error:e.error||null,input_tokens:e.input_tokens||0,output_tokens:e.output_tokens||0,cache_read_tokens:e.cache_read_tokens||0,cache_creation_tokens:e.cache_creation_tokens||0,ip:e.ip||null,session_id:e.session_id||null,duration:e.duration||0,ttft:e.ttft??null,headers:e.headers||null,client:e.client||null}}function Ad(e,t){let n=t.time||new Date().toISOString(),r=Zl(n),i=J();return bd(()=>{i.insert(K).values({id:e,time:n,date:r,preview:Dd(t.response),...kd(t)}).run()}),e}var jd=4,Md=/^logs-(\d{4})(\d{2})(\d{2})\.db$/,Nd=/^\d{6}$/;function Pd(){return c(xt(),`details`)}function Fd(e){return c(Pd(),e.slice(0,7).replace(/-/g,``))}function Id(e){let t=e.replace(/-/g,``);return`details/${t.slice(0,6)}/logs-${t}`}function Ld(e){return c(Fd(e),`logs-${e.replace(/-/g,``)}.db`)}var Rd=new class{#e=new Map;#t(e,t){let n=this.#e.get(e);if(n!==void 0)return this.#e.delete(e),this.#e.set(e,n),n;if(t.create)m(Fd(e),{recursive:!0});else if(!p(Ld(e)))return null;let r=sd(Id(e));return r.createTables(fd),this.#n(e,r)}#n(e,t){for(this.#e.set(e,t);this.#e.size>jd;){let e=this.#e.keys().next().value;this.#r(e)}return t}#r(e){let t=this.#e.get(e);if(t!==void 0){this.#e.delete(e);try{t.close()}catch{}}}open(e){return this.#t(e,{create:!0})}openIfExists(e){return this.#t(e,{create:!1})}closeAll(){for(let e of[...this.#e.keys()])this.#r(e)}listDetailDates(){let e;try{e=_(Pd())}catch{return[]}let t=[];for(let n of e){if(!Nd.test(n))continue;let e;try{e=_(c(Pd(),n))}catch{continue}for(let n of e){let e=Md.exec(n);e!==null&&t.push(`${e[1]}-${e[2]}-${e[3]}`)}}return t.sort()}deleteDetailDb(e){this.#r(e);let t=Ld(e),n=!1;p(t)&&(y(t,{force:!0}),n=!0);for(let e of[`-wal`,`-shm`])y(t+e,{force:!0});try{b(Fd(e))}catch{}return n}};function zd(e){if(e.length===0)return 0;let t=new Map;for(let n of e){let e=t.get(n.date);e===void 0?t.set(n.date,[n]):e.push(n)}let n=J();for(let[e,r]of t){bd(()=>{for(let e of r)n.insert(K).values({id:e.id,time:e.time,date:e.date,preview:e.preview,...kd(e.entry)}).orIgnore().run()});let t=Rd.open(e);t.transaction(()=>{for(let e of r){t.insert(cd).values({log_id:e.id,detail:e.detail}).orReplace().run();for(let[n,r]of e.blobs)t.insert(ld).values({hash:n,content:Ed(Buffer.from(r,`utf-8`))}).orIgnore().run()}})}return e.length}function Bd(e){return fe(Buffer.from(e)).toString(`utf-8`)}function Vd(e){if(e.length>0&&e[0]===2)return fe(Buffer.from(e.subarray(1)));throw Error(`详情 BLOB 格式非法:缺少 brotli 标记字节(历史 gzip 格式已不再支持)`)}function Hd(e){let t=Object.keys(e);if(t.length!==1||t[0]!==`__blob`)return null;let n=e[ql];return typeof n==`string`?n:null}function Ud(e,t){if(Array.isArray(e))return e.map(e=>Ud(e,t));if(typeof e==`object`&&e){let n=e,r=Hd(n);if(r!==null){let n=t.get(r);return n===void 0?e:n}let i={};for(let[e,r]of Object.entries(n))i[e]=Ud(r,t);return i}return e}function Wd(e,t){if(Array.isArray(e)){for(let n of e)Wd(n,t);return}if(typeof e==`object`&&e){let n=e,r=Hd(n);if(r!==null){t.add(r);return}for(let e of Object.values(n))Wd(e,t)}}function Gd(e,t){let n=new Map,r=[...e];if(r.length===0)return n;for(let e=0;e<r.length;e+=400){let i=r.slice(e,e+400),a=t.select(ld).columns([`hash`,`content`]).where(G.in(ld.hash,i)).all();for(let e of a)n.set(e.hash,Bd(e.content))}return n}function Kd(e){let t=J().select(K).where(G.eq(K.id,Number(e))).get();if(t===void 0)return null;let n=Rd.openIfExists(t.date);if(n===null)return null;let r=null,i=n.select(cd).columns([`detail`]).where(G.eq(cd.log_id,t.id)).get();if(i&&i.detail!=null&&i.detail.length>0)try{let e=JSON.parse(Vd(i.detail).toString(`utf-8`)),t=new Set;Wd(e,t),r=Ud(e,Gd(t,n))}catch(e){A(`[logs] 详情 ${String(t.id)} 解析失败,按无详情处理:`,Ql(e))}return r===null?null:{detail:r,meta:{_id:t.id,time:t.time,model:t.model||``,method:t.method||null,path:t.path||null,status:t.status??null,stream:!!t.stream,error:t.error||null,ip:t.ip||null,session_id:t.session_id||null,headers:t.headers||null,client:t.client||null,input_tokens:t.input_tokens??0,output_tokens:t.output_tokens??0,cache_read_tokens:t.cache_read_tokens??0,cache_creation_tokens:t.cache_creation_tokens??0,duration:t.duration??0,ttft:t.ttft??null}}}var qd=V.raw(`AVG(CASE WHEN stream = 1 THEN ttft END) AS avg_ttft,
|
|
26
|
+
SUM(CASE WHEN stream = 1 AND ttft IS NULL THEN NULL
|
|
27
|
+
WHEN stream = 1 THEN duration - ttft
|
|
28
|
+
ELSE duration END) AS tps_window_ms,
|
|
29
|
+
SUM(CASE WHEN stream = 1 AND ttft IS NULL THEN 0 ELSE output_tokens END) AS tps_output_tokens,
|
|
30
|
+
SUM(CASE WHEN stream = 1 AND ttft IS NOT NULL THEN 1 ELSE 0 END) AS ttft_calls`);function Jd(e,t){return e>0&&t>0?Math.round(e*1e3/t*10)/10:null}function Yd(e){if(e==null)return null;let t=e=>typeof e==`number`&&Number.isFinite(e)?e:null,n=t(e.output_tokens),r=t(e.duration);if(n===null||n<=0||r===null)return null;let i=e.stream===!0||e.stream===1,a=t(e.ttft),o=i?a===null?null:r-a:r;return o===null?null:Jd(n,o)}function Xd(e,t,n){let r=(e,t)=>e>=400||t!=null&&t!==``;if(!t)return!0;if(String(t)===`err`)return r(e,n);let i=/^([1-5])xx$/i.exec(String(t));if(i&&i[1]){let t=Number(i[1])*100;return e>=t&&e<t+100}return!/^\d+$/.test(String(t))||e===Number(t)}function Zd(e,t){if(!t)return!0;let n=Jl.some(t=>RegExp(`^`+t.replace(/%/g,`.*`)+`$`).test(e||``));return t===`model`?n:!n}function Qd(e){let t=[];if(e.startDate&&t.push(G.gte(K.date,e.startDate)),e.endDate&&t.push(G.lte(K.date,e.endDate)),e.model&&t.push(G.like(K.model,`%${e.model}%`)),e.sessionId){let n=e.sessionId.trim();n&&t.push(G.and(G.gte(K.session_id,n),G.lt(K.session_id,`${n}\uffff`)))}return e.noSession&&t.push(G.or(G.isNull(K.session_id),G.eq(K.session_id,``))),e.client&&t.push(G.eq(K.client,e.client)),t.length===0?null:G.and(...t)}function $d(e){let t=[],n=Qd(e);if(n!==null&&t.push(n),e.pathGroup){let n=G.or(...Jl.map(e=>G.like(K.path,e)));e.pathGroup===`model`?t.push(n):e.pathGroup===`other`&&t.push(G.or(G.isNull(K.path),G.not(n)))}if(e.status){if(String(e.status)===`err`)t.push(G.or(G.gte(K.status,400),G.and(G.isNotNull(K.error),G.ne(K.error,``))));else{let n=/^([1-5])xx$/i.exec(String(e.status));if(n&&n[1]){let e=Number(n[1]);t.push(G.and(G.gte(K.status,e*100),G.lt(K.status,(e+1)*100)))}else/^\d+$/.test(String(e.status))&&t.push(G.eq(K.status,Number(e.status)))}}if(e.keyword){let n=`%${e.keyword}%`;t.push(G.or(G.like(K.model,n),G.like(K.method,n),G.like(K.path,n),G.like(K.preview,n),G.like(K.error,n),G.like(K.time,n)))}return t.length===0?null:G.and(...t)}function ef(e,t){return t===null?e:e.where(t)}function tf(e){return{p:Math.max(parseInt(String(e.page))||1,1),ps:Math.min(Math.max(parseInt(String(e.pageSize))||50,1),500)}}function nf(e){return e===`model`||e===`status`||e===`stream`?e:`time`}var rf={model:K.model,status:K.status,stream:K.stream,time:K.time},af=[`id`,`time`,`method`,`path`,`model`,`status`,`stream`,`error`,`preview`,`input_tokens`,`output_tokens`,`cache_read_tokens`,`cache_creation_tokens`,`ip`,`session_id`,`duration`,`ttft`,`headers`,`client`];function of(e){let t=e=>{let t=rf[nf(e.sort)];return e.order===`asc`?G.asc(t):G.desc(t)},{p:n,ps:r}=tf(e),i=$d(e),a=J(),o=ef(a.select(K).columns({c:G.count()}),i).get();return{total:o?Number(o.c):0,page:n,pageSize:r,items:ef(a.select(K).columns(af),i).orderBy(t(e)).limit(r).offset((n-1)*r).all().map(e=>({...e}))}}function sf(e={}){let t=[G.and(G.isNotNull(K.model),G.ne(K.model,``)),G.eq(K.status,200),G.or(...Jl.map(e=>G.like(K.path,e)))];e.startDate&&t.push(G.gte(K.date,e.startDate)),e.endDate&&t.push(G.lte(K.date,e.endDate)),e.model&&t.push(G.eq(K.model,e.model));let n=G.and(...t),r=J().all(V`
|
|
26
31
|
SELECT model,
|
|
27
32
|
COUNT(*) AS calls,
|
|
28
33
|
SUM(input_tokens) AS input_tokens,
|
|
@@ -30,17 +35,12 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
30
35
|
SUM(cache_read_tokens) AS cache_read_tokens,
|
|
31
36
|
SUM(cache_creation_tokens) AS cache_creation_tokens,
|
|
32
37
|
AVG(duration) AS avg_duration,
|
|
33
|
-
|
|
34
|
-
SUM(CASE WHEN stream = 1 AND ttft IS NOT NULL THEN 1 ELSE 0 END) AS ttft_calls,
|
|
35
|
-
SUM(CASE WHEN stream = 1 AND ttft IS NULL THEN NULL
|
|
36
|
-
WHEN stream = 1 THEN duration - ttft
|
|
37
|
-
ELSE duration END) AS tps_window_ms,
|
|
38
|
-
SUM(CASE WHEN stream = 1 AND ttft IS NULL THEN 0 ELSE output_tokens END) AS tps_output_tokens
|
|
38
|
+
${qd}
|
|
39
39
|
FROM logs
|
|
40
40
|
WHERE ${n}
|
|
41
41
|
GROUP BY model
|
|
42
42
|
ORDER BY calls DESC
|
|
43
|
-
`),i=
|
|
43
|
+
`),i=0,a=0,o=0,s=0,c=r.map(e=>{let t=Number(e.input_tokens),n=Number(e.output_tokens),r=Number(e.cache_read_tokens),c=Number(e.ttft_calls??0),l=e.avg_ttft==null?null:Math.round(Number(e.avg_ttft)),u=Number(e.tps_output_tokens??0),d=Number(e.tps_window_ms??0);return i+=u,a+=d,l!==null&&c>0&&(o+=l*c,s+=c),{model:e.model||`unknown`,calls:Number(e.calls),input_tokens:t,output_tokens:n,total_tokens:t+n,cache_read_tokens:r,cache_creation_tokens:Number(e.cache_creation_tokens),cache_rate:t>0?Math.round(r/t*1e3)/10:null,avg_duration:e.avg_duration==null?null:Math.round(Number(e.avg_duration)),avg_ttft:l,tps:Jd(u,d)}}),l=c.reduce((e,t)=>e+t.input_tokens,0),u=c.reduce((e,t)=>e+t.output_tokens,0),d=c.reduce((e,t)=>e+t.cache_read_tokens,0);return{total:{calls:c.reduce((e,t)=>e+t.calls,0),input_tokens:l,output_tokens:u,total_tokens:l+u,cache_read_tokens:d,cache_creation_tokens:c.reduce((e,t)=>e+t.cache_creation_tokens,0),cache_rate:l>0?Math.round(d/l*1e3)/10:null,avg_duration:(()=>{let e=c.filter(e=>e.avg_duration!=null);if(!e.length)return null;let t=e.reduce((e,t)=>e+(t.avg_duration??0)*t.calls,0),n=e.reduce((e,t)=>e+t.calls,0);return n>0?Math.round(t/n):null})(),avg_ttft:s>0?Math.round(o/s):null,tps:Jd(i,a)},models:c}}function cf(){return J().select(K).columns([`date`]).groupBy(K.date).orderBy(G.desc(K.date)).all().map(e=>e.date)}function lf(){return J().select(K).columns([`client`]).where(G.and(G.isNotNull(K.client),G.ne(K.client,``))).groupBy(K.client).orderBy(G.asc(K.client)).all().map(e=>e.client)}var uf=V.raw(`
|
|
44
44
|
COUNT(*) AS calls,
|
|
45
45
|
MIN(time) AS first_time,
|
|
46
46
|
MAX(time) AS last_time,
|
|
@@ -51,27 +51,27 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
51
51
|
SUM(output_tokens) AS output_tokens,
|
|
52
52
|
SUM(cache_read_tokens) AS cache_read_tokens,
|
|
53
53
|
SUM(cache_creation_tokens) AS cache_creation_tokens,
|
|
54
|
-
SUM(duration) AS duration`);function
|
|
55
|
-
SELECT session_id, ${
|
|
54
|
+
SUM(duration) AS duration`);function df(e){let t=e=>({session_id:e.session_id==null?``:String(e.session_id),calls:Number(e.calls??0),first_time:String(e.first_time??``),last_time:String(e.last_time??``),models:e.models==null?null:String(e.models),clients:e.clients==null?null:String(e.clients),errors:Number(e.errors??0),input_tokens:Number(e.input_tokens??0),output_tokens:Number(e.output_tokens??0),cache_read_tokens:Number(e.cache_read_tokens??0),cache_creation_tokens:Number(e.cache_creation_tokens??0),duration:Number(e.duration??0),avg_ttft:e.avg_ttft==null?null:Math.round(Number(e.avg_ttft)),tps:Jd(Number(e.tps_output_tokens??0),Number(e.tps_window_ms??0))}),{p:n,ps:r}=tf(e),i=$d(e),a=G.and(G.isNotNull(K.session_id),G.ne(K.session_id,``)),o=G.or(G.isNull(K.session_id),G.eq(K.session_id,``)),s=i===null?a:G.and(i,a),c=i===null?o:G.and(i,o),l=J(),u=l.all(V`
|
|
55
|
+
SELECT session_id, ${uf}, ${qd}
|
|
56
56
|
FROM logs
|
|
57
57
|
WHERE ${s}
|
|
58
58
|
GROUP BY session_id
|
|
59
59
|
ORDER BY last_time DESC
|
|
60
60
|
LIMIT ${r} OFFSET ${(n-1)*r}
|
|
61
61
|
`).map(t),d=l.get(V`
|
|
62
|
-
SELECT ${
|
|
62
|
+
SELECT ${uf}, ${qd}
|
|
63
63
|
FROM logs
|
|
64
64
|
WHERE ${c}
|
|
65
65
|
`),f=d&&Number(d.calls??0)>0?t(d):null,p=l.get(V`
|
|
66
66
|
SELECT COUNT(DISTINCT session_id) AS c FROM logs WHERE ${s}
|
|
67
67
|
`),m=l.get(V`
|
|
68
68
|
SELECT COUNT(*) AS c FROM logs WHERE ${i??G.and()}
|
|
69
|
-
`);return{total:Number(p?.c??0),rowsTotal:Number(m?.c??0),page:n,pageSize:r,groups:u,noSession:f}}var
|
|
69
|
+
`);return{total:Number(p?.c??0),rowsTotal:Number(m?.c??0),page:n,pageSize:r,groups:u,noSession:f}}var ff=[`id`,`time`,`date`,`model`,`status`,`stream`,`error`,`preview`];function pf(e,t=Yl,n=Xl){let{p:r,ps:i}=tf(e),a=String(e.keyword??``).toLowerCase(),o=Math.max(0,Math.floor(t));if(!a)return{total:0,page:r,pageSize:i,items:[],truncated:!1,scanLimit:o};let s=ef(J().select(K).columns(ff),Qd(e)).orderBy(G.desc(K.time)).limit(o+1).all(),c=s.length>o,l=s.slice(0,o),u=new Map;for(let e of l){let t=String(e.date),n=u.get(t);n===void 0?u.set(t,[Number(e.id)]):n.push(Number(e.id))}let d=new Map,f=new Map;for(let[e,t]of u){let n=Rd.openIfExists(e);if(n!==null){f.set(e,n);for(let e=0;e<t.length;e+=400){let r=t.slice(e,e+400),i=n.select(cd).columns([`log_id`,`detail`]).where(G.in(cd.log_id,r)).all();for(let e of i)d.set(Number(e.log_id),e.detail)}}}let p=[],m=new Map,h=0,g=!1;for(let e of l){let t=d.get(Number(e.id));if(!t||t.length===0)continue;if(h>=n){g=!0;break}let r=String(e.date),i;try{let e=Vd(t).toString(`utf-8`);h+=Buffer.byteLength(e),i=JSON.parse(e)}catch{continue}let a=m.get(r);if(a===void 0){let e=new Set;Wd(i,e),m.set(r,e)}else Wd(i,a);p.push({r:e,date:r,raw:i})}let _=c||g,v=new Map;for(let[e,t]of m){let n=f.get(e);n!==void 0&&v.set(e,Gd(t,n))}let y=[];for(let{r:t,date:n,raw:r}of p){let i=Ud(r,v.get(n)??new Map);JSON.stringify(i).toLowerCase().includes(a)&&(!e.model||String(i.model??``).includes(e.model))&&(!e.status||Xd(Number(i.status??0),e.status,i.error))&&Zd(i.path,e.pathGroup)&&y.push({time:t.time,method:i.method||null,path:i.path||null,model:i.model||``,status:i.status,stream:!!i.stream,error:i.error||null,preview:t.preview,id:t.id})}let b=nf(e.sort),x=e.order===`asc`?1:-1;return y.sort((e,t)=>{let n=e[b]??``,r=t[b]??``;return n>r?x:n<r?-x:0}),{total:y.length,page:r,pageSize:i,items:y.slice((r-1)*i,(r-1)*i+i),truncated:_,scanLimit:o}}function mf(e){let t=Rd.open(e),n=new Set,r=0,i=0,a=t.select(cd).columns([`detail`]).all();for(let e of a){r++;try{Wd(JSON.parse(Vd(e.detail).toString(`utf-8`)),n)}catch{i++}}if(i>0)return k(`[logs] 详情库 ${e} 有 ${String(i)} 条详情解析失败,跳过本次 blob 回收(避免误删仍被引用的内容)`),{scanned:r,blobsDeleted:0,skipped:!0};let o=t.select(ld).columns([`hash`]).all().map(e=>e.hash).filter(e=>!n.has(e));if(o.length===0)return{scanned:r,blobsDeleted:0,skipped:!1};let s=0;return t.transaction(()=>{for(let e=0;e<o.length;e+=400){let n=t.delete(ld).where(G.in(ld.hash,o.slice(e,e+400))).run();s+=Number(n.changes)}}),{scanned:r,blobsDeleted:s,skipped:!1}}function hf(e){let t=J(),n=$d(e),r=ef(t.select(K).columns({c:G.count()}),n).get(),i=r?Number(r.c):0,a;if(i>0)a=ef(t.select(K).columns([`id`]),n).all().map(e=>Number(e.id));else if(e.keyword){a=[];let t=!1;for(let n=1;;n++){let r=pf({...e,page:n,pageSize:500,sort:`time`,order:`desc`});if(a.push(...r.items.map(e=>Number(e.id))),t||=r.truncated,r.items.length===0||a.length>=r.total)break}t&&k(`[logs] 详情扫描达到上限,仅清理最近扫描窗口内的命中条目(更早的命中未参与匹配)`)}else return 0;if(a.length===0)return 0;let o=new Map;for(let e=0;e<a.length;e+=400){let n=t.select(K).columns([`id`,`date`]).where(G.in(K.id,a.slice(e,e+400))).all();for(let e of n){let t=o.get(e.date);t===void 0?o.set(e.date,[Number(e.id)]):t.push(Number(e.id))}}for(let[e,t]of o){let n=Rd.open(e);n.transaction(()=>{for(let e=0;e<t.length;e+=400)n.delete(cd).where(G.in(cd.log_id,t.slice(e,e+400))).run()})}bd(()=>{for(let e=0;e<a.length;e+=400)t.delete(K).where(G.in(K.id,a.slice(e,e+400))).run()});for(let e of o.keys())try{mf(e)}catch(t){k(`[logs] 详情库 ${e} 的 blob 回收失败:`,Ql(t))}return a.length}function gf(e,t){let n=e=>Zl(new Date(Date.now()-e*86400*1e3).toISOString());if(e<=0&&t<=0)return{detailsDeleted:0,rowsDeleted:0};let r=0;if(e>0){let t=n(e);for(let e of Rd.listDetailDates())e<t&&Rd.deleteDetailDb(e)&&r++}let i=0;if(t>0){let e=n(t),r=bd(()=>J().delete(K).where(G.lt(K.date,e)).run());i=Number(r.changes)}return{detailsDeleted:r,rowsDeleted:i}}var _f={syncIntervalMs:5e3,payloadQuality:9},vf=2e3,yf=1e3,bf=1e3;function xf(e){return J().select(K).columns([`id`]).where(G.eq(K.id,e)).get()!==void 0}var Sf=class{#e;#t;#n=null;#r=!1;#i=0;constructor(e){this.#e=e.spool,this.#t=e.getConfig}runScheduledRound(){this.#r||this.#n!==null||(this.#r=!0,this.syncOnce().then(e=>{(e.inserted>0||e.poisoned>0)&&O(`[ezllm] spool 入库: 详情 ${String(e.inserted)} 条`)}).catch(e=>{A(`[ezllm] spool 入库失败:`,Ql(e))}).finally(()=>{this.#r=!1}))}async syncOnce(e={}){let t=e.budgetMs??vf,n=Date.now()+t,r={inserted:0,poisoned:0,anchorFilled:0,filesDone:[]},i=this.#t(),a=this.#e.listIds();for(let e of a){if(Date.now()>=n)break;let t=this.#e.readRecord(e);if(t.kind!==`missing`){if(t.kind===`corrupt`){k(`[spool] 丢弃不可解析的记录 ${String(e)}.jsonl`),this.#e.deleteFile(e),r.poisoned++;continue}try{let n=Od(t.entry,e,i.payloadQuality),a=xf(e);zd([n]),a||r.anchorFilled++,r.inserted++}catch(t){A(`[spool] 记录 ${String(e)} 入库失败:`,Ql(t));continue}this.#e.deleteFile(e),r.filesDone.push(e),await au()}}return r}async syncNow(){if(this.#n!==null){await this.#n;return}if(!this.#r&&!(Date.now()-this.#i<bf)){this.#i=Date.now(),this.#n=this.syncOnce({budgetMs:500});try{await this.#n}finally{this.#n=null}}}async recover(){if(this.#n!==null){await this.#n;return}let e=this.syncOnce({budgetMs:3e4});this.#n=e;try{let t=await e;t.inserted>0&&O(`[ezllm] spool 启动恢复:补录 ${String(t.inserted)} 条日志详情`)}catch(e){A(`[ezllm] spool 启动恢复失败:`,Ql(e))}finally{this.#n=null}}async drain(e=6e4){let t={inserted:0,poisoned:0,anchorFilled:0,filesDone:[]},n=Date.now()+e;for(;;){let e=await this.syncOnce({budgetMs:Math.min(5e3,Math.max(0,n-Date.now()))});if(t.inserted+=e.inserted,t.poisoned+=e.poisoned,t.anchorFilled+=e.anchorFilled,t.filesDone.push(...e.filesDone),this.#e.listIds().length===0||Date.now()>=n)break}return t}},Cf=null;function wf(e){return Cf===null&&(Cf=e===void 0?new Sf({spool:new fu,getConfig:()=>_f}):new Sf(e)),Cf}function Tf(e){let t=wf(e);return{name:`spoolSync`,everyMs:()=>e.getConfig().syncIntervalMs,firstDelayMs:yf,run:()=>{t.runScheduledRound()}}}async function Ef(){await wf().syncNow()}async function Df(){await wf().recover()}async function Of(e=6e4){return wf().drain(e)}var kf=216e5,Af=3e4;function jf(e){return{name:`logPrune`,everyMs:kf,firstDelayMs:Af,run:()=>{try{let{detailDays:t,rowDays:n}=e.getRetention(),r=gf(t,n);(r.detailsDeleted>0||r.rowsDeleted>0)&&O(`[ezllm] 日志清理: 详情库 -${String(r.detailsDeleted)} 天, 摘要 -${String(r.rowsDeleted)} 条 (详情${t>0?` ${String(t)}天`:`永久`}, 摘要${n>0?` ${String(n)}天`:`永久`})`)}catch(e){A(`[ezllm] 日志清理失败:`,Ql(e))}}}}var Mf=3,Nf=`fallback`;function Pf(){return new Date().toISOString()}function Ff(e){return J().select(q).columns([`client`]).where(G.eq(q.ua,e)).get()}function If(e){if(e.length===0)return 0;let t=Pf(),n=J(),r=0;return bd(()=>{for(let i of e){let e=n.insert(q).values({ua:i,client:null,source:null,attempts:0,created_at:t,updated_at:t}).orIgnore().run();r+=Number(e.changes)}}),r}function Lf(){return J().select(q).columns([`ua`,`client`]).where(G.isNotNull(q.client)).all().filter(e=>e.client!==null&&e.client!==``)}function Rf(e,t){if(e===``||t===``)return 0;let n=J().run(V`
|
|
70
70
|
UPDATE logs SET client = ${t}
|
|
71
71
|
WHERE client IS NULL AND ${V.raw($l)} = ${e}
|
|
72
|
-
`);return Number(n.changes)}function
|
|
72
|
+
`);return Number(n.changes)}function zf(e){return J().select(q).columns([`ua`]).where(G.and(G.isNull(q.client),G.lt(q.attempts,Mf))).orderBy(G.asc(q.created_at)).limit(e).all().map(e=>e.ua)}function Bf(e,t){if(e.size===0)return 0;let n=Pf(),r=J(),i=0;return bd(()=>{for(let[a,o]of e){let e=r.update(q).set({client:o,source:t,updated_at:n}).where(G.eq(q.ua,a)).run();i+=Number(e.changes)}}),i}function Vf(e){if(e.length===0)return[];let t=J(),n=t.select(q).columns([`ua`,`attempts`,`client`]).where(G.in(q.ua,[...e])).all(),r=[],i=Pf();return bd(()=>{for(let e of n){if(e.client!==null)continue;let n=e.attempts+1;t.update(q).set({attempts:n,updated_at:i}).where(G.eq(q.ua,e.ua)).run(),n>=Mf&&r.push(e.ua)}}),r}var Hf=new Map,Uf=new Set;function Wf(e){let t=e.trim();if(t===``)return null;if(Hf.has(t))return Hf.get(t)??null;let n=Ff(t);return n===void 0?(Hf.set(t,null),Uf.add(t),null):(Hf.set(t,n.client),n.client)}function Gf(e){return(()=>{if(Uf.size===0)return 0;let e=If([...Uf]);return Uf.clear(),e})(),zf(e)}function Kf(e,t){if(e.size===0)return 0;let n=Bf(e,t);for(let[t,n]of e)Rf(t,n),Hf.set(t,n),Uf.delete(t);return n}function qf(e){return Vf(e)}var Jf=100,Yf=67108864,Xf=new Set([`authorization`,`proxy-authorization`,`x-api-key`,`api-key`,`x-goog-api-key`,`cookie`,`set-cookie`]),Zf=new Set([`key`,`apikey`,`accesskey`,`accesstoken`,`token`,`authtoken`,`sig`,`signature`,`secret`,`password`]);function Qf(e){let t=e=>e===null?null:e.split(`
|
|
73
73
|
|
|
74
|
-
`).filter(e=>e.trim()!==``),n=e=>`***redacted(${String(e)})***`,r=e=>e.toLowerCase().replace(/[-_]/g,``),i=e=>{if(e===null)return null;try{return JSON.parse(e)}catch{return e}},a=e=>{if(!e)return e;let t=!1,r={};for(let[i,a]of Object.entries(e))
|
|
74
|
+
`).filter(e=>e.trim()!==``),n=e=>`***redacted(${String(e)})***`,r=e=>e.toLowerCase().replace(/[-_]/g,``),i=e=>{if(e===null)return null;try{return JSON.parse(e)}catch{return e}},a=e=>{if(!e)return e;let t=!1,r={};for(let[i,a]of Object.entries(e))Xf.has(i.toLowerCase())?(r[i]=n(a.length),t=!0):r[i]=a;return t?r:e},o=e=>{let t;try{t=new URL(e)}catch{return e}let i=!1;for(let[e,a]of Array.from(t.searchParams.entries()))Zf.has(r(e))&&(t.searchParams.set(e,n(a.length)),i=!0);return i?t.toString():e},s=e.streaming,c=e.upstream,l=e.inbound.bodyText!==null||c.url!==null||c.responseText!==null||e.client.body!==void 0||e.client.streamText!==null,u=a(e.inbound.headers);return{time:e.time,method:e.http.method||void 0,path:e.http.path||void 0,model:e.route?.name||void 0,status:e.status,stream:s,error:e.error?.message??null,response:l?{_capture:!0,inbound_request:{url:o(e.http.url),headers:u,body:e.inbound.body??null},upstream_request:c.url?{url:o(c.url),headers:a(c.requestHeaders),body:i(c.requestBody)}:null,upstream_response_text:s?null:c.responseText,upstream_stream_frames:s?t(c.responseText):null,client_response:s?void 0:e.client.body,client_stream_frames:s?t(e.client.streamText):null,truncated:e.truncated}:null,input_tokens:e.usage?.inputTokens??0,output_tokens:e.usage?.outputTokens??0,cache_read_tokens:e.usage?.cacheReadInputTokens??0,cache_creation_tokens:e.usage?.cacheCreationInputTokens??0,ip:e.http.clientIp||null,session_id:e.http.sessionId||null,duration:e.durationMs,ttft:e.upstream.firstTokenMs,headers:u===null?null:JSON.stringify(u),client:Wf(e.http.userAgent)}}function $f(e,t){let n=Qf(t),r=Number(t.requestId),i=Number.isSafeInteger(r)&&r>0?r:Td();e.write(i,n),Ad(i,n);let a=Yd({output_tokens:n.output_tokens,duration:n.duration,stream:n.stream,ttft:n.ttft});O(`[ezllm] ${t.requestId} ${t.route?.name??t.http.path} -> ${String(t.status)} ${String(t.durationMs)}ms streaming=${String(t.streaming)}`+(n.ttft==null?``:` ttft=${String(n.ttft)}ms`)+(a===null?``:` tps=${String(a)}`)+(t.error===null?``:` error=${t.error.stage}: ${t.error.message}`))}var ep=class{#e;#t;#n;#r=[];#i=0;#a=!1;constructor(e={}){this.#e=e.spool??new fu,this.#t=e.queueCapacity??Jf,this.#n=e.queueMaxBytes??Yf}#o(){let e=this.#r.shift();return this.#i-=tp(e),e}async#s(){if(!this.#a){this.#a=!0;try{for(;this.#r.length>0;){await au();try{$f(this.#e,this.#o())}catch(e){A(`[ezllm] trace 落盘失败:`,Ql(e))}}}finally{this.#a=!1}}}write(e){for(;this.#r.length>=this.#t||this.#i>=this.#n&&this.#r.length>0;)this.#o(),k(`[ezllm] trace 队列已满(${String(this.#t)} 条 / ${String(Math.round(this.#n/1024/1024))}MB),丢弃最旧一条`);this.#r.push(e),this.#i+=tp(e),this.#s()}async flush(){for(;this.#r.length>0||this.#a;)await au();await this.#e.flush()}flushSync(){for(;this.#r.length>0;)try{$f(this.#e,this.#o())}catch(e){A(`[ezllm] trace 崩溃前落盘失败:`,Ql(e))}this.#e.flushSync()}};function tp(e){return(e.inbound.bodyText?.length??0)+(e.upstream.requestBody?.length??0)+(e.upstream.responseText?.length??0)+(e.client.streamText?.length??0)+4096}var np=48;function rp(e){let t=e.trim();if(t===``)return``;let n=t.split(/\s+/)[0]??t;return n.length>np?n.slice(0,np):n}var ip=500;function ap(e={}){let t=e=>{let t=e.headers;if(typeof t==`string`&&t!==``)return t;let n=e.response;if(typeof n!=`object`||!n)return null;let r=n.inbound_request;if(typeof r!=`object`||!r)return null;let i=r.headers;return typeof i!=`object`||!i||Array.isArray(i)||Object.entries(i).length===0?null:JSON.stringify(i)},n=(e,t)=>{let n=e.get(V`SELECT detail FROM log_details WHERE log_id = ${t}`);if(n===void 0)return null;try{return JSON.parse(Vd(n.detail).toString(`utf-8`))}catch{return null}},r=J(),i={days:0,scanned:0,filled:0,skipped:0,uas:0,clientsAssigned:0},a=Rd.listDetailDates();for(let o of a){let a=r.all(V`SELECT id FROM logs WHERE date = ${o} AND headers IS NULL`).map(e=>Number(e.id));if(a.length===0)continue;i.days++;let s=Rd.openIfExists(o);if(s===null){i.skipped+=a.length,e.onProgress?.(`${o}: 详情库不存在,跳过 ${String(a.length)} 行`);continue}let c=new Set,l=[],u=()=>{if(l.length===0)return;let e=l;l=[],bd(()=>{for(let t of e)r.run(V`UPDATE logs SET headers = ${t.headers} WHERE id = ${t.id} AND headers IS NULL`)})};for(let e of a){i.scanned++;let r=n(s,e),a=r===null?null:t(r);if(a===null){i.skipped++;continue}l.push({id:e,headers:a}),i.filled++;let o=eu(a);o!==``&&c.add(o),l.length>=ip&&u()}u(),c.size>0&&(i.uas+=If([...c])),e.onProgress?.(`${o}: 扫描 ${String(a.length)} 行,回填 ${String(i.filled)} 行(累计)`)}if(a.length>0){let e=r.select(K).columns({n:G.count()}).where(G.and(G.isNull(K.headers),G.not(G.in(K.date,a)))).get();i.skipped+=Number(e?.n??0)}for(let e of Lf())i.clientsAssigned+=Rf(e.ua,e.client);return i}var op=2e3,sp=500;function cp(e={}){let t=e=>{let t;try{t=JSON.parse(e)}catch{return``}if(typeof t!=`object`||!t||Array.isArray(t))return``;try{let e=new Headers;for(let[n,r]of Object.entries(t))typeof r==`string`&&e.set(n,r);return Wc(e)}catch{return``}},n=(e,t)=>{t.length!==0&&bd(()=>{for(let n of t)e.run(V`
|
|
75
75
|
UPDATE logs SET session_id = ${n.sessionId}
|
|
76
76
|
WHERE id = ${n.id} AND (session_id IS NULL OR session_id = '')
|
|
77
77
|
`)})},r=J(),i={scanned:0,filled:0},a=0;for(;;){let o=r.all(V`
|
|
@@ -80,45 +80,45 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
80
80
|
AND (session_id IS NULL OR session_id = '')
|
|
81
81
|
AND headers IS NOT NULL
|
|
82
82
|
ORDER BY id
|
|
83
|
-
LIMIT ${
|
|
84
|
-
`);if(o.length===0)break;let s=[];for(let e of o){a=Number(e.id),i.scanned++;let o=t(e.headers);o!==``&&(s.push({id:Number(e.id),sessionId:o}),i.filled++,s.length>=ap&&(n(r,s),s.length=0))}n(r,s),e.onProgress?.(`已扫描到 id ${String(a)}:写入 ${String(i.filled)} 行(累计)`)}return i}async function sp(e){let t=()=>{for(let e of Dt())if(p(e))return e;return null},n=(e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=n.default??n[`module.exports`]??n;if(typeof r!=`object`||!r)return null;let i=r;return typeof i.onModelRequest==`function`?{onModelRequest:i.onModelRequest}:(k(`[ezllm] ${t} 未导出 onModelRequest 函数,已忽略(不挂任何钩子)`),null)},r=t();if(r===null)return;let i;try{i=await import(te(r).href)}catch(e){A(`[ezllm] 加载用户钩子失败,本次按无钩子运行:${r}`),A(`[ezllm] 原因:${e instanceof Error?e.message:String(e)}`),A(`[ezllm] 提示:模块写法与文件扩展名不匹配。CJS 内容(module.exports)请用 hook.cjs,ESM 内容(export default)请用 hook.mjs——这两个扩展名强制解析模式,不受任何 package.json 的 type 影响`);return}let a=n(i,r);a?.onModelRequest!==void 0&&(e.addHook(`onModelRequest`,a.onModelRequest),O(`[ezllm] 已加载用户钩子:${r}(onModelRequest)`))}function cp(e){return pt.port??e.port}async function lp(e,t,n={}){let r=new Sl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Td())}});t.register(r),await sp(r);let i={current:r,port:r.expanded.port,rebuild(e){i.current.reload(e),i.port=i.current.expanded.port;let t=i.current.expanded.deployments.names.length,n=e.providers.filter(e=>e.enabled===!1).length,r=n>0?`(${String(n)} 个已停用)`:``;O(`[gateway] 配置已热更新: ${String(e.providers.length)} 个供应商${r} / ${String(t)} 个模型`)},proxy:new M},a=async e=>{let t=new URL(e.req.url),n=new Headers(e.req.raw.headers);if(!n.has(`x-forwarded-for`)){let t=e.env?.incoming?.socket?.remoteAddress??``;t!==``&&n.set(`x-forwarded-for`,t)}if(!n.has(`authorization`)&&n.has(`x-api-key`)){let e=n.get(`x-api-key`)??``;e!==``&&n.set(`authorization`,`Bearer ${e}`)}return i.current.build().fetch(new Request(t.toString(),{method:e.req.raw.method,headers:n,body:e.req.raw.body,duplex:`half`}))};return i.proxy.use(`/v1/models`,async(e,n)=>{let r=e.req.header(`authorization`)??(e.req.header(`x-api-key`)===null?``:`Bearer ${e.req.header(`x-api-key`)}`);if(!await t.authorize(r))return Response.json({error:{message:`Unauthorized: invalid api key`,type:`authentication_error`,code:`401`}},{status:401});await n()}),i.proxy.all(`/v1/*`,e=>a(e)),i.proxy.all(`/v1`,e=>a(e)),i.proxy.all(`/responses`,e=>a(e)),i.proxy.all(`/chat/completions`,e=>a(e)),i.proxy.all(`/messages`,e=>a(e)),i.proxy.all(`/messages/count_tokens`,e=>a(e)),i.proxy.all(`/models`,e=>a(e)),i.proxy.all(`/healthz`,e=>a(e)),i}var up=64;function dp(e,t={}){let n=e=>e.trim(),r=new Map;function i(e,t){for(r.delete(e),r.set(e,t);r.size>up;){let e=r.keys().next().value;if(e===void 0)break;r.delete(e)}}function a(){return new Set(t.knownModelNames?t.knownModelNames():e.expanded.deployments.names)}e.plugin(e=>{e.addHook(`onFinish`,e=>{if(e.status!==200||e.ctx.model===null)return;let t=n(e.ctx.userAgent);t!==``&&i(t,e.ctx.model.name)}),e.addHook(`onModelNotFound`,t=>{if(a().has(t.requestedModel))return;let i=n(t.userAgent);if(i===``)return;let o=r.get(i);if(o!==void 0){if(!e.expanded.deployments.byName.has(o)){r.delete(i);return}return o}})})}var fp=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function(e,o){function s(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&s(`Access-Control-Allow-Origin`,c),t.credentials&&s(`Access-Control-Allow-Credentials`,`true`),n&&s(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&s(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&s(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(s(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await o(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};async function pp(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var mp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,hp=new M;function gp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}hp.post(`/login`,async e=>{let t=Rl();if(t.configBroken)return e.json({error:mp},503);if(!t.required)return e.json({error:`当前未设置登录账号,管理台免登录访问(如需启用请先设置账号)`},400);let n=await pp(e);if(n===null)return e.json({error:`请求体格式错误`},400);let{username:r,password:i}=n;return(r??``).trim()!==t.username||i!==t.password?e.json({error:`用户名或密码错误`},401):e.json({token:gp(t)})});async function _p(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=Rl();if(!n.required)return await t();if(n.configBroken)return e.json({error:mp},401);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==gp(n))return e.json({error:`token 无效或已过期`},401);await t()}var vp=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function yp(e,t){return e instanceof vp?(e.status>=500&&A(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e.message),t.json({error:e.message},e.status)):(A(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e instanceof Error?e.message:e),t.json({ok:!1,error:e instanceof Error?e.message:String(e)},500))}function bp(e){return async t=>{try{return await e(t)}catch(e){throw new vp(500,e.message)}}}var xp=8,Sp=6;function Cp(){let e=()=>{let e=El();if(e===null)throw new vp(500,`配置文件不存在`);return e},t=new M;return t.onError(yp),t.use(`*`,async(e,t)=>{if(e.req.method===`GET`)return t();let n=e.req.header(`sec-fetch-site`);if(n===`same-origin`||n===`none`)return t();let r=e.req.header(`origin`);return r===void 0||r.toLowerCase()===new URL(e.req.url).origin.toLowerCase()?t():e.json({error:`已拒绝跨站写请求`},403)}),t.get(`/status`,e=>{let t=zl(),n=!1;try{n=Fl()!==``}catch(e){if(!(e instanceof Tl))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:Rl().required,version:Lt(),buildSource:vt()})}),t.post(`/master-key`,async t=>{if(zl().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await pp(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r;if(n.mode===`generate`)r=re(32).toString(`base64url`);else if(n.mode===`custom`){if(r=(n.masterKey??``).trim(),r.length<xp)return t.json({error:`主密钥至少 ${String(xp)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return Ol(a),t.json({masterKey:r,...Hl(i,a)?{restartHint:Nl}:{}})}),t.post(`/finish`,async t=>{if(zl().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await pp(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r=n.deployment;if(r!==`local`&&r!==`server`)return t.json({error:`deployment 必须是 local 或 server`},400);let i=(n.masterKey??``).trim();if(i!==``&&i.length<xp)return t.json({error:`主密钥至少 ${String(xp)} 位`},400);if(r===`server`&&i===``&&Fl()===``)return t.json({error:`服务器部署必须设置主密钥,防止 /v1 网关被他人盗用`},400);let a=(n.username??``).trim(),o=n.password??``,s=a!==``||o!==``;if(s){if(a===``||o===``)return t.json({error:`用户名和密码需同时提供`},400);if(o.length<Sp)return t.json({error:`密码至少 ${String(Sp)} 位`},400)}else if(r===`server`)return t.json({error:`服务器部署必须设置登录账号密码,防止管理台被陌生人登录`},400);let c=e(),l={...c,...i===``?{}:{masterKey:i},setup:{completed:!0,deployment:r},allowLan:r===`server`,...s?{"web-ui":{...c[`web-ui`],"login-account":{username:a,password:o}}}:{}};return Ol(l),t.json({message:s?`初始化完成,请使用新账号登录`:`初始化完成`,...Hl(c,l)?{restartHint:Nl}:{}})}),t}function wp(e){let t=new M;return t.onError(yp),t.get(`/`,bp(e=>{let t=El();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,bp(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);try{Al(n)}catch(e){if(e instanceof lr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let r=null;try{r=El()}catch{r=null}return Ol(n),e.runtime.rebuild(kl(n)),t.json({message:`配置已保存并生效`,...Hl(r,n)?{restartHint:Nl}:{}})})),t}var Tp=`直接回复我 ok,不要思考不要解释`;function Ep(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function Dp(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function Op(e){for(let t of e.split(/\r?\n/)){if(!t.startsWith(`data:`))continue;let e=t.slice(5).trim();if(e!==``&&e!==`[DONE]`)try{let t=JSON.parse(e);if(typeof t==`object`&&t&&!Array.isArray(t))return t}catch{}}return null}async function kp(e,t){if(!(e.headers.get(`content-type`)??``).toLowerCase().includes(`text/event-stream`)){let n=await e.text().catch(()=>``),r=null;try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(r=e)}catch{}return{streamed:!1,latencyMs:Date.now()-t,payload:r}}let n=e.body?.getReader();if(n===void 0)return{streamed:!0,latencyMs:Date.now()-t,payload:null};let r=new TextDecoder,i=``;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;a!==void 0&&(i+=r.decode(a,{stream:!0}));let o=Op(i);if(o!==null)return{streamed:!0,latencyMs:Date.now()-t,payload:o}}}finally{await n.cancel().catch(()=>void 0)}return{streamed:!0,latencyMs:Date.now()-t,payload:null}}function Ap(e){let t=new M;t.onError(yp);let n=Ht(`test-results.json`),r=Ht(`models-cache.json`);function i(e,t=`openai`,n=!0){let r=e.replace(/\/+$/,``);return t===`anthropic`&&r.endsWith(`/anthropic`)&&(r=r.slice(0,-10)),`${Ep(r,n)}/models`}function a(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();if(e.includes(`authorization`)||e.includes(`api-key`)||e.includes(`token`)){let e=String(r);t[n]=e.length>8?`${e.slice(0,3)}****${e.slice(-4)}`:`****`}else t[n]=r}return t}async function o(e,t,n,r){return fetch(i(e,n,r),{headers:Dp(t,n),signal:AbortSignal.timeout(1e4)})}async function s(e,t){if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`});let n=await o(t.api_base,t.api_key,t.protocol??`openai`,t.autoV1??!0);return n.ok?await n.json():e.json({status:`error`,message:`HTTP ${String(n.status)}`})}function c(e){let{response:t,read:n,url:r,headers:i,payload:o}=e,s={method:`POST`,url:r,headers:a(i),body:o},c=n.payload??{};if(n.streamed){if(!t.ok)return{status:`error`,message:l(c,t.status),latency:n.latencyMs,request:s,response:{status:t.status,body:n.payload}};let e=n.payload!==null;return{status:e?`ok`:`error`,message:e?`流式首帧正常`:`流式响应未收到数据帧`,latency:n.latencyMs,request:s,response:{status:t.status,body:n.payload}}}return t.ok&&(c.choices!==void 0||c.output!==void 0||c.content!==void 0)?{status:`ok`,message:`${String(c.usage?.completion_tokens??c.usage?.output_tokens??0)} tokens`,latency:n.latencyMs,request:s,response:{status:t.status,body:c}}:{status:`error`,message:l(c,t.status),latency:n.latencyMs,request:s,response:{status:t.status,body:c}}}function l(e,t){let n=e.error,r=typeof n==`object`&&n&&`message`in n?String(n.message):typeof n==`string`?n:null;if(r!==null)return u(r);if(typeof e.msg==`string`&&e.msg.trim()!==``){let t=e.code===void 0||e.code===null?``:` (${String(e.code)})`;return u(`${e.msg.trim()}${t}`)}return u(`HTTP ${String(t)}`)}function u(e){let t=e;for(let[e,n]of[[/Weekly usage limit reached/i,`每周使用限额已达上限`],[/Resets in (\d+) day/i,`$1 天后重置`],[/RateLimitError:?\s*OpenAIException\s*-?\s*/gi,``],[/RateLimitError/g,`频率限制`],[/Rate limit/gi,`请求频率超限`],[/Invalid.*api.?key/i,`API Key 无效`],[/Unauthorized/i,`认证失败`],[/Not found/i,`模型或端点不存在`],[/Timeout/i,`请求超时`],[/Connection refused/i,`连接被拒绝`],[/ECONNREFUSED/i,`连接被拒绝`],[/ENOTFOUND/i,`域名无法解析`],[/model.*not.*found/i,`模型不存在`],[/context length exceeded/i,`上下文长度超限`],[/maximum context length/i,`超过最大上下文长度`],[/overloaded/i,`服务过载`],[/internal server error/i,`服务器内部错误`],[/bad gateway/i,`网关错误`],[/OpenAIException\s*-?\s*/i,``],[/To continue using[\s\S]*$/i,``],[/Received Model Group[\s\S]*$/i,``],[/Available Model Group[\s\S]*$/i,``],[/HTTP (\d+)/,`HTTP 错误 $1`]])t=t.replace(e,n);return t=t.replace(/\s+/g,` `).replace(/^[.:;\s-]+|[.:;\s-]+$/g,``).trim(),t||=e,t.length>120&&(t=t.substring(0,120)+`...`),t}t.get(`/results`,bp(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,bp(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,bp(async e=>{let{keyId:t,models:n}=await e.req.json();return!t||!Array.isArray(n)?e.json({error:`缺少必要参数: keyId, models`},400):(r.set(t,n),e.json({message:`模型缓存已更新`,keyId:t,count:n.length}))})),t.post(`/`,async e=>{try{let t=await s(e,await e.req.json());return t instanceof Response?t:e.json({status:`ok`,models:t.data?.length||0,protocol:`openai`})}catch(t){return e.json({status:`error`,message:t.message})}}),t.post(`/fetch-models`,async e=>{try{let t=await e.req.json(),n=await s(e,t);if(n instanceof Response)return n;let i=(n.data||[]).map(e=>e.id||e.name).filter(e=>!!e);if(t.keyId){let e=r.get(t.keyId)??[],n=[...new Set([...e,...i])];r.set(t.keyId,n)}return e.json({status:`ok`,models:i})}catch(t){return e.json({status:`error`,message:t.message})}});function d(e,t){return t===`anthropic`?{model:e,messages:[{role:`user`,content:Tp}],max_tokens:16,stream:!0}:t===`openai-responses`?{model:e,input:Tp,stream:!0}:{model:e,messages:[{role:`user`,content:Tp}],stream:!0}}async function f(e){let t=e.protocol||`openai`,n=e.autoV1??!0,r=e.api_base.replace(/\/+$/,``);if(!r)throw Error(`api_base 不能为空`);let i={"Content-Type":`application/json`,...Dp(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${Ep(r,n)}${a}`,s=d(e.model,t),l=Date.now(),u=await fetch(o,{method:`POST`,headers:i,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)});return c({response:u,read:await kp(u,l),url:o,headers:i,payload:s})}function p(e){let t=El();for(let n of t?.providers??[]){let t=n.models?.find(t=>t?.modelName===e);if(t)return t.customLlmProvider??n.customLlmProvider??`openai`}return`openai`}async function m(t,n){let r=Fl(),i=cp(e),a=`http://127.0.0.1:${String(i)}`,o={"Content-Type":`application/json`};r&&(o.Authorization=`Bearer ${r}`);let s=`${a}${n===`anthropic`?`/v1/messages`:n===`openai-responses`?`/v1/responses`:`/v1/chat/completions`}`,l=d(t,n),u=Date.now(),f;try{f=await fetch(s,{method:`POST`,headers:o,body:JSON.stringify(l),signal:AbortSignal.timeout(3e4)})}catch(e){let t=e;throw A(`[test] 网关自调用失败:`,t.message,`cause:`,t.cause?.message??`n/a`),e}return c({response:f,read:await kp(f,u),url:s,headers:o,payload:l})}return t.post(`/model`,async e=>{try{let t=await e.req.json(),r=t.model;if(!r)return e.json({status:`error`,message:`缺少 model 参数`},400);if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`},400);let i;try{i=await f({model:r,api_base:t.api_base,api_key:t.api_key,protocol:t.protocol,autoV1:t.autoV1})}catch(e){i={status:`error`,message:u(e.message),latency:0}}return n.set(r,{...i,time:new Date().toISOString()}),e.json(i)}catch(t){return e.json({status:`error`,message:u(t.message)})}}),t.post(`/proxy`,async e=>{try{let t=(await e.req.json()).model;if(!t)return e.json({status:`error`,message:`缺少 model 参数`},400);let r=await m(t,p(t));return n.set(t,{...r,time:new Date().toISOString()}),e.json(r)}catch(t){return e.json({status:`error`,message:u(t.message)})}}),t}var jp=Tu(`latency_probes`,{id:U().primaryKey({autoIncrement:!0}),model:H().notNull(),time:U().notNull(),latency_ms:U().notNull(),ok:U().notNull(),error:H()},[wu(`idx_latency_probes_model_time`).on(`model`,`time`),wu(`idx_latency_probes_time`).on(`time`)]),Mp=2592e6,Np=null;function Pp(){let e=Np;if(e!==null)return e;let t=sd(`latency`);return t.createTables([jp]),Np=t,t}function Fp(){return Pp().native}function Ip(e){if(e.length!==0)try{Pp().insert(jp).values(e.map(e=>({model:e.model,time:e.time,latency_ms:e.latencyMs,ok:+!!e.ok,error:e.error??null}))).run()}catch(e){A(`[latency] 探测记录写入失败:`,e instanceof Error?e.message:String(e))}}function Lp(){let e=Date.now()-Mp;return Pp().select(jp).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(G.gt(jp.time,e)).orderBy(G.asc(jp.time)).all().map(e=>({model:e.model,time:Number(e.time),latencyMs:Number(e.latency_ms),ok:e.ok===1,error:e.error??void 0}))}function Rp(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=Pp().select(jp).columns([`time`,`latency_ms`,`ok`]).where(G.and(G.eq(jp.model,e),G.gt(jp.time,a),G.lte(jp.time,r))).all();if(o.length===0)return[];let s=e=>{let n=new Date(e);return t===`hour`?new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()).getTime():new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime()},c=[];for(let e=s(r);e>=s(a);e-=i)c.unshift(e);let l=new Map;for(let e of c)l.set(e,{total:0,success:0,latencySum:0});for(let e of o){let t=l.get(s(Number(e.time)));t&&(t.total+=1,e.ok===1&&(t.success+=1,t.latencySum+=Number(e.latency_ms)))}return c.map(e=>{let t=l.get(e);return{bucketStart:e,total:t.total,success:t.success,failed:t.total-t.success,successRate:t.total===0?null:Math.round(t.success/t.total*1e3)/10,avgLatencyMs:t.success===0?null:Math.round(t.latencySum/t.success)}})}function zp(){let e=Pp().select(jp).columns({t:G.max(jp.time)}).get();return e?.t==null?null:Number(e.t)}function Bp(e){try{let t=Date.now()-e;Pp().delete(jp).where(G.lte(jp.time,t)).run()}catch(e){A(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var Vp=3e4,Hp=4,Up=!1;function Wp(){return Up}function Gp(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function Kp(e){let t=async e=>{let t=Ep((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?Dp(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:Tp}],max_tokens:1,stream:!0}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:Tp,max_output_tokens:16,stream:!0}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:Tp}],max_tokens:1,stream:!0});let a=Date.now();try{let t=await fetch(r,{method:`POST`,headers:n,body:JSON.stringify(i),signal:AbortSignal.timeout(Vp)});if(!t.ok){let n=await t.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,120)).catch(()=>``);return{model:e.name,time:a,latencyMs:0,ok:!1,error:n?`HTTP ${String(t.status)}: ${n}`:`HTTP ${String(t.status)}`}}let o=await kp(t,a);return o.streamed&&o.payload===null?{model:e.name,time:a,latencyMs:0,ok:!1,error:`HTTP ${String(t.status)}: 流式响应未收到数据帧`}:{model:e.name,time:a,latencyMs:o.latencyMs,ok:!0}}catch(t){return{model:e.name,time:a,latencyMs:0,ok:!1,error:t.message}}},n=async e=>{let n=[],r=0,i=Array.from({length:Math.max(1,Math.min(Hp,e.length))},async()=>{for(;;){let i=r++;if(i>=e.length)return;n.push(await t(e[i]))}});return await Promise.all(i),n};if(Up)return!1;Up=!0;try{let t=await n(Gp(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));Ip(t),Bp(Mp);let r=t.filter(e=>e.ok).length;return O(`[latency] 测试完成: ${String(t.length)} 个模型(成功 ${String(r)}),数据已入库 latency.db`),!0}catch(e){return A(`[latency] 测试执行失败:`,e instanceof Error?e.message:String(e)),!0}finally{Up=!1}}function qp(e){return Gp(e).length}var Jp=[{key:`avg10m`,ms:6e5},{key:`avg30m`,ms:18e5},{key:`avg1h`,ms:36e5},{key:`avg2h`,ms:72e5},{key:`avg5h`,ms:18e6},{key:`avg8h`,ms:288e5},{key:`avg12h`,ms:432e5},{key:`avg24h`,ms:864e5}];function Yp(e,t,n){return n.map(n=>{let r=e.filter(e=>e.model===n),i={model:n,avg10m:null,avg30m:null,avg1h:null,avg2h:null,avg5h:null,avg8h:null,avg12h:null,avg24h:null,lastTestAt:null,lastOk:null,lastLatencyMs:null,lastError:null},a=r.reduce((e,t)=>e===null||t.time>e.time?t:e,null);a!==null&&(i.lastTestAt=a.time,i.lastOk=a.ok,a.ok&&(i.lastLatencyMs=a.latencyMs),a.ok||(i.lastError=a.error??null));for(let{key:e,ms:n}of Jp){let a=r.filter(e=>e.ok&&e.time>t-n&&e.time<=t);a.length!==0&&(i[e]=Math.round(a.reduce((e,t)=>e+t.latencyMs,0)/a.length))}return i})}function Xp(e){let t=new M;return t.get(`/history`,t=>{let n=Lp(),r=Date.now();return t.json({running:Wp(),lastRunAt:zp(),models:Yp(n,r,e.current.expanded.deployments.names)})}),t.get(`/trend`,e=>{let t=e.req.query(`model`);if(!t)return e.json({ok:!1,error:`缺少 model 参数`},400);let n=e.req.query(`granularity`)===`day`?`day`:`hour`,r=Rp(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>Wp()?t.json({ok:!1,error:`测试进行中,请稍候`},409):qp(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(Kp(e),t.json({ok:!0,running:!0}))),t}function Zp(){let e=t=>{let n=0;if(!p(t))return 0;for(let r of _(t)){let i=c(t,r),a;try{a=x(i)}catch{continue}a.isDirectory()?n+=e(i):n+=a.size}return n},t=()=>Math.round(e(xt())/1024/1024*10)/10,n=new M;return n.onError(yp),n.get(`/`,bp(e=>{let n=e.req.query(),r=rf({startDate:n.startDate,endDate:n.endDate,model:n.model});return e.json({...r,logStorageMB:t()})})),n}function Y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Qp(e){return typeof e==`string`?e:null}function $p(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function em(e,t){let n=$p(e,t);return n===void 0?void 0:e[n]}function tm(e,t){if(e===void 0)return null;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e!==-1&&n.slice(0,e).trim()===t)return n.slice(e+1).trim()}return null}function nm(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function rm(e){let t=(e,t)=>{let n=e[t];if(n!==`"`&&n!==`'`&&n!=="`")return null;let r=t+1,i=``;for(;r<e.length;){let t=e[r];if(t===`\\`){i+=e[r+1]??``,r+=2;continue}if(t===n)return{value:i,end:r+1};i+=t,r+=1}return null},n=(e,n)=>{let r=(e,t)=>{let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;return n},i=(e,n)=>{if(e[n]!==`{`)return null;let r=0,i=n;for(;i<e.length;){let a=e[i];if(a===`"`||a===`'`||a==="`"){let n=t(e,i);if(n===null)return null;i=n.end;continue}if(a===`{`)r+=1;else if(a===`}`&&(--r,r===0))return{raw:e.slice(n,i+1),end:i+1};i+=1}return null},a=e=>{let n=e=>{let n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`||i===`'`||i==="`"){let i=t(e,r);if(i===null){n+=e.slice(r);break}n+=e.slice(r,i.end),r=i.end;continue}if(i===`,`){let t=r+1;for(;t<e.length&&/\s/.test(e[t]);)t+=1;let n=e[t];if(n===`}`||n===`]`){r+=1;continue}}n+=i,r+=1}return n},r;try{r=JSON.parse(n(e))}catch{return null}let i=Y(r);if(i===null)return null;let a={},o=Y(i.headers);if(o!==null)for(let[e,t]of Object.entries(o))typeof t==`string`&&(a[e]=t);return{method:typeof i.method==`string`?i.method.toUpperCase():`GET`,headers:a,body:typeof i.body==`string`?i.body:null}},o=r(e,n),s=t(e,o);if(s===null)return null;let c=s.value,l=r(e,s.end);if(e[l]!==`,`)return{url:c,method:`GET`,headers:{},body:null};let u=i(e,r(e,l+1));if(u===null)return{url:c,method:`GET`,headers:{},body:null};let d=a(u.raw);if(d===null)throw Error(`无法解析 fetch 的 options 对象(可能复制不完整,请重新复制完整的 fetch 调用)`);return{url:c,method:d.method,headers:d.headers,body:d.body}},r=e=>{let t=new Map;for(let n of e){let e=$p(n.headers,`cookie`);if(e===void 0)continue;let r=nm(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if($p(e.headers,`cookie`)!==void 0)return e;let n=nm(e.url),r=n===``?void 0:t.get(n);return r===void 0?e:{...e,headers:{...e.headers,[r.key]:r.value}}})},i=[],a=/\bfetch\s*\(/g,o;for(;(o=a.exec(e))!==null;){let t=n(e,o.index+o[0].length);t!==null&&i.push(t)}return r(i)}function im(e){return e.some(e=>$p(e.headers,`cookie`)!==void 0)}var am=0xe8d4a51000,om=3e4;async function sm(e,t){let n=e=>{let t={...e};for(let e of Object.keys(t)){let n=e.toLowerCase();(n===`content-length`||n===`host`||n===`connection`)&&delete t[e]}return t},r=await fetch(e,{...t,headers:n(t.headers),signal:AbortSignal.timeout(om)});if(!r.ok){let e=await r.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(r.status)}${e===``?``:`: ${e}`}`)}let i=Y(await r.json());if(i===null)throw Error(`响应不是 JSON 对象`);return i}function cm(e){return e===null||e<=0?null:Math.round(e<am?e*1e3:e)}function lm(e){return Math.round(e*100)/100}function um(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function dm(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function fm(e,t){let n=Y(e);if(n===null)return null;let r=X(n[t.used])??0,i=X(n[t.cap]),a=t.exceeded!==void 0&&n[t.exceeded]===!0||i!==null&&r>=i;return{used:r,cap:i,resetAt:t.resetAt===void 0?null:cm(X(n[t.resetAt])),exceeded:a}}var pm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await sm(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await sm(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},mm=`https://api.commandcode.ai`,hm=`/alpha/billing/credits`,gm=`/alpha/usage/summary`,_m=`/alpha/billing/subscriptions`,vm={"individual-pro-v1":80,"individual-goat":70},ym=/^user_[A-Za-z0-9_-]+$/,bm={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function xm(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:um(t)}]}function Sm(e){let t=Qp(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var Cm=class extends pm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=ym;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!ym.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(mm,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(gm),this.get(hm),this.get(_m).catch(()=>null)]),r=Y(t.windowLimits),i=Y(t.credits),a=n===null?null:Y(n.data),o=a===null?null:Qp(a.planId),s=o===null?null:vm[o]??null,c=i===null?null:X(i.monthlyCredits),l=s===null||c===null?null:{used:lm(Math.max(0,s-c)),cap:s,resetAt:a===null?null:Sm(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:fm(r.fiveHour,bm),weekly:r===null?null:fm(r.weekly,bm),monthly:l,totalTokens:X(e.totalTokens),totalRuns:X(e.totalCount),voucherBalance:null,balance:null,extraStats:xm(l,c)}}},wm=`https://api.deepseek.com`,Tm=`/user/balance`,Em=`余额不足,无法调用 API`;function Dm(e){let t=X(e);if(t!==null)return t;let n=Qp(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function Om(e){return e===`CNY`?`元`:e===`USD`?`美元`:e}function km(e){let t=[];if(!Array.isArray(e))return t;let n=new Set;for(let r of e){let e=Y(r);if(e===null)continue;let i=Qp(e.currency);if(i===null||i.trim()===``)continue;let a=i.trim();if(n.has(a))continue;let o=Dm(e.total_balance);o!==null&&(n.add(a),t.push({currency:a,total:o,granted:Dm(e.granted_balance),toppedUp:Dm(e.topped_up_balance)}))}return t}function Am(e){return e.length===0?null:e.length===1?e[0]:e.find(e=>e.currency===`CNY`)??[...e].sort((e,t)=>e.currency.localeCompare(t.currency))[0]}var jm=class extends pm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static apiHosts=[`api.deepseek.com`];static credentialSource=`apiKey`;constructor(e){super(wm,{authorization:`Bearer ${e}`,accept:`application/json`})}async fetchQuota(){let e=await this.get(Tm),t=Am(km(e.balance_infos));if(t===null)throw Error(`上游未返回余额数据(响应缺少 balance_infos,或各行的 total_balance 不可解析)`);let n=Om(t.currency),r=[];return t.toppedUp!==null&&r.push({label:`充值余额`,value:`${um(lm(t.toppedUp))} ${n}`}),t.granted!==null&&r.push({label:`赠送余额`,value:`${um(lm(t.granted))} ${n}`}),e.is_available===!1&&r.push({label:`账户状态`,value:Em}),{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:lm(t.total),extraStats:r.length===0?null:r}}},Mm=[`127.0.0.1`,`localhost`,`[::1]`],Nm=/^\/p\/([^/]+)(?:\/v1)?\/?$/;function Pm(e){let t;try{t=new URL(e)}catch{return null}if(!Mm.some(e=>e===t.hostname.toLowerCase()))return null;let n=Nm.exec(t.pathname);if(n===null)return null;let r;try{r=decodeURIComponent(n[1])}catch{return null}return r.trim()===``?null:{origin:t.origin,providerId:r}}function Fm(e){let t=[];if(!Array.isArray(e))return t;for(let n of e){let e=Y(n);if(e===null)continue;let r=Qp(e.name),i=Qp(e.display);r!==null&&r.trim()!==``&&i!==null&&i.trim()!==``&&t.push({name:r,usedPercent:X(e.used)??0,display:i,amount:X(e.amount),limit:X(e.limit),unit:Qp(e.unit)})}return t}var Im=class{static vendorId=`pluginHost`;static vendorLabel=`插件(OpenCode 插件宿主)`;static credentialSource=`pluginHost`;static matchMode=`loopbackPath`;static pathPrefix=`/p/`;static apiHosts=Mm;#e;#t;constructor(e){let t=Pm(e);if(t===null)throw Error(`不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径):${e}`);this.#e=t.origin,this.#t=t.providerId}async fetchQuota(){let e=await sm(`${this.#e}/p/${encodeURIComponent(this.#t)}/usage`,{method:`GET`,headers:{accept:`application/json`}}),t=Qp(e.error);if(t!==null&&t.trim()!==``)throw Error(t);let n=Qp(e.plan);return{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:null,windows:Fm(e.windows),...n!==null&&n.trim()!==``?{extraStats:[{label:`套餐`,value:n}]}:{}}}},Lm=`/api/user/self`,Rm=`/api/user/subscription/current_cycle`,zm={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function Bm(e,t){let n=e.usage_infos;if(!Array.isArray(n))return null;for(let e of n){let n=Y(e);if(n!==null&&n.key===t)return n}return null}function Vm(e){return e===null||X(e.total_count)===null?null:fm(e,zm)}function Hm(e){let t=Y(e.account_info),n=t===null?null:t.vouchers;if(!Array.isArray(n))return null;let r=0,i=!1;for(let e of n){let t=Y(e),n=t===null?null:X(t.available);n!==null&&(r+=n,i=!0)}return i?r/1e6:null}function Um(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var Wm=class extends pm{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=rm(e),n=Um(t,Lm),r=Um(t,Rm);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>em(e.headers,`authorization`)!==void 0))throw Error(`复制的请求里没有 authorization 头(登录凭据在它里面)——请从已登录的 senseaudio.cn 页面重新复制 fetch 调用`);let i=n??r;super(new URL(i.url).origin,i.headers)}async fetchQuota(){let[e,t]=await Promise.all([this.get(Lm),this.get(Rm).catch(()=>null)]),n=Vm(Bm(e,`credit_5h_limit`)),r=Vm(Bm(e,`credit_7d_limit`)),i=Vm(Bm(e,`credit_30d_limit`));if(i===null&&t!==null){let e=X(t.plan_points),n=X(t.plan_point_remains);e!==null&&n!==null&&(i={used:e-n,cap:e,resetAt:cm(X(t.plan_points_reset_at)),exceeded:e-n>=e})}if(n===null&&r===null&&i===null)throw Error(`上游未返回任何额度窗口(该账号可能尚未登录或未订阅套餐)`);return{fiveHour:n,weekly:r,monthly:i,totalTokens:null,totalRuns:null,voucherBalance:Hm(e),balance:null}}},Gm=`GetAgentPlanAFPUsage`,Km=`GetAgentPlanUsageDetails`,qm=`console.volcengine.com`,Jm=`2024-01-01`,Ym=`cn-beijing`,Xm={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function Zm(e){return e.find(e=>e.url.includes(Gm))}function Qm(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??Ym}/${Jm}`:t}function $m(e){return e.find(e=>nm(e.url)===qm)}var eh=class extends pm{static vendorId=`volc-ark`;static vendorLabel=`火山方舟`;static hosts=[`console.volcengine.com`];static apiHosts=[`ark.cn-beijing.volces.com`];static credentialSource=`fetchText`;#e;#t;constructor(e){let t=rm(e),n=Zm(t)??$m(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!im(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==qm)throw Error(`非方舟控制台域`);r=e.origin,i=Qm(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=tm(em(n.headers,`cookie`),`csrfToken`)??em(n.headers,`x-csrf-token`)??null;if(a===null)throw Error(`缺少 CSRF 凭据:请求头需含 x-csrf-token,或 Cookie 里需有 csrfToken (两者都来自已登录的控制台会话,请在登录页面上重新复制)`);super(r,{...n.headers,"x-csrf-token":a}),this.#e=`${i}/${Gm}`,this.#t=`${i}/${Km}`}envelope(e){let t=Y(e.ResponseMetadata),n=t===null?null:Y(t.Error);if(n!==null){let e=Qp(n.Code)??`Unknown`,t=Qp(n.Message)??``;throw Error(`上游业务错误 ${e}${t===``?``:`: ${t}`}(多为 Cookie 或 CSRF 凭据失效,请在控制台重新复制)`)}return e}async fetchQuota(){let e=Y((await this.post(this.#e,{})).Result);if(e===null)throw Error(`响应缺少 Result 字段`);let t=fm(e.AFPFiveHour,Xm),n=fm(e.AFPWeekly,Xm),r=fm(e.AFPMonthly,Xm);if(t===null&&n===null&&r===null)throw Error(`上游未返回任何 AFP 窗口(该账号可能尚未订阅 Agent Plan 套餐)`);let i=Y(e.AFPMonthly),a=i===null?null:X(i.SubscribeTime);return{fiveHour:t,weekly:n,monthly:r,totalTokens:await this.#n(a),totalRuns:null,voucherBalance:null,balance:null}}async#n(e){let t=Date.now(),n=e!==null&&e>0?e:t-2592e6;try{let e=Y((await this.post(this.#t,{Filter:{StartTime:dm(new Date(n)),EndTime:dm(new Date(t)),ObjectType:1,BillingType:[`WithinPlan`]},QueryInterval:`Day`})).Result),r=e===null?null:e.Details;return Array.isArray(r)?r.reduce((e,t)=>{let n=Y(t);return n===null||n.Unit!==`Tokens`?e:e+(X(n.Usage)??0)},0):null}catch{return null}}},th=`/api/biz/account/query-customer-account-report`,nh=`/api/finance/expenseBill/expenseBillListByDay`,rh=200,ih=`bigmodel_token_production`;function ah(e){let t=tm(em(e.headers,`cookie`),ih);if(t!==null&&t.trim()!==``)return t.trim();let n=em(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var oh=class extends pm{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=rm(e);if(t.length===0)throw Error(`未找到可用的智谱请求:请在已登录的 bigmodel.cn(财务中心 / 资源包 / 任意控制台页面)里复制任意请求的 fetch 调用粘贴进来,额度端点会自动换算`);let n=t[0],r;try{r=new URL(n.url).origin}catch{throw Error(`粘贴的请求 URL 不是绝对地址,无法换算出额度接口——请粘贴浏览器里完整的 fetch(https://…)`)}let i=ah(n);if(i===null)throw Error(`复制的请求里没有登录凭据(需要 Cookie 里的 bigmodel_token_production,或显式的 authorization 头)——请从已登录的 bigmodel.cn 页面用「以 fetch (Node.js) 格式复制」重新复制`);let a={...n.headers,authorization:i.toLowerCase().startsWith(`bearer `)?i:`Bearer ${i}`};super(r,a)}envelope(e){let t=X(e.code);if(t!==200){let n=Qp(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=dm(e).slice(0,7),n=dm(new Date(e.getFullYear(),e.getMonth(),e.getDate()-(e.getDay()+6)%7));try{let e=1,r=0,i=0,a=1/0,o=[];for(;o.length<a;){let s=await this.get(nh,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(rh)}`),c=s.rows,l=s.total;if(!Array.isArray(c))return null;a=X(l)??o.length,o=o.concat(c);for(let e of c){let t=Y(e);if(t===null)continue;let a=X(t.originalAmount),o=Qp(t.billingDate);a!==null&&o!==null&&(r+=a,o>=n&&(i+=a))}if(e+=1,c.length===0)break}return{weekly:{used:i,cap:null,resetAt:null,exceeded:!1},monthly:{used:r,cap:null,resetAt:null,exceeded:!1}}}catch{return null}}async fetchQuota(){let[e,t]=await Promise.all([this.get(th),this.#e()]),n=Y(e.data),r=(n===null?null:X(n.availableBalance))??(n===null?null:X(n.balance));if(n===null||r===null)throw Error(`响应缺少余额字段(data.availableBalance)`);let i=X(n.totalSpendAmount);return{fiveHour:null,weekly:t?.weekly??null,monthly:t?.monthly??null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:r,totalCost:i,totalCostCurrency:i===null?null:`CNY`,extraStats:sh(n)}}};function sh(e){let t=e=>`${um(e)} 元`,n=[],r=X(e.rechargeAmount);r!==null&&n.push({label:`累计充值`,value:t(r)});let i=X(e.giveAmount);i!==null&&n.push({label:`赠送金额`,value:t(i)});let a=X(e.creditBalance);return a===null?e.creditStatus===`NOT_OPEN`&&n.push({label:`信用余额`,value:`未开通`}):n.push({label:`信用余额`,value:t(a)}),n}var ch=[Cm,jm,Wm,eh,oh,Im];function lh(){return ch}function uh(e){if(e===void 0)return null;let t=nm(e);if(t===``)return null;for(let e of ch)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function dh(e,t){let n=uh(t);if(n===null)throw Error(`该供应商未支持用 API key 自动查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`该供应商的 apiKey 为空,无法查询额度——请在供应商配置里填入 API key`);if(n.apiKeyPattern?.test(r)===!1)throw Error(`配置里的 apiKey 不是 ${n.vendorLabel} 的 API key 形态——请检查该供应商配置的 apiKey 字段`);return{vendorId:n.vendorId,vendor:new n(r)}}function fh(e){return e===void 0||Pm(e)===null?null:Im}function ph(e){if(fh(e)===null)throw Error(`apiBase 不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径,如 http://127.0.0.1:29772/p/workbuddy):${e}`);return{vendorId:Im.vendorId,vendor:new Im(e)}}function mh(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of rm(e)){let e=nm(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of ch)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=nm(t);if(e!==``){for(let t of ch)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of ch)if(e.credentialSource===`fetchText`&&e.hosts?.some(e=>i.has(e))===!0)return e;return null};if(e.trim()===``)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);let r=n(e,t);if(r===null){let e=ch.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=ch.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=uh(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var hh=Ht(`quota.json`);function gh(e){let t=e=>{let t=e=>{let t=Y(e);if(t===null)return null;let n=t.used;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=t.cap,i=t.resetAt;return{used:n,cap:typeof r==`number`&&Number.isFinite(r)?r:null,resetAt:typeof i==`number`&&Number.isFinite(i)?i:null,exceeded:t.exceeded===!0}},n=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null},r=e=>{let t=Y(e);if(t===null)return null;let r=n(t.cost),i=n(t.requests);if(r===null&&i===null)return null;let a=t.currency;return{cost:r,currency:typeof a==`string`&&a!==``?a:null,requests:i}},i=e=>{if(!Array.isArray(e))return null;let t=[];for(let n of e){let e=Y(n);if(e===null)continue;let r=e.label,i=e.value;typeof r==`string`&&r!==``&&typeof i==`string`&&i!==``&&t.push({label:r,value:i})}return t.length>0?t:null},a=e=>{if(!Array.isArray(e))return null;let t=[];for(let r of e){let e=Y(r);if(e===null)continue;let i=e.name,a=e.display;if(typeof i!=`string`||i===``||typeof a!=`string`||a===``)continue;let o=e.usedPercent;t.push({name:i,usedPercent:typeof o==`number`&&Number.isFinite(o)?o:0,display:a,amount:n(e.amount),limit:n(e.limit),unit:typeof e.unit==`string`&&e.unit!==``?e.unit:null})}return t.length>0?t:null},o=Y(e);if(o===null)return null;let s=o.totalTokens,c=o.totalRuns,l=o.voucherBalance,u=o.balance,d=o.totalCost,f=o.totalCostCurrency;return{fiveHour:t(o.fiveHour),weekly:t(o.weekly),monthly:t(o.monthly),totalTokens:typeof s==`number`&&Number.isFinite(s)?s:null,totalRuns:typeof c==`number`&&Number.isFinite(c)?c:null,voucherBalance:typeof l==`number`&&Number.isFinite(l)?l:null,balance:typeof u==`number`&&Number.isFinite(u)?u:null,totalCost:n(d),totalCostCurrency:typeof f==`string`&&f!==``?f:null,today:r(o.today),yesterday:r(o.yesterday),extraStats:i(o.extraStats),windows:a(o.windows)}},n=Y(hh.get(e));if(n===null)return null;let r=n.fetchText,i=n.vendorId,a=n.fetchedAt,o=n.error;return{fetchText:typeof r==`string`&&r.trim()!==``?r:void 0,vendorId:typeof i==`string`?i:void 0,snapshot:t(n.snapshot)??void 0,fetchedAt:typeof a==`number`&&Number.isFinite(a)?a:void 0,error:typeof o==`string`&&o!==``?o:void 0}}function _h(e,t){hh.set(e,t)}function vh(e){hh.get(e)!==void 0&&hh.set(e,void 0)}function yh(){let e=hh.getAll(),t={};for(let n of Object.keys(e)){let e=gh(n);e!==null&&(t[n]=e)}return t}function bh(e,t,n,r){_h(e,{fetchText:gh(e)?.fetchText,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function xh(e,t){let n=gh(e);if(n===null){_h(e,{error:t});return}_h(e,{...n,error:t})}var Sh=!1;function Ch(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function wh(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function Th(){let e=e=>{let t=typeof e==`object`&&e?e:{},n=typeof t.apiBase==`string`&&t.apiBase.trim()!==``?t.apiBase:void 0,r=typeof t.apiKey==`string`&&t.apiKey.trim()!==``?t.apiKey:void 0;return{apiBase:n,apiKey:r===void 0?void 0:wh(r)}};try{let t=El();if(t===null||!Array.isArray(t.providers))return null;let n=new Map;for(let r of t.providers){let t=typeof r==`object`&&r?r.name:void 0;typeof t==`string`&&t!==``&&n.set(t,e(r))}return n}catch{return null}}function Eh(e){return Th()?.get(e)??null}async function Dh(e){try{let t=Eh(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(t.apiBase!==void 0&&fh(t.apiBase)!==null)({vendorId:n,vendor:r}=ph(t.apiBase));else if(uh(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=dh(t.apiKey,t.apiBase))}else{let i=gh(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=mh(i,t.apiBase))}let i=await r.fetchQuota();bh(e,n,i,Date.now())}catch(t){xh(e,Ch(t))}return gh(e)}async function Oh(){let e=()=>{let e=Th();return e===null?null:new Set(e.keys())};if(!Sh){Sh=!0;try{let t=Th(),n=[];for(let[e,r]of t??[])(uh(r.apiBase)!==null||fh(r.apiBase)!==null)&&n.push(e);for(let e of n)await Dh(e);let r=e();for(let[e,t]of Object.entries(yh()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){vh(e);continue}n.includes(e)||await Dh(e)}}catch(e){A(`[quota] 刷新失败:`,Ch(e))}finally{Sh=!1}}}function kh(){let e=async e=>{let t=(await pp(e))?.fetchText;return typeof t==`string`?t:null},t=()=>lh().map(e=>({vendorId:e.vendorId,vendorLabel:e.vendorLabel,hosts:e.hosts??[],apiHosts:e.apiHosts??[],credentialSource:e.credentialSource,...e.matchMode===void 0?{}:{matchMode:e.matchMode},...e.pathPrefix===void 0?{}:{pathPrefix:e.pathPrefix}})),n=new M;return n.get(`/`,e=>e.json({ok:!0,vendors:t(),providers:yh()})),n.get(`/vendors`,e=>e.json({ok:!0,vendors:t()})),n.put(`/:provider`,async t=>{let n=t.req.param(`provider`),r=Eh(n)?.apiBase;if(fh(r)!==null)return t.json({ok:!1,error:`该供应商的额度由插件服务查询,无需手动配置`},400);if(uh(r)!==null)return t.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);let i=await e(t);if(i===null)return t.json({ok:!1,error:`请求体需为 {"fetchText": "..."}`},400);let a=gh(n);_h(n,{fetchText:i,vendorId:a?.vendorId,snapshot:a?.snapshot,fetchedAt:a?.fetchedAt,error:void 0});let o=await Dh(n);return t.json({ok:!0,entry:o})}),n.delete(`/:provider`,e=>(vh(e.req.param(`provider`)),e.json({ok:!0}))),n.post(`/:provider/refresh`,async e=>{let t=await Dh(e.req.param(`provider`));return e.json({ok:!0,entry:t})}),n}function Ah(e){return e===`0.0.0.0`||e===`::`}function jh(e=T()){let t=[];for(let n of Object.values(e))for(let e of n??[])e.internal||e.family!==`IPv4`||t.includes(e.address)||t.push(e.address);return t}function Mh(e,t){let n=new M;return n.get(`/`,n=>n.json({listenPort:cp(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},...t&&Ah(t.hostname)?{lanAddresses:jh()}:{},masterKey:Fl()})),n}var Nh=864e5,Ph=3e5,Fh=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,Ih=new Map;try{let e=g(Ct(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;Ih.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function Lh(){let e=e=>({model:e.model,client:e.client,sessionId:e.sessionId,noSession:e.noSession===`1`||void 0,startDate:e.startDate||e.date,endDate:e.endDate||e.date,status:e.status,pathGroup:e.pathGroup,keyword:e.keyword}),t=e=>{let t=Ih.get(e);if(!t)return null;let n=t.value.error===void 0?Nh:Ph;return Date.now()-t.at>=n?(Ih.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of Ih)e[t]={...n,_ts:r};C(Ct(),JSON.stringify(e))}catch(e){A(`保存 IP 缓存失败:`,e.message)}},r=async e=>{let r=t(e);if(r)return r;let i=await(await fetch(Fh.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return Ih.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return Ih.set(e,{value:a,at:Date.now()}),n(),a},i=new M;return i.onError(yp),i.get(`/dates`,e=>{let t=af();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=of();return e.json({clients:t})}),i.get(`/ipinfo`,async e=>{let t=e.req.query(`ip`)||``;if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return e.json({error:`invalid ip`},400);try{let n=await r(t);return e.json({ip:t,...n})}catch(e){throw new vp(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=Kd(t);return n||=(await Cf(),Kd(t)??pu(Number(t))),n?e.json({...n,meta:{...n.meta,tps:Gf(n.meta)}}):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,bp(async t=>{let n=t.req.query(),r=nf({...e(n),sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize}),i=(n.keyword??``).trim();return i.length>=2&&r.total===0&&(r=uf({...e(n),keyword:i,sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize})),t.json({...r,items:r.items.map(e=>({...e,user_agent:eu(e.headers),tps:Gf(e)}))})})),i.get(`/sessions`,bp(t=>{let n=t.req.query(),r=cf({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,bp(async t=>{await Tf();let n=lu().length;n>0&&k(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=ff(e(r));return O(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}var Rh=3e4,zh=12e4,Bh=5242880,Vh=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`],Hh=[`host`,`content-length`,`connection`,`keep-alive`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`proxy-authorization`,`proxy-connection`];function Uh(e){let t=e.toLowerCase();return t===``||t.startsWith(`text/`)||t.startsWith(`application/json`)||t.endsWith(`+json`)||t.startsWith(`application/xml`)||t.endsWith(`+xml`)||t.startsWith(`application/javascript`)||t.startsWith(`application/x-www-form-urlencoded`)||t.startsWith(`application/x-ndjson`)||t.startsWith(`application/graphql`)}function Wh(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(Hh.includes(n.toLowerCase())||(t[n]=r));return t}function Gh(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?Rh:Math.min(Math.floor(e),zh)}function Kh(e){if(typeof e!=`string`||e.trim()===``)throw new vp(400,`缺少 url(要转发的目标地址)`);let t=e.trim(),n=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t)?t:`https://${t}`,r;try{r=new URL(n)}catch{throw new vp(400,`不是合法的 URL:${t}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw new vp(400,`只支持 http/https 协议(收到 ${r.protocol})`);return r.toString()}function qh(e){if(e!=null)return typeof e==`string`?e:JSON.stringify(e)}async function Jh(e){let t=e.body;if(t===null)return{text:``,truncated:!1};let n=t.getReader(),r=[],i=0,a=!1;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;if(t===void 0)continue;let o=Bh-i;if(t.byteLength>=o){r.push(t.subarray(0,o)),i+=o,a=!0;break}r.push(t),i+=t.byteLength}}finally{await n.cancel().catch(()=>void 0)}let o=new Uint8Array(i),s=0;for(let e of r)o.set(e,s),s+=e.byteLength;return{text:new TextDecoder(`utf-8`).decode(o),truncated:a}}function Yh(e){let t={};return e.headers.forEach((e,n)=>{n.toLowerCase()!==`set-cookie`&&(t[n]=e)}),t}async function Xh(e){let{url:t,method:n,headers:r,body:i,timeoutMs:a}=e,o=i!==void 0&&n!==`GET`&&n!==`HEAD`,s=Date.now(),c;try{c=await fetch(t,{method:n,headers:r,...o?{body:i}:{},signal:AbortSignal.timeout(a),redirect:`follow`})}catch(e){let n=e instanceof Error?e.message:String(e);throw new vp(502,e instanceof Error&&e.name===`TimeoutError`?`上游超时(${String(a)}ms):${t}`:`上游请求失败:${n}`)}let l=c.headers.get(`content-type`)??``,u=Uh(l),{text:d,truncated:f}=u?await Jh(c):{text:``,truncated:!1};return Response.json({ok:!0,url:t,finalUrl:c.url,status:c.status,statusText:c.statusText,headers:Yh(c),contentType:l,body:u?d:null,binary:!u,truncated:f,elapsedMs:Date.now()-s})}function Zh(){let e=new M;return e.onError(yp),e.post(`/`,async e=>{let t=await pp(e);if(t===null)throw new vp(400,`请求体不是合法 JSON 对象`);let n=typeof t.method==`string`?t.method.toUpperCase():`GET`;if(!Vh.includes(n))throw new vp(400,`不支持的请求方法:${n}(可用 ${Vh.join(` / `)})`);return await Xh({url:Kh(t.url),method:n,headers:Wh(t.headers),body:qh(t.body),timeoutMs:Gh(t.timeoutMs)})}),e.get(`/`,async e=>{let t=e.req.query();return await Xh({url:Kh(t.url),method:`GET`,headers:Wh(void 0),body:void 0,timeoutMs:Gh(t.timeoutMs===void 0?void 0:Number(t.timeoutMs))})}),e}function Qh(e){return`http://127.0.0.1:${String(e.port)}`}var $h=`daemon.json`;function eg(e){let t=e=>{let t=e.port??null;return{role:`main`,pid:e.pid??null,status:e.status??`stopped`,port:t,address:t?`http://127.0.0.1:${String(t)}`:null,startedAt:e.startedAt??null,restarts:null}},n=e=>{try{let t=JSON.parse(g(c(e,$h),`utf-8`))?.children;if(typeof t!=`object`||!t)return null;for(let e of Object.values(t)){let t=e;if(t?.pid===process.pid)return typeof t.startedAt==`number`?{pid:t.pid,startedAt:t.startedAt}:null}return null}catch{return null}},r=new M;return r.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:Qh(e)})),r.get(`/processes`,r=>{let i=n(e.appDir);return r.json({ok:!0,processes:[t({pid:i?.pid??process.pid,status:`online`,port:e.port,startedAt:i?.startedAt??e.startedAt})]})}),r}var tg=`ezllm-autostart.vbs`,ng=`ezllm-autostart.cmd`,rg=`com.ezllm.autostart`,ig=`ezllm.service`,ag=`autostart.opt-out`,og=`ezllm-v2`,sg=`Auto-generated by "npx ezllm install" (${og}). Disable in the ezllm admin UI (Settings → startup) or by running \`npx ezllm uninstall\`.`,cg=`ELLM_`,lg=new Set([`WEBUI_USERNAME`,`WEBUI_PASSWORD`,`HOST`]),ug=new Set([`ELLM_PORT`,`ELLM_NODE_MIRROR`,`ELLM_NODE_BIN`]);function dg(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(ug.has(n)||(n.startsWith(cg)||lg.has(n))&&(t[n]=r));return t}function fg(e){return c(e,ag)}function pg(){return c((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return c(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),tg)}function mg(){return c(w(),`Library`,`LaunchAgents`,`${rg}.plist`)}function hg(){return c(w(),`.config`,`systemd`,`user`,ig)}var gg=3e4;function _g(e,t){return new Promise(n=>{let r=he(e,t,{stdio:`ignore`,shell:!1}),i=setTimeout(()=>{r.kill(),n(124)},gg),a=e=>{clearTimeout(i),n(e)};r.on(`error`,()=>a(127)),r.on(`exit`,e=>a(e??1))})}var vg={win32:{itemPath:pg,on:wg,off:Dg},darwin:{itemPath:mg,on:Tg,off:Og},linux:{itemPath:hg,on:Eg,off:kg}};function yg(e){return vg[e]??null}function bg(e){let t=yg(e);if(!t)throw Error(`暂不支持的平台: ${e}。`);return t}function xg(e,t){return[e,t.entryJs,...t.args??[]]}function Sg(e){return c(e,`logs`,`autostart.log`)}async function Cg(e,t,n=_g){try{C(e,t,`utf16le`);return}catch(r){if(await n(`powershell`,[`-NoProfile`,`-Command`,`$bytes=[Convert]::FromBase64String('${Buffer.from(t,`utf16le`).toString(`base64`)}');[IO.File]::WriteAllBytes('${e.replace(/'/g,`''`)}', $bytes)`])!==0)throw r}}async function wg(e,t){let n=(e,t)=>{let n=/["%\r\n]/;if(n.test(e)||n.test(t))throw Error(`环境变量 ${e} 的键/值含 cmd 无法安全转义的字符(" % 或换行),已拒绝写入自启项;请调整该变量后重试 npx ezllm install`)},r=(e,t)=>{let r=Sg(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${sg}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${xg(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
|
|
85
|
-
`)},i=e=>[`' ${
|
|
86
|
-
`),a=
|
|
87
|
-
`),a=
|
|
88
|
-
`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<!-- ${
|
|
89
|
-
`)},i=
|
|
90
|
-
`),r=
|
|
91
|
-
`)},r=
|
|
92
|
-
`,`utf-8`)}function
|
|
93
|
-
`,`utf-8`),!0)}var
|
|
83
|
+
LIMIT ${op}
|
|
84
|
+
`);if(o.length===0)break;let s=[];for(let e of o){a=Number(e.id),i.scanned++;let o=t(e.headers);o!==``&&(s.push({id:Number(e.id),sessionId:o}),i.filled++,s.length>=sp&&(n(r,s),s.length=0))}n(r,s),e.onProgress?.(`已扫描到 id ${String(a)}:写入 ${String(i.filled)} 行(累计)`)}return i}async function lp(e){let t=()=>{for(let e of Dt())if(p(e))return e;return null},n=(e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=n.default??n[`module.exports`]??n;if(typeof r!=`object`||!r)return null;let i=r;return typeof i.onModelRequest==`function`?{onModelRequest:i.onModelRequest}:(k(`[ezllm] ${t} 未导出 onModelRequest 函数,已忽略(不挂任何钩子)`),null)},r=t();if(r===null)return;let i;try{i=await import(te(r).href)}catch(e){A(`[ezllm] 加载用户钩子失败,本次按无钩子运行:${r}`),A(`[ezllm] 原因:${e instanceof Error?e.message:String(e)}`),A(`[ezllm] 提示:模块写法与文件扩展名不匹配。CJS 内容(module.exports)请用 hook.cjs,ESM 内容(export default)请用 hook.mjs——这两个扩展名强制解析模式,不受任何 package.json 的 type 影响`);return}let a=n(i,r);a?.onModelRequest!==void 0&&(e.addHook(`onModelRequest`,a.onModelRequest),O(`[ezllm] 已加载用户钩子:${r}(onModelRequest)`))}function up(e){return pt.port??e.port}async function dp(e,t,n={}){let r=new Sl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Td())}});t.register(r),await lp(r);let i={current:r,port:r.expanded.port,rebuild(e){i.current.reload(e),i.port=i.current.expanded.port;let t=i.current.expanded.deployments.names.length,n=e.providers.filter(e=>e.enabled===!1).length,r=n>0?`(${String(n)} 个已停用)`:``;O(`[gateway] 配置已热更新: ${String(e.providers.length)} 个供应商${r} / ${String(t)} 个模型`)},proxy:new M},a=async e=>{let t=new URL(e.req.url),n=new Headers(e.req.raw.headers);if(!n.has(`x-forwarded-for`)){let t=e.env?.incoming?.socket?.remoteAddress??``;t!==``&&n.set(`x-forwarded-for`,t)}if(!n.has(`authorization`)&&n.has(`x-api-key`)){let e=n.get(`x-api-key`)??``;e!==``&&n.set(`authorization`,`Bearer ${e}`)}return i.current.build().fetch(new Request(t.toString(),{method:e.req.raw.method,headers:n,body:e.req.raw.body,duplex:`half`}))};return i.proxy.use(`/v1/models`,async(e,n)=>{let r=e.req.header(`authorization`)??(e.req.header(`x-api-key`)===null?``:`Bearer ${e.req.header(`x-api-key`)}`);if(!await t.authorize(r))return Response.json({error:{message:`Unauthorized: invalid api key`,type:`authentication_error`,code:`401`}},{status:401});await n()}),i.proxy.all(`/v1/*`,e=>a(e)),i.proxy.all(`/v1`,e=>a(e)),i.proxy.all(`/responses`,e=>a(e)),i.proxy.all(`/chat/completions`,e=>a(e)),i.proxy.all(`/messages`,e=>a(e)),i.proxy.all(`/messages/count_tokens`,e=>a(e)),i.proxy.all(`/models`,e=>a(e)),i.proxy.all(`/healthz`,e=>a(e)),i}var fp=64;function pp(e,t={}){let n=e=>e.trim(),r=new Map;function i(e,t){for(r.delete(e),r.set(e,t);r.size>fp;){let e=r.keys().next().value;if(e===void 0)break;r.delete(e)}}function a(){return new Set(t.knownModelNames?t.knownModelNames():e.expanded.deployments.names)}e.plugin(e=>{e.addHook(`onFinish`,e=>{if(e.status!==200||e.ctx.model===null)return;let t=n(e.ctx.userAgent);t!==``&&i(t,e.ctx.model.name)}),e.addHook(`onModelNotFound`,t=>{if(a().has(t.requestedModel))return;let i=n(t.userAgent);if(i===``)return;let o=r.get(i);if(o!==void 0){if(!e.expanded.deployments.byName.has(o)){r.delete(i);return}return o}})})}var mp=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function(e,o){function s(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&s(`Access-Control-Allow-Origin`,c),t.credentials&&s(`Access-Control-Allow-Credentials`,`true`),n&&s(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&s(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&s(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(s(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await o(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};async function hp(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var gp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,_p=new M;function vp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}_p.post(`/login`,async e=>{let t=Rl();if(t.configBroken)return e.json({error:gp},503);if(!t.required)return e.json({error:`当前未设置登录账号,管理台免登录访问(如需启用请先设置账号)`},400);let n=await hp(e);if(n===null)return e.json({error:`请求体格式错误`},400);let{username:r,password:i}=n;return(r??``).trim()!==t.username||i!==t.password?e.json({error:`用户名或密码错误`},401):e.json({token:vp(t)})});async function yp(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=Rl();if(!n.required)return await t();if(n.configBroken)return e.json({error:gp},401);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==vp(n))return e.json({error:`token 无效或已过期`},401);await t()}var bp=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function xp(e,t){return e instanceof bp?(e.status>=500&&A(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e.message),t.json({error:e.message},e.status)):(A(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e instanceof Error?e.message:e),t.json({ok:!1,error:e instanceof Error?e.message:String(e)},500))}function Sp(e){return async t=>{try{return await e(t)}catch(e){throw new bp(500,e.message)}}}var Cp=8,wp=6;function Tp(){let e=()=>{let e=El();if(e===null)throw new bp(500,`配置文件不存在`);return e},t=new M;return t.onError(xp),t.use(`*`,async(e,t)=>{if(e.req.method===`GET`)return t();let n=e.req.header(`sec-fetch-site`);if(n===`same-origin`||n===`none`)return t();let r=e.req.header(`origin`);return r===void 0||r.toLowerCase()===new URL(e.req.url).origin.toLowerCase()?t():e.json({error:`已拒绝跨站写请求`},403)}),t.get(`/status`,e=>{let t=zl(),n=!1;try{n=Fl()!==``}catch(e){if(!(e instanceof Tl))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:Rl().required,version:Lt(),buildSource:vt()})}),t.post(`/master-key`,async t=>{if(zl().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await hp(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r;if(n.mode===`generate`)r=re(32).toString(`base64url`);else if(n.mode===`custom`){if(r=(n.masterKey??``).trim(),r.length<Cp)return t.json({error:`主密钥至少 ${String(Cp)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return Ol(a),t.json({masterKey:r,...Hl(i,a)?{restartHint:Nl}:{}})}),t.post(`/finish`,async t=>{if(zl().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await hp(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r=n.deployment;if(r!==`local`&&r!==`server`)return t.json({error:`deployment 必须是 local 或 server`},400);let i=(n.masterKey??``).trim();if(i!==``&&i.length<Cp)return t.json({error:`主密钥至少 ${String(Cp)} 位`},400);if(r===`server`&&i===``&&Fl()===``)return t.json({error:`服务器部署必须设置主密钥,防止 /v1 网关被他人盗用`},400);let a=(n.username??``).trim(),o=n.password??``,s=a!==``||o!==``;if(s){if(a===``||o===``)return t.json({error:`用户名和密码需同时提供`},400);if(o.length<wp)return t.json({error:`密码至少 ${String(wp)} 位`},400)}else if(r===`server`)return t.json({error:`服务器部署必须设置登录账号密码,防止管理台被陌生人登录`},400);let c=e(),l={...c,...i===``?{}:{masterKey:i},setup:{completed:!0,deployment:r},allowLan:r===`server`,...s?{"web-ui":{...c[`web-ui`],"login-account":{username:a,password:o}}}:{}};return Ol(l),t.json({message:s?`初始化完成,请使用新账号登录`:`初始化完成`,...Hl(c,l)?{restartHint:Nl}:{}})}),t}function Ep(e){let t=new M;return t.onError(xp),t.get(`/`,Sp(e=>{let t=El();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,Sp(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);try{Al(n)}catch(e){if(e instanceof lr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let r=null;try{r=El()}catch{r=null}return Ol(n),e.runtime.rebuild(kl(n)),t.json({message:`配置已保存并生效`,...Hl(r,n)?{restartHint:Nl}:{}})})),t}var Dp=`直接回复我 ok,不要思考不要解释`;function Op(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function kp(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function Ap(e){for(let t of e.split(/\r?\n/)){if(!t.startsWith(`data:`))continue;let e=t.slice(5).trim();if(e!==``&&e!==`[DONE]`)try{let t=JSON.parse(e);if(typeof t==`object`&&t&&!Array.isArray(t))return t}catch{}}return null}async function jp(e,t){if(!(e.headers.get(`content-type`)??``).toLowerCase().includes(`text/event-stream`)){let n=await e.text().catch(()=>``),r=null;try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(r=e)}catch{}return{streamed:!1,latencyMs:Date.now()-t,payload:r}}let n=e.body?.getReader();if(n===void 0)return{streamed:!0,latencyMs:Date.now()-t,payload:null};let r=new TextDecoder,i=``;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;a!==void 0&&(i+=r.decode(a,{stream:!0}));let o=Ap(i);if(o!==null)return{streamed:!0,latencyMs:Date.now()-t,payload:o}}}finally{await n.cancel().catch(()=>void 0)}return{streamed:!0,latencyMs:Date.now()-t,payload:null}}function Mp(e){let t=new M;t.onError(xp);let n=Ht(`test-results.json`),r=Ht(`models-cache.json`);function i(e,t=`openai`,n=!0){let r=e.replace(/\/+$/,``);return t===`anthropic`&&r.endsWith(`/anthropic`)&&(r=r.slice(0,-10)),`${Op(r,n)}/models`}function a(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();if(e.includes(`authorization`)||e.includes(`api-key`)||e.includes(`token`)){let e=String(r);t[n]=e.length>8?`${e.slice(0,3)}****${e.slice(-4)}`:`****`}else t[n]=r}return t}async function o(e,t,n,r){return fetch(i(e,n,r),{headers:kp(t,n),signal:AbortSignal.timeout(1e4)})}async function s(e,t){if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`});let n=await o(t.api_base,t.api_key,t.protocol??`openai`,t.autoV1??!0);return n.ok?await n.json():e.json({status:`error`,message:`HTTP ${String(n.status)}`})}function c(e){let{response:t,read:n,url:r,headers:i,payload:o}=e,s={method:`POST`,url:r,headers:a(i),body:o},c=n.payload??{};if(n.streamed){if(!t.ok)return{status:`error`,message:l(c,t.status),latency:n.latencyMs,request:s,response:{status:t.status,body:n.payload}};let e=n.payload!==null;return{status:e?`ok`:`error`,message:e?`流式首帧正常`:`流式响应未收到数据帧`,latency:n.latencyMs,request:s,response:{status:t.status,body:n.payload}}}return t.ok&&(c.choices!==void 0||c.output!==void 0||c.content!==void 0)?{status:`ok`,message:`${String(c.usage?.completion_tokens??c.usage?.output_tokens??0)} tokens`,latency:n.latencyMs,request:s,response:{status:t.status,body:c}}:{status:`error`,message:l(c,t.status),latency:n.latencyMs,request:s,response:{status:t.status,body:c}}}function l(e,t){let n=e.error,r=typeof n==`object`&&n&&`message`in n?String(n.message):typeof n==`string`?n:null;if(r!==null)return u(r);if(typeof e.msg==`string`&&e.msg.trim()!==``){let t=e.code===void 0||e.code===null?``:` (${String(e.code)})`;return u(`${e.msg.trim()}${t}`)}return u(`HTTP ${String(t)}`)}function u(e){let t=e;for(let[e,n]of[[/Weekly usage limit reached/i,`每周使用限额已达上限`],[/Resets in (\d+) day/i,`$1 天后重置`],[/RateLimitError:?\s*OpenAIException\s*-?\s*/gi,``],[/RateLimitError/g,`频率限制`],[/Rate limit/gi,`请求频率超限`],[/Invalid.*api.?key/i,`API Key 无效`],[/Unauthorized/i,`认证失败`],[/Not found/i,`模型或端点不存在`],[/Timeout/i,`请求超时`],[/Connection refused/i,`连接被拒绝`],[/ECONNREFUSED/i,`连接被拒绝`],[/ENOTFOUND/i,`域名无法解析`],[/model.*not.*found/i,`模型不存在`],[/context length exceeded/i,`上下文长度超限`],[/maximum context length/i,`超过最大上下文长度`],[/overloaded/i,`服务过载`],[/internal server error/i,`服务器内部错误`],[/bad gateway/i,`网关错误`],[/OpenAIException\s*-?\s*/i,``],[/To continue using[\s\S]*$/i,``],[/Received Model Group[\s\S]*$/i,``],[/Available Model Group[\s\S]*$/i,``],[/HTTP (\d+)/,`HTTP 错误 $1`]])t=t.replace(e,n);return t=t.replace(/\s+/g,` `).replace(/^[.:;\s-]+|[.:;\s-]+$/g,``).trim(),t||=e,t.length>120&&(t=t.substring(0,120)+`...`),t}t.get(`/results`,Sp(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,Sp(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,Sp(async e=>{let{keyId:t,models:n}=await e.req.json();return!t||!Array.isArray(n)?e.json({error:`缺少必要参数: keyId, models`},400):(r.set(t,n),e.json({message:`模型缓存已更新`,keyId:t,count:n.length}))})),t.post(`/`,async e=>{try{let t=await s(e,await e.req.json());return t instanceof Response?t:e.json({status:`ok`,models:t.data?.length||0,protocol:`openai`})}catch(t){return e.json({status:`error`,message:t.message})}}),t.post(`/fetch-models`,async e=>{try{let t=await e.req.json(),n=await s(e,t);if(n instanceof Response)return n;let i=(n.data||[]).map(e=>e.id||e.name).filter(e=>!!e);if(t.keyId){let e=r.get(t.keyId)??[],n=[...new Set([...e,...i])];r.set(t.keyId,n)}return e.json({status:`ok`,models:i})}catch(t){return e.json({status:`error`,message:t.message})}});function d(e,t){return t===`anthropic`?{model:e,messages:[{role:`user`,content:Dp}],max_tokens:16,stream:!0}:t===`openai-responses`?{model:e,input:Dp,stream:!0}:{model:e,messages:[{role:`user`,content:Dp}],stream:!0}}async function f(e){let t=e.protocol||`openai`,n=e.autoV1??!0,r=e.api_base.replace(/\/+$/,``);if(!r)throw Error(`api_base 不能为空`);let i={"Content-Type":`application/json`,...kp(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${Op(r,n)}${a}`,s=d(e.model,t),l=Date.now(),u=await fetch(o,{method:`POST`,headers:i,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)});return c({response:u,read:await jp(u,l),url:o,headers:i,payload:s})}function p(e){let t=El();for(let n of t?.providers??[]){let t=n.models?.find(t=>t?.modelName===e);if(t)return t.customLlmProvider??n.customLlmProvider??`openai`}return`openai`}async function m(t,n){let r=Fl(),i=up(e),a=`http://127.0.0.1:${String(i)}`,o={"Content-Type":`application/json`};r&&(o.Authorization=`Bearer ${r}`);let s=`${a}${n===`anthropic`?`/v1/messages`:n===`openai-responses`?`/v1/responses`:`/v1/chat/completions`}`,l=d(t,n),u=Date.now(),f;try{f=await fetch(s,{method:`POST`,headers:o,body:JSON.stringify(l),signal:AbortSignal.timeout(3e4)})}catch(e){let t=e;throw A(`[test] 网关自调用失败:`,t.message,`cause:`,t.cause?.message??`n/a`),e}return c({response:f,read:await jp(f,u),url:s,headers:o,payload:l})}return t.post(`/model`,async e=>{try{let t=await e.req.json(),r=t.model;if(!r)return e.json({status:`error`,message:`缺少 model 参数`},400);if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`},400);let i;try{i=await f({model:r,api_base:t.api_base,api_key:t.api_key,protocol:t.protocol,autoV1:t.autoV1})}catch(e){i={status:`error`,message:u(e.message),latency:0}}return n.set(r,{...i,time:new Date().toISOString()}),e.json(i)}catch(t){return e.json({status:`error`,message:u(t.message)})}}),t.post(`/proxy`,async e=>{try{let t=(await e.req.json()).model;if(!t)return e.json({status:`error`,message:`缺少 model 参数`},400);let r=await m(t,p(t));return n.set(t,{...r,time:new Date().toISOString()}),e.json(r)}catch(t){return e.json({status:`error`,message:u(t.message)})}}),t}var Np=Tu(`latency_probes`,{id:U().primaryKey({autoIncrement:!0}),model:H().notNull(),time:U().notNull(),latency_ms:U().notNull(),ok:U().notNull(),error:H()},[wu(`idx_latency_probes_model_time`).on(`model`,`time`),wu(`idx_latency_probes_time`).on(`time`)]),Pp=2592e6,Fp=null;function Ip(){let e=Fp;if(e!==null)return e;let t=sd(`latency`);return t.createTables([Np]),Fp=t,t}function Lp(){return Ip().native}function Rp(e){if(e.length!==0)try{Ip().insert(Np).values(e.map(e=>({model:e.model,time:e.time,latency_ms:e.latencyMs,ok:+!!e.ok,error:e.error??null}))).run()}catch(e){A(`[latency] 探测记录写入失败:`,e instanceof Error?e.message:String(e))}}function zp(){let e=Date.now()-Pp;return Ip().select(Np).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(G.gt(Np.time,e)).orderBy(G.asc(Np.time)).all().map(e=>({model:e.model,time:Number(e.time),latencyMs:Number(e.latency_ms),ok:e.ok===1,error:e.error??void 0}))}function Bp(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=Ip().select(Np).columns([`time`,`latency_ms`,`ok`]).where(G.and(G.eq(Np.model,e),G.gt(Np.time,a),G.lte(Np.time,r))).all();if(o.length===0)return[];let s=e=>{let n=new Date(e);return t===`hour`?new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()).getTime():new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime()},c=[];for(let e=s(r);e>=s(a);e-=i)c.unshift(e);let l=new Map;for(let e of c)l.set(e,{total:0,success:0,latencySum:0});for(let e of o){let t=l.get(s(Number(e.time)));t&&(t.total+=1,e.ok===1&&(t.success+=1,t.latencySum+=Number(e.latency_ms)))}return c.map(e=>{let t=l.get(e);return{bucketStart:e,total:t.total,success:t.success,failed:t.total-t.success,successRate:t.total===0?null:Math.round(t.success/t.total*1e3)/10,avgLatencyMs:t.success===0?null:Math.round(t.latencySum/t.success)}})}function Vp(){let e=Ip().select(Np).columns({t:G.max(Np.time)}).get();return e?.t==null?null:Number(e.t)}function Hp(e){try{let t=Date.now()-e;Ip().delete(Np).where(G.lte(Np.time,t)).run()}catch(e){A(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var Up=3e4,Wp=4,Gp=!1;function Kp(){return Gp}function qp(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function Jp(e){let t=async e=>{let t=Op((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?kp(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:Dp}],max_tokens:1,stream:!0}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:Dp,max_output_tokens:16,stream:!0}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:Dp}],max_tokens:1,stream:!0});let a=Date.now();try{let t=await fetch(r,{method:`POST`,headers:n,body:JSON.stringify(i),signal:AbortSignal.timeout(Up)});if(!t.ok){let n=await t.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,120)).catch(()=>``);return{model:e.name,time:a,latencyMs:0,ok:!1,error:n?`HTTP ${String(t.status)}: ${n}`:`HTTP ${String(t.status)}`}}let o=await jp(t,a);return o.streamed&&o.payload===null?{model:e.name,time:a,latencyMs:0,ok:!1,error:`HTTP ${String(t.status)}: 流式响应未收到数据帧`}:{model:e.name,time:a,latencyMs:o.latencyMs,ok:!0}}catch(t){return{model:e.name,time:a,latencyMs:0,ok:!1,error:t.message}}},n=async e=>{let n=[],r=0,i=Array.from({length:Math.max(1,Math.min(Wp,e.length))},async()=>{for(;;){let i=r++;if(i>=e.length)return;n.push(await t(e[i]))}});return await Promise.all(i),n};if(Gp)return!1;Gp=!0;try{let t=await n(qp(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));Rp(t),Hp(Pp);let r=t.filter(e=>e.ok).length;return O(`[latency] 测试完成: ${String(t.length)} 个模型(成功 ${String(r)}),数据已入库 latency.db`),!0}catch(e){return A(`[latency] 测试执行失败:`,e instanceof Error?e.message:String(e)),!0}finally{Gp=!1}}function Yp(e){return qp(e).length}var Xp=[{key:`avg10m`,ms:6e5},{key:`avg30m`,ms:18e5},{key:`avg1h`,ms:36e5},{key:`avg2h`,ms:72e5},{key:`avg5h`,ms:18e6},{key:`avg8h`,ms:288e5},{key:`avg12h`,ms:432e5},{key:`avg24h`,ms:864e5}];function Zp(e,t,n){return n.map(n=>{let r=e.filter(e=>e.model===n),i={model:n,avg10m:null,avg30m:null,avg1h:null,avg2h:null,avg5h:null,avg8h:null,avg12h:null,avg24h:null,lastTestAt:null,lastOk:null,lastLatencyMs:null,lastError:null},a=r.reduce((e,t)=>e===null||t.time>e.time?t:e,null);a!==null&&(i.lastTestAt=a.time,i.lastOk=a.ok,a.ok&&(i.lastLatencyMs=a.latencyMs),a.ok||(i.lastError=a.error??null));for(let{key:e,ms:n}of Xp){let a=r.filter(e=>e.ok&&e.time>t-n&&e.time<=t);a.length!==0&&(i[e]=Math.round(a.reduce((e,t)=>e+t.latencyMs,0)/a.length))}return i})}function Qp(e){let t=new M;return t.get(`/history`,t=>{let n=zp(),r=Date.now();return t.json({running:Kp(),lastRunAt:Vp(),models:Zp(n,r,e.current.expanded.deployments.names)})}),t.get(`/trend`,e=>{let t=e.req.query(`model`);if(!t)return e.json({ok:!1,error:`缺少 model 参数`},400);let n=e.req.query(`granularity`)===`day`?`day`:`hour`,r=Bp(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>Kp()?t.json({ok:!1,error:`测试进行中,请稍候`},409):Yp(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(Jp(e),t.json({ok:!0,running:!0}))),t}function $p(){let e=t=>{let n=0;if(!p(t))return 0;for(let r of _(t)){let i=c(t,r),a;try{a=x(i)}catch{continue}a.isDirectory()?n+=e(i):n+=a.size}return n},t=()=>Math.round(e(xt())/1024/1024*10)/10,n=new M;return n.onError(xp),n.get(`/`,Sp(e=>{let n=e.req.query(),r=sf({startDate:n.startDate,endDate:n.endDate,model:n.model});return e.json({...r,logStorageMB:t()})})),n}function Y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function em(e){return typeof e==`string`?e:null}function tm(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function nm(e,t){let n=tm(e,t);return n===void 0?void 0:e[n]}function rm(e,t){if(e===void 0)return null;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e!==-1&&n.slice(0,e).trim()===t)return n.slice(e+1).trim()}return null}function im(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function am(e){let t=(e,t)=>{let n=e[t];if(n!==`"`&&n!==`'`&&n!=="`")return null;let r=t+1,i=``;for(;r<e.length;){let t=e[r];if(t===`\\`){i+=e[r+1]??``,r+=2;continue}if(t===n)return{value:i,end:r+1};i+=t,r+=1}return null},n=(e,n)=>{let r=(e,t)=>{let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;return n},i=(e,n)=>{if(e[n]!==`{`)return null;let r=0,i=n;for(;i<e.length;){let a=e[i];if(a===`"`||a===`'`||a==="`"){let n=t(e,i);if(n===null)return null;i=n.end;continue}if(a===`{`)r+=1;else if(a===`}`&&(--r,r===0))return{raw:e.slice(n,i+1),end:i+1};i+=1}return null},a=e=>{let n=e=>{let n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`||i===`'`||i==="`"){let i=t(e,r);if(i===null){n+=e.slice(r);break}n+=e.slice(r,i.end),r=i.end;continue}if(i===`,`){let t=r+1;for(;t<e.length&&/\s/.test(e[t]);)t+=1;let n=e[t];if(n===`}`||n===`]`){r+=1;continue}}n+=i,r+=1}return n},r;try{r=JSON.parse(n(e))}catch{return null}let i=Y(r);if(i===null)return null;let a={},o=Y(i.headers);if(o!==null)for(let[e,t]of Object.entries(o))typeof t==`string`&&(a[e]=t);return{method:typeof i.method==`string`?i.method.toUpperCase():`GET`,headers:a,body:typeof i.body==`string`?i.body:null}},o=r(e,n),s=t(e,o);if(s===null)return null;let c=s.value,l=r(e,s.end);if(e[l]!==`,`)return{url:c,method:`GET`,headers:{},body:null};let u=i(e,r(e,l+1));if(u===null)return{url:c,method:`GET`,headers:{},body:null};let d=a(u.raw);if(d===null)throw Error(`无法解析 fetch 的 options 对象(可能复制不完整,请重新复制完整的 fetch 调用)`);return{url:c,method:d.method,headers:d.headers,body:d.body}},r=e=>{let t=new Map;for(let n of e){let e=tm(n.headers,`cookie`);if(e===void 0)continue;let r=im(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(tm(e.headers,`cookie`)!==void 0)return e;let n=im(e.url),r=n===``?void 0:t.get(n);return r===void 0?e:{...e,headers:{...e.headers,[r.key]:r.value}}})},i=[],a=/\bfetch\s*\(/g,o;for(;(o=a.exec(e))!==null;){let t=n(e,o.index+o[0].length);t!==null&&i.push(t)}return r(i)}function om(e){return e.some(e=>tm(e.headers,`cookie`)!==void 0)}var sm=0xe8d4a51000,cm=3e4;async function lm(e,t){let n=e=>{let t={...e};for(let e of Object.keys(t)){let n=e.toLowerCase();(n===`content-length`||n===`host`||n===`connection`)&&delete t[e]}return t},r=await fetch(e,{...t,headers:n(t.headers),signal:AbortSignal.timeout(cm)});if(!r.ok){let e=await r.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(r.status)}${e===``?``:`: ${e}`}`)}let i=Y(await r.json());if(i===null)throw Error(`响应不是 JSON 对象`);return i}function um(e){return e===null||e<=0?null:Math.round(e<sm?e*1e3:e)}function dm(e){return Math.round(e*100)/100}function fm(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function pm(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function mm(e,t){let n=Y(e);if(n===null)return null;let r=X(n[t.used])??0,i=X(n[t.cap]),a=t.exceeded!==void 0&&n[t.exceeded]===!0||i!==null&&r>=i;return{used:r,cap:i,resetAt:t.resetAt===void 0?null:um(X(n[t.resetAt])),exceeded:a}}var hm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await lm(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await lm(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},gm=`https://api.commandcode.ai`,_m=`/alpha/billing/credits`,vm=`/alpha/usage/summary`,ym=`/alpha/billing/subscriptions`,bm={"individual-pro-v1":80,"individual-goat":70},xm=/^user_[A-Za-z0-9_-]+$/,Sm={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function Cm(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:fm(t)}]}function wm(e){let t=em(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var Tm=class extends hm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=xm;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!xm.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(gm,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(vm),this.get(_m),this.get(ym).catch(()=>null)]),r=Y(t.windowLimits),i=Y(t.credits),a=n===null?null:Y(n.data),o=a===null?null:em(a.planId),s=o===null?null:bm[o]??null,c=i===null?null:X(i.monthlyCredits),l=s===null||c===null?null:{used:dm(Math.max(0,s-c)),cap:s,resetAt:a===null?null:wm(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:mm(r.fiveHour,Sm),weekly:r===null?null:mm(r.weekly,Sm),monthly:l,totalTokens:X(e.totalTokens),totalRuns:X(e.totalCount),voucherBalance:null,balance:null,extraStats:Cm(l,c)}}},Em=`https://api.deepseek.com`,Dm=`/user/balance`,Om=`余额不足,无法调用 API`;function km(e){let t=X(e);if(t!==null)return t;let n=em(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function Am(e){return e===`CNY`?`元`:e===`USD`?`美元`:e}function jm(e){let t=[];if(!Array.isArray(e))return t;let n=new Set;for(let r of e){let e=Y(r);if(e===null)continue;let i=em(e.currency);if(i===null||i.trim()===``)continue;let a=i.trim();if(n.has(a))continue;let o=km(e.total_balance);o!==null&&(n.add(a),t.push({currency:a,total:o,granted:km(e.granted_balance),toppedUp:km(e.topped_up_balance)}))}return t}function Mm(e){return e.length===0?null:e.length===1?e[0]:e.find(e=>e.currency===`CNY`)??[...e].sort((e,t)=>e.currency.localeCompare(t.currency))[0]}var Nm=class extends hm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static apiHosts=[`api.deepseek.com`];static credentialSource=`apiKey`;constructor(e){super(Em,{authorization:`Bearer ${e}`,accept:`application/json`})}async fetchQuota(){let e=await this.get(Dm),t=Mm(jm(e.balance_infos));if(t===null)throw Error(`上游未返回余额数据(响应缺少 balance_infos,或各行的 total_balance 不可解析)`);let n=Am(t.currency),r=[];return t.toppedUp!==null&&r.push({label:`充值余额`,value:`${fm(dm(t.toppedUp))} ${n}`}),t.granted!==null&&r.push({label:`赠送余额`,value:`${fm(dm(t.granted))} ${n}`}),e.is_available===!1&&r.push({label:`账户状态`,value:Om}),{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:dm(t.total),extraStats:r.length===0?null:r}}},Pm=[`127.0.0.1`,`localhost`,`[::1]`],Fm=/^\/p\/([^/]+)(?:\/v1)?\/?$/;function Im(e){let t;try{t=new URL(e)}catch{return null}if(!Pm.some(e=>e===t.hostname.toLowerCase()))return null;let n=Fm.exec(t.pathname);if(n===null)return null;let r;try{r=decodeURIComponent(n[1])}catch{return null}return r.trim()===``?null:{origin:t.origin,providerId:r}}function Lm(e){let t=[];if(!Array.isArray(e))return t;for(let n of e){let e=Y(n);if(e===null)continue;let r=em(e.name),i=em(e.display);r!==null&&r.trim()!==``&&i!==null&&i.trim()!==``&&t.push({name:r,usedPercent:X(e.used)??0,display:i,amount:X(e.amount),limit:X(e.limit),unit:em(e.unit)})}return t}var Rm=class{static vendorId=`pluginHost`;static vendorLabel=`插件(OpenCode 插件宿主)`;static credentialSource=`pluginHost`;static matchMode=`loopbackPath`;static pathPrefix=`/p/`;static apiHosts=Pm;#e;#t;constructor(e){let t=Im(e);if(t===null)throw Error(`不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径):${e}`);this.#e=t.origin,this.#t=t.providerId}async fetchQuota(){let e=await lm(`${this.#e}/p/${encodeURIComponent(this.#t)}/usage`,{method:`GET`,headers:{accept:`application/json`}}),t=em(e.error);if(t!==null&&t.trim()!==``)throw Error(t);let n=em(e.plan);return{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:null,windows:Lm(e.windows),...n!==null&&n.trim()!==``?{extraStats:[{label:`套餐`,value:n}]}:{}}}},zm=`/api/user/self`,Bm=`/api/user/subscription/current_cycle`,Vm={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function Hm(e,t){let n=e.usage_infos;if(!Array.isArray(n))return null;for(let e of n){let n=Y(e);if(n!==null&&n.key===t)return n}return null}function Um(e){return e===null||X(e.total_count)===null?null:mm(e,Vm)}function Wm(e){let t=Y(e.account_info),n=t===null?null:t.vouchers;if(!Array.isArray(n))return null;let r=0,i=!1;for(let e of n){let t=Y(e),n=t===null?null:X(t.available);n!==null&&(r+=n,i=!0)}return i?r/1e6:null}function Gm(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var Km=class extends hm{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=am(e),n=Gm(t,zm),r=Gm(t,Bm);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>nm(e.headers,`authorization`)!==void 0))throw Error(`复制的请求里没有 authorization 头(登录凭据在它里面)——请从已登录的 senseaudio.cn 页面重新复制 fetch 调用`);let i=n??r;super(new URL(i.url).origin,i.headers)}async fetchQuota(){let[e,t]=await Promise.all([this.get(zm),this.get(Bm).catch(()=>null)]),n=Um(Hm(e,`credit_5h_limit`)),r=Um(Hm(e,`credit_7d_limit`)),i=Um(Hm(e,`credit_30d_limit`));if(i===null&&t!==null){let e=X(t.plan_points),n=X(t.plan_point_remains);e!==null&&n!==null&&(i={used:e-n,cap:e,resetAt:um(X(t.plan_points_reset_at)),exceeded:e-n>=e})}if(n===null&&r===null&&i===null)throw Error(`上游未返回任何额度窗口(该账号可能尚未登录或未订阅套餐)`);return{fiveHour:n,weekly:r,monthly:i,totalTokens:null,totalRuns:null,voucherBalance:Wm(e),balance:null}}},qm=`GetAgentPlanAFPUsage`,Jm=`GetAgentPlanUsageDetails`,Ym=`console.volcengine.com`,Xm=`2024-01-01`,Zm=`cn-beijing`,Qm={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function $m(e){return e.find(e=>e.url.includes(qm))}function eh(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??Zm}/${Xm}`:t}function th(e){return e.find(e=>im(e.url)===Ym)}var nh=class extends hm{static vendorId=`volc-ark`;static vendorLabel=`火山方舟`;static hosts=[`console.volcengine.com`];static apiHosts=[`ark.cn-beijing.volces.com`];static credentialSource=`fetchText`;#e;#t;constructor(e){let t=am(e),n=$m(t)??th(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!om(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==Ym)throw Error(`非方舟控制台域`);r=e.origin,i=eh(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=rm(nm(n.headers,`cookie`),`csrfToken`)??nm(n.headers,`x-csrf-token`)??null;if(a===null)throw Error(`缺少 CSRF 凭据:请求头需含 x-csrf-token,或 Cookie 里需有 csrfToken (两者都来自已登录的控制台会话,请在登录页面上重新复制)`);super(r,{...n.headers,"x-csrf-token":a}),this.#e=`${i}/${qm}`,this.#t=`${i}/${Jm}`}envelope(e){let t=Y(e.ResponseMetadata),n=t===null?null:Y(t.Error);if(n!==null){let e=em(n.Code)??`Unknown`,t=em(n.Message)??``;throw Error(`上游业务错误 ${e}${t===``?``:`: ${t}`}(多为 Cookie 或 CSRF 凭据失效,请在控制台重新复制)`)}return e}async fetchQuota(){let e=Y((await this.post(this.#e,{})).Result);if(e===null)throw Error(`响应缺少 Result 字段`);let t=mm(e.AFPFiveHour,Qm),n=mm(e.AFPWeekly,Qm),r=mm(e.AFPMonthly,Qm);if(t===null&&n===null&&r===null)throw Error(`上游未返回任何 AFP 窗口(该账号可能尚未订阅 Agent Plan 套餐)`);let i=Y(e.AFPMonthly),a=i===null?null:X(i.SubscribeTime);return{fiveHour:t,weekly:n,monthly:r,totalTokens:await this.#n(a),totalRuns:null,voucherBalance:null,balance:null}}async#n(e){let t=Date.now(),n=e!==null&&e>0?e:t-2592e6;try{let e=Y((await this.post(this.#t,{Filter:{StartTime:pm(new Date(n)),EndTime:pm(new Date(t)),ObjectType:1,BillingType:[`WithinPlan`]},QueryInterval:`Day`})).Result),r=e===null?null:e.Details;return Array.isArray(r)?r.reduce((e,t)=>{let n=Y(t);return n===null||n.Unit!==`Tokens`?e:e+(X(n.Usage)??0)},0):null}catch{return null}}},rh=`/api/biz/account/query-customer-account-report`,ih=`/api/finance/expenseBill/expenseBillListByDay`,ah=200,oh=`bigmodel_token_production`;function sh(e){let t=rm(nm(e.headers,`cookie`),oh);if(t!==null&&t.trim()!==``)return t.trim();let n=nm(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var ch=class extends hm{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=am(e);if(t.length===0)throw Error(`未找到可用的智谱请求:请在已登录的 bigmodel.cn(财务中心 / 资源包 / 任意控制台页面)里复制任意请求的 fetch 调用粘贴进来,额度端点会自动换算`);let n=t[0],r;try{r=new URL(n.url).origin}catch{throw Error(`粘贴的请求 URL 不是绝对地址,无法换算出额度接口——请粘贴浏览器里完整的 fetch(https://…)`)}let i=sh(n);if(i===null)throw Error(`复制的请求里没有登录凭据(需要 Cookie 里的 bigmodel_token_production,或显式的 authorization 头)——请从已登录的 bigmodel.cn 页面用「以 fetch (Node.js) 格式复制」重新复制`);let a={...n.headers,authorization:i.toLowerCase().startsWith(`bearer `)?i:`Bearer ${i}`};super(r,a)}envelope(e){let t=X(e.code);if(t!==200){let n=em(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=pm(e).slice(0,7),n=pm(new Date(e.getFullYear(),e.getMonth(),e.getDate()-(e.getDay()+6)%7));try{let e=1,r=0,i=0,a=1/0,o=[];for(;o.length<a;){let s=await this.get(ih,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(ah)}`),c=s.rows,l=s.total;if(!Array.isArray(c))return null;a=X(l)??o.length,o=o.concat(c);for(let e of c){let t=Y(e);if(t===null)continue;let a=X(t.originalAmount),o=em(t.billingDate);a!==null&&o!==null&&(r+=a,o>=n&&(i+=a))}if(e+=1,c.length===0)break}return{weekly:{used:i,cap:null,resetAt:null,exceeded:!1},monthly:{used:r,cap:null,resetAt:null,exceeded:!1}}}catch{return null}}async fetchQuota(){let[e,t]=await Promise.all([this.get(rh),this.#e()]),n=Y(e.data),r=(n===null?null:X(n.availableBalance))??(n===null?null:X(n.balance));if(n===null||r===null)throw Error(`响应缺少余额字段(data.availableBalance)`);let i=X(n.totalSpendAmount);return{fiveHour:null,weekly:t?.weekly??null,monthly:t?.monthly??null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:r,totalCost:i,totalCostCurrency:i===null?null:`CNY`,extraStats:lh(n)}}};function lh(e){let t=e=>`${fm(e)} 元`,n=[],r=X(e.rechargeAmount);r!==null&&n.push({label:`累计充值`,value:t(r)});let i=X(e.giveAmount);i!==null&&n.push({label:`赠送金额`,value:t(i)});let a=X(e.creditBalance);return a===null?e.creditStatus===`NOT_OPEN`&&n.push({label:`信用余额`,value:`未开通`}):n.push({label:`信用余额`,value:t(a)}),n}var uh=[Tm,Nm,Km,nh,ch,Rm];function dh(){return uh}function fh(e){if(e===void 0)return null;let t=im(e);if(t===``)return null;for(let e of uh)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function ph(e,t){let n=fh(t);if(n===null)throw Error(`该供应商未支持用 API key 自动查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`该供应商的 apiKey 为空,无法查询额度——请在供应商配置里填入 API key`);if(n.apiKeyPattern?.test(r)===!1)throw Error(`配置里的 apiKey 不是 ${n.vendorLabel} 的 API key 形态——请检查该供应商配置的 apiKey 字段`);return{vendorId:n.vendorId,vendor:new n(r)}}function mh(e){return e===void 0||Im(e)===null?null:Rm}function hh(e){if(mh(e)===null)throw Error(`apiBase 不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径,如 http://127.0.0.1:29772/p/workbuddy):${e}`);return{vendorId:Rm.vendorId,vendor:new Rm(e)}}function gh(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of am(e)){let e=im(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of uh)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=im(t);if(e!==``){for(let t of uh)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of uh)if(e.credentialSource===`fetchText`&&e.hosts?.some(e=>i.has(e))===!0)return e;return null};if(e.trim()===``)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);let r=n(e,t);if(r===null){let e=uh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=uh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=fh(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var _h=Ht(`quota.json`);function vh(e){let t=e=>{let t=e=>{let t=Y(e);if(t===null)return null;let n=t.used;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=t.cap,i=t.resetAt;return{used:n,cap:typeof r==`number`&&Number.isFinite(r)?r:null,resetAt:typeof i==`number`&&Number.isFinite(i)?i:null,exceeded:t.exceeded===!0}},n=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null},r=e=>{let t=Y(e);if(t===null)return null;let r=n(t.cost),i=n(t.requests);if(r===null&&i===null)return null;let a=t.currency;return{cost:r,currency:typeof a==`string`&&a!==``?a:null,requests:i}},i=e=>{if(!Array.isArray(e))return null;let t=[];for(let n of e){let e=Y(n);if(e===null)continue;let r=e.label,i=e.value;typeof r==`string`&&r!==``&&typeof i==`string`&&i!==``&&t.push({label:r,value:i})}return t.length>0?t:null},a=e=>{if(!Array.isArray(e))return null;let t=[];for(let r of e){let e=Y(r);if(e===null)continue;let i=e.name,a=e.display;if(typeof i!=`string`||i===``||typeof a!=`string`||a===``)continue;let o=e.usedPercent;t.push({name:i,usedPercent:typeof o==`number`&&Number.isFinite(o)?o:0,display:a,amount:n(e.amount),limit:n(e.limit),unit:typeof e.unit==`string`&&e.unit!==``?e.unit:null})}return t.length>0?t:null},o=Y(e);if(o===null)return null;let s=o.totalTokens,c=o.totalRuns,l=o.voucherBalance,u=o.balance,d=o.totalCost,f=o.totalCostCurrency;return{fiveHour:t(o.fiveHour),weekly:t(o.weekly),monthly:t(o.monthly),totalTokens:typeof s==`number`&&Number.isFinite(s)?s:null,totalRuns:typeof c==`number`&&Number.isFinite(c)?c:null,voucherBalance:typeof l==`number`&&Number.isFinite(l)?l:null,balance:typeof u==`number`&&Number.isFinite(u)?u:null,totalCost:n(d),totalCostCurrency:typeof f==`string`&&f!==``?f:null,today:r(o.today),yesterday:r(o.yesterday),extraStats:i(o.extraStats),windows:a(o.windows)}},n=Y(_h.get(e));if(n===null)return null;let r=n.fetchText,i=n.vendorId,a=n.fetchedAt,o=n.error;return{fetchText:typeof r==`string`&&r.trim()!==``?r:void 0,vendorId:typeof i==`string`?i:void 0,snapshot:t(n.snapshot)??void 0,fetchedAt:typeof a==`number`&&Number.isFinite(a)?a:void 0,error:typeof o==`string`&&o!==``?o:void 0}}function yh(e,t){_h.set(e,t)}function bh(e){_h.get(e)!==void 0&&_h.set(e,void 0)}function xh(){let e=_h.getAll(),t={};for(let n of Object.keys(e)){let e=vh(n);e!==null&&(t[n]=e)}return t}function Sh(e,t,n,r){yh(e,{fetchText:vh(e)?.fetchText,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function Ch(e,t){let n=vh(e);if(n===null){yh(e,{error:t});return}yh(e,{...n,error:t})}var wh=!1;function Th(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function Eh(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function Dh(){let e=e=>{let t=typeof e==`object`&&e?e:{},n=typeof t.apiBase==`string`&&t.apiBase.trim()!==``?t.apiBase:void 0,r=typeof t.apiKey==`string`&&t.apiKey.trim()!==``?t.apiKey:void 0;return{apiBase:n,apiKey:r===void 0?void 0:Eh(r)}};try{let t=El();if(t===null||!Array.isArray(t.providers))return null;let n=new Map;for(let r of t.providers){let t=typeof r==`object`&&r?r.name:void 0;typeof t==`string`&&t!==``&&n.set(t,e(r))}return n}catch{return null}}function Oh(e){return Dh()?.get(e)??null}async function kh(e){try{let t=Oh(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(t.apiBase!==void 0&&mh(t.apiBase)!==null)({vendorId:n,vendor:r}=hh(t.apiBase));else if(fh(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=ph(t.apiKey,t.apiBase))}else{let i=vh(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=gh(i,t.apiBase))}let i=await r.fetchQuota();Sh(e,n,i,Date.now())}catch(t){Ch(e,Th(t))}return vh(e)}async function Ah(){let e=()=>{let e=Dh();return e===null?null:new Set(e.keys())};if(!wh){wh=!0;try{let t=Dh(),n=[];for(let[e,r]of t??[])(fh(r.apiBase)!==null||mh(r.apiBase)!==null)&&n.push(e);for(let e of n)await kh(e);let r=e();for(let[e,t]of Object.entries(xh()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){bh(e);continue}n.includes(e)||await kh(e)}}catch(e){A(`[quota] 刷新失败:`,Th(e))}finally{wh=!1}}}function jh(){let e=async e=>{let t=(await hp(e))?.fetchText;return typeof t==`string`?t:null},t=()=>dh().map(e=>({vendorId:e.vendorId,vendorLabel:e.vendorLabel,hosts:e.hosts??[],apiHosts:e.apiHosts??[],credentialSource:e.credentialSource,...e.matchMode===void 0?{}:{matchMode:e.matchMode},...e.pathPrefix===void 0?{}:{pathPrefix:e.pathPrefix}})),n=new M;return n.get(`/`,e=>e.json({ok:!0,vendors:t(),providers:xh()})),n.get(`/vendors`,e=>e.json({ok:!0,vendors:t()})),n.put(`/:provider`,async t=>{let n=t.req.param(`provider`),r=Oh(n)?.apiBase;if(mh(r)!==null)return t.json({ok:!1,error:`该供应商的额度由插件服务查询,无需手动配置`},400);if(fh(r)!==null)return t.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);let i=await e(t);if(i===null)return t.json({ok:!1,error:`请求体需为 {"fetchText": "..."}`},400);let a=vh(n);yh(n,{fetchText:i,vendorId:a?.vendorId,snapshot:a?.snapshot,fetchedAt:a?.fetchedAt,error:void 0});let o=await kh(n);return t.json({ok:!0,entry:o})}),n.delete(`/:provider`,e=>(bh(e.req.param(`provider`)),e.json({ok:!0}))),n.post(`/:provider/refresh`,async e=>{let t=await kh(e.req.param(`provider`));return e.json({ok:!0,entry:t})}),n}function Mh(e){return e===`0.0.0.0`||e===`::`}function Nh(e=T()){let t=[];for(let n of Object.values(e))for(let e of n??[])e.internal||e.family!==`IPv4`||t.includes(e.address)||t.push(e.address);return t}function Ph(e,t){let n=new M;return n.get(`/`,n=>n.json({listenPort:up(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},...t&&Mh(t.hostname)?{lanAddresses:Nh()}:{},masterKey:Fl()})),n}var Fh=864e5,Ih=3e5,Lh=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,Rh=new Map;try{let e=g(Ct(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;Rh.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function zh(){let e=e=>({model:e.model,client:e.client,sessionId:e.sessionId,noSession:e.noSession===`1`||void 0,startDate:e.startDate||e.date,endDate:e.endDate||e.date,status:e.status,pathGroup:e.pathGroup,keyword:e.keyword}),t=e=>{let t=Rh.get(e);if(!t)return null;let n=t.value.error===void 0?Fh:Ih;return Date.now()-t.at>=n?(Rh.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of Rh)e[t]={...n,_ts:r};C(Ct(),JSON.stringify(e))}catch(e){A(`保存 IP 缓存失败:`,e.message)}},r=async e=>{let r=t(e);if(r)return r;let i=await(await fetch(Lh.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return Rh.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return Rh.set(e,{value:a,at:Date.now()}),n(),a},i=new M;return i.onError(xp),i.get(`/dates`,e=>{let t=cf();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=lf();return e.json({clients:t})}),i.get(`/ipinfo`,async e=>{let t=e.req.query(`ip`)||``;if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return e.json({error:`invalid ip`},400);try{let n=await r(t);return e.json({ip:t,...n})}catch(e){throw new bp(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=Kd(t);return n||=(await Ef(),Kd(t)??pu(Number(t))),n?e.json({...n,meta:{...n.meta,tps:Yd(n.meta)}}):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,Sp(async t=>{let n=t.req.query(),r=of({...e(n),sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize}),i=(n.keyword??``).trim();return i.length>=2&&r.total===0&&(r=pf({...e(n),keyword:i,sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize})),t.json({...r,items:r.items.map(e=>({...e,user_agent:eu(e.headers),tps:Yd(e)}))})})),i.get(`/sessions`,Sp(t=>{let n=t.req.query(),r=df({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,Sp(async t=>{await Of();let n=lu().length;n>0&&k(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=hf(e(r));return O(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}var Bh=3e4,Vh=12e4,Hh=5242880,Uh=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`],Wh=[`host`,`content-length`,`connection`,`keep-alive`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`proxy-authorization`,`proxy-connection`];function Gh(e){let t=e.toLowerCase();return t===``||t.startsWith(`text/`)||t.startsWith(`application/json`)||t.endsWith(`+json`)||t.startsWith(`application/xml`)||t.endsWith(`+xml`)||t.startsWith(`application/javascript`)||t.startsWith(`application/x-www-form-urlencoded`)||t.startsWith(`application/x-ndjson`)||t.startsWith(`application/graphql`)}function Kh(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(Wh.includes(n.toLowerCase())||(t[n]=r));return t}function qh(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?Bh:Math.min(Math.floor(e),Vh)}function Jh(e){if(typeof e!=`string`||e.trim()===``)throw new bp(400,`缺少 url(要转发的目标地址)`);let t=e.trim(),n=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t)?t:`https://${t}`,r;try{r=new URL(n)}catch{throw new bp(400,`不是合法的 URL:${t}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw new bp(400,`只支持 http/https 协议(收到 ${r.protocol})`);return r.toString()}function Yh(e){if(e!=null)return typeof e==`string`?e:JSON.stringify(e)}async function Xh(e){let t=e.body;if(t===null)return{text:``,truncated:!1};let n=t.getReader(),r=[],i=0,a=!1;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;if(t===void 0)continue;let o=Hh-i;if(t.byteLength>=o){r.push(t.subarray(0,o)),i+=o,a=!0;break}r.push(t),i+=t.byteLength}}finally{await n.cancel().catch(()=>void 0)}let o=new Uint8Array(i),s=0;for(let e of r)o.set(e,s),s+=e.byteLength;return{text:new TextDecoder(`utf-8`).decode(o),truncated:a}}function Zh(e){let t={};return e.headers.forEach((e,n)=>{n.toLowerCase()!==`set-cookie`&&(t[n]=e)}),t}async function Qh(e){let{url:t,method:n,headers:r,body:i,timeoutMs:a}=e,o=i!==void 0&&n!==`GET`&&n!==`HEAD`,s=Date.now(),c;try{c=await fetch(t,{method:n,headers:r,...o?{body:i}:{},signal:AbortSignal.timeout(a),redirect:`follow`})}catch(e){let n=e instanceof Error?e.message:String(e);throw new bp(502,e instanceof Error&&e.name===`TimeoutError`?`上游超时(${String(a)}ms):${t}`:`上游请求失败:${n}`)}let l=c.headers.get(`content-type`)??``,u=Gh(l),{text:d,truncated:f}=u?await Xh(c):{text:``,truncated:!1};return Response.json({ok:!0,url:t,finalUrl:c.url,status:c.status,statusText:c.statusText,headers:Zh(c),contentType:l,body:u?d:null,binary:!u,truncated:f,elapsedMs:Date.now()-s})}function $h(){let e=new M;return e.onError(xp),e.post(`/`,async e=>{let t=await hp(e);if(t===null)throw new bp(400,`请求体不是合法 JSON 对象`);let n=typeof t.method==`string`?t.method.toUpperCase():`GET`;if(!Uh.includes(n))throw new bp(400,`不支持的请求方法:${n}(可用 ${Uh.join(` / `)})`);return await Qh({url:Jh(t.url),method:n,headers:Kh(t.headers),body:Yh(t.body),timeoutMs:qh(t.timeoutMs)})}),e.get(`/`,async e=>{let t=e.req.query();return await Qh({url:Jh(t.url),method:`GET`,headers:Kh(void 0),body:void 0,timeoutMs:qh(t.timeoutMs===void 0?void 0:Number(t.timeoutMs))})}),e}function eg(e){return`http://127.0.0.1:${String(e.port)}`}var tg=`daemon.json`;function ng(e){let t=e=>{let t=e.port??null;return{role:`main`,pid:e.pid??null,status:e.status??`stopped`,port:t,address:t?`http://127.0.0.1:${String(t)}`:null,startedAt:e.startedAt??null,restarts:null}},n=e=>{try{let t=JSON.parse(g(c(e,tg),`utf-8`))?.children;if(typeof t!=`object`||!t)return null;for(let e of Object.values(t)){let t=e;if(t?.pid===process.pid)return typeof t.startedAt==`number`?{pid:t.pid,startedAt:t.startedAt}:null}return null}catch{return null}},r=new M;return r.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:eg(e)})),r.get(`/processes`,r=>{let i=n(e.appDir);return r.json({ok:!0,processes:[t({pid:i?.pid??process.pid,status:`online`,port:e.port,startedAt:i?.startedAt??e.startedAt})]})}),r}var rg=`ezllm-autostart.vbs`,ig=`ezllm-autostart.cmd`,ag=`com.ezllm.autostart`,og=`ezllm.service`,sg=`autostart.opt-out`,cg=`ezllm-v2`,lg=`Auto-generated by "npx ezllm install" (${cg}). Disable in the ezllm admin UI (Settings → startup) or by running \`npx ezllm uninstall\`.`,ug=`ELLM_`,dg=new Set([`WEBUI_USERNAME`,`WEBUI_PASSWORD`,`HOST`]),fg=new Set([`ELLM_PORT`,`ELLM_NODE_MIRROR`,`ELLM_NODE_BIN`]);function pg(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(fg.has(n)||(n.startsWith(ug)||dg.has(n))&&(t[n]=r));return t}function mg(e){return c(e,sg)}function hg(){return c((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return c(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),rg)}function gg(){return c(w(),`Library`,`LaunchAgents`,`${ag}.plist`)}function _g(){return c(w(),`.config`,`systemd`,`user`,og)}var vg=3e4;function yg(e,t){return new Promise(n=>{let r=he(e,t,{stdio:`ignore`,shell:!1}),i=setTimeout(()=>{r.kill(),n(124)},vg),a=e=>{clearTimeout(i),n(e)};r.on(`error`,()=>a(127)),r.on(`exit`,e=>a(e??1))})}var bg={win32:{itemPath:hg,on:Eg,off:kg},darwin:{itemPath:gg,on:Dg,off:Ag},linux:{itemPath:_g,on:Og,off:jg}};function xg(e){return bg[e]??null}function Sg(e){let t=xg(e);if(!t)throw Error(`暂不支持的平台: ${e}。`);return t}function Cg(e,t){return[e,t.entryJs,...t.args??[]]}function wg(e){return c(e,`logs`,`autostart.log`)}async function Tg(e,t,n=yg){try{C(e,t,`utf16le`);return}catch(r){if(await n(`powershell`,[`-NoProfile`,`-Command`,`$bytes=[Convert]::FromBase64String('${Buffer.from(t,`utf16le`).toString(`base64`)}');[IO.File]::WriteAllBytes('${e.replace(/'/g,`''`)}', $bytes)`])!==0)throw r}}async function Eg(e,t){let n=(e,t)=>{let n=/["%\r\n]/;if(n.test(e)||n.test(t))throw Error(`环境变量 ${e} 的键/值含 cmd 无法安全转义的字符(" % 或换行),已拒绝写入自启项;请调整该变量后重试 npx ezllm install`)},r=(e,t)=>{let r=wg(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${lg}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${Cg(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
|
|
85
|
+
`)},i=e=>[`' ${lg}`,`CreateObject("WScript.Shell").Run """${e}""", 0, False`,``].join(`\r
|
|
86
|
+
`),a=hg(),o=c(t.appDir,ig);return C(o,r(e,t),`utf-8`),await Tg(a,`\uFEFF${i(o)}`),a}async function Dg(e,t){let n=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`),r=(e,t)=>{let r=wg(t.appDir),i=Object.entries(t.env).map(([e,t])=>` <string>${n(e)}</string>\n <string>${n(t)}</string>`).join(`
|
|
87
|
+
`),a=Cg(e,t).map(e=>` <string>${n(e)}</string>`).join(`
|
|
88
|
+
`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<!-- ${cg}: launch daemon -->`,`<plist version="1.0">`,`<dict>`,` <key>Label</key><string>${n(ag)}</string>`,` <key>ProgramArguments</key>`,` <array>`,a,` </array>`,` <key>EnvironmentVariables</key>`,` <dict>`,i,` </dict>`,` <key>RunAtLoad</key><true/>`,` <key>StandardOutPath</key><string>${n(r)}</string>`,` <key>StandardErrorPath</key><string>${n(r)}</string>`,`</dict>`,`</plist>`,``].join(`
|
|
89
|
+
`)},i=gg();C(i,r(e,t),`utf-8`),await yg(`launchctl`,[`unload`,i]);let a=await yg(`launchctl`,[`load`,i]);if(a!==0)throw Error(`launchctl load 失败(退出码 ${String(a)})。请手动执行: launchctl load "${i}"`);return i}async function Og(e,t){let n=(e,t)=>{let n=Object.entries(t.env).map(([e,t])=>`Environment="${e}=${t.replace(/"/g,`\\"`)}"`).join(`
|
|
90
|
+
`),r=Cg(e,t).map(e=>`"${e.replace(/"/g,`\\"`)}"`).join(` `);return[`[Unit]`,`Description=ezllm autostart (${cg}, launch daemon)`,`After=default.target`,``,`[Service]`,`Type=simple`,`ExecStart=${r}`,n,`Restart=on-failure`,`RestartSec=3`,``,`[Install]`,`WantedBy=default.target`,``].join(`
|
|
91
|
+
`)},r=_g();m(s(r),{recursive:!0}),C(r,n(e,t),`utf-8`);let i=await yg(`systemctl`,[`--user`,`daemon-reload`]);if(i!==0)throw Error(`systemctl --user daemon-reload 失败(退出码 ${String(i)})。当前环境可能无 systemd(WSL/容器),请手动启用或删除: ${r}`);let a=await yg(`systemctl`,[`--user`,`enable`,og]);if(a!==0)throw Error(`systemctl --user enable 失败(退出码 ${String(a)})。请手动执行: systemctl --user enable ${og}`);return r}async function kg(e){let t=hg(),n=p(t);return y(t,{force:!0}),y(c(e,ig),{force:!0}),n}async function Ag(){let e=gg();return p(e)?(await yg(`launchctl`,[`unload`,e]),y(e,{force:!0}),!0):!1}async function jg(){let e=_g();return p(e)?(await yg(`systemctl`,[`--user`,`disable`,og]),y(e,{force:!0}),await yg(`systemctl`,[`--user`,`daemon-reload`]),!0):!1}function Mg(e){let t=()=>xg(E())?.itemPath()??null,n=e=>{let t=g(e);return t.length>=2&&t[0]===255&&t[1]===254?t.toString(`utf16le`).slice(1):t.toString(`utf-8`)},r=t(),i=!1;if(r&&p(r))try{i=n(r).includes(cg)}catch{}return{platform:E(),enabled:i,itemPath:r,optOut:p(mg(e))}}async function Ng(e){let t=Sg(E());m(c(e.appDir,`logs`),{recursive:!0});let n=await t.on(e.nodePath,e);return y(mg(e.appDir),{force:!0}),{itemPath:n}}async function Pg(e){let t=await Sg(E()).off(e.appDir);return m(e.appDir,{recursive:!0}),C(mg(e.appDir),new Date().toISOString(),`utf-8`),{removed:t}}var Fg=new Map,Ig=1;function Lg(){return typeof process.send==`function`}function Rg(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=Ig++;return new Promise((i,a)=>{let o=setTimeout(()=>{Fg.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);Fg.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function zg(e){typeof process.send==`function`&&(process.connected===!1?e():process.connected===!0&&process.once(`disconnect`,e)),process.on(`message`,e=>{let t=e;if(!t?.type||typeof t.id!=`number`)return;let n=Fg.get(t.id);n&&(Fg.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}async function Bg(e){let t;try{t=(await e.req.json())?.enabled}catch{return e.json({ok:!1,error:`请求体不是合法 JSON`},400)}return typeof t==`boolean`?t:e.json({ok:!1,error:`body 需为 {"enabled": true|false}`},400)}var Vg=`当前为源码运行模式,更新功能不可用(仅通过 npx ezllm install 装配的实例支持)`,Hg=`服务未由 ezllm 主进程托管,更新功能不可用;请在终端执行 npx ezllm update`,Ug=9e5;function Wg(e){let t=()=>{if(!It())return!1;if(p(c(kt(),`dist`,`cli.js`)))return!0;let e=s(Pt);return o(e)===`node_modules`||o(s(e))===`node_modules`},n=()=>{let e=El()?.autoUpdate;return typeof e!=`boolean`||e},r=()=>t()?Lg()?null:Hg:Vg,i=new M;return i.get(`/autostart`,t=>t.json({ok:!0,...Mg(e.appDir)})),i.post(`/autostart`,async t=>{let n=await Bg(t);if(n instanceof Response)return n;if(n){let{itemPath:n}=await Ng({entryJs:Bt(),args:[`--app-dir=${e.appDir}`],env:pg(),appDir:e.appDir,nodePath:process.execPath});return t.json({ok:!0,enabled:!0,itemPath:n,note:`已注册自启项,下次登录时自动启动服务`})}let{removed:r}=await Pg({appDir:e.appDir});return t.json({ok:!0,enabled:!1,removed:r,note:r?`已移除自启项,且首次启动不再自动注册(重新开启即可解除)`:`原本未开启,无操作`})}),i.get(`/update`,e=>{let r=Ut(),i=r.pending??null,a=i!==null&&Date.now()-i.startedAt<Ug;return e.json({ok:!0,enabled:n(),lastCheck:r.lastCheck??null,lastApply:r.lastApply??null,pendingUpdate:a&&i?i.toVersion:null,supported:t()&&Lg(),updating:a})}),i.post(`/update/enabled`,async e=>{let t=await Bg(e);if(t instanceof Response)return t;try{let e=El();e&&Ol({...e,autoUpdate:t})}catch{return e.json({ok:!1,error:`写入配置文件失败(文件只读或损坏)`},500)}return e.json({ok:!0,enabled:t,note:t?`自动更新已开启(主进程每小时检查一次)`:`自动更新已关闭(手动检查不受影响)`})}),i.post(`/update/check`,async e=>{let t=r();if(t)return e.json({ok:!1,error:t},400);let n=await Rg(`update.check`);return e.json({ok:!0,...n})}),i.post(`/update/apply`,async e=>{let t=r();if(t)return e.json({ok:!1,error:t},400);let n=await Rg(`update.apply`);return e.json({ok:!0,fromVersion:n.currentVersion,toVersion:n.latestVersion,hasUpdate:n.hasUpdate,updated:n.updated,...n.updated?{restarting:!0}:{},note:n.updated?`已开始更新 ${n.currentVersion} → ${n.latestVersion},服务将在安装完成后自动重启`:`已是最新版本 ${n.currentVersion}`})}),i}var Gg=`服务未由 ezllm 主进程托管(源码运行模式),托管服务不可用;请用 ezllm 启动服务`;function Kg(e){let t=(e,t)=>{let n={};return t===null?typeof e.name==`string`&&(n.name=e.name):n.name=t,typeof e.exec==`string`&&(n.exec=e.exec),typeof e.cwd==`string`&&(n.cwd=e.cwd),typeof e.autostart==`boolean`&&(n.autostart=e.autostart),typeof e.start==`boolean`&&(n.start=e.start),Array.isArray(e.args)&&(n.args=e.args.map(e=>String(e))),n},n=()=>Lg()?null:Response.json({ok:!1,error:Gg},{status:400}),r=new M;return r.onError(xp),r.get(`/`,async e=>{let t=n();if(t)return t;let r=await Rg(`svc.list`);return e.json({ok:!0,...r})}),r.post(`/`,async e=>{let r=n();if(r)return r;let i=await hp(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await Rg(`svc.create`,t(i,null));return e.json({ok:!0,...a})}),r.put(`/:name`,async e=>{let r=n();if(r)return r;let i=await hp(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await Rg(`svc.update`,t(i,e.req.param(`name`)));return e.json({ok:!0,...a})}),r.delete(`/:name`,async e=>{let t=n();if(t)return t;let r=await Rg(`svc.remove`,{name:e.req.param(`name`)});return e.json({ok:!0,...r})}),r.post(`/:name/start`,async e=>{let t=n();if(t)return t;let r=await Rg(`child.start`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r.post(`/:name/stop`,async e=>{let t=n();if(t)return t;let r=await Rg(`child.stop`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r.post(`/:name/restart`,async e=>{let t=n();if(t)return t;let r=await Rg(`child.restart`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r}var qg=`服务未由 ezllm 主进程托管(源码运行模式),插件服务开关不可用;请用 ezllm 启动服务`;function Jg(e){let t=()=>Lg()?null:Response.json({ok:!1,error:qg},{status:400}),n=new M;return n.onError(xp),n.get(`/`,async e=>{let n=t();if(n)return n;let r=await Rg(`plugin.status`);return e.json({ok:!0,available:!0,...r})}),n.post(`/enabled`,async e=>{let n=t();if(n)return n;let r=await hp(e);if(r===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);if(typeof r.enabled!=`boolean`)return e.json({ok:!1,error:`body 需为 {"enabled": true|false}`},400);let i=await Rg(r.enabled?`plugin.enable`:`plugin.disable`);return e.json({ok:!0,available:!0,...i})}),n.post(`/restart`,async e=>{let n=t();if(n)return n;let r=await Rg(`plugin.restart`);return e.json({ok:!0,available:!0,...r})}),n.post(`/auto-update`,async e=>{let n=t();if(n)return n;let r=await hp(e);if(r===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);if(typeof r.enabled!=`boolean`)return e.json({ok:!1,error:`body 需为 {"enabled": true|false}`},400);let i=await Rg(`plugin.auto-update`,{enabled:r.enabled});return e.json({ok:!0,available:!0,...i})}),n}function Yg(e){let t=`${e}.ellm-bak`;return!p(t)&&(p(e)&&f(e,t),!0)}function Xg(e){let t=`${e}.ellm-bak`;return p(t)?(f(t,e),y(t,{force:!0}),!0):!1}function Zg(e,t){return String(e||``).replace(/\/+$/,``)===String(t||``).replace(/\/+$/,``)}var Qg=c(w(),`.claude`,`settings.json`);function $g(){if(!p(Qg))return null;try{return JSON.parse(g(Qg,`utf-8`))}catch(e){throw Error(`${Qg} 不是合法 JSON,拒绝修改(请先手工修复): ${e.message}`)}}function e_(e){let t=$g();return t?Zg(t?.env?.ANTHROPIC_BASE_URL,e):!1}function t_(e){m(s(Qg),{recursive:!0});let t=$g()??{};Yg(Qg),t.env={...t.env??{}},t.env.ANTHROPIC_BASE_URL=e.gatewayBase,t.env.ANTHROPIC_AUTH_TOKEN=e.token,C(Qg,JSON.stringify(t,null,2)+`
|
|
92
|
+
`,`utf-8`)}function n_(e){if(Xg(Qg))return!0;let t=$g();return!t||!Zg(t?.env?.ANTHROPIC_BASE_URL,e)?!1:(delete t.env.ANTHROPIC_BASE_URL,delete t.env.ANTHROPIC_AUTH_TOKEN,t.env&&Object.keys(t.env).length===0&&delete t.env,C(Qg,JSON.stringify(t,null,2)+`
|
|
93
|
+
`,`utf-8`),!0)}var r_=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,i_=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(r_);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};function a_(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function o_(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
|
|
94
94
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
95
|
-
`))}return i}var Z=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
96
|
-
`,t);return e.charCodeAt(n-1)===13&&n--,n}function
|
|
97
|
-
`;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new Z(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new Z(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new Z(`unfinished string`,{toml:e.s,ptr:t})}function
|
|
98
|
-
`),i=
|
|
99
|
-
`)?`${i}\n${r}`:i+r;m(s(n),{recursive:!0}),C(n,c,`utf-8`)};if(r===`win32`)n(`setx`,[e,t]);else if(r!==`darwin`)return!1;else o(e,t,i);return process.env[e]=t,!0}function
|
|
95
|
+
`))}return i}var Z=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=a_(t.toml,t.ptr),i=o_(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};function s_(e,t=0){let n=e.indexOf(`
|
|
96
|
+
`,t);return e.charCodeAt(n-1)===13&&n--,n}function c_(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)throw new Z(`control characters are not allowed in comments`,{toml:e.s,ptr:e.p})}}function l_(e,t,n){let r;for(;;){for(;(r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10);)e.p++;if(n||r!==35)break;c_(e)}}function u_(e,t,n){let r=e.p;if(!n){r=s_(e.s,r),e.p=r<0?e.s.length:r;return}for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===35)c_(e);else if(r===n||r===t)return}throw new Z(`cannot find end of structure`,{toml:e.s,ptr:r})}var d_=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,f_=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,p_=/^[+-]?0[0-9_]/;function m_(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)throw new Z(`control characters are not allowed in strings`,{toml:e.s,ptr:e.p});else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r))return a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),c||(o+=e.s.slice(s,e.p)),e.p+=a?3:1,o;else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1){if(n===120||n===117||n===85){let t=0,r=n===120?2:n===117?4:8;for(let n=0;n<r;n++,e.p++){let n=e.s.charCodeAt(e.p+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new Z(`invalid non-hex character in unicode escape`,{toml:e.s,ptr:e.p+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new Z(`invalid unicode escape`,{toml:e.s,ptr:e.p});o+=String.fromCodePoint(t),s=e.p+1,c=0}else if(n===32||n===9)c=2;else{if(n===98)o+=`\b`;else if(n===116)o+=` `;else if(n===110)o+=`
|
|
97
|
+
`;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new Z(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new Z(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new Z(`unfinished string`,{toml:e.s,ptr:t})}function h_(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(c_({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function g_(e,t,n){let r=e.p,i={toml:e.s,ptr:r};u_(e,44,n);let a=h_(e,r,e.p);if(!a)throw new Z(`incomplete declaration: value expected`,i);if(a===`-inf`)return-1/0;if(a===`inf`||a===`+inf`)return 1/0;if(a===`nan`||a===`+nan`||a===`-nan`)return NaN;if(a===`-0`)return t?0n:0;let o=d_.test(a);if(o||f_.test(a)){if(p_.test(a))throw new Z(`leading zeroes are not allowed`,i);a=a.replace(/_/g,``);let e=+a;if(isNaN(e))throw new Z(`invalid number`,i);if(o){if((o=!Number.isSafeInteger(e))&&!t)throw new Z(`integer value cannot be represented losslessly`,i);(o||t===!0)&&(e=BigInt(a))}return e}let s=new i_(a);if(!s.isValid())throw new Z(`invalid value`,i);return s}function __(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)throw new Z(`document contains excessively nested structures. aborting.`,{toml:e.s,ptr:r});let t=i===91?x_(e,n):b_(e,n);return e.d++,t}if(i===34||i===39)return m_(e);if(i===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)throw new Z(`invalid value`,{toml:e.s,ptr:r});return e.p++,!0}if(i===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)throw new Z(`invalid value`,{toml:e.s,ptr:r});return e.p++,!1}return g_(e,n,t)}var v_=/^[a-zA-Z0-9-_]+[ \t]*$/;function y_(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.indexOf(t,n);if(a<0)throw new Z(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});do{let o=e.s.charCodeAt(e.p=++r);if(o!==32&&o!==9){if(o===34||o===39){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))throw new Z(`multiline strings are not allowed in keys`,{toml:e.s,ptr:e.p});let s=m_(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=s_(c);if(l>-1)throw new Z(`newlines are not allowed in keys`,{toml:e.s,ptr:l});if(c.trimStart())throw new Z(`found extra tokens after the string part`,{toml:e.s,ptr:e.p});if(a<e.p&&(a=e.s.indexOf(t,e.p),a<0))throw new Z(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});i.push(s)}else{r=e.s.indexOf(`.`,e.p);let t=e.s.slice(e.p,r<0||r>a?a:r);if(!v_.test(t))throw new Z(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e.s,ptr:e.p});i.push(t.trimEnd())}}}while(r+1&&r<a);return e.p=a+1,l_(e,!0,!0),i}function b_(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(l_(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=y_(e);for(let t=0;t<l.length;t++){if(t&&(o=s?o[a]:o[a]={}),a=l[t],(s=Object.hasOwn(o,a))&&(typeof o[a]!=`object`||r.has(o[a])))throw new Z(`trying to redefine an already defined value`,{toml:e.s,ptr:c});!s&&a===`__proto__`&&Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})}if(s)throw new Z(`trying to redefine an already defined value`,{toml:e.s,ptr:e.p});let u=__(e,125,t);if(r.add(o[a]=u),l_(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)throw new Z(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new Z(`unfinished table encountered`,{toml:e.s,ptr:e.p})}function x_(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(l_(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(__(e,93,t)),l_(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)throw new Z(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new Z(`unfinished array encountered`,{toml:e.s,ptr:e.p})}function S_(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function C_(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(l_(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=y_(r,`]`);if(t){if(e.charCodeAt(r.p-1)!==93)throw new Z(`expected end of table declaration`,{toml:e,ptr:r.p-1});r.p++}let l=S_(n,i,a,t?2:1);if(!l)throw new Z(`trying to redefine an already defined table or value`,{toml:e,ptr:o});c=l[2],s=l[1]}else{o=r.p;let t=S_(y_(r),s,c,0);if(!t)throw new Z(`trying to redefine an already defined table or value`,{toml:e,ptr:o});t[1][t[0]]=__(r,void 0,n)}if(l_(r,!0),r.p<e.length&&(o=e.charCodeAt(r.p))!==10&&o!==13)throw new Z(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:r.p});l_(r)}return i}var w_=`ellm-proxy`,T_=c(w(),`.codex`,`config.toml`),E_=`# >>> ellm-proxy codex switch >>>`,D_=`# <<< ellm-proxy codex switch <<<`;function O_(e){return p(e)?g(e,`utf-8`):null}function k_(){return RegExp(`${E_}[\\s\\S]*?${D_}\\n?`)}function A_(e,t,n=(e,t)=>me(e,t,{stdio:`ignore`}),r=process.platform,i=c(w(),`.zshrc`)){let a=e=>e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\$/g,`\\$`),o=(e,t,n)=>{let r=[E_,`export ${e}="${a(t)}"`,D_,``].join(`
|
|
98
|
+
`),i=O_(n)??``,o=k_(),c=o.test(i)?i.replace(o,r):i&&!i.endsWith(`
|
|
99
|
+
`)?`${i}\n${r}`:i+r;m(s(n),{recursive:!0}),C(n,c,`utf-8`)};if(r===`win32`)n(`setx`,[e,t]);else if(r!==`darwin`)return!1;else o(e,t,i);return process.env[e]=t,!0}function j_(e,t=c(w(),`.zshrc`),n=process.platform){if(n!==`darwin`)return!1;let r=O_(t),i=r?.match(k_());return!r||!i||!i[0].includes(`export ${e}=`)?!1:(C(t,r.replace(k_(),``),`utf-8`),!0)}function M_(e){try{return C_(e)?.model_provider===w_}catch{return!1}}function N_(e,t){let n;try{n=C_(e)}catch(e){throw Error(`编辑后的 config.toml 不是合法 TOML,已保留原文件: ${e.message}`)}if(t&&n?.model_provider!==w_)throw Error(`编辑后的 config.toml 顶层 model_provider 不是 "${w_}",已保留原文件`)}function P_(){let e=O_(T_);return e?M_(e):!1}function F_(e){let t=(()=>{let e=w_.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^\\s*\\[model_providers\\.(?:"|')?(?:${e}|ezllm)(?:"|')?\\]\\s*$`)})(),n=e.split(`
|
|
100
100
|
`),r=[],i=!1;for(let e of n){if(t.test(e)){i=!0;continue}i&&/^\s*\[/.test(e)&&(i=!1),i||r.push(e)}return r.join(`
|
|
101
101
|
`).replace(/\n{3,}$/,`
|
|
102
102
|
|
|
103
|
-
`)}function
|
|
104
|
-
`),n=`model_provider = "${
|
|
103
|
+
`)}function I_(e){let t=e=>{let t=e.split(`
|
|
104
|
+
`),n=`model_provider = "${w_}"`,r=!1,i=t.map(e=>!r&&/^\s*model_provider\s*=/.test(e)&&!e.trim().startsWith(`#`)?(r=!0,n):e);if(r)return i.join(`
|
|
105
105
|
`);let a=i.findIndex(e=>/^\s*\[/.test(e));return a===-1?[...i,n].join(`
|
|
106
106
|
`):(i.splice(a,0,n,``),i.join(`
|
|
107
|
-
`))};m(s(
|
|
107
|
+
`))};m(s(T_),{recursive:!0});let n=O_(T_);if(n!==null)try{C_(n)}catch(e){throw Error(`${T_} 不是合法 TOML,拒绝修改(请先手工修复): ${e.message}`)}let r=n??``;Yg(T_),r=F_(r),r=t(r);let i=[`[model_providers.${w_}]`,`name = "ezllm gateway"`,`base_url = "${e.gatewayBase}/v1"`,`wire_api = "chat"`,`env_key = "ELLM_PROXY_API_KEY"`].join(`
|
|
108
108
|
`);return r=r.replace(/\s*$/,``)+`
|
|
109
109
|
|
|
110
110
|
`+i+`
|
|
111
|
-
`,
|
|
111
|
+
`,N_(r,!0),C(T_,r,`utf-8`),e.apiKey?A_(`ELLM_PROXY_API_KEY`,e.apiKey):!1}function L_(){let e=Xg(T_),t=j_(`ELLM_PROXY_API_KEY`);if(delete process.env.ELLM_PROXY_API_KEY,e)return!0;let n=O_(T_);if(!n||!M_(n))return t;let r=F_(n);return r=r.split(`
|
|
112
112
|
`).filter(e=>!/^\s*model_provider\s*=\s*["']?ellm-proxy["']?\s*$/.test(e)).join(`
|
|
113
|
-
`),
|
|
114
|
-
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),
|
|
113
|
+
`),N_(r,!1),C(T_,r,`utf-8`),!0}var Q=D((e=>{var t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),R_=D((e=>{var t=Q(),n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),z_=D((e=>{var t=Q(),n=R_(),r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]),a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
114
|
+
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),B_=D((e=>{var t=Q(),n=R_();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),V_=D((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),H_=D((e=>{var t=Q();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),U_=D((e=>{var t=V_(),n=Q(),r=H_();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),W_=D((e=>{var t=B_(),n=R_(),r=Q(),i=U_(),a=H_(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),$=D((e=>{var t=Q(),n=U_(),r=H_(),i=e=>!e||typeof e!=`function`&&typeof e!=`object`,a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),G_=D((e=>{var t=W_(),n=Q(),r=$(),i=`tag:yaml.org,2002:`;function a(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function o(e,o,s){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=s.schema[n.MAP].createNode?.(s.schema,null,s);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:c,onAnchor:l,onTagObj:u,schema:d,sourceObjects:f}=s,p;if(c&&e&&typeof e==`object`){if(p=f.get(e),p)return p.anchor??(p.anchor=l(e)),new t.Alias(p.anchor);p={anchor:null,node:null},f.set(e,p)}o?.startsWith(`!!`)&&(o=i+o.slice(2));let m=a(e,o,d.tags);if(!m){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return p&&(p.node=t),t}m=e instanceof Map?d[n.MAP]:Symbol.iterator in Object(e)?d[n.SEQ]:d[n.MAP]}u&&(u(m),delete s.onTagObj);let h=m?.createNode?m.createNode(s.schema,e,s):typeof m?.nodeClass?.from==`function`?m.nodeClass.from(s.schema,e,s):new r.Scalar(e);return o?h.tag=o:m.default||(h.tag=m.tag),p&&(p.node=h),h}e.createNode=o})),K_=D((e=>{var t=G_(),n=Q(),r=U_();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),q_=D((e=>{var t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
115
115
|
`)?n(r,t):r.includes(`
|
|
116
116
|
`)?`
|
|
117
|
-
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),
|
|
117
|
+
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),J_=D((e=>{var t=`flow`,n=`block`,r=`quoted`;function i(e,t,i=`flow`,{indentAtStart:o,lineWidth:s=80,minContentWidth:c=20,onFold:l,onOverflow:u}={}){if(!s||s<0)return e;s<c&&(c=0);let d=Math.max(1+c,1+s-t.length);if(e.length<=d)return e;let f=[],p={},m=s-t.length;typeof o==`number`&&(o>s-Math.max(2,c)?f.push(0):m=s-o);let h,g,_=!1,v=-1,y=-1,b=-1;i===n&&(v=a(e,v,t.length),v!==-1&&(m=v+d));for(let o;o=e[v+=1];){if(i===r&&o===`\\`){switch(y=v,e[v+1]){case`x`:v+=3;break;case`u`:v+=5;break;case`U`:v+=9;break;default:v+=1}b=v}if(o===`
|
|
118
118
|
`)i===n&&(v=a(e,v,t.length)),m=v+t.length+d,h=void 0;else{if(o===` `&&g&&g!==` `&&g!==`
|
|
119
119
|
`&&g!==` `){let t=e[v+1];t&&t!==` `&&t!==`
|
|
120
120
|
`&&t!==` `&&(h=v)}if(v>=m){if(h)f.push(h),m=h+d,h=void 0;else if(i===r){for(;g===` `||g===` `;)g=o,o=e[v+=1],_=!0;let t=v>b+1?v-2:y-1;if(p[t])return e;f.push(t),p[t]=!0,m=t+d,h=void 0}else _=!0}}g=o}if(_&&u&&u(),f.length===0)return e;l&&l();let x=e.slice(0,f[0]);for(let n=0;n<f.length;++n){let a=f[n],o=f[n+1]||e.length;a===0?x=`\n${t}${e.slice(0,o)}`:(i===r&&p[a]&&(x+=`${e[a]}\\`),x+=`\n${t}${e.slice(a+1,o)}`)}return x}function a(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
121
|
-
`);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i})),
|
|
121
|
+
`);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i})),Y_=D((e=>{var t=$(),n=J_(),r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),i=e=>/^(%|---|\.\.\.)/m.test(e);function a(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
|
|
122
122
|
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function o(e,t){let a=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return a;let{implicitKey:o}=t,s=t.options.doubleQuotedMinMultiLineLength,c=t.indent||(i(e)?` `:``),l=``,u=0;for(let e=0,t=a[e];t;t=a[++e])if(t===` `&&a[e+1]===`\\`&&a[e+2]===`n`&&(l+=a.slice(u,e)+`\\ `,e+=1,u=e,t=`\\`),t===`\\`)switch(a[e+1]){case`u`:{l+=a.slice(u,e);let t=a.substr(e+2,4);switch(t){case`0000`:l+=`\\0`;break;case`0007`:l+=`\\a`;break;case`000b`:l+=`\\v`;break;case`001b`:l+=`\\e`;break;case`0085`:l+=`\\N`;break;case`00a0`:l+=`\\_`;break;case`2028`:l+=`\\L`;break;case`2029`:l+=`\\P`;break;default:t.substr(0,2)===`00`?l+=`\\x`+t.substr(2):l+=a.substr(e,6)}e+=5,u=e+1}break;case`n`:if(o||a[e+2]===`"`||a.length<s)e+=1;else{for(l+=a.slice(u,e)+`
|
|
123
123
|
|
|
124
124
|
`;a[e+2]===`\\`&&a[e+3]===`n`&&a[e+4]!==`"`;)l+=`
|
|
@@ -136,29 +136,29 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
136
136
|
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${g}`),i=!1,a=r(u,!0);p!==`folded`&&o!==t.Scalar.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let c=n.foldFlowLines(`${T}${e}${b}`,g,n.FOLD_BLOCK,a);if(!i)return`>${E}\n${g}${c}`}return s=s.replace(/\n+/g,`$&${g}`),`|${E}\n${g}${T}${s}${b}`}function d(e,a,o,s){let{type:l,value:d}=e,{actualString:f,implicitKey:p,indent:m,indentStep:h,inFlow:g}=a;if(p&&d.includes(`
|
|
137
137
|
`)||g&&/[[\]{},]/.test(d))return c(d,a);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(d))return p||g||!d.includes(`
|
|
138
138
|
`)?c(d,a):u(e,a,o,s);if(!p&&!g&&l!==t.Scalar.PLAIN&&d.includes(`
|
|
139
|
-
`))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),
|
|
139
|
+
`))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),X_=D((e=>{var t=B_(),n=Q(),r=q_(),i=Y_();function a(e,t){let n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case`block`:i=!1;break;case`flow`:i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:i,options:n}}function o(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let r,i;if(n.isScalar(t)){i=t.value;let n=e.filter(e=>e.identify?.(i));if(n.length>1){let e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else i=t,r=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!r){let e=i?.constructor?.name??(i===null?`null`:typeof i);throw Error(`Tag not resolved for ${e} value`)}return r}function s(e,r,{anchors:i,doc:a}){if(!a.directives)return``;let o=[],s=(n.isScalar(e)||n.isCollection(e))&&e.anchor;s&&t.anchorIsValid(s)&&(i.add(s),o.push(`&${s}`));let c=e.tag??(r.default?null:r.tag);return c&&o.push(a.directives.tagString(c)),o.join(` `)}function c(e,t,r,a){if(n.isPair(e))return e.toString(t,r,a);if(n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let c,l=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>c=e});c??=o(t.doc.schema.tags,l);let u=s(l,c,t);u.length>0&&(t.indentAtStart=(t.indentAtStart??0)+u.length+1);let d=typeof c.stringify==`function`?c.stringify(l,t,r,a):n.isScalar(l)?i.stringifyString(l,t,r,a):l.toString(t,r,a);return u?n.isScalar(l)||d[0]===`{`||d[0]===`[`?`${u} ${d}`:`${u}\n${t.indent}${d}`:d}e.createStringifyContext=a,e.stringify=c})),Z_=D((e=>{var t=Q(),n=$(),r=X_(),i=q_();function a({key:e,value:a},o,s,c){let{allNullValues:l,doc:u,indent:d,indentStep:f,options:{commentString:p,indentSeq:m,simpleKeys:h}}=o,g=t.isNode(e)&&e.comment||null;if(h){if(g)throw Error(`With simple keys, key nodes cannot have comments`);if(t.isCollection(e)||!t.isNode(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let _=!h&&(!e||g&&a==null&&!o.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:typeof e==`object`));o=Object.assign({},o,{allNullValues:!1,implicitKey:!_&&(h||!l),indent:d+f});let v=!1,y=!1,b=r.stringify(e,o,()=>v=!0,()=>y=!0);if(!_&&!o.inFlow&&b.length>1024){if(h)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);_=!0}if(o.inFlow){if(l||a==null)return v&&s&&s(),b===``?`?`:_?`? ${b}`:b}else if(l&&!h||a==null&&_)return b=`? ${b}`,g&&!v?b+=i.lineComment(b,o.indent,p(g)):y&&c&&c(),b;v&&(g=null),_?(g&&(b+=i.lineComment(b,o.indent,p(g))),b=`? ${b}\n${d}:`):(b=`${b}:`,g&&(b+=i.lineComment(b,o.indent,p(g))));let x,S,C;t.isNode(a)?(x=!!a.spaceBefore,S=a.commentBefore,C=a.comment):(x=!1,S=null,C=null,a&&typeof a==`object`&&(a=u.createNode(a))),o.implicitKey=!1,!_&&!g&&t.isScalar(a)&&(o.indentAtStart=b.length+1),y=!1,!m&&f.length>=2&&!o.inFlow&&!_&&t.isSeq(a)&&!a.flow&&!a.tag&&!a.anchor&&(o.indent=o.indent.substring(2));let w=!1,T=r.stringify(a,o,()=>w=!0,()=>y=!0),E=` `;if(g||x||S){if(E=x?`
|
|
140
140
|
`:``,S){let e=p(S);E+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?E===`
|
|
141
141
|
`&&C&&(E=`
|
|
142
142
|
|
|
143
143
|
`):E+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
|
|
144
144
|
`),n=t!==-1,r=o.inFlow??a.flow??a.items.length===0;if(n||!r){let r=!1;if(n&&(e===`&`||e===`!`)){let n=T.indexOf(` `);e===`&`&&n!==-1&&n<t&&T[n+1]===`!`&&(n=T.indexOf(` `,n+1)),(n===-1||t<n)&&(r=!0)}r||(E=`\n${o.indent}`)}}else(T===``||T[0]===`
|
|
145
|
-
`)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=a})),
|
|
145
|
+
`)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=a})),Q_=D((e=>{var t=xe(`process`);function n(e,...t){e===`debug`&&console.log(...t)}function r(e,n){(e===`debug`||e===`warn`)&&(typeof t.emitWarning==`function`?t.emitWarning(n):console.warn(n))}e.debug=n,e.warn=r})),$_=D((e=>{var t=Q(),n=$(),r=`<<`,i={identify:e=>e===r||typeof e==`symbol`&&e.description===r,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(r)),{addToJSMap:o}),stringify:()=>r},a=(e,r)=>(i.identify(r)||t.isScalar(r)&&(!r.type||r.type===n.Scalar.PLAIN)&&i.identify(r.value))&&e?.doc.schema.tags.some(e=>e.tag===i.tag&&e.default);function o(e,n,r){let i=c(e,r);if(t.isSeq(i))for(let t of i.items)s(e,n,t);else if(Array.isArray(i))for(let t of i)s(e,n,t);else s(e,n,i)}function s(e,n,r){let i=c(e,r);if(!t.isMap(i))throw Error(`Merge sources must be maps or map aliases`);let a=i.toJSON(null,e,Map);for(let[e,t]of a)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}function c(e,n){return e&&t.isAlias(n)?n.resolve(e.doc,e):n}e.addMergeToJSMap=o,e.isMergeKey=a,e.merge=i})),ev=D((e=>{var t=Q_(),n=$_(),r=X_(),i=Q(),a=H_();function o(e,t,{key:r,value:o}){if(i.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,o);else{let n=a.toJS(r,``,e);if(t instanceof Map)t.set(n,a.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=s(r,n,e),c=a.toJS(o,i,e);i in t?Object.defineProperty(t,i,{value:c,writable:!0,enumerable:!0,configurable:!0}):t[i]=c}}return t}function s(e,n,a){if(n===null)return``;if(typeof n!=`object`)return String(n);if(i.isNode(e)&&a?.doc){let n=r.createStringifyContext(a.doc,{});n.anchors=new Set;for(let e of a.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!a.mapKeyWarned){let e=JSON.stringify(i);e.length>40&&(e=e.substring(0,36)+`..."`),t.warn(a.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),a.mapKeyWarned=!0}return i}return JSON.stringify(n)}e.addPairToJSMap=o})),tv=D((e=>{var t=G_(),n=Z_(),r=ev(),i=Q();function a(e,n,r){return new o(t.createNode(e,void 0,r),t.createNode(n,void 0,r))}var o=class e{constructor(e,t=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return i.isNode(n)&&(n=n.clone(t)),i.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=o,e.createPair=a})),nv=D((e=>{var t=Q(),n=X_(),r=q_();function i(e,t,n){return(t.inFlow??e.flow?o:a)(e,t,n)}function a({comment:e,items:i},a,{blockItemPrefix:o,flowChars:c,itemIndent:l,onChompKeep:u,onComment:d}){let{indent:f,options:{commentString:p}}=a,m=Object.assign({},a,{indent:l,type:null}),h=!1,g=[];for(let e=0;e<i.length;++e){let c=i[e],u=null;if(t.isNode(c))!h&&c.spaceBefore&&g.push(``),s(a,g,c.commentBefore,h),c.comment&&(u=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(!h&&e.spaceBefore&&g.push(``),s(a,g,e.commentBefore,h))}h=!1;let d=n.stringify(c,m,()=>u=null,()=>h=!0);u&&(d+=r.lineComment(d,l,p(u))),h&&u&&(h=!1),g.push(o+d)}let _;if(g.length===0)_=c.start+c.end;else{_=g[0];for(let e=1;e<g.length;++e){let t=g[e];_+=t?`\n${f}${t}`:`
|
|
146
146
|
`}}return e?(_+=`
|
|
147
147
|
`+r.indentComment(p(e),f),d&&d()):h&&u&&u(),_}function o({items:e},i,{flowChars:a,itemIndent:o}){let{indent:c,indentStep:l,flowCollectionPadding:u,options:{commentString:d}}=i;o+=l;let f=Object.assign({},i,{indent:o,inFlow:!0,type:null}),p=!1,m=0,h=[];for(let a=0;a<e.length;++a){let c=e[a],l=null;if(t.isNode(c))c.spaceBefore&&h.push(``),s(i,h,c.commentBefore,!1),c.comment&&(l=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(e.spaceBefore&&h.push(``),s(i,h,e.commentBefore,!1),e.comment&&(p=!0));let n=t.isNode(c.value)?c.value:null;n?(n.comment&&(l=n.comment),n.commentBefore&&(p=!0)):c.value==null&&e?.comment&&(l=e.comment)}l&&(p=!0);let u=n.stringify(c,f,()=>l=null);p||=h.length>m||u.includes(`
|
|
148
148
|
`),a<e.length-1?u+=`,`:i.options.trailingComma&&(i.options.lineWidth>0&&(p||=h.reduce((e,t)=>e+t.length+2,2)+(u.length+2)>i.options.lineWidth),p&&(u+=`,`)),l&&(u+=r.lineComment(u,o,d(l))),h.push(u),m=h.length}let{start:g,end:_}=a;if(h.length===0)return g+_;if(!p){let e=h.reduce((e,t)=>e+t.length+2,2);p=i.options.lineWidth>0&&e>i.options.lineWidth}if(p){let e=g;for(let t of h)e+=t?`\n${l}${c}${t}`:`
|
|
149
|
-
`;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),
|
|
150
|
-
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),mv=D((e=>{var t=Q(),n=$_(),r=$(),i=rv();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}var s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),hv=D((e=>{var t=Q(),n=B_(),r=tv(),i=rv(),a=mv(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;var s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),gv=D((e=>{var t=$();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var r={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),_v=D((e=>{var t=$(),n=cv(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),vv=D((e=>{var t=cv(),n=e=>typeof e==`bigint`||Number.isInteger(e);function r(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}var a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),yv=D((e=>{var t=Q(),n=$_(),r=tv(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;var a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),bv=D((e=>{var t=cv();function n(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var i={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>n(e,r),stringify:r},a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>n(e,!1),stringify:r},o={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),xv=D((e=>{var t=nv(),n=ov(),r=iv(),i=av(),a=pv(),o=gv(),s=_v(),c=vv(),l=Z_(),u=hv(),d=mv(),f=yv(),p=bv();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),Sv=D((e=>{var t=nv(),n=ov(),r=iv(),i=av(),a=sv(),o=lv(),s=uv(),c=dv(),l=fv(),u=pv(),d=Z_(),f=hv(),p=mv(),m=xv(),h=yv(),g=bv(),_=new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),Cv=D((e=>{var t=Q(),n=nv(),r=iv(),i=av(),a=Sv(),o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),wv=D((e=>{var t=Q(),n=J_(),r=G_();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
|
|
149
|
+
`;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),rv=D((e=>{var t=nv(),n=ev(),r=K_(),i=Q(),a=tv(),o=$();function s(e,t){let n=i.isScalar(t)?t.value:t;for(let r of e)if(i.isPair(r)&&(r.key===t||r.key===n||i.isScalar(r.key)&&r.key.value===n))return r}e.YAMLMap=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(i.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),s=(e,s)=>{if(typeof i==`function`)s=i.call(t,e,s);else if(Array.isArray(i)&&!i.includes(e))return;(s!==void 0||r)&&o.items.push(a.createPair(e,s,n))};if(t instanceof Map)for(let[e,n]of t)s(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))s(e,t[e]);return typeof e.sortMapEntries==`function`&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;n=i.isPair(e)?e:!e||typeof e!=`object`||!(`key`in e)?new a.Pair(e,e?.value):new a.Pair(e.key,e.value);let r=s(this.items,n.key),c=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);i.isScalar(r.value)&&o.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(c){let e=this.items.findIndex(e=>c(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=s(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=s(this.items,e)?.value;return(!t&&i.isScalar(n)?n.value:n)??void 0}has(e){return!!s(this.items,e)}set(e,t){this.add(new a.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let e of this.items)n.addPairToJSMap(t,i,e);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let e of this.items)if(!i.isPair(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),t.stringifyCollection(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:r,onComment:n})}},e.findPair=s})),iv=D((e=>{var t=Q(),n=rv();e.map={collection:`map`,default:!0,nodeClass:n.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(e,n){return t.isMap(e)||n(`Expected a mapping for this tag`),e},createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)}})),av=D((e=>{var t=G_(),n=nv(),r=K_(),i=Q(),a=$(),o=H_(),s=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(i.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=c(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=c(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&i.isScalar(r)?r.value:r}has(e){let t=c(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=c(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];i.isScalar(r)&&a.isScalarValue(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(o.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,a=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let o of n){if(typeof i==`function`){let t=n instanceof Set?o:String(e++);o=i.call(n,t,o)}a.items.push(t.createNode(o,void 0,r))}}return a}};function c(e){let t=i.isScalar(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=s})),ov=D((e=>{var t=Q(),n=av();e.seq={collection:`seq`,default:!0,nodeClass:n.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(e,n){return t.isSeq(e)||n(`Expected a sequence for this tag`),e},createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)}})),sv=D((e=>{var t=Y_();e.string={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,n,r,i){return n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,i)}}})),cv=D((e=>{var t=$(),n={identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>typeof e==`string`&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n})),lv=D((e=>{var t=$(),n={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},r){return e&&n.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?r.options.trueStr:r.options.falseStr}};e.boolTag=n})),uv=D((e=>{function t({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}e.stringifyNumber=t})),dv=D((e=>{var t=$(),n=uv(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let n=new t.Scalar(parseFloat(e)),r=e.indexOf(`.`);return r!==-1&&e[e.length-1]===`0`&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),fv=D((e=>{var t=uv(),n=e=>typeof e==`bigint`||Number.isInteger(e),r=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function i(e,r,i){let{value:a}=e;return n(a)&&a>=0?i+a.toString(r):t.stringifyNumber(e)}e.int={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},e.intHex={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)},e.intOct={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>r(e,2,8,n),stringify:e=>i(e,8,`0o`)}})),pv=D((e=>{var t=iv(),n=cv(),r=ov(),i=sv(),a=lv(),o=dv(),s=fv();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),mv=D((e=>{var t=$(),n=iv(),r=ov();function i(e){return typeof e==`bigint`||Number.isInteger(e)}var a=({value:e})=>JSON.stringify(e),o=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:a},{identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:a},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:a},{identify:i,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>i(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:a}];e.schema=[n.map,r.seq].concat(o,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),hv=D((e=>{var t=xe(`buffer`),n=$(),r=Y_();e.binary={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,n){if(typeof t.Buffer==`function`)return t.Buffer.from(e,`base64`);if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return n(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:i,value:a},o,s,c){if(!a)return``;let l=a,u;if(typeof t.Buffer==`function`)u=l instanceof t.Buffer?l.toString(`base64`):t.Buffer.from(l.buffer).toString(`base64`);else if(typeof btoa==`function`){let e=``;for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);u=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(i??=n.Scalar.BLOCK_LITERAL,i!==n.Scalar.QUOTE_DOUBLE){let e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),t=Math.ceil(u.length/e),r=Array(t);for(let n=0,i=0;n<t;++n,i+=e)r[n]=u.substr(i,e);u=r.join(i===n.Scalar.BLOCK_LITERAL?`
|
|
150
|
+
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),gv=D((e=>{var t=Q(),n=tv(),r=$(),i=av();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}var s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),_v=D((e=>{var t=Q(),n=H_(),r=rv(),i=av(),a=gv(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;var s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),vv=D((e=>{var t=$();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var r={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),yv=D((e=>{var t=$(),n=uv(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),bv=D((e=>{var t=uv(),n=e=>typeof e==`bigint`||Number.isInteger(e);function r(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}var a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),xv=D((e=>{var t=Q(),n=tv(),r=rv(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;var a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),Sv=D((e=>{var t=uv();function n(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var i={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>n(e,r),stringify:r},a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>n(e,!1),stringify:r},o={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),Cv=D((e=>{var t=iv(),n=cv(),r=ov(),i=sv(),a=hv(),o=vv(),s=yv(),c=bv(),l=$_(),u=_v(),d=gv(),f=xv(),p=Sv();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),wv=D((e=>{var t=iv(),n=cv(),r=ov(),i=sv(),a=lv(),o=dv(),s=fv(),c=pv(),l=mv(),u=hv(),d=$_(),f=_v(),p=gv(),m=Cv(),h=xv(),g=Sv(),_=new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),Tv=D((e=>{var t=Q(),n=iv(),r=ov(),i=sv(),a=wv(),o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),Ev=D((e=>{var t=Q(),n=X_(),r=q_();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
|
|
151
151
|
`)?(a.push(`...`),a.push(r.indentComment(t,``))):a.push(`... ${t}`)}else a.push(`...`)}else{let t=e.comment;t&&l&&(t=t.replace(/^\n+/,``)),t&&((!l||u)&&a[a.length-1]!==``&&a.push(``),a.push(r.indentComment(c(t),``)))}return a.join(`
|
|
152
152
|
`)+`
|
|
153
|
-
`}e.stringifyDocument=i})),
|
|
154
|
-
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}})),
|
|
155
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),
|
|
153
|
+
`}e.stringifyDocument=i})),Dv=D((e=>{var t=W_(),n=K_(),r=Q(),i=tv(),a=H_(),o=Tv(),s=Ev(),c=B_(),l=V_(),u=G_(),d=z_(),f=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;typeof t==`function`||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new d.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let t=Object.create(e.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=r.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){p(this.contents)&&this.contents.add(e)}addIn(e,t){p(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){let t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||`a`,t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let i;if(typeof t==`function`)e=t.call({"":e},``,e),i=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:d,tag:f}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:h}=c.createNodeAnchors(this,o||`a`),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:p,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:h},_=u.createNode(e,f,g);return s&&r.isCollection(_)&&(_.flow=!0),m(),_}createPair(e,t,n={}){let r=this.createNode(e,null,n),a=this.createNode(t,null,n);return new i.Pair(r,a)}delete(e){return p(this.contents)?this.contents.delete(e):!1}deleteIn(e){return n.isEmptyPath(e)?this.contents!=null&&(this.contents=null,!0):p(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return r.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return n.isEmptyPath(e)?this.contents!==void 0:r.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=n.collectionFromPath(this.schema,[e],t):p(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):p(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new d.Directives({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new d.Directives({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new o.Schema(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},c=a.toJS(this.contents,t??``,s);if(typeof i==`function`)for(let{count:e,res:t}of s.anchors.values())i(t,e);return typeof o==`function`?l.applyReviver(o,{"":c},``,c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return s.stringifyDocument(this,e)}};function p(e){if(r.isCollection(e))return!0;throw Error(`Expected a YAML collection as document contents`)}e.Document=f})),Ov=D((e=>{var t=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},n=class extends t{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},r=class extends t{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
|
|
154
|
+
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}})),kv=D((e=>{function t(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}e.resolveProps=t})),Av=D((e=>{function t(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
|
|
155
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),jv=D((e=>{var t=Av();function n(e,n,r){if(n?.type===`flow-collection`){let i=n.end[0];i.indent===e&&(i.source===`]`||i.source===`}`)&&t.containsNewline(n)&&r(i,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}e.flowIndentCheck=n})),Mv=D((e=>{var t=Q();function n(e,n,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let a=typeof i==`function`?i:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>a(e.key,r))}e.mapIncludes=n})),Nv=D((e=>{var t=tv(),n=rv(),r=kv(),i=Av(),a=jv(),o=Mv(),s=`All mapping items must start at the same column`;function c({composeNode:e,composeEmptyNode:c},l,u,d,f){let p=new((f?.nodeClass)??n.YAMLMap)(l.schema);l.atRoot&&=!1;let m=u.offset,h=null;for(let n of u.items){let{start:f,key:g,sep:_,value:v}=n,y=r.resolveProps(f,{indicator:`explicit-key-ind`,next:g??_?.[0],offset:m,onError:d,parentIndent:u.indent,startOnNewline:!0}),b=!y.found;if(b){if(g&&(g.type===`block-seq`?d(m,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in g&&g.indent!==u.indent&&d(m,`BAD_INDENT`,s)),!y.anchor&&!y.tag&&!_){h=y.end,y.comment&&(p.comment?p.comment+=`
|
|
156
156
|
`+y.comment:p.comment=y.comment);continue}(y.newlineAfterProp||i.containsNewline(g))&&d(g??f[f.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else y.found?.indent!==u.indent&&d(m,`BAD_INDENT`,s);l.atKey=!0;let x=y.end,S=g?e(l,g,y,d):c(l,x,f,null,y,d);l.schema.compat&&a.flowIndentCheck(u.indent,g,d),l.atKey=!1,o.mapIncludes(l,p.items,S)&&d(x,`DUPLICATE_KEY`,`Map keys must be unique`);let C=r.resolveProps(_??[],{indicator:`map-value-ind`,next:v,offset:S.range[2],onError:d,parentIndent:u.indent,startOnNewline:!g||g.type===`block-scalar`});if(m=C.end,C.found){b&&(v?.type===`block-map`&&!C.hasNewline&&d(m,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),l.options.strict&&y.start<C.found.offset-1024&&d(S.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let r=v?e(l,v,C,d):c(l,m,_,null,C,d);l.schema.compat&&a.flowIndentCheck(u.indent,v,d),m=r.range[2];let i=new t.Pair(S,r);l.options.keepSourceTokens&&(i.srcToken=n),p.items.push(i)}else{b&&d(S.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),C.comment&&(S.comment?S.comment+=`
|
|
157
|
-
`+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),
|
|
157
|
+
`+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),Pv=D((e=>{var t=av(),n=kv(),r=jv();function i({composeNode:e,composeEmptyNode:i},a,o,s,c){let l=new((c?.nodeClass)??t.YAMLSeq)(a.schema);a.atRoot&&=!1,a.atKey&&=!1;let u=o.offset,d=null;for(let{start:t,value:c}of o.items){let f=n.resolveProps(t,{indicator:`seq-item-ind`,next:c,offset:u,onError:s,parentIndent:o.indent,startOnNewline:!0});if(!f.found){if(f.anchor||f.tag||c)c?.type===`block-seq`?s(f.end,`BAD_INDENT`,`All sequence items must start at the same column`):s(u,`MISSING_CHAR`,`Sequence item without - indicator`);else{d=f.end,f.comment&&(l.comment=f.comment);continue}}let p=c?e(a,c,f,s):i(a,f.end,t,null,f,s);a.schema.compat&&r.flowIndentCheck(o.indent,c,s),u=p.range[2],l.items.push(p)}return l.range=[o.offset,u,d??u],l}e.resolveBlockSeq=i})),Fv=D((e=>{function t(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}e.resolveEnd=t})),Iv=D((e=>{var t=Q(),n=tv(),r=rv(),i=av(),a=Fv(),o=kv(),s=Av(),c=Mv(),l=`Block collections are not allowed within flow collections`,u=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function d({composeNode:e,composeEmptyNode:d},f,p,m,h){let g=p.start.source===`{`,_=g?`flow map`:`flow sequence`,v=new((h?.nodeClass)??(g?r.YAMLMap:i.YAMLSeq))(f.schema);v.flow=!0;let y=f.atRoot;y&&(f.atRoot=!1),f.atKey&&=!1;let b=p.offset+p.start.source.length;for(let i=0;i<p.items.length;++i){let a=p.items[i],{start:h,key:y,sep:x,value:S}=a,C=o.resolveProps(h,{flow:_,indicator:`explicit-key-ind`,next:y??x?.[0],offset:b,onError:m,parentIndent:p.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!x&&!S){i===0&&C.comma?m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`):i<p.items.length-1&&m(C.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${_}`),C.comment&&(v.comment?v.comment+=`
|
|
158
158
|
`+C.comment:v.comment=C.comment),b=C.end;continue}!g&&f.options.strict&&s.containsNewline(y)&&m(y,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(i===0)C.comma&&m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`);else if(C.comma||m(C.start,`MISSING_CHAR`,`Missing , between ${_} items`),C.comment){let e=``;loop:for(let t of h)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let n=v.items[v.items.length-1];t.isPair(n)&&(n=n.value??n.key),n.comment?n.comment+=`
|
|
159
159
|
`+e:n.comment=e,C.comment=C.comment.substring(e.length+1)}}if(!g&&!x&&!C.found){let t=S?e(f,S,C,m):d(f,C.end,x,null,C,m);v.items.push(t),b=t.range[2],u(S)&&m(t.range,`BLOCK_IN_FLOW`,l)}else{f.atKey=!0;let t=C.end,i=y?e(f,y,C,m):d(f,t,h,null,C,m);u(y)&&m(i.range,`BLOCK_IN_FLOW`,l),f.atKey=!1;let s=o.resolveProps(x??[],{flow:_,indicator:`map-value-ind`,next:S,offset:i.range[2],onError:m,parentIndent:p.indent,startOnNewline:!1});if(s.found){if(!g&&!C.found&&f.options.strict){if(x)for(let e of x){if(e===s.found)break;if(e.type===`newline`){m(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}C.start<s.found.offset-1024&&m(s.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else S&&(`source`in S&&S.source?.[0]===`:`?m(S,`MISSING_CHAR`,`Missing space after : in ${_}`):m(s.start,`MISSING_CHAR`,`Missing , or : between ${_} items`));let w=S?e(f,S,s,m):s.found?d(f,s.end,x,null,s,m):null;w?u(S)&&m(w.range,`BLOCK_IN_FLOW`,l):s.comment&&(i.comment?i.comment+=`
|
|
160
160
|
`+s.comment:i.comment=s.comment);let T=new n.Pair(i,w);if(f.options.keepSourceTokens&&(T.srcToken=a),g){let e=v;c.mapIncludes(f,e.items,i)&&m(t,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(T)}else{let e=new r.YAMLMap(f.schema);e.flow=!0,e.items.push(T);let t=(w??i).range;e.range=[i.range[0],t[1],t[2]],v.items.push(e)}b=w?w.range[2]:s.end}}let x=g?`}`:`]`,[S,...C]=p.end,w=b;if(S?.source===x)w=S.offset+S.source.length;else{let e=_[0].toUpperCase()+_.substring(1),t=y?`${e} must end with a ${x}`:`${e} in block collection must be sufficiently indented and end with a ${x}`;m(b,y?`MISSING_CHAR`:`BAD_INDENT`,t),S&&S.source.length!==1&&C.unshift(S)}if(C.length>0){let e=a.resolveEnd(C,w,f.options.strict,m);e.comment&&(v.comment?v.comment+=`
|
|
161
|
-
`+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),
|
|
161
|
+
`+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),Lv=D((e=>{var t=Q(),n=$(),r=rv(),i=av(),a=Nv(),o=Pv(),s=Iv();function c(e,t,n,r,i,c){let l=n.type===`block-map`?a.resolveBlockMap(e,t,n,r,c):n.type===`block-seq`?o.resolveBlockSeq(e,t,n,r,c):s.resolveFlowCollection(e,t,n,r,c),u=l.constructor;return i===`!`||i===u.tagName?(l.tag=u.tagName,l):(i&&(l.tag=i),l)}function l(e,a,o,s,l){let u=s.tag,d=u?a.directives.tagName(u.source,e=>l(u,`TAG_RESOLVE_FAILED`,e)):null;if(o.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=s,n=e&&u?e.offset>u.offset?e:u:e??u;n&&(!t||t.offset<n.offset)&&l(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let f=o.type===`block-map`?`map`:o.type===`block-seq`?`seq`:o.start.source===`{`?`map`:`seq`;if(!u||!d||d===`!`||d===r.YAMLMap.tagName&&f===`map`||d===i.YAMLSeq.tagName&&f===`seq`)return c(e,a,o,l,d);let p=a.schema.tags.find(e=>e.tag===d&&e.collection===f);if(!p){let t=a.schema.knownTags[d];if(t?.collection===f)a.schema.tags.push(Object.assign({},t,{default:!1})),p=t;else return t?l(u,`BAD_COLLECTION_TYPE`,`${t.tag} used for ${f} collection, but expects ${t.collection??`scalar`}`,!0):l(u,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${d}`,!0),c(e,a,o,l,d)}let m=c(e,a,o,l,d,p),h=p.resolve?.(m,e=>l(u,`TAG_RESOLVE_FAILED`,e),a.options)??m,g=t.isNode(h)?h:new n.Scalar(h);return g.range=m.range,g.tag=d,p?.format&&(g.format=p.format),g}e.composeCollection=l})),Rv=D((e=>{var t=$();function n(e,n,a){let o=n.offset,s=r(n,e.options.strict,a);if(!s)return{value:``,type:null,comment:``,range:[o,o,o]};let c=s.mode===`>`?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,l=n.source?i(n.source):[],u=l.length;for(let e=l.length-1;e>=0;--e){let t=l[e][1];if(t===``||t===`\r`)u=e;else break}if(u===0){let e=s.chomp===`+`&&l.length>0?`
|
|
162
162
|
`.repeat(Math.max(1,l.length-1)):``,t=o+s.length;return n.source&&(t+=n.source.length),{value:e,type:c,comment:s.comment,range:[o,t,t]}}let d=n.indent+s.indent,f=n.offset+s.length,p=0;for(let t=0;t<u;++t){let[n,r]=l[t];if(r===``||r===`\r`)s.indent===0&&n.length>d&&(d=n.length);else{n.length<d&&a(f+n.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),s.indent===0&&(d=n.length),p=t,d===0&&!e.atRoot&&a(f,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}f+=n.length+r.length+1}for(let e=l.length-1;e>=u;--e)l[e][0].length>d&&(u=e+1);let m=``,h=``,g=!1;for(let e=0;e<p;++e)m+=l[e][0].slice(d)+`
|
|
163
163
|
`;for(let e=p;e<u;++e){let[n,r]=l[e];f+=n.length+r.length+1;let i=r[r.length-1]===`\r`;if(i&&(r=r.slice(0,-1)),r&&n.length<d){let e=`Block scalar lines must not be less indented than their ${s.indent?`explicit indentation indicator`:`first line`}`;a(f-r.length-(i?2:1),`BAD_INDENT`,e),n=``}c===t.Scalar.BLOCK_LITERAL?(m+=h+n.slice(d)+r,h=`
|
|
164
164
|
`):n.length>d||r[0]===` `?(h===` `?h=`
|
|
@@ -173,7 +173,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
173
173
|
`+l[e][0].slice(d);m[m.length-1]!==`
|
|
174
174
|
`&&(m+=`
|
|
175
175
|
`);break;default:m+=`
|
|
176
|
-
`}let _=o+s.length+n.source.length;return{value:m,type:c,comment:s.comment,range:[o,_,_]}}function r({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function i(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=n})),
|
|
176
|
+
`}let _=o+s.length+n.source.length;return{value:m,type:c,comment:s.comment,range:[o,_,_]}}function r({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function i(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=n})),zv=D((e=>{var t=$(),n=Fv();function r(e,r,o){let{offset:c,type:l,source:u,end:d}=e,f,p,m=(e,t,n)=>o(c+e,t,n);switch(l){case`scalar`:f=t.Scalar.PLAIN,p=i(u,m);break;case`single-quoted-scalar`:f=t.Scalar.QUOTE_SINGLE,p=a(u,m);break;case`double-quoted-scalar`:f=t.Scalar.QUOTE_DOUBLE,p=s(u,m);break;default:return o(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${l}`),{value:``,type:null,comment:``,range:[c,c+u.length,c+u.length]}}let h=c+u.length,g=n.resolveEnd(d,h,r,o);return{value:p,type:f,comment:g.comment,range:[c,h,g.offset]}}function i(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),o(e)}function a(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),o(e.slice(1,-1)).replace(/''/g,`'`)}function o(e){let t,n;try{t=RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
177
177
|
`,`sy`),n=RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
178
178
|
`,`sy`)}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],a=` `,o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)r[1]===``?a===`
|
|
179
179
|
`?i+=a:a=`
|
|
@@ -188,10 +188,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
188
188
|
`);)r===`
|
|
189
189
|
`&&(n+=`
|
|
190
190
|
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var l={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
|
|
191
|
-
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=r})),
|
|
191
|
+
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=r})),Bv=D((e=>{var t=Q(),n=$(),r=Rv(),i=zv();function a(e,a,c,l){let{value:u,type:d,comment:f,range:p}=a.type===`block-scalar`?r.resolveBlockScalar(e,a,l):i.resolveFlowScalar(a,e.options.strict,l),m=c?e.directives.tagName(c.source,e=>l(c,`TAG_RESOLVE_FAILED`,e)):null,h;h=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:m?o(e.schema,u,m,c,l):a.type===`scalar`?s(e,u,a,l):e.schema[t.SCALAR];let g;try{let r=h.resolve(u,e=>l(c??a,`TAG_RESOLVE_FAILED`,e),e.options);g=t.isScalar(r)?r:new n.Scalar(r)}catch(e){let t=e instanceof Error?e.message:String(e);l(c??a,`TAG_RESOLVE_FAILED`,t),g=new n.Scalar(u)}return g.range=p,g.source=u,d&&(g.type=d),m&&(g.tag=m),h.format&&(g.format=h.format),f&&(g.comment=f),g}function o(e,n,r,i,a){if(r===`!`)return e[t.SCALAR];let o=[];for(let t of e.tags)if(!t.collection&&t.tag===r){if(t.default&&t.test)o.push(t);else return t}for(let e of o)if(e.test?.test(n))return e;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(i,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${r}`,r!==`tag:yaml.org,2002:str`),e[t.SCALAR])}function s({atKey:e,directives:n,schema:r},i,a,o){let s=r.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(i))||r[t.SCALAR];if(r.compat){let e=r.compat.find(e=>e.default&&e.test?.test(i))??r[t.SCALAR];s.tag!==e.tag&&o(a,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${n.tagString(s.tag)} or ${n.tagString(e.tag)}`,!0)}return s}e.composeScalar=a})),Vv=D((e=>{function t(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}e.emptyScalarPosition=t})),Hv=D((e=>{var t=W_(),n=Q(),r=Lv(),i=Bv(),a=Fv(),o=Vv(),s={composeNode:c,composeEmptyNode:l};function c(e,t,a,o){let c=e.atKey,{spaceBefore:d,comment:f,anchor:p,tag:m}=a,h,g=!0;switch(t.type){case`alias`:h=u(e,t,o),(p||m)&&o(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:h=i.composeScalar(e,t,m,o),p&&(h.anchor=p.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{h=r.composeCollection(s,e,t,a,o),p&&(h.anchor=p.source.substring(1))}catch(e){o(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:o(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),g=!1}return h??=l(e,t.offset,void 0,null,a,o),p&&h.anchor===``&&o(p,`BAD_ALIAS`,`Anchor cannot be an empty string`),c&&e.options.stringKeys&&(!n.isScalar(h)||typeof h.value!=`string`||h.tag&&h.tag!==`tag:yaml.org,2002:str`)&&o(m??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),d&&(h.spaceBefore=!0),f&&(t.type===`scalar`&&t.source===``?h.comment=f:h.commentBefore=f),e.options.keepSourceTokens&&g&&(h.srcToken=t),h}function l(e,t,n,r,{spaceBefore:a,comment:s,anchor:c,tag:l,end:u},d){let f={type:`scalar`,offset:o.emptyScalarPosition(t,n,r),indent:-1,source:``},p=i.composeScalar(e,f,l,d);return c&&(p.anchor=c.source.substring(1),p.anchor===``&&d(c,`BAD_ALIAS`,`Anchor cannot be an empty string`)),a&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=u),p}function u({options:e},{offset:n,source:r,end:i},o){let s=new t.Alias(r.substring(1));s.source===``&&o(n,`BAD_ALIAS`,`Alias cannot be an empty string`),s.source.endsWith(`:`)&&o(n+r.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let c=n+r.length,l=a.resolveEnd(i,c,e.strict,o);return s.range=[n,c,l.offset],l.comment&&(s.comment=l.comment),s}e.composeEmptyNode=l,e.composeNode=c})),Uv=D((e=>{var t=Dv(),n=Hv(),r=Fv(),i=kv();function a(e,a,{offset:o,start:s,value:c,end:l},u){let d=Object.assign({_directives:a},e),f=new t.Document(void 0,d),p={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},m=i.resolveProps(s,{indicator:`doc-start`,next:c??l?.[0],offset:o,onError:u,parentIndent:0,startOnNewline:!0});m.found&&(f.directives.docStart=!0,c&&(c.type===`block-map`||c.type===`block-seq`)&&!m.hasNewline&&u(m.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),f.contents=c?n.composeNode(p,c,m,u):n.composeEmptyNode(p,m.end,s,null,m,u);let h=f.contents.range[2],g=r.resolveEnd(l,h,!1,u);return g.comment&&(f.comment=g.comment),f.range=[o,h,g.offset],f}e.composeDoc=a})),Wv=D((e=>{var t=xe(`process`),n=z_(),r=Dv(),i=Ov(),a=Q(),o=Uv(),s=Fv();function c(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function l(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
|
|
192
192
|
|
|
193
193
|
`:`
|
|
194
|
-
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}})),
|
|
194
|
+
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}})),Gv=D((e=>{var t=Rv(),n=zv(),r=Ov(),i=Y_();function a(e,i=!0,a){if(e){let o=(e,t,n)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(a)a(i,t,n);else throw new r.YAMLParseError([i,i+1],t,n)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return n.resolveFlowScalar(e,i,o);case`block-scalar`:return t.resolveBlockScalar({options:{strict:i}},e,o)}}return null}function o(e,t){let{implicitKey:n=!1,indent:r,inFlow:a=!1,offset:o=-1,type:s=`PLAIN`}=t,c=i.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),u=t.end??[{type:`newline`,offset:-1,indent:r,source:`
|
|
195
195
|
`}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
|
|
196
196
|
`),t=c.substring(0,e),n=c.substring(e+1)+`
|
|
197
197
|
`,i=[{type:`block-scalar-header`,offset:o,indent:r,source:t}];return l(i,u)||i.push({type:`newline`,offset:-1,indent:r,source:`
|
|
@@ -199,9 +199,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
199
199
|
`),r=t.substring(0,n),i=t.substring(n+1)+`
|
|
200
200
|
`;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];l(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
|
|
201
201
|
`});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function l(e,t){if(t)for(let n of t)switch(n.type){case`space`:case`comment`:e.push(n);break;case`newline`:return e.push(n),!0}return!1}function u(e,t,n){switch(e.type){case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:e.type=n,e.source=t;break;case`block-scalar`:{let r=e.props.slice(1),i=t.length;e.props[0].type===`block-scalar-header`&&(i-=e.props[0].source.length);for(let e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
|
|
202
|
-
`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),
|
|
202
|
+
`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),Kv=D((e=>{var t=e=>`type`in e?n(e):r(e);function n(e){switch(e.type){case`block-scalar`:{let t=``;for(let r of e.props)t+=n(r);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=r(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=r(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=r(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function r({start:e,key:t,sep:r,value:i}){let a=``;for(let t of e)a+=t.source;if(t&&(a+=n(t)),r)for(let e of r)a+=e.source;return i&&(a+=n(i)),a}e.stringify=t})),qv=D((e=>{var t=Symbol(`break visit`),n=Symbol(`skip children`),r=Symbol(`remove item`);function i(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),a(Object.freeze([]),e,t)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},i.parentCollection=(e,t)=>{let n=i.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],a=n?.[r];if(a&&`items`in a)return a;throw Error(`Parent collection not found`)};function a(e,n,i){let o=i(n,e);if(typeof o==`symbol`)return o;for(let s of[`key`,`value`]){let c=n[s];if(c&&`items`in c){for(let n=0;n<c.items.length;++n){let o=a(Object.freeze(e.concat([[s,n]])),c.items[n],i);if(typeof o==`number`)n=o-1;else if(o===t)return t;else o===r&&(c.items.splice(n,1),--n)}typeof o==`function`&&s===`key`&&(o=o(n,e))}}return typeof o==`function`?o(n,e):o}e.visit=i})),Jv=D((e=>{var t=Gv(),n=Kv(),r=qv(),i=``,a=``,o=``,s=``,c=e=>!!e&&`items`in e,l=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`);function u(e){switch(e){case i:return`<BOM>`;case a:return`<DOC>`;case o:return`<FLOW_END>`;case s:return`<SCALAR>`;default:return JSON.stringify(e)}}function d(e){switch(e){case i:return`byte-order-mark`;case a:return`doc-mode`;case o:return`flow-error-end`;case s:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
|
|
203
203
|
`:case`\r
|
|
204
|
-
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=a,e.FLOW_END=o,e.SCALAR=s,e.isCollection=c,e.isScalar=l,e.prettyToken=u,e.tokenType=d})),
|
|
204
|
+
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=a,e.FLOW_END=o,e.SCALAR=s,e.isCollection=c,e.isScalar=l,e.prettyToken=u,e.tokenType=d})),Yv=D((e=>{var t=Jv();function n(e){switch(e){case void 0:case` `:case`
|
|
205
205
|
`:case`\r`:case` `:return!0;default:return!1}}var r=new Set(`0123456789ABCDEFabcdef`),i=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),a=new Set(`,[]{}`),o=new Set(` ,[]{}
|
|
206
206
|
\r `),s=e=>!e||o.has(e);e.Lexer=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
|
|
207
207
|
`||t===`\r`&&this.buffer[e+1]===`
|
|
@@ -220,10 +220,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
220
220
|
`,t=this.buffer[i+1]):r=i),t===`#`||e&&a.has(t))break;if(o===`
|
|
221
221
|
`){let e=this.continueScalar(i+1);if(e===-1)break;i=Math.max(i,e-2)}}else{if(e&&a.has(o))break;r=i}return!o&&!this.atEnd?this.setNext(`plain-scalar`):(yield t.SCALAR,yield*this.pushToIndex(r+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(s),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,r=this.charAt(1);if(n(r)||t&&a.has(r)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!n(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(i.has(t))t=this.buffer[++e];else if(t===`%`&&r.has(this.buffer[e+1])&&r.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
222
222
|
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
|
|
223
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),
|
|
223
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),Xv=D((e=>{e.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}})),Zv=D((e=>{var t=xe(`process`),n=Jv(),r=Yv();function i(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function a(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function o(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function s(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function c(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function l(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function u(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!i(t.start,`explicit-key-ind`)&&!i(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,o(t.value)?t.value.end?l(t.value.end,t.sep):t.value.end=t.sep:l(t.start,t.sep),delete t.sep)}e.Parser=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,t.env.LOG_TOKENS&&console.log(`|`,n.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=n.tokenType(e);if(!r){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(r===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=r,yield*this.step(),r){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&u(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&a(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:a(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=c(s(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
|
|
224
224
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
225
225
|
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){l(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,a=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(a=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(i(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=c(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(i(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(o(t.key)&&!i(t.sep,`newline`)){let e=c(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else a.length>0?t.sep=t.sep.concat(a,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):i(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:a,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!i(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){l(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||i(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));u(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
226
226
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
227
|
-
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Xv=D((e=>{var t=Hv(),n=Tv(),r=Ev(),i=X_(),a=Q(),o=Jv(),s=Yv();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Zv=D((e=>{var t=Hv(),n=Tv(),r=Cv(),i=Ev(),a=H_(),o=Q(),s=$_(),c=$(),l=tv(),u=rv();Kv();var d=qv(),f=Jv(),p=Yv(),m=Xv(),h=I_();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))(),Qv=`DEEPSEEK_API_KEY`,$v=1,ey=`ezllm`,ty=()=>process.env.DSH_HOME||c(w(),`.dsh`),ny=()=>c(ty(),`settings.yaml`),ry=()=>c(ty(),`.credentials.yaml`);function iy(e){if(!p(e))return null;let t=g(e,`utf-8`);return t.trim()===``?null:t}function ay(e,t){let n=(0,Zv.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function oy(e){return`${e}/v1`}function sy(e){let t=iy(ny());if(!t)return!1;try{return Yg(ay(t,ny()).toJS()?.[`llm-deepseek`]?.baseURL,oy(e))}catch{return!1}}function cy(e){let t=oy(e.gatewayBase);m(ty(),{recursive:!0});let n=ny(),r=iy(n),i=ay(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);qg(n),i.setIn([`llm-deepseek`,`baseURL`],t),uy(n,i);let o=ry(),s=e.masterKey||ey,c=iy(o);if(qg(o),c===null){let e=ay(``,o);e.set(`version`,$v),e.setIn([`refs`,Qv],s),uy(o,e);return}let l=ay(c,o),u=l.toJS();if(!(0,Zv.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==$v)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String($v)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(Qv,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,Qv],s)}uy(o,l)}function ly(e,t){let n=ny(),r=ry(),i=!1;if(Jg(n))i=!0;else{let t=iy(n);if(t){let r=ay(t,n);if(Yg(r.toJS()?.[`llm-deepseek`]?.baseURL,oy(e))){r.deleteIn([`llm-deepseek`,`baseURL`]);let e=r.toJS()?.[`llm-deepseek`];(!e||typeof e!=`object`||Object.keys(e).length===0)&&r.deleteIn([`llm-deepseek`]),uy(n,r),i=!0}}}if(Jg(r))i=!0;else{let e=iy(r);if(e){let n=ay(e,r),a=n.toJS(),o=e=>e===t||e===ey;a?.version===$v&&o(a?.refs?.[Qv])?(n.deleteIn([`refs`,Qv]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),uy(r,n),i=!0):a?.version===void 0&&o(a?.[Qv])&&(n.deleteIn([Qv]),uy(r,n),i=!0)}}return i}function uy(e,t){let n=t.toString(),r=(0,Zv.parseDocument)(n);if(r.errors.length>0)throw Error(`编辑后的 ${e} 不是合法 YAML,已保留原文件: ${r.errors[0]?.message??`未知错误`}`);m(s(e),{recursive:!0}),C(e,n,`utf-8`)}function dy(e){let t=e=>{try{return JSON.parse(g(e,`utf-8`)).masterKey||``}catch{return``}},n=new M;return n.get(`/`,t=>{let n=Qh(e);return t.json({ok:!0,claudeCode:Qg(n),codex:M_(),dsh:sy(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await Rg(n);if(r instanceof Response)return r;let i=Qh(e);if(r){let e=t(St());return e?($g({gatewayBase:i,token:e}),n.json({ok:!0,claudeCode:!0,file:`~/.claude/settings.json`,note:`已备份原文件为 settings.json.ellm-bak,重启 Claude Code 会话后生效`})):n.json({ok:!1,error:`配置未设置 masterKey,Claude Code 代理无法鉴权。请先在配置文件中设置 masterKey: ${St()}`},400)}let a=e_(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await Rg(n);if(r instanceof Response)return r;let i=Qh(e);if(r){let e=t(St()),r=P_({gatewayBase:i,apiKey:e||void 0});return n.json({ok:!0,codex:!0,file:`~/.codex/config.toml`,note:e?r?`已备份原文件为 config.toml.ellm-bak;已自动写入用户环境变量 ELLM_PROXY_API_KEY(Windows 写注册表 / macOS 写 ~/.zshrc,对之后新开的终端与 Codex 会话生效)`:`已备份原文件为 config.toml.ellm-bak;当前平台不支持自动写入,请手动设置环境变量 ELLM_PROXY_API_KEY=${e}`:`已备份原文件为 config.toml.ellm-bak;请设置环境变量 ELLM_PROXY_API_KEY(网关未配 masterKey 时取值任意)`})}let a=F_();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await Rg(n);if(r instanceof Response)return r;let i=Qh(e),a=t(St());if(r)return cy({gatewayBase:i,masterKey:a}),n.json({ok:!0,dsh:!0,file:`~/.dsh/settings.yaml`,note:a?`已写入 settings.yaml(llm-deepseek.baseURL)与 .credentials.yaml(refs.DEEPSEEK_API_KEY),原文件备份为 *.ellm-bak。注意:进程环境里已设 DEEPSEEK_API_KEY 时其优先级更高,需自行改用网关 masterKey;模型请在 dsh 内选择与网关部署名一致的模型`:`已写入 settings.yaml 与 .credentials.yaml(网关未配 masterKey,密钥为占位值即可放行),原文件备份为 *.ellm-bak。模型请在 dsh 内选择与网关部署名一致的模型`});let o=ly(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var fy=[`/api/*(管理台与全部接口)`,`POST|GET /api/fetch(通用 HTTP 转发)`,`GET /api/service/status|processes`,`GET|POST /api/service/autostart`,`GET /api/service/update`,`POST /api/service/update/enabled|check|apply`,`GET|POST /api/service/managed`,`PUT|DELETE /api/service/managed/:name`,`POST /api/service/managed/:name/start|stop|restart`,`GET /api/service/plugins`,`POST /api/service/plugins/enabled`,`POST /api/service/plugins/restart`,`POST /api/service/plugins/auto-update`,`GET /api/harness`,`POST /api/harness/claude-code|codex|dsh`,`GET /api/latency/history`,`POST /api/latency/run`].join(`, `);function py(e,t){let{runtime:n,admin:r,listen:i}=t;e.route(`/api/auth`,hp),e.route(`/api/setup`,Cp()),e.use(`/api/*`,_p),e.route(`/api/config`,wp({runtime:n})),e.route(`/api/test`,Ap(n)),e.route(`/api/latency`,Xp(n)),e.route(`/api/usage`,Zp()),e.route(`/api/quota`,kh()),e.route(`/api/logs`,Lh()),e.route(`/api/status`,Mh(n,i)),e.route(`/api/fetch`,Zh()),r&&(e.route(`/api/service`,eg(r)),e.route(`/api/service`,Hg(r)),e.route(`/api/service/managed`,Wg(r)),e.route(`/api/service/plugins`,Kg(r)),e.route(`/api/harness`,dy(r)))}var my=(e,t=hy)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},hy={aac:`audio/aac`,avi:`video/x-msvideo`,avif:`image/avif`,av1:`video/av1`,bin:`application/octet-stream`,bmp:`image/bmp`,css:`text/css; charset=utf-8`,csv:`text/csv; charset=utf-8`,eot:`application/vnd.ms-fontobject`,epub:`application/epub+zip`,gif:`image/gif`,gz:`application/gzip`,htm:`text/html; charset=utf-8`,html:`text/html; charset=utf-8`,ico:`image/x-icon`,ics:`text/calendar; charset=utf-8`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript; charset=utf-8`,json:`application/json`,jsonld:`application/ld+json`,map:`application/json`,mid:`audio/x-midi`,midi:`audio/x-midi`,mjs:`text/javascript; charset=utf-8`,mp3:`audio/mpeg`,mp4:`video/mp4`,mpeg:`video/mpeg`,oga:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,opus:`audio/opus`,otf:`font/otf`,pdf:`application/pdf`,png:`image/png`,rtf:`application/rtf`,svg:`image/svg+xml; charset=utf-8`,tif:`image/tiff`,tiff:`image/tiff`,ts:`video/mp2t`,ttf:`font/ttf`,txt:`text/plain; charset=utf-8`,wasm:`application/wasm`,webm:`video/webm`,weba:`audio/webm`,webmanifest:`application/manifest+json`,webp:`image/webp`,woff:`font/woff`,woff2:`font/woff2`,xhtml:`application/xhtml+xml; charset=utf-8`,xml:`application/xml; charset=utf-8`,zip:`application/zip`,"3gp":`video/3gpp`,"3g2":`video/3gpp2`,gltf:`model/gltf+json`,glb:`model/gltf-binary`},gy=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,_y={br:`.br`,zstd:`.zst`,gzip:`.gz`},vy=Object.keys(_y),yy=(()=>{let[e,t]=ge.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),by=e=>yy?i.toWeb(e):new ReadableStream({start(t){e.on(`data`,e=>{t.enqueue(e)}),e.on(`error`,e=>{t.error(e)}),e.on(`end`,()=>{t.close()})},cancel(){e.destroy()}}),xy=e=>{let t;try{t=ye(e)}catch{}return t},Sy=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Cy=e=>Sy(e,decodeURI),wy=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!ve(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(r,i)=>{if(r.finalized)return i();let a;if(n)a=n;else try{if(a=Cy(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=be(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=xy(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=be(o,t),s=xy(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=my(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||gy.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of vy){if(!e.has(t))continue;let n=xy(o+_y[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=_y[t];break}}}let l,u=s.size,d=r.req.header(`range`)||``;if(r.req.method==`HEAD`||r.req.method==`OPTIONS`)r.header(`Content-Length`,u.toString()),r.status(200),l=r.body(null);else if(!d)r.header(`Content-Length`,u.toString()),l=r.body(by(_e(o)),200);else{r.header(`Accept-Ranges`,`bytes`),r.header(`Date`,s.birthtime.toUTCString());let e=d.replace(/bytes=/,``).split(`-`,2),t=parseInt(e[0],10)||0,n=parseInt(e[1],10)||u-1;u<n-t+1&&(n=u-1);let i=n-t+1,a=_e(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(by(a),206)}return await e.onFound?.(o,r),l}},Ty=s(ee(import.meta.url));function Ey(e,t){let n=t??[c(Ty,`web-ui`),l(Ty,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),l(Ty,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>p(c(e,`index.html`)))??c(Ty,`web-ui`);p(c(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await se(c(n,`index.html`));return e.body(new Uint8Array(t),200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-cache`})}catch{return e.text(`Not Found`,404)}}),e.use(`/*`,async(e,t)=>{if(e.req.path===`/`)return t();let r=await wy({root:n})(e,t);return r instanceof Response&&r.status===200&&e.req.path.startsWith(`/assets/`)&&r.headers.set(`Cache-Control`,`public, max-age=31536000, immutable`),r}))}function Dy(e,t,n){let r=new M;return r.use(`/v1/*`,fp()),py(r,{runtime:e,admin:t,listen:n}),r.route(`/`,e.proxy),Ey(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), ${fy})`},404)),r.onError(yp),r}var Oy=6e4;function ky(e){let t=()=>{let e=El()?.latencyTest;return typeof e==`object`&&e?e:{}},n=(e,t,n)=>{if(e.enabled!==!0)return!1;let r=(e.intervalMinutes??60)*60*1e3;return t===void 0||n-t>=r};return{name:`latencyAutoTest`,everyMs:Oy,run:async()=>{try{if(qp(e)===0)return;let r=t();if(!n(r,zp()??void 0,Date.now()))return;O(`[latency] 自动测试触发`),await Kp(e)}catch(e){A(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var Ay=6e5,jy=3e4;function My(){return{name:`quotaRefresh`,everyMs:Ay,firstDelayMs:jy,run:async()=>{try{await Oh()}catch(e){A(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var Ny=6e4,Py=3e4,Fy=20,Iy=3e4,Ly=1024,Ry=/^[^\u0000-\u001f\u007f]{1,24}$/u,zy=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),By=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
|
|
228
|
-
`);async function
|
|
229
|
-
`),s=``,c=null;try{s=await t(a,o)}catch(e){c=e instanceof Error?e.message:String(e)}let l=new Map;if(c===null)for(let[e,t]of r(s,i.length)){let n=i[e-1];n!==void 0&&l.set(n,t)}let u=
|
|
227
|
+
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Qv=D((e=>{var t=Wv(),n=Dv(),r=Ov(),i=Q_(),a=Q(),o=Xv(),s=Zv();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),$v=D((e=>{var t=Wv(),n=Dv(),r=Tv(),i=Ov(),a=W_(),o=Q(),s=tv(),c=$(),l=rv(),u=av();Jv();var d=Yv(),f=Xv(),p=Zv(),m=Qv(),h=R_();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))(),ey=`DEEPSEEK_API_KEY`,ty=1,ny=`ezllm`,ry=()=>process.env.DSH_HOME||c(w(),`.dsh`),iy=()=>c(ry(),`settings.yaml`),ay=()=>c(ry(),`.credentials.yaml`);function oy(e){if(!p(e))return null;let t=g(e,`utf-8`);return t.trim()===``?null:t}function sy(e,t){let n=(0,$v.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function cy(e){return`${e}/v1`}function ly(e){let t=oy(iy());if(!t)return!1;try{return Zg(sy(t,iy()).toJS()?.[`llm-deepseek`]?.baseURL,cy(e))}catch{return!1}}function uy(e){let t=cy(e.gatewayBase);m(ry(),{recursive:!0});let n=iy(),r=oy(n),i=sy(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);Yg(n),i.setIn([`llm-deepseek`,`baseURL`],t),fy(n,i);let o=ay(),s=e.masterKey||ny,c=oy(o);if(Yg(o),c===null){let e=sy(``,o);e.set(`version`,ty),e.setIn([`refs`,ey],s),fy(o,e);return}let l=sy(c,o),u=l.toJS();if(!(0,$v.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==ty)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(ty)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(ey,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,ey],s)}fy(o,l)}function dy(e,t){let n=iy(),r=ay(),i=!1;if(Xg(n))i=!0;else{let t=oy(n);if(t){let r=sy(t,n);if(Zg(r.toJS()?.[`llm-deepseek`]?.baseURL,cy(e))){r.deleteIn([`llm-deepseek`,`baseURL`]);let e=r.toJS()?.[`llm-deepseek`];(!e||typeof e!=`object`||Object.keys(e).length===0)&&r.deleteIn([`llm-deepseek`]),fy(n,r),i=!0}}}if(Xg(r))i=!0;else{let e=oy(r);if(e){let n=sy(e,r),a=n.toJS(),o=e=>e===t||e===ny;a?.version===ty&&o(a?.refs?.[ey])?(n.deleteIn([`refs`,ey]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),fy(r,n),i=!0):a?.version===void 0&&o(a?.[ey])&&(n.deleteIn([ey]),fy(r,n),i=!0)}}return i}function fy(e,t){let n=t.toString(),r=(0,$v.parseDocument)(n);if(r.errors.length>0)throw Error(`编辑后的 ${e} 不是合法 YAML,已保留原文件: ${r.errors[0]?.message??`未知错误`}`);m(s(e),{recursive:!0}),C(e,n,`utf-8`)}function py(e){let t=e=>{try{return JSON.parse(g(e,`utf-8`)).masterKey||``}catch{return``}},n=new M;return n.get(`/`,t=>{let n=eg(e);return t.json({ok:!0,claudeCode:e_(n),codex:P_(),dsh:ly(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await Bg(n);if(r instanceof Response)return r;let i=eg(e);if(r){let e=t(St());return e?(t_({gatewayBase:i,token:e}),n.json({ok:!0,claudeCode:!0,file:`~/.claude/settings.json`,note:`已备份原文件为 settings.json.ellm-bak,重启 Claude Code 会话后生效`})):n.json({ok:!1,error:`配置未设置 masterKey,Claude Code 代理无法鉴权。请先在配置文件中设置 masterKey: ${St()}`},400)}let a=n_(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await Bg(n);if(r instanceof Response)return r;let i=eg(e);if(r){let e=t(St()),r=I_({gatewayBase:i,apiKey:e||void 0});return n.json({ok:!0,codex:!0,file:`~/.codex/config.toml`,note:e?r?`已备份原文件为 config.toml.ellm-bak;已自动写入用户环境变量 ELLM_PROXY_API_KEY(Windows 写注册表 / macOS 写 ~/.zshrc,对之后新开的终端与 Codex 会话生效)`:`已备份原文件为 config.toml.ellm-bak;当前平台不支持自动写入,请手动设置环境变量 ELLM_PROXY_API_KEY=${e}`:`已备份原文件为 config.toml.ellm-bak;请设置环境变量 ELLM_PROXY_API_KEY(网关未配 masterKey 时取值任意)`})}let a=L_();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await Bg(n);if(r instanceof Response)return r;let i=eg(e),a=t(St());if(r)return uy({gatewayBase:i,masterKey:a}),n.json({ok:!0,dsh:!0,file:`~/.dsh/settings.yaml`,note:a?`已写入 settings.yaml(llm-deepseek.baseURL)与 .credentials.yaml(refs.DEEPSEEK_API_KEY),原文件备份为 *.ellm-bak。注意:进程环境里已设 DEEPSEEK_API_KEY 时其优先级更高,需自行改用网关 masterKey;模型请在 dsh 内选择与网关部署名一致的模型`:`已写入 settings.yaml 与 .credentials.yaml(网关未配 masterKey,密钥为占位值即可放行),原文件备份为 *.ellm-bak。模型请在 dsh 内选择与网关部署名一致的模型`});let o=dy(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var my=[`/api/*(管理台与全部接口)`,`POST|GET /api/fetch(通用 HTTP 转发)`,`GET /api/service/status|processes`,`GET|POST /api/service/autostart`,`GET /api/service/update`,`POST /api/service/update/enabled|check|apply`,`GET|POST /api/service/managed`,`PUT|DELETE /api/service/managed/:name`,`POST /api/service/managed/:name/start|stop|restart`,`GET /api/service/plugins`,`POST /api/service/plugins/enabled`,`POST /api/service/plugins/restart`,`POST /api/service/plugins/auto-update`,`GET /api/harness`,`POST /api/harness/claude-code|codex|dsh`,`GET /api/latency/history`,`POST /api/latency/run`].join(`, `);function hy(e,t){let{runtime:n,admin:r,listen:i}=t;e.route(`/api/auth`,_p),e.route(`/api/setup`,Tp()),e.use(`/api/*`,yp),e.route(`/api/config`,Ep({runtime:n})),e.route(`/api/test`,Mp(n)),e.route(`/api/latency`,Qp(n)),e.route(`/api/usage`,$p()),e.route(`/api/quota`,jh()),e.route(`/api/logs`,zh()),e.route(`/api/status`,Ph(n,i)),e.route(`/api/fetch`,$h()),r&&(e.route(`/api/service`,ng(r)),e.route(`/api/service`,Wg(r)),e.route(`/api/service/managed`,Kg(r)),e.route(`/api/service/plugins`,Jg(r)),e.route(`/api/harness`,py(r)))}var gy=(e,t=_y)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},_y={aac:`audio/aac`,avi:`video/x-msvideo`,avif:`image/avif`,av1:`video/av1`,bin:`application/octet-stream`,bmp:`image/bmp`,css:`text/css; charset=utf-8`,csv:`text/csv; charset=utf-8`,eot:`application/vnd.ms-fontobject`,epub:`application/epub+zip`,gif:`image/gif`,gz:`application/gzip`,htm:`text/html; charset=utf-8`,html:`text/html; charset=utf-8`,ico:`image/x-icon`,ics:`text/calendar; charset=utf-8`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript; charset=utf-8`,json:`application/json`,jsonld:`application/ld+json`,map:`application/json`,mid:`audio/x-midi`,midi:`audio/x-midi`,mjs:`text/javascript; charset=utf-8`,mp3:`audio/mpeg`,mp4:`video/mp4`,mpeg:`video/mpeg`,oga:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,opus:`audio/opus`,otf:`font/otf`,pdf:`application/pdf`,png:`image/png`,rtf:`application/rtf`,svg:`image/svg+xml; charset=utf-8`,tif:`image/tiff`,tiff:`image/tiff`,ts:`video/mp2t`,ttf:`font/ttf`,txt:`text/plain; charset=utf-8`,wasm:`application/wasm`,webm:`video/webm`,weba:`audio/webm`,webmanifest:`application/manifest+json`,webp:`image/webp`,woff:`font/woff`,woff2:`font/woff2`,xhtml:`application/xhtml+xml; charset=utf-8`,xml:`application/xml; charset=utf-8`,zip:`application/zip`,"3gp":`video/3gpp`,"3g2":`video/3gpp2`,gltf:`model/gltf+json`,glb:`model/gltf-binary`},vy=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,yy={br:`.br`,zstd:`.zst`,gzip:`.gz`},by=Object.keys(yy),xy=(()=>{let[e,t]=ge.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),Sy=e=>xy?i.toWeb(e):new ReadableStream({start(t){e.on(`data`,e=>{t.enqueue(e)}),e.on(`error`,e=>{t.error(e)}),e.on(`end`,()=>{t.close()})},cancel(){e.destroy()}}),Cy=e=>{let t;try{t=ye(e)}catch{}return t},wy=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Ty=e=>wy(e,decodeURI),Ey=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!ve(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(r,i)=>{if(r.finalized)return i();let a;if(n)a=n;else try{if(a=Ty(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=be(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=Cy(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=be(o,t),s=Cy(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=gy(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||vy.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of by){if(!e.has(t))continue;let n=Cy(o+yy[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=yy[t];break}}}let l,u=s.size,d=r.req.header(`range`)||``;if(r.req.method==`HEAD`||r.req.method==`OPTIONS`)r.header(`Content-Length`,u.toString()),r.status(200),l=r.body(null);else if(!d)r.header(`Content-Length`,u.toString()),l=r.body(Sy(_e(o)),200);else{r.header(`Accept-Ranges`,`bytes`),r.header(`Date`,s.birthtime.toUTCString());let e=d.replace(/bytes=/,``).split(`-`,2),t=parseInt(e[0],10)||0,n=parseInt(e[1],10)||u-1;u<n-t+1&&(n=u-1);let i=n-t+1,a=_e(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(Sy(a),206)}return await e.onFound?.(o,r),l}},Dy=s(ee(import.meta.url));function Oy(e,t){let n=t??[c(Dy,`web-ui`),l(Dy,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),l(Dy,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>p(c(e,`index.html`)))??c(Dy,`web-ui`);p(c(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await se(c(n,`index.html`));return e.body(new Uint8Array(t),200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-cache`})}catch{return e.text(`Not Found`,404)}}),e.use(`/*`,async(e,t)=>{if(e.req.path===`/`)return t();let r=await Ey({root:n})(e,t);return r instanceof Response&&r.status===200&&e.req.path.startsWith(`/assets/`)&&r.headers.set(`Cache-Control`,`public, max-age=31536000, immutable`),r}))}function ky(e,t,n){let r=new M;return r.use(`/v1/*`,mp()),hy(r,{runtime:e,admin:t,listen:n}),r.route(`/`,e.proxy),Oy(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), ${my})`},404)),r.onError(xp),r}var Ay=6e4;function jy(e){let t=()=>{let e=El()?.latencyTest;return typeof e==`object`&&e?e:{}},n=(e,t,n)=>{if(e.enabled!==!0)return!1;let r=(e.intervalMinutes??60)*60*1e3;return t===void 0||n-t>=r};return{name:`latencyAutoTest`,everyMs:Ay,run:async()=>{try{if(Yp(e)===0)return;let r=t();if(!n(r,Vp()??void 0,Date.now()))return;O(`[latency] 自动测试触发`),await Jp(e)}catch(e){A(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var My=6e5,Ny=3e4;function Py(){return{name:`quotaRefresh`,everyMs:My,firstDelayMs:Ny,run:async()=>{try{await Ah()}catch(e){A(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var Fy=6e4,Iy=3e4,Ly=20,Ry=3e4,zy=1024,By=/^[^\u0000-\u001f\u007f]{1,24}$/u,Vy=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),Hy=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
|
|
228
|
+
`);async function Uy(e){let t=async(e,t)=>{let n=(e,t)=>{let n=Op((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0);return e.provider===`anthropic`?{url:`${n}/messages`,payload:{model:e.modelName,system:Hy,messages:[{role:`user`,content:t}],max_tokens:zy}}:e.provider===`openai-responses`?{url:`${n}/responses`,payload:{model:e.modelName,instructions:Hy,input:t,max_output_tokens:zy}}:{url:`${n}/chat/completions`,payload:{model:e.modelName,messages:[{role:`system`,content:Hy},{role:`user`,content:t}],max_tokens:zy}}},r=(e,t)=>{if(typeof t!=`object`||!t)return``;let n=t;if(e===`anthropic`){let e=n.content;return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``}if(e===`openai-responses`){if(typeof n.output_text==`string`)return n.output_text;let e=n.output;return Array.isArray(e)?e.map(e=>{if(typeof e!=`object`||!e)return``;let t=e.content;return Array.isArray(t)?t.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``}).join(``):``}let r=n.choices;if(!Array.isArray(r)||r.length===0)return``;let i=r[0].message;if(typeof i!=`object`||!i)return``;let a=i.content;return typeof a==`string`?a:Array.isArray(a)?a.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``},{url:i,payload:a}=n(e,t),o={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?kp(e.apiKey,e.provider):{}},s=await fetch(i,{method:`POST`,headers:o,body:JSON.stringify(a),signal:AbortSignal.timeout(Ry)});if(!s.ok){let e=await s.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(s.status)}${e?`: ${e}`:``}`)}let c=await s.json().catch(()=>null);return r(e.provider,c)},n=e=>{let t=e.current.expanded.deployments,n=t.names;if(n.length===0)return null;let r=of({status:`2xx`,pageSize:30}).items;for(let e of r){let n=typeof e.model==`string`?e.model:``;if(n===``)continue;let r=t.byName.get(n);if(r!==void 0)return{provider:r.provider,modelName:r.modelName,apiKey:r.apiKey,apiBase:r.apiBase,autoV1:r.autoV1,headers:r.headers}}let i=t.byName.get(n[0]);return i===void 0?null:{provider:i.provider,modelName:i.modelName,apiKey:i.apiKey,apiBase:i.apiBase,autoV1:i.autoV1,headers:i.headers}},r=(e,t)=>{let n=new Map,r=e.replace(/```[a-zA-Z]*/g,``).trim(),i=r.indexOf(`[`),a=r.lastIndexOf(`]`);if(i===-1||a<=i)return n;let o;try{o=JSON.parse(r.slice(i,a+1))}catch{return n}if(!Array.isArray(o))return n;for(let e of o){if(typeof e!=`object`||!e)continue;let r=e,i=Number(r.i),a=r.name;if(!Number.isInteger(i)||i<1||i>t||typeof a!=`string`)continue;let o=a.trim();By.test(o)&&(Vy.has(o.toLowerCase())||n.set(i,o))}return n},i=Gf(Ly);if(i.length===0)return{resolved:0,fallback:0,failed:0};let a=n(e);if(a===null)return k(`[client-name] 无可用部署,${String(i.length)} 个待识别 UA 顺延到下一轮`),{resolved:0,fallback:0,failed:i.length};let o=i.map((e,t)=>`${String(t+1)}) ${e}`).join(`
|
|
229
|
+
`),s=``,c=null;try{s=await t(a,o)}catch(e){c=e instanceof Error?e.message:String(e)}let l=new Map;if(c===null)for(let[e,t]of r(s,i.length)){let n=i[e-1];n!==void 0&&l.set(n,t)}let u=Kf(l,`llm`),d=i.filter(e=>!l.has(e)),f=qf(d),p=new Map;for(let e of f){let t=rp(e);t!==``&&p.set(e,t)}let m=Kf(p,Nf);return c!==null&&k(`[client-name] 识别请求失败(${String(d.length)} 个 UA 顺延重试): ${c}`),(u>0||m>0)&&O(`[client-name] 客户端短名: 模型定名 ${String(u)} 个 / 回落 ${String(m)} 个(模型 ${a.modelName})`),{resolved:u,fallback:m,failed:d.length-m}}function Wy(e){return{name:`clientNameResolve`,everyMs:Fy,firstDelayMs:Iy,run:async()=>{try{await Uy(e)}catch(e){A(`[client-name] 识别作业异常:`,e instanceof Error?e.message:String(e))}}}}var Gy=`--log-backfill`;function Ky(e=process.argv){return e.includes(Gy)}async function qy(){O(`[log-backfill] 开始存量补齐(入站头 → 会话标识;客户端短名随后由服务内作业定名)`),vd();let e=ap({onProgress:e=>O(`[log-backfill] ${e}`)});O(`[log-backfill] 入站头:${String(e.days)} 天 / 扫描 ${String(e.scanned)} 行,回填 ${String(e.filled)} 行,跳过(详情无入站头)${String(e.skipped)} 行,登记 UA ${String(e.uas)} 个,补写 client ${String(e.clientsAssigned)} 行`);let t=cp({onProgress:e=>O(`[log-backfill] ${e}`)});O(`[log-backfill] 会话标识:扫描 ${String(t.scanned)} 行,补 session_id ${String(t.filled)} 行`),O(`[log-backfill] 完成`)}function Jy(e={}){let t=e.entry??process.argv[1];if(t===void 0||t===``)return{started:!1,reason:`拿不到本进程入口(process.argv[1] 为空)`};let n=e.spawnFn??he,r,i;try{return m(wt(),{recursive:!0}),r=h(c(wt(),`out-backfill.log`),`a`),i=h(c(wt(),`err-backfill.log`),`a`),n(process.execPath,[...e.execArgv??process.execArgv,t,Gy],{detached:!0,stdio:[`ignore`,r,i],env:{...process.env,ELLM_APP_DIR:bt()}}).unref(),{started:!0,reason:``}}catch(e){return{started:!1,reason:e instanceof Error?e.message:String(e)}}finally{r!==void 0&&d(r),i!==void 0&&d(i)}}function Yy(e={}){let t=Jy(e);return t.started||A(`[log-backfill] 存量补齐子进程未拉起:${t.reason}`),t}Ky()&&(await qy(),process.exit(0));var Xy=Dl();Xy===null&&(A(`[ezllm] 缺少配置文件 ${St()}(参考 ezllm.config.example.json)`),process.exit(1));var Zy=Xy;vd(),Lp();var Qy=new fu({maxBytes:Kl().maxBytes}),$y=Tf({spool:Qy,getConfig:()=>Kl()}),eb=du();eb>0&&O(`[ezllm] spool 启动清理:回收中断残留 ${String(eb)} 个中转文件`),await Df(),Yy();var tb=new ep({spool:Qy}),nb=()=>Zy.providers.flatMap(e=>e.models.map(e=>e.modelName)),rb=await dp(Zy,{authorize(e){let t=Fl();return t===``||e===`Bearer ${t}`},register(e){e.addHook(`onAuthorize`,e=>{let t=Fl();t!==``&&(e.headers.authorization??``)!==`Bearer ${t}`&&e.reject(`invalid api key`)}),pp(e,{knownModelNames:nb})}},{traceSink:tb}),ib={port:0,startedAt:Date.now(),appDir:bt()},ab=Vl(),ob=ky(rb,ib,ab),sb=Wt({jobs:[$y,jf({getRetention:()=>Gl()}),jy(rb),Py(),Wy(rb)]}),cb=await db(ob,up(rb),ab.hostname);ib.port=cb;var lb=!1;function ub(e,t=0){lb||(lb=!0,sb.stop(),O(`[ezllm] ${e},服务退出`),Promise.race([tb.flush(),new Promise(e=>setTimeout(e,5e3))]).then(()=>process.exit(t)))}zg(()=>ub(`与主进程的 IPC 连接已断开`));for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>ub(`收到 ${e}`));fb(cb,ab);async function db(e,t,n){let r=Date.now()+1e4;for(;;)try{return await new Promise((r,i)=>{let a=st({fetch:e.fetch,port:t,hostname:n,overrideGlobalObjects:!1});a.once(`error`,e=>i(e)),a.once(`listening`,()=>r(a.address()?.port??t))})}catch(e){let n=e.code??String(e);if(n===`EADDRINUSE`&&Date.now()<r){await new Promise(e=>setTimeout(e,300));continue}A(`错误:服务监听 ${String(t)} 失败(${n})${n===`EADDRINUSE`?`,端口被占用(可在配置文件修改 port)`:``}`),process.exit(1)}}function fb(e,t){let n=Mh(t.hostname)?`localhost`:t.hostname,r=Mh(t.hostname)?`全部网卡`:t.hostname,i=t.source===`credentials`?`未设置任何凭据(主密钥与登录账号皆无),强制仅本机(设置页开关已忽略)`:t.hostname===`127.0.0.1`?`设置页「允许局域网访问」已关闭`:`设置页「允许局域网访问」开启(缺省)`;if(O(`========================================`),O(` EZLLM 服务(网关 + 管理台,单进程)`),O(` 网关端点: http://${n}:${String(e)}/v1/*`),O(` 管理台: http://${n}:${String(e)}/(管理 API 与界面同端口,登录后使用)`),O(` 监听地址: ${r}:${String(e)}(${i})`),Mh(t.hostname))for(let t of Nh())O(` 局域网访问: http://${t}:${String(e)}`);O(` 模型数量: ${String(rb.current.expanded.deployments.names.length)}`),zl().completed||O(` ⚠ 首次启动:请打开 http://${n}:${String(e)}/ 完成初始化向导(设置主密钥与登录账号)`),O(`========================================`)}export{};
|